lang
stringclasses
1 value
license
stringclasses
13 values
stderr
stringlengths
0
350
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
7
45.1k
new_contents
stringlengths
0
1.87M
new_file
stringlengths
6
292
old_contents
stringlengths
0
1.87M
message
stringlengths
6
9.26k
old_file
stringlengths
6
292
subject
stringlengths
0
4.45k
Java
apache-2.0
error: pathspec 'BaragonCore/src/main/java/com/hubspot/baragon/exceptions/AgentStartupException.java' did not match any file(s) known to git
d082b032ff995b8ee7112306d3e7b85c2830c13e
1
HubSpot/Baragon,HubSpot/Baragon,evertrue/Baragon,HubSpot/Baragon,protochron/Baragon,evertrue/Baragon,protochron/Baragon,evertrue/Baragon,evertrue/Baragon,protochron/Baragon,evertrue/Baragon
package com.hubspot.baragon.exceptions; public class AgentStartupException extends Exception { public AgentStartupException(String message) { super(message); } }
BaragonCore/src/main/java/com/hubspot/baragon/exceptions/AgentStartupException.java
missing file
BaragonCore/src/main/java/com/hubspot/baragon/exceptions/AgentStartupException.java
missing file
Java
apache-2.0
error: pathspec 'xmvn-connector-aether/src/main/java/org/fedoraproject/xmvn/connector/aether/XMvnJavadocEcecutionListener.java' did not match any file(s) known to git
450959041f818abf40c3103589d1182d93449d35
1
fedora-java/xmvn,mizdebsk/xmvn,rvais/xmvn,fedora-java/xmvn,mizdebsk/xmvn,mizdebsk/xmvn,mizdebsk/xmvn,rvais/xmvn,rvais/xmvn,rvais/xmvn,fedora-java/xmvn
/*- * Copyright (c) 2014 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.fedoraproject.xmvn.connector.aether; import java.io.IOException; import java.lang.reflect.Method; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import javax.inject.Named; import javax.inject.Singleton; import org.apache.maven.execution.MojoExecutionEvent; import org.apache.maven.execution.MojoExecutionListener; import org.apache.maven.plugin.Mojo; import org.apache.maven.plugin.MojoExecution; /** * Listens to executions of "aggregate" goal of Maven Javadoc Plugin and captures Javadoc report output location. * * @author Mikolaj Izdebski */ @Named @Singleton public class XMvnJavadocEcecutionListener implements MojoExecutionListener { private static final String JAVADOC_PLUGIN_GROUPID = "org.apache.maven.plugins"; private static final String JAVADOC_PLUGIN_ARTIFACTID = "maven-javadoc-plugin"; private static final String JAVADOC_PLUGIN_GOAL = "aggregate"; private static final Path XMVN_STATE_DIR = Paths.get( ".xmvn" ); private static final Path APIDOCS_SYMLINK = XMVN_STATE_DIR.resolve( "apidocs" ); @Override public void afterMojoExecutionSuccess( MojoExecutionEvent event ) { try { Mojo mojo = event.getMojo(); MojoExecution execution = event.getExecution(); if ( execution.getGroupId().equals( JAVADOC_PLUGIN_GROUPID ) && execution.getArtifactId().equals( JAVADOC_PLUGIN_ARTIFACTID ) && execution.getGoal().equals( JAVADOC_PLUGIN_GOAL ) ) { Method method = mojo.getClass().getMethod( "getReportOutputDirectory" ); Path javadocDir = Paths.get( method.invoke( mojo ).toString() ); if ( !Files.exists( XMVN_STATE_DIR ) ) Files.createDirectory( XMVN_STATE_DIR ); if ( Files.isSymbolicLink( APIDOCS_SYMLINK ) ) Files.delete( APIDOCS_SYMLINK ); Files.createSymbolicLink( APIDOCS_SYMLINK, javadocDir ); } } catch ( ReflectiveOperationException | IOException e ) { throw new RuntimeException( e ); } } @Override public void beforeMojoExecution( MojoExecutionEvent event ) { // Nothing to do } @Override public void afterExecutionFailure( MojoExecutionEvent event ) { // Nothing to do } }
xmvn-connector-aether/src/main/java/org/fedoraproject/xmvn/connector/aether/XMvnJavadocEcecutionListener.java
Save javadoc report location in .xmvn/apidocs (rhbz#1106598)
xmvn-connector-aether/src/main/java/org/fedoraproject/xmvn/connector/aether/XMvnJavadocEcecutionListener.java
Save javadoc report location in .xmvn/apidocs (rhbz#1106598)
Java
apache-2.0
error: pathspec 'airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/util/AiravataServerThreadPoolExecutor.java' did not match any file(s) known to git
fc25c7284a77f51a68b7509a6366e733f66c59be
1
dogless/airavata,gouravshenoy/airavata,jjj117/airavata,hasinitg/airavata,hasinitg/airavata,apache/airavata,anujbhan/airavata,machristie/airavata,apache/airavata,gouravshenoy/airavata,machristie/airavata,apache/airavata,gouravshenoy/airavata,anujbhan/airavata,anujbhan/airavata,machristie/airavata,jjj117/airavata,gouravshenoy/airavata,jjj117/airavata,anujbhan/airavata,anujbhan/airavata,machristie/airavata,gouravshenoy/airavata,dogless/airavata,apache/airavata,hasinitg/airavata,hasinitg/airavata,dogless/airavata,anujbhan/airavata,machristie/airavata,apache/airavata,hasinitg/airavata,dogless/airavata,dogless/airavata,gouravshenoy/airavata,gouravshenoy/airavata,jjj117/airavata,hasinitg/airavata,machristie/airavata,jjj117/airavata,apache/airavata,apache/airavata,jjj117/airavata,machristie/airavata,apache/airavata,dogless/airavata,anujbhan/airavata
package org.apache.airavata.api.server.util; import org.apache.airavata.common.exception.ApplicationSettingsException; import org.apache.airavata.common.logger.AiravataLogger; import org.apache.airavata.common.logger.AiravataLoggerFactory; import org.apache.airavata.common.utils.ServerSettings; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * Created by airavata on 10/24/14. */ public class AiravataServerThreadPoolExecutor { private final static AiravataLogger logger = AiravataLoggerFactory.getLogger(AiravataServerThreadPoolExecutor.class); public static final String AIRAVATA_SERVER_THREAD_POOL_SIZE = "airavata.server.thread.pool.size"; private static ExecutorService threadPool; public static ExecutorService getThreadPool() { if(threadPool ==null){ threadPool = Executors.newCachedThreadPool(); } return threadPool; } public static ExecutorService getFixedThreadPool() { if(threadPool ==null){ try { threadPool = Executors.newFixedThreadPool(Integer.parseInt(ServerSettings.getSetting(AIRAVATA_SERVER_THREAD_POOL_SIZE))); } catch (ApplicationSettingsException e) { logger.error("Error reading " + AIRAVATA_SERVER_THREAD_POOL_SIZE+ " property"); } } return threadPool; } }
airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/util/AiravataServerThreadPoolExecutor.java
adding the missing class
airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/util/AiravataServerThreadPoolExecutor.java
adding the missing class
Java
bsd-2-clause
d6a5a2d83ea7958098d82c0ada7a3efee5a7c44b
0
unchiujar/dnsjavap2p
// Copyright (c) 1999 Brian Wellington (bwelling@xbill.org) // Portions Copyright (c) 1999 Network Associates, Inc. package org.xbill.DNS; import java.net.*; import java.io.*; import java.util.*; import org.xbill.DNS.utils.*; /** * Address Record - maps a domain name to an Internet address * * @author Brian Wellington */ public class ARecord extends Record { private InetAddress address; private ARecord() {} /** * Creates an A Record from the given data * @param address The address that the name refers to */ public ARecord(Name _name, short _dclass, int _ttl, InetAddress _address) throws IOException { super(_name, Type.A, _dclass, _ttl); address = _address; } ARecord(Name _name, short _dclass, int _ttl, int length, DataByteInputStream in, Compression c) throws IOException { super(_name, Type.A, _dclass, _ttl); if (in == null) return; byte [] data = new byte[4]; in.read(data); String s; s = (data[0] & 0xFF) + "." + (data[1] & 0xFF) + "." + (data[2] & 0xFF) + "." + (data[3] & 0xFF); try { address = InetAddress.getByName(s); } catch (UnknownHostException e) { System.out.println("Invalid IP address " + s); } } ARecord(Name _name, short _dclass, int _ttl, MyStringTokenizer st, Name origin) throws IOException { super(_name, Type.A, _dclass, _ttl); String s = st.nextToken(); if (s.equals("@me@")) { try { address = InetAddress.getLocalHost(); if (address.equals(InetAddress.getByName("127.0.0.1"))) { System.out.println("InetAddress.getLocalHost() is broken. For now, don't use @me@"); System.exit(-1); } } catch (UnknownHostException e) { address = null; } } else address = InetAddress.getByName(s); } /** Converts to a String */ public String toString() { StringBuffer sb = toStringNoData(); if (address != null) sb.append(address.getHostAddress()); return sb.toString(); } /** Returns the Internet address */ public InetAddress getAddress() { return address; } void rrToWire(DataByteOutputStream out, Compression c) throws IOException { if (address == null) return; out.write(address.getAddress()); } }
org/xbill/DNS/ARecord.java
// Copyright (c) 1999 Brian Wellington (bwelling@xbill.org) // Portions Copyright (c) 1999 Network Associates, Inc. package org.xbill.DNS; import java.net.*; import java.io.*; import java.util.*; import org.xbill.DNS.utils.*; /** * Address Record - maps a domain name to an Internet address * * @author Brian Wellington */ public class ARecord extends Record { private InetAddress address; private ARecord() {} /** * Creates an A Record from the given data * @param address The address that the name refers to */ public ARecord(Name _name, short _dclass, int _ttl, InetAddress _address) throws IOException { super(_name, Type.A, _dclass, _ttl); address = _address; } ARecord(Name _name, short _dclass, int _ttl, int length, DataByteInputStream in, Compression c) throws IOException { super(_name, Type.A, _dclass, _ttl); if (in == null) return; byte [] data = new byte[4]; in.read(data); String s = new String(); s = (data[0] & 0xFF) + "." + (data[1] & 0xFF) + "." + (data[2] & 0xFF) + "." + (data[3] & 0xFF); try { address = InetAddress.getByName(s); } catch (UnknownHostException e) { System.out.println("Invalid IP address " + s); } } ARecord(Name _name, short _dclass, int _ttl, MyStringTokenizer st, Name origin) throws IOException { super(_name, Type.A, _dclass, _ttl); String s = st.nextToken(); if (s.equals("@me@")) { try { address = InetAddress.getLocalHost(); if (address.equals(InetAddress.getByName("127.0.0.1"))) { System.out.println("InetAddress.getLocalHost() is broken. For now, don't use @me@"); System.exit(-1); } } catch (UnknownHostException e) { address = null; } } else address = InetAddress.getByName(s); } /** Converts to a String */ public String toString() { StringBuffer sb = toStringNoData(); if (address != null) sb.append(address.getHostAddress()); return sb.toString(); } /** Returns the Internet address */ public InetAddress getAddress() { return address; } void rrToWire(DataByteOutputStream out, Compression c) throws IOException { if (address == null) return; out.write(address.getAddress()); } }
removed extra Sring create
org/xbill/DNS/ARecord.java
removed extra Sring create
Java
bsd-2-clause
error: pathspec 'src/nzbsplit/FileNamer.java' did not match any file(s) known to git
ce181292c61a39217c70578f413cf0a38cbb7dc4
1
samicemalone/nzbsplit
/* * Copyright (c) 2013, Sam Malone * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package nzbsplit; import java.io.File; /** * * @author Sam Malone */ public class FileNamer { private final String fileNameBase; private String suffixDivider = "_"; private final String extension; private int zeroPadding = 0; /** * Creates a new instance of FileNamer * @param originalFileName File name that should be used to base the file parts on * @param extension File extension including periods e.g. ".nzb" */ public FileNamer(String originalFileName, String extension) { fileNameBase = originalFileName.substring(0, originalFileName.length() - extension.length()); this.extension = extension; } /** * Get the file name that should be used to store the given part * @param destDir Destination directory to store the part * @param partNo file part number * @return file name that should be used to store the given part */ public File getPartFileName(File destDir, int partNo) { return new File(destDir, String.format("%s%s%s%s", fileNameBase, suffixDivider, zeroPad(partNo), extension)); } /** * Set the length of the each name part to be padded with zeroes if necessary * @param length length of each name part to be padded e.g. formatting 23: * with maxLength = 2 => 23, maxLength = 3, => 023 */ public void setZeroPadding(int length) { zeroPadding = length; } /** * Sets the divider between each part. Default divider is "_" * @param divider Divider between file name and part number */ public void setPartDivider(String divider) { suffixDivider = divider; } /** * Pad the integer given with zeroes. The amount if zeroes is read from * {@link #zeroPadding} * @param toPad integer to pad * @return Zero padded string if {@link #zeroPadding} > 1. Otherwise no * padding is applied and a String representation of toPad is returned. */ private String zeroPad(int toPad) { if(zeroPadding > 1) { return String.format("%0" + zeroPadding + "d", toPad); } return String.valueOf(toPad); } }
src/nzbsplit/FileNamer.java
Added FileNamer class to manage the split nzb parts file names
src/nzbsplit/FileNamer.java
Added FileNamer class to manage the split nzb parts file names
Java
bsd-3-clause
5b45b76a237583555c8dd97725e5e2c8a1f0293a
0
tkruse/jline2,renew-tgi/jline2,cosmin/jline2,fantasy86/jline2,ctubbsii/jline2,DALDEI/jline2,scala/scala-jline,kaulkie/jline2,scala/scala-jline,msaxena2/jline2
/* * Copyright (c) 2002-2007, Marc Prud'hommeaux. All rights reserved. * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. */ package jline.console; import jline.Terminal; import jline.TerminalFactory; import jline.console.completer.CandidateListCompletionHandler; import jline.console.completer.Completer; import jline.console.completer.CompletionHandler; import jline.console.history.History; import jline.console.history.MemoryHistory; import jline.internal.Configuration; import jline.internal.Log; import org.fusesource.jansi.AnsiOutputStream; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.awt.event.ActionListener; import java.io.*; import java.util.*; /** * A reader for console applications. It supports custom tab-completion, * saveable command history, and command line editing. On some platforms, * platform-specific commands will need to be issued before the reader will * function properly. See {@link jline.Terminal#init} for convenience * methods for issuing platform-specific setup commands. * * @author <a href="mailto:mwp1@cornell.edu">Marc Prud'hommeaux</a> * @author <a href="mailto:jason@planet57.com">Jason Dillon</a> */ public class ConsoleReader { public static final String JLINE_NOBELL = "jline.nobell"; public static final String JLINE_EXPANDEVENTS = "jline.expandevents"; public static final char BACKSPACE = '\b'; public static final char RESET_LINE = '\r'; public static final char KEYBOARD_BELL = '\07'; public static final char NULL_MASK = 0; public static final int TAB_WIDTH = 4; private static final ResourceBundle resources = ResourceBundle.getBundle(CandidateListCompletionHandler.class.getName()); private final Terminal terminal; private InputStream in; private final Writer out; private final CursorBuffer buf = new CursorBuffer(); private String prompt; private boolean bellEnabled = true; private boolean expandEvents = false; private Character mask; private Character echoCharacter; private StringBuffer searchTerm = null; private String previousSearchTerm = ""; private int searchIndex = -1; public ConsoleReader(final InputStream in, final OutputStream out, final InputStream bindings, final Terminal term) throws IOException { this.in = in; this.terminal = term != null ? term : TerminalFactory.get(); this.out = new PrintWriter(terminal.wrapOutIfNeeded(out)); this.keyBindings = loadKeyBindings(bindings); setBellEnabled(!Configuration.getBoolean(JLINE_NOBELL, false)); setExpandEvents(Configuration.getBoolean(JLINE_EXPANDEVENTS, false)); } /** * @deprecated use {@link #ConsoleReader(InputStream, OutputStream, InputStream, Terminal)} * to let the terminal wrap the output stream if needed. */ public ConsoleReader(final InputStream in, final Writer out, final InputStream bindings, final Terminal term) throws IOException { this.in = in; this.out = out; this.terminal = term != null ? term : TerminalFactory.get(); this.keyBindings = loadKeyBindings(bindings); setBellEnabled(!Configuration.getBoolean(JLINE_NOBELL, false)); } /** * @deprecated use {@link #ConsoleReader(InputStream, OutputStream, InputStream, Terminal)} * to let the terminal wrap the output stream if needed. */ public ConsoleReader(final InputStream in, final Writer out, final Terminal term) throws IOException { this(in, out, null, term); } /** * @deprecated use {@link #ConsoleReader(InputStream, OutputStream, InputStream, Terminal)} * to let the terminal wrap the output stream if needed. */ public ConsoleReader(final InputStream in, final Writer out) throws IOException { this(in, out, null, null); } /** * Create a new reader using {@link FileDescriptor#in} for input and * {@link System#out} for output. * <p/> * {@link FileDescriptor#in} is used because it has a better chance of not being buffered. */ public ConsoleReader() throws IOException { this(new FileInputStream(FileDescriptor.in), System.out, null, null ); } // FIXME: Only used for tests void setInput(final InputStream in) { this.in = in; } public InputStream getInput() { return in; } public Writer getOutput() { return out; } public Terminal getTerminal() { return terminal; } public CursorBuffer getCursorBuffer() { return buf; } public void setBellEnabled(final boolean enabled) { this.bellEnabled = enabled; } public boolean isBellEnabled() { return bellEnabled; } public void setExpandEvents(final boolean expand) { this.expandEvents = expand; } public boolean getExpandEvents() { return expandEvents; } public void setPrompt(final String prompt) { this.prompt = prompt; } public String getPrompt() { return prompt; } /** * Set the echo character. For example, to have "*" entered when a password is typed: * <p/> * <pre> * myConsoleReader.setEchoCharacter(new Character('*')); * </pre> * <p/> * Setting the character to * <p/> * <pre> * null * </pre> * <p/> * will restore normal character echoing. Setting the character to * <p/> * <pre> * new Character(0) * </pre> * <p/> * will cause nothing to be echoed. * * @param c the character to echo to the console in place of the typed character. */ public void setEchoCharacter(final Character c) { this.echoCharacter = c; } /** * Returns the echo character. */ public Character getEchoCharacter() { return echoCharacter; } /** * Erase the current line. * * @return false if we failed (e.g., the buffer was empty) */ final boolean resetLine() throws IOException { if (buf.cursor == 0) { return false; } backspaceAll(); return true; } int getCursorPosition() { // FIXME: does not handle anything but a line with a prompt absolute position String prompt = getPrompt(); return ((prompt == null) ? 0 : stripAnsi(lastLine(prompt)).length()) + buf.cursor; } /** * Returns the text after the last '\n'. * prompt is returned if no '\n' characters are present. * null is returned if prompt is null. */ private String lastLine(String str) { if (str == null) return ""; int last = str.lastIndexOf("\n"); if (last >= 0) { return str.substring(last + 1, str.length()); } return str; } private String stripAnsi(String str) { if (str == null) return ""; try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); AnsiOutputStream aos = new AnsiOutputStream(baos); aos.write(str.getBytes()); aos.flush(); return baos.toString(); } catch (IOException e) { return str; } } /** * Move the cursor position to the specified absolute index. */ public final boolean setCursorPosition(final int position) throws IOException { return moveCursor(position - buf.cursor) != 0; } /** * Set the current buffer's content to the specified {@link String}. The * visual console will be modified to show the current buffer. * * @param buffer the new contents of the buffer. */ private void setBuffer(final String buffer) throws IOException { // don't bother modifying it if it is unchanged if (buffer.equals(buf.buffer.toString())) { return; } // obtain the difference between the current buffer and the new one int sameIndex = 0; for (int i = 0, l1 = buffer.length(), l2 = buf.buffer.length(); (i < l1) && (i < l2); i++) { if (buffer.charAt(i) == buf.buffer.charAt(i)) { sameIndex++; } else { break; } } int diff = buf.cursor - sameIndex; if (diff < 0) { // we can't backspace here so try from the end of the buffer moveToEnd(); diff = buf.buffer.length() - sameIndex; } backspace(diff); // go back for the differences killLine(); // clear to the end of the line buf.buffer.setLength(sameIndex); // the new length putString(buffer.substring(sameIndex)); // append the differences } private void setBuffer(final CharSequence buffer) throws IOException { setBuffer(String.valueOf(buffer)); } /** * Output put the prompt + the current buffer */ public final void drawLine() throws IOException { String prompt = getPrompt(); if (prompt != null) { print(prompt); } print(buf.buffer.toString()); if (buf.length() != buf.cursor) { // not at end of line back(buf.length() - buf.cursor - 1); } // force drawBuffer to check for weird wrap (after clear screen) drawBuffer(); } /** * Clear the line and redraw it. */ public final void redrawLine() throws IOException { print(RESET_LINE); // flush(); drawLine(); } /** * Clear the buffer and add its contents to the history. * * @return the former contents of the buffer. */ final String finishBuffer() throws IOException { // FIXME: Package protected because used by tests String str = buf.buffer.toString(); if (expandEvents) { str = expandEvents(str); } // we only add it to the history if the buffer is not empty // and if mask is null, since having a mask typically means // the string was a password. We clear the mask after this call if (str.length() > 0) { if (mask == null && isHistoryEnabled()) { history.add(str); } else { mask = null; } } history.moveToEnd(); buf.buffer.setLength(0); buf.cursor = 0; return str; } /** * Expand event designator such as !!, !#, !3, etc... * See http://www.gnu.org/software/bash/manual/html_node/Event-Designators.html * * @param str * @return */ final String expandEvents(String str) throws IOException { StringBuilder sb = new StringBuilder(); for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); switch (c) { case '!': if (i + 1 < str.length()) { c = str.charAt(++i); boolean neg = false; String rep = null; int i1, idx; switch (c) { case '!': if (history.size() == 0) { throw new IllegalArgumentException("!!: event not found"); } rep = history.get(history.index() - 1).toString(); break; case '#': sb.append(sb.toString()); break; case '?': i1 = str.indexOf('?', i + 1); if (i1 < 0) { i1 = str.length(); } String sc = str.substring(i + 1, i1); i = i1; idx = searchBackwards(sc); if (idx < 0) { throw new IllegalArgumentException("!?" + sc + ": event not found"); } else { rep = history.get(idx).toString(); } break; case ' ': case '\t': sb.append('!'); sb.append(c); break; case '-': neg = true; i++; // fall through case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': i1 = i; for (; i < str.length(); i++) { c = str.charAt(i); if (c < '0' || c > '9') { break; } } idx = 0; try { idx = Integer.parseInt(str.substring(i1, i)); } catch (NumberFormatException e) { throw new IllegalArgumentException((neg ? "!-" : "!") + str.substring(i1, i) + ": event not found"); } if (neg) { if (idx < history.size()) { rep = (history.get(history.index() - idx)).toString(); } else { throw new IllegalArgumentException((neg ? "!-" : "!") + str.substring(i1, i) + ": event not found"); } } else { if (idx >= history.index() - history.size() && idx < history.index()) { rep = (history.get(idx)).toString(); } else { throw new IllegalArgumentException((neg ? "!-" : "!") + str.substring(i1, i) + ": event not found"); } } break; default: String ss = str.substring(i); i = str.length(); idx = searchBackwards(ss, history.index(), true); if (idx < 0) { throw new IllegalArgumentException("!" + ss + ": event not found"); } else { rep = history.get(idx).toString(); } break; } if (rep != null) { sb.append(rep); } } else { sb.append(c); } break; case '^': if (i == 0) { int i1 = str.indexOf('^', i + 1); int i2 = str.indexOf('^', i1 + 1); if (i2 < 0) { i2 = str.length(); } if (i1 > 0 && i2 > 0) { String s1 = str.substring(i + 1, i1); String s2 = str.substring(i1 + 1, i2); String s = history.get(history.index() - 1).toString().replace(s1, s2); sb.append(s); i = i2 + 1; break; } } sb.append(c); break; default: sb.append(c); break; } } String result = sb.toString(); if (!str.equals(result)) { print(result); println(); flush(); } return result; } /** * Write out the specified string to the buffer and the output stream. */ public final void putString(final CharSequence str) throws IOException { buf.write(str); print(str); drawBuffer(); } /** * Output the specified character, both to the buffer and the output stream. */ private void putChar(final int c, final boolean print) throws IOException { buf.write((char) c); if (print) { if (mask == null) { // no masking print(c); } else if (mask == NULL_MASK) { // Don't print anything } else { print(mask); } drawBuffer(); } } /** * Redraw the rest of the buffer from the cursor onwards. This is necessary * for inserting text into the buffer. * * @param clear the number of characters to clear after the end of the buffer */ private void drawBuffer(final int clear) throws IOException { // debug ("drawBuffer: " + clear); if (buf.cursor == buf.length() && clear == 0) { } else { char[] chars = buf.buffer.substring(buf.cursor).toCharArray(); if (mask != null) { Arrays.fill(chars, mask); } if (terminal.hasWeirdWrap()) { // need to determine if wrapping will occur: int width = terminal.getWidth(); int pos = getCursorPosition(); for (int i = 0; i < chars.length; i++) { print(chars[i]); if ((pos + i + 1) % width == 0) { print(32); // move cursor to next line by printing dummy space print(13); // CR / not newline. } } } else { print(chars); } clearAhead(clear, chars.length); if (terminal.isAnsiSupported()) { if (chars.length > 0) { back(chars.length); } } else { back(chars.length); } } if (terminal.hasWeirdWrap()) { int width = terminal.getWidth(); // best guess on whether the cursor is in that weird location... // Need to do this without calling ansi cursor location methods // otherwise it breaks paste of wrapped lines in xterm. if (getCursorPosition() > 0 && (getCursorPosition() % width == 0) && buf.cursor == buf.length() && clear == 0) { // the following workaround is reverse-engineered from looking // at what bash sent to the terminal in the same situation print(32); // move cursor to next line by printing dummy space print(13); // CR / not newline. } } } /** * Redraw the rest of the buffer from the cursor onwards. This is necessary * for inserting text into the buffer. */ private void drawBuffer() throws IOException { drawBuffer(0); } /** * Clear ahead the specified number of characters without moving the cursor. * * @param num the number of characters to clear * @param delta the difference between the internal cursor and the screen * cursor - if > 0, assume some stuff was printed and weird wrap has to be * checked */ private void clearAhead(final int num, int delta) throws IOException { if (num == 0) { return; } if (terminal.isAnsiSupported()) { int width = terminal.getWidth(); int screenCursorCol = getCursorPosition() + delta; // clear current line printAnsiSequence("K"); // if cursor+num wraps, then we need to clear the line(s) below too int curCol = screenCursorCol % width; int endCol = (screenCursorCol + num - 1) % width; int lines = num / width; if (endCol < curCol) lines++; for (int i = 0; i < lines; i++) { printAnsiSequence("B"); printAnsiSequence("2K"); } for (int i = 0; i < lines; i++) { printAnsiSequence("A"); } return; } // print blank extra characters print(' ', num); // we need to flush here so a "clever" console doesn't just ignore the redundancy // of a space followed by a backspace. // flush(); // reset the visual cursor back(num); // flush(); } /** * Move the visual cursor backwards without modifying the buffer cursor. */ protected void back(final int num) throws IOException { if (num == 0) return; if (terminal.isAnsiSupported()) { int width = getTerminal().getWidth(); int cursor = getCursorPosition(); int realCursor = cursor + num; int realCol = realCursor % width; int newCol = cursor % width; int moveup = num / width; int delta = realCol - newCol; if (delta < 0) moveup++; if (moveup > 0) { printAnsiSequence(moveup + "A"); } printAnsiSequence((1 + newCol) + "G"); return; } print(BACKSPACE, num); // flush(); } /** * Flush the console output stream. This is important for printout out single characters (like a backspace or * keyboard) that we want the console to handle immediately. */ public void flush() throws IOException { out.flush(); } private int backspaceAll() throws IOException { return backspace(Integer.MAX_VALUE); } /** * Issue <em>num</em> backspaces. * * @return the number of characters backed up */ private int backspace(final int num) throws IOException { if (buf.cursor == 0) { return 0; } int count = 0; int termwidth = getTerminal().getWidth(); int lines = getCursorPosition() / termwidth; count = moveCursor(-1 * num) * -1; buf.buffer.delete(buf.cursor, buf.cursor + count); if (getCursorPosition() / termwidth != lines) { if (terminal.isAnsiSupported()) { // debug("doing backspace redraw: " + getCursorPosition() + " on " + termwidth + ": " + lines); printAnsiSequence("K"); // if cursor+num wraps, then we need to clear the line(s) below too // last char printed is one pos less than cursor so we subtract // one /* // TODO: fixme (does not work - test with reverse search with wrapping line and CTRL-E) int endCol = (getCursorPosition() + num - 1) % termwidth; int curCol = getCursorPosition() % termwidth; if (endCol < curCol) lines++; for (int i = 1; i < lines; i++) { printAnsiSequence("B"); printAnsiSequence("2K"); } for (int i = 1; i < lines; i++) { printAnsiSequence("A"); } return count; */ } } drawBuffer(count); return count; } /** * Issue a backspace. * * @return true if successful */ public boolean backspace() throws IOException { return backspace(1) == 1; } private boolean moveToEnd() throws IOException { return moveCursor(buf.length() - buf.cursor) > 0; } /** * Delete the character at the current position and redraw the remainder of the buffer. */ private boolean deleteCurrentCharacter() throws IOException { if (buf.length() == 0 || buf.cursor == buf.length()) { return false; } buf.buffer.deleteCharAt(buf.cursor); drawBuffer(1); return true; } private boolean previousWord() throws IOException { while (isDelimiter(buf.current()) && (moveCursor(-1) != 0)) { // nothing } while (!isDelimiter(buf.current()) && (moveCursor(-1) != 0)) { // nothing } return true; } private boolean nextWord() throws IOException { while (isDelimiter(buf.current()) && (moveCursor(1) != 0)) { // nothing } while (!isDelimiter(buf.current()) && (moveCursor(1) != 0)) { // nothing } return true; } private boolean deletePreviousWord() throws IOException { while (isDelimiter(buf.current()) && backspace()) { // nothing } while (!isDelimiter(buf.current()) && backspace()) { // nothing } return true; } /** * Move the cursor <i>where</i> characters. * * @param num If less than 0, move abs(<i>where</i>) to the left, otherwise move <i>where</i> to the right. * @return The number of spaces we moved */ public int moveCursor(final int num) throws IOException { int where = num; if ((buf.cursor == 0) && (where <= 0)) { return 0; } if ((buf.cursor == buf.buffer.length()) && (where >= 0)) { return 0; } if ((buf.cursor + where) < 0) { where = -buf.cursor; } else if ((buf.cursor + where) > buf.buffer.length()) { where = buf.buffer.length() - buf.cursor; } moveInternal(where); return where; } /** * Move the cursor <i>where</i> characters, without checking the current buffer. * * @param where the number of characters to move to the right or left. */ private void moveInternal(final int where) throws IOException { // debug ("move cursor " + where + " (" // + buf.cursor + " => " + (buf.cursor + where) + ")"); buf.cursor += where; if (terminal.isAnsiSupported()) { if (where < 0) { back(Math.abs(where)); } else { int width = getTerminal().getWidth(); int cursor = getCursorPosition(); int oldLine = (cursor - where) / width; int newLine = cursor / width; if (newLine > oldLine) { if (terminal.hasWeirdWrap()) { // scroll up if at bottom // note: // on rxvt cywgin terminal.getHeight() is incorrect // MacOs xterm does not seem to support scrolling if (getCurrentAnsiRow() == terminal.getHeight()) { printAnsiSequence((newLine - oldLine) + "S"); } } printAnsiSequence((newLine - oldLine) + "B"); } printAnsiSequence(1 +(cursor % width) + "G"); } // flush(); return; } char c; if (where < 0) { int len = 0; for (int i = buf.cursor; i < buf.cursor - where; i++) { if (buf.buffer.charAt(i) == '\t') { len += TAB_WIDTH; } else { len++; } } char chars[] = new char[len]; Arrays.fill(chars, BACKSPACE); out.write(chars); return; } else if (buf.cursor == 0) { return; } else if (mask != null) { c = mask; } else { print(buf.buffer.substring(buf.cursor - where, buf.cursor).toCharArray()); return; } // null character mask: don't output anything if (mask == NULL_MASK) { return; } print(c, Math.abs(where)); } // FIXME: replace() is not used public final boolean replace(final int num, final String replacement) { buf.buffer.replace(buf.cursor - num, buf.cursor, replacement); try { moveCursor(-num); drawBuffer(Math.max(0, num - replacement.length())); moveCursor(replacement.length()); } catch (IOException e) { e.printStackTrace(); return false; } return true; } // // Key reading // /** * Read a character from the console. * * @return the character, or -1 if an EOF is received. */ public final int readVirtualKey() throws IOException { int c = terminal.readVirtualKey(in); Log.trace("Keystroke: ", c); // clear any echo characters clearEcho(c); return c; } /** * Clear the echoed characters for the specified character code. */ private int clearEcho(final int c) throws IOException { // if the terminal is not echoing, then ignore if (!terminal.isEchoEnabled()) { return 0; } // otherwise, clear int num = countEchoCharacters((char) c); back(num); drawBuffer(num); return num; } private int countEchoCharacters(final char c) { // tabs as special: we need to determine the number of spaces // to cancel based on what out current cursor position is if (c == 9) { int tabStop = 8; // will this ever be different? int position = getCursorPosition(); return tabStop - (position % tabStop); } return getPrintableCharacters(c).length(); } /** * Return the number of characters that will be printed when the specified * character is echoed to the screen * * Adapted from cat by Torbjorn Granlund, as repeated in stty by David MacKenzie. */ private StringBuilder getPrintableCharacters(final char ch) { StringBuilder sbuff = new StringBuilder(); if (ch >= 32) { if (ch < 127) { sbuff.append(ch); } else if (ch == 127) { sbuff.append('^'); sbuff.append('?'); } else { sbuff.append('M'); sbuff.append('-'); if (ch >= (128 + 32)) { if (ch < (128 + 127)) { sbuff.append((char) (ch - 128)); } else { sbuff.append('^'); sbuff.append('?'); } } else { sbuff.append('^'); sbuff.append((char) (ch - 128 + 64)); } } } else { sbuff.append('^'); sbuff.append((char) (ch + 64)); } return sbuff; } public final int readCharacter(final char... allowed) throws IOException { // if we restrict to a limited set and the current character is not in the set, then try again. char c; Arrays.sort(allowed); // always need to sort before binarySearch while (Arrays.binarySearch(allowed, c = (char) readVirtualKey()) < 0) { // nothing } return c; } // // Key Bindings // public static final String JLINE_COMPLETION_THRESHOLD = "jline.completion.threshold"; public static final String JLINE_KEYBINDINGS = "jline.keybindings"; public static final String JLINEBINDINGS_PROPERTIES = ".jlinebindings.properties"; /** * The map for logical operations. */ private final short[] keyBindings; private short[] loadKeyBindings(InputStream input) throws IOException { if (input == null) { try { File file = new File(Configuration.getUserHome(), JLINEBINDINGS_PROPERTIES); String path = Configuration.getString(JLINE_KEYBINDINGS); if (path != null) { file = new File(path); } if (file.isFile()) { Log.debug("Loading user bindings from: ", file); input = new FileInputStream(file); } } catch (Exception e) { Log.error("Failed to load user bindings", e); } } if (input == null) { Log.debug("Using default bindings"); input = getTerminal().getDefaultBindings(); } short[] keyBindings = new short[Character.MAX_VALUE * 2]; Arrays.fill(keyBindings, Operation.UNKNOWN.code); // Loads the key bindings. Bindings file is in the format: // // keycode: operation name if (input != null) { input = new BufferedInputStream(input); Properties p = new Properties(); p.load(input); input.close(); for (Object key : p.keySet()) { String val = (String) key; try { short code = Short.parseShort(val); String name = p.getProperty(val); Operation op = Operation.valueOf(name); keyBindings[code] = op.code; } catch (NumberFormatException e) { Log.error("Failed to convert binding code: ", val, e); } } // hardwired arrow key bindings // keybindings[VK_UP] = PREV_HISTORY; // keybindings[VK_DOWN] = NEXT_HISTORY; // keybindings[VK_LEFT] = PREV_CHAR; // keybindings[VK_RIGHT] = NEXT_CHAR; } return keyBindings; } int getKeyForAction(final short logicalAction) { for (int i = 0; i < keyBindings.length; i++) { if (keyBindings[i] == logicalAction) { return i; } } return -1; } int getKeyForAction(final Operation op) { assert op != null; return getKeyForAction(op.code); } /** * Reads the console input and returns an array of the form [raw, key binding]. */ private int[] readBinding() throws IOException { int c = readVirtualKey(); if (c == -1) { return null; } // extract the appropriate key binding short code = keyBindings[c]; Log.trace("Translated: ", c, " -> ", code); return new int[]{c, code}; } // // Line Reading // /** * Read the next line and return the contents of the buffer. */ public String readLine() throws IOException { return readLine((String) null); } /** * Read the next line with the specified character mask. If null, then * characters will be echoed. If 0, then no characters will be echoed. */ public String readLine(final Character mask) throws IOException { return readLine(null, mask); } public String readLine(final String prompt) throws IOException { return readLine(prompt, null); } /** * Read a line from the <i>in</i> {@link InputStream}, and return the line * (without any trailing newlines). * * @param prompt The prompt to issue to the console, may be null. * @return A line that is read from the terminal, or null if there was null input (e.g., <i>CTRL-D</i> * was pressed). */ public String readLine(String prompt, final Character mask) throws IOException { // prompt may be null // mask may be null // FIXME: This blows, each call to readLine will reset the console's state which doesn't seem very nice. this.mask = mask; if (prompt != null) { setPrompt(prompt); } else { prompt = getPrompt(); } try { if (!terminal.isSupported()) { beforeReadLine(prompt, mask); } if (prompt != null && prompt.length() > 0) { out.write(prompt); out.flush(); } // if the terminal is unsupported, just use plain-java reading if (!terminal.isSupported()) { return readLine(in); } String originalPrompt = this.prompt; final int NORMAL = 1; final int SEARCH = 2; int state = NORMAL; boolean success = true; while (true) { int[] next = readBinding(); if (next == null) { return null; } int c = next[0]; // int code = next[1]; Operation code = Operation.valueOf(next[1]); if (c == -1) { return null; } // Search mode. // // Note that we have to do this first, because if there is a command // not linked to a search command, we leave the search mode and fall // through to the normal state. if (state == SEARCH) { int cursorDest = -1; switch (code) { // This doesn't work right now, it seems CTRL-G is not passed // down correctly. :( case ABORT: state = NORMAL; break; case SEARCH_PREV: if (searchTerm.length() == 0) { searchTerm.append(previousSearchTerm); } if (searchIndex == -1) { searchIndex = searchBackwards(searchTerm.toString()); } else { searchIndex = searchBackwards(searchTerm.toString(), searchIndex); } break; case DELETE_PREV_CHAR: if (searchTerm.length() > 0) { searchTerm.deleteCharAt(searchTerm.length() - 1); searchIndex = searchBackwards(searchTerm.toString()); } break; case UNKNOWN: searchTerm.appendCodePoint(c); searchIndex = searchBackwards(searchTerm.toString()); break; default: // Set buffer and cursor position to the found string. if (searchIndex != -1) { history.moveTo(searchIndex); // set cursor position to the found string cursorDest = history.current().toString().indexOf(searchTerm.toString()); } state = NORMAL; break; } // if we're still in search mode, print the search status if (state == SEARCH) { if (searchTerm.length() == 0) { printSearchStatus("", ""); searchIndex = -1; } else { if (searchIndex == -1) { beep(); } else { printSearchStatus(searchTerm.toString(), history.get(searchIndex).toString()); } } } // otherwise, restore the line else { restoreLine(originalPrompt, cursorDest); } } if (state == NORMAL) { switch (code) { case EXIT: // ctrl-d if (buf.buffer.length() == 0) { return null; } else { deleteCurrentCharacter(); } break; case COMPLETE: // tab success = complete(); break; case MOVE_TO_BEG: success = setCursorPosition(0); break; case KILL_LINE: // CTRL-K success = killLine(); break; case CLEAR_SCREEN: // CTRL-L success = clearScreen(); break; case KILL_LINE_PREV: // CTRL-U success = resetLine(); break; case NEWLINE: // enter moveToEnd(); println(); // output newline flush(); return finishBuffer(); case DELETE_PREV_CHAR: // backspace success = backspace(); break; case DELETE_NEXT_CHAR: // delete success = deleteCurrentCharacter(); break; case MOVE_TO_END: success = moveToEnd(); break; case PREV_CHAR: success = moveCursor(-1) != 0; break; case NEXT_CHAR: success = moveCursor(1) != 0; break; case NEXT_HISTORY: success = moveHistory(true); break; case PREV_HISTORY: success = moveHistory(false); break; case ABORT: case REDISPLAY: break; case PASTE: success = paste(); break; case DELETE_PREV_WORD: success = deletePreviousWord(); break; case PREV_WORD: success = previousWord(); break; case NEXT_WORD: success = nextWord(); break; case START_OF_HISTORY: success = history.moveToFirst(); if (success) { setBuffer(history.current()); } break; case END_OF_HISTORY: success = history.moveToLast(); if (success) { setBuffer(history.current()); } break; case CLEAR_LINE: moveInternal(-(buf.cursor)); killLine(); break; case INSERT: buf.setOverTyping(!buf.isOverTyping()); break; case SEARCH_PREV: // CTRL-R if (searchTerm != null) { previousSearchTerm = searchTerm.toString(); } searchTerm = new StringBuffer(buf.buffer); state = SEARCH; if (searchTerm.length() > 0) { searchIndex = searchBackwards(searchTerm.toString()); if (searchIndex == -1) { beep(); } printSearchStatus(searchTerm.toString(), searchIndex > -1 ? history.get(searchIndex).toString() : ""); } else { searchIndex = -1; printSearchStatus("", ""); } break; case UNKNOWN: default: if (c != 0) { // ignore null chars ActionListener action = triggeredActions.get((char) c); if (action != null) { action.actionPerformed(null); } else { putChar(c, true); } } else { success = false; } } if (!success) { beep(); } flush(); } } } finally { if (!terminal.isSupported()) { afterReadLine(); } } } /** * Read a line for unsupported terminals. */ private String readLine(final InputStream in) throws IOException { StringBuilder buff = new StringBuilder(); while (true) { int i = in.read(); if (i == -1 || i == '\n' || i == '\r') { return buff.toString(); } buff.append((char) i); } // return new BufferedReader (new InputStreamReader (in)).readLine (); } // // Completion // private final List<Completer> completers = new LinkedList<Completer>(); private CompletionHandler completionHandler = new CandidateListCompletionHandler(); /** * Add the specified {@link jline.console.completer.Completer} to the list of handlers for tab-completion. * * @param completer the {@link jline.console.completer.Completer} to add * @return true if it was successfully added */ public boolean addCompleter(final Completer completer) { return completers.add(completer); } /** * Remove the specified {@link jline.console.completer.Completer} from the list of handlers for tab-completion. * * @param completer The {@link Completer} to remove * @return True if it was successfully removed */ public boolean removeCompleter(final Completer completer) { return completers.remove(completer); } /** * Returns an unmodifiable list of all the completers. */ public Collection<Completer> getCompleters() { return Collections.unmodifiableList(completers); } public void setCompletionHandler(final CompletionHandler handler) { assert handler != null; this.completionHandler = handler; } public CompletionHandler getCompletionHandler() { return this.completionHandler; } /** * Use the completers to modify the buffer with the appropriate completions. * * @return true if successful */ protected boolean complete() throws IOException { // debug ("tab for (" + buf + ")"); if (completers.size() == 0) { return false; } List<CharSequence> candidates = new LinkedList<CharSequence>(); String bufstr = buf.buffer.toString(); int cursor = buf.cursor; int position = -1; for (Completer comp : completers) { if ((position = comp.complete(bufstr, cursor, candidates)) != -1) { break; } } return candidates.size() != 0 && getCompletionHandler().complete(this, candidates, position); } /** * The number of tab-completion candidates above which a warning will be * prompted before showing all the candidates. */ private int autoprintThreshold = Integer.getInteger(JLINE_COMPLETION_THRESHOLD, 100); // same default as bash /** * @param threshold the number of candidates to print without issuing a warning. */ public void setAutoprintThreshold(final int threshold) { this.autoprintThreshold = threshold; } /** * @return the number of candidates to print without issuing a warning. */ public int getAutoprintThreshold() { return autoprintThreshold; } private boolean paginationEnabled; /** * Whether to use pagination when the number of rows of candidates exceeds the height of the terminal. */ public void setPaginationEnabled(final boolean enabled) { this.paginationEnabled = enabled; } /** * Whether to use pagination when the number of rows of candidates exceeds the height of the terminal. */ public boolean isPaginationEnabled() { return paginationEnabled; } // // History // private History history = new MemoryHistory(); public void setHistory(final History history) { this.history = history; } public History getHistory() { return history; } private boolean historyEnabled = true; /** * Whether or not to add new commands to the history buffer. */ public void setHistoryEnabled(final boolean enabled) { this.historyEnabled = enabled; } /** * Whether or not to add new commands to the history buffer. */ public boolean isHistoryEnabled() { return historyEnabled; } /** * Move up or down the history tree. */ private boolean moveHistory(final boolean next) throws IOException { if (next && !history.next()) { return false; } else if (!next && !history.previous()) { return false; } setBuffer(history.current()); return true; } // // Printing // public static final String CR = System.getProperty("line.separator"); /** * Output the specified character to the output stream without manipulating the current buffer. */ private void print(final int c) throws IOException { if (c == '\t') { char chars[] = new char[TAB_WIDTH]; Arrays.fill(chars, ' '); out.write(chars); return; } out.write(c); } /** * Output the specified characters to the output stream without manipulating the current buffer. */ private void print(final char... buff) throws IOException { int len = 0; for (char c : buff) { if (c == '\t') { len += TAB_WIDTH; } else { len++; } } char chars[]; if (len == buff.length) { chars = buff; } else { chars = new char[len]; int pos = 0; for (char c : buff) { if (c == '\t') { Arrays.fill(chars, pos, pos + TAB_WIDTH, ' '); pos += TAB_WIDTH; } else { chars[pos] = c; pos++; } } } out.write(chars); } private void print(final char c, final int num) throws IOException { if (num == 1) { print(c); } else { char[] chars = new char[num]; Arrays.fill(chars, c); print(chars); } } /** * Output the specified string to the output stream (but not the buffer). */ public final void print(final CharSequence s) throws IOException { assert s != null; print(s.toString().toCharArray()); } public final void println(final CharSequence s) throws IOException { assert s != null; print(s.toString().toCharArray()); println(); } /** * Output a platform-dependant newline. */ public final void println() throws IOException { print(CR); // flush(); } // // Actions // /** * Issue a delete. * * @return true if successful */ public final boolean delete() throws IOException { return delete(1) == 1; } // FIXME: delete(int) only used by above + the return is always 1 and num is ignored /** * Issue <em>num</em> deletes. * * @return the number of characters backed up */ private int delete(final int num) throws IOException { // TODO: Try to use jansi for this /* Commented out because of DWA-2949: if (buf.cursor == 0) { return 0; } */ buf.buffer.delete(buf.cursor, buf.cursor + 1); drawBuffer(1); return 1; } /** * Kill the buffer ahead of the current cursor position. * * @return true if successful */ public boolean killLine() throws IOException { int cp = buf.cursor; int len = buf.buffer.length(); if (cp >= len) { return false; } int num = buf.buffer.length() - cp; clearAhead(num, 0); for (int i = 0; i < num; i++) { buf.buffer.deleteCharAt(len - i - 1); } return true; } /** * Clear the screen by issuing the ANSI "clear screen" code. */ public boolean clearScreen() throws IOException { if (!terminal.isAnsiSupported()) { return false; } // send the ANSI code to clear the screen printAnsiSequence("2J"); // then send the ANSI code to go to position 1,1 printAnsiSequence("1;1H"); redrawLine(); return true; } /** * Issue an audible keyboard bell, if {@link #isBellEnabled} return true. */ public void beep() throws IOException { if (isBellEnabled()) { print(KEYBOARD_BELL); // need to flush so the console actually beeps flush(); } } /** * Paste the contents of the clipboard into the console buffer * * @return true if clipboard contents pasted */ public boolean paste() throws IOException { Clipboard clipboard; try { // May throw ugly exception on system without X clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); } catch (Exception e) { return false; } if (clipboard == null) { return false; } Transferable transferable = clipboard.getContents(null); if (transferable == null) { return false; } try { Object content = transferable.getTransferData(DataFlavor.plainTextFlavor); // This fix was suggested in bug #1060649 at // http://sourceforge.net/tracker/index.php?func=detail&aid=1060649&group_id=64033&atid=506056 // to get around the deprecated DataFlavor.plainTextFlavor, but it // raises a UnsupportedFlavorException on Mac OS X if (content == null) { try { content = new DataFlavor().getReaderForText(transferable); } catch (Exception e) { // ignore } } if (content == null) { return false; } String value; if (content instanceof Reader) { // TODO: we might want instead connect to the input stream // so we can interpret individual lines value = ""; String line; BufferedReader read = new BufferedReader((Reader) content); while ((line = read.readLine()) != null) { if (value.length() > 0) { value += "\n"; } value += line; } } else { value = content.toString(); } if (value == null) { return true; } putString(value); return true; } catch (UnsupportedFlavorException e) { Log.error("Paste failed: ", e); return false; } } // // Triggered Actions // private final Map<Character, ActionListener> triggeredActions = new HashMap<Character, ActionListener>(); /** * Adding a triggered Action allows to give another curse of action if a character passed the pre-processing. * <p/> * Say you want to close the application if the user enter q. * addTriggerAction('q', new ActionListener(){ System.exit(0); }); would do the trick. */ public void addTriggeredAction(final char c, final ActionListener listener) { triggeredActions.put(c, listener); } // // Formatted Output // /** * Output the specified {@link Collection} in proper columns. */ public void printColumns(final Collection<? extends CharSequence> items) throws IOException { if (items == null || items.isEmpty()) { return; } int width = getTerminal().getWidth(); int height = getTerminal().getHeight(); int maxWidth = 0; for (CharSequence item : items) { maxWidth = Math.max(maxWidth, item.length()); } Log.debug("Max width: ", maxWidth); int showLines; if (isPaginationEnabled()) { showLines = height - 1; // page limit } else { showLines = Integer.MAX_VALUE; } StringBuilder buff = new StringBuilder(); for (CharSequence item : items) { if ((buff.length() + maxWidth) > width) { println(buff); buff.setLength(0); if (--showLines == 0) { // Overflow print(resources.getString("display-more")); flush(); int c = readVirtualKey(); if (c == '\r' || c == '\n') { // one step forward showLines = 1; } else if (c != 'q') { // page forward showLines = height - 1; } back(resources.getString("display-more").length()); if (c == 'q') { // cancel break; } } } // NOTE: toString() is important here due to AnsiString being retarded buff.append(item.toString()); for (int i = 0; i < (maxWidth + 3 - item.length()); i++) { buff.append(' '); } } if (buff.length() > 0) { println(buff); } } // // Non-supported Terminal Support // private Thread maskThread; private void beforeReadLine(final String prompt, final Character mask) { if (mask != null && maskThread == null) { final String fullPrompt = "\r" + prompt + " " + " " + " " + "\r" + prompt; maskThread = new Thread() { public void run() { while (!interrupted()) { try { Writer out = getOutput(); out.write(fullPrompt); out.flush(); sleep(3); } catch (IOException e) { return; } catch (InterruptedException e) { return; } } } }; maskThread.setPriority(Thread.MAX_PRIORITY); maskThread.setDaemon(true); maskThread.start(); } } private void afterReadLine() { if (maskThread != null && maskThread.isAlive()) { maskThread.interrupt(); } maskThread = null; } /** * Erases the current line with the existing prompt, then redraws the line * with the provided prompt and buffer * @param prompt * the new prompt * @param buffer * the buffer to be drawn * @param cursorDest * where you want the cursor set when the line has been drawn. * -1 for end of line. * */ public void resetPromptLine(String prompt, String buffer, int cursorDest) throws IOException { // move cursor to end of line moveToEnd(); // backspace all text, including prompt buf.buffer.append(this.prompt); buf.cursor += this.prompt.length(); this.prompt = ""; backspaceAll(); this.prompt = prompt; redrawLine(); setBuffer(buffer); // move cursor to destination (-1 will move to end of line) if (cursorDest < 0) cursorDest = buffer.length(); setCursorPosition(cursorDest); flush(); } public void printSearchStatus(String searchTerm, String match) throws IOException { String prompt = "(reverse-i-search)`" + searchTerm + "': "; String buffer = match; int cursorDest = match.indexOf(searchTerm); resetPromptLine(prompt, buffer, cursorDest); } public void restoreLine(String originalPrompt, int cursorDest) throws IOException { // TODO move cursor to matched string String prompt = lastLine(originalPrompt); String buffer = buf.buffer.toString(); resetPromptLine(prompt, buffer, cursorDest); } // // History search // /** * Search backward in history from a given position. * * @param searchTerm substring to search for. * @param startIndex the index from which on to search * @return index where this substring has been found, or -1 else. */ public int searchBackwards(String searchTerm, int startIndex) { return searchBackwards(searchTerm, startIndex, false); } /** * Search backwards in history from the current position. * * @param searchTerm substring to search for. * @return index where the substring has been found, or -1 else. */ public int searchBackwards(String searchTerm) { return searchBackwards(searchTerm, history.index()); } public int searchBackwards(String searchTerm, int startIndex, boolean startsWith) { ListIterator<History.Entry> it = history.entries(startIndex); while (it.hasPrevious()) { History.Entry e = it.previous(); if (startsWith) { if (e.value().toString().startsWith(searchTerm)) { return e.index(); } } else { if (e.value().toString().contains(searchTerm)) { return e.index(); } } } return -1; } // // Helpers // /** * Checks to see if the specified character is a delimiter. We consider a * character a delimiter if it is anything but a letter or digit. * * @param c The character to test * @return True if it is a delimiter */ private boolean isDelimiter(final char c) { return !Character.isLetterOrDigit(c); } private void printAnsiSequence(String sequence) throws IOException { print(27); print('['); print(sequence); flush(); // helps with step debugging } // return column position, reported by the terminal private int getCurrentPosition() { // check for ByteArrayInputStream to disable for unit tests if (terminal.isAnsiSupported() && !(in instanceof ByteArrayInputStream)) { try { printAnsiSequence("6n"); flush(); StringBuffer b = new StringBuffer(8); // position is sent as <ESC>[{ROW};{COLUMN}R int r; while((r = in.read()) > -1 && r != 'R') { if (r != 27 && r != '[') { b.append((char) r); } } String[] pos = b.toString().split(";"); return Integer.parseInt(pos[1]); } catch (Exception x) { // no luck } } return -1; // TODO: throw exception instead? } // return row position, reported by the terminal // needed to know whether to scroll up on cursor move in last col for weird // wrapping terminals - not tested for anything else private int getCurrentAnsiRow() { // check for ByteArrayInputStream to disable for unit tests if (terminal.isAnsiSupported() && !(in instanceof ByteArrayInputStream)) { try { printAnsiSequence("6n"); flush(); StringBuffer b = new StringBuffer(8); // position is sent as <ESC>[{ROW};{COLUMN}R int r; while((r = in.read()) > -1 && r != 'R') { if (r != 27 && r != '[') { b.append((char) r); } } String[] pos = b.toString().split(";"); return Integer.parseInt(pos[0]); } catch (Exception x) { // no luck } } return -1; // TODO: throw exception instead? } }
src/main/java/jline/console/ConsoleReader.java
/* * Copyright (c) 2002-2007, Marc Prud'hommeaux. All rights reserved. * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. */ package jline.console; import jline.Terminal; import jline.TerminalFactory; import jline.console.completer.CandidateListCompletionHandler; import jline.console.completer.Completer; import jline.console.completer.CompletionHandler; import jline.console.history.History; import jline.console.history.MemoryHistory; import jline.internal.Configuration; import jline.internal.Log; import org.fusesource.jansi.AnsiOutputStream; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.awt.event.ActionListener; import java.io.*; import java.util.*; /** * A reader for console applications. It supports custom tab-completion, * saveable command history, and command line editing. On some platforms, * platform-specific commands will need to be issued before the reader will * function properly. See {@link jline.Terminal#init} for convenience * methods for issuing platform-specific setup commands. * * @author <a href="mailto:mwp1@cornell.edu">Marc Prud'hommeaux</a> * @author <a href="mailto:jason@planet57.com">Jason Dillon</a> */ public class ConsoleReader { public static final String JLINE_NOBELL = "jline.nobell"; public static final String JLINE_EXPANDEVENTS = "jline.expandevents"; public static final char BACKSPACE = '\b'; public static final char RESET_LINE = '\r'; public static final char KEYBOARD_BELL = '\07'; public static final char NULL_MASK = 0; public static final int TAB_WIDTH = 4; private static final ResourceBundle resources = ResourceBundle.getBundle(CandidateListCompletionHandler.class.getName()); private final Terminal terminal; private InputStream in; private final Writer out; private final CursorBuffer buf = new CursorBuffer(); private String prompt; private boolean bellEnabled = true; private boolean expandEvents = false; private Character mask; private Character echoCharacter; private StringBuffer searchTerm = null; private String previousSearchTerm = ""; private int searchIndex = -1; public ConsoleReader(final InputStream in, final OutputStream out, final InputStream bindings, final Terminal term) throws IOException { this.in = in; this.terminal = term != null ? term : TerminalFactory.get(); this.out = new PrintWriter(terminal.wrapOutIfNeeded(out)); this.keyBindings = loadKeyBindings(bindings); setBellEnabled(!Configuration.getBoolean(JLINE_NOBELL, false)); setExpandEvents(Configuration.getBoolean(JLINE_EXPANDEVENTS, false)); } /** * @deprecated use {@link #ConsoleReader(InputStream, OutputStream, InputStream, Terminal)} * to let the terminal wrap the output stream if needed. */ public ConsoleReader(final InputStream in, final Writer out, final InputStream bindings, final Terminal term) throws IOException { this.in = in; this.out = out; this.terminal = term != null ? term : TerminalFactory.get(); this.keyBindings = loadKeyBindings(bindings); setBellEnabled(!Configuration.getBoolean(JLINE_NOBELL, false)); } /** * @deprecated use {@link #ConsoleReader(InputStream, OutputStream, InputStream, Terminal)} * to let the terminal wrap the output stream if needed. */ public ConsoleReader(final InputStream in, final Writer out, final Terminal term) throws IOException { this(in, out, null, term); } /** * @deprecated use {@link #ConsoleReader(InputStream, OutputStream, InputStream, Terminal)} * to let the terminal wrap the output stream if needed. */ public ConsoleReader(final InputStream in, final Writer out) throws IOException { this(in, out, null, null); } /** * Create a new reader using {@link FileDescriptor#in} for input and * {@link System#out} for output. * <p/> * {@link FileDescriptor#in} is used because it has a better chance of not being buffered. */ public ConsoleReader() throws IOException { this(new FileInputStream(FileDescriptor.in), System.out, null, null ); } // FIXME: Only used for tests void setInput(final InputStream in) { this.in = in; } public InputStream getInput() { return in; } public Writer getOutput() { return out; } public Terminal getTerminal() { return terminal; } public CursorBuffer getCursorBuffer() { return buf; } public void setBellEnabled(final boolean enabled) { this.bellEnabled = enabled; } public boolean isBellEnabled() { return bellEnabled; } public void setExpandEvents(final boolean expand) { this.expandEvents = expand; } public boolean getExpandEvents() { return expandEvents; } public void setPrompt(final String prompt) { this.prompt = prompt; } public String getPrompt() { return prompt; } /** * Set the echo character. For example, to have "*" entered when a password is typed: * <p/> * <pre> * myConsoleReader.setEchoCharacter(new Character('*')); * </pre> * <p/> * Setting the character to * <p/> * <pre> * null * </pre> * <p/> * will restore normal character echoing. Setting the character to * <p/> * <pre> * new Character(0) * </pre> * <p/> * will cause nothing to be echoed. * * @param c the character to echo to the console in place of the typed character. */ public void setEchoCharacter(final Character c) { this.echoCharacter = c; } /** * Returns the echo character. */ public Character getEchoCharacter() { return echoCharacter; } /** * Erase the current line. * * @return false if we failed (e.g., the buffer was empty) */ final boolean resetLine() throws IOException { if (buf.cursor == 0) { return false; } backspaceAll(); return true; } int getCursorPosition() { // FIXME: does not handle anything but a line with a prompt absolute position String prompt = getPrompt(); return ((prompt == null) ? 0 : stripAnsi(lastLine(prompt)).length()) + buf.cursor; } /** * Returns the text after the last '\n'. * prompt is returned if no '\n' characters are present. * null is returned if prompt is null. */ private String lastLine(String str) { if (str == null) return ""; int last = str.lastIndexOf("\n"); if (last >= 0) { return str.substring(last + 1, str.length()); } return str; } private String stripAnsi(String str) { if (str == null) return ""; try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); AnsiOutputStream aos = new AnsiOutputStream(baos); aos.write(str.getBytes()); aos.flush(); return baos.toString(); } catch (IOException e) { return str; } } /** * Move the cursor position to the specified absolute index. */ public final boolean setCursorPosition(final int position) throws IOException { return moveCursor(position - buf.cursor) != 0; } /** * Set the current buffer's content to the specified {@link String}. The * visual console will be modified to show the current buffer. * * @param buffer the new contents of the buffer. */ private void setBuffer(final String buffer) throws IOException { // don't bother modifying it if it is unchanged if (buffer.equals(buf.buffer.toString())) { return; } // obtain the difference between the current buffer and the new one int sameIndex = 0; for (int i = 0, l1 = buffer.length(), l2 = buf.buffer.length(); (i < l1) && (i < l2); i++) { if (buffer.charAt(i) == buf.buffer.charAt(i)) { sameIndex++; } else { break; } } int diff = buf.cursor - sameIndex; if (diff < 0) { // we can't backspace here so try from the end of the buffer moveToEnd(); diff = buf.buffer.length() - sameIndex; } backspace(diff); // go back for the differences killLine(); // clear to the end of the line buf.buffer.setLength(sameIndex); // the new length putString(buffer.substring(sameIndex)); // append the differences } private void setBuffer(final CharSequence buffer) throws IOException { setBuffer(String.valueOf(buffer)); } /** * Output put the prompt + the current buffer */ public final void drawLine() throws IOException { String prompt = getPrompt(); if (prompt != null) { print(prompt); } print(buf.buffer.toString()); if (buf.length() != buf.cursor) { // not at end of line back(buf.length() - buf.cursor - 1); } // force drawBuffer to check for weird wrap (after clear screen) drawBuffer(); } /** * Clear the line and redraw it. */ public final void redrawLine() throws IOException { print(RESET_LINE); // flush(); drawLine(); } /** * Clear the buffer and add its contents to the history. * * @return the former contents of the buffer. */ final String finishBuffer() throws IOException { // FIXME: Package protected because used by tests String str = buf.buffer.toString(); if (expandEvents) { str = expandEvents(str); } // we only add it to the history if the buffer is not empty // and if mask is null, since having a mask typically means // the string was a password. We clear the mask after this call if (str.length() > 0) { if (mask == null && isHistoryEnabled()) { history.add(str); } else { mask = null; } } history.moveToEnd(); buf.buffer.setLength(0); buf.cursor = 0; return str; } /** * Expand event designator such as !!, !#, !3, etc... * See http://www.gnu.org/software/bash/manual/html_node/Event-Designators.html * * @param str * @return */ final String expandEvents(String str) throws IOException { StringBuilder sb = new StringBuilder(); for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); switch (c) { case '!': if (i + 1 < str.length()) { c = str.charAt(++i); boolean neg = false; String rep = null; int i1, idx; switch (c) { case '!': if (history.size() == 0) { throw new IllegalArgumentException("!!: event not found"); } rep = history.get(history.index() - 1).toString(); break; case '#': sb.append(sb.toString()); break; case '?': i1 = str.indexOf('?', i + 1); if (i1 < 0) { i1 = str.length(); } String sc = str.substring(i + 1, i1); i = i1; idx = searchBackwards(sc); if (idx < 0) { throw new IllegalArgumentException("!?" + sc + ": event not found"); } else { rep = history.get(idx).toString(); } break; case ' ': case '\t': sb.append('!'); sb.append(c); break; case '-': neg = true; i++; // fall through case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': i1 = i; for (; i < str.length(); i++) { c = str.charAt(i); if (c < '0' || c > '9') { break; } } idx = 0; try { idx = Integer.parseInt(str.substring(i1, i)); } catch (NumberFormatException e) { throw new IllegalArgumentException((neg ? "!-" : "!") + str.substring(i1, i) + ": event not found"); } if (neg) { if (idx < history.size()) { rep = (history.get(history.index() - idx)).toString(); } else { throw new IllegalArgumentException((neg ? "!-" : "!") + str.substring(i1, i) + ": event not found"); } } else { if (idx >= history.index() - history.size() && idx < history.index()) { rep = (history.get(idx)).toString(); } else { throw new IllegalArgumentException((neg ? "!-" : "!") + str.substring(i1, i) + ": event not found"); } } break; default: String ss = str.substring(i); i = str.length(); idx = searchBackwards(ss, history.index(), true); if (idx < 0) { throw new IllegalArgumentException("!" + ss + ": event not found"); } else { rep = history.get(idx).toString(); } break; } if (rep != null) { sb.append(rep); } } else { sb.append(c); } break; case '^': if (i == 0) { int i1 = str.indexOf('^', i + 1); int i2 = str.indexOf('^', i1 + 1); if (i2 < 0) { i2 = str.length(); } if (i1 > 0 && i2 > 0) { String s1 = str.substring(i + 1, i1); String s2 = str.substring(i1 + 1, i2); String s = history.get(history.index() - 1).toString().replace(s1, s2); sb.append(s); i = i2 + 1; break; } } sb.append(c); break; default: sb.append(c); break; } } String result = sb.toString(); if (!str.equals(result)) { print(result); println(); flush(); } return result; } /** * Write out the specified string to the buffer and the output stream. */ public final void putString(final CharSequence str) throws IOException { buf.write(str); print(str); drawBuffer(); } /** * Output the specified character, both to the buffer and the output stream. */ private void putChar(final int c, final boolean print) throws IOException { buf.write((char) c); if (print) { if (mask == null) { // no masking print(c); } else if (mask == NULL_MASK) { // Don't print anything } else { print(mask); } drawBuffer(); } } /** * Redraw the rest of the buffer from the cursor onwards. This is necessary * for inserting text into the buffer. * * @param clear the number of characters to clear after the end of the buffer */ private void drawBuffer(final int clear) throws IOException { // debug ("drawBuffer: " + clear); if (buf.cursor == buf.length() && clear == 0) { } else { char[] chars = buf.buffer.substring(buf.cursor).toCharArray(); if (mask != null) { Arrays.fill(chars, mask); } if (terminal.hasWeirdWrap()) { // need to determine if wrapping will occur: int width = terminal.getWidth(); int pos = getCursorPosition(); for (int i = 0; i < chars.length; i++) { print(chars[i]); if ((pos + i + 1) % width == 0) { print(32); // move cursor to next line by printing dummy space print(13); // CR / not newline. } } } else { print(chars); } clearAhead(clear, chars.length); if (terminal.isAnsiSupported()) { if (chars.length > 0) { back(chars.length); } } else { back(chars.length); } } if (terminal.hasWeirdWrap()) { int width = terminal.getWidth(); // best guess on whether the cursor is in that weird location... // Need to do this without calling ansi cursor location methods // otherwise it breaks paste of wrapped lines in xterm. if (getCursorPosition() > 0 && (getCursorPosition() % width == 0) && buf.cursor == buf.length() && clear == 0) { // the following workaround is reverse-engineered from looking // at what bash sent to the terminal in the same situation print(32); // move cursor to next line by printing dummy space print(13); // CR / not newline. } } } /** * Redraw the rest of the buffer from the cursor onwards. This is necessary * for inserting text into the buffer. */ private void drawBuffer() throws IOException { drawBuffer(0); } /** * Clear ahead the specified number of characters without moving the cursor. * * @param num the number of characters to clear * @param delta the difference between the internal cursor and the screen * cursor - if > 0, assume some stuff was printed and weird wrap has to be * checked */ private void clearAhead(final int num, int delta) throws IOException { if (num == 0) { return; } if (terminal.isAnsiSupported()) { int width = terminal.getWidth(); int screenCursorCol = getCursorPosition() + delta; // clear current line printAnsiSequence("K"); // if cursor+num wraps, then we need to clear the line(s) below too int curCol = screenCursorCol % width; int endCol = (screenCursorCol + num - 1) % width; int lines = num / width; if (endCol < curCol) lines++; for (int i = 0; i < lines; i++) { printAnsiSequence("B"); printAnsiSequence("2K"); } for (int i = 0; i < lines; i++) { printAnsiSequence("A"); } return; } // print blank extra characters print(' ', num); // we need to flush here so a "clever" console doesn't just ignore the redundancy // of a space followed by a backspace. // flush(); // reset the visual cursor back(num); // flush(); } /** * Move the visual cursor backwards without modifying the buffer cursor. */ protected void back(final int num) throws IOException { if (num == 0) return; if (terminal.isAnsiSupported()) { int width = getTerminal().getWidth(); int cursor = getCursorPosition(); int realCursor = cursor + num; int realCol = realCursor % width; int newCol = cursor % width; int moveup = num / width; int delta = realCol - newCol; if (delta < 0) moveup++; if (moveup > 0) { printAnsiSequence(moveup + "A"); } printAnsiSequence((1 + newCol) + "G"); return; } print(BACKSPACE, num); // flush(); } /** * Flush the console output stream. This is important for printout out single characters (like a backspace or * keyboard) that we want the console to handle immediately. */ public void flush() throws IOException { out.flush(); } private int backspaceAll() throws IOException { return backspace(Integer.MAX_VALUE); } /** * Issue <em>num</em> backspaces. * * @return the number of characters backed up */ private int backspace(final int num) throws IOException { if (buf.cursor == 0) { return 0; } int count = 0; int termwidth = getTerminal().getWidth(); int lines = getCursorPosition() / termwidth; count = moveCursor(-1 * num) * -1; buf.buffer.delete(buf.cursor, buf.cursor + count); if (getCursorPosition() / termwidth != lines) { if (terminal.isAnsiSupported()) { // debug("doing backspace redraw: " + getCursorPosition() + " on " + termwidth + ": " + lines); printAnsiSequence("K"); // if cursor+num wraps, then we need to clear the line(s) below too // last char printed is one pos less than cursor so we subtract // one /* // TODO: fixme (does not work - test with reverse search with wrapping line and CTRL-E) int endCol = (getCursorPosition() + num - 1) % termwidth; int curCol = getCursorPosition() % termwidth; if (endCol < curCol) lines++; for (int i = 1; i < lines; i++) { printAnsiSequence("B"); printAnsiSequence("2K"); } for (int i = 1; i < lines; i++) { printAnsiSequence("A"); } return count; */ } } drawBuffer(count); return count; } /** * Issue a backspace. * * @return true if successful */ public boolean backspace() throws IOException { return backspace(1) == 1; } private boolean moveToEnd() throws IOException { return moveCursor(buf.length() - buf.cursor) > 0; } /** * Delete the character at the current position and redraw the remainder of the buffer. */ private boolean deleteCurrentCharacter() throws IOException { if (buf.length() == 0 || buf.cursor == buf.length()) { return false; } buf.buffer.deleteCharAt(buf.cursor); drawBuffer(1); return true; } private boolean previousWord() throws IOException { while (isDelimiter(buf.current()) && (moveCursor(-1) != 0)) { // nothing } while (!isDelimiter(buf.current()) && (moveCursor(-1) != 0)) { // nothing } return true; } private boolean nextWord() throws IOException { while (isDelimiter(buf.current()) && (moveCursor(1) != 0)) { // nothing } while (!isDelimiter(buf.current()) && (moveCursor(1) != 0)) { // nothing } return true; } private boolean deletePreviousWord() throws IOException { while (isDelimiter(buf.current()) && backspace()) { // nothing } while (!isDelimiter(buf.current()) && backspace()) { // nothing } return true; } /** * Move the cursor <i>where</i> characters. * * @param num If less than 0, move abs(<i>where</i>) to the left, otherwise move <i>where</i> to the right. * @return The number of spaces we moved */ public int moveCursor(final int num) throws IOException { int where = num; if ((buf.cursor == 0) && (where <= 0)) { return 0; } if ((buf.cursor == buf.buffer.length()) && (where >= 0)) { return 0; } if ((buf.cursor + where) < 0) { where = -buf.cursor; } else if ((buf.cursor + where) > buf.buffer.length()) { where = buf.buffer.length() - buf.cursor; } moveInternal(where); return where; } /** * Move the cursor <i>where</i> characters, without checking the current buffer. * * @param where the number of characters to move to the right or left. */ private void moveInternal(final int where) throws IOException { // debug ("move cursor " + where + " (" // + buf.cursor + " => " + (buf.cursor + where) + ")"); buf.cursor += where; if (terminal.isAnsiSupported()) { if (where < 0) { back(Math.abs(where)); } else { int width = getTerminal().getWidth(); int cursor = getCursorPosition(); int oldLine = (cursor - where) / width; int newLine = cursor / width; if (newLine > oldLine) { if (terminal.hasWeirdWrap()) { // scroll up if at bottom // note: // on rxvt cywgin terminal.getHeight() is incorrect // MacOs xterm does not seem to support scrolling if (getCurrentAnsiRow() == terminal.getHeight()) { printAnsiSequence((newLine - oldLine) + "S"); } } printAnsiSequence((newLine - oldLine) + "B"); } printAnsiSequence(1 +(cursor % width) + "G"); } // flush(); return; } char c; if (where < 0) { int len = 0; for (int i = buf.cursor; i < buf.cursor - where; i++) { if (buf.buffer.charAt(i) == '\t') { len += TAB_WIDTH; } else { len++; } } char chars[] = new char[len]; Arrays.fill(chars, BACKSPACE); out.write(chars); return; } else if (buf.cursor == 0) { return; } else if (mask != null) { c = mask; } else { print(buf.buffer.substring(buf.cursor - where, buf.cursor).toCharArray()); return; } // null character mask: don't output anything if (mask == NULL_MASK) { return; } print(c, Math.abs(where)); } // FIXME: replace() is not used public final boolean replace(final int num, final String replacement) { buf.buffer.replace(buf.cursor - num, buf.cursor, replacement); try { moveCursor(-num); drawBuffer(Math.max(0, num - replacement.length())); moveCursor(replacement.length()); } catch (IOException e) { e.printStackTrace(); return false; } return true; } // // Key reading // /** * Read a character from the console. * * @return the character, or -1 if an EOF is received. */ public final int readVirtualKey() throws IOException { int c = terminal.readVirtualKey(in); Log.trace("Keystroke: ", c); // clear any echo characters clearEcho(c); return c; } /** * Clear the echoed characters for the specified character code. */ private int clearEcho(final int c) throws IOException { // if the terminal is not echoing, then ignore if (!terminal.isEchoEnabled()) { return 0; } // otherwise, clear int num = countEchoCharacters((char) c); back(num); drawBuffer(num); return num; } private int countEchoCharacters(final char c) { // tabs as special: we need to determine the number of spaces // to cancel based on what out current cursor position is if (c == 9) { int tabStop = 8; // will this ever be different? int position = getCursorPosition(); return tabStop - (position % tabStop); } return getPrintableCharacters(c).length(); } /** * Return the number of characters that will be printed when the specified * character is echoed to the screen * * Adapted from cat by Torbjorn Granlund, as repeated in stty by David MacKenzie. */ private StringBuilder getPrintableCharacters(final char ch) { StringBuilder sbuff = new StringBuilder(); if (ch >= 32) { if (ch < 127) { sbuff.append(ch); } else if (ch == 127) { sbuff.append('^'); sbuff.append('?'); } else { sbuff.append('M'); sbuff.append('-'); if (ch >= (128 + 32)) { if (ch < (128 + 127)) { sbuff.append((char) (ch - 128)); } else { sbuff.append('^'); sbuff.append('?'); } } else { sbuff.append('^'); sbuff.append((char) (ch - 128 + 64)); } } } else { sbuff.append('^'); sbuff.append((char) (ch + 64)); } return sbuff; } public final int readCharacter(final char... allowed) throws IOException { // if we restrict to a limited set and the current character is not in the set, then try again. char c; Arrays.sort(allowed); // always need to sort before binarySearch while (Arrays.binarySearch(allowed, c = (char) readVirtualKey()) < 0) { // nothing } return c; } // // Key Bindings // public static final String JLINE_COMPLETION_THRESHOLD = "jline.completion.threshold"; public static final String JLINE_KEYBINDINGS = "jline.keybindings"; public static final String JLINEBINDINGS_PROPERTIES = ".jlinebindings.properties"; /** * The map for logical operations. */ private final short[] keyBindings; private short[] loadKeyBindings(InputStream input) throws IOException { if (input == null) { try { File file = new File(Configuration.getUserHome(), JLINEBINDINGS_PROPERTIES); String path = Configuration.getString(JLINE_KEYBINDINGS); if (path != null) { file = new File(path); } if (file.isFile()) { Log.debug("Loading user bindings from: ", file); input = new FileInputStream(file); } } catch (Exception e) { Log.error("Failed to load user bindings", e); } } if (input == null) { Log.debug("Using default bindings"); input = getTerminal().getDefaultBindings(); } short[] keyBindings = new short[Character.MAX_VALUE * 2]; Arrays.fill(keyBindings, Operation.UNKNOWN.code); // Loads the key bindings. Bindings file is in the format: // // keycode: operation name if (input != null) { input = new BufferedInputStream(input); Properties p = new Properties(); p.load(input); input.close(); for (Object key : p.keySet()) { String val = (String) key; try { short code = Short.parseShort(val); String name = p.getProperty(val); Operation op = Operation.valueOf(name); keyBindings[code] = op.code; } catch (NumberFormatException e) { Log.error("Failed to convert binding code: ", val, e); } } // hardwired arrow key bindings // keybindings[VK_UP] = PREV_HISTORY; // keybindings[VK_DOWN] = NEXT_HISTORY; // keybindings[VK_LEFT] = PREV_CHAR; // keybindings[VK_RIGHT] = NEXT_CHAR; } return keyBindings; } int getKeyForAction(final short logicalAction) { for (int i = 0; i < keyBindings.length; i++) { if (keyBindings[i] == logicalAction) { return i; } } return -1; } int getKeyForAction(final Operation op) { assert op != null; return getKeyForAction(op.code); } /** * Reads the console input and returns an array of the form [raw, key binding]. */ private int[] readBinding() throws IOException { int c = readVirtualKey(); if (c == -1) { return null; } // extract the appropriate key binding short code = keyBindings[c]; Log.trace("Translated: ", c, " -> ", code); return new int[]{c, code}; } // // Line Reading // /** * Read the next line and return the contents of the buffer. */ public String readLine() throws IOException { return readLine((String) null); } /** * Read the next line with the specified character mask. If null, then * characters will be echoed. If 0, then no characters will be echoed. */ public String readLine(final Character mask) throws IOException { return readLine(null, mask); } public String readLine(final String prompt) throws IOException { return readLine(prompt, null); } /** * Read a line from the <i>in</i> {@link InputStream}, and return the line * (without any trailing newlines). * * @param prompt The prompt to issue to the console, may be null. * @return A line that is read from the terminal, or null if there was null input (e.g., <i>CTRL-D</i> * was pressed). */ public String readLine(String prompt, final Character mask) throws IOException { // prompt may be null // mask may be null // FIXME: This blows, each call to readLine will reset the console's state which doesn't seem very nice. this.mask = mask; if (prompt != null) { setPrompt(prompt); } else { prompt = getPrompt(); } try { if (!terminal.isSupported()) { beforeReadLine(prompt, mask); } if (prompt != null && prompt.length() > 0) { out.write(prompt); out.flush(); } // if the terminal is unsupported, just use plain-java reading if (!terminal.isSupported()) { return readLine(in); } String originalPrompt = this.prompt; final int NORMAL = 1; final int SEARCH = 2; int state = NORMAL; boolean success = true; while (true) { int[] next = readBinding(); if (next == null) { return null; } int c = next[0]; // int code = next[1]; Operation code = Operation.valueOf(next[1]); if (c == -1) { return null; } // Search mode. // // Note that we have to do this first, because if there is a command // not linked to a search command, we leave the search mode and fall // through to the normal state. if (state == SEARCH) { int cursorDest = -1; switch (code) { // This doesn't work right now, it seems CTRL-G is not passed // down correctly. :( case ABORT: state = NORMAL; break; case SEARCH_PREV: if (searchTerm.length() == 0) { searchTerm.append(previousSearchTerm); } if (searchIndex == -1) { searchIndex = searchBackwards(searchTerm.toString()); } else { searchIndex = searchBackwards(searchTerm.toString(), searchIndex); } break; case DELETE_PREV_CHAR: if (searchTerm.length() > 0) { searchTerm.deleteCharAt(searchTerm.length() - 1); searchIndex = searchBackwards(searchTerm.toString()); } break; case UNKNOWN: searchTerm.appendCodePoint(c); searchIndex = searchBackwards(searchTerm.toString()); break; default: // Set buffer and cursor position to the found string. if (searchIndex != -1) { history.moveTo(searchIndex); // set cursor position to the found string cursorDest = history.current().toString().indexOf(searchTerm.toString()); } state = NORMAL; break; } // if we're still in search mode, print the search status if (state == SEARCH) { if (searchTerm.length() == 0) { printSearchStatus("", ""); searchIndex = -1; } else { if (searchIndex == -1) { beep(); } else { printSearchStatus(searchTerm.toString(), history.get(searchIndex).toString()); } } } // otherwise, restore the line else { restoreLine(originalPrompt, cursorDest); } } if (state == NORMAL) { switch (code) { case EXIT: // ctrl-d if (buf.buffer.length() == 0) { return null; } else { deleteCurrentCharacter(); } break; case COMPLETE: // tab success = complete(); break; case MOVE_TO_BEG: success = setCursorPosition(0); break; case KILL_LINE: // CTRL-K success = killLine(); break; case CLEAR_SCREEN: // CTRL-L success = clearScreen(); break; case KILL_LINE_PREV: // CTRL-U success = resetLine(); break; case NEWLINE: // enter moveToEnd(); println(); // output newline flush(); return finishBuffer(); case DELETE_PREV_CHAR: // backspace success = backspace(); break; case DELETE_NEXT_CHAR: // delete success = deleteCurrentCharacter(); break; case MOVE_TO_END: success = moveToEnd(); break; case PREV_CHAR: success = moveCursor(-1) != 0; break; case NEXT_CHAR: success = moveCursor(1) != 0; break; case NEXT_HISTORY: success = moveHistory(true); break; case PREV_HISTORY: success = moveHistory(false); break; case ABORT: case REDISPLAY: break; case PASTE: success = paste(); break; case DELETE_PREV_WORD: success = deletePreviousWord(); break; case PREV_WORD: success = previousWord(); break; case NEXT_WORD: success = nextWord(); break; case START_OF_HISTORY: success = history.moveToFirst(); if (success) { setBuffer(history.current()); } break; case END_OF_HISTORY: success = history.moveToLast(); if (success) { setBuffer(history.current()); } break; case CLEAR_LINE: moveInternal(-(buf.cursor)); killLine(); break; case INSERT: buf.setOverTyping(!buf.isOverTyping()); break; case SEARCH_PREV: // CTRL-R if (searchTerm != null) { previousSearchTerm = searchTerm.toString(); } searchTerm = new StringBuffer(buf.buffer); state = SEARCH; if (searchTerm.length() > 0) { searchIndex = searchBackwards(searchTerm.toString()); if (searchIndex == -1) { beep(); } printSearchStatus(searchTerm.toString(), searchIndex > -1 ? history.get(searchIndex).toString() : ""); } else { searchIndex = -1; printSearchStatus("", ""); } break; case UNKNOWN: default: if (c != 0) { // ignore null chars ActionListener action = triggeredActions.get((char) c); if (action != null) { action.actionPerformed(null); } else { putChar(c, true); } } else { success = false; } } if (!success) { beep(); } flush(); } } } finally { if (!terminal.isSupported()) { afterReadLine(); } } } /** * Read a line for unsupported terminals. */ private String readLine(final InputStream in) throws IOException { StringBuilder buff = new StringBuilder(); while (true) { int i = in.read(); if (i == -1 || i == '\n' || i == '\r') { return buff.toString(); } buff.append((char) i); } // return new BufferedReader (new InputStreamReader (in)).readLine (); } // // Completion // private final List<Completer> completers = new LinkedList<Completer>(); private CompletionHandler completionHandler = new CandidateListCompletionHandler(); /** * Add the specified {@link jline.console.completer.Completer} to the list of handlers for tab-completion. * * @param completer the {@link jline.console.completer.Completer} to add * @return true if it was successfully added */ public boolean addCompleter(final Completer completer) { return completers.add(completer); } /** * Remove the specified {@link jline.console.completer.Completer} from the list of handlers for tab-completion. * * @param completer The {@link Completer} to remove * @return True if it was successfully removed */ public boolean removeCompleter(final Completer completer) { return completers.remove(completer); } /** * Returns an unmodifiable list of all the completers. */ public Collection<Completer> getCompleters() { return Collections.unmodifiableList(completers); } public void setCompletionHandler(final CompletionHandler handler) { assert handler != null; this.completionHandler = handler; } public CompletionHandler getCompletionHandler() { return this.completionHandler; } /** * Use the completers to modify the buffer with the appropriate completions. * * @return true if successful */ private boolean complete() throws IOException { // debug ("tab for (" + buf + ")"); if (completers.size() == 0) { return false; } List<CharSequence> candidates = new LinkedList<CharSequence>(); String bufstr = buf.buffer.toString(); int cursor = buf.cursor; int position = -1; for (Completer comp : completers) { if ((position = comp.complete(bufstr, cursor, candidates)) != -1) { break; } } return candidates.size() != 0 && getCompletionHandler().complete(this, candidates, position); } /** * The number of tab-completion candidates above which a warning will be * prompted before showing all the candidates. */ private int autoprintThreshold = Integer.getInteger(JLINE_COMPLETION_THRESHOLD, 100); // same default as bash /** * @param threshold the number of candidates to print without issuing a warning. */ public void setAutoprintThreshold(final int threshold) { this.autoprintThreshold = threshold; } /** * @return the number of candidates to print without issuing a warning. */ public int getAutoprintThreshold() { return autoprintThreshold; } private boolean paginationEnabled; /** * Whether to use pagination when the number of rows of candidates exceeds the height of the terminal. */ public void setPaginationEnabled(final boolean enabled) { this.paginationEnabled = enabled; } /** * Whether to use pagination when the number of rows of candidates exceeds the height of the terminal. */ public boolean isPaginationEnabled() { return paginationEnabled; } // // History // private History history = new MemoryHistory(); public void setHistory(final History history) { this.history = history; } public History getHistory() { return history; } private boolean historyEnabled = true; /** * Whether or not to add new commands to the history buffer. */ public void setHistoryEnabled(final boolean enabled) { this.historyEnabled = enabled; } /** * Whether or not to add new commands to the history buffer. */ public boolean isHistoryEnabled() { return historyEnabled; } /** * Move up or down the history tree. */ private boolean moveHistory(final boolean next) throws IOException { if (next && !history.next()) { return false; } else if (!next && !history.previous()) { return false; } setBuffer(history.current()); return true; } // // Printing // public static final String CR = System.getProperty("line.separator"); /** * Output the specified character to the output stream without manipulating the current buffer. */ private void print(final int c) throws IOException { if (c == '\t') { char chars[] = new char[TAB_WIDTH]; Arrays.fill(chars, ' '); out.write(chars); return; } out.write(c); } /** * Output the specified characters to the output stream without manipulating the current buffer. */ private void print(final char... buff) throws IOException { int len = 0; for (char c : buff) { if (c == '\t') { len += TAB_WIDTH; } else { len++; } } char chars[]; if (len == buff.length) { chars = buff; } else { chars = new char[len]; int pos = 0; for (char c : buff) { if (c == '\t') { Arrays.fill(chars, pos, pos + TAB_WIDTH, ' '); pos += TAB_WIDTH; } else { chars[pos] = c; pos++; } } } out.write(chars); } private void print(final char c, final int num) throws IOException { if (num == 1) { print(c); } else { char[] chars = new char[num]; Arrays.fill(chars, c); print(chars); } } /** * Output the specified string to the output stream (but not the buffer). */ public final void print(final CharSequence s) throws IOException { assert s != null; print(s.toString().toCharArray()); } public final void println(final CharSequence s) throws IOException { assert s != null; print(s.toString().toCharArray()); println(); } /** * Output a platform-dependant newline. */ public final void println() throws IOException { print(CR); // flush(); } // // Actions // /** * Issue a delete. * * @return true if successful */ public final boolean delete() throws IOException { return delete(1) == 1; } // FIXME: delete(int) only used by above + the return is always 1 and num is ignored /** * Issue <em>num</em> deletes. * * @return the number of characters backed up */ private int delete(final int num) throws IOException { // TODO: Try to use jansi for this /* Commented out because of DWA-2949: if (buf.cursor == 0) { return 0; } */ buf.buffer.delete(buf.cursor, buf.cursor + 1); drawBuffer(1); return 1; } /** * Kill the buffer ahead of the current cursor position. * * @return true if successful */ public boolean killLine() throws IOException { int cp = buf.cursor; int len = buf.buffer.length(); if (cp >= len) { return false; } int num = buf.buffer.length() - cp; clearAhead(num, 0); for (int i = 0; i < num; i++) { buf.buffer.deleteCharAt(len - i - 1); } return true; } /** * Clear the screen by issuing the ANSI "clear screen" code. */ public boolean clearScreen() throws IOException { if (!terminal.isAnsiSupported()) { return false; } // send the ANSI code to clear the screen printAnsiSequence("2J"); // then send the ANSI code to go to position 1,1 printAnsiSequence("1;1H"); redrawLine(); return true; } /** * Issue an audible keyboard bell, if {@link #isBellEnabled} return true. */ public void beep() throws IOException { if (isBellEnabled()) { print(KEYBOARD_BELL); // need to flush so the console actually beeps flush(); } } /** * Paste the contents of the clipboard into the console buffer * * @return true if clipboard contents pasted */ public boolean paste() throws IOException { Clipboard clipboard; try { // May throw ugly exception on system without X clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); } catch (Exception e) { return false; } if (clipboard == null) { return false; } Transferable transferable = clipboard.getContents(null); if (transferable == null) { return false; } try { Object content = transferable.getTransferData(DataFlavor.plainTextFlavor); // This fix was suggested in bug #1060649 at // http://sourceforge.net/tracker/index.php?func=detail&aid=1060649&group_id=64033&atid=506056 // to get around the deprecated DataFlavor.plainTextFlavor, but it // raises a UnsupportedFlavorException on Mac OS X if (content == null) { try { content = new DataFlavor().getReaderForText(transferable); } catch (Exception e) { // ignore } } if (content == null) { return false; } String value; if (content instanceof Reader) { // TODO: we might want instead connect to the input stream // so we can interpret individual lines value = ""; String line; BufferedReader read = new BufferedReader((Reader) content); while ((line = read.readLine()) != null) { if (value.length() > 0) { value += "\n"; } value += line; } } else { value = content.toString(); } if (value == null) { return true; } putString(value); return true; } catch (UnsupportedFlavorException e) { Log.error("Paste failed: ", e); return false; } } // // Triggered Actions // private final Map<Character, ActionListener> triggeredActions = new HashMap<Character, ActionListener>(); /** * Adding a triggered Action allows to give another curse of action if a character passed the pre-processing. * <p/> * Say you want to close the application if the user enter q. * addTriggerAction('q', new ActionListener(){ System.exit(0); }); would do the trick. */ public void addTriggeredAction(final char c, final ActionListener listener) { triggeredActions.put(c, listener); } // // Formatted Output // /** * Output the specified {@link Collection} in proper columns. */ public void printColumns(final Collection<? extends CharSequence> items) throws IOException { if (items == null || items.isEmpty()) { return; } int width = getTerminal().getWidth(); int height = getTerminal().getHeight(); int maxWidth = 0; for (CharSequence item : items) { maxWidth = Math.max(maxWidth, item.length()); } Log.debug("Max width: ", maxWidth); int showLines; if (isPaginationEnabled()) { showLines = height - 1; // page limit } else { showLines = Integer.MAX_VALUE; } StringBuilder buff = new StringBuilder(); for (CharSequence item : items) { if ((buff.length() + maxWidth) > width) { println(buff); buff.setLength(0); if (--showLines == 0) { // Overflow print(resources.getString("display-more")); flush(); int c = readVirtualKey(); if (c == '\r' || c == '\n') { // one step forward showLines = 1; } else if (c != 'q') { // page forward showLines = height - 1; } back(resources.getString("display-more").length()); if (c == 'q') { // cancel break; } } } // NOTE: toString() is important here due to AnsiString being retarded buff.append(item.toString()); for (int i = 0; i < (maxWidth + 3 - item.length()); i++) { buff.append(' '); } } if (buff.length() > 0) { println(buff); } } // // Non-supported Terminal Support // private Thread maskThread; private void beforeReadLine(final String prompt, final Character mask) { if (mask != null && maskThread == null) { final String fullPrompt = "\r" + prompt + " " + " " + " " + "\r" + prompt; maskThread = new Thread() { public void run() { while (!interrupted()) { try { Writer out = getOutput(); out.write(fullPrompt); out.flush(); sleep(3); } catch (IOException e) { return; } catch (InterruptedException e) { return; } } } }; maskThread.setPriority(Thread.MAX_PRIORITY); maskThread.setDaemon(true); maskThread.start(); } } private void afterReadLine() { if (maskThread != null && maskThread.isAlive()) { maskThread.interrupt(); } maskThread = null; } /** * Erases the current line with the existing prompt, then redraws the line * with the provided prompt and buffer * @param prompt * the new prompt * @param buffer * the buffer to be drawn * @param cursorDest * where you want the cursor set when the line has been drawn. * -1 for end of line. * */ public void resetPromptLine(String prompt, String buffer, int cursorDest) throws IOException { // move cursor to end of line moveToEnd(); // backspace all text, including prompt buf.buffer.append(this.prompt); buf.cursor += this.prompt.length(); this.prompt = ""; backspaceAll(); this.prompt = prompt; redrawLine(); setBuffer(buffer); // move cursor to destination (-1 will move to end of line) if (cursorDest < 0) cursorDest = buffer.length(); setCursorPosition(cursorDest); flush(); } public void printSearchStatus(String searchTerm, String match) throws IOException { String prompt = "(reverse-i-search)`" + searchTerm + "': "; String buffer = match; int cursorDest = match.indexOf(searchTerm); resetPromptLine(prompt, buffer, cursorDest); } public void restoreLine(String originalPrompt, int cursorDest) throws IOException { // TODO move cursor to matched string String prompt = lastLine(originalPrompt); String buffer = buf.buffer.toString(); resetPromptLine(prompt, buffer, cursorDest); } // // History search // /** * Search backward in history from a given position. * * @param searchTerm substring to search for. * @param startIndex the index from which on to search * @return index where this substring has been found, or -1 else. */ public int searchBackwards(String searchTerm, int startIndex) { return searchBackwards(searchTerm, startIndex, false); } /** * Search backwards in history from the current position. * * @param searchTerm substring to search for. * @return index where the substring has been found, or -1 else. */ public int searchBackwards(String searchTerm) { return searchBackwards(searchTerm, history.index()); } public int searchBackwards(String searchTerm, int startIndex, boolean startsWith) { ListIterator<History.Entry> it = history.entries(startIndex); while (it.hasPrevious()) { History.Entry e = it.previous(); if (startsWith) { if (e.value().toString().startsWith(searchTerm)) { return e.index(); } } else { if (e.value().toString().contains(searchTerm)) { return e.index(); } } } return -1; } // // Helpers // /** * Checks to see if the specified character is a delimiter. We consider a * character a delimiter if it is anything but a letter or digit. * * @param c The character to test * @return True if it is a delimiter */ private boolean isDelimiter(final char c) { return !Character.isLetterOrDigit(c); } private void printAnsiSequence(String sequence) throws IOException { print(27); print('['); print(sequence); flush(); // helps with step debugging } // return column position, reported by the terminal private int getCurrentPosition() { // check for ByteArrayInputStream to disable for unit tests if (terminal.isAnsiSupported() && !(in instanceof ByteArrayInputStream)) { try { printAnsiSequence("6n"); flush(); StringBuffer b = new StringBuffer(8); // position is sent as <ESC>[{ROW};{COLUMN}R int r; while((r = in.read()) > -1 && r != 'R') { if (r != 27 && r != '[') { b.append((char) r); } } String[] pos = b.toString().split(";"); return Integer.parseInt(pos[1]); } catch (Exception x) { // no luck } } return -1; // TODO: throw exception instead? } // return row position, reported by the terminal // needed to know whether to scroll up on cursor move in last col for weird // wrapping terminals - not tested for anything else private int getCurrentAnsiRow() { // check for ByteArrayInputStream to disable for unit tests if (terminal.isAnsiSupported() && !(in instanceof ByteArrayInputStream)) { try { printAnsiSequence("6n"); flush(); StringBuffer b = new StringBuffer(8); // position is sent as <ESC>[{ROW};{COLUMN}R int r; while((r = in.read()) > -1 && r != 'R') { if (r != 27 && r != '[') { b.append((char) r); } } String[] pos = b.toString().split(";"); return Integer.parseInt(pos[0]); } catch (Exception x) { // no luck } } return -1; // TODO: throw exception instead? } }
Deprivatized complete() for similar reasons.
src/main/java/jline/console/ConsoleReader.java
Deprivatized complete() for similar reasons.
Java
mit
3c252ffe70c59fe3a2d08c98ef638120cdafb609
0
Indemnity83/Schematica,CannibalVox/Schematica
package com.github.lunatrius.schematica.handler; import com.github.lunatrius.schematica.reference.Names; import com.github.lunatrius.schematica.reference.Reference; import com.github.lunatrius.schematica.world.chunk.SchematicContainer; import com.github.lunatrius.schematica.world.schematic.SchematicFormat; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.gameevent.TickEvent; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityClientPlayerMP; import net.minecraft.util.ChatComponentTranslation; import java.util.ArrayDeque; import java.util.Queue; public class QueueTickHandler { public static final QueueTickHandler INSTANCE = new QueueTickHandler(); private final Queue<SchematicContainer> queue = new ArrayDeque<SchematicContainer>(); private QueueTickHandler() {} @SubscribeEvent public void onClientTick(TickEvent.ClientTickEvent event) { if (event.phase == TickEvent.Phase.START) { return; } // TODO: find a better way... maybe? try { final EntityClientPlayerMP player = Minecraft.getMinecraft().thePlayer; if (player != null && !player.sendQueue.getNetworkManager().isLocalChannel()) { processQueue(); } } catch (Exception e) { Reference.logger.error("Something went wrong...", e); } } @SubscribeEvent public void onServerTick(TickEvent.ServerTickEvent event) { if (event.phase == TickEvent.Phase.START) { return; } processQueue(); } private void processQueue() { if (this.queue.size() == 0) { return; } final SchematicContainer container = this.queue.poll(); if (container == null) { return; } if (container.hasNext()) { if (container.isFirst()) { final ChatComponentTranslation chatComponent = new ChatComponentTranslation(Names.Command.Save.Message.SAVE_STARTED, container.chunkCount, container.file.getName()); container.player.addChatMessage(chatComponent); } container.next(); } if (container.hasNext()) { this.queue.offer(container); } else { final boolean success = SchematicFormat.writeToFile(container.file, container.schematic); final String message = success ? Names.Command.Save.Message.SAVE_SUCCESSFUL : Names.Command.Save.Message.SAVE_FAILED; container.player.addChatMessage(new ChatComponentTranslation(message, container.file.getName())); } } public void queueSchematic(SchematicContainer container) { this.queue.offer(container); } }
src/main/java/com/github/lunatrius/schematica/handler/QueueTickHandler.java
package com.github.lunatrius.schematica.handler; import com.github.lunatrius.schematica.reference.Names; import com.github.lunatrius.schematica.world.chunk.SchematicContainer; import com.github.lunatrius.schematica.world.schematic.SchematicFormat; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.gameevent.TickEvent; import net.minecraft.util.ChatComponentTranslation; import java.util.ArrayDeque; import java.util.Queue; public class QueueTickHandler { public static final QueueTickHandler INSTANCE = new QueueTickHandler(); private final Queue<SchematicContainer> queue = new ArrayDeque<SchematicContainer>(); private QueueTickHandler() {} @SubscribeEvent public void onServerTick(TickEvent.ServerTickEvent event) { if (this.queue.size() == 0) { return; } final SchematicContainer container = this.queue.poll(); if (container == null) { return; } if (container.hasNext()) { if (container.isFirst()) { final ChatComponentTranslation chatComponent = new ChatComponentTranslation(Names.Command.Save.Message.SAVE_STARTED, container.chunkCount, container.file.getName()); container.player.addChatMessage(chatComponent); } container.next(); } if (container.hasNext()) { this.queue.offer(container); } else { final boolean success = SchematicFormat.writeToFile(container.file, container.schematic); final String message = success ? Names.Command.Save.Message.SAVE_SUCCESSFUL : Names.Command.Save.Message.SAVE_FAILED; container.player.addChatMessage(new ChatComponentTranslation(message, container.file.getName())); } } public void queueSchematic(SchematicContainer container) { this.queue.offer(container); } }
Temporary fix for saving schematics on servers.
src/main/java/com/github/lunatrius/schematica/handler/QueueTickHandler.java
Temporary fix for saving schematics on servers.
Java
mit
d72845a4fe5434489281cc9fc7df33e86bdbad31
0
brianjd/react-native-navigation,uni-react/react-native-navigation,yusufyildirim/react-native-navigation,chicojasl/react-native-navigation,lakhman/react-native-navigation,varungupta85/react-native-navigation,MattDavies/react-native-navigation,MediaMonksMobile/react-native-navigation,ceyhuno/react-native-navigation,thanhzusu/react-native-navigation,3sidedcube/react-native-navigation,snapme/react-native-navigation,shahen94/react-native-navigation,InTeach/react-native-navigation,eeynard/react-native-navigation,Jpoliachik/react-native-navigation,shahen94/react-native-navigation,lkj01010/react-native-navigation,Jpoliachik/react-native-navigation,kristoff-it/react-native-navigation,brianjd/react-native-navigation,thanhzusu/react-native-navigation,pqkluan/react-native-navigation,inalist/react-native-navigation,InTeach/react-native-navigation,wix/react-native-navigation,guangmingzizai/react-native-navigation,iotize/react-native-navigation,chicojasl/react-native-navigation,BrendonSled/react-native-navigation,MattDavies/react-native-navigation,3sidedcube/react-native-navigation,uni-react/react-native-navigation,Ehesp/react-native-navigation,inalist/react-native-navigation,MattDavies/react-native-navigation,guangmingzizai/react-native-navigation,kristoff-it/react-native-navigation,brianjd/react-native-navigation,junedomingo/react-native-navigation,guyca/react-native-navigation,ceyhuno/react-native-navigation,guangmingzizai/react-native-navigation,MediaMonksMobile/react-native-navigation,uni-react/react-native-navigation,pqkluan/react-native-navigation,guyca/react-native-navigation,thanhzusu/react-native-navigation,wix/react-native-navigation,3sidedcube/react-native-navigation,wix/react-native-navigation,shahen94/react-native-navigation,wix/react-native-navigation,lakhman/react-native-navigation,lkj01010/react-native-navigation,ceyhuno/react-native-navigation,inalist/react-native-navigation,chicojasl/react-native-navigation,ceyhuno/react-native-navigation,Jpoliachik/react-native-navigation,snapme/react-native-navigation,brianjd/react-native-navigation,iotize/react-native-navigation,Jpoliachik/react-native-navigation,eeynard/react-native-navigation,holmesal/react-native-navigation,lakhman/react-native-navigation,eeynard/react-native-navigation,wix/react-native-navigation,okarakose/react-native-navigation,junedomingo/react-native-navigation,Ehesp/react-native-navigation,iotize/react-native-navigation,lkj01010/react-native-navigation,MediaMonksMobile/react-native-navigation,kristoff-it/react-native-navigation,Jpoliachik/react-native-navigation,coteries/react-native-navigation,varungupta85/react-native-navigation,guyca/react-native-navigation,shahen94/react-native-navigation,Jpoliachik/react-native-navigation,brianjd/react-native-navigation,thanhzusu/react-native-navigation,brianjd/react-native-navigation,BrendonSled/react-native-navigation,luggit/react-native-navigation,3sidedcube/react-native-navigation,wix/react-native-navigation,holmesal/react-native-navigation,BrendonSled/react-native-navigation,inalist/react-native-navigation,yusufyildirim/react-native-navigation,thanhzusu/react-native-navigation,varungupta85/react-native-navigation,MattDavies/react-native-navigation,guyca/react-native-navigation,holmesal/react-native-navigation,thanhzusu/react-native-navigation,kristoff-it/react-native-navigation,iotize/react-native-navigation,chicojasl/react-native-navigation,Ehesp/react-native-navigation,eeynard/react-native-navigation,lakhman/react-native-navigation,junedomingo/react-native-navigation,uni-react/react-native-navigation,ceyhuno/react-native-navigation,okarakose/react-native-navigation,luggit/react-native-navigation,snapme/react-native-navigation,junedomingo/react-native-navigation,chicojasl/react-native-navigation,ceyhuno/react-native-navigation,coteries/react-native-navigation,InTeach/react-native-navigation,coteries/react-native-navigation,InTeach/react-native-navigation,okarakose/react-native-navigation,snapme/react-native-navigation,yusufyildirim/react-native-navigation,coteries/react-native-navigation,yusufyildirim/react-native-navigation,okarakose/react-native-navigation,varungupta85/react-native-navigation,luggit/react-native-navigation,pqkluan/react-native-navigation,guangmingzizai/react-native-navigation,chicojasl/react-native-navigation,holmesal/react-native-navigation,pqkluan/react-native-navigation,MediaMonksMobile/react-native-navigation,luggit/react-native-navigation,BrendonSled/react-native-navigation,Ehesp/react-native-navigation
package com.reactnativenavigation.events; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.List; import java.util.ListIterator; public enum EventBus { instance; private final List<WeakReference<Subscriber>> subscribers = new ArrayList<>(); public void register(Subscriber subscriber) { if (isSubscribed(subscriber)) return; subscribers.add(new WeakReference<>(subscriber)); } public void unregister(Subscriber subscriber) { ListIterator<WeakReference<Subscriber>> iterator = subscribers.listIterator(); while (iterator.hasNext()) { WeakReference<Subscriber> ref = iterator.next(); Subscriber registered = ref.get(); if (registered != null && registered == subscriber) { iterator.remove(); } } } public void post(Event event) { ListIterator<WeakReference<Subscriber>> iterator = subscribers.listIterator(); while (iterator.hasNext()) { WeakReference<Subscriber> ref = iterator.next(); Subscriber registered = ref.get(); if (registered != null) { registered.onEvent(event); } } } public boolean isSubscribed(Subscriber subscriber) { for (WeakReference<Subscriber> ref : subscribers) { Subscriber registered = ref.get(); if (registered != null && registered.equals(subscriber)) { return true; } } return false; } }
android/app/src/main/java/com/reactnativenavigation/events/EventBus.java
package com.reactnativenavigation.events; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.List; import java.util.ListIterator; public enum EventBus { instance; private final List<WeakReference<Subscriber>> subscribers = new ArrayList<>(); public void register(Subscriber subscriber) { if (isSubscribed(subscriber)) return; subscribers.add(new WeakReference<>(subscriber)); } public void unregister(Subscriber subscriber) { ListIterator<WeakReference<Subscriber>> iterator = subscribers.listIterator(); while (iterator.hasNext()) { WeakReference<Subscriber> ref = iterator.next(); Subscriber registered = ref.get(); if (registered != null && registered == subscriber) { iterator.remove(); } } } public void post(Event event) { for (WeakReference<Subscriber> ref : subscribers) { Subscriber registered = ref.get(); if (registered != null) { registered.onEvent(event); } } } public boolean isSubscribed(Subscriber subscriber) { for (WeakReference<Subscriber> ref : subscribers) { Subscriber registered = ref.get(); if (registered != null && registered.equals(subscriber)) { return true; } } return false; } }
Fix concurrent modification exception
android/app/src/main/java/com/reactnativenavigation/events/EventBus.java
Fix concurrent modification exception
Java
mit
error: pathspec 'MinimumAverageWaitingTime.java' did not match any file(s) known to git
4ab7bfe4d0ffe0925cd8a8b7fdf195d1057fb8bc
1
Nilzone-/HackerRank-Challenges
import java.io.*; import java.util.*; import java.text.*; import java.math.*; class Solution { public static void main(String[] args) { Scanner s = new Scanner(System.in); int orders = s.nextInt(); PizzaShop ps = new PizzaShop(orders); while(orders-- > 0) { ps.addOrder(s.nextLong(), s.nextLong()); } System.out.println(ps.calculateMinimumAverageWaitingTime()); } } class PizzaShop { private int orders; private Queue<Order> arrivalQueue; private Queue<Order> cookingQueue; PizzaShop(int orders) { this.orders = orders; this.arrivalQueue = new PriorityQueue<>(orders, new Comparator<Order>() { public int compare(Order o1, Order o2) { return (o1.arrivalTime < o2.arrivalTime) ? -1 : (o1.arrivalTime == o2.arrivalTime) ? 0 : 1; } }); this.cookingQueue = new PriorityQueue<>(orders, new Comparator<Order>() { public int compare(Order o1, Order o2) { return (o1.cookTime < o2.cookTime) ? -1 : (o1.cookTime == o2.cookTime) ? 0 : 1; } }); } public void addOrder(long arrivalTime, long cookTime) { arrivalQueue.add(new Order(arrivalTime, cookTime)); } public long calculateMinimumAverageWaitingTime() { long time = arrivalQueue.peek().arrivalTime; long waitTime = 0; Order current = null; while(!arrivalQueue.isEmpty() || !cookingQueue.isEmpty()) { if(!arrivalQueue.isEmpty()) { while(arrivalQueue.peek() != null && time >= arrivalQueue.peek().arrivalTime) { current = arrivalQueue.remove(); cookingQueue.add(current); } } if(!cookingQueue.isEmpty()) { if(time >= cookingQueue.peek().arrivalTime) { current = cookingQueue.remove(); time += current.cookTime; current.completionTime = time; waitTime += (current.completionTime - current.arrivalTime); continue; } } time++; } return waitTime / orders; } private static class Order { public long arrivalTime; public long cookTime; public long completionTime; Order(long arrivalTime, long cookTime) { this.arrivalTime = arrivalTime; this.cookTime = cookTime; } } }
MinimumAverageWaitingTime.java
Initial commit
MinimumAverageWaitingTime.java
Initial commit
Java
mit
error: pathspec 'src/sorting/types/BubbleSort.java' did not match any file(s) known to git
ef09b6f6b5704f1feed76a8d2aad4809895c133c
1
fran93/ImplementingSortingTypes
package sorting.types; import sorting.utils.SortingUtils; /** * * @author fran */ public class BubbleSort { /** * @param args the command line arguments */ public static void main(String[] args) { //example array int [] integerArray = new int []{3,11,2,9,1,5,5}; boolean end = false; boolean noChanges; //the loop will end, when the array dont change anymore while(!end){ noChanges = true; for(int i=1;i<integerArray.length;i++){ if(integerArray[i]<integerArray[i-1]){ noChanges = false; //store the numbers int a = integerArray[i-1]; int b = integerArray[i]; //change his positions integerArray[i] = a; integerArray[i-1] = b; }; } end = noChanges; } SortingUtils.printArray(integerArray); } }
src/sorting/types/BubbleSort.java
Bubble Sort implemented
src/sorting/types/BubbleSort.java
Bubble Sort implemented
Java
mit
error: pathspec 'src/main/java/leetcode/Problem41.java' did not match any file(s) known to git
42fb635266cfbb42b07705ca9885205fbe0637bb
1
fredyw/leetcode,fredyw/leetcode,fredyw/leetcode,fredyw/leetcode
package leetcode; /** * https://leetcode.com/problems/first-missing-positive/ */ public class Problem41 { public int firstMissingPositive(int[] nums) { // TODO return 0; } public static void main(String[] args) { Problem41 prob = new Problem41(); System.out.println(prob.firstMissingPositive(new int[]{1, 2, 0})); // 3 System.out.println(prob.firstMissingPositive(new int[]{3, 4, -1, 1})); // 2 } }
src/main/java/leetcode/Problem41.java
Skeleton for problem 41
src/main/java/leetcode/Problem41.java
Skeleton for problem 41
Java
mit
error: pathspec 'src/main/java/coyote/commons/security/PPG.java' did not match any file(s) known to git
62ced4cd66c133439a964a696d8d573c58c846af
1
sdcote/commons
/* * Copyright (c) 2014 Stephan D. Cote' - All rights reserved. * * This program and the accompanying materials are made available under the * terms of the MIT License which accompanies this distribution, and is * available at http://creativecommons.org/licenses/MIT/ * * Contributors: * Stephan D. Cote * - Initial concept and initial implementation */ package coyote.commons.security; import java.util.Random; /** * Class which holds the character distribution data */ class Data { static int triples[][][] = null; static long sigma[] = null; Data() { int a, b, c; triples = new int[26][26][26]; sigma = new long[1]; DataInit1.fill( this ); DataInit2.fill( this ); for ( a = 0; a < 26; a++ ) { for ( b = 0; b < 26; b++ ) { for ( c = 0; c < 26; c++ ) { sigma[0] += triples[a][b][c]; } } } } long get( final int x1, final int x2, final int x3 ) { return triples[x1][x2][x3]; } long getSigma() { return sigma[0]; } void set( final int a, final int b, final int c, final int value ) { triples[a][b][c] = value; } } // Data class class DataInit1 { static final int[][][] tris1 = { { /* A A */{ 2, 0, 3, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 3, 2, 0, 0, 0, 0, 0, 0, 0 }, /* A B */{ 37, 25, 2, 5, 38, 0, 0, 2, 46, 1, 0, 304, 0, 2, 49, 0, 0, 24, 24, 0, 19, 0, 0, 0, 14, 0 }, /* A C */{ 26, 1, 64, 2, 107, 0, 1, 94, 67, 0, 173, 13, 5, 1, 35, 1, 13, 32, 3, 114, 23, 0, 0, 0, 45, 0 }, /* A D */{ 35, 7, 3, 43, 116, 6, 3, 8, 75, 14, 1, 16, 25, 3, 44, 3, 1, 35, 20, 1, 10, 25, 9, 0, 18, 0 }, /* A E */{ 2, 0, 2, 1, 0, 1, 3, 0, 0, 0, 0, 10, 0, 2, 3, 0, 0, 12, 6, 0, 2, 0, 0, 0, 0, 0 }, /* A F */{ 5, 0, 0, 0, 14, 50, 2, 0, 3, 0, 2, 5, 0, 2, 7, 0, 0, 5, 1, 39, 1, 0, 0, 0, 1, 0 }, /* A G */{ 30, 1, 0, 1, 182, 0, 42, 5, 30, 0, 0, 7, 9, 42, 51, 3, 0, 24, 3, 0, 21, 0, 3, 0, 3, 0 }, /* A H */{ 12, 0, 0, 0, 20, 0, 0, 0, 3, 0, 0, 5, 4, 2, 13, 0, 0, 2, 0, 0, 1, 0, 0, 0, 0, 0 }, /* A I */{ 2, 0, 10, 26, 2, 1, 10, 0, 2, 1, 2, 87, 13, 144, 0, 2, 0, 93, 30, 23, 0, 3, 1, 0, 0, 0 }, /* A J */{ 4, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* A K */{ 11, 0, 1, 1, 98, 1, 0, 1, 15, 0, 0, 3, 0, 0, 5, 1, 0, 3, 0, 1, 2, 0, 3, 0, 8, 0 }, /* A L */{ 78, 20, 34, 45, 124, 21, 24, 5, 109, 0, 28, 237, 31, 3, 53, 23, 0, 7, 16, 69, 29, 26, 5, 0, 26, 2 }, /* A M */{ 70, 57, 1, 1, 98, 3, 0, 1, 68, 0, 0, 3, 38, 2, 43, 69, 0, 3, 14, 3, 12, 0, 2, 0, 14, 0 }, /* A N */{ 114, 6, 156, 359, 103, 8, 146, 12, 141, 2, 57, 4, 0, 89, 61, 1, 4, 1, 124, 443, 29, 6, 1, 3, 28, 9 }, /* A O */{ 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 3, 1, 0, 0, 0, 0, 3, 2, 2, 2, 0, 0, 0, 0, 0 }, /* A P */{ 29, 3, 0, 1, 59, 1, 0, 86, 25, 0, 1, 14, 1, 1, 37, 94, 0, 9, 22, 30, 8, 0, 0, 0, 9, 0 }, /* A Q */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 14, 0, 0, 0, 0, 0 }, /* A R */{ 124, 64, 101, 233, 115, 12, 47, 5, 188, 3, 61, 55, 68, 34, 46, 25, 6, 94, 48, 189, 5, 22, 5, 1, 172, 2 }, /* A S */{ 19, 3, 32, 0, 71, 0, 1, 81, 49, 0, 22, 3, 19, 2, 19, 34, 4, 0, 152, 211, 12, 0, 1, 0, 17, 1 }, /* A T */{ 50, 3, 41, 2, 863, 4, 0, 144, 352, 0, 5, 14, 6, 3, 144, 0, 0, 60, 13, 106, 57, 1, 5, 0, 8, 5 }, /* A U */{ 0, 5, 23, 35, 5, 5, 38, 1, 0, 1, 3, 33, 4, 23, 0, 4, 1, 35, 52, 56, 0, 1, 0, 7, 0, 1 }, /* A V */{ 35, 0, 0, 1, 108, 0, 0, 0, 49, 0, 0, 1, 0, 0, 19, 0, 0, 0, 0, 0, 3, 1, 0, 0, 6, 0 }, /* A W */{ 30, 10, 0, 4, 3, 6, 2, 2, 2, 0, 10, 13, 4, 15, 3, 0, 0, 6, 3, 5, 0, 0, 0, 0, 2, 0 }, /* A X */{ 3, 0, 0, 0, 4, 0, 0, 0, 22, 0, 0, 1, 0, 0, 7, 2, 0, 0, 1, 1, 0, 0, 3, 0, 3, 0 }, /* A Y */{ 11, 8, 1, 5, 16, 5, 1, 2, 2, 0, 0, 10, 7, 4, 13, 1, 0, 3, 5, 7, 3, 0, 5, 0, 0, 0 }, /* A Z */{ 10, 0, 0, 1, 22, 0, 0, 0, 10, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 2, 2, 0, 0, 0, 4, 11 } }, /* B A */{ { 0, 17, 74, 11, 1, 2, 19, 4, 8, 0, 10, 68, 7, 73, 1, 7, 0, 110, 54, 55, 9, 1, 3, 1, 12, 1 }, /* B B */{ 7, 0, 0, 0, 16, 0, 0, 0, 10, 0, 0, 24, 0, 0, 9, 0, 0, 2, 3, 0, 2, 0, 0, 0, 14, 0 }, /* B C */{ 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* B D */{ 2, 0, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0, 0, 0, 3, 0, 0, 1, 0, 0, 3, 0, 0, 0, 0, 0 }, /* B E */{ 51, 1, 14, 34, 18, 11, 16, 7, 9, 0, 1, 85, 5, 48, 2, 2, 2, 199, 36, 41, 0, 4, 5, 1, 6, 2 }, /* B F */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0 }, /* B G */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* B H */{ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 }, /* B I */{ 34, 8, 22, 21, 8, 3, 9, 1, 0, 3, 1, 50, 7, 45, 16, 4, 2, 29, 22, 59, 4, 4, 0, 0, 0, 3 }, /* B J */{ 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 }, /* B K */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* B L */{ 57, 0, 0, 0, 519, 0, 0, 0, 35, 0, 0, 0, 0, 0, 47, 0, 0, 0, 0, 0, 32, 1, 0, 0, 3, 0 }, /* B M */{ 0, 0, 0, 0, 1, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 }, /* B N */{ 1, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* B O */{ 62, 7, 4, 21, 3, 2, 9, 3, 8, 1, 1, 46, 8, 63, 58, 2, 0, 55, 15, 20, 46, 6, 17, 10, 19, 0 }, /* B P */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 }, /* B Q */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* B R */{ 110, 0, 0, 0, 77, 0, 0, 0, 100, 0, 0, 0, 0, 0, 78, 0, 0, 0, 0, 0, 28, 0, 0, 0, 10, 0 }, /* B S */{ 0, 0, 6, 0, 16, 0, 0, 0, 7, 0, 0, 0, 0, 0, 12, 0, 0, 0, 0, 27, 2, 0, 0, 0, 0, 0 }, /* B T */{ 1, 0, 0, 0, 3, 1, 0, 0, 0, 0, 0, 4, 0, 0, 1, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0 }, /* B U */{ 0, 3, 21, 16, 3, 5, 14, 0, 12, 1, 2, 52, 7, 20, 2, 0, 1, 104, 44, 54, 0, 0, 0, 3, 1, 5 }, /* B V */{ 0, 0, 0, 0, 3, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* B W */{ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* B X */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* B Y */{ 1, 0, 0, 0, 3, 0, 1, 2, 0, 0, 0, 4, 0, 0, 0, 3, 0, 6, 8, 3, 0, 0, 2, 0, 0, 2 }, /* B Z */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, /* C A */{ { 1, 47, 17, 33, 1, 3, 4, 5, 7, 1, 3, 120, 40, 120, 1, 59, 1, 171, 60, 150, 19, 20, 1, 0, 5, 0 }, /* C B */{ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0 }, /* C C */{ 23, 0, 0, 0, 22, 0, 0, 5, 13, 0, 0, 13, 0, 0, 26, 0, 0, 7, 0, 0, 27, 0, 0, 0, 0, 0 }, /* C D */{ 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* C E */{ 23, 6, 4, 17, 6, 6, 1, 2, 13, 0, 0, 50, 12, 109, 7, 43, 0, 76, 63, 22, 1, 0, 4, 0, 2, 1 }, /* C F */{ 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* C G */{ 0, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 0, 0, 2, 0, 0, 4, 1, 0, 1, 0, 0, 0, 0, 0 }, /* C H */{ 165, 10, 2, 3, 176, 4, 3, 1, 141, 0, 0, 26, 20, 16, 102, 1, 0, 63, 8, 10, 44, 0, 13, 0, 20, 0 }, /* C I */{ 76, 15, 8, 33, 24, 16, 3, 0, 0, 0, 0, 38, 5, 45, 50, 28, 0, 29, 38, 71, 6, 8, 0, 0, 0, 0 }, /* C J */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* C K */{ 17, 16, 2, 3, 90, 4, 1, 7, 20, 1, 1, 45, 8, 8, 12, 9, 0, 3, 32, 6, 6, 0, 13, 0, 22, 0 }, /* C L */{ 95, 0, 0, 0, 84, 0, 0, 0, 50, 0, 0, 0, 0, 0, 54, 0, 0, 0, 0, 0, 34, 0, 0, 0, 3, 0 }, /* C M */{ 1, 0, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 }, /* C N */{ 2, 0, 0, 0, 1, 0, 0, 0, 4, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 }, /* C O */{ 33, 16, 40, 22, 14, 10, 11, 12, 9, 1, 1, 101, 218, 421, 24, 56, 2, 129, 37, 40, 86, 22, 25, 4, 4, 2 }, /* C P */{ 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 }, /* C Q */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 13, 0, 0, 0, 0, 0 }, /* C R */{ 101, 0, 0, 0, 112, 0, 0, 0, 75, 0, 0, 0, 0, 0, 88, 0, 0, 0, 0, 1, 41, 0, 0, 0, 25, 0 }, /* C S */{ 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 1, 2, 0, 0, 0, 1, 2, 0, 0, 0, 0, 0, 0 }, /* C T */{ 44, 0, 0, 0, 12, 2, 0, 0, 113, 0, 0, 0, 2, 0, 94, 0, 0, 46, 0, 0, 42, 0, 1, 0, 3, 0 }, /* C U */{ 3, 12, 2, 6, 6, 6, 0, 0, 8, 0, 0, 102, 42, 10, 9, 15, 0, 72, 51, 41, 1, 0, 0, 0, 0, 0 }, /* C V */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* C W */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* C X */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* C Y */{ 5, 1, 20, 0, 0, 0, 1, 0, 0, 0, 0, 3, 0, 2, 2, 4, 0, 3, 2, 9, 0, 0, 0, 0, 0, 0 }, /* C Z */{ 2, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, /* D A */{ { 0, 7, 16, 7, 1, 2, 13, 6, 18, 0, 3, 54, 23, 59, 0, 10, 0, 31, 6, 40, 8, 13, 3, 0, 32, 3 }, /* D B */{ 9, 0, 0, 0, 7, 0, 0, 0, 3, 0, 0, 2, 0, 0, 8, 0, 0, 1, 0, 0, 8, 0, 0, 0, 2, 0 }, /* D C */{ 5, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 2, 0, 0, 3, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0 }, /* D D */{ 8, 0, 0, 0, 30, 0, 0, 3, 19, 0, 0, 38, 0, 0, 4, 0, 0, 4, 0, 0, 1, 0, 0, 0, 16, 0 }, /* D E */{ 34, 37, 82, 14, 17, 41, 11, 4, 5, 2, 0, 88, 62, 170, 14, 40, 4, 183, 99, 39, 6, 20, 16, 6, 1, 2 }, /* D F */{ 6, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 2, 0, 0, 5, 0, 0, 2, 0, 0, 4, 0, 0, 0, 0, 0 }, /* D G */{ 4, 0, 0, 0, 73, 0, 0, 0, 2, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 2, 0, 1, 0, 3, 0 }, /* D H */{ 8, 0, 0, 0, 9, 0, 0, 0, 4, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* D I */{ 100, 10, 104, 12, 33, 26, 31, 1, 1, 0, 1, 22, 22, 65, 57, 15, 0, 20, 138, 53, 20, 31, 1, 6, 0, 1 }, /* D J */{ 4, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0 }, /* D K */{ 0, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* D L */{ 9, 0, 0, 0, 79, 0, 0, 0, 12, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 1, 0, 0, 0, 3, 0 }, /* D M */{ 13, 0, 0, 0, 3, 0, 0, 0, 21, 0, 0, 0, 0, 0, 11, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 }, /* D N */{ 7, 0, 0, 0, 9, 0, 0, 0, 3, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0 }, /* D O */{ 1, 5, 21, 10, 6, 3, 20, 1, 3, 0, 0, 30, 38, 54, 17, 7, 0, 39, 11, 10, 30, 5, 54, 5, 1, 3 }, /* D P */{ 6, 0, 0, 0, 1, 0, 0, 1, 3, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 }, /* D Q */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0 }, /* D R */{ 74, 0, 0, 0, 47, 0, 0, 0, 53, 0, 0, 0, 0, 0, 80, 0, 0, 0, 0, 0, 22, 0, 0, 0, 8, 0 }, /* D S */{ 1, 0, 3, 0, 10, 0, 0, 9, 5, 0, 1, 3, 10, 0, 16, 8, 0, 0, 0, 31, 1, 0, 2, 0, 0, 0 }, /* D T */{ 3, 0, 0, 0, 1, 0, 0, 6, 1, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* D U */{ 10, 7, 52, 2, 5, 3, 4, 0, 2, 0, 1, 33, 14, 15, 5, 11, 1, 19, 15, 8, 1, 0, 0, 0, 0, 1 }, /* D V */{ 3, 0, 0, 0, 13, 0, 0, 0, 7, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* D W */{ 19, 0, 0, 0, 10, 0, 0, 0, 19, 0, 0, 0, 0, 0, 8, 0, 0, 2, 0, 0, 0, 0, 0, 0, 2, 0 }, /* D X */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* D Y */{ 4, 2, 1, 2, 3, 1, 2, 0, 1, 0, 1, 4, 4, 12, 0, 0, 0, 0, 8, 1, 0, 0, 1, 0, 0, 0 }, /* D Z */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 } }, /* E A */{ { 0, 39, 34, 110, 0, 12, 13, 3, 0, 0, 50, 68, 38, 71, 0, 13, 1, 117, 80, 112, 28, 19, 7, 0, 0, 1 }, /* E B */{ 32, 5, 0, 0, 31, 0, 0, 0, 8, 0, 0, 6, 0, 0, 28, 0, 0, 32, 2, 3, 29, 0, 0, 0, 4, 0 }, /* E C */{ 33, 0, 9, 2, 51, 0, 0, 39, 49, 0, 47, 26, 0, 0, 59, 0, 0, 35, 2, 206, 42, 0, 0, 0, 2, 0 }, /* E D */{ 29, 7, 1, 16, 45, 5, 22, 3, 88, 0, 0, 8, 9, 4, 24, 2, 0, 27, 8, 4, 27, 0, 7, 0, 13, 0 }, /* E E */{ 2, 4, 13, 63, 1, 6, 1, 4, 10, 0, 19, 23, 13, 66, 1, 42, 0, 43, 9, 34, 1, 4, 6, 0, 0, 8 }, /* E F */{ 14, 0, 1, 2, 36, 33, 0, 0, 22, 0, 0, 15, 0, 0, 24, 0, 0, 14, 1, 13, 35, 0, 0, 0, 5, 0 }, /* E G */{ 48, 1, 0, 0, 36, 1, 15, 2, 38, 0, 0, 7, 4, 4, 26, 0, 0, 38, 0, 0, 19, 0, 0, 0, 4, 0 }, /* E H */{ 14, 0, 0, 0, 24, 0, 0, 0, 6, 0, 0, 0, 1, 0, 18, 0, 0, 4, 0, 0, 4, 0, 0, 0, 3, 0 }, /* E I */{ 8, 0, 5, 13, 2, 1, 42, 0, 1, 1, 2, 13, 7, 59, 1, 1, 0, 10, 25, 22, 0, 7, 0, 0, 0, 2 }, /* E J */{ 4, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0 }, /* E K */{ 2, 1, 0, 1, 6, 0, 0, 0, 4, 0, 0, 0, 0, 1, 1, 0, 0, 0, 2, 3, 0, 0, 0, 0, 1, 0 }, /* E L */{ 76, 7, 6, 57, 131, 19, 7, 3, 125, 0, 4, 238, 22, 1, 48, 15, 0, 4, 27, 26, 17, 19, 2, 0, 7, 0 }, /* E M */{ 87, 53, 1, 0, 84, 0, 0, 0, 102, 0, 0, 3, 8, 8, 56, 64, 0, 0, 4, 0, 19, 0, 1, 0, 8, 0 }, /* E N */{ 78, 17, 68, 159, 128, 8, 35, 14, 96, 2, 2, 4, 5, 54, 57, 3, 2, 9, 127, 624, 33, 10, 8, 0, 11, 16 }, /* E O */{ 0, 0, 8, 10, 0, 6, 7, 1, 2, 0, 0, 23, 10, 38, 0, 16, 0, 14, 6, 4, 41, 3, 2, 2, 0, 1 }, /* E P */{ 26, 1, 1, 0, 27, 0, 0, 32, 45, 0, 0, 21, 1, 0, 35, 9, 0, 35, 10, 65, 13, 0, 2, 0, 3, 0 }, /* E Q */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 59, 0, 0, 0, 0, 0 }, /* E R */{ 217, 57, 66, 22, 190, 41, 70, 13, 200, 3, 14, 40, 134, 117, 113, 42, 2, 123, 167, 135, 23, 58, 22, 1, 123, 1 }, /* E S */{ 17, 7, 74, 6, 58, 1, 3, 25, 82, 0, 3, 6, 17, 5, 34, 52, 7, 0, 222, 278, 18, 2, 1, 0, 6, 0 }, /* E T */{ 78, 3, 19, 0, 129, 4, 0, 93, 105, 0, 1, 3, 2, 2, 50, 1, 0, 73, 5, 113, 17, 0, 4, 0, 32, 4 }, /* E U */{ 0, 4, 7, 6, 1, 0, 4, 0, 0, 0, 2, 3, 17, 4, 0, 15, 0, 46, 20, 18, 0, 2, 1, 0, 0, 0 }, /* E V */{ 29, 0, 0, 0, 121, 0, 0, 0, 56, 0, 0, 0, 0, 0, 26, 0, 0, 2, 1, 0, 2, 2, 0, 0, 3, 1 }, /* E W */{ 33, 4, 3, 4, 16, 2, 0, 5, 24, 0, 0, 3, 3, 3, 23, 2, 0, 3, 15, 4, 0, 0, 1, 0, 2, 0 }, /* E X */{ 29, 0, 43, 0, 20, 0, 0, 14, 21, 0, 0, 0, 0, 0, 15, 78, 1, 0, 0, 72, 12, 0, 0, 1, 2, 0 }, /* E Y */{ 7, 3, 1, 4, 25, 2, 0, 2, 0, 0, 1, 4, 6, 4, 4, 1, 0, 2, 3, 0, 0, 1, 4, 0, 0, 0 }, /* E Z */{ 1, 0, 0, 0, 9, 0, 0, 0, 1, 0, 0, 0, 0, 0, 4, 0, 0, 1, 0, 0, 1, 1, 0, 0, 2, 3 } }, /* F A */{ { 1, 10, 39, 5, 2, 1, 1, 3, 18, 0, 2, 35, 10, 27, 0, 0, 0, 36, 13, 18, 10, 0, 2, 3, 4, 1 }, /* F B */{ 2, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* F C */{ 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* F D */{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* F E */{ 18, 5, 24, 6, 12, 0, 2, 0, 6, 0, 1, 25, 6, 18, 2, 0, 0, 114, 17, 15, 4, 2, 2, 0, 1, 0 }, /* F F */{ 10, 2, 0, 0, 51, 0, 0, 2, 45, 0, 0, 21, 4, 0, 13, 0, 0, 9, 7, 0, 7, 0, 0, 0, 8, 0 }, /* F G */{ 1, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* F H */{ 2, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* F I */{ 9, 9, 58, 18, 42, 7, 11, 0, 0, 0, 0, 29, 2, 53, 0, 0, 0, 40, 41, 18, 0, 2, 0, 10, 0, 3 }, /* F J */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* F K */{ 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* F L */{ 64, 0, 0, 0, 50, 0, 0, 0, 21, 0, 0, 0, 0, 0, 60, 0, 0, 0, 0, 0, 42, 0, 0, 0, 15, 0 }, /* F M */{ 6, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* F N */{ 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* F O */{ 5, 1, 8, 2, 1, 0, 7, 0, 6, 0, 0, 34, 1, 8, 32, 2, 0, 165, 5, 0, 25, 1, 2, 7, 1, 0 }, /* F P */{ 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* F Q */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* F R */{ 64, 0, 0, 0, 66, 0, 0, 0, 35, 0, 0, 0, 0, 0, 35, 0, 0, 0, 0, 0, 11, 0, 0, 0, 3, 0 }, /* F S */{ 1, 0, 0, 0, 2, 0, 0, 2, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0 }, /* F T */{ 1, 1, 1, 0, 19, 0, 0, 3, 1, 0, 0, 0, 1, 0, 3, 0, 0, 1, 9, 0, 0, 0, 4, 0, 8, 0 }, /* F U */{ 0, 0, 4, 2, 1, 0, 9, 0, 0, 2, 0, 119, 7, 24, 0, 0, 0, 28, 31, 6, 0, 0, 0, 0, 0, 2 }, /* F V */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* F W */{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* F X */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* F Y */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* F Z */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, /* G A */{ { 0, 20, 5, 11, 3, 2, 11, 3, 13, 0, 0, 68, 24, 60, 1, 5, 0, 63, 23, 68, 15, 8, 5, 0, 2, 5 }, /* G B */{ 4, 0, 0, 0, 1, 0, 0, 0, 3, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* G C */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* G D */{ 2, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* G E */{ 23, 3, 2, 4, 12, 1, 1, 3, 4, 0, 0, 32, 8, 141, 39, 4, 0, 96, 29, 33, 1, 1, 4, 0, 5, 0 }, /* G F */{ 0, 0, 0, 0, 1, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 3, 0, 0, 0, 0, 0 }, /* G G */{ 8, 0, 0, 0, 20, 0, 0, 1, 60, 0, 0, 24, 0, 0, 3, 1, 0, 6, 4, 0, 0, 0, 0, 0, 12, 0 }, /* G H */{ 18, 4, 1, 1, 12, 2, 1, 1, 2, 0, 1, 4, 0, 3, 12, 1, 0, 1, 3, 153, 2, 0, 3, 0, 1, 0 }, /* G I */{ 23, 21, 16, 6, 7, 2, 9, 0, 0, 0, 0, 24, 7, 103, 17, 1, 0, 10, 26, 19, 3, 10, 0, 0, 0, 1 }, /* G J */{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* G K */{ 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* G L */{ 49, 0, 0, 0, 73, 0, 0, 0, 25, 0, 0, 0, 0, 0, 38, 0, 0, 0, 0, 0, 13, 0, 0, 0, 17, 0 }, /* G M */{ 23, 0, 0, 0, 12, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 0, 0, 0, 1, 0 }, /* G N */{ 26, 1, 0, 0, 28, 0, 0, 0, 20, 0, 0, 0, 0, 0, 26, 2, 0, 0, 0, 1, 7, 0, 0, 0, 0, 0 }, /* G O */{ 6, 4, 3, 16, 6, 1, 10, 1, 5, 0, 0, 22, 1, 49, 20, 3, 0, 34, 12, 23, 16, 7, 5, 0, 1, 0 }, /* G P */{ 0, 0, 0, 0, 1, 0, 0, 0, 3, 0, 0, 2, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* G Q */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* G R */{ 216, 0, 0, 0, 97, 0, 0, 0, 43, 0, 0, 0, 0, 0, 50, 0, 0, 0, 0, 0, 14, 0, 0, 0, 3, 0 }, /* G S */{ 2, 2, 0, 0, 0, 0, 0, 2, 2, 0, 1, 1, 0, 0, 2, 1, 0, 0, 0, 18, 0, 0, 1, 0, 0, 0 }, /* G T */{ 2, 0, 0, 0, 0, 0, 0, 8, 3, 0, 0, 0, 0, 0, 17, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 }, /* G U */{ 28, 1, 1, 0, 49, 1, 1, 0, 41, 0, 0, 26, 15, 24, 2, 0, 0, 14, 22, 6, 0, 0, 0, 0, 3, 1 }, /* G V */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* G W */{ 5, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0 }, /* G X */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* G Y */{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 3, 0, 6, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0 }, /* G Z */{ 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, /* H A */{ { 2, 26, 15, 20, 6, 8, 22, 3, 31, 0, 11, 90, 66, 171, 3, 25, 0, 142, 30, 49, 20, 11, 20, 0, 13, 8 }, /* H B */{ 4, 0, 0, 0, 3, 0, 0, 0, 1, 0, 0, 2, 0, 0, 12, 0, 0, 2, 0, 0, 4, 0, 0, 0, 1, 0 }, /* H C */{ 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 2, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 }, /* H D */{ 2, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 2, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0 }, /* H E */{ 123, 5, 22, 33, 37, 5, 3, 0, 27, 0, 0, 87, 65, 86, 17, 7, 1, 311, 57, 42, 11, 11, 14, 8, 11, 2 }, /* H F */{ 2, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0 }, /* H G */{ 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* H H */{ 1, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* H I */{ 22, 22, 56, 15, 23, 6, 19, 0, 0, 1, 1, 73, 20, 79, 17, 41, 0, 36, 53, 39, 3, 11, 0, 0, 0, 6 }, /* H J */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* H K */{ 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* H L */{ 5, 0, 0, 0, 11, 0, 0, 0, 8, 0, 0, 0, 0, 0, 22, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0 }, /* H M */{ 21, 0, 0, 0, 15, 0, 0, 0, 6, 0, 0, 0, 1, 0, 7, 0, 0, 0, 2, 0, 1, 0, 0, 0, 0, 0 }, /* H N */{ 3, 0, 0, 0, 8, 0, 0, 0, 9, 0, 0, 0, 0, 1, 3, 0, 0, 0, 4, 0, 2, 0, 0, 0, 0, 0 }, /* H O */{ 13, 18, 13, 25, 17, 5, 13, 0, 7, 1, 4, 101, 62, 62, 44, 29, 0, 130, 45, 33, 81, 8, 28, 0, 6, 2 }, /* H P */{ 3, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 }, /* H Q */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 }, /* H R */{ 20, 0, 0, 0, 23, 0, 0, 0, 40, 0, 0, 1, 0, 0, 72, 0, 0, 0, 0, 0, 13, 0, 0, 0, 3, 0 }, /* H S */{ 3, 0, 1, 0, 0, 0, 0, 2, 1, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0 }, /* H T */{ 3, 0, 2, 1, 21, 9, 1, 7, 5, 0, 0, 1, 4, 3, 4, 1, 0, 2, 7, 1, 1, 0, 3, 0, 6, 0 }, /* H U */{ 3, 13, 7, 6, 3, 5, 12, 1, 0, 0, 0, 7, 37, 26, 0, 3, 0, 37, 24, 15, 0, 0, 0, 2, 2, 1 }, /* H V */{ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* H W */{ 17, 0, 0, 0, 5, 0, 0, 2, 5, 0, 0, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* H X */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* H Y */{ 5, 1, 1, 39, 1, 0, 3, 0, 1, 0, 0, 13, 9, 0, 0, 25, 0, 9, 29, 9, 0, 0, 0, 1, 0, 0 }, /* H Z */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, /* I A */{ { 0, 33, 20, 8, 1, 0, 17, 5, 1, 0, 2, 169, 20, 230, 0, 3, 0, 30, 13, 91, 0, 1, 1, 2, 0, 1 }, /* I B */{ 11, 19, 0, 0, 38, 0, 0, 0, 22, 0, 0, 131, 1, 2, 10, 0, 0, 20, 1, 0, 23, 0, 0, 0, 2, 0 }, /* I C */{ 161, 0, 3, 0, 113, 0, 0, 62, 113, 0, 142, 15, 0, 4, 46, 0, 0, 12, 5, 53, 42, 0, 0, 0, 7, 0 }, /* I D */{ 51, 2, 0, 31, 232, 0, 30, 0, 46, 1, 0, 5, 1, 8, 10, 1, 0, 1, 10, 5, 11, 0, 7, 0, 9, 0 }, /* I E */{ 0, 1, 17, 6, 1, 16, 11, 1, 0, 0, 1, 52, 4, 70, 0, 1, 0, 66, 18, 50, 7, 17, 6, 0, 0, 2 }, /* I F */{ 7, 0, 0, 0, 31, 45, 0, 0, 27, 0, 0, 9, 0, 1, 10, 0, 0, 2, 0, 24, 10, 0, 0, 0, 71, 0 }, /* I G */{ 48, 0, 0, 0, 41, 0, 30, 147, 30, 0, 0, 4, 15, 57, 20, 1, 0, 23, 3, 1, 15, 0, 1, 0, 2, 2 }, /* I H */{ 1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* I I */{ 1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* I J */{ 3, 0, 0, 0, 2, 0, 0, 0, 1, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 }, /* I K */{ 6, 0, 0, 0, 17, 0, 0, 0, 3, 0, 1, 0, 0, 0, 3, 0, 0, 0, 0, 1, 2, 0, 0, 0, 1, 0 }, /* I L */{ 60, 10, 6, 36, 106, 6, 5, 7, 90, 0, 13, 253, 14, 0, 24, 1, 0, 1, 10, 31, 6, 6, 5, 0, 10, 0 }, /* I M */{ 76, 26, 0, 0, 94, 1, 0, 1, 53, 0, 0, 1, 38, 1, 30, 133, 0, 1, 8, 0, 17, 0, 0, 0, 2, 0 }, /* I N */{ 212, 12, 143, 168, 396, 83, 435, 26, 94, 8, 43, 9, 6, 44, 70, 3, 10, 2, 139, 205, 35, 46, 4, 4, 15, 1 }, /* I O */{ 2, 2, 20, 10, 1, 0, 9, 0, 0, 0, 0, 28, 12, 604, 0, 8, 0, 25, 13, 24, 139, 3, 2, 3, 0, 1 }, /* I P */{ 20, 5, 0, 0, 26, 2, 0, 16, 16, 1, 0, 33, 6, 0, 13, 39, 0, 5, 19, 28, 5, 0, 1, 0, 1, 0 }, /* I Q */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 36, 0, 0, 0, 0, 0 }, /* I R */{ 41, 2, 39, 24, 106, 7, 9, 0, 19, 0, 11, 20, 24, 1, 24, 8, 0, 39, 11, 31, 3, 5, 8, 0, 10, 0 }, /* I S */{ 35, 5, 71, 4, 110, 4, 2, 189, 56, 1, 13, 12, 93, 5, 55, 33, 3, 6, 85, 271, 4, 1, 1, 0, 8, 0 }, /* I T */{ 136, 1, 34, 1, 184, 5, 0, 77, 158, 0, 1, 4, 6, 5, 70, 1, 0, 31, 2, 105, 72, 0, 1, 0, 142, 19 }, /* I U */{ 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 121, 1, 0, 0, 0, 1, 19, 0, 0, 0, 0, 0, 0, 0 }, /* I V */{ 57, 0, 0, 0, 292, 0, 0, 0, 37, 0, 0, 0, 0, 0, 12, 0, 0, 1, 0, 0, 3, 0, 0, 0, 2, 0 }, /* I W */{ 3, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* I X */{ 1, 0, 0, 0, 2, 1, 1, 0, 3, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 9, 1, 0, 0, 0, 1, 0 }, /* I Y */{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* I Z */{ 9, 0, 0, 0, 13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 16 } }, /* J A */{ { 0, 2, 32, 1, 1, 0, 3, 3, 2, 0, 3, 1, 8, 17, 0, 2, 0, 5, 2, 0, 2, 3, 2, 1, 1, 2 }, /* J B */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* J C */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* J D */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* J E */{ 4, 0, 24, 1, 1, 3, 0, 1, 0, 2, 0, 2, 0, 6, 2, 0, 0, 11, 9, 5, 0, 0, 6, 0, 0, 0 }, /* J F */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* J G */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* J H */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* J I */{ 0, 1, 0, 0, 0, 1, 4, 0, 0, 0, 0, 2, 4, 3, 0, 0, 0, 0, 0, 4, 0, 1, 0, 0, 0, 0 }, /* J J */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* J K */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* J L */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* J M */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* J N */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* J O */{ 4, 2, 6, 0, 3, 0, 3, 12, 10, 0, 1, 6, 0, 5, 0, 0, 0, 10, 10, 1, 13, 4, 2, 0, 7, 0 }, /* J P */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* J Q */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* J R */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* J S */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* J T */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* J U */{ 3, 3, 0, 19, 0, 0, 8, 0, 2, 2, 2, 8, 5, 24, 0, 1, 0, 15, 9, 5, 0, 1, 0, 2, 0, 0 }, /* J V */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* J W */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* J X */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* J Y */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* J Z */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, /* K A */{ { 0, 3, 0, 6, 1, 2, 8, 2, 1, 1, 1, 9, 4, 13, 2, 3, 0, 18, 4, 17, 2, 1, 2, 1, 5, 2 }, /* K B */{ 3, 0, 0, 0, 3, 0, 0, 0, 2, 0, 0, 0, 0, 0, 11, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0 }, /* K C */{ 2, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 }, /* K D */{ 3, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 }, /* K E */{ 4, 3, 0, 7, 28, 3, 3, 2, 1, 0, 0, 20, 5, 55, 3, 3, 0, 59, 18, 56, 2, 1, 4, 0, 27, 0 }, /* K F */{ 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0 }, /* K G */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 }, /* K H */{ 9, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 1, 0, 8, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0 }, /* K I */{ 5, 2, 3, 9, 15, 1, 1, 0, 0, 0, 1, 10, 10, 87, 2, 4, 0, 11, 15, 13, 0, 2, 2, 0, 0, 0 }, /* K J */{ 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* K K */{ 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* K L */{ 15, 0, 0, 0, 46, 0, 0, 0, 13, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 1, 0, 0, 0, 2, 0 }, /* K M */{ 13, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* K N */{ 5, 0, 0, 0, 11, 0, 0, 0, 10, 0, 0, 0, 0, 0, 24, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0 }, /* K O */{ 1, 1, 2, 3, 2, 4, 0, 2, 1, 0, 1, 3, 1, 7, 1, 2, 0, 6, 2, 1, 7, 4, 5, 2, 0, 0 }, /* K P */{ 2, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 4, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* K Q */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* K R */{ 10, 0, 0, 0, 3, 0, 0, 0, 3, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 5, 0, 0, 0, 2, 0 }, /* K S */{ 2, 2, 1, 0, 1, 0, 1, 9, 5, 0, 1, 0, 4, 0, 8, 3, 0, 0, 0, 11, 4, 0, 1, 0, 1, 0 }, /* K T */{ 3, 0, 0, 0, 0, 0, 0, 2, 3, 0, 0, 0, 0, 0, 5, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0 }, /* K U */{ 0, 0, 0, 2, 0, 0, 0, 1, 0, 0, 0, 5, 1, 1, 0, 8, 0, 2, 1, 1, 0, 0, 1, 0, 1, 0 }, /* K V */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* K W */{ 9, 0, 0, 0, 4, 0, 0, 1, 2, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* K X */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* K Y */{ 2, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 4, 0, 0, 2, 0, 0, 2, 1, 0, 1, 0, 3, 0, 0, 0 }, /* K Z */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, /* L A */{ { 1, 46, 84, 43, 3, 2, 46, 9, 52, 0, 10, 3, 64, 242, 4, 23, 1, 157, 92, 210, 45, 21, 23, 9, 42, 11 }, /* L B */{ 12, 0, 0, 0, 17, 0, 0, 0, 3, 0, 0, 2, 0, 0, 13, 0, 0, 4, 0, 0, 4, 0, 0, 0, 2, 0 }, /* L C */{ 9, 0, 0, 0, 6, 0, 0, 12, 4, 0, 0, 1, 1, 0, 19, 0, 0, 2, 0, 1, 7, 0, 0, 0, 2, 0 }, /* L D */{ 2, 3, 2, 0, 41, 4, 0, 1, 16, 0, 0, 1, 2, 3, 13, 1, 0, 8, 9, 2, 3, 0, 5, 0, 3, 0 }, /* L E */{ 94, 25, 75, 44, 36, 13, 55, 9, 26, 1, 1, 9, 55, 121, 22, 22, 0, 77, 84, 115, 12, 29, 14, 30, 75, 1 }, /* L F */{ 9, 1, 0, 0, 4, 1, 1, 1, 12, 0, 0, 1, 0, 0, 7, 0, 0, 8, 1, 2, 8, 0, 1, 0, 0, 0 }, /* L G */{ 16, 0, 0, 0, 12, 0, 0, 0, 10, 0, 0, 0, 0, 0, 6, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 0 }, /* L H */{ 7, 0, 0, 0, 6, 0, 0, 0, 2, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* L I */{ 82, 33, 140, 26, 43, 37, 73, 0, 0, 1, 6, 11, 46, 238, 50, 40, 13, 5, 90, 127, 12, 36, 0, 3, 0, 7 }, /* L J */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* L K */{ 7, 0, 0, 0, 4, 0, 0, 3, 9, 0, 0, 2, 0, 1, 2, 0, 0, 0, 3, 0, 0, 0, 3, 0, 8, 0 }, /* L L */{ 128, 12, 2, 4, 169, 7, 2, 4, 152, 1, 0, 0, 7, 0, 100, 2, 0, 1, 10, 2, 41, 0, 7, 0, 53, 0 }, /* L M */{ 27, 0, 0, 2, 11, 0, 0, 2, 9, 0, 0, 0, 1, 0, 13, 0, 0, 0, 4, 0, 3, 0, 0, 0, 3, 0 }, /* L N */{ 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0 }, /* L O */{ 23, 23, 65, 15, 7, 4, 132, 3, 32, 0, 2, 7, 29, 69, 50, 36, 11, 74, 33, 53, 66, 16, 80, 1, 12, 1 }, /* L P */{ 11, 0, 0, 0, 3, 1, 0, 21, 5, 0, 0, 0, 1, 0, 6, 0, 0, 3, 1, 4, 0, 0, 0, 0, 1, 0 }, /* L Q */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* L R */{ 2, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 2, 0, 0, 0, 6, 0 }, /* L S */{ 7, 1, 0, 0, 16, 0, 0, 8, 23, 0, 1, 0, 1, 0, 20, 3, 0, 0, 1, 23, 0, 0, 1, 0, 2, 0 }, /* L T */{ 22, 1, 0, 0, 23, 0, 0, 14, 34, 0, 0, 0, 2, 0, 23, 0, 0, 9, 3, 0, 8, 1, 1, 0, 18, 5 }, /* L U */{ 5, 17, 26, 18, 31, 5, 13, 0, 5, 2, 4, 8, 68, 31, 15, 5, 0, 21, 68, 56, 0, 4, 0, 13, 0, 1 }, /* L V */{ 19, 0, 0, 1, 46, 0, 0, 0, 9, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* L W */{ 8, 0, 0, 0, 2, 0, 0, 1, 2, 0, 0, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 }, /* L X */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* L Y */{ 2, 4, 12, 2, 2, 2, 3, 7, 2, 0, 1, 3, 13, 11, 2, 11, 0, 2, 31, 15, 1, 0, 4, 0, 0, 0 }, /* L Z */{ 2, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, /* M A */{ { 0, 10, 59, 34, 3, 0, 57, 7, 31, 3, 25, 104, 6, 326, 2, 4, 0, 144, 49, 192, 10, 2, 3, 11, 14, 7 }, /* M B */{ 31, 1, 0, 1, 44, 0, 0, 0, 32, 0, 0, 31, 0, 1, 27, 1, 0, 32, 1, 0, 21, 0, 0, 0, 0, 0 }, /* M C */{ 3, 1, 17, 6, 2, 2, 9, 3, 5, 0, 9, 3, 3, 4, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* M D */{ 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 }, /* M E */{ 30, 6, 8, 45, 3, 2, 14, 1, 4, 0, 1, 51, 19, 283, 10, 4, 0, 125, 39, 128, 0, 2, 9, 3, 4, 1 }, /* M F */{ 0, 0, 0, 0, 3, 0, 0, 0, 3, 0, 0, 2, 0, 0, 4, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0 }, /* M G */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* M H */{ 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 }, /* M I */{ 19, 0, 93, 54, 8, 2, 19, 0, 0, 1, 2, 76, 9, 194, 4, 0, 1, 21, 96, 109, 10, 0, 0, 5, 0, 1 }, /* M J */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* M K */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* M L */{ 1, 0, 0, 0, 3, 0, 0, 0, 6, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* M M */{ 40, 0, 0, 0, 46, 0, 0, 0, 33, 0, 0, 0, 0, 0, 32, 0, 0, 0, 0, 0, 17, 0, 0, 0, 12, 0 }, /* M N */{ 12, 0, 0, 0, 4, 0, 0, 0, 10, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0 }, /* M O */{ 4, 10, 13, 28, 4, 1, 14, 3, 11, 0, 6, 47, 10, 168, 16, 3, 0, 107, 40, 45, 56, 8, 1, 1, 1, 2 }, /* M P */{ 52, 3, 0, 0, 71, 1, 1, 26, 18, 0, 4, 71, 0, 0, 50, 0, 0, 41, 9, 43, 19, 0, 0, 0, 7, 0 }, /* M Q */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0 }, /* M R */{ 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 }, /* M S */{ 0, 1, 2, 1, 5, 1, 0, 2, 3, 0, 1, 0, 2, 0, 8, 2, 0, 0, 1, 10, 1, 0, 0, 0, 2, 0 }, /* M T */{ 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 }, /* M U */{ 0, 0, 7, 11, 6, 3, 6, 0, 2, 0, 2, 55, 11, 29, 2, 1, 0, 18, 53, 30, 0, 0, 0, 0, 0, 3 }, /* M V */{ 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* M W */{ 2, 0, 0, 0, 2, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* M X */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* M Y */{ 0, 0, 11, 0, 5, 0, 1, 0, 0, 0, 0, 1, 0, 2, 7, 0, 0, 7, 7, 4, 0, 0, 0, 0, 0, 0 }, /* M Z */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } } }; static void fill( final Data data ) { int a, b, c; for ( a = 0; a < 13; a++ ) { for ( b = 0; b < 26; b++ ) { for ( c = 0; c < 26; c++ ) { data.set( a, b, c, tris1[a][b][c] ); } } } } } class DataInit2 { static final int tris2[][][] = { { /* N A */{ 2, 24, 33, 23, 6, 3, 30, 6, 20, 0, 9, 115, 29, 59, 2, 31, 0, 94, 28, 159, 19, 10, 5, 0, 1, 5 }, /* N B */{ 5, 0, 1, 0, 20, 0, 0, 0, 1, 0, 0, 4, 0, 0, 7, 0, 0, 4, 1, 0, 10, 0, 0, 0, 0, 0 }, /* N C */{ 25, 0, 0, 0, 190, 0, 0, 87, 51, 0, 1, 18, 0, 0, 62, 0, 0, 16, 0, 36, 21, 0, 0, 0, 8, 0 }, /* N D */{ 75, 11, 4, 1, 162, 6, 3, 7, 102, 1, 1, 22, 10, 2, 57, 9, 2, 46, 30, 4, 37, 0, 11, 0, 20, 0 }, /* N E */{ 34, 12, 36, 12, 29, 17, 16, 4, 14, 0, 0, 45, 16, 20, 25, 8, 6, 88, 80, 84, 32, 12, 37, 18, 45, 3 }, /* N F */{ 15, 0, 0, 0, 30, 0, 0, 0, 38, 0, 0, 23, 0, 0, 26, 0, 0, 10, 0, 0, 19, 0, 0, 0, 0, 0 }, /* N G */{ 22, 8, 0, 3, 114, 6, 0, 15, 18, 0, 3, 51, 5, 0, 20, 2, 0, 24, 24, 28, 38, 0, 2, 0, 9, 0 }, /* N H */{ 18, 0, 0, 0, 16, 0, 0, 0, 6, 0, 0, 0, 0, 0, 15, 0, 0, 0, 0, 0, 2, 0, 0, 0, 3, 0 }, /* N I */{ 90, 9, 148, 14, 33, 27, 35, 4, 1, 0, 5, 12, 25, 44, 26, 21, 7, 4, 87, 94, 29, 11, 0, 4, 0, 4 }, /* N J */{ 2, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 13, 0, 0, 0, 0, 0 }, /* N K */{ 6, 0, 1, 0, 22, 4, 1, 1, 10, 0, 0, 12, 2, 0, 1, 1, 0, 2, 2, 3, 0, 0, 0, 0, 9, 0 }, /* N L */{ 9, 0, 0, 0, 8, 0, 0, 0, 5, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 }, /* N M */{ 8, 0, 0, 0, 5, 0, 0, 0, 2, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* N N */{ 39, 0, 0, 0, 74, 0, 0, 0, 52, 0, 1, 0, 0, 0, 23, 0, 0, 0, 1, 0, 14, 0, 1, 0, 25, 0 }, /* N O */{ 4, 18, 21, 10, 4, 4, 15, 0, 11, 0, 0, 30, 60, 34, 11, 11, 0, 80, 32, 47, 52, 18, 24, 7, 2, 2 }, /* N P */{ 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 4, 0, 0, 6, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0 }, /* N Q */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 22, 0, 0, 0, 0, 0 }, /* N R */{ 3, 0, 1, 0, 1, 0, 0, 0, 6, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 3, 0, 0, 0, 6, 0 }, /* N S */{ 26, 4, 23, 2, 73, 17, 3, 12, 96, 0, 5, 8, 13, 0, 60, 25, 0, 1, 3, 79, 39, 4, 4, 0, 5, 0 }, /* N T */{ 143, 1, 1, 1, 175, 2, 2, 64, 209, 0, 0, 13, 3, 1, 65, 1, 0, 114, 3, 0, 32, 0, 2, 0, 21, 1 }, /* N U */{ 12, 6, 16, 6, 11, 3, 6, 0, 5, 0, 1, 15, 35, 9, 6, 3, 0, 9, 25, 31, 1, 0, 0, 0, 0, 1 }, /* N V */{ 15, 0, 0, 0, 43, 0, 0, 0, 20, 0, 0, 0, 0, 0, 17, 0, 0, 0, 0, 0, 4, 0, 0, 0, 1, 0 }, /* N W */{ 12, 0, 0, 0, 3, 0, 0, 2, 4, 0, 0, 0, 0, 0, 6, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 }, /* N X */{ 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 }, /* N Y */{ 5, 3, 1, 1, 0, 0, 0, 1, 0, 0, 0, 7, 14, 0, 4, 1, 1, 1, 3, 1, 1, 1, 2, 1, 0, 0 }, /* N Z */{ 10, 0, 0, 0, 5, 0, 0, 0, 5, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 5, 0 } }, /* O A */{ { 1, 0, 20, 30, 0, 2, 5, 2, 0, 0, 9, 9, 8, 18, 0, 4, 1, 51, 13, 44, 1, 1, 0, 2, 0, 0 }, /* O B */{ 17, 24, 2, 2, 28, 2, 0, 1, 32, 4, 0, 19, 0, 1, 16, 0, 0, 5, 26, 3, 8, 3, 1, 0, 2, 0 }, /* O C */{ 50, 0, 28, 0, 38, 0, 0, 47, 26, 0, 129, 14, 0, 0, 33, 0, 0, 25, 0, 34, 20, 0, 0, 0, 8, 0 }, /* O D */{ 17, 3, 3, 15, 59, 3, 13, 4, 47, 0, 1, 13, 2, 1, 22, 3, 0, 8, 11, 0, 21, 0, 8, 0, 35, 0 }, /* O E */{ 0, 6, 1, 7, 0, 3, 0, 1, 6, 0, 1, 10, 3, 13, 1, 0, 1, 10, 15, 6, 2, 7, 0, 3, 1, 0 }, /* O F */{ 7, 0, 0, 0, 4, 63, 0, 0, 10, 0, 0, 4, 1, 0, 6, 0, 0, 1, 0, 15, 4, 0, 0, 0, 1, 0 }, /* O G */{ 34, 2, 0, 1, 44, 1, 22, 3, 15, 1, 0, 11, 3, 11, 7, 0, 0, 80, 1, 2, 18, 0, 1, 0, 83, 0 }, /* O H */{ 10, 0, 0, 0, 8, 0, 0, 0, 6, 0, 0, 1, 5, 9, 5, 0, 0, 2, 0, 0, 0, 0, 0, 0, 1, 0 }, /* O I */{ 3, 1, 12, 53, 1, 1, 2, 0, 0, 0, 1, 27, 0, 51, 0, 0, 0, 11, 39, 8, 0, 0, 0, 1, 0, 0 }, /* O J */{ 1, 0, 0, 0, 5, 0, 0, 0, 1, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* O K */{ 5, 2, 1, 0, 48, 0, 0, 1, 7, 0, 1, 4, 0, 0, 3, 1, 0, 0, 5, 0, 3, 0, 1, 0, 6, 0 }, /* O L */{ 71, 4, 6, 83, 111, 8, 5, 3, 121, 0, 14, 124, 16, 1, 132, 6, 0, 1, 18, 24, 43, 16, 2, 0, 46, 1 }, /* O M */{ 89, 50, 1, 0, 174, 5, 0, 1, 76, 0, 0, 2, 64, 7, 56, 125, 1, 1, 4, 0, 4, 0, 2, 0, 22, 0 }, /* O N */{ 129, 3, 64, 82, 181, 52, 86, 3, 124, 10, 11, 7, 3, 46, 75, 1, 6, 10, 107, 149, 8, 38, 9, 1, 54, 5 }, /* O O */{ 0, 2, 4, 92, 0, 22, 4, 1, 0, 0, 68, 42, 42, 44, 0, 19, 0, 21, 21, 68, 0, 3, 0, 0, 0, 2 }, /* O P */{ 28, 1, 2, 0, 71, 0, 2, 82, 32, 1, 3, 16, 1, 1, 45, 29, 0, 17, 14, 21, 10, 0, 2, 0, 19, 0 }, /* O Q */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 14, 0, 0, 0, 0, 0 }, /* O R */{ 122, 26, 31, 96, 138, 7, 34, 2, 143, 0, 61, 8, 85, 76, 61, 59, 1, 58, 46, 211, 11, 4, 9, 0, 116, 1 }, /* O S */{ 31, 4, 24, 0, 107, 0, 3, 18, 102, 0, 2, 7, 9, 1, 18, 42, 2, 0, 63, 127, 5, 1, 2, 0, 8, 0 }, /* O T */{ 45, 7, 11, 0, 64, 2, 1, 88, 63, 0, 0, 10, 3, 1, 42, 4, 0, 17, 7, 63, 9, 0, 3, 0, 11, 0 }, /* O U */{ 3, 11, 17, 13, 3, 3, 62, 1, 6, 0, 0, 32, 1, 137, 0, 11, 1, 86, 445, 103, 0, 7, 0, 1, 0, 2 }, /* O V */{ 26, 0, 0, 0, 109, 0, 0, 0, 27, 0, 1, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0 }, /* O W */{ 18, 14, 2, 13, 48, 6, 0, 8, 8, 0, 1, 28, 7, 83, 1, 8, 0, 5, 13, 2, 2, 0, 1, 0, 4, 1 }, /* O X */{ 2, 1, 3, 0, 5, 1, 1, 3, 26, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 14, 0 }, /* O Y */{ 15, 1, 4, 6, 3, 1, 0, 0, 1, 0, 0, 3, 0, 1, 4, 1, 0, 1, 2, 1, 0, 0, 0, 0, 0, 0 }, /* O Z */{ 2, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 1 } }, /* P A */{ { 0, 8, 38, 11, 1, 0, 18, 0, 17, 0, 2, 50, 5, 73, 1, 23, 1, 176, 50, 101, 18, 5, 7, 1, 10, 2 }, /* P B */{ 3, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 1, 0, 0, 6, 0, 0, 2, 1, 0, 3, 0, 0, 0, 0, 0 }, /* P C */{ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* P D */{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0 }, /* P E */{ 51, 1, 62, 34, 19, 4, 8, 0, 3, 1, 2, 47, 2, 108, 4, 10, 0, 292, 22, 50, 3, 1, 8, 2, 2, 4 }, /* P F */{ 0, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 3, 0, 0, 0, 0, 0 }, /* P G */{ 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0 }, /* P H */{ 56, 0, 0, 2, 88, 0, 0, 0, 76, 0, 0, 3, 0, 1, 97, 0, 0, 13, 1, 3, 5, 0, 0, 0, 79, 0 }, /* P I */{ 21, 0, 74, 25, 33, 1, 19, 0, 0, 0, 6, 27, 3, 74, 12, 11, 2, 37, 27, 57, 3, 2, 0, 2, 0, 2 }, /* P J */{ 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* P K */{ 0, 0, 0, 0, 2, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* P L */{ 150, 0, 0, 0, 121, 0, 0, 0, 59, 0, 0, 0, 0, 0, 33, 0, 0, 0, 0, 0, 29, 0, 0, 0, 11, 0 }, /* P M */{ 6, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 }, /* P N */{ 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* P O */{ 2, 1, 19, 10, 12, 2, 7, 0, 31, 0, 12, 111, 14, 55, 23, 17, 0, 97, 126, 52, 20, 3, 13, 3, 2, 0 }, /* P P */{ 16, 0, 0, 0, 48, 0, 0, 1, 20, 0, 0, 32, 1, 0, 25, 0, 0, 32, 3, 0, 1, 0, 0, 0, 16, 0 }, /* P Q */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* P R */{ 39, 0, 0, 0, 166, 0, 0, 0, 104, 0, 0, 0, 0, 0, 273, 0, 0, 0, 0, 0, 12, 0, 0, 0, 1, 0 }, /* P S */{ 4, 1, 3, 0, 17, 0, 0, 5, 22, 0, 1, 1, 2, 0, 13, 0, 0, 0, 0, 14, 6, 0, 1, 0, 35, 0 }, /* P T */{ 16, 0, 1, 0, 9, 0, 0, 3, 107, 0, 0, 0, 0, 0, 33, 0, 0, 3, 0, 0, 19, 0, 0, 0, 4, 0 }, /* P U */{ 1, 8, 4, 8, 3, 6, 4, 0, 1, 0, 1, 41, 8, 22, 0, 9, 0, 39, 18, 28, 0, 0, 0, 0, 0, 1 }, /* P V */{ 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* P W */{ 3, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 }, /* P X */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* P Y */{ 1, 2, 0, 0, 0, 0, 3, 0, 1, 0, 1, 3, 0, 0, 1, 0, 0, 20, 0, 3, 0, 0, 1, 0, 0, 0 }, /* P Z */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, /* Q A */{ { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 }, /* Q B */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* Q C */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* Q D */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* Q E */{ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* Q F */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* Q G */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* Q H */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* Q I */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* Q J */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* Q K */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* Q L */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* Q M */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* Q N */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* Q O */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* Q P */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* Q Q */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* Q R */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* Q S */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* Q T */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* Q U */{ 110, 0, 0, 0, 100, 0, 0, 0, 128, 0, 0, 0, 0, 0, 13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0 }, /* Q V */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* Q W */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* Q X */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* Q Y */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* Q Z */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, /* R A */{ { 0, 72, 130, 95, 8, 35, 73, 14, 85, 3, 10, 121, 95, 313, 2, 119, 1, 26, 66, 277, 19, 45, 28, 2, 28, 13 }, /* R B */{ 32, 0, 0, 0, 26, 0, 0, 0, 35, 0, 0, 4, 0, 0, 44, 0, 0, 3, 1, 0, 9, 0, 0, 0, 5, 0 }, /* R C */{ 18, 0, 2, 0, 47, 0, 0, 86, 25, 0, 3, 11, 0, 0, 13, 0, 0, 1, 2, 7, 38, 0, 0, 0, 4, 0 }, /* R D */{ 22, 5, 1, 0, 26, 1, 0, 4, 42, 0, 0, 4, 0, 2, 17, 1, 0, 5, 9, 4, 3, 0, 4, 0, 7, 0 }, /* R E */{ 166, 26, 106, 99, 114, 52, 55, 20, 25, 4, 4, 60, 69, 143, 20, 72, 8, 11, 257, 119, 14, 56, 34, 7, 23, 2 }, /* R F */{ 11, 0, 0, 0, 15, 1, 0, 0, 9, 0, 0, 7, 0, 0, 8, 0, 0, 4, 0, 0, 12, 0, 0, 0, 0, 0 }, /* R G */{ 26, 0, 0, 0, 63, 0, 0, 5, 25, 0, 0, 11, 1, 0, 18, 0, 0, 2, 2, 0, 13, 0, 0, 0, 11, 0 }, /* R H */{ 11, 0, 0, 0, 19, 0, 0, 0, 5, 0, 0, 0, 0, 0, 18, 0, 0, 0, 0, 0, 2, 0, 0, 0, 3, 0 }, /* R I */{ 182, 54, 210, 87, 79, 38, 65, 1, 0, 1, 6, 49, 65, 166, 82, 61, 1, 0, 151, 141, 29, 44, 1, 6, 1, 10 }, /* R J */{ 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0 }, /* R K */{ 4, 2, 0, 1, 19, 0, 0, 3, 9, 0, 0, 6, 3, 2, 5, 3, 0, 1, 10, 2, 0, 0, 1, 0, 6, 0 }, /* R L */{ 24, 2, 0, 4, 28, 0, 0, 0, 36, 0, 0, 0, 0, 0, 14, 1, 0, 0, 2, 1, 2, 0, 1, 0, 8, 0 }, /* R M */{ 97, 1, 2, 0, 29, 2, 0, 3, 65, 0, 0, 2, 0, 0, 39, 1, 0, 0, 1, 1, 10, 0, 1, 0, 5, 0 }, /* R N */{ 53, 5, 0, 0, 50, 4, 0, 3, 29, 0, 1, 0, 6, 0, 16, 1, 0, 0, 9, 5, 7, 0, 2, 0, 4, 0 }, /* R O */{ 46, 40, 79, 40, 18, 22, 56, 4, 32, 5, 10, 76, 90, 167, 84, 127, 2, 14, 127, 74, 127, 42, 63, 17, 15, 3 }, /* R P */{ 10, 0, 0, 0, 21, 0, 0, 33, 10, 0, 0, 5, 1, 0, 25, 0, 0, 12, 8, 8, 5, 0, 0, 0, 1, 0 }, /* R Q */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0 }, /* R R */{ 53, 0, 0, 0, 92, 0, 0, 5, 85, 0, 0, 0, 0, 0, 47, 0, 0, 0, 0, 0, 14, 0, 0, 0, 60, 0 }, /* R S */{ 26, 2, 2, 2, 84, 1, 0, 16, 44, 0, 4, 2, 3, 1, 43, 12, 1, 0, 0, 32, 14, 1, 2, 0, 2, 0 }, /* R T */{ 39, 2, 2, 0, 61, 5, 3, 101, 99, 0, 0, 11, 7, 3, 32, 0, 0, 17, 12, 1, 27, 0, 2, 0, 24, 7 }, /* R U */{ 5, 21, 30, 31, 15, 6, 12, 0, 18, 0, 0, 10, 46, 41, 1, 28, 0, 3, 83, 22, 0, 1, 1, 1, 0, 1 }, /* R V */{ 31, 0, 0, 0, 37, 0, 0, 0, 28, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 1, 0, 0, 0, 2, 0 }, /* R W */{ 15, 0, 0, 0, 6, 0, 0, 0, 12, 0, 0, 0, 0, 0, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* R X */{ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* R Y */{ 5, 3, 3, 5, 3, 0, 1, 0, 0, 0, 0, 10, 11, 4, 12, 16, 0, 0, 9, 4, 0, 0, 2, 0, 0, 0 }, /* R Z */{ 2, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, /* S A */{ { 2, 44, 23, 16, 1, 10, 21, 4, 16, 1, 7, 80, 17, 89, 1, 10, 0, 36, 10, 43, 22, 10, 13, 5, 7, 0 }, /* S B */{ 9, 0, 0, 0, 4, 0, 0, 0, 2, 0, 0, 0, 0, 0, 6, 0, 0, 2, 0, 0, 18, 0, 0, 0, 3, 0 }, /* S C */{ 81, 0, 0, 0, 65, 0, 1, 78, 37, 0, 0, 5, 1, 0, 88, 0, 0, 92, 0, 0, 40, 0, 0, 0, 3, 0 }, /* S D */{ 11, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 2, 0, 0, 2, 0, 0, 2, 0, 0, 0, 0, 0 }, /* S E */{ 38, 14, 47, 18, 33, 7, 8, 3, 11, 0, 1, 63, 39, 101, 5, 28, 14, 83, 28, 41, 12, 19, 15, 15, 19, 1 }, /* S F */{ 3, 0, 0, 0, 7, 0, 0, 0, 5, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 6, 0, 0, 0, 1, 0 }, /* S G */{ 0, 0, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0, 0, 0, 2, 0, 0, 5, 1, 0, 2, 0, 0, 0, 0, 0 }, /* S H */{ 97, 9, 1, 0, 79, 3, 0, 0, 75, 0, 1, 4, 16, 3, 81, 2, 0, 27, 0, 1, 20, 1, 6, 0, 17, 0 }, /* S I */{ 55, 56, 44, 80, 28, 15, 38, 0, 0, 0, 2, 50, 40, 78, 148, 7, 1, 7, 99, 89, 9, 76, 0, 8, 0, 3 }, /* S J */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 }, /* S K */{ 9, 0, 0, 0, 24, 0, 0, 0, 35, 0, 0, 0, 2, 0, 3, 0, 0, 1, 0, 0, 5, 0, 0, 0, 23, 0 }, /* S L */{ 42, 0, 0, 0, 35, 0, 0, 0, 29, 0, 0, 1, 0, 0, 29, 0, 0, 0, 0, 0, 13, 0, 0, 0, 2, 0 }, /* S M */{ 57, 0, 0, 0, 30, 0, 0, 0, 31, 0, 0, 0, 0, 0, 25, 0, 0, 0, 0, 0, 14, 0, 0, 0, 2, 0 }, /* S N */{ 21, 0, 0, 0, 12, 0, 0, 0, 12, 0, 0, 0, 0, 0, 19, 0, 0, 0, 0, 4, 6, 0, 0, 0, 2, 0 }, /* S O */{ 6, 4, 26, 12, 6, 10, 4, 1, 8, 1, 0, 67, 65, 190, 8, 21, 0, 71, 0, 11, 34, 6, 3, 0, 3, 1 }, /* S P */{ 63, 1, 0, 0, 116, 0, 0, 41, 82, 0, 0, 24, 0, 0, 69, 0, 0, 34, 1, 0, 16, 0, 0, 0, 3, 0 }, /* S Q */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 52, 0, 0, 0, 0, 0 }, /* S R */{ 4, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 2, 0, 0, 0, 1, 0, 3, 0, 0, 0, 0, 0 }, /* S S */{ 50, 3, 2, 0, 77, 3, 0, 4, 151, 0, 0, 5, 11, 1, 42, 2, 0, 4, 0, 4, 17, 0, 13, 0, 19, 0 }, /* S T */{ 258, 6, 4, 1, 291, 9, 1, 11, 240, 1, 0, 25, 12, 2, 205, 6, 0, 255, 3, 0, 58, 2, 7, 0, 36, 0 }, /* S U */{ 14, 38, 17, 6, 7, 11, 6, 0, 11, 0, 0, 39, 35, 37, 1, 42, 0, 71, 30, 4, 0, 0, 0, 0, 0, 4 }, /* S V */{ 0, 0, 0, 0, 5, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* S W */{ 37, 0, 0, 0, 31, 0, 0, 0, 28, 0, 0, 0, 0, 0, 21, 0, 0, 2, 0, 0, 2, 0, 0, 0, 0, 0 }, /* S X */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* S Y */{ 0, 2, 32, 1, 1, 0, 1, 0, 0, 0, 1, 18, 19, 30, 0, 2, 0, 9, 5, 1, 0, 0, 0, 0, 0, 1 }, /* S Z */{ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, /* T A */{ { 0, 74, 44, 8, 3, 9, 45, 8, 68, 0, 15, 130, 36, 181, 1, 23, 0, 128, 22, 185, 13, 11, 9, 13, 4, 0 }, /* T B */{ 7, 0, 0, 0, 4, 0, 0, 0, 4, 0, 0, 0, 0, 0, 6, 0, 0, 3, 0, 0, 3, 0, 0, 0, 0, 0 }, /* T C */{ 5, 0, 0, 0, 0, 0, 0, 112, 0, 0, 0, 2, 0, 0, 5, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0 }, /* T D */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 }, /* T E */{ 52, 9, 29, 37, 66, 9, 17, 6, 16, 0, 2, 65, 49, 185, 18, 20, 0, 588, 61, 23, 9, 9, 9, 16, 1, 0 }, /* T F */{ 6, 0, 0, 0, 1, 0, 0, 0, 5, 0, 0, 1, 0, 0, 6, 0, 0, 1, 0, 0, 24, 0, 0, 0, 0, 0 }, /* T G */{ 4, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0 }, /* T H */{ 68, 6, 1, 5, 274, 8, 1, 2, 62, 0, 1, 9, 13, 3, 90, 4, 1, 61, 8, 2, 31, 0, 16, 0, 49, 0 }, /* T I */{ 99, 35, 342, 16, 35, 45, 34, 0, 0, 0, 3, 67, 75, 183, 419, 28, 9, 18, 75, 88, 9, 128, 0, 0, 0, 2 }, /* T J */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* T K */{ 2, 0, 0, 0, 1, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 }, /* T L */{ 18, 0, 0, 0, 102, 0, 0, 0, 5, 0, 0, 2, 0, 0, 3, 0, 0, 0, 0, 0, 2, 0, 0, 0, 3, 0 }, /* T M */{ 25, 0, 0, 0, 8, 0, 0, 0, 3, 0, 0, 0, 0, 0, 11, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0 }, /* T N */{ 3, 0, 0, 0, 9, 0, 0, 0, 5, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 4, 1, 0, 0, 0, 0, 0 }, /* T O */{ 5, 6, 34, 11, 8, 7, 26, 0, 14, 0, 9, 38, 65, 238, 26, 56, 0, 319, 19, 16, 36, 3, 36, 7, 3, 2 }, /* T P */{ 2, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 2, 0, 0, 3, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0 }, /* T Q */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* T R */{ 315, 0, 0, 0, 98, 0, 0, 0, 246, 0, 0, 0, 0, 0, 201, 0, 0, 0, 0, 0, 68, 0, 1, 0, 64, 0 }, /* T S */{ 2, 2, 2, 1, 10, 2, 0, 3, 4, 0, 1, 0, 13, 0, 9, 3, 0, 0, 0, 8, 5, 2, 5, 0, 3, 0 }, /* T T */{ 44, 0, 0, 0, 154, 1, 1, 2, 53, 0, 1, 45, 0, 0, 33, 0, 0, 10, 8, 0, 4, 1, 0, 0, 25, 0 }, /* T U */{ 41, 14, 9, 41, 8, 5, 4, 0, 10, 0, 0, 19, 30, 29, 13, 10, 0, 159, 35, 22, 0, 0, 0, 1, 1, 0 }, /* T V */{ 3, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* T W */{ 14, 0, 0, 0, 12, 0, 0, 1, 23, 0, 0, 0, 0, 0, 15, 0, 0, 0, 0, 0, 2, 0, 0, 1, 0, 0 }, /* T X */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* T Y */{ 2, 1, 2, 0, 0, 0, 1, 0, 1, 0, 0, 14, 2, 0, 0, 34, 0, 14, 3, 0, 0, 0, 2, 1, 0, 0 }, /* T Z */{ 1, 0, 0, 0, 5, 0, 1, 0, 2, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0 } }, /* U A */{ { 0, 4, 7, 21, 0, 1, 5, 1, 4, 0, 5, 51, 2, 26, 0, 1, 0, 48, 9, 37, 0, 2, 4, 0, 3, 0 }, /* U B */{ 8, 18, 0, 1, 20, 0, 0, 2, 18, 2, 0, 23, 5, 0, 2, 1, 0, 10, 15, 8, 7, 2, 0, 0, 1, 0 }, /* U C */{ 10, 0, 14, 0, 23, 0, 0, 31, 29, 0, 55, 16, 0, 0, 7, 0, 0, 9, 1, 47, 5, 0, 0, 0, 2, 0 }, /* U D */{ 17, 1, 0, 24, 67, 0, 18, 0, 39, 0, 0, 4, 0, 0, 8, 0, 0, 1, 10, 0, 2, 0, 2, 0, 7, 1 }, /* U E */{ 6, 9, 0, 1, 5, 5, 4, 1, 0, 1, 0, 21, 1, 33, 1, 1, 0, 19, 22, 15, 2, 0, 0, 0, 3, 6 }, /* U F */{ 1, 0, 0, 0, 0, 58, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 3, 1, 0, 0, 0, 0, 0 }, /* U G */{ 19, 1, 0, 0, 21, 0, 34, 80, 3, 0, 0, 4, 2, 2, 6, 0, 0, 1, 1, 0, 11, 0, 0, 0, 0, 0 }, /* U H */{ 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* U I */{ 3, 2, 14, 14, 6, 0, 1, 0, 0, 0, 0, 32, 0, 31, 1, 8, 0, 19, 44, 64, 1, 4, 0, 2, 0, 3 }, /* U J */{ 1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0 }, /* U K */{ 1, 0, 0, 1, 12, 0, 0, 0, 3, 0, 1, 0, 0, 0, 1, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0 }, /* U L */{ 136, 4, 11, 11, 46, 14, 7, 0, 35, 0, 10, 67, 5, 2, 23, 16, 0, 1, 24, 73, 16, 3, 1, 0, 5, 1 }, /* U M */{ 22, 52, 3, 1, 51, 5, 0, 1, 32, 0, 0, 2, 28, 11, 8, 48, 1, 0, 8, 1, 6, 2, 0, 0, 0, 0 }, /* U N */{ 21, 6, 73, 131, 25, 5, 46, 2, 55, 0, 33, 4, 2, 13, 4, 2, 0, 2, 15, 82, 1, 0, 2, 0, 5, 0 }, /* U O */{ 0, 0, 0, 1, 0, 0, 0, 0, 3, 0, 0, 2, 0, 3, 0, 2, 0, 16, 3, 5, 29, 0, 0, 0, 2, 0 }, /* U P */{ 4, 4, 1, 2, 31, 1, 1, 14, 10, 0, 1, 13, 1, 0, 8, 24, 0, 13, 13, 24, 2, 0, 2, 0, 2, 0 }, /* U Q */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0 }, /* U R */{ 75, 27, 21, 17, 149, 8, 60, 1, 66, 2, 11, 17, 11, 55, 28, 15, 1, 51, 43, 43, 9, 15, 3, 0, 28, 1 }, /* U S */{ 31, 5, 29, 2, 105, 0, 1, 53, 64, 0, 17, 3, 0, 1, 8, 12, 1, 0, 34, 115, 6, 0, 0, 0, 4, 0 }, /* U T */{ 45, 1, 14, 1, 69, 0, 1, 55, 77, 0, 0, 8, 3, 3, 49, 0, 0, 13, 7, 51, 11, 0, 2, 0, 6, 2 }, /* U U */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* U V */{ 0, 0, 0, 0, 8, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0 }, /* U W */{ 2, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* U X */{ 0, 0, 0, 0, 4, 0, 0, 0, 2, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 5, 4, 0, 0, 0, 0, 0 }, /* U Y */{ 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0 }, /* U Z */{ 2, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 12 } }, /* V A */{ { 0, 9, 20, 8, 1, 0, 14, 2, 8, 1, 3, 69, 2, 57, 0, 1, 0, 31, 18, 36, 5, 0, 0, 0, 0, 0 }, /* V B */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* V C */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* V D */{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* V E */{ 6, 2, 5, 4, 4, 3, 6, 4, 5, 0, 1, 47, 4, 120, 3, 1, 0, 271, 46, 24, 0, 0, 1, 5, 10, 0 }, /* V F */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* V G */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* V H */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* V I */{ 37, 4, 33, 23, 21, 2, 8, 0, 2, 0, 3, 43, 0, 47, 18, 0, 0, 16, 65, 30, 5, 16, 0, 2, 0, 1 }, /* V J */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* V K */{ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* V L */{ 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* V M */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* V N */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* V O */{ 0, 0, 23, 0, 0, 0, 3, 0, 9, 0, 5, 48, 2, 6, 1, 0, 0, 10, 4, 9, 10, 1, 3, 0, 6, 0 }, /* V P */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* V Q */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* V R */{ 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* V S */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* V T */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* V U */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 13, 0, 0, 0, 0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0 }, /* V V */{ 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 }, /* V W */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* V X */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* V Y */{ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 }, /* V Z */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, /* W A */{ { 1, 4, 7, 8, 0, 3, 12, 3, 18, 0, 8, 53, 5, 20, 0, 4, 0, 100, 27, 55, 1, 9, 1, 4, 71, 1 }, /* W B */{ 6, 0, 0, 0, 7, 0, 0, 0, 1, 0, 0, 0, 0, 0, 10, 0, 0, 3, 0, 0, 1, 0, 0, 0, 0, 0 }, /* W C */{ 3, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 }, /* W D */{ 0, 0, 0, 0, 5, 0, 0, 0, 1, 0, 0, 0, 0, 0, 4, 0, 0, 3, 0, 0, 1, 0, 0, 0, 3, 0 }, /* W E */{ 30, 5, 1, 9, 33, 0, 2, 1, 19, 0, 0, 51, 0, 11, 0, 2, 0, 36, 21, 7, 0, 2, 0, 0, 2, 0 }, /* W F */{ 1, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 3, 0, 0, 4, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0 }, /* W G */{ 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* W H */{ 18, 0, 0, 0, 47, 0, 0, 0, 52, 0, 0, 0, 0, 0, 19, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0 }, /* W I */{ 0, 0, 14, 18, 5, 5, 15, 0, 0, 0, 0, 40, 2, 83, 0, 2, 0, 8, 38, 47, 0, 4, 0, 1, 0, 2 }, /* W J */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* W K */{ 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0 }, /* W L */{ 3, 0, 0, 0, 9, 0, 0, 0, 5, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 3, 0 }, /* W M */{ 8, 0, 0, 0, 5, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* W N */{ 0, 1, 1, 1, 6, 1, 1, 2, 3, 0, 0, 0, 0, 0, 0, 2, 0, 1, 10, 4, 1, 0, 2, 0, 3, 0 }, /* W O */{ 0, 1, 0, 0, 3, 1, 0, 0, 0, 0, 3, 10, 17, 8, 54, 1, 0, 121, 1, 1, 3, 2, 1, 0, 0, 0 }, /* W P */{ 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 5, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 }, /* W Q */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* W R */{ 7, 0, 0, 0, 12, 0, 0, 0, 25, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 0 }, /* W S */{ 0, 1, 1, 0, 2, 0, 0, 1, 1, 0, 1, 2, 2, 0, 5, 3, 0, 1, 1, 4, 1, 0, 2, 0, 1, 0 }, /* W T */{ 1, 0, 0, 0, 1, 0, 0, 3, 1, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 }, /* W U */{ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0 }, /* W V */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* W W */{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* W X */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* W Y */{ 2, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 1, 1, 4, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* W Z */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 } }, /* X A */{ { 0, 0, 5, 1, 0, 1, 3, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 0, 3, 6, 0, 1, 0, 0, 0, 0 }, /* X B */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 }, /* X C */{ 3, 0, 0, 0, 11, 0, 0, 3, 7, 0, 0, 7, 0, 0, 3, 0, 0, 5, 0, 0, 7, 0, 0, 0, 0, 0 }, /* X D */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* X E */{ 0, 0, 7, 1, 0, 0, 2, 0, 1, 0, 0, 2, 6, 9, 0, 0, 0, 6, 1, 1, 0, 0, 0, 0, 1, 0 }, /* X F */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* X G */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 }, /* X H */{ 7, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0 }, /* X I */{ 8, 2, 12, 8, 4, 2, 2, 0, 0, 0, 0, 2, 11, 4, 8, 0, 0, 0, 9, 2, 0, 1, 1, 0, 0, 0 }, /* X J */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* X K */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* X L */{ 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* X M */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* X N */{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* X O */{ 0, 0, 0, 1, 0, 0, 3, 0, 0, 0, 0, 1, 1, 10, 0, 1, 0, 6, 1, 5, 0, 0, 0, 0, 0, 0 }, /* X P */{ 8, 0, 0, 0, 27, 0, 0, 0, 5, 0, 0, 18, 0, 0, 12, 0, 0, 7, 0, 0, 3, 0, 0, 0, 0, 0 }, /* X Q */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 }, /* X R */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* X S */{ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* X T */{ 6, 1, 0, 0, 22, 0, 0, 1, 7, 0, 0, 0, 0, 0, 7, 0, 0, 31, 0, 0, 9, 0, 0, 0, 1, 0 }, /* X U */{ 4, 1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 1, 0, 6, 0, 0, 0, 0, 0, 0, 0, 0 }, /* X V */{ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* X W */{ 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* X X */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* X Y */{ 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0 }, /* X Z */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, /* Y A */{ { 0, 0, 5, 5, 0, 0, 1, 1, 0, 0, 2, 11, 3, 29, 1, 4, 1, 20, 1, 3, 0, 0, 3, 0, 0, 0 }, /* Y B */{ 4, 0, 0, 4, 7, 0, 0, 0, 2, 0, 0, 0, 0, 0, 9, 0, 0, 3, 0, 0, 3, 0, 0, 0, 0, 0 }, /* Y C */{ 4, 0, 0, 0, 18, 0, 0, 31, 4, 0, 0, 19, 0, 0, 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* Y D */{ 4, 1, 0, 0, 12, 0, 0, 0, 2, 0, 0, 0, 0, 2, 1, 0, 0, 37, 0, 0, 0, 0, 0, 0, 0, 0 }, /* Y E */{ 11, 3, 0, 1, 1, 1, 1, 0, 1, 0, 0, 13, 1, 6, 2, 1, 0, 19, 7, 6, 0, 1, 1, 0, 0, 0 }, /* Y F */{ 1, 0, 0, 0, 1, 0, 0, 0, 3, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0 }, /* Y G */{ 0, 0, 0, 1, 2, 0, 0, 0, 2, 0, 0, 1, 3, 1, 8, 0, 0, 3, 0, 0, 1, 0, 0, 0, 2, 0 }, /* Y H */{ 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 }, /* Y I */{ 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 2, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0 }, /* Y J */{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* Y K */{ 0, 0, 0, 0, 3, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* Y L */{ 15, 0, 0, 0, 22, 0, 0, 0, 13, 0, 1, 19, 0, 0, 11, 1, 0, 0, 2, 0, 3, 6, 0, 0, 0, 0 }, /* Y M */{ 18, 4, 1, 0, 20, 0, 0, 0, 5, 0, 0, 0, 3, 7, 11, 20, 0, 0, 0, 0, 2, 0, 0, 0, 1, 0 }, /* Y N */{ 14, 0, 11, 3, 12, 0, 3, 1, 2, 0, 0, 0, 0, 3, 11, 0, 0, 0, 0, 6, 0, 0, 0, 2, 1, 0 }, /* Y O */{ 0, 0, 2, 2, 0, 4, 6, 0, 0, 0, 5, 2, 1, 18, 0, 4, 0, 8, 4, 5, 17, 1, 1, 0, 0, 1 }, /* Y P */{ 2, 0, 0, 0, 24, 0, 0, 17, 5, 0, 0, 2, 0, 2, 21, 0, 0, 5, 7, 16, 3, 0, 0, 0, 1, 0 }, /* Y Q */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 }, /* Y R */{ 15, 0, 0, 2, 6, 1, 0, 0, 21, 0, 0, 0, 0, 2, 29, 0, 0, 2, 0, 1, 4, 0, 0, 0, 1, 0 }, /* Y S */{ 3, 1, 3, 0, 12, 0, 0, 1, 38, 0, 0, 1, 2, 0, 4, 3, 0, 0, 6, 39, 2, 0, 0, 0, 0, 0 }, /* Y T */{ 2, 0, 0, 0, 16, 0, 0, 16, 10, 0, 0, 0, 0, 0, 12, 0, 0, 0, 0, 2, 0, 0, 0, 0, 1, 0 }, /* Y U */{ 0, 0, 3, 0, 0, 0, 3, 1, 0, 0, 2, 1, 0, 1, 0, 1, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0 }, /* Y V */{ 1, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* Y W */{ 10, 0, 1, 0, 3, 0, 0, 2, 4, 0, 0, 0, 0, 0, 5, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0 }, /* Y X */{ 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* Y Y */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* Y Z */{ 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 } }, /* Z A */{ { 1, 3, 2, 0, 0, 0, 5, 1, 1, 0, 1, 4, 1, 11, 0, 1, 0, 19, 0, 0, 0, 1, 0, 0, 0, 1 }, /* Z B */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* Z C */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* Z D */{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* Z E */{ 5, 1, 2, 1, 1, 0, 0, 0, 1, 0, 1, 7, 0, 12, 0, 0, 0, 13, 3, 3, 1, 0, 1, 0, 0, 0 }, /* Z F */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* Z G */{ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* Z H */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* Z I */{ 1, 1, 2, 0, 7, 0, 5, 0, 0, 0, 0, 5, 4, 6, 1, 1, 0, 2, 1, 1, 1, 0, 0, 0, 0, 0 }, /* Z J */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* Z K */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* Z L */{ 0, 0, 0, 0, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0 }, /* Z M */{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* Z N */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* Z O */{ 3, 0, 0, 2, 2, 0, 1, 0, 7, 0, 0, 0, 3, 10, 5, 2, 0, 5, 0, 0, 1, 1, 0, 0, 0, 0 }, /* Z P */{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* Z Q */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* Z R */{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* Z S */{ 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* Z T */{ 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* Z U */{ 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0 }, /* Z V */{ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* Z W */{ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* Z X */{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* Z Y */{ 0, 1, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* Z Z */{ 7, 0, 0, 0, 1, 0, 0, 0, 7, 0, 0, 17, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 1, 0, 5, 0 } } }; static void fill( final Data data ) { int a, b, c; for ( a = 0; a < 13; a++ ) { for ( b = 0; b < 26; b++ ) { for ( c = 0; c < 26; c++ ) { data.set( a + 13, b, c, tris2[a][b][c] ); } } } } } // /** * PPG - Pronounceable Password / Pass-phrase Generator. * * <p>It is known that pass-phrases of multiple words are better than short * passwords that are hard to remember. As a result, there are pass-phrase * generators that string together a number of words. The problem with this * approach is that these phrases are still prone to dictionary attacks.</p> * * <p>One solution is to use uncommon words. It's even better to use words * that don't actually exist in dictionaries. The problem is, these words can * be too difficult to remember and the result is little more than groups of * randomized characters delimited with spaces.</p> * * One way to make these words easier to remember is to make your brain think * they are words by grouping characters into "pronounceable" tokens making * them easier to remember.</p> * * This program uses statistics on the frequency of three-letter sequences in * English to generate passwords. * * This is based on the concept developed by Tom Van Vleck, based on work * by Morrie Gasser. */ public class PPG { private static final Data DATA = new Data(); private static final String CHARACTERS = "abcdefghijklmnopqrstuvwxyz"; private static final Random random = new Random(); /** * Generate a pass phrase utilizing a set of randomized characters which form * "pronounceable" tokens. * * <p>Anecdotal evidence seems to indicate using pass-phrases of only 2 to 4 * tokens of 3 to 5 characters each. When performed correctly, many think the * result is a Latin phrase.</p> * * @param tokens Number of tokens in the phrase * @param min minimum length of the tokens in the phrase * @param max maximum length of the tokens in the phrase * * @return a pass-phrase of pronounceable, randomized characters */ public static String generate( final int tokens, final int min, final int max ) { if ( min > max ) { throw new IllegalArgumentException( "Maximum length cannot be less than minimum lenght value." ); } final StringBuilder retval = new StringBuilder(); for ( int x = 0; x < tokens; x++ ) { retval.append( generateToken( min + random.nextInt( min == max ? min : ( max + 1 ) - min ) ) ); retval.append( ' ' ); } return retval.toString(); } /** * Generate a pronounceable word of a given length. * * <p>Because this algorithm uses 3-character patterns to generate "words" so * if a length of 1 or 2 is requested, a return value of 3 characters in * length. Requesting a length of zero or less results in an empty string * being returned.</p> * * @param length length of the token to create * * @return A pronounceable token of the requested length */ public static String generateToken( final int length ) { if ( length < 1 ) { return ""; } int a, b, c; long sum = 0; int nchar; long ranno; double choice; StringBuilder password; password = new StringBuilder( length ); choice = random.nextDouble(); ranno = (long)( choice * DATA.getSigma() ); sum = 0; for ( a = 0; a < 26; a++ ) { for ( b = 0; b < 26; b++ ) { for ( c = 0; c < 26; c++ ) { sum += DATA.get( a, b, c ); if ( sum > ranno ) { password.append( CHARACTERS.charAt( a ) ); password.append( CHARACTERS.charAt( b ) ); password.append( CHARACTERS.charAt( c ) ); a = 26; b = 26; c = 26; } } } } nchar = 3; while ( nchar < length ) { a = CHARACTERS.indexOf( password.charAt( nchar - 2 ) ); b = CHARACTERS.indexOf( password.charAt( nchar - 1 ) ); sum = 0; for ( c = 0; c < 26; c++ ) { sum += DATA.get( a, b, c ); } if ( sum == 0 ) { break; } choice = random.nextDouble(); ranno = (long)( choice * sum ); sum = 0; for ( c = 0; c < 26; c++ ) { sum += DATA.get( a, b, c ); if ( sum > ranno ) { password.append( CHARACTERS.charAt( c ) ); break; } } nchar++; } return password.toString(); } public static void main( final String[] arge ) { System.out.println( PPG.generate( 1, 3, 5 ) ); System.out.println( PPG.generate( 2, 3, 5 ) ); System.out.println( PPG.generate( 3, 3, 5 ) ); System.out.println( PPG.generate( 4, 3, 5 ) ); System.out.println( PPG.generate( 5, 3, 5 ) ); System.out.println( PPG.generate( 6, 3, 5 ) ); System.out.println( PPG.generate( 7, 3, 5 ) ); System.out.println( PPG.generate( 8, 3, 5 ) ); System.out.println( PPG.generate( 9, 3, 5 ) ); System.out.println( PPG.generate( 10, 3, 5 ) ); System.out.println( PPG.generate( 11, 3, 5 ) ); System.out.println( PPG.generate( 12, 3, 5 ) ); } }
src/main/java/coyote/commons/security/PPG.java
created new pronounceable pass-phrase generator.
src/main/java/coyote/commons/security/PPG.java
created new pronounceable pass-phrase generator.
Java
mit
error: pathspec 'codeplay-io/src/main/java/com/tazine/io/scanner/ScannerDemo.java' did not match any file(s) known to git
11ccd09ea0c4cf05bd8246b9fc129df58c0edcd5
1
BookFrank/CodePlay,BookFrank/CodePlay,BookFrank/CodePlay
package com.tazine.io.scanner; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.Scanner; /** * Scanner API * * @author frank * @since 1.0.0 */ public class ScannerDemo { public static void main(String[] args) { // Scanner 是一个文本扫描器,可以使用正则表达式来分隔文本,并支持多种输入 // 最常见的用法是监控控制台输入流,等待用户输入 fileScan(); } private static void fileScan() { try { Scanner sc = new Scanner(new FileInputStream("/Users/lina/Desktop/zy.log")); sc.useDelimiter("\r"); while (sc.hasNext()){ System.out.println(sc.next()); } } catch (FileNotFoundException e) { e.printStackTrace(); } } public static void strScan() { System.out.println("Scanner默认使用空格作为分隔符"); Scanner sc = new Scanner("A B C"); while (sc.hasNext()){ System.out.println(sc.next()); } System.out.println(); System.out.println("使用 - 作为分隔符"); Scanner sc1 = new Scanner("1-2-3"); sc1.useDelimiter("-"); while (sc1.hasNext()){ System.out.println(sc1.next()); } } public static void input(){ Scanner sc = new Scanner(System.in); while (sc.hasNext()) { System.out.println(sc.next()); } } }
codeplay-io/src/main/java/com/tazine/io/scanner/ScannerDemo.java
feat (codeplay-io) : add the Scanner API practice.
codeplay-io/src/main/java/com/tazine/io/scanner/ScannerDemo.java
feat (codeplay-io) : add the Scanner API practice.
Java
mit
error: pathspec 'JURANI/app/src/main/java/com/papier/jurani/RandomTargetActivity.java' did not match any file(s) known to git
91fb6ff01b6b23134a4aa30d0dd8a24777ce2819
1
angellicaos/asde-papier,gunadarma-academy/asde-papier
package com.papier.jurani; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.TextView; /** * Created by Angellica on 3/23/2016. */ public class RandomTargetActivity extends AppCompatActivity { private int i = 0; private String [] player; private String chosenPlayer; private String chosenTask; private String chosenTarget; private TextView thePlayer; private TextView theTask; private TextView randTarget; private Button stop; private Thread runThread; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_random_target); Toolbar toolbar = (Toolbar) findViewById(R.id.random_target_toolbar); setSupportActionBar(toolbar); player = getIntent().getStringArrayExtra("player"); chosenPlayer = getIntent().getExtras().getString("chosen"); thePlayer = (TextView) findViewById(R.id.first_text); thePlayer.setText(chosenPlayer); chosenTask = getIntent().getExtras().getString("task"); theTask = (TextView) findViewById(R.id.second_text); theTask.setText(chosenTask); randTarget = (TextView) findViewById(R.id.random_target); Runnable runName = new Runnable() { @Override public void run() { while (i < player.length) { try { Thread.sleep(150); randTarget.post(new Runnable() { @Override public void run() { if (player[i].equals(chosenPlayer)) { if (i == player.length-1) { i = 0; } else { i += 1; } } else { randTarget.setText(player[i]); if (i == player.length-1) { i = 0; } else { i += 1; } } } }); } catch (InterruptedException e) { e.printStackTrace(); } } } }; runThread = new Thread(runName); runThread.start(); stop = (Button) findViewById(R.id.stop_button_random_target); stop.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { runThread.interrupt(); chosenTarget = randTarget.getText().toString(); Intent goChoose = new Intent(getApplicationContext(), ChosenTargetActivity.class); goChoose.putExtra("player", chosenPlayer); goChoose.putExtra("task", chosenTask); goChoose.putExtra("target", chosenTarget); startActivity(goChoose); finish(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_help) { Intent goToHelp = new Intent (getApplicationContext(), HelpActivity.class); startActivity(goToHelp); return true; } else if (id == R.id.action_developer) { Intent goToDev = new Intent (getApplicationContext(), PengembangActivity.class); startActivity(goToDev); return true; } else if (id == R.id.action_reset) { return true; } return super.onOptionsItemSelected(item); } }
JURANI/app/src/main/java/com/papier/jurani/RandomTargetActivity.java
Add new feature: random target activity.
JURANI/app/src/main/java/com/papier/jurani/RandomTargetActivity.java
Add new feature: random target activity.
Java
mit
error: pathspec 'src/edu/ucsb/cs56/w15/drawings/jordannguyen/advanced/BathroomDoors.java' did not match any file(s) known to git
4ad81389c7fa1e5051b513de9640043c4b752e9e
1
UCSB-CS56-W15/W15-lab04
package edu.ucsb.cs56.w15.drawings.jordannguyen.advanced; import java.awt.geom.GeneralPath; // combinations of lines and curves import java.awt.geom.AffineTransform; // translation, rotation, scale import java.awt.Shape; // general class for shapes // all imports below this line needed if you are implementing Shape import java.awt.geom.Point2D; import java.awt.geom.Line2D; import java.awt.geom.Rectangle2D; import java.awt.geom.Ellipse2D; import java.awt.Rectangle; import java.awt.geom.PathIterator; import java.awt.geom.AffineTransform; import edu.ucsb.cs56.w15.drawings.utilities.ShapeTransforms; import edu.ucsb.cs56.w15.drawings.utilities.GeneralPathWrapper; /** Bathroom Doors @author Jordan Nguyen @version for CS56, W15, UCSB, 02/12/2015 */ public class BathroomDoors extends Door implements Shape { /** Constructor for objects of class BathroomDoors. This creates two doors, one for men and one for women. @param x upper left x-coordinate of first door @param y upper left y-coordinate of first door @param width width of both doors @param height height of both doors @param distance distance between the two doors */ public BathroomDoors(double x, double y, double width, double height, double distance) { // construct the first door super(x,y,width,height); // construct the second door Door secondDoor = new Door(x+width+distance, y, width, height); // get the GeneralPath that we are going to append stuff to GeneralPath gp = this.get(); // draw a triangle on the left door for men's bathroom double triangleLength = width * .2; double topOfTriangleX = x + width * .5; double topOfTriangleY = y + height * .2; GeneralPath triangle = new GeneralPath(); triangle.moveTo(topOfTriangleX, topOfTriangleY); triangle.lineTo(topOfTriangleX - (triangleLength * .5), topOfTriangleY + triangleLength); triangle.lineTo(topOfTriangleX + (triangleLength * .5), topOfTriangleY + triangleLength); triangle.lineTo(topOfTriangleX, topOfTriangleY); // draw a circle on right door for women's bathroom double signDiameter = width * .2; double centerOfCircleX = x + width + distance + width * .5 - signDiameter/2; double centerOfCircleY = y + height * .2; Ellipse2D.Double circle = new Ellipse2D.Double(centerOfCircleX, centerOfCircleY, signDiameter, signDiameter); // add the signs to the doors GeneralPath bothDoors = this.get(); bothDoors.append(secondDoor, false); bothDoors.append(triangle, false); bothDoors.append(circle, false); } }
src/edu/ucsb/cs56/w15/drawings/jordannguyen/advanced/BathroomDoors.java
finished BathroomDoors.java class
src/edu/ucsb/cs56/w15/drawings/jordannguyen/advanced/BathroomDoors.java
finished BathroomDoors.java class
Java
mit
error: pathspec 'src/edu/cornell/mannlib/vitro/webapp/servlet/setup/ContentModelSetup.java' did not match any file(s) known to git
d8be09ac0216fc5a5e36f5e9dece496042d1e8a8
1
Brown-University-Library/rab,Brown-University-Library/rab,Brown-University-Library/rab
/* $This file is distributed under the terms of the license in /doc/license.txt$ */ package edu.cornell.mannlib.vitro.webapp.servlet.setup; import static edu.cornell.mannlib.vitro.webapp.dao.jena.WebappDaoFactorySDB.SDBDatasetMode.ASSERTIONS_ONLY; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.hp.hpl.jena.ontology.OntModel; import com.hp.hpl.jena.query.Dataset; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.ResIterator; import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.shared.Lock; import com.hp.hpl.jena.util.ResourceUtils; import com.hp.hpl.jena.util.iterator.ClosableIterator; import com.hp.hpl.jena.vocabulary.RDF; import edu.cornell.mannlib.vitro.webapp.dao.ModelAccess; import edu.cornell.mannlib.vitro.webapp.dao.ModelAccess.FactoryID; import edu.cornell.mannlib.vitro.webapp.dao.ModelAccess.ModelID; import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary; import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory; import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactoryConfig; import edu.cornell.mannlib.vitro.webapp.dao.jena.ModelSynchronizer; import edu.cornell.mannlib.vitro.webapp.dao.jena.OntModelSelector; import edu.cornell.mannlib.vitro.webapp.dao.jena.RDFServiceDataset; import edu.cornell.mannlib.vitro.webapp.dao.jena.WebappDaoFactorySDB; import edu.cornell.mannlib.vitro.webapp.rdfservice.RDFService; import edu.cornell.mannlib.vitro.webapp.rdfservice.RDFServiceFactory; import edu.cornell.mannlib.vitro.webapp.rdfservice.adapters.VitroModelFactory; import edu.cornell.mannlib.vitro.webapp.rdfservice.impl.RDFServiceUtils; import edu.cornell.mannlib.vitro.webapp.startup.StartupStatus; /** * Sets up the content models, OntModelSelectors and webapp DAO factories. */ public class ContentModelSetup extends JenaDataSourceSetupBase implements javax.servlet.ServletContextListener { private static final Log log = LogFactory.getLog(ContentModelSetup.class); @Override public void contextInitialized(ServletContextEvent sce) { ServletContext ctx = sce.getServletContext(); StartupStatus ss = StartupStatus.getBean(ctx); long begin = System.currentTimeMillis(); setUpJenaDataSource(ctx); ss.info(this, secondsSince(begin) + " seconds to set up models and DAO factories"); } private void setUpJenaDataSource(ServletContext ctx) { RDFServiceFactory rdfServiceFactory = RDFServiceUtils.getRDFServiceFactory(ctx); RDFService rdfService = rdfServiceFactory.getRDFService(); Dataset dataset = new RDFServiceDataset(rdfService); setStartupDataset(dataset, ctx); OntModel applicationMetadataModel = createdMemoryMappedModel(dataset, JENA_APPLICATION_METADATA_MODEL, "application metadata model"); if (applicationMetadataModel.size()== 0) { JenaDataSourceSetupBase.thisIsFirstStartup(); } ModelAccess models = ModelAccess.on(ctx); OntModel baseABoxModel = createNamedModelFromDataset(dataset, JENA_DB_MODEL); OntModel inferenceABoxModel = createNamedModelFromDataset(dataset, JENA_INF_MODEL); OntModel baseTBoxModel = createdMemoryMappedModel(dataset, JENA_TBOX_ASSERTIONS_MODEL, "tbox assertions"); OntModel inferenceTBoxModel = createdMemoryMappedModel(dataset, JENA_TBOX_INF_MODEL, "tbox inferences"); OntModel unionABoxModel = VitroModelFactory.createUnion(baseABoxModel, inferenceABoxModel); OntModel unionTBoxModel = VitroModelFactory.createUnion(baseTBoxModel, inferenceTBoxModel); if (isFirstStartup()) { initializeApplicationMetadata(ctx, applicationMetadataModel); RDFFilesLoader.loadFirstTimeFiles(ctx, "abox", baseABoxModel, true); RDFFilesLoader.loadFirstTimeFiles(ctx, "tbox", baseTBoxModel, true); } else { checkForNamespaceMismatch( applicationMetadataModel, ctx ); } RDFFilesLoader.loadEveryTimeFiles(ctx, "abox", baseABoxModel); RDFFilesLoader.loadEveryTimeFiles(ctx, "tbox", baseTBoxModel); log.info("Setting up full models"); OntModel baseFullModel = VitroModelFactory.createUnion(baseABoxModel, baseTBoxModel); OntModel inferenceFullModel = VitroModelFactory.createUnion(inferenceABoxModel, inferenceTBoxModel); OntModel unionFullModel = VitroModelFactory.createOntologyModel(dataset.getDefaultModel()); models.setOntModel(ModelID.APPLICATION_METADATA, applicationMetadataModel); models.setOntModel(ModelID.BASE_ABOX, baseABoxModel); models.setOntModel(ModelID.BASE_TBOX, baseTBoxModel); models.setOntModel(ModelID.BASE_FULL, baseFullModel); models.setOntModel(ModelID.INFERRED_ABOX, inferenceABoxModel); models.setOntModel(ModelID.INFERRED_TBOX, inferenceTBoxModel); models.setOntModel(ModelID.INFERRED_FULL, inferenceFullModel); models.setOntModel(ModelID.UNION_ABOX, unionABoxModel); models.setOntModel(ModelID.UNION_TBOX, unionTBoxModel); models.setOntModel(ModelID.UNION_FULL, unionFullModel); log.info("Setting up DAO factories"); WebappDaoFactoryConfig config = new WebappDaoFactoryConfig(); config.setDefaultNamespace(getDefaultNamespace(ctx)); OntModelSelector baseOms = models.getBaseOntModelSelector(); WebappDaoFactory baseWadf = new WebappDaoFactorySDB(rdfService, baseOms, config, ASSERTIONS_ONLY); ModelAccess.on(ctx).setWebappDaoFactory(FactoryID.BASE, baseWadf); ModelAccess.on(ctx).setWebappDaoFactory(FactoryID.UNFILTERED_BASE, baseWadf); OntModelSelector unionOms = models.getUnionOntModelSelector(); WebappDaoFactory wadf = new WebappDaoFactorySDB(rdfService, unionOms, config); ModelAccess.on(ctx).setWebappDaoFactory(FactoryID.UNION, wadf); ModelAccess.on(ctx).setWebappDaoFactory(FactoryID.UNFILTERED_UNION, wadf); log.info("Model makers set up"); ctx.setAttribute("defaultNamespace", getDefaultNamespace(ctx)); } private OntModel createNamedModelFromDataset(Dataset dataset, String name) { return VitroModelFactory.createOntologyModel(dataset.getNamedModel(name)); } private OntModel createdMemoryMappedModel(Dataset dataset, String name, String label) { try { Model dbModel = dataset.getNamedModel(name); OntModel memoryModel = VitroModelFactory.createOntologyModel(); if (dbModel != null) { long begin = System.currentTimeMillis(); log.info("Copying cached " + label + " into memory"); memoryModel.add(dbModel); log.info(secondsSince(begin) + " seconds to load " + label); memoryModel.getBaseModel().register(new ModelSynchronizer(dbModel)); } return memoryModel; } catch (Throwable e) { throw new RuntimeException("Unable to load " + label + " from DB", e); } } private long secondsSince(long startTime) { return (System.currentTimeMillis() - startTime) / 1000; } /* ===================================================================== */ /** * We need to read the RDF files and change the Portal from a blank node to * one with a URI in the default namespace. * * Do this before adding the data to the RDFService-backed model, to avoid * warnings about editing a blank node. */ private void initializeApplicationMetadata(ServletContext ctx, OntModel applicationMetadataModel) { OntModel temporaryAMModel = VitroModelFactory.createOntologyModel(); RDFFilesLoader.loadFirstTimeFiles(ctx, "applicationMetadata", temporaryAMModel, true); setPortalUriOnFirstTime(temporaryAMModel, ctx); applicationMetadataModel.add(temporaryAMModel); } /** * If we are loading the application metadata for the first time, set the * URI of the Portal based on the default namespace. */ private void setPortalUriOnFirstTime(OntModel model, ServletContext ctx) { // Only a single portal is permitted in the initialization data Resource portalResource = null; ClosableIterator<Resource> portalResIt = model .listSubjectsWithProperty(RDF.type, model.getResource(VitroVocabulary.PORTAL)); try { if (portalResIt.hasNext()) { Resource portalRes = portalResIt.next(); if (portalRes.isAnon()) { portalResource = portalRes; } } } finally { portalResIt.close(); } if (portalResource != null) { ResourceUtils.renameResource(portalResource, getDefaultNamespace(ctx) + "portal1"); } } /** * If we find a "portal1" portal (and we should), its URI should use the * default namespace. */ private void checkForNamespaceMismatch(OntModel model, ServletContext ctx) { String expectedNamespace = getDefaultNamespace(ctx); List<Resource> portals = getPortal1s(model); if(!portals.isEmpty() && noPortalForNamespace( portals, expectedNamespace)) { // There really should be only one portal 1, but if there happen to // be multiple, just arbitrarily pick the first in the list. Resource portal = portals.get(0); String oldNamespace = portal.getNameSpace(); renamePortal(portal, expectedNamespace, model); StartupStatus ss = StartupStatus.getBean(ctx); ss.warning(this, "\nThe default namespace has been changed \n" + "from " + oldNamespace + "\nto " + expectedNamespace + ".\n" + "The application will function normally, but " + "any individuals in the \n" + oldNamespace + " " + "namespace will need to have their URIs \n" + "changed in order to be served as linked data. " + "You can use the Ingest Tools \nto change the " + "URIs for a batch of resources."); } } private List<Resource> getPortal1s(Model model) { List<Resource> portals = new ArrayList<Resource>(); try { model.enterCriticalSection(Lock.READ); ResIterator portalIt = model.listResourcesWithProperty( RDF.type, PORTAL); while (portalIt.hasNext()) { Resource portal = portalIt.nextResource(); if ("portal1".equals(portal.getLocalName())) { portals.add(portal); } } } finally { model.leaveCriticalSection(); } return portals; } private boolean noPortalForNamespace(List<Resource> portals, String expectedNamespace) { for (Resource portal : portals) { if(expectedNamespace.equals(portal.getNameSpace())) { return false; } } return true; } private void renamePortal(Resource portal, String namespace, Model model) { model.enterCriticalSection(Lock.WRITE); try { ResourceUtils.renameResource(portal, namespace + portal.getLocalName()); } finally { model.leaveCriticalSection(); } } /* ===================================================================== */ @Override public void contextDestroyed(ServletContextEvent sce) { // Nothing to do. } }
src/edu/cornell/mannlib/vitro/webapp/servlet/setup/ContentModelSetup.java
Add default ContentModelSetup
src/edu/cornell/mannlib/vitro/webapp/servlet/setup/ContentModelSetup.java
Add default ContentModelSetup
Java
mit
error: pathspec 'scaffold-spring/rabbit/src/main/java/com/andyadc/scaffold/springrabbit/MQConfig.java' did not match any file(s) known to git
5f0661ba7a7e71773231d06bb867f6e08074cba3
1
andyadc/scaffold,andyadc/scaffold
package com.andyadc.scaffold.springrabbit; import org.springframework.context.annotation.Configuration; /** * @author andy.an * @since 2017/11/13 */ @Configuration public class MQConfig { }
scaffold-spring/rabbit/src/main/java/com/andyadc/scaffold/springrabbit/MQConfig.java
MQConfig
scaffold-spring/rabbit/src/main/java/com/andyadc/scaffold/springrabbit/MQConfig.java
MQConfig
Java
mit
error: pathspec 'aoj/introduction/IntroductiionToAlgorithmsAndDataStructures/1_2_D_Shell_Sort/Main.java' did not match any file(s) known to git
9a377d69cbc503ed8f6f66e8cf545387aa292ce0
1
KoKumagai/exercises,KoKumagai/exercises,KoKumagai/exercises
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] A = new int[n]; for (int i = 0; i < n; i++) { A[i] = sc.nextInt(); } shellSort(A); } private static int insertionSort(int[] A, int g) { int cnt = 0; for (int i = g; i < A.length; i++) { int key = A[i]; int j = i - g; while (j >= 0 && A[j] > key) { A[j + g] = A[j]; j -= g; cnt++; } A[j + g] = key; } return cnt; } private static void shellSort(int[] A) { int m = 0; int tmp = 1; while (true) { if (tmp > A.length) { break; } tmp = 3 * tmp + 1; m++; } System.out.println(m); int[] G = new int[m]; int h = 1; for (int i = 0; ; ) { if (h > A.length) { break; } G[i] = h; h = 3 * h + 1; i++; } int cnt = 0; for (int i = G.length - 1; i >= 0; i--) { if (i != 0) { System.out.print(G[i] + " "); } else { System.out.println(G[i]); } cnt += insertionSort(A, G[i]); } System.out.println(cnt); for (int i = 0; i < A.length; i++) { System.out.println(A[i]); } } }
aoj/introduction/IntroductiionToAlgorithmsAndDataStructures/1_2_D_Shell_Sort/Main.java
ALDS1_2_D : Shell Sort
aoj/introduction/IntroductiionToAlgorithmsAndDataStructures/1_2_D_Shell_Sort/Main.java
ALDS1_2_D : Shell Sort
Java
mit
error: pathspec 'src/main/java/com/sixdimensions/wcm/primer/internal/ResourceEventListenerComponent.java' did not match any file(s) known to git
7ea68e7f318d466c383f9b9bc7d9279785629daa
1
SixDimensions/Service-Primer
package com.sixdimensions.wcm.primer.internal; import java.util.Dictionary; import java.util.Hashtable; import org.osgi.framework.BundleContext; import org.osgi.service.event.Event; import org.osgi.service.event.EventConstants; import org.osgi.service.event.EventHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ResourceEventListenerComponent { private static final Logger log = LoggerFactory .getLogger(ResourceEventListenerComponent.class); protected void registerEventLisener(BundleContext bundleContext) { String[] topics = new String[] { "org/apache/sling/api/resource/Resource/*" }; Dictionary<Object, Object[]> props = new Hashtable<Object, Object[]>(); props.put(EventConstants.EVENT_TOPIC, topics); bundleContext.registerService(EventHandler.class.getName(), new EventHandler() { public void handleEvent(Event event) { String title = (String) event.getProperty("title"); String path = (String) event.getProperty("path"); log.info("Title: {} Path: {}", new Object[] { title, path }); } }, props); } }
src/main/java/com/sixdimensions/wcm/primer/internal/ResourceEventListenerComponent.java
Adding the sample component
src/main/java/com/sixdimensions/wcm/primer/internal/ResourceEventListenerComponent.java
Adding the sample component
Java
mit
error: pathspec 'instrumentation/src/test/java/eu/mikroskeem/test/shuriken/instrumentation/URLClassLoaderToolsTester.java' did not match any file(s) known to git
bda9749a6aef794b13f9aba7d170575ba58657e3
1
mikroskeem/Shuriken
package eu.mikroskeem.test.shuriken.instrumentation; import eu.mikroskeem.shuriken.common.ToURL; import eu.mikroskeem.shuriken.instrumentation.ClassLoaderTools; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.io.FileOutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLClassLoader; import java.nio.channels.Channels; import java.nio.channels.FileChannel; import java.nio.file.Files; import java.nio.file.Path; /** * @author Mark Vainomaa */ public class URLClassLoaderToolsTester { @Test public void testUCLTools() throws Exception { //URLClassLoader ucl = new URLClassLoader(new URL[0]); URLClassLoader ucl = (URLClassLoader) ClassLoader.getSystemClassLoader(); ClassLoaderTools.URLClassLoaderTools uclTools = new ClassLoaderTools.URLClassLoaderTools(ucl); Assertions.assertThrows(IllegalStateException.class, () -> uclTools.addURL(new URL("https://mikroskeem.eu/stuff/fernflower.jar")) ); uclTools.addURL(ToURL.to(downloadTestJar())); uclTools.resetCache(); } private Path downloadTestJar() throws Exception { /* aopalliance library for test, hopefully this won't disappear */ String url = "https://repo.maven.apache.org/maven2/aopalliance/aopalliance/1.0/aopalliance-1.0.jar"; HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); Path file = Files.createTempFile("testlib", ".jar"); try(FileChannel fc = new FileOutputStream(file.toFile()).getChannel()) { fc.transferFrom( Channels.newChannel(connection.getInputStream()), 0, Long.MAX_VALUE ); } return file; } }
instrumentation/src/test/java/eu/mikroskeem/test/shuriken/instrumentation/URLClassLoaderToolsTester.java
Add URLClassLoaderTools tests
instrumentation/src/test/java/eu/mikroskeem/test/shuriken/instrumentation/URLClassLoaderToolsTester.java
Add URLClassLoaderTools tests
Java
epl-1.0
error: pathspec 'JavaSE/day08/ReaderAndWriter.java' did not match any file(s) known to git
47acd0d14421c324266e86977e685e7abdd18fd1
1
planetarianZero/JavaStudy
package day08; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.Scanner; /** * 字符转换流 * 字符流的读写单位为字符,字符流都是高级流,虽然以字符为单位读写数据,但实际底层还是读写字节, * 只是从字节与字符的转换工作交给了字符流来完成。 * java.io.Reader:字符输入流的顶级父类 * java.io.Writer:字符输出流的顶级父类 * * 大多数字符流只能处理其他字符流,而低级流又是字节流,这就导致字符流不能处理字节流的问题,转换流相当于 * 是一个转换器的作用,它们可以将字节流先转变为字符流,这样其他的字符流就可以处理了。 * * 缓冲字符流 * BufferedWriter,BufferedReader * 特点是可以按行读写字符串。 * BufferedReader:缓冲字符输入流,特点是按行读取字符串。 * * java.io.PrintWriter * 具有自动行刷新的缓冲字符输出流,创建该对象时,其内部一定会创建BufferedWriter作为缓冲功能的叠加。 * 提供了多种构造方法,其中有两个可以直接对文件进行写出操作的构造方法。 * String readLin() * 连续读取若干字符,读到换行符为止,但返回的字符串不包含换行符。读到文件末尾返回null。 * * PrintWriter(File file) * PrintWriter(String path) * * PrinterWriter也提供了可以处理其他流的构造方法,提供的方法可以传入字节流,也可以处理字符流,并且当使用 * 这类构造方法时,可以再传入第二个参数,该参数为Boolean值,当该值为true时,则具有了自动行刷新功能。 * 只有调用println方法时,才能实现自动行刷新。即flush()方法。 * * @author 87188 * */ public class ReaderAndWriter { /** * @param args */ public static void main(String[] args) { //Demo(); //Demo2(); //Demo3(); //Demo4(); Demo5(); } public static void Demo() { try { FileOutputStream fos = new FileOutputStream("osw.txt"); //OutputStreamWriter osw=new OutputStreamWriter(fos); OutputStreamWriter osw=new OutputStreamWriter(fos,"UTF-8"); try { osw.write("123456"); osw.write("asdfgh"); System.out.println("Success"); osw.close(); } catch (IOException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } } catch (Exception e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } } public static void Demo2() { int d=-1; try { FileInputStream fis=new FileInputStream("osw.txt"); InputStreamReader isr=new InputStreamReader(fis,"UTF-8"); while((d=isr.read())!=-1) { System.out.print((char)d); } isr.close(); } catch (Exception e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } } public static void Demo3() { try { FileOutputStream fos=new FileOutputStream("pw1.txt"); OutputStreamWriter osw=new OutputStreamWriter(fos,"UTF-8"); PrintWriter pw=new PrintWriter(osw); pw.println("12345"); pw.println("asdfg"); System.out.println("Success"); pw.close(); } catch (Exception e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } } public static void Demo4() { String fileName; String text=null; Scanner sc=new Scanner(System.in); fileName=sc.next(); try { FileOutputStream fos=new FileOutputStream(fileName+".txt"); OutputStreamWriter osw=new OutputStreamWriter(fos,"UTF-8"); PrintWriter pw=new PrintWriter(osw,true); while(true) { text=sc.nextLine(); if(text.equals("exit")) { break; } pw.println(text); } System.out.println("Fin"); pw.close(); }catch(Exception e) { e.printStackTrace(); } } public static void Demo5() { String line=null; try { FileInputStream fis=new FileInputStream("src/day08/ReaderAndWriter.java"); InputStreamReader isr=new InputStreamReader(fis); BufferedReader br=new BufferedReader(isr); while((line=br.readLine())!=null) { System.out.println(line); } br.close(); } catch (Exception e) { e.printStackTrace(); } } }
JavaSE/day08/ReaderAndWriter.java
Create ReaderAndWriter.java
JavaSE/day08/ReaderAndWriter.java
Create ReaderAndWriter.java
Java
epl-1.0
error: pathspec 'src/main/java/org/jtrfp/trcl/objects/SmartObject.java' did not match any file(s) known to git
fdac622333e45167dc700d42c3484a87419e69b4
1
jtrfp/terminal-recall,jtrfp/terminal-recall,jtrfp/terminal-recall
/******************************************************************************* * This file is part of TERMINAL RECALL * Copyright (c) 2012, 2013 Chuck Ritola. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/gpl.html * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the COPYING and CREDITS files for more details. * * Contributors: * chuck - initial API and implementation ******************************************************************************/ package org.jtrfp.trcl.objects; import org.apache.commons.math3.geometry.euclidean.threed.Vector3D; import org.jtrfp.trcl.Model; import org.jtrfp.trcl.TickListener; import org.jtrfp.trcl.World; import org.jtrfp.trcl.ai.ObjectBehavior; public abstract class SmartObject extends WorldObject implements TickListener { private long lastTimeInMillis=-1;//Makes sure if this is read without being set, it's very obvious. private long timePassedSinceLastTick=0L; //private ObjectBehavior behavior; public SmartObject(Model model, ObjectBehavior behavior, World world) { super(world.getTr(),model); if(behavior!=null){setBehavior(behavior);behavior.setParent(this);} world.addTickListener(this); }//end constructor() protected boolean translate(){return true;} @Override public void tick(long time) {if(lastTimeInMillis==-1) {//First time <3 <3 <3 } else {//Been around... timePassedSinceLastTick=time-lastTimeInMillis; if(getBehavior()!=null)getBehavior().tick(time); } lastTimeInMillis=time; }//end tick() @Override public void proposeCollision(WorldObject other) {if(this.getBehavior()!=null)this.getBehavior().proposeCollision(other);} @Override public String toString() {return "MobileObject x="+position.getX()+" y="+position.getY()+" z="+position.getZ();} /** * @return the lastTimeInMillis */ public long getLastTimeInMillis() {return lastTimeInMillis;} /** * @param lastTimeInMillis the lastTimeInMillis to set */ public void setLastTimeInMillis(long lastTimeInMillis) {this.lastTimeInMillis = lastTimeInMillis;} /** * @return the timePassedSinceLastTick */ public long getTimePassedSinceLastTick() {return timePassedSinceLastTick;} }//end MobileObject
src/main/java/org/jtrfp/trcl/objects/SmartObject.java
Added timePassedSinceLastTick
src/main/java/org/jtrfp/trcl/objects/SmartObject.java
Added timePassedSinceLastTick
Java
epl-1.0
error: pathspec 'src/main/java/org/jtrfp/trcl/core/DebugStatesMenuItemFactory.java' did not match any file(s) known to git
57c736338adf784777f9cfb1f64cf8f39ed6b2b2
1
jtrfp/terminal-recall,jtrfp/terminal-recall,jtrfp/terminal-recall
/******************************************************************************* * This file is part of TERMINAL RECALL * Copyright (c) 2016 Chuck Ritola * Part of the jTRFP.org project * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/gpl.html * * Contributors: * chuck - initial API and implementation ******************************************************************************/ package org.jtrfp.trcl.core; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import org.jtrfp.trcl.gui.MenuSystem; import org.jtrfp.trcl.gui.Reporter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class DebugStatesMenuItemFactory { private static final String [] MENU_PATH = new String[]{"Debug","Debug States..."}; private Reporter reporter; private TR tr; private ActionListener menuItemListener; private void proposeInit(){ if(getReporter() == null || getTr() == null || getMenuItemListener() != null) return; setMenuItemListener(new MenuItemListener()); final MenuSystem ms = getTr().getMenuSystem(); ms.addMenuItem(MENU_PATH); ms.addMenuItemListener(menuItemListener, MENU_PATH); ms.setMenuItemEnabled(true, MENU_PATH); }//end proposeInit() private class MenuItemListener implements ActionListener { @Override public void actionPerformed(ActionEvent evt) { final Reporter rep = getReporter(); rep.setVisible(true); } }//end MenuItemListener public Reporter getReporter() { return reporter; } @Autowired public void setReporter(Reporter reporter) { this.reporter = reporter; proposeInit(); } public TR getTr() { return tr; } @Autowired public void setTr(TR tr) { this.tr = tr; proposeInit(); } public ActionListener getMenuItemListener() { return menuItemListener; } public void setMenuItemListener(ActionListener menuItemListener) { this.menuItemListener = menuItemListener; } }//end DebugStatesMenuItemFactory
src/main/java/org/jtrfp/trcl/core/DebugStatesMenuItemFactory.java
⟴Reintroduce debug states as Spring Component.
src/main/java/org/jtrfp/trcl/core/DebugStatesMenuItemFactory.java
⟴Reintroduce debug states as Spring Component.
Java
lgpl-2.1
fatal: invalid reference: FETCH_HEAD^
7b2a7cd849c39303a9d44f15e6d7819304800ed7
128
simoc/mapyrus,simoc/mapyrus,simoc/mapyrus
/** * Wrapper around a Reader to read from a file, whilst expanding any included files. */ /* * $Id$ */ import java.io.*; import java.net.URL; import java.net.MalformedURLException; import java.util.LinkedList; import java.lang.String; import java.util.StringTokenizer; import java.util.NoSuchElementException; class Preprocessor { private static final String INCLUDE_KEYWORD = "include"; /* * Files we are reading from and their names. * Built up as a stack as we include nested files. */ private LinkedList mFileStack; private LinkedList mFilenameStack; /* * Last character read. */ private int mLastChar; private int mPushedChar; private boolean mCharPushedBack; /** * Create new user input producer. * @param in is a source to read input from. * @param filename is the name of the file being read. */ public Preprocessor(Reader in, String filename) { mFileStack = new LinkedList(); mFilenameStack = new LinkedList(); mFileStack.add(new LineNumberReader(in)); mFilenameStack.add(filename); mLastChar = '\n'; mCharPushedBack = false; } /* * Open new file to read from and push it on stack of files being read. */ private void openIncludedFile(String filename) throws IOException { BufferedReader in; /* * Open file being included and start read from it instead. */ try { /* * Try filename as an absolute URL. */ URL url = new URL(filename); InputStream urlStream = url.openStream(); in = new BufferedReader(new InputStreamReader(urlStream)); } catch (MalformedURLException e) { /* * Well, maybe it is just a regular file. */ in = new BufferedReader(new FileReader(filename)); } mFileStack.add(new LineNumberReader(in)); mFilenameStack.add(filename); } /** * Reads next character. * Blocks if another character is not available. * @return next character from wherever user input is coming from, or -1 * if at EOF. */ public int read() throws IOException, GfException { int c; LineNumberReader in; if (mCharPushedBack) { /* * Return the character that was pushed back. */ mCharPushedBack = false; return(mPushedChar); } in = (LineNumberReader)(mFileStack.getLast()); c = in.read(); /* * If we just read a newline then check if next line is an include * line. */ if (mLastChar == '\n') { /* * Read whole line and see if we should include another file. */ in.mark(2048); Character cs = new Character((char)c); String nextLine = cs.toString() + in.readLine(); StringTokenizer st = new StringTokenizer(nextLine); if (st.hasMoreTokens()) { String keyword = st.nextToken(); keyword.toLowerCase(); if (INCLUDE_KEYWORD.equals(keyword)) { if (st.hasMoreTokens()) { openIncludedFile(st.nextToken()); return(read()); } else { throw new GfException("Missing include filename at " + getCurrentFilenameAndLine()); } } } /* * It's not an include line so rewind back to the * character we just read. */ in.reset(); } if (c == -1) { /* * Got end-of-file. Continue reading any file that included * this one. */ in.close(); mFileStack.removeLast(); mFilenameStack.removeLast(); if (mFileStack.size() > 0) { return(read()); } } mLastChar = c; return(c); } /* * Pushes a single character that was read back to the reader. */ public void unread(int c) { mPushedChar = c; mCharPushedBack = true; } /** * Returns line number and name of file being read. * @retval the name of the file currently being read. */ public String getCurrentFilenameAndLine() { String s = (String)mFilenameStack.getLast(); if (s == null) return(""); else { LineNumberReader in; try { in = (LineNumberReader)mFileStack.getLast(); s.concat(":" + in.getLineNumber()); } catch(NoSuchElementException e) { } } return(s); } }
src/org/mapyrus/Preprocessor.java
Initial revision
src/org/mapyrus/Preprocessor.java
Initial revision
Java
lgpl-2.1
error: pathspec 'abixen-platform-common/src/main/java/com/abixen/platform/core/converter/AbstractConverter.java' did not match any file(s) known to git
a514b4a05d754b0a149107abc60a03b881cc284f
1
asteriskbimal/abixen-platform,konradkwisniewski/abixen-platform,rbharath26/abixen-platform,cloudowski/abixen-platform,cloudowski/abixen-platform,abixen/abixen-platform,cloudowski/abixen-platform,rajsingh8220/abixen-platform,asteriskbimal/abixen-platform,rajsingh8220/abixen-platform,abixen/abixen-platform,asteriskbimal/abixen-platform,rajsingh8220/abixen-platform,abixen/abixen-platform,rajsingh8220/abixen-platform,rbharath26/abixen-platform,abixen/abixen-platform,konradkwisniewski/abixen-platform,konradkwisniewski/abixen-platform,rbharath26/abixen-platform,asteriskbimal/abixen-platform,rbharath26/abixen-platform,konradkwisniewski/abixen-platform,cloudowski/abixen-platform
/** * Copyright (c) 2010-present Abixen Systems. All rights reserved. * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. */ package com.abixen.platform.core.converter; import java.util.*; public abstract class AbstractConverter<Source, Target> { public final List<Target> convertToList(Collection<Source> sources, Map<String, Object> parameters) { List<Target> targets = new ArrayList<>(sources.size()); for (Source source : sources) { targets.add(convert(source, parameters)); } return targets; } public List<Target> convertToList(Collection<Source> sources) { return convertToList(sources, Collections.emptyMap()); } public Target convert(Source source) { return convert(source, Collections.emptyMap()); } public abstract Target convert(Source source, Map<String, Object> parameters); }
abixen-platform-common/src/main/java/com/abixen/platform/core/converter/AbstractConverter.java
Created a converter concept between domain and dto. Resolved #825
abixen-platform-common/src/main/java/com/abixen/platform/core/converter/AbstractConverter.java
Created a converter concept between domain and dto. Resolved #825
Java
apache-2.0
4ac2fc8f7d93500486eb7bb50efc6ee8da35a3b4
0
samthor/intellij-community,blademainer/intellij-community,ivan-fedorov/intellij-community,semonte/intellij-community,FHannes/intellij-community,fitermay/intellij-community,kool79/intellij-community,petteyg/intellij-community,allotria/intellij-community,blademainer/intellij-community,fitermay/intellij-community,xfournet/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,adedayo/intellij-community,apixandru/intellij-community,vladmm/intellij-community,vvv1559/intellij-community,SerCeMan/intellij-community,ahb0327/intellij-community,akosyakov/intellij-community,ftomassetti/intellij-community,holmes/intellij-community,fengbaicanhe/intellij-community,TangHao1987/intellij-community,vladmm/intellij-community,gnuhub/intellij-community,allotria/intellij-community,caot/intellij-community,signed/intellij-community,alphafoobar/intellij-community,pwoodworth/intellij-community,consulo/consulo,asedunov/intellij-community,orekyuu/intellij-community,akosyakov/intellij-community,fengbaicanhe/intellij-community,Lekanich/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,xfournet/intellij-community,asedunov/intellij-community,holmes/intellij-community,jagguli/intellij-community,kdwink/intellij-community,TangHao1987/intellij-community,petteyg/intellij-community,ol-loginov/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,da1z/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,fitermay/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,izonder/intellij-community,Lekanich/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,Distrotech/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,blademainer/intellij-community,retomerz/intellij-community,consulo/consulo,samthor/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,slisson/intellij-community,supersven/intellij-community,gnuhub/intellij-community,robovm/robovm-studio,petteyg/intellij-community,muntasirsyed/intellij-community,robovm/robovm-studio,ahb0327/intellij-community,salguarnieri/intellij-community,TangHao1987/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,caot/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,amith01994/intellij-community,ernestp/consulo,fengbaicanhe/intellij-community,izonder/intellij-community,vladmm/intellij-community,ivan-fedorov/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,ryano144/intellij-community,vvv1559/intellij-community,amith01994/intellij-community,Lekanich/intellij-community,robovm/robovm-studio,holmes/intellij-community,samthor/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,izonder/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,kdwink/intellij-community,ryano144/intellij-community,kool79/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,alphafoobar/intellij-community,kool79/intellij-community,MER-GROUP/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,ivan-fedorov/intellij-community,tmpgit/intellij-community,da1z/intellij-community,retomerz/intellij-community,holmes/intellij-community,fnouama/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,supersven/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,orekyuu/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,kool79/intellij-community,adedayo/intellij-community,signed/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,apixandru/intellij-community,jagguli/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,Distrotech/intellij-community,fitermay/intellij-community,slisson/intellij-community,da1z/intellij-community,alphafoobar/intellij-community,allotria/intellij-community,tmpgit/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,kdwink/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,wreckJ/intellij-community,ryano144/intellij-community,tmpgit/intellij-community,diorcety/intellij-community,holmes/intellij-community,pwoodworth/intellij-community,pwoodworth/intellij-community,salguarnieri/intellij-community,petteyg/intellij-community,akosyakov/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,jagguli/intellij-community,dslomov/intellij-community,Distrotech/intellij-community,Distrotech/intellij-community,fitermay/intellij-community,ahb0327/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,consulo/consulo,fengbaicanhe/intellij-community,kdwink/intellij-community,ahb0327/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,slisson/intellij-community,pwoodworth/intellij-community,signed/intellij-community,nicolargo/intellij-community,ftomassetti/intellij-community,SerCeMan/intellij-community,amith01994/intellij-community,lucafavatella/intellij-community,caot/intellij-community,signed/intellij-community,ol-loginov/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,MER-GROUP/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,diorcety/intellij-community,caot/intellij-community,clumsy/intellij-community,kdwink/intellij-community,FHannes/intellij-community,semonte/intellij-community,FHannes/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,izonder/intellij-community,gnuhub/intellij-community,samthor/intellij-community,FHannes/intellij-community,orekyuu/intellij-community,youdonghai/intellij-community,samthor/intellij-community,gnuhub/intellij-community,fnouama/intellij-community,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,signed/intellij-community,jagguli/intellij-community,izonder/intellij-community,wreckJ/intellij-community,amith01994/intellij-community,gnuhub/intellij-community,diorcety/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,dslomov/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,apixandru/intellij-community,kdwink/intellij-community,fitermay/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,TangHao1987/intellij-community,gnuhub/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,supersven/intellij-community,TangHao1987/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,izonder/intellij-community,akosyakov/intellij-community,MichaelNedzelsky/intellij-community,supersven/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,ivan-fedorov/intellij-community,wreckJ/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,Lekanich/intellij-community,ThiagoGarciaAlves/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,muntasirsyed/intellij-community,ryano144/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,ernestp/consulo,retomerz/intellij-community,jagguli/intellij-community,amith01994/intellij-community,izonder/intellij-community,allotria/intellij-community,blademainer/intellij-community,da1z/intellij-community,gnuhub/intellij-community,vladmm/intellij-community,dslomov/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,fengbaicanhe/intellij-community,apixandru/intellij-community,alphafoobar/intellij-community,signed/intellij-community,hurricup/intellij-community,akosyakov/intellij-community,ftomassetti/intellij-community,izonder/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,Lekanich/intellij-community,slisson/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,fengbaicanhe/intellij-community,allotria/intellij-community,pwoodworth/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,consulo/consulo,orekyuu/intellij-community,vladmm/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,alphafoobar/intellij-community,michaelgallacher/intellij-community,petteyg/intellij-community,hurricup/intellij-community,supersven/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,akosyakov/intellij-community,tmpgit/intellij-community,ernestp/consulo,FHannes/intellij-community,salguarnieri/intellij-community,MER-GROUP/intellij-community,clumsy/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,kool79/intellij-community,allotria/intellij-community,adedayo/intellij-community,ibinti/intellij-community,jagguli/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,kool79/intellij-community,kool79/intellij-community,fitermay/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,ibinti/intellij-community,apixandru/intellij-community,TangHao1987/intellij-community,Distrotech/intellij-community,petteyg/intellij-community,ibinti/intellij-community,izonder/intellij-community,kool79/intellij-community,ivan-fedorov/intellij-community,muntasirsyed/intellij-community,robovm/robovm-studio,diorcety/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,SerCeMan/intellij-community,semonte/intellij-community,slisson/intellij-community,diorcety/intellij-community,semonte/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,MichaelNedzelsky/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,ernestp/consulo,samthor/intellij-community,signed/intellij-community,tmpgit/intellij-community,allotria/intellij-community,ahb0327/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,fnouama/intellij-community,xfournet/intellij-community,asedunov/intellij-community,fengbaicanhe/intellij-community,lucafavatella/intellij-community,robovm/robovm-studio,fnouama/intellij-community,SerCeMan/intellij-community,supersven/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community,fengbaicanhe/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,retomerz/intellij-community,ol-loginov/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,ahb0327/intellij-community,pwoodworth/intellij-community,gnuhub/intellij-community,MER-GROUP/intellij-community,ftomassetti/intellij-community,nicolargo/intellij-community,amith01994/intellij-community,MichaelNedzelsky/intellij-community,MER-GROUP/intellij-community,ryano144/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,adedayo/intellij-community,wreckJ/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,dslomov/intellij-community,michaelgallacher/intellij-community,Distrotech/intellij-community,tmpgit/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,SerCeMan/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,vladmm/intellij-community,fnouama/intellij-community,ibinti/intellij-community,akosyakov/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,ol-loginov/intellij-community,ahb0327/intellij-community,SerCeMan/intellij-community,adedayo/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,kdwink/intellij-community,apixandru/intellij-community,ol-loginov/intellij-community,allotria/intellij-community,holmes/intellij-community,ol-loginov/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,ivan-fedorov/intellij-community,holmes/intellij-community,ftomassetti/intellij-community,clumsy/intellij-community,fnouama/intellij-community,salguarnieri/intellij-community,SerCeMan/intellij-community,clumsy/intellij-community,apixandru/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,fnouama/intellij-community,ryano144/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,dslomov/intellij-community,signed/intellij-community,SerCeMan/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,fengbaicanhe/intellij-community,ftomassetti/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,Distrotech/intellij-community,slisson/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,semonte/intellij-community,ol-loginov/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,ryano144/intellij-community,adedayo/intellij-community,blademainer/intellij-community,caot/intellij-community,diorcety/intellij-community,gnuhub/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,petteyg/intellij-community,da1z/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,samthor/intellij-community,samthor/intellij-community,supersven/intellij-community,petteyg/intellij-community,da1z/intellij-community,petteyg/intellij-community,da1z/intellij-community,hurricup/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,caot/intellij-community,vvv1559/intellij-community,slisson/intellij-community,izonder/intellij-community,hurricup/intellij-community,jagguli/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,ibinti/intellij-community,caot/intellij-community,amith01994/intellij-community,FHannes/intellij-community,robovm/robovm-studio,muntasirsyed/intellij-community,ernestp/consulo,kool79/intellij-community,fnouama/intellij-community,holmes/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,amith01994/intellij-community,clumsy/intellij-community,caot/intellij-community,semonte/intellij-community,asedunov/intellij-community,clumsy/intellij-community,Distrotech/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,kool79/intellij-community,adedayo/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,fnouama/intellij-community,signed/intellij-community,Distrotech/intellij-community,MichaelNedzelsky/intellij-community,ol-loginov/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,signed/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,orekyuu/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,dslomov/intellij-community,robovm/robovm-studio,kdwink/intellij-community,jagguli/intellij-community,ol-loginov/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,muntasirsyed/intellij-community,amith01994/intellij-community,supersven/intellij-community,alphafoobar/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,amith01994/intellij-community,wreckJ/intellij-community,da1z/intellij-community,tmpgit/intellij-community,hurricup/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,semonte/intellij-community,allotria/intellij-community,fengbaicanhe/intellij-community,supersven/intellij-community,caot/intellij-community,TangHao1987/intellij-community,diorcety/intellij-community,clumsy/intellij-community,da1z/intellij-community,blademainer/intellij-community,xfournet/intellij-community,nicolargo/intellij-community,kool79/intellij-community,adedayo/intellij-community,hurricup/intellij-community,ibinti/intellij-community,petteyg/intellij-community,blademainer/intellij-community,retomerz/intellij-community,apixandru/intellij-community,ryano144/intellij-community,fnouama/intellij-community,robovm/robovm-studio,Lekanich/intellij-community,idea4bsd/idea4bsd,petteyg/intellij-community,adedayo/intellij-community,hurricup/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,pwoodworth/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,nicolargo/intellij-community,diorcety/intellij-community,nicolargo/intellij-community,xfournet/intellij-community,vladmm/intellij-community,amith01994/intellij-community,MichaelNedzelsky/intellij-community,ryano144/intellij-community,Distrotech/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,suncycheng/intellij-community,akosyakov/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,robovm/robovm-studio,signed/intellij-community,clumsy/intellij-community,caot/intellij-community,izonder/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,ftomassetti/intellij-community,pwoodworth/intellij-community,TangHao1987/intellij-community,ahb0327/intellij-community,supersven/intellij-community,semonte/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,consulo/consulo,salguarnieri/intellij-community,diorcety/intellij-community,FHannes/intellij-community,holmes/intellij-community,supersven/intellij-community,robovm/robovm-studio,muntasirsyed/intellij-community,orekyuu/intellij-community,ernestp/consulo,dslomov/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,ftomassetti/intellij-community,holmes/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,robovm/robovm-studio,salguarnieri/intellij-community,suncycheng/intellij-community,dslomov/intellij-community,vladmm/intellij-community,holmes/intellij-community,vladmm/intellij-community,suncycheng/intellij-community,muntasirsyed/intellij-community,diorcety/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,orekyuu/intellij-community,slisson/intellij-community,samthor/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,alphafoobar/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,pwoodworth/intellij-community,signed/intellij-community,caot/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,ol-loginov/intellij-community,retomerz/intellij-community,tmpgit/intellij-community,blademainer/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,TangHao1987/intellij-community,muntasirsyed/intellij-community,kdwink/intellij-community,ahb0327/intellij-community,ahb0327/intellij-community,SerCeMan/intellij-community,slisson/intellij-community,caot/intellij-community,ibinti/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,ibinti/intellij-community,blademainer/intellij-community,kdwink/intellij-community,adedayo/intellij-community,diorcety/intellij-community,Lekanich/intellij-community,ftomassetti/intellij-community,orekyuu/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,vladmm/intellij-community,tmpgit/intellij-community,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,consulo/consulo,SerCeMan/intellij-community,Lekanich/intellij-community,diorcety/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,allotria/intellij-community,robovm/robovm-studio,asedunov/intellij-community,adedayo/intellij-community,Lekanich/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,gnuhub/intellij-community,holmes/intellij-community,vvv1559/intellij-community,kool79/intellij-community
/* * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.options.ex; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.options.Configurable; import com.intellij.openapi.options.ConfigurableEP; import com.intellij.openapi.options.ConfigurableProvider; import com.intellij.openapi.options.OptionalConfigurable; import com.intellij.openapi.project.Project; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; /** * @author nik */ public class ConfigurableExtensionPointUtil { private final static Logger LOG = Logger.getInstance(ConfigurableExtensionPointUtil.class); private ConfigurableExtensionPointUtil() { } public static List<Configurable> buildConfigurablesList(final ConfigurableEP<Configurable>[] extensions, final Configurable[] components, @Nullable ConfigurableFilter filter) { final List<Configurable> result = new ArrayList<Configurable>(); for (Configurable component : components) { if (!isSuppressed(component, filter)) { result.add(component); } } final Map<String, ConfigurableWrapper> idToConfigurable = new HashMap<String, ConfigurableWrapper>(); for (ConfigurableEP<Configurable> ep : extensions) { final Configurable configurable = ConfigurableWrapper.wrapConfigurable(ep); if (isSuppressed(configurable, filter)) continue; if (configurable instanceof ConfigurableWrapper) { final ConfigurableWrapper wrapper = (ConfigurableWrapper)configurable; idToConfigurable.put(wrapper.getId(), wrapper); } else { // dumpConfigurable(configurablesExtensionPoint, ep, configurable); ContainerUtil.addIfNotNull(configurable, result); } } //modify configurables (append children) for (final String id : idToConfigurable.keySet()) { final ConfigurableWrapper wrapper = idToConfigurable.get(id); final String parentId = wrapper.getParentId(); if (parentId != null) { final ConfigurableWrapper parent = idToConfigurable.get(parentId); if (parent != null) { idToConfigurable.put(parentId, parent.addChild(wrapper)); } else { LOG.error("Can't find parent for " + parentId + " (" + wrapper + ")"); } } } //leave only roots (i.e. configurables without parents) for (final Iterator<String> iterator = idToConfigurable.keySet().iterator(); iterator.hasNext(); ) { final String key = iterator.next(); final ConfigurableWrapper wrapper = idToConfigurable.get(key); if (wrapper.getParentId() != null) { iterator.remove(); } } ContainerUtil.addAll(result, idToConfigurable.values()); return result; } private static boolean isSuppressed(Configurable each, ConfigurableFilter filter) { return each instanceof Configurable.Assistant || each instanceof OptionalConfigurable && !((OptionalConfigurable) each).needDisplay() || filter != null && !filter.isIncluded(each); } /* private static void dumpConfigurable(ExtensionPointName<ConfigurableEP<Configurable>> configurablesExtensionPoint, ConfigurableEP<Configurable> ep, Configurable configurable) { if (configurable != null && !(configurable instanceof ConfigurableGroup)) { if (ep.instanceClass != null && (configurable instanceof SearchableConfigurable) && (configurable instanceof Configurable.Composite)) { Element element = dump(ep, configurable, StringUtil.getShortName(configurablesExtensionPoint.getName())); final Configurable[] configurables = ((Configurable.Composite)configurable).getConfigurables(); for (Configurable child : configurables) { final Element dump = dump(null, child, "configurable"); element.addContent(dump); } final StringWriter out = new StringWriter(); try { new XMLOutputter(Format.getPrettyFormat()).output(element, out); } catch (IOException e) { } System.out.println(out); } } } private static Element dump(@Nullable ConfigurableEP ep, Configurable configurable, String name) { Element element = new Element(name); if (ep != null) { element.setAttribute("instance", ep.instanceClass); String id = ep.id == null ? ((SearchableConfigurable)configurable).getId() : ep.id; element.setAttribute("id", id); } else { element.setAttribute("instance", configurable.getClass().getName()); if (configurable instanceof SearchableConfigurable) { element.setAttribute("id", ((SearchableConfigurable)configurable).getId()); } } CommonBundle.lastKey = null; String displayName = configurable.getDisplayName(); if (CommonBundle.lastKey != null) { element.setAttribute("key", CommonBundle.lastKey).setAttribute("bundle", CommonBundle.lastBundle); } else { element.setAttribute("displayName", displayName); } if (configurable instanceof NonDefaultProjectConfigurable) { element.setAttribute("nonDefaultProject", "true"); } return element; } */ /** * @deprecated create a new instance of configurable instead */ @NotNull public static <T extends Configurable> T findProjectConfigurable(@NotNull Project project, @NotNull Class<T> configurableClass) { return findConfigurable(project.getExtensions(Configurable.PROJECT_CONFIGURABLE), configurableClass); } @NotNull public static <T extends Configurable> T findApplicationConfigurable(@NotNull Class<T> configurableClass) { return findConfigurable(Configurable.APPLICATION_CONFIGURABLE.getExtensions(), configurableClass); } @NotNull private static <T extends Configurable> T findConfigurable(ConfigurableEP<Configurable>[] extensions, Class<T> configurableClass) { for (ConfigurableEP<Configurable> extension : extensions) { if (extension.providerClass != null || extension.instanceClass != null || extension.implementationClass != null) { final Configurable configurable = extension.createConfigurable(); if (configurableClass.isInstance(configurable)) { return configurableClass.cast(configurable); } } } throw new IllegalArgumentException("Cannot find configurable of " + configurableClass); } @Nullable public static Configurable createProjectConfigurableForProvider(@NotNull Project project, Class<? extends ConfigurableProvider> providerClass) { return createConfigurableForProvider(project.getExtensions(Configurable.PROJECT_CONFIGURABLE), providerClass); } @Nullable public static Configurable createApplicationConfigurableForProvider(Class<? extends ConfigurableProvider> providerClass) { return createConfigurableForProvider(Configurable.APPLICATION_CONFIGURABLE.getExtensions(), providerClass); } @Nullable private static Configurable createConfigurableForProvider(ConfigurableEP<Configurable>[] extensions, Class<? extends ConfigurableProvider> providerClass) { for (ConfigurableEP<Configurable> extension : extensions) { if (extension.providerClass != null) { final Class<Object> aClass = extension.findClassNoExceptions(extension.providerClass); if (aClass != null && providerClass.isAssignableFrom(aClass)) { return extension.createConfigurable(); } } } return null; } }
platform/platform-impl/src/com/intellij/openapi/options/ex/ConfigurableExtensionPointUtil.java
/* * Copyright 2000-2010 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.options.ex; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.options.Configurable; import com.intellij.openapi.options.ConfigurableEP; import com.intellij.openapi.options.ConfigurableProvider; import com.intellij.openapi.options.OptionalConfigurable; import com.intellij.openapi.project.Project; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; /** * @author nik */ public class ConfigurableExtensionPointUtil { private final static Logger LOG = Logger.getInstance(ConfigurableExtensionPointUtil.class); private ConfigurableExtensionPointUtil() { } public static List<Configurable> buildConfigurablesList(final ConfigurableEP<Configurable>[] extensions, final Configurable[] components, @Nullable ConfigurableFilter filter) { final List<Configurable> result = new ArrayList<Configurable>(); for (Configurable component : components) { if (!isSuppressed(component, filter)) { result.add(component); } } final Map<String, ConfigurableWrapper> idToConfigurable = new HashMap<String, ConfigurableWrapper>(); for (ConfigurableEP<Configurable> ep : extensions) { final Configurable configurable = ConfigurableWrapper.wrapConfigurable(ep); if (isSuppressed(configurable, filter)) continue; if (configurable instanceof ConfigurableWrapper) { final ConfigurableWrapper wrapper = (ConfigurableWrapper)configurable; idToConfigurable.put(wrapper.getId(), wrapper); } else { // dumpConfigurable(configurablesExtensionPoint, ep, configurable); ContainerUtil.addIfNotNull(configurable, result); } } //modify configurables (append children) for (final String id : idToConfigurable.keySet()) { final ConfigurableWrapper wrapper = idToConfigurable.get(id); final String parentId = wrapper.getParentId(); if (parentId != null) { final ConfigurableWrapper parent = idToConfigurable.get(parentId); LOG.assertTrue(parent != null, "Can't find parent for " + parentId + " (" + wrapper + ")"); idToConfigurable.put(parentId, parent.addChild(wrapper)); } } //leave only roots (i.e. configurables without parents) for (final Iterator<String> iterator = idToConfigurable.keySet().iterator(); iterator.hasNext(); ) { final String key = iterator.next(); final ConfigurableWrapper wrapper = idToConfigurable.get(key); if (wrapper.getParentId() != null) { iterator.remove(); } } ContainerUtil.addAll(result, idToConfigurable.values()); return result; } private static boolean isSuppressed(Configurable each, ConfigurableFilter filter) { return each instanceof Configurable.Assistant || each instanceof OptionalConfigurable && !((OptionalConfigurable) each).needDisplay() || filter != null && !filter.isIncluded(each); } /* private static void dumpConfigurable(ExtensionPointName<ConfigurableEP<Configurable>> configurablesExtensionPoint, ConfigurableEP<Configurable> ep, Configurable configurable) { if (configurable != null && !(configurable instanceof ConfigurableGroup)) { if (ep.instanceClass != null && (configurable instanceof SearchableConfigurable) && (configurable instanceof Configurable.Composite)) { Element element = dump(ep, configurable, StringUtil.getShortName(configurablesExtensionPoint.getName())); final Configurable[] configurables = ((Configurable.Composite)configurable).getConfigurables(); for (Configurable child : configurables) { final Element dump = dump(null, child, "configurable"); element.addContent(dump); } final StringWriter out = new StringWriter(); try { new XMLOutputter(Format.getPrettyFormat()).output(element, out); } catch (IOException e) { } System.out.println(out); } } } private static Element dump(@Nullable ConfigurableEP ep, Configurable configurable, String name) { Element element = new Element(name); if (ep != null) { element.setAttribute("instance", ep.instanceClass); String id = ep.id == null ? ((SearchableConfigurable)configurable).getId() : ep.id; element.setAttribute("id", id); } else { element.setAttribute("instance", configurable.getClass().getName()); if (configurable instanceof SearchableConfigurable) { element.setAttribute("id", ((SearchableConfigurable)configurable).getId()); } } CommonBundle.lastKey = null; String displayName = configurable.getDisplayName(); if (CommonBundle.lastKey != null) { element.setAttribute("key", CommonBundle.lastKey).setAttribute("bundle", CommonBundle.lastBundle); } else { element.setAttribute("displayName", displayName); } if (configurable instanceof NonDefaultProjectConfigurable) { element.setAttribute("nonDefaultProject", "true"); } return element; } */ /** * @deprecated create a new instance of configurable instead */ @NotNull public static <T extends Configurable> T findProjectConfigurable(@NotNull Project project, @NotNull Class<T> configurableClass) { return findConfigurable(project.getExtensions(Configurable.PROJECT_CONFIGURABLE), configurableClass); } @NotNull public static <T extends Configurable> T findApplicationConfigurable(@NotNull Class<T> configurableClass) { return findConfigurable(Configurable.APPLICATION_CONFIGURABLE.getExtensions(), configurableClass); } @NotNull private static <T extends Configurable> T findConfigurable(ConfigurableEP<Configurable>[] extensions, Class<T> configurableClass) { for (ConfigurableEP<Configurable> extension : extensions) { if (extension.providerClass != null || extension.instanceClass != null || extension.implementationClass != null) { final Configurable configurable = extension.createConfigurable(); if (configurableClass.isInstance(configurable)) { return configurableClass.cast(configurable); } } } throw new IllegalArgumentException("Cannot find configurable of " + configurableClass); } @Nullable public static Configurable createProjectConfigurableForProvider(@NotNull Project project, Class<? extends ConfigurableProvider> providerClass) { return createConfigurableForProvider(project.getExtensions(Configurable.PROJECT_CONFIGURABLE), providerClass); } @Nullable public static Configurable createApplicationConfigurableForProvider(Class<? extends ConfigurableProvider> providerClass) { return createConfigurableForProvider(Configurable.APPLICATION_CONFIGURABLE.getExtensions(), providerClass); } @Nullable private static Configurable createConfigurableForProvider(ConfigurableEP<Configurable>[] extensions, Class<? extends ConfigurableProvider> providerClass) { for (ConfigurableEP<Configurable> extension : extensions) { if (extension.providerClass != null) { final Class<Object> aClass = extension.findClassNoExceptions(extension.providerClass); if (aClass != null && providerClass.isAssignableFrom(aClass)) { return extension.createConfigurable(); } } } return null; } }
Prevent stupid NPE
platform/platform-impl/src/com/intellij/openapi/options/ex/ConfigurableExtensionPointUtil.java
Prevent stupid NPE
Java
apache-2.0
e78dc1b8ee7e531694c2b22f34595c6483b11b84
0
tmaret/sling,labertasch/sling,awadheshv/sling,vladbailescu/sling,mcdan/sling,JEBailey/sling,ieb/sling,vladbailescu/sling,roele/sling,tmaret/sling,anchela/sling,mikibrv/sling,labertasch/sling,ist-dresden/sling,mcdan/sling,anchela/sling,cleliameneghin/sling,ist-dresden/sling,cleliameneghin/sling,roele/sling,vladbailescu/sling,headwirecom/sling,cleliameneghin/sling,ieb/sling,mikibrv/sling,mikibrv/sling,awadheshv/sling,JEBailey/sling,trekawek/sling,JEBailey/sling,mcdan/sling,headwirecom/sling,ist-dresden/sling,vladbailescu/sling,headwirecom/sling,tmaret/sling,labertasch/sling,ieb/sling,awadheshv/sling,JEBailey/sling,ist-dresden/sling,trekawek/sling,headwirecom/sling,cleliameneghin/sling,trekawek/sling,mikibrv/sling,ieb/sling,vladbailescu/sling,roele/sling,labertasch/sling,trekawek/sling,JEBailey/sling,cleliameneghin/sling,labertasch/sling,roele/sling,awadheshv/sling,tmaret/sling,roele/sling,tmaret/sling,mcdan/sling,mcdan/sling,mikibrv/sling,ieb/sling,awadheshv/sling,mikibrv/sling,mcdan/sling,trekawek/sling,trekawek/sling,ieb/sling,headwirecom/sling,awadheshv/sling,ist-dresden/sling,anchela/sling,anchela/sling,anchela/sling
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.sling.tenant.internal; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.SortedMap; import java.util.TreeMap; import org.apache.felix.scr.annotations.Activate; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Deactivate; import org.apache.felix.scr.annotations.Property; import org.apache.felix.scr.annotations.PropertyUnbounded; import org.apache.felix.scr.annotations.Reference; import org.apache.felix.scr.annotations.ReferenceCardinality; import org.apache.felix.scr.annotations.ReferencePolicy; import org.apache.felix.scr.annotations.References; import org.apache.felix.scr.annotations.Service; import org.apache.sling.api.resource.LoginException; import org.apache.sling.api.resource.ModifiableValueMap; import org.apache.sling.api.resource.PersistenceException; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.resource.ResourceResolver; import org.apache.sling.api.resource.ResourceResolverFactory; import org.apache.sling.api.resource.ResourceUtil; import org.apache.sling.commons.osgi.PropertiesUtil; import org.apache.sling.commons.osgi.ServiceUtil; import org.apache.sling.tenant.Tenant; import org.apache.sling.tenant.TenantManager; import org.apache.sling.tenant.TenantProvider; import org.apache.sling.tenant.internal.console.WebConsolePlugin; import org.apache.sling.tenant.spi.TenantCustomizer; import org.apache.sling.tenant.spi.TenantManagerHook; import org.osgi.framework.BundleContext; import org.osgi.framework.Constants; import org.osgi.framework.Filter; import org.osgi.framework.FrameworkUtil; import org.osgi.framework.InvalidSyntaxException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Resource based Tenant Provider implementation. */ @Component( metatype = true, label = "Apache Sling Tenant Provider", description = "Service responsible for providing Tenants", immediate = true) @Service(value = {TenantProvider.class, TenantManager.class}) @Property(name = Constants.SERVICE_DESCRIPTION, value = "Apache Sling Tenant Provider") @References({ @Reference( name = "tenantSetup", referenceInterface = TenantCustomizer.class, cardinality = ReferenceCardinality.OPTIONAL_MULTIPLE, policy = ReferencePolicy.DYNAMIC), @Reference( name = "hook", referenceInterface = TenantManagerHook.class, cardinality = ReferenceCardinality.OPTIONAL_MULTIPLE, policy = ReferencePolicy.DYNAMIC) }) public class TenantProviderImpl implements TenantProvider, TenantManager { /** default log */ private final Logger log = LoggerFactory.getLogger(getClass()); /** * Root path for tenant */ private static final String RESOURCE_TENANT_ROOT = "/etc/tenants"; @Property(value = RESOURCE_TENANT_ROOT, label = "Tenants Root Path", description = "Defines tenants root path") private static final String TENANT_ROOT = "tenant.root"; private static final String[] DEFAULT_PATH_MATCHER = {}; private SortedMap<Comparable<Object>, TenantCustomizer> registeredTenantHandlers = new TreeMap<Comparable<Object>, TenantCustomizer>( Collections.reverseOrder()); private SortedMap<Comparable<Object>, TenantManagerHook> registeredHooks = new TreeMap<Comparable<Object>, TenantManagerHook>( Collections.reverseOrder()); @Property( value = {}, unbounded = PropertyUnbounded.ARRAY, label = "Tenants Path Matcher", description = "Defines tenants path matcher i.e. /content/sample/([^/]+)/*, used while resolving path to tenant") private static final String TENANT_PATH_MATCHER = "tenant.path.matcher"; private String tenantRootPath = RESOURCE_TENANT_ROOT; @Reference private ResourceResolverFactory factory; private TenantAdapterFactory adapterFactory; private WebConsolePlugin plugin; @Activate protected void activate(final BundleContext bundleContext, final Map<String, Object> properties) { this.tenantRootPath = PropertiesUtil.toString(properties.get(TENANT_ROOT), RESOURCE_TENANT_ROOT); this.adapterFactory = new TenantAdapterFactory(bundleContext, this, PropertiesUtil.toStringArray(properties.get(TENANT_PATH_MATCHER), DEFAULT_PATH_MATCHER)); this.plugin = new WebConsolePlugin(bundleContext, this); } @Deactivate protected void deactivate() { if (this.adapterFactory != null) { this.adapterFactory.dispose(); this.adapterFactory = null; } if (this.plugin != null) { this.plugin.dispose(); this.plugin = null; } } @SuppressWarnings("unused") private synchronized void bindTenantSetup(TenantCustomizer action, Map<String, Object> config) { registeredTenantHandlers.put(ServiceUtil.getComparableForServiceRanking(config), action); } @SuppressWarnings("unused") private synchronized void unbindTenantSetup(TenantCustomizer action, Map<String, Object> config) { registeredTenantHandlers.remove(ServiceUtil.getComparableForServiceRanking(config)); } private synchronized Collection<TenantCustomizer> getTenantHandlers() { return registeredTenantHandlers.values(); } @SuppressWarnings("unused") private synchronized void bindHook(TenantManagerHook action, Map<String, Object> config) { registeredHooks.put(ServiceUtil.getComparableForServiceRanking(config), action); } @SuppressWarnings("unused") private synchronized void unbindHook(TenantManagerHook action, Map<String, Object> config) { registeredHooks.remove(ServiceUtil.getComparableForServiceRanking(config)); } private synchronized Collection<TenantManagerHook> getHooks() { return registeredHooks.values(); } @Override public Tenant getTenant(final String tenantId) { if (tenantId != null && tenantId.length() > 0) { return call(new ResourceResolverTask<Tenant>() { @Override public Tenant call(ResourceResolver resolver) { Resource tenantRes = getTenantResource(resolver, tenantId); return (tenantRes != null) ? new TenantImpl(tenantRes) : null; } }); } // in case of some problem return null; } @Override public Iterator<Tenant> getTenants() { return getTenants(null); } @Override public Iterator<Tenant> getTenants(final String tenantFilter) { final Filter filter; if (tenantFilter != null && tenantFilter.length() > 0) { try { filter = FrameworkUtil.createFilter(tenantFilter); } catch (InvalidSyntaxException e) { throw new IllegalArgumentException(e.getMessage(), e); } } else { filter = null; } Iterator<Tenant> result = call(new ResourceResolverTask<Iterator<Tenant>>() { @SuppressWarnings("unchecked") @Override public Iterator<Tenant> call(ResourceResolver resolver) { Resource tenantRootRes = resolver.getResource(tenantRootPath); if ( tenantRootRes != null ) { List<Tenant> tenantList = new ArrayList<Tenant>(); Iterator<Resource> tenantResourceList = tenantRootRes.listChildren(); while (tenantResourceList.hasNext()) { Resource tenantRes = tenantResourceList.next(); if (filter == null || filter.matches(ResourceUtil.getValueMap(tenantRes))) { TenantImpl tenant = new TenantImpl(tenantRes); tenantList.add(tenant); } } return tenantList.iterator(); } return Collections.EMPTY_LIST.iterator(); } }); if (result == null) { // no filter or no resource resolver for calling result = Collections.<Tenant> emptyList().iterator(); } return result; } @Override public Tenant create(final String tenantId, final Map<String, Object> properties) { return call(new ResourceResolverTask<Tenant>() { @Override public Tenant call(ResourceResolver adminResolver) { try { // create the tenant Resource tenantRes = createTenantResource(adminResolver, tenantId, properties); TenantImpl tenant = new TenantImpl(tenantRes); customizeTenant(tenantRes, tenant, true); adminResolver.commit(); // refresh tenant instance, as it copies property from // resource tenant.loadProperties(tenantRes); return tenant; } catch (PersistenceException e) { log.error("create: Failed creating Tenant {}", tenantId, e); } finally { adminResolver.close(); } // no new tenant in case of problems return null; } }); } @Override public void remove(final Tenant tenant) { call(new ResourceResolverTask<Void>() { @Override public Void call(ResourceResolver resolver) { try { Resource tenantRes = getTenantResource(resolver, tenant.getId()); if (tenantRes != null) { // call tenant setup handler for (TenantCustomizer ts : getTenantHandlers()) { try { ts.remove(tenant, resolver); } catch (Exception e) { log.info("removeTenant: Unexpected problem calling TenantCustomizer " + ts, e); } } // call tenant hooks for (TenantManagerHook ts : getHooks()) { try { ts.remove(tenant); } catch (Exception e) { log.info("removeTenant: Unexpected problem calling TenantManagerHook " + ts, e); } } resolver.delete(tenantRes); resolver.commit(); } } catch (PersistenceException e) { log.error("remove({}): Cannot persist Tenant removal", tenant.getId(), e); } return null; } }); } @Override public void setProperty(final Tenant tenant, final String name, final Object value) { updateProperties(tenant, new PropertiesUpdater() { @Override public void update(ModifiableValueMap properties) { if (value != null) { properties.put(name, value); } else { properties.remove(name); } } }); } @Override public void setProperties(final Tenant tenant, final Map<String, Object> properties) { updateProperties(tenant, new PropertiesUpdater() { @Override public void update(ModifiableValueMap vm) { for (Entry<String, Object> entry : properties.entrySet()) { if (entry.getValue() != null) { vm.put(entry.getKey(), entry.getValue()); } else { vm.remove(entry.getKey()); } } } }); } @Override public void removeProperties(final Tenant tenant, final String... propertyNames) { updateProperties(tenant, new PropertiesUpdater() { @Override public void update(ModifiableValueMap properties) { for (String name : propertyNames) { properties.remove(name); } } }); } @SuppressWarnings("serial") private Resource createTenantResource(final ResourceResolver resolver, final String tenantId, final Map<String, Object> properties) throws PersistenceException { // check for duplicate first if (getTenantResource(resolver, tenantId) != null) { throw new PersistenceException("Tenant '" + tenantId + "' already exists"); } Resource tenantRoot = resolver.getResource(tenantRootPath); if (tenantRoot == null) { Resource current = resolver.getResource("/"); if (current == null) { throw new PersistenceException("Cannot get root Resource"); } String[] segments = this.tenantRootPath.split("/"); for (String segment : segments) { Resource child = current.getChild(segment); if (child == null) { child = resolver.create(current, segment, new HashMap<String, Object>() { { put("jcr:primaryType", "sling:Folder"); } }); } current = child; } tenantRoot = current; } return resolver.create(tenantRoot, tenantId, properties); } private Resource getTenantResource(final ResourceResolver resolver, final String tenantId) { return resolver.getResource(tenantRootPath + "/" + tenantId); } private void customizeTenant(final Resource tenantRes, final Tenant tenant, boolean isCreate) { // call tenant setup handler Map<String, Object> tenantProps = tenantRes.adaptTo(ModifiableValueMap.class); if (tenantProps == null) { log.warn( "create({}): Cannot get ModifiableValueMap for new tenant; will not store changed properties of TenantCustomizers", tenant.getId()); tenantProps = new HashMap<String, Object>(); } for (TenantCustomizer ts : getTenantHandlers()) { try { Map<String, Object> props = ts.setup(tenant, tenantRes.getResourceResolver()); if (props != null) { tenantProps.putAll(props); } } catch (Exception e) { log.info("addTenant/updateTenant: Unexpected problem calling TenantCustomizer " + ts, e); } } // call tenant hooks for (TenantManagerHook ts : getHooks()) { try { Map<String, Object> props = (isCreate ? ts.setup(tenant) : ts.change(tenant)); if (props != null) { tenantProps.putAll(props); } } catch (Exception e) { log.info("addTenant/updateTenant: Unexpected problem calling TenantManagerHook " + ts, e); } } } private <T> T call(ResourceResolverTask<T> task) { ResourceResolver resolver = null; T result = null; try { resolver = factory.getServiceResourceResolver(null); result = task.call(resolver); } catch (LoginException le) { // unexpected, thus ignore } finally { if (resolver != null) { resolver.close(); } } return result; } private void updateProperties(final Tenant tenant, final PropertiesUpdater updater) { call(new ResourceResolverTask<Void>() { @Override public Void call(ResourceResolver resolver) { try { Resource tenantRes = getTenantResource(resolver, tenant.getId()); if (tenantRes != null) { updater.update(tenantRes.adaptTo(ModifiableValueMap.class)); //refresh so that customizer gets a refreshed tenant instance if (tenant instanceof TenantImpl) { ((TenantImpl) tenant).loadProperties(tenantRes); } customizeTenant(tenantRes, tenant, false); resolver.commit(); if (tenant instanceof TenantImpl) { ((TenantImpl) tenant).loadProperties(tenantRes); } } } catch (PersistenceException pe) { log.error("setProperty({}): Cannot persist Tenant removal", tenant.getId(), pe); } return null; } }); } private static interface ResourceResolverTask<T> { T call(ResourceResolver resolver); } private static interface PropertiesUpdater { void update(ModifiableValueMap properties); } }
contrib/extensions/tenant/src/main/java/org/apache/sling/tenant/internal/TenantProviderImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.sling.tenant.internal; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.SortedMap; import java.util.TreeMap; import org.apache.felix.scr.annotations.Activate; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Deactivate; import org.apache.felix.scr.annotations.Property; import org.apache.felix.scr.annotations.PropertyUnbounded; import org.apache.felix.scr.annotations.Reference; import org.apache.felix.scr.annotations.ReferenceCardinality; import org.apache.felix.scr.annotations.ReferencePolicy; import org.apache.felix.scr.annotations.References; import org.apache.felix.scr.annotations.Service; import org.apache.sling.api.resource.LoginException; import org.apache.sling.api.resource.ModifiableValueMap; import org.apache.sling.api.resource.PersistenceException; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.resource.ResourceResolver; import org.apache.sling.api.resource.ResourceResolverFactory; import org.apache.sling.api.resource.ResourceUtil; import org.apache.sling.commons.osgi.PropertiesUtil; import org.apache.sling.commons.osgi.ServiceUtil; import org.apache.sling.tenant.Tenant; import org.apache.sling.tenant.TenantManager; import org.apache.sling.tenant.TenantProvider; import org.apache.sling.tenant.internal.console.WebConsolePlugin; import org.apache.sling.tenant.spi.TenantCustomizer; import org.apache.sling.tenant.spi.TenantManagerHook; import org.osgi.framework.BundleContext; import org.osgi.framework.Constants; import org.osgi.framework.Filter; import org.osgi.framework.FrameworkUtil; import org.osgi.framework.InvalidSyntaxException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Resource based Tenant Provider implementation. */ @Component( metatype = true, label = "Apache Sling Tenant Provider", description = "Service responsible for providing Tenants", immediate = true) @Service(value = {TenantProvider.class, TenantManager.class}) @Property(name = Constants.SERVICE_DESCRIPTION, value = "Apache Sling Tenant Provider") @References({ @Reference( name = "tenantSetup", referenceInterface = TenantCustomizer.class, cardinality = ReferenceCardinality.OPTIONAL_MULTIPLE, policy = ReferencePolicy.DYNAMIC), @Reference( name = "hook", referenceInterface = TenantManagerHook.class, cardinality = ReferenceCardinality.OPTIONAL_MULTIPLE, policy = ReferencePolicy.DYNAMIC) }) public class TenantProviderImpl implements TenantProvider, TenantManager { /** default log */ private final Logger log = LoggerFactory.getLogger(getClass()); /** * Root path for tenant */ private static final String RESOURCE_TENANT_ROOT = "/etc/tenants"; @Property(value = RESOURCE_TENANT_ROOT, label = "Tenants Root Path", description = "Defines tenants root path") private static final String TENANT_ROOT = "tenant.root"; private static final String[] DEFAULT_PATH_MATCHER = {}; private SortedMap<Comparable<Object>, TenantCustomizer> registeredTenantHandlers = new TreeMap<Comparable<Object>, TenantCustomizer>( Collections.reverseOrder()); private SortedMap<Comparable<Object>, TenantManagerHook> registeredHooks = new TreeMap<Comparable<Object>, TenantManagerHook>( Collections.reverseOrder()); @Property( value = {}, unbounded = PropertyUnbounded.ARRAY, label = "Tenants Path Matcher", description = "Defines tenants path matcher i.e. /content/sample/([^/]+)/*, used while resolving path to tenant") private static final String TENANT_PATH_MATCHER = "tenant.path.matcher"; private String tenantRootPath = RESOURCE_TENANT_ROOT; @Reference private ResourceResolverFactory factory; private TenantAdapterFactory adapterFactory; private WebConsolePlugin plugin; @Activate protected void activate(final BundleContext bundleContext, final Map<String, Object> properties) { this.tenantRootPath = PropertiesUtil.toString(properties.get(TENANT_ROOT), RESOURCE_TENANT_ROOT); this.adapterFactory = new TenantAdapterFactory(bundleContext, this, PropertiesUtil.toStringArray(properties.get(TENANT_PATH_MATCHER), DEFAULT_PATH_MATCHER)); this.plugin = new WebConsolePlugin(bundleContext, this); } @Deactivate protected void deactivate() { if (this.adapterFactory != null) { this.adapterFactory.dispose(); this.adapterFactory = null; } if (this.plugin != null) { this.plugin.dispose(); this.plugin = null; } } @SuppressWarnings("unused") private synchronized void bindTenantSetup(TenantCustomizer action, Map<String, Object> config) { registeredTenantHandlers.put(ServiceUtil.getComparableForServiceRanking(config), action); } @SuppressWarnings("unused") private synchronized void unbindTenantSetup(TenantCustomizer action, Map<String, Object> config) { registeredTenantHandlers.remove(ServiceUtil.getComparableForServiceRanking(config)); } private synchronized Collection<TenantCustomizer> getTenantHandlers() { return registeredTenantHandlers.values(); } @SuppressWarnings("unused") private synchronized void bindHook(TenantManagerHook action, Map<String, Object> config) { registeredHooks.put(ServiceUtil.getComparableForServiceRanking(config), action); } @SuppressWarnings("unused") private synchronized void unbindHook(TenantManagerHook action, Map<String, Object> config) { registeredHooks.remove(ServiceUtil.getComparableForServiceRanking(config)); } private synchronized Collection<TenantManagerHook> getHooks() { return registeredHooks.values(); } @Override public Tenant getTenant(final String tenantId) { if (tenantId != null && tenantId.length() > 0) { return call(new ResourceResolverTask<Tenant>() { @Override public Tenant call(ResourceResolver resolver) { Resource tenantRes = getTenantResource(resolver, tenantId); return (tenantRes != null) ? new TenantImpl(tenantRes) : null; } }); } // in case of some problem return null; } @Override public Iterator<Tenant> getTenants() { return getTenants(null); } @Override public Iterator<Tenant> getTenants(final String tenantFilter) { final Filter filter; if (tenantFilter != null && tenantFilter.length() > 0) { try { filter = FrameworkUtil.createFilter(tenantFilter); } catch (InvalidSyntaxException e) { throw new IllegalArgumentException(e.getMessage(), e); } } else { filter = null; } Iterator<Tenant> result = call(new ResourceResolverTask<Iterator<Tenant>>() { @SuppressWarnings("unchecked") @Override public Iterator<Tenant> call(ResourceResolver resolver) { Resource tenantRootRes = resolver.getResource(tenantRootPath); if ( tenantRootRes != null ) { List<Tenant> tenantList = new ArrayList<Tenant>(); Iterator<Resource> tenantResourceList = tenantRootRes.listChildren(); while (tenantResourceList.hasNext()) { Resource tenantRes = tenantResourceList.next(); if (filter == null || filter.matches(ResourceUtil.getValueMap(tenantRes))) { TenantImpl tenant = new TenantImpl(tenantRes); tenantList.add(tenant); } } return tenantList.iterator(); } return Collections.EMPTY_LIST.iterator(); } }); if (result == null) { // no filter or no resource resolver for calling result = Collections.<Tenant> emptyList().iterator(); } return result; } @Override public Tenant create(final String tenantId, final Map<String, Object> properties) { return call(new ResourceResolverTask<Tenant>() { @Override public Tenant call(ResourceResolver adminResolver) { try { // create the tenant Resource tenantRes = createTenantResource(adminResolver, tenantId, properties); TenantImpl tenant = new TenantImpl(tenantRes); adminResolver.commit(); customizeTenant(tenantRes, tenant, true); adminResolver.commit(); // refresh tenant instance, as it copies property from // resource tenant.loadProperties(tenantRes); return tenant; } catch (PersistenceException e) { log.error("create: Failed creating Tenant {}", tenantId, e); } finally { adminResolver.close(); } // no new tenant in case of problems return null; } }); } @Override public void remove(final Tenant tenant) { call(new ResourceResolverTask<Void>() { @Override public Void call(ResourceResolver resolver) { try { Resource tenantRes = getTenantResource(resolver, tenant.getId()); if (tenantRes != null) { // call tenant setup handler for (TenantCustomizer ts : getTenantHandlers()) { try { ts.remove(tenant, resolver); } catch (Exception e) { log.info("removeTenant: Unexpected problem calling TenantCustomizer " + ts, e); } } // call tenant hooks for (TenantManagerHook ts : getHooks()) { try { ts.remove(tenant); } catch (Exception e) { log.info("removeTenant: Unexpected problem calling TenantManagerHook " + ts, e); } } resolver.delete(tenantRes); resolver.commit(); } } catch (PersistenceException e) { log.error("remove({}): Cannot persist Tenant removal", tenant.getId(), e); } return null; } }); } @Override public void setProperty(final Tenant tenant, final String name, final Object value) { updateProperties(tenant, new PropertiesUpdater() { @Override public void update(ModifiableValueMap properties) { if (value != null) { properties.put(name, value); } else { properties.remove(name); } } }); } @Override public void setProperties(final Tenant tenant, final Map<String, Object> properties) { updateProperties(tenant, new PropertiesUpdater() { @Override public void update(ModifiableValueMap vm) { for (Entry<String, Object> entry : properties.entrySet()) { if (entry.getValue() != null) { vm.put(entry.getKey(), entry.getValue()); } else { vm.remove(entry.getKey()); } } } }); } @Override public void removeProperties(final Tenant tenant, final String... propertyNames) { updateProperties(tenant, new PropertiesUpdater() { @Override public void update(ModifiableValueMap properties) { for (String name : propertyNames) { properties.remove(name); } } }); } @SuppressWarnings("serial") private Resource createTenantResource(final ResourceResolver resolver, final String tenantId, final Map<String, Object> properties) throws PersistenceException { // check for duplicate first if (getTenantResource(resolver, tenantId) != null) { throw new PersistenceException("Tenant '" + tenantId + "' already exists"); } Resource tenantRoot = resolver.getResource(tenantRootPath); if (tenantRoot == null) { Resource current = resolver.getResource("/"); if (current == null) { throw new PersistenceException("Cannot get root Resource"); } String[] segments = this.tenantRootPath.split("/"); for (String segment : segments) { Resource child = current.getChild(segment); if (child == null) { child = resolver.create(current, segment, new HashMap<String, Object>() { { put("jcr:primaryType", "sling:Folder"); } }); } current = child; } tenantRoot = current; } return resolver.create(tenantRoot, tenantId, properties); } private Resource getTenantResource(final ResourceResolver resolver, final String tenantId) { return resolver.getResource(tenantRootPath + "/" + tenantId); } private void customizeTenant(final Resource tenantRes, final Tenant tenant, boolean isCreate) { // call tenant setup handler Map<String, Object> tenantProps = tenantRes.adaptTo(ModifiableValueMap.class); if (tenantProps == null) { log.warn( "create({}): Cannot get ModifiableValueMap for new tenant; will not store changed properties of TenantCustomizers", tenant.getId()); tenantProps = new HashMap<String, Object>(); } for (TenantCustomizer ts : getTenantHandlers()) { try { Map<String, Object> props = ts.setup(tenant, tenantRes.getResourceResolver()); if (props != null) { tenantProps.putAll(props); } } catch (Exception e) { log.info("addTenant/updateTenant: Unexpected problem calling TenantCustomizer " + ts, e); } } // call tenant hooks for (TenantManagerHook ts : getHooks()) { try { Map<String, Object> props = (isCreate ? ts.setup(tenant) : ts.change(tenant)); if (props != null) { tenantProps.putAll(props); } } catch (Exception e) { log.info("addTenant/updateTenant: Unexpected problem calling TenantManagerHook " + ts, e); } } } private <T> T call(ResourceResolverTask<T> task) { ResourceResolver resolver = null; T result = null; try { resolver = factory.getServiceResourceResolver(null); result = task.call(resolver); } catch (LoginException le) { // unexpected, thus ignore } finally { if (resolver != null) { resolver.close(); } } return result; } private void updateProperties(final Tenant tenant, final PropertiesUpdater updater) { call(new ResourceResolverTask<Void>() { @Override public Void call(ResourceResolver resolver) { try { Resource tenantRes = getTenantResource(resolver, tenant.getId()); if (tenantRes != null) { updater.update(tenantRes.adaptTo(ModifiableValueMap.class)); //refresh so that customizer gets a refreshed tenant instance if (tenant instanceof TenantImpl) { ((TenantImpl) tenant).loadProperties(tenantRes); } customizeTenant(tenantRes, tenant, false); resolver.commit(); if (tenant instanceof TenantImpl) { ((TenantImpl) tenant).loadProperties(tenantRes); } } } catch (PersistenceException pe) { log.error("setProperty({}): Cannot persist Tenant removal", tenant.getId(), pe); } return null; } }); } private static interface ResourceResolverTask<T> { T call(ResourceResolver resolver); } private static interface PropertiesUpdater { void update(ModifiableValueMap properties); } }
SLING-4753 - Commit the Resource Resolver before passing it to Tenant Customizers * Revert commit r1681937 git-svn-id: 6eed74fe9a15c8da84b9a8d7f2960c0406113ece@1778434 13f79535-47bb-0310-9956-ffa450edef68
contrib/extensions/tenant/src/main/java/org/apache/sling/tenant/internal/TenantProviderImpl.java
SLING-4753 - Commit the Resource Resolver before passing it to Tenant Customizers
Java
apache-2.0
1802b3bb47c7144af3d73b378b5ad83816835946
0
giacomolm/syncope,NuwanSameera/syncope,tmess567/syncope,NuwanSameera/syncope,tmess567/syncope,securny/syncope,nscendoni/syncope,tmess567/syncope,securny/syncope,securny/syncope,ilgrosso/syncope,securny/syncope,giacomolm/syncope,nscendoni/syncope,apache/syncope,NuwanSameera/syncope,giacomolm/syncope,apache/syncope,ilgrosso/syncope,apache/syncope,nscendoni/syncope,apache/syncope,giacomolm/syncope,NuwanSameera/syncope,ilgrosso/syncope,nscendoni/syncope,ilgrosso/syncope,tmess567/syncope
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.syncope.core.workflow.activiti; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.Resource; import javax.ws.rs.NotFoundException; import org.activiti.bpmn.converter.BpmnXMLConverter; import org.activiti.bpmn.model.BpmnModel; import org.activiti.editor.constants.ModelDataJsonConstants; import org.activiti.editor.language.json.converter.BpmnJsonConverter; import org.activiti.engine.ActivitiException; import org.activiti.engine.form.FormProperty; import org.activiti.engine.form.FormType; import org.activiti.engine.form.TaskFormData; import org.activiti.engine.history.HistoricActivityInstance; import org.activiti.engine.history.HistoricDetail; import org.activiti.engine.history.HistoricTaskInstance; import org.activiti.engine.impl.persistence.entity.HistoricFormPropertyEntity; import org.activiti.engine.query.Query; import org.activiti.engine.repository.Model; import org.activiti.engine.repository.ProcessDefinition; import org.activiti.engine.runtime.ProcessInstance; import org.activiti.engine.task.Task; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; import org.apache.syncope.common.lib.SyncopeClientException; import org.apache.syncope.common.lib.patch.PasswordPatch; import org.apache.syncope.common.lib.patch.UserPatch; import org.apache.syncope.common.lib.to.UserTO; import org.apache.syncope.common.lib.to.WorkflowFormPropertyTO; import org.apache.syncope.common.lib.to.WorkflowFormTO; import org.apache.syncope.common.lib.types.PropagationByResource; import org.apache.syncope.common.lib.types.ResourceOperation; import org.apache.syncope.common.lib.types.WorkflowFormPropertyType; import org.apache.syncope.core.misc.security.AuthContextUtils; import org.apache.syncope.core.misc.spring.BeanUtils; import org.apache.syncope.core.persistence.api.attrvalue.validation.InvalidEntityException; import org.apache.syncope.core.persistence.api.attrvalue.validation.ParsingValidationException; import org.apache.syncope.core.persistence.api.entity.user.User; import org.apache.syncope.core.provisioning.api.WorkflowResult; import org.apache.syncope.core.workflow.activiti.spring.DomainProcessEngine; import org.apache.syncope.core.workflow.api.WorkflowDefinitionFormat; import org.apache.syncope.core.workflow.api.WorkflowException; import org.apache.syncope.core.workflow.java.AbstractUserWorkflowAdapter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.transaction.annotation.Transactional; /** * <a href="http://www.activiti.org/">Activiti</a> based implementation. */ public class ActivitiUserWorkflowAdapter extends AbstractUserWorkflowAdapter { protected static final String[] PROPERTY_IGNORE_PROPS = { "type" }; public static final String WF_PROCESS_ID = "userWorkflow"; public static final String WF_PROCESS_RESOURCE = "userWorkflow.bpmn20.xml"; public static final String WF_DGRM_RESOURCE = "userWorkflow.userWorkflow.png"; public static final String USER = "user"; public static final String WF_EXECUTOR = "wfExecutor"; public static final String FORM_SUBMITTER = "formSubmitter"; public static final String USER_TO = "userTO"; public static final String ENABLED = "enabled"; public static final String USER_PATCH = "userPatch"; public static final String EMAIL_KIND = "emailKind"; public static final String TASK = "task"; public static final String TOKEN = "token"; public static final String PASSWORD = "password"; public static final String PROP_BY_RESOURCE = "propByResource"; public static final String PROPAGATE_ENABLE = "propagateEnable"; public static final String ENCRYPTED_PWD = "encryptedPwd"; public static final String TASK_IS_FORM = "taskIsForm"; public static final String MODEL_DATA_JSON_MODEL = "model"; public static final String STORE_PASSWORD = "storePassword"; public static final String EVENT = "event"; @Resource(name = "adminUser") protected String adminUser; @Autowired protected DomainProcessEngine engine; @Override public String getPrefix() { return "ACT_"; } protected void throwException(final ActivitiException e, final String defaultMessage) { if (e.getCause() != null) { if (e.getCause().getCause() instanceof SyncopeClientException) { throw (SyncopeClientException) e.getCause().getCause(); } else if (e.getCause().getCause() instanceof ParsingValidationException) { throw (ParsingValidationException) e.getCause().getCause(); } else if (e.getCause().getCause() instanceof InvalidEntityException) { throw (InvalidEntityException) e.getCause().getCause(); } } throw new WorkflowException(defaultMessage, e); } protected void updateStatus(final User user) { List<Task> tasks = engine.getTaskService().createTaskQuery().processInstanceId(user.getWorkflowId()).list(); if (tasks.isEmpty() || tasks.size() > 1) { LOG.warn("While setting user status: unexpected task number ({})", tasks.size()); } else { user.setStatus(tasks.get(0).getTaskDefinitionKey()); } } protected String getFormTask(final User user) { String result = null; List<Task> tasks = engine.getTaskService().createTaskQuery().processInstanceId(user.getWorkflowId()).list(); if (tasks.isEmpty() || tasks.size() > 1) { LOG.warn("While checking if form task: unexpected task number ({})", tasks.size()); } else { try { TaskFormData formData = engine.getFormService().getTaskFormData(tasks.get(0).getId()); if (formData != null && !formData.getFormProperties().isEmpty()) { result = tasks.get(0).getId(); } } catch (ActivitiException e) { LOG.warn("Could not get task form data", e); } } return result; } protected Set<String> getPerformedTasks(final User user) { final Set<String> result = new HashSet<>(); for (HistoricActivityInstance task : engine.getHistoryService().createHistoricActivityInstanceQuery(). executionId(user.getWorkflowId()).list()) { result.add(task.getActivityId()); } return result; } protected void cleanupHistory(final User user) { JdbcTemplate jdbcTemplate = new JdbcTemplate(engine.getDataSource()); List<String> taskIds = jdbcTemplate.queryForList( "SELECT TASK_ID_ FROM ACT_HI_VARINST WHERE NAME_='" + TASK_IS_FORM + "' AND LONG_=1 AND PROC_INST_ID_='" + user.getWorkflowId() + "'", String.class); StringBuilder update = new StringBuilder(); update.append("DELETE FROM ACT_HI_VARINST WHERE PROC_INST_ID_='").append(user.getWorkflowId()).append("' "); for (String taskId : taskIds) { update.append("AND TASK_ID_<>'").append(taskId).append("' "); } jdbcTemplate.execute(update.toString()); update.setLength(0); update.append("DELETE FROM ACT_HI_TASKINST WHERE PROC_INST_ID_='").append(user.getWorkflowId()).append("' "); for (String taskId : taskIds) { update.append("AND ID_<>'").append(taskId).append("' "); } jdbcTemplate.execute(update.toString()); update.setLength(0); update.append("DELETE FROM ACT_HI_ACTINST WHERE PROC_INST_ID_='").append(user.getWorkflowId()).append("' "); for (String taskId : taskIds) { update.append("AND TASK_ID_<>'").append(taskId).append("' "); } jdbcTemplate.execute(update.toString()); List<String> byteArrayIds = jdbcTemplate.queryForList( "SELECT BYTEARRAY_ID_ FROM ACT_HI_VARINST WHERE BYTEARRAY_ID_ IS NOT NULL", String.class); update.setLength(0); update.append("DELETE FROM ACT_GE_BYTEARRAY WHERE NAME_ LIKE 'hist.%' "); for (String byteArrayId : byteArrayIds) { update.append("AND ID_<>'").append(byteArrayId).append("' "); } jdbcTemplate.execute(update.toString()); } /** * Saves resources to be propagated and password for later - after form submission - propagation. * * @param user user * @param password pasword * @param propByRes current propagation actions against resources */ protected void saveForFormSubmit(final User user, final String password, final PropagationByResource propByRes) { String formTaskId = getFormTask(user); if (formTaskId != null) { // SYNCOPE-238: This is needed to simplify the task query in this.getForms() engine.getTaskService().setVariableLocal(formTaskId, TASK_IS_FORM, Boolean.TRUE); engine.getRuntimeService().setVariable(user.getWorkflowId(), PROP_BY_RESOURCE, propByRes); if (propByRes != null) { propByRes.clear(); } if (StringUtils.isNotBlank(password)) { engine.getRuntimeService().setVariable(user.getWorkflowId(), ENCRYPTED_PWD, encrypt(password)); } } } @Override public WorkflowResult<Pair<Long, Boolean>> create(final UserTO userTO, final boolean disablePwdPolicyCheck, final boolean storePassword) { return create(userTO, disablePwdPolicyCheck, null, storePassword); } @Override public WorkflowResult<Pair<Long, Boolean>> create(final UserTO userTO, final boolean storePassword) { return create(userTO, false, storePassword); } @Override public WorkflowResult<Pair<Long, Boolean>> create(final UserTO userTO, final boolean disablePwdPolicyCheck, final Boolean enabled, final boolean storePassword) { Map<String, Object> variables = new HashMap<>(); variables.put(WF_EXECUTOR, AuthContextUtils.getUsername()); variables.put(USER_TO, userTO); variables.put(ENABLED, enabled); variables.put(STORE_PASSWORD, storePassword); ProcessInstance processInstance = null; try { processInstance = engine.getRuntimeService().startProcessInstanceByKey(WF_PROCESS_ID, variables); } catch (ActivitiException e) { throwException(e, "While starting " + WF_PROCESS_ID + " instance"); } User user = engine.getRuntimeService().getVariable(processInstance.getProcessInstanceId(), USER, User.class); Boolean updatedEnabled = engine.getRuntimeService().getVariable(processInstance.getProcessInstanceId(), ENABLED, Boolean.class); if (updatedEnabled != null) { user.setSuspended(!updatedEnabled); } // this will make UserValidator not to consider password policies at all if (disablePwdPolicyCheck) { user.removeClearPassword(); } updateStatus(user); user = userDAO.save(user); Boolean propagateEnable = engine.getRuntimeService().getVariable( processInstance.getProcessInstanceId(), PROPAGATE_ENABLE, Boolean.class); if (propagateEnable == null) { propagateEnable = enabled; } PropagationByResource propByRes = new PropagationByResource(); propByRes.set(ResourceOperation.CREATE, userDAO.findAllResourceNames(user)); saveForFormSubmit(user, userTO.getPassword(), propByRes); Set<String> tasks = getPerformedTasks(user); cleanupHistory(user); return new WorkflowResult<Pair<Long, Boolean>>( new ImmutablePair<>(user.getKey(), propagateEnable), propByRes, tasks); } protected Set<String> doExecuteTask(final User user, final String task, final Map<String, Object> moreVariables) { Set<String> preTasks = getPerformedTasks(user); Map<String, Object> variables = new HashMap<>(); variables.put(WF_EXECUTOR, AuthContextUtils.getUsername()); variables.put(TASK, task); // using BeanUtils to access all user's properties and trigger lazy loading - we are about to // serialize a User instance for availability within workflow tasks, and this breaks transactions BeanUtils.copyProperties(user, entityFactory.newEntity(User.class)); variables.put(USER, user); if (moreVariables != null && !moreVariables.isEmpty()) { variables.putAll(moreVariables); } if (StringUtils.isBlank(user.getWorkflowId())) { throw new WorkflowException(new NotFoundException("Empty workflow id for " + user)); } List<Task> tasks = engine.getTaskService().createTaskQuery().processInstanceId(user.getWorkflowId()).list(); if (tasks.size() == 1) { try { engine.getTaskService().complete(tasks.get(0).getId(), variables); } catch (ActivitiException e) { throwException(e, "While completing task '" + tasks.get(0).getName() + "' for " + user); } } else { LOG.warn("Expected a single task, found {}", tasks.size()); } Set<String> postTasks = getPerformedTasks(user); postTasks.removeAll(preTasks); postTasks.add(task); cleanupHistory(user); return postTasks; } @Override protected WorkflowResult<Long> doActivate(final User user, final String token) { Set<String> tasks = doExecuteTask(user, "activate", Collections.singletonMap(TOKEN, (Object) token)); updateStatus(user); User updated = userDAO.save(user); return new WorkflowResult<>(updated.getKey(), null, tasks); } @Override protected WorkflowResult<Pair<UserPatch, Boolean>> doUpdate(final User user, final UserPatch userPatch) { Set<String> tasks = doExecuteTask(user, "update", Collections.singletonMap(USER_PATCH, (Object) userPatch)); updateStatus(user); User updated = userDAO.save(user); PropagationByResource propByRes = engine.getRuntimeService().getVariable( user.getWorkflowId(), PROP_BY_RESOURCE, PropagationByResource.class); UserPatch updatedPatch = engine.getRuntimeService().getVariable( user.getWorkflowId(), USER_PATCH, UserPatch.class); saveForFormSubmit( updated, updatedPatch.getPassword() == null ? null : updatedPatch.getPassword().getValue(), propByRes); Boolean propagateEnable = engine.getRuntimeService().getVariable( user.getWorkflowId(), PROPAGATE_ENABLE, Boolean.class); return new WorkflowResult<Pair<UserPatch, Boolean>>( new ImmutablePair<>(updatedPatch, propagateEnable), propByRes, tasks); } @Override protected WorkflowResult<Long> doSuspend(final User user) { Set<String> performedTasks = doExecuteTask(user, "suspend", null); updateStatus(user); User updated = userDAO.save(user); return new WorkflowResult<>(updated.getKey(), null, performedTasks); } @Override protected WorkflowResult<Long> doReactivate(final User user) { Set<String> performedTasks = doExecuteTask(user, "reactivate", null); updateStatus(user); User updated = userDAO.save(user); return new WorkflowResult<>(updated.getKey(), null, performedTasks); } @Override protected void doRequestPasswordReset(final User user) { Map<String, Object> variables = new HashMap<>(2); variables.put(USER_TO, dataBinder.getUserTO(user, true)); variables.put(EVENT, "requestPasswordReset"); doExecuteTask(user, "requestPasswordReset", variables); userDAO.save(user); } @Override protected WorkflowResult<Pair<UserPatch, Boolean>> doConfirmPasswordReset( final User user, final String token, final String password) { Map<String, Object> variables = new HashMap<>(4); variables.put(TOKEN, token); variables.put(PASSWORD, password); variables.put(USER_TO, dataBinder.getUserTO(user, true)); variables.put(EVENT, "confirmPasswordReset"); Set<String> tasks = doExecuteTask(user, "confirmPasswordReset", variables); userDAO.save(user); PropagationByResource propByRes = engine.getRuntimeService().getVariable( user.getWorkflowId(), PROP_BY_RESOURCE, PropagationByResource.class); UserPatch updatedPatch = engine.getRuntimeService().getVariable( user.getWorkflowId(), USER_PATCH, UserPatch.class); Boolean propagateEnable = engine.getRuntimeService().getVariable( user.getWorkflowId(), PROPAGATE_ENABLE, Boolean.class); return new WorkflowResult<Pair<UserPatch, Boolean>>( new ImmutablePair<>(updatedPatch, propagateEnable), propByRes, tasks); } @Override protected void doDelete(final User user) { doExecuteTask(user, "delete", null); PropagationByResource propByRes = new PropagationByResource(); propByRes.set(ResourceOperation.DELETE, userDAO.findAllResourceNames(user)); saveForFormSubmit(user, null, propByRes); if (engine.getRuntimeService().createProcessInstanceQuery(). processInstanceId(user.getWorkflowId()).active().list().isEmpty()) { userDAO.delete(user.getKey()); if (!engine.getHistoryService().createHistoricProcessInstanceQuery(). processInstanceId(user.getWorkflowId()).list().isEmpty()) { engine.getHistoryService().deleteHistoricProcessInstance(user.getWorkflowId()); } } else { updateStatus(user); userDAO.save(user); } } @Override public WorkflowResult<Long> execute(final UserTO userTO, final String taskId) { User user = userDAO.authFind(userTO.getKey()); final Map<String, Object> variables = new HashMap<>(); variables.put(USER_TO, userTO); Set<String> performedTasks = doExecuteTask(user, taskId, variables); updateStatus(user); User updated = userDAO.save(user); return new WorkflowResult<>(updated.getKey(), null, performedTasks); } protected ProcessDefinition getProcessDefinition() { try { return engine.getRepositoryService().createProcessDefinitionQuery().processDefinitionKey( ActivitiUserWorkflowAdapter.WF_PROCESS_ID).latestVersion().singleResult(); } catch (ActivitiException e) { throw new WorkflowException("While accessing process " + ActivitiUserWorkflowAdapter.WF_PROCESS_ID, e); } } protected Model getModel(final ProcessDefinition procDef) { try { Model model = engine.getRepositoryService().createModelQuery(). deploymentId(procDef.getDeploymentId()).singleResult(); if (model == null) { throw new NotFoundException("Could not find Model for deployment " + procDef.getDeploymentId()); } return model; } catch (Exception e) { throw new WorkflowException("While accessing process " + ActivitiUserWorkflowAdapter.WF_PROCESS_ID, e); } } protected void exportProcessResource(final String resourceName, final OutputStream os) { ProcessDefinition procDef = getProcessDefinition(); InputStream procDefIS = engine.getRepositoryService().getResourceAsStream(procDef.getDeploymentId(), resourceName); try { IOUtils.copy(procDefIS, os); } catch (IOException e) { LOG.error("While exporting workflow definition {}", procDef.getKey(), e); } finally { IOUtils.closeQuietly(procDefIS); } } protected void exportProcessModel(final OutputStream os) { Model model = getModel(getProcessDefinition()); ObjectMapper objectMapper = new ObjectMapper(); try { ObjectNode modelNode = (ObjectNode) objectMapper.readTree(model.getMetaInfo()); modelNode.put(ModelDataJsonConstants.MODEL_ID, model.getId()); modelNode.replace(MODEL_DATA_JSON_MODEL, objectMapper.readTree(engine.getRepositoryService().getModelEditorSource(model.getId()))); os.write(modelNode.toString().getBytes()); } catch (IOException e) { LOG.error("While exporting workflow definition {}", model.getId(), e); } } @Override public void exportDefinition(final WorkflowDefinitionFormat format, final OutputStream os) { switch (format) { case JSON: exportProcessModel(os); break; case XML: default: exportProcessResource(WF_PROCESS_RESOURCE, os); } } @Override public void exportDiagram(final OutputStream os) { exportProcessResource(WF_DGRM_RESOURCE, os); } @Override public void importDefinition(final WorkflowDefinitionFormat format, final String definition) { Model model = getModel(getProcessDefinition()); switch (format) { case JSON: JsonNode definitionNode; try { definitionNode = new ObjectMapper().readTree(definition); if (definitionNode.has(MODEL_DATA_JSON_MODEL)) { definitionNode = definitionNode.get(MODEL_DATA_JSON_MODEL); } if (!definitionNode.has(BpmnJsonConverter.EDITOR_CHILD_SHAPES)) { throw new IllegalArgumentException( "Could not find JSON node " + BpmnJsonConverter.EDITOR_CHILD_SHAPES); } BpmnModel bpmnModel = new BpmnJsonConverter().convertToBpmnModel(definitionNode); ActivitiImportUtils.fromXML(engine, new BpmnXMLConverter().convertToXML(bpmnModel)); } catch (Exception e) { throw new WorkflowException("While updating process " + ActivitiUserWorkflowAdapter.WF_PROCESS_RESOURCE, e); } ActivitiImportUtils.fromJSON( engine, definitionNode.toString().getBytes(), getProcessDefinition(), model); break; case XML: default: ActivitiImportUtils.fromXML(engine, definition.getBytes()); ActivitiImportUtils.fromJSON(engine, getProcessDefinition(), model); } } protected WorkflowFormPropertyType fromActivitiFormType(final FormType activitiFormType) { WorkflowFormPropertyType result = WorkflowFormPropertyType.String; if ("string".equals(activitiFormType.getName())) { result = WorkflowFormPropertyType.String; } if ("long".equals(activitiFormType.getName())) { result = WorkflowFormPropertyType.Long; } if ("enum".equals(activitiFormType.getName())) { result = WorkflowFormPropertyType.Enum; } if ("date".equals(activitiFormType.getName())) { result = WorkflowFormPropertyType.Date; } if ("boolean".equals(activitiFormType.getName())) { result = WorkflowFormPropertyType.Boolean; } return result; } protected WorkflowFormTO getFormTO(final Task task) { return getFormTO(task, engine.getFormService().getTaskFormData(task.getId())); } protected WorkflowFormTO getFormTO(final Task task, final TaskFormData fd) { final WorkflowFormTO formTO = getFormTO(task.getProcessInstanceId(), task.getId(), fd.getFormKey(), fd.getFormProperties()); BeanUtils.copyProperties(task, formTO); return formTO; } protected WorkflowFormTO getFormTO(final HistoricTaskInstance task) { final List<HistoricFormPropertyEntity> props = new ArrayList<>(); for (HistoricDetail historicDetail : engine.getHistoryService().createHistoricDetailQuery().taskId(task.getId()).list()) { if (historicDetail instanceof HistoricFormPropertyEntity) { props.add((HistoricFormPropertyEntity) historicDetail); } } final WorkflowFormTO formTO = getHistoricFormTO( task.getProcessInstanceId(), task.getId(), task.getFormKey(), props); BeanUtils.copyProperties(task, formTO); final HistoricActivityInstance historicActivityInstance = engine.getHistoryService(). createHistoricActivityInstanceQuery(). executionId(task.getExecutionId()).activityType("userTask").activityName(task.getName()).singleResult(); if (historicActivityInstance != null) { formTO.setCreateTime(historicActivityInstance.getStartTime()); formTO.setDueDate(historicActivityInstance.getEndTime()); } return formTO; } protected WorkflowFormTO getHistoricFormTO( final String processInstanceId, final String taskId, final String formKey, final List<HistoricFormPropertyEntity> props) { WorkflowFormTO formTO = new WorkflowFormTO(); User user = userDAO.findByWorkflowId(processInstanceId); if (user == null) { throw new NotFoundException("User with workflow id " + processInstanceId); } formTO.setUserKey(user.getKey()); formTO.setTaskId(taskId); formTO.setKey(formKey); for (HistoricFormPropertyEntity prop : props) { WorkflowFormPropertyTO propertyTO = new WorkflowFormPropertyTO(); propertyTO.setId(prop.getPropertyId()); propertyTO.setName(prop.getPropertyId()); propertyTO.setValue(prop.getPropertyValue()); formTO.addProperty(propertyTO); } return formTO; } @SuppressWarnings("unchecked") protected WorkflowFormTO getFormTO( final String processInstanceId, final String taskId, final String formKey, final List<FormProperty> properties) { WorkflowFormTO formTO = new WorkflowFormTO(); User user = userDAO.findByWorkflowId(processInstanceId); if (user == null) { throw new NotFoundException("User with workflow id " + processInstanceId); } formTO.setUserKey(user.getKey()); formTO.setTaskId(taskId); formTO.setKey(formKey); for (FormProperty fProp : properties) { WorkflowFormPropertyTO propertyTO = new WorkflowFormPropertyTO(); BeanUtils.copyProperties(fProp, propertyTO, PROPERTY_IGNORE_PROPS); propertyTO.setType(fromActivitiFormType(fProp.getType())); if (propertyTO.getType() == WorkflowFormPropertyType.Date) { propertyTO.setDatePattern((String) fProp.getType().getInformation("datePattern")); } if (propertyTO.getType() == WorkflowFormPropertyType.Enum) { propertyTO.getEnumValues().putAll((Map<String, String>) fProp.getType().getInformation("values")); } formTO.addProperty(propertyTO); } return formTO; } @Transactional(readOnly = true) @Override public List<WorkflowFormTO> getForms() { List<WorkflowFormTO> forms = new ArrayList<>(); String authUser = AuthContextUtils.getUsername(); if (adminUser.equals(authUser)) { forms.addAll(getForms(engine.getTaskService().createTaskQuery(). taskVariableValueEquals(TASK_IS_FORM, Boolean.TRUE))); } else { User user = userDAO.find(authUser); if (user == null) { throw new NotFoundException("Syncope User " + authUser); } forms.addAll(getForms(engine.getTaskService().createTaskQuery(). taskVariableValueEquals(TASK_IS_FORM, Boolean.TRUE). taskCandidateOrAssigned(user.getKey().toString()))); List<String> candidateGroups = new ArrayList<>(); for (Long groupId : userDAO.findAllGroupKeys(user)) { candidateGroups.add(groupId.toString()); } if (!candidateGroups.isEmpty()) { forms.addAll(getForms(engine.getTaskService().createTaskQuery(). taskVariableValueEquals(TASK_IS_FORM, Boolean.TRUE). taskCandidateGroupIn(candidateGroups))); } } return forms; } @Override public List<WorkflowFormTO> getForms(final String workflowId, final String name) { List<WorkflowFormTO> forms = getForms( engine.getTaskService().createTaskQuery().processInstanceId(workflowId).taskName(name). taskVariableValueEquals(TASK_IS_FORM, Boolean.TRUE)); forms.addAll(getForms(engine.getHistoryService().createHistoricTaskInstanceQuery().taskName(name). taskVariableValueEquals(TASK_IS_FORM, Boolean.TRUE))); return forms; } protected <T extends Query<?, ?>, U extends Object> List<WorkflowFormTO> getForms(final Query<T, U> query) { List<WorkflowFormTO> forms = new ArrayList<>(); for (U obj : query.list()) { try { if (obj instanceof HistoricTaskInstance) { forms.add(getFormTO((HistoricTaskInstance) obj)); } else if (obj instanceof Task) { forms.add(getFormTO((Task) obj)); } else { throw new ActivitiException( "Failure retrieving form", new IllegalArgumentException("Invalid task type")); } } catch (ActivitiException e) { LOG.debug("No form found for task {}", obj, e); } } return forms; } @Override public WorkflowFormTO getForm(final String workflowId) { Task task; try { task = engine.getTaskService().createTaskQuery().processInstanceId(workflowId).singleResult(); } catch (ActivitiException e) { throw new WorkflowException("While reading form for workflow instance " + workflowId, e); } TaskFormData formData; try { formData = engine.getFormService().getTaskFormData(task.getId()); } catch (ActivitiException e) { LOG.debug("No form found for task {}", task.getId(), e); formData = null; } WorkflowFormTO result = null; if (formData != null && !formData.getFormProperties().isEmpty()) { result = getFormTO(task); } return result; } protected Pair<Task, TaskFormData> checkTask(final String taskId, final String authUser) { Task task; try { task = engine.getTaskService().createTaskQuery().taskId(taskId).singleResult(); if (task == null) { throw new ActivitiException("NULL result"); } } catch (ActivitiException e) { throw new NotFoundException("Activiti Task " + taskId, e); } TaskFormData formData; try { formData = engine.getFormService().getTaskFormData(task.getId()); } catch (ActivitiException e) { throw new NotFoundException("Form for Activiti Task " + taskId, e); } if (!adminUser.equals(authUser)) { User user = userDAO.find(authUser); if (user == null) { throw new NotFoundException("Syncope User " + authUser); } } return new ImmutablePair<>(task, formData); } @Override public WorkflowFormTO claimForm(final String taskId) { String authUser = AuthContextUtils.getUsername(); Pair<Task, TaskFormData> checked = checkTask(taskId, authUser); if (!adminUser.equals(authUser)) { List<Task> tasksForUser = engine.getTaskService().createTaskQuery().taskId(taskId).taskCandidateUser( authUser).list(); if (tasksForUser.isEmpty()) { throw new WorkflowException( new IllegalArgumentException(authUser + " is not candidate for task " + taskId)); } } Task task; try { engine.getTaskService().setOwner(taskId, authUser); task = engine.getTaskService().createTaskQuery().taskId(taskId).singleResult(); } catch (ActivitiException e) { throw new WorkflowException("While reading task " + taskId, e); } return getFormTO(task, checked.getValue()); } @Override public WorkflowResult<UserPatch> submitForm(final WorkflowFormTO form) { String authUser = AuthContextUtils.getUsername(); Pair<Task, TaskFormData> checked = checkTask(form.getTaskId(), authUser); if (!checked.getKey().getOwner().equals(authUser)) { throw new WorkflowException(new IllegalArgumentException("Task " + form.getTaskId() + " assigned to " + checked.getKey().getOwner() + " but submitted by " + authUser)); } User user = userDAO.findByWorkflowId(checked.getKey().getProcessInstanceId()); if (user == null) { throw new NotFoundException("User with workflow id " + checked.getKey().getProcessInstanceId()); } Set<String> preTasks = getPerformedTasks(user); try { engine.getFormService().submitTaskFormData(form.getTaskId(), form.getPropertiesForSubmit()); engine.getRuntimeService().setVariable(user.getWorkflowId(), FORM_SUBMITTER, authUser); } catch (ActivitiException e) { throwException(e, "While submitting form for task " + form.getTaskId()); } Set<String> postTasks = getPerformedTasks(user); postTasks.removeAll(preTasks); postTasks.add(form.getTaskId()); updateStatus(user); User updated = userDAO.save(user); // see if there is any propagation to be done PropagationByResource propByRes = engine.getRuntimeService().getVariable( user.getWorkflowId(), PROP_BY_RESOURCE, PropagationByResource.class); // fetch - if available - the encrypted password String clearPassword = null; String encryptedPwd = engine.getRuntimeService().getVariable(user.getWorkflowId(), ENCRYPTED_PWD, String.class); if (StringUtils.isNotBlank(encryptedPwd)) { clearPassword = decrypt(encryptedPwd); } // supports approval chains saveForFormSubmit(user, clearPassword, propByRes); UserPatch userPatch = engine.getRuntimeService().getVariable(user.getWorkflowId(), USER_PATCH, UserPatch.class); if (userPatch == null) { userPatch = new UserPatch(); userPatch.setKey(updated.getKey()); userPatch.setPassword(new PasswordPatch.Builder().onSyncope(true).value(clearPassword).build()); if (propByRes != null) { userPatch.getPassword().getResources().addAll(propByRes.get(ResourceOperation.CREATE)); } } cleanupHistory(user); return new WorkflowResult<>(userPatch, propByRes, postTasks); } }
core/workflow-activiti/src/main/java/org/apache/syncope/core/workflow/activiti/ActivitiUserWorkflowAdapter.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.syncope.core.workflow.activiti; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.Resource; import javax.ws.rs.NotFoundException; import org.activiti.bpmn.converter.BpmnXMLConverter; import org.activiti.bpmn.model.BpmnModel; import org.activiti.editor.constants.ModelDataJsonConstants; import org.activiti.editor.language.json.converter.BpmnJsonConverter; import org.activiti.engine.ActivitiException; import org.activiti.engine.form.FormProperty; import org.activiti.engine.form.FormType; import org.activiti.engine.form.TaskFormData; import org.activiti.engine.history.HistoricActivityInstance; import org.activiti.engine.history.HistoricDetail; import org.activiti.engine.history.HistoricTaskInstance; import org.activiti.engine.impl.persistence.entity.HistoricFormPropertyEntity; import org.activiti.engine.query.Query; import org.activiti.engine.repository.Model; import org.activiti.engine.repository.ProcessDefinition; import org.activiti.engine.runtime.ProcessInstance; import org.activiti.engine.task.Task; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; import org.apache.syncope.common.lib.SyncopeClientException; import org.apache.syncope.common.lib.patch.PasswordPatch; import org.apache.syncope.common.lib.patch.UserPatch; import org.apache.syncope.common.lib.to.UserTO; import org.apache.syncope.common.lib.to.WorkflowFormPropertyTO; import org.apache.syncope.common.lib.to.WorkflowFormTO; import org.apache.syncope.common.lib.types.PropagationByResource; import org.apache.syncope.common.lib.types.ResourceOperation; import org.apache.syncope.common.lib.types.WorkflowFormPropertyType; import org.apache.syncope.core.misc.security.AuthContextUtils; import org.apache.syncope.core.misc.spring.BeanUtils; import org.apache.syncope.core.persistence.api.attrvalue.validation.InvalidEntityException; import org.apache.syncope.core.persistence.api.attrvalue.validation.ParsingValidationException; import org.apache.syncope.core.persistence.api.entity.user.User; import org.apache.syncope.core.provisioning.api.WorkflowResult; import org.apache.syncope.core.provisioning.api.data.UserDataBinder; import org.apache.syncope.core.workflow.activiti.spring.DomainProcessEngine; import org.apache.syncope.core.workflow.api.WorkflowDefinitionFormat; import org.apache.syncope.core.workflow.api.WorkflowException; import org.apache.syncope.core.workflow.java.AbstractUserWorkflowAdapter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.transaction.annotation.Transactional; /** * <a href="http://www.activiti.org/">Activiti</a> based implementation. */ public class ActivitiUserWorkflowAdapter extends AbstractUserWorkflowAdapter { protected static final String[] PROPERTY_IGNORE_PROPS = { "type" }; public static final String WF_PROCESS_ID = "userWorkflow"; public static final String WF_PROCESS_RESOURCE = "userWorkflow.bpmn20.xml"; public static final String WF_DGRM_RESOURCE = "userWorkflow.userWorkflow.png"; public static final String USER = "user"; public static final String WF_EXECUTOR = "wfExecutor"; public static final String FORM_SUBMITTER = "formSubmitter"; public static final String USER_TO = "userTO"; public static final String ENABLED = "enabled"; public static final String USER_PATCH = "userPatch"; public static final String EMAIL_KIND = "emailKind"; public static final String TASK = "task"; public static final String TOKEN = "token"; public static final String PASSWORD = "password"; public static final String PROP_BY_RESOURCE = "propByResource"; public static final String PROPAGATE_ENABLE = "propagateEnable"; public static final String ENCRYPTED_PWD = "encryptedPwd"; public static final String TASK_IS_FORM = "taskIsForm"; public static final String MODEL_DATA_JSON_MODEL = "model"; public static final String STORE_PASSWORD = "storePassword"; public static final String EVENT = "event"; @Resource(name = "adminUser") protected String adminUser; @Autowired protected DomainProcessEngine engine; @Autowired protected UserDataBinder userDataBinder; @Override public String getPrefix() { return "ACT_"; } protected void throwException(final ActivitiException e, final String defaultMessage) { if (e.getCause() != null) { if (e.getCause().getCause() instanceof SyncopeClientException) { throw (SyncopeClientException) e.getCause().getCause(); } else if (e.getCause().getCause() instanceof ParsingValidationException) { throw (ParsingValidationException) e.getCause().getCause(); } else if (e.getCause().getCause() instanceof InvalidEntityException) { throw (InvalidEntityException) e.getCause().getCause(); } } throw new WorkflowException(defaultMessage, e); } protected void updateStatus(final User user) { List<Task> tasks = engine.getTaskService().createTaskQuery().processInstanceId(user.getWorkflowId()).list(); if (tasks.isEmpty() || tasks.size() > 1) { LOG.warn("While setting user status: unexpected task number ({})", tasks.size()); } else { user.setStatus(tasks.get(0).getTaskDefinitionKey()); } } protected String getFormTask(final User user) { String result = null; List<Task> tasks = engine.getTaskService().createTaskQuery().processInstanceId(user.getWorkflowId()).list(); if (tasks.isEmpty() || tasks.size() > 1) { LOG.warn("While checking if form task: unexpected task number ({})", tasks.size()); } else { try { TaskFormData formData = engine.getFormService().getTaskFormData(tasks.get(0).getId()); if (formData != null && !formData.getFormProperties().isEmpty()) { result = tasks.get(0).getId(); } } catch (ActivitiException e) { LOG.warn("Could not get task form data", e); } } return result; } protected Set<String> getPerformedTasks(final User user) { final Set<String> result = new HashSet<>(); for (HistoricActivityInstance task : engine.getHistoryService().createHistoricActivityInstanceQuery(). executionId(user.getWorkflowId()).list()) { result.add(task.getActivityId()); } return result; } protected void cleanupHistory(final User user) { JdbcTemplate jdbcTemplate = new JdbcTemplate(engine.getDataSource()); List<String> taskIds = jdbcTemplate.queryForList( "SELECT TASK_ID_ FROM ACT_HI_VARINST WHERE NAME_='" + TASK_IS_FORM + "' AND LONG_=1 AND PROC_INST_ID_='" + user.getWorkflowId() + "'", String.class); StringBuilder update = new StringBuilder(); update.append("DELETE FROM ACT_HI_VARINST WHERE PROC_INST_ID_='").append(user.getWorkflowId()).append("' "); for (String taskId : taskIds) { update.append("AND TASK_ID_<>'").append(taskId).append("' "); } jdbcTemplate.execute(update.toString()); update.setLength(0); update.append("DELETE FROM ACT_HI_TASKINST WHERE PROC_INST_ID_='").append(user.getWorkflowId()).append("' "); for (String taskId : taskIds) { update.append("AND ID_<>'").append(taskId).append("' "); } jdbcTemplate.execute(update.toString()); update.setLength(0); update.append("DELETE FROM ACT_HI_ACTINST WHERE PROC_INST_ID_='").append(user.getWorkflowId()).append("' "); for (String taskId : taskIds) { update.append("AND TASK_ID_<>'").append(taskId).append("' "); } jdbcTemplate.execute(update.toString()); List<String> byteArrayIds = jdbcTemplate.queryForList( "SELECT BYTEARRAY_ID_ FROM ACT_HI_VARINST WHERE BYTEARRAY_ID_ IS NOT NULL", String.class); update.setLength(0); update.append("DELETE FROM ACT_GE_BYTEARRAY WHERE NAME_ LIKE 'hist.%' "); for (String byteArrayId : byteArrayIds) { update.append("AND ID_<>'").append(byteArrayId).append("' "); } jdbcTemplate.execute(update.toString()); } /** * Saves resources to be propagated and password for later - after form submission - propagation. * * @param user user * @param password pasword * @param propByRes current propagation actions against resources */ protected void saveForFormSubmit(final User user, final String password, final PropagationByResource propByRes) { String formTaskId = getFormTask(user); if (formTaskId != null) { // SYNCOPE-238: This is needed to simplify the task query in this.getForms() engine.getTaskService().setVariableLocal(formTaskId, TASK_IS_FORM, Boolean.TRUE); engine.getRuntimeService().setVariable(user.getWorkflowId(), PROP_BY_RESOURCE, propByRes); if (propByRes != null) { propByRes.clear(); } if (StringUtils.isNotBlank(password)) { engine.getRuntimeService().setVariable(user.getWorkflowId(), ENCRYPTED_PWD, encrypt(password)); } } } @Override public WorkflowResult<Pair<Long, Boolean>> create(final UserTO userTO, final boolean disablePwdPolicyCheck, final boolean storePassword) { return create(userTO, disablePwdPolicyCheck, null, storePassword); } @Override public WorkflowResult<Pair<Long, Boolean>> create(final UserTO userTO, final boolean storePassword) { return create(userTO, false, storePassword); } @Override public WorkflowResult<Pair<Long, Boolean>> create(final UserTO userTO, final boolean disablePwdPolicyCheck, final Boolean enabled, final boolean storePassword) { Map<String, Object> variables = new HashMap<>(); variables.put(WF_EXECUTOR, AuthContextUtils.getUsername()); variables.put(USER_TO, userTO); variables.put(ENABLED, enabled); variables.put(STORE_PASSWORD, storePassword); ProcessInstance processInstance = null; try { processInstance = engine.getRuntimeService().startProcessInstanceByKey(WF_PROCESS_ID, variables); } catch (ActivitiException e) { throwException(e, "While starting " + WF_PROCESS_ID + " instance"); } User user = engine.getRuntimeService().getVariable(processInstance.getProcessInstanceId(), USER, User.class); Boolean updatedEnabled = engine.getRuntimeService().getVariable(processInstance.getProcessInstanceId(), ENABLED, Boolean.class); if (updatedEnabled != null) { user.setSuspended(!updatedEnabled); } // this will make UserValidator not to consider password policies at all if (disablePwdPolicyCheck) { user.removeClearPassword(); } updateStatus(user); user = userDAO.save(user); Boolean propagateEnable = engine.getRuntimeService().getVariable( processInstance.getProcessInstanceId(), PROPAGATE_ENABLE, Boolean.class); if (propagateEnable == null) { propagateEnable = enabled; } PropagationByResource propByRes = new PropagationByResource(); propByRes.set(ResourceOperation.CREATE, userDAO.findAllResourceNames(user)); saveForFormSubmit(user, userTO.getPassword(), propByRes); Set<String> tasks = getPerformedTasks(user); cleanupHistory(user); return new WorkflowResult<Pair<Long, Boolean>>( new ImmutablePair<>(user.getKey(), propagateEnable), propByRes, tasks); } protected Set<String> doExecuteTask(final User user, final String task, final Map<String, Object> moreVariables) { Set<String> preTasks = getPerformedTasks(user); Map<String, Object> variables = new HashMap<>(); variables.put(WF_EXECUTOR, AuthContextUtils.getUsername()); variables.put(TASK, task); // using BeanUtils to access all user's properties and trigger lazy loading - we are about to // serialize a User instance for availability within workflow tasks, and this breaks transactions BeanUtils.copyProperties(user, entityFactory.newEntity(User.class)); variables.put(USER, user); if (moreVariables != null && !moreVariables.isEmpty()) { variables.putAll(moreVariables); } if (StringUtils.isBlank(user.getWorkflowId())) { throw new WorkflowException(new NotFoundException("Empty workflow id for " + user)); } List<Task> tasks = engine.getTaskService().createTaskQuery().processInstanceId(user.getWorkflowId()).list(); if (tasks.size() == 1) { try { engine.getTaskService().complete(tasks.get(0).getId(), variables); } catch (ActivitiException e) { throwException(e, "While completing task '" + tasks.get(0).getName() + "' for " + user); } } else { LOG.warn("Expected a single task, found {}", tasks.size()); } Set<String> postTasks = getPerformedTasks(user); postTasks.removeAll(preTasks); postTasks.add(task); cleanupHistory(user); return postTasks; } @Override protected WorkflowResult<Long> doActivate(final User user, final String token) { Set<String> tasks = doExecuteTask(user, "activate", Collections.singletonMap(TOKEN, (Object) token)); updateStatus(user); User updated = userDAO.save(user); return new WorkflowResult<>(updated.getKey(), null, tasks); } @Override protected WorkflowResult<Pair<UserPatch, Boolean>> doUpdate(final User user, final UserPatch userPatch) { Set<String> tasks = doExecuteTask(user, "update", Collections.singletonMap(USER_PATCH, (Object) userPatch)); updateStatus(user); User updated = userDAO.save(user); PropagationByResource propByRes = engine.getRuntimeService().getVariable( user.getWorkflowId(), PROP_BY_RESOURCE, PropagationByResource.class); UserPatch updatedPatch = engine.getRuntimeService().getVariable( user.getWorkflowId(), USER_PATCH, UserPatch.class); saveForFormSubmit( updated, updatedPatch.getPassword() == null ? null : updatedPatch.getPassword().getValue(), propByRes); Boolean propagateEnable = engine.getRuntimeService().getVariable( user.getWorkflowId(), PROPAGATE_ENABLE, Boolean.class); return new WorkflowResult<Pair<UserPatch, Boolean>>( new ImmutablePair<>(updatedPatch, propagateEnable), propByRes, tasks); } @Override protected WorkflowResult<Long> doSuspend(final User user) { Set<String> performedTasks = doExecuteTask(user, "suspend", null); updateStatus(user); User updated = userDAO.save(user); return new WorkflowResult<>(updated.getKey(), null, performedTasks); } @Override protected WorkflowResult<Long> doReactivate(final User user) { Set<String> performedTasks = doExecuteTask(user, "reactivate", null); updateStatus(user); User updated = userDAO.save(user); return new WorkflowResult<>(updated.getKey(), null, performedTasks); } @Override protected void doRequestPasswordReset(final User user) { Map<String, Object> variables = new HashMap<>(2); variables.put(USER_TO, userDataBinder.getUserTO(user, true)); variables.put(EVENT, "requestPasswordReset"); doExecuteTask(user, "requestPasswordReset", variables); userDAO.save(user); } @Override protected WorkflowResult<Pair<UserPatch, Boolean>> doConfirmPasswordReset( final User user, final String token, final String password) { Map<String, Object> variables = new HashMap<>(4); variables.put(TOKEN, token); variables.put(PASSWORD, password); variables.put(USER_TO, userDataBinder.getUserTO(user, true)); variables.put(EVENT, "confirmPasswordReset"); Set<String> tasks = doExecuteTask(user, "confirmPasswordReset", variables); userDAO.save(user); PropagationByResource propByRes = engine.getRuntimeService().getVariable( user.getWorkflowId(), PROP_BY_RESOURCE, PropagationByResource.class); UserPatch updatedPatch = engine.getRuntimeService().getVariable( user.getWorkflowId(), USER_PATCH, UserPatch.class); Boolean propagateEnable = engine.getRuntimeService().getVariable( user.getWorkflowId(), PROPAGATE_ENABLE, Boolean.class); return new WorkflowResult<Pair<UserPatch, Boolean>>( new ImmutablePair<>(updatedPatch, propagateEnable), propByRes, tasks); } @Override protected void doDelete(final User user) { doExecuteTask(user, "delete", null); PropagationByResource propByRes = new PropagationByResource(); propByRes.set(ResourceOperation.DELETE, userDAO.findAllResourceNames(user)); saveForFormSubmit(user, null, propByRes); if (engine.getRuntimeService().createProcessInstanceQuery(). processInstanceId(user.getWorkflowId()).active().list().isEmpty()) { userDAO.delete(user.getKey()); if (!engine.getHistoryService().createHistoricProcessInstanceQuery(). processInstanceId(user.getWorkflowId()).list().isEmpty()) { engine.getHistoryService().deleteHistoricProcessInstance(user.getWorkflowId()); } } else { updateStatus(user); userDAO.save(user); } } @Override public WorkflowResult<Long> execute(final UserTO userTO, final String taskId) { User user = userDAO.authFind(userTO.getKey()); final Map<String, Object> variables = new HashMap<>(); variables.put(USER_TO, userTO); Set<String> performedTasks = doExecuteTask(user, taskId, variables); updateStatus(user); User updated = userDAO.save(user); return new WorkflowResult<>(updated.getKey(), null, performedTasks); } protected ProcessDefinition getProcessDefinition() { try { return engine.getRepositoryService().createProcessDefinitionQuery().processDefinitionKey( ActivitiUserWorkflowAdapter.WF_PROCESS_ID).latestVersion().singleResult(); } catch (ActivitiException e) { throw new WorkflowException("While accessing process " + ActivitiUserWorkflowAdapter.WF_PROCESS_ID, e); } } protected Model getModel(final ProcessDefinition procDef) { try { Model model = engine.getRepositoryService().createModelQuery(). deploymentId(procDef.getDeploymentId()).singleResult(); if (model == null) { throw new NotFoundException("Could not find Model for deployment " + procDef.getDeploymentId()); } return model; } catch (Exception e) { throw new WorkflowException("While accessing process " + ActivitiUserWorkflowAdapter.WF_PROCESS_ID, e); } } protected void exportProcessResource(final String resourceName, final OutputStream os) { ProcessDefinition procDef = getProcessDefinition(); InputStream procDefIS = engine.getRepositoryService().getResourceAsStream(procDef.getDeploymentId(), resourceName); try { IOUtils.copy(procDefIS, os); } catch (IOException e) { LOG.error("While exporting workflow definition {}", procDef.getKey(), e); } finally { IOUtils.closeQuietly(procDefIS); } } protected void exportProcessModel(final OutputStream os) { Model model = getModel(getProcessDefinition()); ObjectMapper objectMapper = new ObjectMapper(); try { ObjectNode modelNode = (ObjectNode) objectMapper.readTree(model.getMetaInfo()); modelNode.put(ModelDataJsonConstants.MODEL_ID, model.getId()); modelNode.replace(MODEL_DATA_JSON_MODEL, objectMapper.readTree(engine.getRepositoryService().getModelEditorSource(model.getId()))); os.write(modelNode.toString().getBytes()); } catch (IOException e) { LOG.error("While exporting workflow definition {}", model.getId(), e); } } @Override public void exportDefinition(final WorkflowDefinitionFormat format, final OutputStream os) { switch (format) { case JSON: exportProcessModel(os); break; case XML: default: exportProcessResource(WF_PROCESS_RESOURCE, os); } } @Override public void exportDiagram(final OutputStream os) { exportProcessResource(WF_DGRM_RESOURCE, os); } @Override public void importDefinition(final WorkflowDefinitionFormat format, final String definition) { Model model = getModel(getProcessDefinition()); switch (format) { case JSON: JsonNode definitionNode; try { definitionNode = new ObjectMapper().readTree(definition); if (definitionNode.has(MODEL_DATA_JSON_MODEL)) { definitionNode = definitionNode.get(MODEL_DATA_JSON_MODEL); } if (!definitionNode.has(BpmnJsonConverter.EDITOR_CHILD_SHAPES)) { throw new IllegalArgumentException( "Could not find JSON node " + BpmnJsonConverter.EDITOR_CHILD_SHAPES); } BpmnModel bpmnModel = new BpmnJsonConverter().convertToBpmnModel(definitionNode); ActivitiImportUtils.fromXML(engine, new BpmnXMLConverter().convertToXML(bpmnModel)); } catch (Exception e) { throw new WorkflowException("While updating process " + ActivitiUserWorkflowAdapter.WF_PROCESS_RESOURCE, e); } ActivitiImportUtils.fromJSON( engine, definitionNode.toString().getBytes(), getProcessDefinition(), model); break; case XML: default: ActivitiImportUtils.fromXML(engine, definition.getBytes()); ActivitiImportUtils.fromJSON(engine, getProcessDefinition(), model); } } protected WorkflowFormPropertyType fromActivitiFormType(final FormType activitiFormType) { WorkflowFormPropertyType result = WorkflowFormPropertyType.String; if ("string".equals(activitiFormType.getName())) { result = WorkflowFormPropertyType.String; } if ("long".equals(activitiFormType.getName())) { result = WorkflowFormPropertyType.Long; } if ("enum".equals(activitiFormType.getName())) { result = WorkflowFormPropertyType.Enum; } if ("date".equals(activitiFormType.getName())) { result = WorkflowFormPropertyType.Date; } if ("boolean".equals(activitiFormType.getName())) { result = WorkflowFormPropertyType.Boolean; } return result; } protected WorkflowFormTO getFormTO(final Task task) { return getFormTO(task, engine.getFormService().getTaskFormData(task.getId())); } protected WorkflowFormTO getFormTO(final Task task, final TaskFormData fd) { final WorkflowFormTO formTO = getFormTO(task.getProcessInstanceId(), task.getId(), fd.getFormKey(), fd.getFormProperties()); BeanUtils.copyProperties(task, formTO); return formTO; } protected WorkflowFormTO getFormTO(final HistoricTaskInstance task) { final List<HistoricFormPropertyEntity> props = new ArrayList<>(); for (HistoricDetail historicDetail : engine.getHistoryService().createHistoricDetailQuery().taskId(task.getId()).list()) { if (historicDetail instanceof HistoricFormPropertyEntity) { props.add((HistoricFormPropertyEntity) historicDetail); } } final WorkflowFormTO formTO = getHistoricFormTO( task.getProcessInstanceId(), task.getId(), task.getFormKey(), props); BeanUtils.copyProperties(task, formTO); final HistoricActivityInstance historicActivityInstance = engine.getHistoryService(). createHistoricActivityInstanceQuery(). executionId(task.getExecutionId()).activityType("userTask").activityName(task.getName()).singleResult(); if (historicActivityInstance != null) { formTO.setCreateTime(historicActivityInstance.getStartTime()); formTO.setDueDate(historicActivityInstance.getEndTime()); } return formTO; } protected WorkflowFormTO getHistoricFormTO( final String processInstanceId, final String taskId, final String formKey, final List<HistoricFormPropertyEntity> props) { WorkflowFormTO formTO = new WorkflowFormTO(); User user = userDAO.findByWorkflowId(processInstanceId); if (user == null) { throw new NotFoundException("User with workflow id " + processInstanceId); } formTO.setUserKey(user.getKey()); formTO.setTaskId(taskId); formTO.setKey(formKey); for (HistoricFormPropertyEntity prop : props) { WorkflowFormPropertyTO propertyTO = new WorkflowFormPropertyTO(); propertyTO.setId(prop.getPropertyId()); propertyTO.setName(prop.getPropertyId()); propertyTO.setValue(prop.getPropertyValue()); formTO.addProperty(propertyTO); } return formTO; } @SuppressWarnings("unchecked") protected WorkflowFormTO getFormTO( final String processInstanceId, final String taskId, final String formKey, final List<FormProperty> properties) { WorkflowFormTO formTO = new WorkflowFormTO(); User user = userDAO.findByWorkflowId(processInstanceId); if (user == null) { throw new NotFoundException("User with workflow id " + processInstanceId); } formTO.setUserKey(user.getKey()); formTO.setTaskId(taskId); formTO.setKey(formKey); for (FormProperty fProp : properties) { WorkflowFormPropertyTO propertyTO = new WorkflowFormPropertyTO(); BeanUtils.copyProperties(fProp, propertyTO, PROPERTY_IGNORE_PROPS); propertyTO.setType(fromActivitiFormType(fProp.getType())); if (propertyTO.getType() == WorkflowFormPropertyType.Date) { propertyTO.setDatePattern((String) fProp.getType().getInformation("datePattern")); } if (propertyTO.getType() == WorkflowFormPropertyType.Enum) { propertyTO.getEnumValues().putAll((Map<String, String>) fProp.getType().getInformation("values")); } formTO.addProperty(propertyTO); } return formTO; } @Transactional(readOnly = true) @Override public List<WorkflowFormTO> getForms() { List<WorkflowFormTO> forms = new ArrayList<>(); String authUser = AuthContextUtils.getUsername(); if (adminUser.equals(authUser)) { forms.addAll(getForms(engine.getTaskService().createTaskQuery(). taskVariableValueEquals(TASK_IS_FORM, Boolean.TRUE))); } else { User user = userDAO.find(authUser); if (user == null) { throw new NotFoundException("Syncope User " + authUser); } forms.addAll(getForms(engine.getTaskService().createTaskQuery(). taskVariableValueEquals(TASK_IS_FORM, Boolean.TRUE). taskCandidateOrAssigned(user.getKey().toString()))); List<String> candidateGroups = new ArrayList<>(); for (Long groupId : userDAO.findAllGroupKeys(user)) { candidateGroups.add(groupId.toString()); } if (!candidateGroups.isEmpty()) { forms.addAll(getForms(engine.getTaskService().createTaskQuery(). taskVariableValueEquals(TASK_IS_FORM, Boolean.TRUE). taskCandidateGroupIn(candidateGroups))); } } return forms; } @Override public List<WorkflowFormTO> getForms(final String workflowId, final String name) { List<WorkflowFormTO> forms = getForms( engine.getTaskService().createTaskQuery().processInstanceId(workflowId).taskName(name). taskVariableValueEquals(TASK_IS_FORM, Boolean.TRUE)); forms.addAll(getForms(engine.getHistoryService().createHistoricTaskInstanceQuery().taskName(name). taskVariableValueEquals(TASK_IS_FORM, Boolean.TRUE))); return forms; } protected <T extends Query<?, ?>, U extends Object> List<WorkflowFormTO> getForms(final Query<T, U> query) { List<WorkflowFormTO> forms = new ArrayList<>(); for (U obj : query.list()) { try { if (obj instanceof HistoricTaskInstance) { forms.add(getFormTO((HistoricTaskInstance) obj)); } else if (obj instanceof Task) { forms.add(getFormTO((Task) obj)); } else { throw new ActivitiException( "Failure retrieving form", new IllegalArgumentException("Invalid task type")); } } catch (ActivitiException e) { LOG.debug("No form found for task {}", obj, e); } } return forms; } @Override public WorkflowFormTO getForm(final String workflowId) { Task task; try { task = engine.getTaskService().createTaskQuery().processInstanceId(workflowId).singleResult(); } catch (ActivitiException e) { throw new WorkflowException("While reading form for workflow instance " + workflowId, e); } TaskFormData formData; try { formData = engine.getFormService().getTaskFormData(task.getId()); } catch (ActivitiException e) { LOG.debug("No form found for task {}", task.getId(), e); formData = null; } WorkflowFormTO result = null; if (formData != null && !formData.getFormProperties().isEmpty()) { result = getFormTO(task); } return result; } protected Pair<Task, TaskFormData> checkTask(final String taskId, final String authUser) { Task task; try { task = engine.getTaskService().createTaskQuery().taskId(taskId).singleResult(); if (task == null) { throw new ActivitiException("NULL result"); } } catch (ActivitiException e) { throw new NotFoundException("Activiti Task " + taskId, e); } TaskFormData formData; try { formData = engine.getFormService().getTaskFormData(task.getId()); } catch (ActivitiException e) { throw new NotFoundException("Form for Activiti Task " + taskId, e); } if (!adminUser.equals(authUser)) { User user = userDAO.find(authUser); if (user == null) { throw new NotFoundException("Syncope User " + authUser); } } return new ImmutablePair<>(task, formData); } @Override public WorkflowFormTO claimForm(final String taskId) { String authUser = AuthContextUtils.getUsername(); Pair<Task, TaskFormData> checked = checkTask(taskId, authUser); if (!adminUser.equals(authUser)) { List<Task> tasksForUser = engine.getTaskService().createTaskQuery().taskId(taskId).taskCandidateUser( authUser).list(); if (tasksForUser.isEmpty()) { throw new WorkflowException( new IllegalArgumentException(authUser + " is not candidate for task " + taskId)); } } Task task; try { engine.getTaskService().setOwner(taskId, authUser); task = engine.getTaskService().createTaskQuery().taskId(taskId).singleResult(); } catch (ActivitiException e) { throw new WorkflowException("While reading task " + taskId, e); } return getFormTO(task, checked.getValue()); } @Override public WorkflowResult<UserPatch> submitForm(final WorkflowFormTO form) { String authUser = AuthContextUtils.getUsername(); Pair<Task, TaskFormData> checked = checkTask(form.getTaskId(), authUser); if (!checked.getKey().getOwner().equals(authUser)) { throw new WorkflowException(new IllegalArgumentException("Task " + form.getTaskId() + " assigned to " + checked.getKey().getOwner() + " but submitted by " + authUser)); } User user = userDAO.findByWorkflowId(checked.getKey().getProcessInstanceId()); if (user == null) { throw new NotFoundException("User with workflow id " + checked.getKey().getProcessInstanceId()); } Set<String> preTasks = getPerformedTasks(user); try { engine.getFormService().submitTaskFormData(form.getTaskId(), form.getPropertiesForSubmit()); engine.getRuntimeService().setVariable(user.getWorkflowId(), FORM_SUBMITTER, authUser); } catch (ActivitiException e) { throwException(e, "While submitting form for task " + form.getTaskId()); } Set<String> postTasks = getPerformedTasks(user); postTasks.removeAll(preTasks); postTasks.add(form.getTaskId()); updateStatus(user); User updated = userDAO.save(user); // see if there is any propagation to be done PropagationByResource propByRes = engine.getRuntimeService().getVariable( user.getWorkflowId(), PROP_BY_RESOURCE, PropagationByResource.class); // fetch - if available - the encrypted password String clearPassword = null; String encryptedPwd = engine.getRuntimeService().getVariable(user.getWorkflowId(), ENCRYPTED_PWD, String.class); if (StringUtils.isNotBlank(encryptedPwd)) { clearPassword = decrypt(encryptedPwd); } // supports approval chains saveForFormSubmit(user, clearPassword, propByRes); UserPatch userPatch = engine.getRuntimeService().getVariable(user.getWorkflowId(), USER_PATCH, UserPatch.class); if (userPatch == null) { userPatch = new UserPatch(); userPatch.setKey(updated.getKey()); userPatch.setPassword(new PasswordPatch.Builder().onSyncope(true).value(clearPassword).build()); if (propByRes != null) { userPatch.getPassword().getResources().addAll(propByRes.get(ResourceOperation.CREATE)); } } cleanupHistory(user); return new WorkflowResult<>(userPatch, propByRes, postTasks); } }
Duplicate removal
core/workflow-activiti/src/main/java/org/apache/syncope/core/workflow/activiti/ActivitiUserWorkflowAdapter.java
Duplicate removal
Java
apache-2.0
773901bd7144a33915ce0d902e1ca10bba6f7e1b
0
dinushab/carbon-maven-plugins,wso2/carbon-maven-plugins,callkalpa/carbon-maven-plugins
/* * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.maven.p2.feature.generate.utils; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.wso2.maven.p2.exceptions.MissingRequiredPropertyException; import org.wso2.maven.p2.feature.generate.Advice; import org.wso2.maven.p2.feature.generate.Bundle; import org.wso2.maven.p2.feature.generate.Feature; import org.wso2.maven.p2.feature.generate.FeatureResourceBundle; import org.wso2.maven.p2.utils.BundleUtils; import org.wso2.maven.p2.utils.P2Utils; import org.wso2.maven.p2.utils.PropertyReplacer; import org.xml.sax.SAXException; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Properties; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; /** * Generate output files that are needed to generate a particular feature. * * @since 2.0.0 */ public class FeatureFileGeneratorUtils { private static final String DEFAULT_ENCODING = "UTF-8"; private static final String LINE_SEPARATOR = System.lineSeparator(); /** * Generates the feature property file. * * @param resourceBundle containing the project resources * @param featurePropertyFile File Object representing the feature property file * @throws IOException throws when unable to create the feature property file. * @throws MissingRequiredPropertyException throws if mandatory properties are not found in provided property files */ public static void createPropertiesFile(FeatureResourceBundle resourceBundle, File featurePropertyFile) throws IOException, MissingRequiredPropertyException { Properties props = getProperties(resourceBundle); if (!props.isEmpty()) { try (OutputStream propertyFileStream = new FileOutputStream(featurePropertyFile)) { resourceBundle.getLog().info("Generating feature properties"); props.store(propertyFileStream, "Properties of " + resourceBundle.getId()); } catch (IOException e) { throw new IOException("Unable to create the feature.properties file", e); } } } /** * Merge properties passed into the maven plugin as properties and via the properties file. * * @param resourceBundle containing the project resources * @return Properties object containing properties passed in to the tool as properties and via the properties file * @throws IOException throws if unable to read a given property file * @throws MissingRequiredPropertyException throws if mandatory properties are not found in provided property files */ private static Properties getProperties(FeatureResourceBundle resourceBundle) throws IOException, MissingRequiredPropertyException { Properties props = resourceBundle.getProperties(); Properties propertiesFromFiles = getMergedPropertiesFromFiles(resourceBundle); if (props != null) { props.forEach((key, value) -> propertiesFromFiles.setProperty(key.toString(), value.toString())); } resourceBundle.setProperties(propertiesFromFiles); return propertiesFromFiles; } /** * Merge the properties from the properties files that are found in; * <ul> * <li>predefined location</li> * <li>properties file given through plugin configuration<li/> * </ul> * * @param resourceBundle resourceBundle containing mojo resources. * @return Properties containing all the properties found in the aforementioned properties files. * @throws IOException throws if unable to read a given property file * @throws MissingRequiredPropertyException throws if mandatory properties are not found in provided property files */ private static Properties getMergedPropertiesFromFiles(FeatureResourceBundle resourceBundle) throws IOException, MissingRequiredPropertyException { Properties props = new Properties(); File propertyFileFromResourceDir = resourceBundle.getPropertyFileInResourceDir(); File propertyFileFromConfig = resourceBundle.getPropertyFile(); if (propertyFileFromResourceDir.exists()) { try (InputStream propertyFileStream = new FileInputStream(propertyFileFromResourceDir)) { props.load(propertyFileStream); } } if (propertyFileFromConfig != null && propertyFileFromConfig.exists()) { try (InputStream propertyFileStream = new FileInputStream(propertyFileFromConfig)) { props.load(propertyFileStream); } } if (!props.containsKey("copyright") && !props.containsKey("license")) { throw new MissingRequiredPropertyException("Mandatory properties are not specified in the property files"); } return props; } /** * Creates manifest file for a feature. * * @param resourceBundle containing the project resources * @param featureManifestFile File Object representing the manifest file * @throws IOException throws when unable to create the manifest file */ public static void createManifestMFFile(FeatureResourceBundle resourceBundle, File featureManifestFile) throws IOException { try (Writer writer = new OutputStreamWriter(new FileOutputStream(featureManifestFile), DEFAULT_ENCODING); PrintWriter pw = new PrintWriter(writer)) { resourceBundle.getLog().info("Generating MANIFEST.MF"); pw.print("Manifest-Version: 1.0" + LINE_SEPARATOR + LINE_SEPARATOR); } catch (IOException e) { throw new IOException("Unable to create manifest file", e); } } /** * Generates the P2Inf file. * * @param resourceBundle containing the project resources * @param p2InfFile File object representing the p2inf file * @throws IOException throws when unable to read or create p2.inf file */ public static void createP2Inf(FeatureResourceBundle resourceBundle, File p2InfFile) throws IOException { List<Advice> list = resourceBundle.getAdviceFileContent(); List<String> p2infStringList = null; if (p2InfFile.exists()) { p2infStringList = readAdviceFile(p2InfFile.getAbsolutePath()); resourceBundle.getLog().info("Updating Advice file (p2.inf)"); } else { resourceBundle.getLog().info("Generating Advice file (p2.inf)"); } try (Writer writer = new OutputStreamWriter(new FileOutputStream(p2InfFile.getAbsolutePath()), DEFAULT_ENCODING); PrintWriter pw = new PrintWriter(writer)) { Properties properties = new Properties(); properties.setProperty("feature.version", BundleUtils.getOSGIVersion(resourceBundle.getVersion())); if (p2infStringList != null && p2infStringList.size() > 0) { // writing the strings after replacing ${feature.version} p2infStringList.forEach(p2InfEntry -> pw.write(PropertyReplacer.replaceProperties(p2InfEntry, properties) + LINE_SEPARATOR)); } if (list != null && list.size() != 0) { int nextIndex = P2Utils.getLastIndexOfProperties(p2InfFile) + 1; for (Advice category : list) { pw.write(LINE_SEPARATOR + "properties." + nextIndex + ".name=" + category.getName()); pw.write(LINE_SEPARATOR + "properties." + nextIndex + ".value=" + category.getValue()); nextIndex++; } } } catch (UnsupportedEncodingException e) { resourceBundle.getLog().error("Unable to read p2.inf file. Unsupported encoding in existing file."); throw e; } catch (IOException e) { throw new IOException("Unable to create/open p2.inf file", e); } } /** * Read a given advice file in the pom.xml and return the items in the advice file in a String list. * * @param absolutePath Path to the advice file * @return List&lt;String&gt; containing items in the given advice file * @throws IOException throws when an error occurs when reading p2.inf file */ private static List<String> readAdviceFile(String absolutePath) throws IOException { List<String> stringList = new ArrayList<>(); String inputLine; try (InputStreamReader reader = new InputStreamReader(new FileInputStream(absolutePath), DEFAULT_ENCODING); BufferedReader br = new BufferedReader(reader)) { while ((inputLine = br.readLine()) != null) { stringList.add(inputLine); } } catch (IOException e) { throw new IOException("Error while reading from p2.inf file", e); } return stringList; } /** * Generates the feature.xml file for a feature. * * @param resourceBundle containing the project resources * @param featureXmlFile File object representing the feature xml file * @throws TransformerException throws when xml transformation fails * @throws IOException throws when unable to read/write feature.xml file * @throws SAXException throws when failing to parse the feature.xml file * @throws ParserConfigurationException throws when failing to parse the feature.xml file */ public static void createFeatureXml(FeatureResourceBundle resourceBundle, File featureXmlFile) throws TransformerException, IOException, SAXException, ParserConfigurationException { resourceBundle.getLog().info("Generating feature manifest"); Document document = getManifestDocument(resourceBundle.getManifest()); Element rootElement = document.getDocumentElement(); if (rootElement == null) { rootElement = document.createElement("feature"); document.appendChild(rootElement); } if (!rootElement.hasAttribute("id")) { rootElement.setAttribute("id", resourceBundle.getId()); } if (!rootElement.hasAttribute("label")) { rootElement.setAttribute("label", resourceBundle.getLabel()); } if (!rootElement.hasAttribute("version")) { rootElement.setAttribute("version", BundleUtils.getOSGIVersion(resourceBundle.getVersion())); } if (!rootElement.hasAttribute("provider-name")) { rootElement.setAttribute("provider-name", resourceBundle.getProviderName()); } NodeList descriptionTags = rootElement.getElementsByTagName("description"); if (descriptionTags.getLength() == 0) { Node description = document.createElement("description"); description.setTextContent(resourceBundle.getDescription()); rootElement.appendChild(description); } NodeList copyrightTags = rootElement.getElementsByTagName("copyright"); if (copyrightTags.getLength() == 0) { Node copyright = document.createElement("copyright"); copyright.setTextContent(resourceBundle.getCopyright()); rootElement.appendChild(copyright); } NodeList licenseTags = rootElement.getElementsByTagName("license"); if (licenseTags.getLength() == 0) { Node license = document.createElement("license"); ((Element) license).setAttribute("url", resourceBundle.getLicenceUrl()); license.setTextContent(resourceBundle.getLicence()); rootElement.appendChild(license); } List<Bundle> processedMissingPlugins = getMissingPlugins(resourceBundle.getBundles(), document); List<Feature> missingImportFeatures = getMissingImportFeatures(resourceBundle. getImportFeatures(), document, "feature"); List<Feature> includedFeatures = resourceBundle.getIncludeFeatures(); //region updating feature.xml with missing plugins for (Bundle bundle : processedMissingPlugins) { Element plugin = document.createElement("plugin"); plugin.setAttribute("id", bundle.getSymbolicName()); plugin.setAttribute("version", bundle.getBundleVersion()); plugin.setAttribute("unpack", "false"); rootElement.appendChild(plugin); } //endregion //region updating feature.xml with missing import plugins and features NodeList requireNodes = document.getElementsByTagName("require"); Node require; if (requireNodes == null || requireNodes.getLength() == 0) { require = document.createElement("require"); rootElement.appendChild(require); } else { require = requireNodes.item(0); } missingImportFeatures.stream().filter(feature -> !feature.isOptional()).forEach(feature -> { Element plugin = document.createElement("import"); plugin.setAttribute("feature", feature.getId()); plugin.setAttribute("version", feature.getFeatureVersion()); if (P2Utils.isPatch(feature.getCompatibility())) { plugin.setAttribute("patch", "true"); } else { plugin.setAttribute("match", P2Utils.getMatchRule(feature.getCompatibility())); } require.appendChild(plugin); }); for (Feature includedFeature : includedFeatures) { Element includeElement = document.createElement("includes"); includeElement.setAttribute("id", includedFeature.getId()); includeElement.setAttribute("version", includedFeature.getFeatureVersion()); includeElement.setAttribute("optional", Boolean.toString(includedFeature.isOptional())); rootElement.appendChild(includeElement); } for (Feature feature : missingImportFeatures) { if (feature.isOptional()) { Element includeElement = document.createElement("includes"); includeElement.setAttribute("id", feature.getId()); includeElement.setAttribute("version", feature.getFeatureVersion()); includeElement.setAttribute("optional", Boolean.toString(feature.isOptional())); rootElement.appendChild(includeElement); } } //endregion try { TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer; transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(document); StreamResult result = new StreamResult(featureXmlFile); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); transformer.transform(source, result); } catch (TransformerConfigurationException e) { throw new TransformerConfigurationException("Unable to create feature manifest", e); } } /** * If a manifest file is given, parse the manifest file and return the Document object representing the file. * Generates a new Document otherwise. * * @param manifest java.io.File pointing an existing manifest file. * @return Document object representing a given manifest file or a newly generated manifest file * @throws ParserConfigurationException * @throws SAXException throws when failing to parse the feature.xml file * @throws IOException throws when unable to read/write feature.xml file */ private static Document getManifestDocument(File manifest) throws ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder; try { documentBuilder = documentBuilderFactory.newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new ParserConfigurationException("Unable to load feature manifest"); } Document document; if (manifest != null && manifest.exists()) { try (InputStream manifestFileStream = new FileInputStream(manifest)) { document = documentBuilder.parse(manifestFileStream); } catch (SAXException e) { throw new SAXException("Unable to parse feature manifest", e); } catch (IOException e) { throw new IOException("Unable to load feature manifest", e); } } else { document = documentBuilder.newDocument(); } return document; } /** * Cross check plugins given in the manifest file against the plugins configured in the pom.xml file. Returns a * list of bundles found in the pom.xml but not in the manifest file. * * @param bundles list of bundles configured in the pom.xml * @param document Document representing the give manifest * @return ArrayList&lt;Bundle&gt; missing plugins */ private static List<Bundle> getMissingPlugins(List<Bundle> bundles, Document document) { if (bundles == null || bundles.size() == 0) { return new ArrayList<>(); } HashMap<String, Bundle> missingPlugins = new HashMap<>(); bundles.forEach(bundle -> missingPlugins.put(bundle.getArtifactId(), bundle)); NodeList existingPlugins = document.getDocumentElement().getElementsByTagName("plugin"); for (int i = 0; i < existingPlugins.getLength(); i++) { Node node = existingPlugins.item(i); Node namedItem = node.getAttributes().getNamedItem("id"); if (namedItem != null && namedItem.getTextContent() != null && missingPlugins.containsKey(namedItem.getTextContent())) { missingPlugins.remove(namedItem.getTextContent()); } } return new ArrayList<>(missingPlugins.values()); } /** * Cross check import features in the given manifest file against the plugins configured in the * pom.xml file. Returns a list of import bundles/import features found in the pom.xml but not in the manifest file. * * @param processedImportItemsList list of import plugins/import features configured in the pom.xml * @param document Document representing the give manifest * @param itemType String type, either "feature" or "plugin" * @return ArrayList<Feature> List of features in the plugin configuration but not in the given manifest file */ private static List<Feature> getMissingImportFeatures(List<Feature> processedImportItemsList, Document document, String itemType) { if (processedImportItemsList == null) { return new ArrayList<>(); } HashMap<String, Feature> missingImportItems = new HashMap<>(); for (Feature item : processedImportItemsList) { missingImportItems.put(item.getId(), item); } NodeList requireNodeList = document.getDocumentElement().getElementsByTagName("require"); if (requireNodeList.getLength() == 0) { return new ArrayList<>(missingImportItems.values()); } Node requireNode = requireNodeList.item(0); if (requireNode instanceof Element) { Element requireElement = (Element) requireNode; NodeList importNodes = requireElement.getElementsByTagName("import"); for (int i = 0; i < importNodes.getLength(); i++) { Node node = importNodes.item(i); Node namedItem = node.getAttributes().getNamedItem(itemType); if (namedItem != null && namedItem.getTextContent() != null && missingImportItems.containsKey(namedItem.getTextContent())) { missingImportItems.remove(namedItem.getTextContent()); } } } return new ArrayList<>(missingImportItems.values()); } }
carbon-feature-plugin/src/main/java/org/wso2/maven/p2/feature/generate/utils/FeatureFileGeneratorUtils.java
/* * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.maven.p2.feature.generate.utils; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.wso2.maven.p2.exceptions.MissingRequiredPropertyException; import org.wso2.maven.p2.feature.generate.Advice; import org.wso2.maven.p2.feature.generate.Bundle; import org.wso2.maven.p2.feature.generate.Feature; import org.wso2.maven.p2.feature.generate.FeatureResourceBundle; import org.wso2.maven.p2.utils.BundleUtils; import org.wso2.maven.p2.utils.P2Utils; import org.wso2.maven.p2.utils.PropertyReplacer; import org.xml.sax.SAXException; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Properties; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; /** * Generate output files that are needed to generate a particular feature. * * @since 2.0.0 */ public class FeatureFileGeneratorUtils { private static final String DEFAULT_ENCODING = "UTF-8"; private static final String LINE_SEPARATOR = System.lineSeparator(); /** * Generates the feature property file. * * @param resourceBundle containing the project resources * @param featurePropertyFile File Object representing the feature property file * @throws IOException throws when unable to create the feature property file. * @throws MissingRequiredPropertyException throws if mandatory properties are not found in provided property files */ public static void createPropertiesFile(FeatureResourceBundle resourceBundle, File featurePropertyFile) throws IOException, MissingRequiredPropertyException { Properties props = getProperties(resourceBundle); if (!props.isEmpty()) { try (OutputStream propertyFileStream = new FileOutputStream(featurePropertyFile)) { resourceBundle.getLog().info("Generating feature properties"); props.store(propertyFileStream, "Properties of " + resourceBundle.getId()); } catch (IOException e) { throw new IOException("Unable to create the feature.properties file", e); } } } /** * Merge properties passed into the maven plugin as properties and via the properties file. * * @param resourceBundle containing the project resources * @return Properties object containing properties passed in to the tool as properties and via the properties file * @throws IOException throws if unable to read a given property file * @throws MissingRequiredPropertyException throws if mandatory properties are not found in provided property files */ private static Properties getProperties(FeatureResourceBundle resourceBundle) throws IOException, MissingRequiredPropertyException { Properties props = resourceBundle.getProperties(); Properties propertiesFromFiles = getMergedPropertiesFromFiles(resourceBundle); if (props != null) { props.forEach((key, value) -> propertiesFromFiles.setProperty(key.toString(), value.toString())); } resourceBundle.setProperties(propertiesFromFiles); return propertiesFromFiles; } /** * Merge the properties from the properties files that are found in; * <ul> * <li>predefined location</li> * <li>properties file given through plugin configuration<li/> * </ul> * * @param resourceBundle resourceBundle containing mojo resources. * @return Properties containing all the properties found in the aforementioned properties files. * @throws IOException throws if unable to read a given property file * @throws MissingRequiredPropertyException throws if mandatory properties are not found in provided property files */ private static Properties getMergedPropertiesFromFiles(FeatureResourceBundle resourceBundle) throws IOException, MissingRequiredPropertyException { Properties props = new Properties(); File propertyFileFromResourceDir = resourceBundle.getPropertyFileInResourceDir(); File propertyFileFromConfig = resourceBundle.getPropertyFile(); if (propertyFileFromResourceDir.exists()) { try (InputStream propertyFileStream = new FileInputStream(propertyFileFromResourceDir)) { props.load(propertyFileStream); } } if (propertyFileFromConfig != null && propertyFileFromConfig.exists()) { try (InputStream propertyFileStream = new FileInputStream(propertyFileFromConfig)) { props.load(propertyFileStream); } } if (!props.containsKey("copyright") && !props.containsKey("license")) { throw new MissingRequiredPropertyException("Mandatory properties are not specified in the property files"); } return props; } /** * Creates manifest file for a feature. * * @param resourceBundle containing the project resources * @param featureManifestFile File Object representing the manifest file * @throws IOException throws when unable to create the manifest file */ public static void createManifestMFFile(FeatureResourceBundle resourceBundle, File featureManifestFile) throws IOException { try (Writer writer = new OutputStreamWriter(new FileOutputStream(featureManifestFile), DEFAULT_ENCODING); PrintWriter pw = new PrintWriter(writer)) { resourceBundle.getLog().info("Generating MANIFEST.MF"); pw.print("Manifest-Version: 1.0" + LINE_SEPARATOR + LINE_SEPARATOR); } catch (IOException e) { throw new IOException("Unable to create manifest file", e); } } /** * Generates the P2Inf file. * * @param resourceBundle containing the project resources * @param p2InfFile File object representing the p2inf file * @throws IOException throws when unable to read or create p2.inf file */ public static void createP2Inf(FeatureResourceBundle resourceBundle, File p2InfFile) throws IOException { try (Writer writer = new OutputStreamWriter(new FileOutputStream(p2InfFile.getAbsolutePath()), DEFAULT_ENCODING); PrintWriter pw = new PrintWriter(writer)) { List<Advice> list = resourceBundle.getAdviceFileContent(); List<String> p2infStringList = null; if (p2InfFile.exists()) { p2infStringList = readAdviceFile(p2InfFile.getAbsolutePath()); resourceBundle.getLog().info("Updating Advice file (p2.inf)"); } else { resourceBundle.getLog().info("Generating Advice file (p2.inf)"); } Properties properties = new Properties(); properties.setProperty("feature.version", BundleUtils.getOSGIVersion(resourceBundle.getVersion())); if (p2infStringList != null && p2infStringList.size() > 0) { // writing the strings after replacing ${feature.version} p2infStringList.forEach(p2InfEntry -> pw.write(PropertyReplacer.replaceProperties(p2InfEntry, properties) + LINE_SEPARATOR)); } if (list != null && list.size() != 0) { int nextIndex = P2Utils.getLastIndexOfProperties(p2InfFile) + 1; for (Advice category : list) { pw.write(LINE_SEPARATOR + "properties." + nextIndex + ".name=" + category.getName()); pw.write(LINE_SEPARATOR + "properties." + nextIndex + ".value=" + category.getValue()); nextIndex++; } } } catch (UnsupportedEncodingException e) { resourceBundle.getLog().error("Unable to read p2.inf file. Unsupported encoding in existing file."); throw e; } catch (IOException e) { throw new IOException("Unable to create/open p2.inf file", e); } } /** * Read a given advice file in the pom.xml and return the items in the advice file in a String list. * * @param absolutePath Path to the advice file * @return List&lt;String&gt; containing items in the given advice file * @throws IOException throws when an error occurs when reading p2.inf file */ private static List<String> readAdviceFile(String absolutePath) throws IOException { List<String> stringList = new ArrayList<>(); String inputLine; try (InputStreamReader reader = new InputStreamReader(new FileInputStream(absolutePath), DEFAULT_ENCODING); BufferedReader br = new BufferedReader(reader)) { while ((inputLine = br.readLine()) != null) { stringList.add(inputLine); } } catch (IOException e) { throw new IOException("Error while reading from p2.inf file", e); } return stringList; } /** * Generates the feature.xml file for a feature. * * @param resourceBundle containing the project resources * @param featureXmlFile File object representing the feature xml file * @throws TransformerException throws when xml transformation fails * @throws IOException throws when unable to read/write feature.xml file * @throws SAXException throws when failing to parse the feature.xml file * @throws ParserConfigurationException throws when failing to parse the feature.xml file */ public static void createFeatureXml(FeatureResourceBundle resourceBundle, File featureXmlFile) throws TransformerException, IOException, SAXException, ParserConfigurationException { resourceBundle.getLog().info("Generating feature manifest"); Document document = getManifestDocument(resourceBundle.getManifest()); Element rootElement = document.getDocumentElement(); if (rootElement == null) { rootElement = document.createElement("feature"); document.appendChild(rootElement); } if (!rootElement.hasAttribute("id")) { rootElement.setAttribute("id", resourceBundle.getId()); } if (!rootElement.hasAttribute("label")) { rootElement.setAttribute("label", resourceBundle.getLabel()); } if (!rootElement.hasAttribute("version")) { rootElement.setAttribute("version", BundleUtils.getOSGIVersion(resourceBundle.getVersion())); } if (!rootElement.hasAttribute("provider-name")) { rootElement.setAttribute("provider-name", resourceBundle.getProviderName()); } NodeList descriptionTags = rootElement.getElementsByTagName("description"); if (descriptionTags.getLength() == 0) { Node description = document.createElement("description"); description.setTextContent(resourceBundle.getDescription()); rootElement.appendChild(description); } NodeList copyrightTags = rootElement.getElementsByTagName("copyright"); if (copyrightTags.getLength() == 0) { Node copyright = document.createElement("copyright"); copyright.setTextContent(resourceBundle.getCopyright()); rootElement.appendChild(copyright); } NodeList licenseTags = rootElement.getElementsByTagName("license"); if (licenseTags.getLength() == 0) { Node license = document.createElement("license"); ((Element) license).setAttribute("url", resourceBundle.getLicenceUrl()); license.setTextContent(resourceBundle.getLicence()); rootElement.appendChild(license); } List<Bundle> processedMissingPlugins = getMissingPlugins(resourceBundle.getBundles(), document); List<Feature> missingImportFeatures = getMissingImportFeatures(resourceBundle. getImportFeatures(), document, "feature"); List<Feature> includedFeatures = resourceBundle.getIncludeFeatures(); //region updating feature.xml with missing plugins for (Bundle bundle : processedMissingPlugins) { Element plugin = document.createElement("plugin"); plugin.setAttribute("id", bundle.getSymbolicName()); plugin.setAttribute("version", bundle.getBundleVersion()); plugin.setAttribute("unpack", "false"); rootElement.appendChild(plugin); } //endregion //region updating feature.xml with missing import plugins and features NodeList requireNodes = document.getElementsByTagName("require"); Node require; if (requireNodes == null || requireNodes.getLength() == 0) { require = document.createElement("require"); rootElement.appendChild(require); } else { require = requireNodes.item(0); } missingImportFeatures.stream().filter(feature -> !feature.isOptional()).forEach(feature -> { Element plugin = document.createElement("import"); plugin.setAttribute("feature", feature.getId()); plugin.setAttribute("version", feature.getFeatureVersion()); if (P2Utils.isPatch(feature.getCompatibility())) { plugin.setAttribute("patch", "true"); } else { plugin.setAttribute("match", P2Utils.getMatchRule(feature.getCompatibility())); } require.appendChild(plugin); }); for (Feature includedFeature : includedFeatures) { Element includeElement = document.createElement("includes"); includeElement.setAttribute("id", includedFeature.getId()); includeElement.setAttribute("version", includedFeature.getFeatureVersion()); includeElement.setAttribute("optional", Boolean.toString(includedFeature.isOptional())); rootElement.appendChild(includeElement); } for (Feature feature : missingImportFeatures) { if (feature.isOptional()) { Element includeElement = document.createElement("includes"); includeElement.setAttribute("id", feature.getId()); includeElement.setAttribute("version", feature.getFeatureVersion()); includeElement.setAttribute("optional", Boolean.toString(feature.isOptional())); rootElement.appendChild(includeElement); } } //endregion try { TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer; transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(document); StreamResult result = new StreamResult(featureXmlFile); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); transformer.transform(source, result); } catch (TransformerConfigurationException e) { throw new TransformerConfigurationException("Unable to create feature manifest", e); } } /** * If a manifest file is given, parse the manifest file and return the Document object representing the file. * Generates a new Document otherwise. * * @param manifest java.io.File pointing an existing manifest file. * @return Document object representing a given manifest file or a newly generated manifest file * @throws ParserConfigurationException * @throws SAXException throws when failing to parse the feature.xml file * @throws IOException throws when unable to read/write feature.xml file */ private static Document getManifestDocument(File manifest) throws ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder; try { documentBuilder = documentBuilderFactory.newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new ParserConfigurationException("Unable to load feature manifest"); } Document document; if (manifest != null && manifest.exists()) { try (InputStream manifestFileStream = new FileInputStream(manifest)) { document = documentBuilder.parse(manifestFileStream); } catch (SAXException e) { throw new SAXException("Unable to parse feature manifest", e); } catch (IOException e) { throw new IOException("Unable to load feature manifest", e); } } else { document = documentBuilder.newDocument(); } return document; } /** * Cross check plugins given in the manifest file against the plugins configured in the pom.xml file. Returns a * list of bundles found in the pom.xml but not in the manifest file. * * @param bundles list of bundles configured in the pom.xml * @param document Document representing the give manifest * @return ArrayList&lt;Bundle&gt; missing plugins */ private static List<Bundle> getMissingPlugins(List<Bundle> bundles, Document document) { if (bundles == null || bundles.size() == 0) { return new ArrayList<>(); } HashMap<String, Bundle> missingPlugins = new HashMap<>(); bundles.forEach(bundle -> missingPlugins.put(bundle.getArtifactId(), bundle)); NodeList existingPlugins = document.getDocumentElement().getElementsByTagName("plugin"); for (int i = 0; i < existingPlugins.getLength(); i++) { Node node = existingPlugins.item(i); Node namedItem = node.getAttributes().getNamedItem("id"); if (namedItem != null && namedItem.getTextContent() != null && missingPlugins.containsKey(namedItem.getTextContent())) { missingPlugins.remove(namedItem.getTextContent()); } } return new ArrayList<>(missingPlugins.values()); } /** * Cross check import features in the given manifest file against the plugins configured in the * pom.xml file. Returns a list of import bundles/import features found in the pom.xml but not in the manifest file. * * @param processedImportItemsList list of import plugins/import features configured in the pom.xml * @param document Document representing the give manifest * @param itemType String type, either "feature" or "plugin" * @return ArrayList<Feature> List of features in the plugin configuration but not in the given manifest file */ private static List<Feature> getMissingImportFeatures(List<Feature> processedImportItemsList, Document document, String itemType) { if (processedImportItemsList == null) { return new ArrayList<>(); } HashMap<String, Feature> missingImportItems = new HashMap<>(); for (Feature item : processedImportItemsList) { missingImportItems.put(item.getId(), item); } NodeList requireNodeList = document.getDocumentElement().getElementsByTagName("require"); if (requireNodeList.getLength() == 0) { return new ArrayList<>(missingImportItems.values()); } Node requireNode = requireNodeList.item(0); if (requireNode instanceof Element) { Element requireElement = (Element) requireNode; NodeList importNodes = requireElement.getElementsByTagName("import"); for (int i = 0; i < importNodes.getLength(); i++) { Node node = importNodes.item(i); Node namedItem = node.getAttributes().getNamedItem(itemType); if (namedItem != null && namedItem.getTextContent() != null && missingImportItems.containsKey(namedItem.getTextContent())) { missingImportItems.remove(namedItem.getTextContent()); } } } return new ArrayList<>(missingImportItems.values()); } }
CMVNPLG-1 : Fix for copying files using p2.inf
carbon-feature-plugin/src/main/java/org/wso2/maven/p2/feature/generate/utils/FeatureFileGeneratorUtils.java
CMVNPLG-1 : Fix for copying files using p2.inf
Java
apache-2.0
e8fcb93386f2a302fe3a548105dfd7f8d101d9bc
0
fnouama/intellij-community,orekyuu/intellij-community,kool79/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,diorcety/intellij-community,petteyg/intellij-community,apixandru/intellij-community,samthor/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,da1z/intellij-community,allotria/intellij-community,fengbaicanhe/intellij-community,vvv1559/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,slisson/intellij-community,tmpgit/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,apixandru/intellij-community,jagguli/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,SerCeMan/intellij-community,jagguli/intellij-community,retomerz/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,adedayo/intellij-community,kdwink/intellij-community,izonder/intellij-community,izonder/intellij-community,michaelgallacher/intellij-community,akosyakov/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,MichaelNedzelsky/intellij-community,youdonghai/intellij-community,Distrotech/intellij-community,samthor/intellij-community,MichaelNedzelsky/intellij-community,fnouama/intellij-community,akosyakov/intellij-community,xfournet/intellij-community,slisson/intellij-community,fitermay/intellij-community,nicolargo/intellij-community,hurricup/intellij-community,MER-GROUP/intellij-community,SerCeMan/intellij-community,robovm/robovm-studio,pwoodworth/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,alphafoobar/intellij-community,muntasirsyed/intellij-community,alphafoobar/intellij-community,ivan-fedorov/intellij-community,alphafoobar/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,Lekanich/intellij-community,asedunov/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,supersven/intellij-community,akosyakov/intellij-community,da1z/intellij-community,holmes/intellij-community,slisson/intellij-community,asedunov/intellij-community,fitermay/intellij-community,pwoodworth/intellij-community,signed/intellij-community,samthor/intellij-community,ahb0327/intellij-community,pwoodworth/intellij-community,michaelgallacher/intellij-community,orekyuu/intellij-community,SerCeMan/intellij-community,orekyuu/intellij-community,ryano144/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,adedayo/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,xfournet/intellij-community,allotria/intellij-community,blademainer/intellij-community,tmpgit/intellij-community,orekyuu/intellij-community,gnuhub/intellij-community,jagguli/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,orekyuu/intellij-community,samthor/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,ivan-fedorov/intellij-community,vladmm/intellij-community,holmes/intellij-community,caot/intellij-community,jagguli/intellij-community,robovm/robovm-studio,da1z/intellij-community,clumsy/intellij-community,da1z/intellij-community,ibinti/intellij-community,Lekanich/intellij-community,fitermay/intellij-community,caot/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,semonte/intellij-community,amith01994/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,robovm/robovm-studio,ftomassetti/intellij-community,da1z/intellij-community,signed/intellij-community,signed/intellij-community,Lekanich/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,semonte/intellij-community,tmpgit/intellij-community,amith01994/intellij-community,kool79/intellij-community,lucafavatella/intellij-community,nicolargo/intellij-community,amith01994/intellij-community,TangHao1987/intellij-community,allotria/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,nicolargo/intellij-community,holmes/intellij-community,ryano144/intellij-community,retomerz/intellij-community,asedunov/intellij-community,petteyg/intellij-community,gnuhub/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,kdwink/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,orekyuu/intellij-community,Distrotech/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,suncycheng/intellij-community,adedayo/intellij-community,caot/intellij-community,jagguli/intellij-community,ftomassetti/intellij-community,Distrotech/intellij-community,ol-loginov/intellij-community,TangHao1987/intellij-community,MichaelNedzelsky/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,da1z/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,samthor/intellij-community,kool79/intellij-community,TangHao1987/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,blademainer/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,allotria/intellij-community,kdwink/intellij-community,fengbaicanhe/intellij-community,dslomov/intellij-community,wreckJ/intellij-community,caot/intellij-community,petteyg/intellij-community,Distrotech/intellij-community,holmes/intellij-community,kool79/intellij-community,ibinti/intellij-community,adedayo/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,fitermay/intellij-community,clumsy/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,jagguli/intellij-community,kdwink/intellij-community,petteyg/intellij-community,tmpgit/intellij-community,blademainer/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,diorcety/intellij-community,MichaelNedzelsky/intellij-community,ol-loginov/intellij-community,alphafoobar/intellij-community,tmpgit/intellij-community,MichaelNedzelsky/intellij-community,fengbaicanhe/intellij-community,salguarnieri/intellij-community,ThiagoGarciaAlves/intellij-community,dslomov/intellij-community,xfournet/intellij-community,supersven/intellij-community,izonder/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,Lekanich/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,semonte/intellij-community,FHannes/intellij-community,fitermay/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,MER-GROUP/intellij-community,da1z/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,diorcety/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,ol-loginov/intellij-community,pwoodworth/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,wreckJ/intellij-community,vladmm/intellij-community,supersven/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,robovm/robovm-studio,retomerz/intellij-community,jagguli/intellij-community,diorcety/intellij-community,adedayo/intellij-community,retomerz/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,tmpgit/intellij-community,supersven/intellij-community,fitermay/intellij-community,kool79/intellij-community,orekyuu/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,gnuhub/intellij-community,caot/intellij-community,clumsy/intellij-community,semonte/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,ahb0327/intellij-community,jagguli/intellij-community,holmes/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,adedayo/intellij-community,amith01994/intellij-community,blademainer/intellij-community,petteyg/intellij-community,TangHao1987/intellij-community,youdonghai/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,dslomov/intellij-community,petteyg/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,signed/intellij-community,clumsy/intellij-community,fengbaicanhe/intellij-community,kdwink/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,signed/intellij-community,Lekanich/intellij-community,caot/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,nicolargo/intellij-community,signed/intellij-community,clumsy/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,petteyg/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,holmes/intellij-community,caot/intellij-community,Lekanich/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,asedunov/intellij-community,amith01994/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,ol-loginov/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,suncycheng/intellij-community,SerCeMan/intellij-community,fnouama/intellij-community,apixandru/intellij-community,izonder/intellij-community,muntasirsyed/intellij-community,wreckJ/intellij-community,holmes/intellij-community,vvv1559/intellij-community,SerCeMan/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,ryano144/intellij-community,hurricup/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,supersven/intellij-community,diorcety/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,vvv1559/intellij-community,fengbaicanhe/intellij-community,fnouama/intellij-community,blademainer/intellij-community,ibinti/intellij-community,clumsy/intellij-community,izonder/intellij-community,dslomov/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,slisson/intellij-community,petteyg/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,supersven/intellij-community,slisson/intellij-community,ol-loginov/intellij-community,caot/intellij-community,MER-GROUP/intellij-community,semonte/intellij-community,adedayo/intellij-community,dslomov/intellij-community,Distrotech/intellij-community,fengbaicanhe/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,pwoodworth/intellij-community,ivan-fedorov/intellij-community,FHannes/intellij-community,kdwink/intellij-community,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,dslomov/intellij-community,blademainer/intellij-community,pwoodworth/intellij-community,muntasirsyed/intellij-community,muntasirsyed/intellij-community,slisson/intellij-community,samthor/intellij-community,samthor/intellij-community,vladmm/intellij-community,slisson/intellij-community,diorcety/intellij-community,petteyg/intellij-community,ryano144/intellij-community,wreckJ/intellij-community,ivan-fedorov/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,ryano144/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,xfournet/intellij-community,MichaelNedzelsky/intellij-community,petteyg/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,vladmm/intellij-community,fnouama/intellij-community,kool79/intellij-community,Distrotech/intellij-community,izonder/intellij-community,Lekanich/intellij-community,fitermay/intellij-community,robovm/robovm-studio,fitermay/intellij-community,suncycheng/intellij-community,slisson/intellij-community,pwoodworth/intellij-community,wreckJ/intellij-community,ryano144/intellij-community,caot/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,gnuhub/intellij-community,salguarnieri/intellij-community,vladmm/intellij-community,retomerz/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,supersven/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,amith01994/intellij-community,allotria/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,fnouama/intellij-community,gnuhub/intellij-community,Lekanich/intellij-community,diorcety/intellij-community,clumsy/intellij-community,pwoodworth/intellij-community,vvv1559/intellij-community,samthor/intellij-community,slisson/intellij-community,xfournet/intellij-community,wreckJ/intellij-community,youdonghai/intellij-community,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,muntasirsyed/intellij-community,fnouama/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,michaelgallacher/intellij-community,robovm/robovm-studio,kool79/intellij-community,ol-loginov/intellij-community,amith01994/intellij-community,amith01994/intellij-community,clumsy/intellij-community,MER-GROUP/intellij-community,MER-GROUP/intellij-community,nicolargo/intellij-community,dslomov/intellij-community,lucafavatella/intellij-community,wreckJ/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,ol-loginov/intellij-community,clumsy/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,clumsy/intellij-community,samthor/intellij-community,ryano144/intellij-community,TangHao1987/intellij-community,MichaelNedzelsky/intellij-community,FHannes/intellij-community,jagguli/intellij-community,retomerz/intellij-community,diorcety/intellij-community,SerCeMan/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,petteyg/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,signed/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,da1z/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,ahb0327/intellij-community,amith01994/intellij-community,vladmm/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,caot/intellij-community,supersven/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,asedunov/intellij-community,ryano144/intellij-community,signed/intellij-community,SerCeMan/intellij-community,vladmm/intellij-community,dslomov/intellij-community,alphafoobar/intellij-community,signed/intellij-community,vladmm/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,vladmm/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,ol-loginov/intellij-community,samthor/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,FHannes/intellij-community,ahb0327/intellij-community,SerCeMan/intellij-community,Distrotech/intellij-community,dslomov/intellij-community,TangHao1987/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,dslomov/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,gnuhub/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,ol-loginov/intellij-community,Lekanich/intellij-community,jagguli/intellij-community,kdwink/intellij-community,petteyg/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,salguarnieri/intellij-community,ryano144/intellij-community,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,diorcety/intellij-community,orekyuu/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,michaelgallacher/intellij-community,diorcety/intellij-community,signed/intellij-community,diorcety/intellij-community,TangHao1987/intellij-community,ivan-fedorov/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,tmpgit/intellij-community,xfournet/intellij-community,fnouama/intellij-community,fnouama/intellij-community,ivan-fedorov/intellij-community,semonte/intellij-community,alphafoobar/intellij-community,MichaelNedzelsky/intellij-community,fengbaicanhe/intellij-community,orekyuu/intellij-community,vladmm/intellij-community,clumsy/intellij-community,retomerz/intellij-community,nicolargo/intellij-community,allotria/intellij-community,kool79/intellij-community,slisson/intellij-community,gnuhub/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,samthor/intellij-community,izonder/intellij-community,hurricup/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,akosyakov/intellij-community,robovm/robovm-studio,holmes/intellij-community,allotria/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,michaelgallacher/intellij-community,kdwink/intellij-community,ivan-fedorov/intellij-community,holmes/intellij-community,nicolargo/intellij-community,nicolargo/intellij-community,fnouama/intellij-community,MER-GROUP/intellij-community,kool79/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,blademainer/intellij-community,vladmm/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,Distrotech/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,ftomassetti/intellij-community,ahb0327/intellij-community,da1z/intellij-community,slisson/intellij-community,jagguli/intellij-community,kdwink/intellij-community,blademainer/intellij-community,robovm/robovm-studio,da1z/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,holmes/intellij-community,alphafoobar/intellij-community,orekyuu/intellij-community,kool79/intellij-community,ftomassetti/intellij-community,kool79/intellij-community,semonte/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,fnouama/intellij-community,izonder/intellij-community,akosyakov/intellij-community,xfournet/intellij-community,fnouama/intellij-community,caot/intellij-community,alphafoobar/intellij-community,Distrotech/intellij-community,holmes/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,caot/intellij-community,kool79/intellij-community,asedunov/intellij-community,ryano144/intellij-community,holmes/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,tmpgit/intellij-community,MichaelNedzelsky/intellij-community,nicolargo/intellij-community,ftomassetti/intellij-community,muntasirsyed/intellij-community,ahb0327/intellij-community,salguarnieri/intellij-community,adedayo/intellij-community,nicolargo/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,MER-GROUP/intellij-community,blademainer/intellij-community,apixandru/intellij-community,allotria/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,wreckJ/intellij-community,robovm/robovm-studio,clumsy/intellij-community,retomerz/intellij-community,blademainer/intellij-community,gnuhub/intellij-community,supersven/intellij-community
/* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.usageView; import com.intellij.lang.injection.InjectedLanguageManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.fileEditor.OpenFileDescriptor; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.GeneratedSourcesFilter; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.wm.StatusBar; import com.intellij.openapi.wm.WindowManager; import com.intellij.psi.ElementDescriptionUtil; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiReference; import com.intellij.refactoring.RefactoringBundle; import com.intellij.refactoring.util.MoveRenameUsageInfo; import com.intellij.refactoring.util.NonCodeUsageInfo; import com.intellij.usages.Usage; import com.intellij.usages.UsageInfo2UsageAdapter; import com.intellij.usages.UsageView; import com.intellij.util.Function; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import java.util.Arrays; import java.util.Collection; import java.util.LinkedHashSet; import java.util.Set; public class UsageViewUtil { private static final Logger LOG = Logger.getInstance("#com.intellij.usageView.UsageViewUtil"); private UsageViewUtil() { } public static String createNodeText(PsiElement element) { return ElementDescriptionUtil.getElementDescription(element, UsageViewNodeTextLocation.INSTANCE); } public static String getShortName(final PsiElement psiElement) { LOG.assertTrue(psiElement.isValid(), psiElement); return ElementDescriptionUtil.getElementDescription(psiElement, UsageViewShortNameLocation.INSTANCE); } public static String getLongName(final PsiElement psiElement) { LOG.assertTrue(psiElement.isValid(), psiElement); return ElementDescriptionUtil.getElementDescription(psiElement, UsageViewLongNameLocation.INSTANCE); } public static String getType(@NotNull PsiElement psiElement) { return ElementDescriptionUtil.getElementDescription(psiElement, UsageViewTypeLocation.INSTANCE); } public static boolean hasNonCodeUsages(UsageInfo[] usages) { for (UsageInfo usage : usages) { if (usage.isNonCodeUsage) return true; } return false; } public static boolean hasUsagesInGeneratedCode(UsageInfo[] usages, Project project) { GeneratedSourcesFilter[] filters = GeneratedSourcesFilter.EP_NAME.getExtensions(); for (UsageInfo usage : usages) { VirtualFile file = usage.getVirtualFile(); if (file != null) { for (GeneratedSourcesFilter filter : filters) { if (filter.isGeneratedSource(file, project)) { return true; } } } } return false; } public static boolean hasReadOnlyUsages(UsageInfo[] usages) { for (UsageInfo usage : usages) { if (!usage.isWritable()) return true; } return false; } public static UsageInfo[] removeDuplicatedUsages(@NotNull UsageInfo[] usages) { Set<UsageInfo> set = new LinkedHashSet<UsageInfo>(Arrays.asList(usages)); // Replace duplicates of move rename usage infos in injections from non code usages of master files String newTextInNonCodeUsage = null; for(UsageInfo usage:usages) { if (!(usage instanceof NonCodeUsageInfo)) continue; newTextInNonCodeUsage = ((NonCodeUsageInfo)usage).newText; break; } if (newTextInNonCodeUsage != null) { for(UsageInfo usage:usages) { if (!(usage instanceof MoveRenameUsageInfo)) continue; PsiFile file = usage.getFile(); if (file != null) { PsiElement context = InjectedLanguageManager.getInstance(file.getProject()).getInjectionHost(file); if (context != null) { PsiElement usageElement = usage.getElement(); if (usageElement == null) continue; PsiReference psiReference = usage.getReference(); if (psiReference == null) continue; int injectionOffsetInMasterFile = InjectedLanguageManager.getInstance(usageElement.getProject()).injectedToHost(usageElement, usageElement.getTextOffset()); TextRange rangeInElement = usage.getRangeInElement(); assert rangeInElement != null : usage; TextRange range = rangeInElement.shiftRight(injectionOffsetInMasterFile); PsiFile containingFile = context.getContainingFile(); if (containingFile == null) continue; //move package to another package set.remove( NonCodeUsageInfo.create( containingFile, range.getStartOffset(), range.getEndOffset(), ((MoveRenameUsageInfo)usage).getReferencedElement(), newTextInNonCodeUsage ) ); } } } } return set.toArray(new UsageInfo[set.size()]); } @NotNull public static UsageInfo[] toUsageInfoArray(@NotNull final Collection<? extends UsageInfo> collection) { final int size = collection.size(); return size == 0 ? UsageInfo.EMPTY_ARRAY : collection.toArray(new UsageInfo[size]); } @NotNull public static PsiElement[] toElements(@NotNull UsageInfo[] usageInfos) { return ContainerUtil.map2Array(usageInfos, PsiElement.class, new Function<UsageInfo, PsiElement>() { @Override public PsiElement fun(UsageInfo info) { return info.getElement(); } }); } public static void navigateTo(@NotNull UsageInfo info, boolean requestFocus) { int offset = info.getNavigationOffset(); VirtualFile file = info.getVirtualFile(); Project project = info.getProject(); if (file != null) { FileEditorManager.getInstance(project).openTextEditor(new OpenFileDescriptor(project, file, offset), requestFocus); } } public static Set<UsageInfo> getNotExcludedUsageInfos(final UsageView usageView) { Set<Usage> excludedUsages = usageView.getExcludedUsages(); Set<UsageInfo> usageInfos = new LinkedHashSet<UsageInfo>(); for (Usage usage : usageView.getUsages()) { if (usage instanceof UsageInfo2UsageAdapter && !excludedUsages.contains(usage)) { UsageInfo usageInfo = ((UsageInfo2UsageAdapter)usage).getUsageInfo(); usageInfos.add(usageInfo); } } return usageInfos; } public static boolean reportNonRegularUsages(UsageInfo[] usages, final Project project) { boolean inGeneratedCode = hasUsagesInGeneratedCode(usages, project); if (hasNonCodeUsages(usages) || inGeneratedCode) { StatusBar statusBar = WindowManager.getInstance().getStatusBar(project); if (statusBar != null) { statusBar.setInfo(inGeneratedCode ? RefactoringBundle.message("occurrences.found.in.comments.strings.non.java.files.and.generated.code") : RefactoringBundle.message("occurrences.found.in.comments.strings.and.non.java.files")); } return true; } return false; } }
platform/lang-impl/src/com/intellij/usageView/UsageViewUtil.java
/* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.usageView; import com.intellij.lang.injection.InjectedLanguageManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.fileEditor.OpenFileDescriptor; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.GeneratedSourcesFilter; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.wm.StatusBar; import com.intellij.openapi.wm.WindowManager; import com.intellij.psi.ElementDescriptionUtil; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiReference; import com.intellij.refactoring.RefactoringBundle; import com.intellij.refactoring.util.MoveRenameUsageInfo; import com.intellij.refactoring.util.NonCodeUsageInfo; import com.intellij.usages.Usage; import com.intellij.usages.UsageInfo2UsageAdapter; import com.intellij.usages.UsageView; import com.intellij.util.Function; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import java.util.Arrays; import java.util.Collection; import java.util.LinkedHashSet; import java.util.Set; public class UsageViewUtil { private static final Logger LOG = Logger.getInstance("#com.intellij.usageView.UsageViewUtil"); private UsageViewUtil() { } public static String createNodeText(PsiElement element) { return ElementDescriptionUtil.getElementDescription(element, UsageViewNodeTextLocation.INSTANCE); } public static String getShortName(final PsiElement psiElement) { LOG.assertTrue(psiElement.isValid(), psiElement); return ElementDescriptionUtil.getElementDescription(psiElement, UsageViewShortNameLocation.INSTANCE); } public static String getLongName(final PsiElement psiElement) { LOG.assertTrue(psiElement.isValid(), psiElement); return ElementDescriptionUtil.getElementDescription(psiElement, UsageViewLongNameLocation.INSTANCE); } public static String getType(@NotNull PsiElement psiElement) { return ElementDescriptionUtil.getElementDescription(psiElement, UsageViewTypeLocation.INSTANCE); } public static boolean hasNonCodeUsages(UsageInfo[] usages) { for (UsageInfo usage : usages) { if (usage.isNonCodeUsage) return true; } return false; } public static boolean hasUsagesInGeneratedCode(UsageInfo[] usages, Project project) { GeneratedSourcesFilter[] filters = GeneratedSourcesFilter.EP_NAME.getExtensions(); for (UsageInfo usage : usages) { VirtualFile file = usage.getVirtualFile(); if (file != null) { for (GeneratedSourcesFilter filter : filters) { if (filter.isGeneratedSource(file, project)) { return true; } } } } return false; } public static boolean hasReadOnlyUsages(UsageInfo[] usages) { for (UsageInfo usage : usages) { if (!usage.isWritable()) return true; } return false; } public static UsageInfo[] removeDuplicatedUsages(@NotNull UsageInfo[] usages) { Set<UsageInfo> set = new LinkedHashSet<UsageInfo>(Arrays.asList(usages)); // Replace duplicates of move rename usage infos in injections from non code usages of master files String newTextInNonCodeUsage = null; for(UsageInfo usage:usages) { if (!(usage instanceof NonCodeUsageInfo)) continue; newTextInNonCodeUsage = ((NonCodeUsageInfo)usage).newText; break; } if (newTextInNonCodeUsage != null) { for(UsageInfo usage:usages) { if (!(usage instanceof MoveRenameUsageInfo)) continue; PsiFile file = usage.getFile(); if (file != null) { PsiElement context = InjectedLanguageManager.getInstance(file.getProject()).getInjectionHost(file); if (context != null) { PsiElement usageElement = usage.getElement(); if (usageElement == null) continue; PsiReference psiReference = usage.getReference(); if (psiReference == null) continue; int injectionOffsetInMasterFile = InjectedLanguageManager.getInstance(usageElement.getProject()).injectedToHost(usageElement, usageElement.getTextOffset()); TextRange rangeInElement = usage.getRangeInElement(); assert rangeInElement != null : usage; TextRange range = rangeInElement.shiftRight(injectionOffsetInMasterFile); PsiFile containingFile = context.getContainingFile(); if (containingFile == null) continue; //move package to another package set.remove( NonCodeUsageInfo.create( containingFile, range.getStartOffset(), range.getEndOffset(), ((MoveRenameUsageInfo)usage).getReferencedElement(), newTextInNonCodeUsage ) ); } } } } return set.toArray(new UsageInfo[set.size()]); } @NotNull public static UsageInfo[] toUsageInfoArray(@NotNull final Collection<? extends UsageInfo> collection) { final int size = collection.size(); return size == 0 ? UsageInfo.EMPTY_ARRAY : collection.toArray(new UsageInfo[size]); } @NotNull public static PsiElement[] toElements(@NotNull UsageInfo[] usageInfos) { return ContainerUtil.map2Array(usageInfos, PsiElement.class, new Function<UsageInfo, PsiElement>() { @Override public PsiElement fun(UsageInfo info) { return info.getElement(); } }); } public static void navigateTo(@NotNull UsageInfo info, boolean requestFocus) { int offset = info.getNavigationOffset(); VirtualFile file = info.getVirtualFile(); Project project = info.getProject(); FileEditorManager.getInstance(project).openTextEditor(new OpenFileDescriptor(project, file, offset), requestFocus); } public static Set<UsageInfo> getNotExcludedUsageInfos(final UsageView usageView) { Set<Usage> excludedUsages = usageView.getExcludedUsages(); Set<UsageInfo> usageInfos = new LinkedHashSet<UsageInfo>(); for (Usage usage : usageView.getUsages()) { if (usage instanceof UsageInfo2UsageAdapter && !excludedUsages.contains(usage)) { UsageInfo usageInfo = ((UsageInfo2UsageAdapter)usage).getUsageInfo(); usageInfos.add(usageInfo); } } return usageInfos; } public static boolean reportNonRegularUsages(UsageInfo[] usages, final Project project) { boolean inGeneratedCode = hasUsagesInGeneratedCode(usages, project); if (hasNonCodeUsages(usages) || inGeneratedCode) { StatusBar statusBar = WindowManager.getInstance().getStatusBar(project); if (statusBar != null) { statusBar.setInfo(inGeneratedCode ? RefactoringBundle.message("occurrences.found.in.comments.strings.non.java.files.and.generated.code") : RefactoringBundle.message("occurrences.found.in.comments.strings.and.non.java.files")); } return true; } return false; } }
EA-57560
platform/lang-impl/src/com/intellij/usageView/UsageViewUtil.java
EA-57560
Java
apache-2.0
bebd453db9de458d8b3d5a3e2f32efdb7b7fe147
0
dslomov/intellij-community,supersven/intellij-community,FHannes/intellij-community,orekyuu/intellij-community,dslomov/intellij-community,robovm/robovm-studio,fitermay/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,apixandru/intellij-community,ivan-fedorov/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,nicolargo/intellij-community,caot/intellij-community,da1z/intellij-community,adedayo/intellij-community,akosyakov/intellij-community,kdwink/intellij-community,ivan-fedorov/intellij-community,ivan-fedorov/intellij-community,TangHao1987/intellij-community,petteyg/intellij-community,retomerz/intellij-community,fengbaicanhe/intellij-community,muntasirsyed/intellij-community,petteyg/intellij-community,tmpgit/intellij-community,signed/intellij-community,SerCeMan/intellij-community,ol-loginov/intellij-community,blademainer/intellij-community,hurricup/intellij-community,retomerz/intellij-community,alphafoobar/intellij-community,ivan-fedorov/intellij-community,tmpgit/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,vladmm/intellij-community,salguarnieri/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,Lekanich/intellij-community,semonte/intellij-community,diorcety/intellij-community,ibinti/intellij-community,adedayo/intellij-community,xfournet/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,samthor/intellij-community,kool79/intellij-community,ftomassetti/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,semonte/intellij-community,da1z/intellij-community,amith01994/intellij-community,allotria/intellij-community,jagguli/intellij-community,vvv1559/intellij-community,semonte/intellij-community,adedayo/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,diorcety/intellij-community,blademainer/intellij-community,Distrotech/intellij-community,da1z/intellij-community,tmpgit/intellij-community,petteyg/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,alphafoobar/intellij-community,petteyg/intellij-community,orekyuu/intellij-community,orekyuu/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,semonte/intellij-community,samthor/intellij-community,retomerz/intellij-community,Lekanich/intellij-community,samthor/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,robovm/robovm-studio,ibinti/intellij-community,ol-loginov/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,Distrotech/intellij-community,supersven/intellij-community,caot/intellij-community,slisson/intellij-community,da1z/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,amith01994/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,fengbaicanhe/intellij-community,allotria/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,signed/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,orekyuu/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,vladmm/intellij-community,da1z/intellij-community,holmes/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,ftomassetti/intellij-community,SerCeMan/intellij-community,amith01994/intellij-community,ivan-fedorov/intellij-community,suncycheng/intellij-community,slisson/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,asedunov/intellij-community,ryano144/intellij-community,MichaelNedzelsky/intellij-community,robovm/robovm-studio,ryano144/intellij-community,fengbaicanhe/intellij-community,ryano144/intellij-community,orekyuu/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,vladmm/intellij-community,fitermay/intellij-community,amith01994/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,akosyakov/intellij-community,fnouama/intellij-community,fitermay/intellij-community,retomerz/intellij-community,jagguli/intellij-community,ThiagoGarciaAlves/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,hurricup/intellij-community,signed/intellij-community,allotria/intellij-community,Distrotech/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,ahb0327/intellij-community,ThiagoGarciaAlves/intellij-community,slisson/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,FHannes/intellij-community,izonder/intellij-community,FHannes/intellij-community,asedunov/intellij-community,dslomov/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,supersven/intellij-community,retomerz/intellij-community,MER-GROUP/intellij-community,ThiagoGarciaAlves/intellij-community,orekyuu/intellij-community,slisson/intellij-community,signed/intellij-community,asedunov/intellij-community,kdwink/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,izonder/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,wreckJ/intellij-community,jagguli/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,dslomov/intellij-community,caot/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,kdwink/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,FHannes/intellij-community,da1z/intellij-community,FHannes/intellij-community,supersven/intellij-community,apixandru/intellij-community,ol-loginov/intellij-community,caot/intellij-community,mglukhikh/intellij-community,caot/intellij-community,youdonghai/intellij-community,signed/intellij-community,robovm/robovm-studio,ryano144/intellij-community,petteyg/intellij-community,retomerz/intellij-community,amith01994/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,orekyuu/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,muntasirsyed/intellij-community,petteyg/intellij-community,gnuhub/intellij-community,Lekanich/intellij-community,Lekanich/intellij-community,kool79/intellij-community,wreckJ/intellij-community,slisson/intellij-community,alphafoobar/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community,muntasirsyed/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,MichaelNedzelsky/intellij-community,ryano144/intellij-community,holmes/intellij-community,Lekanich/intellij-community,muntasirsyed/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,apixandru/intellij-community,jagguli/intellij-community,kdwink/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,orekyuu/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,dslomov/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,slisson/intellij-community,fnouama/intellij-community,clumsy/intellij-community,diorcety/intellij-community,clumsy/intellij-community,ol-loginov/intellij-community,TangHao1987/intellij-community,tmpgit/intellij-community,petteyg/intellij-community,amith01994/intellij-community,clumsy/intellij-community,slisson/intellij-community,petteyg/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,supersven/intellij-community,dslomov/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,xfournet/intellij-community,blademainer/intellij-community,jagguli/intellij-community,jagguli/intellij-community,izonder/intellij-community,jagguli/intellij-community,kdwink/intellij-community,izonder/intellij-community,jagguli/intellij-community,caot/intellij-community,ivan-fedorov/intellij-community,MER-GROUP/intellij-community,izonder/intellij-community,holmes/intellij-community,diorcety/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,alphafoobar/intellij-community,youdonghai/intellij-community,signed/intellij-community,da1z/intellij-community,holmes/intellij-community,amith01994/intellij-community,xfournet/intellij-community,ryano144/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,ibinti/intellij-community,fnouama/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,robovm/robovm-studio,kool79/intellij-community,kool79/intellij-community,kool79/intellij-community,hurricup/intellij-community,supersven/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,caot/intellij-community,Distrotech/intellij-community,semonte/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,holmes/intellij-community,apixandru/intellij-community,blademainer/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,kdwink/intellij-community,vladmm/intellij-community,caot/intellij-community,hurricup/intellij-community,signed/intellij-community,clumsy/intellij-community,wreckJ/intellij-community,robovm/robovm-studio,ryano144/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,nicolargo/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,SerCeMan/intellij-community,holmes/intellij-community,salguarnieri/intellij-community,slisson/intellij-community,apixandru/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,dslomov/intellij-community,kool79/intellij-community,FHannes/intellij-community,gnuhub/intellij-community,robovm/robovm-studio,ahb0327/intellij-community,blademainer/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,supersven/intellij-community,ahb0327/intellij-community,kool79/intellij-community,wreckJ/intellij-community,izonder/intellij-community,fnouama/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,adedayo/intellij-community,Distrotech/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,alphafoobar/intellij-community,adedayo/intellij-community,diorcety/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,asedunov/intellij-community,diorcety/intellij-community,izonder/intellij-community,retomerz/intellij-community,ftomassetti/intellij-community,ibinti/intellij-community,kdwink/intellij-community,alphafoobar/intellij-community,Lekanich/intellij-community,akosyakov/intellij-community,kdwink/intellij-community,semonte/intellij-community,samthor/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,TangHao1987/intellij-community,SerCeMan/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,ryano144/intellij-community,apixandru/intellij-community,SerCeMan/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,diorcety/intellij-community,fitermay/intellij-community,xfournet/intellij-community,ol-loginov/intellij-community,SerCeMan/intellij-community,SerCeMan/intellij-community,amith01994/intellij-community,nicolargo/intellij-community,pwoodworth/intellij-community,holmes/intellij-community,ol-loginov/intellij-community,clumsy/intellij-community,vladmm/intellij-community,akosyakov/intellij-community,ftomassetti/intellij-community,MichaelNedzelsky/intellij-community,fnouama/intellij-community,MER-GROUP/intellij-community,xfournet/intellij-community,allotria/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,nicolargo/intellij-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,SerCeMan/intellij-community,fnouama/intellij-community,amith01994/intellij-community,amith01994/intellij-community,gnuhub/intellij-community,FHannes/intellij-community,ryano144/intellij-community,fengbaicanhe/intellij-community,pwoodworth/intellij-community,adedayo/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,SerCeMan/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,ftomassetti/intellij-community,robovm/robovm-studio,allotria/intellij-community,supersven/intellij-community,caot/intellij-community,tmpgit/intellij-community,kdwink/intellij-community,ibinti/intellij-community,retomerz/intellij-community,ivan-fedorov/intellij-community,adedayo/intellij-community,signed/intellij-community,alphafoobar/intellij-community,wreckJ/intellij-community,pwoodworth/intellij-community,holmes/intellij-community,clumsy/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,retomerz/intellij-community,muntasirsyed/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,clumsy/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,nicolargo/intellij-community,gnuhub/intellij-community,caot/intellij-community,slisson/intellij-community,ahb0327/intellij-community,fengbaicanhe/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,fitermay/intellij-community,ftomassetti/intellij-community,pwoodworth/intellij-community,kool79/intellij-community,samthor/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,samthor/intellij-community,ibinti/intellij-community,orekyuu/intellij-community,ivan-fedorov/intellij-community,robovm/robovm-studio,fitermay/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,fnouama/intellij-community,supersven/intellij-community,MER-GROUP/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,tmpgit/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,muntasirsyed/intellij-community,petteyg/intellij-community,alphafoobar/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,tmpgit/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,pwoodworth/intellij-community,adedayo/intellij-community,ol-loginov/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,fengbaicanhe/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,semonte/intellij-community,diorcety/intellij-community,petteyg/intellij-community,vladmm/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,salguarnieri/intellij-community,ivan-fedorov/intellij-community,vvv1559/intellij-community,clumsy/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,caot/intellij-community,idea4bsd/idea4bsd,izonder/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,akosyakov/intellij-community,fengbaicanhe/intellij-community,Lekanich/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,allotria/intellij-community,supersven/intellij-community,salguarnieri/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,gnuhub/intellij-community,ryano144/intellij-community,tmpgit/intellij-community,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,ibinti/intellij-community,kool79/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,suncycheng/intellij-community,allotria/intellij-community,gnuhub/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,retomerz/intellij-community,vladmm/intellij-community,holmes/intellij-community,youdonghai/intellij-community,ahb0327/intellij-community,fnouama/intellij-community,izonder/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,dslomov/intellij-community,MichaelNedzelsky/intellij-community,diorcety/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,Lekanich/intellij-community,salguarnieri/intellij-community,orekyuu/intellij-community,alphafoobar/intellij-community,TangHao1987/intellij-community,salguarnieri/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,muntasirsyed/intellij-community,ahb0327/intellij-community,alphafoobar/intellij-community,akosyakov/intellij-community,Distrotech/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,ibinti/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,gnuhub/intellij-community,SerCeMan/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,diorcety/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,caot/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,vladmm/intellij-community,holmes/intellij-community,diorcety/intellij-community,ThiagoGarciaAlves/intellij-community,dslomov/intellij-community,semonte/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,pwoodworth/intellij-community,Lekanich/intellij-community,kool79/intellij-community,slisson/intellij-community,nicolargo/intellij-community,Distrotech/intellij-community,diorcety/intellij-community,hurricup/intellij-community,blademainer/intellij-community,gnuhub/intellij-community,samthor/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,samthor/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,petteyg/intellij-community,hurricup/intellij-community,nicolargo/intellij-community,jagguli/intellij-community,holmes/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,pwoodworth/intellij-community,retomerz/intellij-community,TangHao1987/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,youdonghai/intellij-community,tmpgit/intellij-community,TangHao1987/intellij-community,MER-GROUP/intellij-community,ryano144/intellij-community,vvv1559/intellij-community,holmes/intellij-community,samthor/intellij-community,da1z/intellij-community,signed/intellij-community,asedunov/intellij-community,robovm/robovm-studio,mglukhikh/intellij-community,hurricup/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,kool79/intellij-community,ibinti/intellij-community,tmpgit/intellij-community,nicolargo/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,ahb0327/intellij-community,wreckJ/intellij-community,supersven/intellij-community,akosyakov/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community,TangHao1987/intellij-community,gnuhub/intellij-community,robovm/robovm-studio,asedunov/intellij-community,samthor/intellij-community,asedunov/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,ahb0327/intellij-community,akosyakov/intellij-community,ol-loginov/intellij-community,lucafavatella/intellij-community,nicolargo/intellij-community
/* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.util.io; import com.intellij.openapi.diagnostic.LoggerRt; import com.intellij.openapi.util.SystemInfoRt; import com.intellij.openapi.util.text.StringUtilRt; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import java.io.*; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.nio.channels.FileChannel; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import java.util.UUID; /** * Stripped-down version of {@code com.intellij.openapi.util.io.FileUtil}. * Intended to use by external (out-of-IDE-process) runners and helpers so it should not contain any library dependencies. * * @since 12.0 */ @SuppressWarnings({"UtilityClassWithoutPrivateConstructor"}) public class FileUtilRt { private static final int KILOBYTE = 1024; public static final int MEGABYTE = KILOBYTE * KILOBYTE; public static final int LARGE_FOR_CONTENT_LOADING = Math.max(20 * MEGABYTE, getUserFileSizeLimit()); private static final LoggerRt LOG = LoggerRt.getInstance("#com.intellij.openapi.util.io.FileUtilLight"); private static final int MAX_FILE_IO_ATTEMPTS = 10; private static final boolean USE_FILE_CHANNELS = "true".equalsIgnoreCase(System.getProperty("idea.fs.useChannels")); public static final FileFilter ALL_FILES = new FileFilter() { public boolean accept(File file) { return true; } }; public static final FileFilter ALL_DIRECTORIES = new FileFilter() { public boolean accept(File file) { return file.isDirectory(); } }; protected static final ThreadLocal<byte[]> BUFFER = new ThreadLocal<byte[]>() { @Override protected byte[] initialValue() { return new byte[1024 * 20]; } }; private static String ourCanonicalTempPathCache = null; protected static final boolean NIO_FILE_API_AVAILABLE; // todo: replace reflection with normal code after migration to JDK 1.8 private static Method ourFilesDeleteIfExistsMethod; private static Method ourFilesWalkMethod; private static Method ourFileToPathMethod; private static Object ourDeletionVisitor; private static Class ourNoSuchFileExceptionClass; static { boolean initSuccess = false; try { final Class<?> pathClass = Class.forName("java.nio.file.Path"); final Class<?> visitorClass = Class.forName("java.nio.file.FileVisitor"); final Class<?> filesClass = Class.forName("java.nio.file.Files"); ourNoSuchFileExceptionClass = Class.forName("java.nio.file.NoSuchFileException"); ourFileToPathMethod = Class.forName("java.io.File").getMethod("toPath"); ourFilesWalkMethod = filesClass.getMethod("walkFileTree", pathClass, visitorClass); ourFilesDeleteIfExistsMethod = filesClass.getMethod("deleteIfExists", pathClass); final Class<?> fileVisitResultClass = Class.forName("java.nio.file.FileVisitResult"); final Object Result_Continue = fileVisitResultClass.getDeclaredField("CONTINUE").get(null); final Object Result_Terminate = fileVisitResultClass.getDeclaredField("TERMINATE").get(null); ourDeletionVisitor = Proxy.newProxyInstance(FileUtilRt.class.getClassLoader(), new Class[]{visitorClass}, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (args.length == 2) { final Object second = args[1]; if (second instanceof Throwable) { throw (Throwable)second; } final String methodName = method.getName(); if ("visitFile".equals(methodName) || "postVisitDirectory".equals(methodName)) { if (!performDelete(args[0])) { return Result_Terminate; } } } return Result_Continue; } private boolean performDelete(@NotNull final Object fileObject) { Boolean result = doIOOperation(new RepeatableIOOperation<Boolean, RuntimeException>() { public Boolean execute(boolean lastAttempt) { try { //Files.deleteIfExists(file); ourFilesDeleteIfExistsMethod.invoke(null, fileObject); return Boolean.TRUE; } catch (InvocationTargetException e) { if (!(e.getCause() instanceof IOException)) { return Boolean.FALSE; } } catch (IllegalAccessException e) { return Boolean.FALSE; } return lastAttempt? Boolean.FALSE : null; } }); return Boolean.TRUE.equals(result); } }); initSuccess = true; LOG.info("Using NIO-based file deletion"); } catch (Throwable ignored) { LOG.info("Was not able to detect NIO API"); ourFileToPathMethod = null; ourFilesWalkMethod = null; ourFilesDeleteIfExistsMethod = null; ourDeletionVisitor = null; ourNoSuchFileExceptionClass = null; } NIO_FILE_API_AVAILABLE = initSuccess; } @NotNull public static String getExtension(@NotNull String fileName) { int index = fileName.lastIndexOf('.'); if (index < 0) return ""; return fileName.substring(index + 1); } @NotNull public static CharSequence getExtension(@NotNull CharSequence fileName) { int index = StringUtilRt.lastIndexOf(fileName, '.', 0, fileName.length()); if (index < 0) return ""; return fileName.subSequence(index + 1, fileName.length()); } public static boolean extensionEquals(@NotNull String fileName, @NotNull String extension) { int extLen = extension.length(); if (extLen == 0) { return fileName.indexOf('.') == -1; } int extStart = fileName.length() - extLen; return extStart >= 1 && fileName.charAt(extStart-1) == '.' && fileName.regionMatches(!SystemInfoRt.isFileSystemCaseSensitive, extStart, extension, 0, extLen); } @NotNull public static String toSystemDependentName(@NonNls @NotNull String fileName) { return toSystemDependentName(fileName, File.separatorChar); } @NotNull public static String toSystemDependentName(@NonNls @NotNull String fileName, final char separatorChar) { return fileName.replace('/', separatorChar).replace('\\', separatorChar); } @NotNull public static String toSystemIndependentName(@NonNls @NotNull String fileName) { return fileName.replace('\\', '/'); } @Nullable public static String getRelativePath(File base, File file) { if (base == null || file == null) return null; if (!base.isDirectory()) { base = base.getParentFile(); if (base == null) return null; } //noinspection FileEqualsUsage if (base.equals(file)) return "."; final String filePath = file.getAbsolutePath(); String basePath = base.getAbsolutePath(); return getRelativePath(basePath, filePath, File.separatorChar); } @Nullable public static String getRelativePath(@NotNull String basePath, @NotNull String filePath, final char separator) { return getRelativePath(basePath, filePath, separator, SystemInfoRt.isFileSystemCaseSensitive); } @Nullable public static String getRelativePath(@NotNull String basePath, @NotNull String filePath, final char separator, final boolean caseSensitive) { basePath = ensureEnds(basePath, separator); if (basePath.equals(ensureEnds(filePath, separator))) return "."; int len = 0; int lastSeparatorIndex = 0; // need this for cases like this: base="/temp/abc/base" and file="/temp/ab" final CharComparingStrategy charComparingStrategy = caseSensitive? CharComparingStrategy.IDENTITY : CharComparingStrategy.CASE_INSENSITIVE; while (len < filePath.length() && len < basePath.length() && charComparingStrategy.charsEqual(filePath.charAt(len), basePath.charAt(len))) { if (basePath.charAt(len) == separator) { lastSeparatorIndex = len; } len++; } if (len == 0) return null; StringBuilder relativePath = new StringBuilder(); for (int i = len; i < basePath.length(); i++) { if (basePath.charAt(i) == separator) { relativePath.append(".."); relativePath.append(separator); } } relativePath.append(filePath.substring(lastSeparatorIndex + 1)); return relativePath.toString(); } private static String ensureEnds(@NotNull String s, final char endsWith) { return StringUtilRt.endsWithChar(s, endsWith) ? s : s + endsWith; } @NotNull public static String getNameWithoutExtension(@NotNull String name) { int i = name.lastIndexOf('.'); if (i != -1) { name = name.substring(0, i); } return name; } @NotNull public static File createTempDirectory(@NotNull @NonNls String prefix, @Nullable @NonNls String suffix) throws IOException { return createTempDirectory(prefix, suffix, true); } @NotNull public static File createTempDirectory(@NotNull @NonNls String prefix, @Nullable @NonNls String suffix, boolean deleteOnExit) throws IOException { final File dir = new File(getTempDirectory()); return createTempDirectory(dir, prefix, suffix, deleteOnExit); } @NotNull public static File createTempDirectory(@NotNull File dir, @NotNull @NonNls String prefix, @Nullable @NonNls String suffix) throws IOException { return createTempDirectory(dir, prefix, suffix, true); } @NotNull public static File createTempDirectory(@NotNull File dir, @NotNull @NonNls String prefix, @Nullable @NonNls String suffix, boolean deleteOnExit) throws IOException { File file = doCreateTempFile(dir, prefix, suffix, true); if (deleteOnExit) { file.deleteOnExit(); } if (!file.isDirectory()) { throw new IOException("Cannot create directory: " + file); } return file; } @NotNull public static File createTempFile(@NotNull @NonNls String prefix, @Nullable @NonNls String suffix) throws IOException { return createTempFile(prefix, suffix, false); //false until TeamCity fixes its plugin } @NotNull public static File createTempFile(@NotNull @NonNls String prefix, @Nullable @NonNls String suffix, boolean deleteOnExit) throws IOException { final File dir = new File(getTempDirectory()); return createTempFile(dir, prefix, suffix, true, deleteOnExit); } @NotNull public static File createTempFile(@NonNls File dir, @NotNull @NonNls String prefix, @Nullable @NonNls String suffix) throws IOException { return createTempFile(dir, prefix, suffix, true, true); } @NotNull public static File createTempFile(@NonNls File dir, @NotNull @NonNls String prefix, @Nullable @NonNls String suffix, boolean create) throws IOException { return createTempFile(dir, prefix, suffix, create, true); } @NotNull public static File createTempFile(@NonNls File dir, @NotNull @NonNls String prefix, @Nullable @NonNls String suffix, boolean create, boolean deleteOnExit) throws IOException { File file = doCreateTempFile(dir, prefix, suffix, false); if (deleteOnExit) { file.deleteOnExit(); } if (!create) { if (!file.delete() && file.exists()) { throw new IOException("Cannot delete file: " + file); } } return file; } @NotNull private static File doCreateTempFile(@NotNull File dir, @NotNull @NonNls String prefix, @Nullable @NonNls String suffix, boolean isDirectory) throws IOException { //noinspection ResultOfMethodCallIgnored dir.mkdirs(); if (prefix.length() < 3) { prefix = (prefix + "___").substring(0, 3); } if (suffix == null) { suffix = ".tmp"; } int exceptionsCount = 0; while (true) { try { final File temp = createTemp(prefix, suffix, dir, isDirectory); return normalizeFile(temp); } catch (IOException e) { // Win32 createFileExclusively access denied if (++exceptionsCount >= 100) { throw e; } } } } @NotNull private static File createTemp(@NotNull String prefix, @NotNull String suffix, @NotNull File directory, boolean isDirectory) throws IOException { // normalize and use only the file name from the prefix prefix = new File(prefix).getName(); File f; int i = 0; do { String name = prefix + i + suffix; f = new File(directory, name); if (!name.equals(f.getName())) { throw new IOException("Unable to create temporary file " + f + " for name " + name); } i++; } while (f.exists()); boolean success = isDirectory ? f.mkdir() : f.createNewFile(); if (!success) { throw new IOException("Unable to create temporary file " + f); } return f; } @NotNull private static File normalizeFile(@NotNull File temp) throws IOException { final File canonical = temp.getCanonicalFile(); return SystemInfoRt.isWindows && canonical.getAbsolutePath().contains(" ") ? temp.getAbsoluteFile() : canonical; } @NotNull public static String getTempDirectory() { if (ourCanonicalTempPathCache == null) { ourCanonicalTempPathCache = calcCanonicalTempPath(); } return ourCanonicalTempPathCache; } @NotNull private static String calcCanonicalTempPath() { final File file = new File(System.getProperty("java.io.tmpdir")); try { final String canonical = file.getCanonicalPath(); if (!SystemInfoRt.isWindows || !canonical.contains(" ")) { return canonical; } } catch (IOException ignore) { } return file.getAbsolutePath(); } @TestOnly public static void resetCanonicalTempPathCache(final String tempPath) { ourCanonicalTempPathCache = tempPath; } @NotNull public static File generateRandomTemporaryPath() throws IOException { File file = new File(getTempDirectory(), UUID.randomUUID().toString()); int i = 0; while (file.exists() && i < 5) { file = new File(getTempDirectory(), UUID.randomUUID().toString()); ++i; } if (file.exists()) { throw new IOException("Couldn't generate unique random path."); } return normalizeFile(file); } /** * Set executable attribute, it makes sense only on non-windows platforms. * * @param path the path to use * @param executableFlag new value of executable attribute * @throws java.io.IOException if there is a problem with setting the flag */ public static void setExecutableAttribute(@NotNull String path, boolean executableFlag) throws IOException { final File file = new File(path); if (!file.setExecutable(executableFlag) && file.canExecute() != executableFlag) { LOG.warn("Can't set executable attribute of '" + path + "' to " + executableFlag); } } @NotNull public static String loadFile(@NotNull File file) throws IOException { return loadFile(file, null, false); } @NotNull public static String loadFile(@NotNull File file, boolean convertLineSeparators) throws IOException { return loadFile(file, null, convertLineSeparators); } @NotNull public static String loadFile(@NotNull File file, @Nullable @NonNls String encoding) throws IOException { return loadFile(file, encoding, false); } @NotNull public static String loadFile(@NotNull File file, @Nullable @NonNls String encoding, boolean convertLineSeparators) throws IOException { final String s = new String(loadFileText(file, encoding)); return convertLineSeparators ? StringUtilRt.convertLineSeparators(s) : s; } @NotNull public static char[] loadFileText(@NotNull File file) throws IOException { return loadFileText(file, (String)null); } @NotNull public static char[] loadFileText(@NotNull File file, @Nullable @NonNls String encoding) throws IOException { InputStream stream = new FileInputStream(file); @SuppressWarnings("IOResourceOpenedButNotSafelyClosed") Reader reader = encoding == null ? new InputStreamReader(stream) : new InputStreamReader(stream, encoding); try { return loadText(reader, (int)file.length()); } finally { reader.close(); } } @NotNull public static char[] loadFileText(@NotNull File file, @NotNull @NonNls Charset encoding) throws IOException { Reader reader = new InputStreamReader(new FileInputStream(file), encoding); try { return loadText(reader, (int)file.length()); } finally { reader.close(); } } @NotNull public static char[] loadText(@NotNull Reader reader, int length) throws IOException { char[] chars = new char[length]; int count = 0; while (count < chars.length) { int n = reader.read(chars, count, chars.length - count); if (n <= 0) break; count += n; } if (count == chars.length) { return chars; } else { char[] newChars = new char[count]; System.arraycopy(chars, 0, newChars, 0, count); return newChars; } } @NotNull public static List<String> loadLines(@NotNull File file) throws IOException { return loadLines(file.getPath()); } @NotNull public static List<String> loadLines(@NotNull File file, @Nullable @NonNls String encoding) throws IOException { return loadLines(file.getPath(), encoding); } @NotNull public static List<String> loadLines(@NotNull String path) throws IOException { return loadLines(path, null); } @NotNull public static List<String> loadLines(@NotNull String path, @Nullable @NonNls String encoding) throws IOException { InputStream stream = new FileInputStream(path); try { @SuppressWarnings("IOResourceOpenedButNotSafelyClosed") InputStreamReader in = encoding == null ? new InputStreamReader(stream) : new InputStreamReader(stream, encoding); BufferedReader reader = new BufferedReader(in); try { return loadLines(reader); } finally { reader.close(); } } finally { stream.close(); } } @NotNull public static List<String> loadLines(@NotNull BufferedReader reader) throws IOException { List<String> lines = new ArrayList<String>(); String line; while ((line = reader.readLine()) != null) { lines.add(line); } return lines; } @NotNull public static byte[] loadBytes(@NotNull InputStream stream) throws IOException { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); final byte[] bytes = BUFFER.get(); while (true) { int n = stream.read(bytes, 0, bytes.length); if (n <= 0) break; buffer.write(bytes, 0, n); } buffer.close(); return buffer.toByteArray(); } public static boolean isTooLarge(long len) { return len > LARGE_FOR_CONTENT_LOADING; } @NotNull public static byte[] loadBytes(@NotNull InputStream stream, int length) throws IOException { byte[] bytes = new byte[length]; int count = 0; while (count < length) { int n = stream.read(bytes, count, length - count); if (n <= 0) break; count += n; } return bytes; } /** * Get parent for the file. The method correctly * processes "." and ".." in file names. The name * remains relative if was relative before. * * @param file a file to analyze * @return a parent or the null if the file has no parent. */ @Nullable public static File getParentFile(@NotNull File file) { int skipCount = 0; File parentFile = file; while (true) { parentFile = parentFile.getParentFile(); if (parentFile == null) { return null; } if (".".equals(parentFile.getName())) { continue; } if ("..".equals(parentFile.getName())) { skipCount++; continue; } if (skipCount > 0) { skipCount--; continue; } return parentFile; } } /** * Warning! this method is _not_ symlinks-aware. Consider using com.intellij.openapi.util.io.FileUtil.delete() * @param file file or directory to delete * @return true if the file did not exist or was successfully deleted */ public static boolean delete(@NotNull File file) { if (NIO_FILE_API_AVAILABLE) { return deleteRecursivelyNIO(file); } return deleteRecursively(file); } protected static boolean deleteRecursivelyNIO(File file) { try { /* Files.walkFileTree(file.toPath(), new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.deleteIfExists(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { Files.deleteIfExists(dir); return FileVisitResult.CONTINUE; } }); */ final Object pathObject = ourFileToPathMethod.invoke(file); ourFilesWalkMethod.invoke(null, pathObject, ourDeletionVisitor); } catch (InvocationTargetException e) { final Throwable cause = e.getCause(); if (cause == null || !ourNoSuchFileExceptionClass.isInstance(cause)) { LOG.info(e); return false; } } catch (Exception e) { LOG.info(e); return false; } return true; } private static boolean deleteRecursively(@NotNull File file) { File[] files = file.listFiles(); if (files != null) { for (File child : files) { if (!deleteRecursively(child)) return false; } } return deleteFile(file); } public interface RepeatableIOOperation<T, E extends Throwable> { @Nullable T execute(boolean lastAttempt) throws E; } @Nullable public static <T, E extends Throwable> T doIOOperation(@NotNull RepeatableIOOperation<T, E> ioTask) throws E { for (int i = MAX_FILE_IO_ATTEMPTS; i > 0; i--) { T result = ioTask.execute(i == 1); if (result != null) return result; try { //noinspection BusyWait Thread.sleep(10); } catch (InterruptedException ignored) { } } return null; } protected static boolean deleteFile(@NotNull final File file) { Boolean result = doIOOperation(new RepeatableIOOperation<Boolean, RuntimeException>() { public Boolean execute(boolean lastAttempt) { if (file.delete() || !file.exists()) return Boolean.TRUE; else if (lastAttempt) return Boolean.FALSE; else return null; } }); return Boolean.TRUE.equals(result); } public static boolean ensureCanCreateFile(@NotNull File file) { if (file.exists()) return file.canWrite(); if (!createIfNotExists(file)) return false; return delete(file); } public static boolean createIfNotExists(@NotNull File file) { if (file.exists()) return true; try { if (!createParentDirs(file)) return false; OutputStream s = new FileOutputStream(file); s.close(); return true; } catch (IOException e) { LOG.info(e); return false; } } public static boolean createParentDirs(@NotNull File file) { if (!file.exists()) { final File parentFile = file.getParentFile(); if (parentFile != null) { return createDirectory(parentFile); } } return true; } public static boolean createDirectory(@NotNull File path) { return path.isDirectory() || path.mkdirs(); } public static void copy(@NotNull File fromFile, @NotNull File toFile) throws IOException { if (!ensureCanCreateFile(toFile)) { return; } FileOutputStream fos = new FileOutputStream(toFile); try { FileInputStream fis = new FileInputStream(fromFile); try { copy(fis, fos); } finally { fis.close(); } } finally { fos.close(); } long timeStamp = fromFile.lastModified(); if (timeStamp < 0) { LOG.warn("Invalid timestamp " + timeStamp + " of '" + fromFile + "'"); } else if (!toFile.setLastModified(timeStamp)) { LOG.warn("Unable to set timestamp " + timeStamp + " to '" + toFile + "'"); } } public static void copy(@NotNull InputStream inputStream, @NotNull OutputStream outputStream) throws IOException { if (USE_FILE_CHANNELS && inputStream instanceof FileInputStream && outputStream instanceof FileOutputStream) { final FileChannel fromChannel = ((FileInputStream)inputStream).getChannel(); try { final FileChannel toChannel = ((FileOutputStream)outputStream).getChannel(); try { fromChannel.transferTo(0, Long.MAX_VALUE, toChannel); } finally { toChannel.close(); } } finally { fromChannel.close(); } } else { final byte[] buffer = BUFFER.get(); while (true) { int read = inputStream.read(buffer); if (read < 0) break; outputStream.write(buffer, 0, read); } } } public static int getUserFileSizeLimit() { try { return Integer.parseInt(System.getProperty("idea.max.intellisense.filesize")) * KILOBYTE; } catch (NumberFormatException e) { return 2500 * KILOBYTE; } } private interface CharComparingStrategy { CharComparingStrategy IDENTITY = new CharComparingStrategy() { @Override public boolean charsEqual(char ch1, char ch2) { return ch1 == ch2; } }; CharComparingStrategy CASE_INSENSITIVE = new CharComparingStrategy() { @Override public boolean charsEqual(char ch1, char ch2) { return StringUtilRt.charsEqualIgnoreCase(ch1, ch2); } }; boolean charsEqual(char ch1, char ch2); } }
platform/util-rt/src/com/intellij/openapi/util/io/FileUtilRt.java
/* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.util.io; import com.intellij.openapi.diagnostic.LoggerRt; import com.intellij.openapi.util.SystemInfoRt; import com.intellij.openapi.util.text.StringUtilRt; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import java.io.*; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.nio.channels.FileChannel; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import java.util.UUID; /** * Stripped-down version of {@code com.intellij.openapi.util.io.FileUtil}. * Intended to use by external (out-of-IDE-process) runners and helpers so it should not contain any library dependencies. * * @since 12.0 */ @SuppressWarnings({"UtilityClassWithoutPrivateConstructor"}) public class FileUtilRt { private static final int KILOBYTE = 1024; public static final int MEGABYTE = KILOBYTE * KILOBYTE; public static final int LARGE_FOR_CONTENT_LOADING = Math.max(20 * MEGABYTE, getUserFileSizeLimit()); private static final LoggerRt LOG = LoggerRt.getInstance("#com.intellij.openapi.util.io.FileUtilLight"); private static final int MAX_FILE_IO_ATTEMPTS = 10; private static final boolean USE_FILE_CHANNELS = "true".equalsIgnoreCase(System.getProperty("idea.fs.useChannels")); public static final FileFilter ALL_FILES = new FileFilter() { public boolean accept(File file) { return true; } }; public static final FileFilter ALL_DIRECTORIES = new FileFilter() { public boolean accept(File file) { return file.isDirectory(); } }; protected static final ThreadLocal<byte[]> BUFFER = new ThreadLocal<byte[]>() { @Override protected byte[] initialValue() { return new byte[1024 * 20]; } }; private static String ourCanonicalTempPathCache = null; protected static final boolean NIO_FILE_API_AVAILABLE; // todo: replace reflection with normal code after migration to JDK 1.8 private static Method ourFilesDeleteIfExistsMethod; private static Method ourFilesWalkMethod; private static Method ourFileToPathMethod; private static Object ourDeletionVisitor; private static Class ourNoSuchFileExceptionClass; static { boolean initSuccess = false; try { final Class<?> pathClass = Class.forName("java.nio.file.Path"); final Class<?> visitorClass = Class.forName("java.nio.file.FileVisitor"); final Class<?> filesClass = Class.forName("java.nio.file.Files"); ourNoSuchFileExceptionClass = Class.forName("java.nio.file.NoSuchFileException"); ourFileToPathMethod = Class.forName("java.io.File").getMethod("toPath"); ourFilesWalkMethod = filesClass.getMethod("walkFileTree", pathClass, visitorClass); ourFilesDeleteIfExistsMethod = filesClass.getMethod("deleteIfExists", pathClass); final Class<?> fileVisitResultClass = Class.forName("java.nio.file.FileVisitResult"); final Object Result_Continue = fileVisitResultClass.getDeclaredField("CONTINUE").get(null); final Object Result_Terminate = fileVisitResultClass.getDeclaredField("TERMINATE").get(null); ourDeletionVisitor = Proxy.newProxyInstance(FileUtilRt.class.getClassLoader(), new Class[]{visitorClass}, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (args.length == 2) { final Object second = args[1]; if (second instanceof Throwable) { throw (Throwable)second; } final String methodName = method.getName(); if ("visitFile".equals(methodName) || "postVisitDirectory".equals(methodName)) { if (!performDelete(args[0])) { return Result_Terminate; } } } return Result_Continue; } private boolean performDelete(@NotNull final Object fileObject) { Boolean result = doIOOperation(new RepeatableIOOperation<Boolean, RuntimeException>() { public Boolean execute(boolean lastAttempt) { try { //Files.deleteIfExists(file); ourFilesDeleteIfExistsMethod.invoke(null, fileObject); return Boolean.TRUE; } catch (InvocationTargetException e) { if (!(e.getCause() instanceof IOException)) { return Boolean.FALSE; } } catch (IllegalAccessException e) { return Boolean.FALSE; } return lastAttempt? Boolean.FALSE : null; } }); return Boolean.TRUE.equals(result); } }); initSuccess = true; LOG.info("Using NIO-based file deletion"); } catch (Throwable ignored) { LOG.info("Was not able to detect NIO API"); ourFileToPathMethod = null; ourFilesWalkMethod = null; ourFilesDeleteIfExistsMethod = null; ourDeletionVisitor = null; ourNoSuchFileExceptionClass = null; } NIO_FILE_API_AVAILABLE = initSuccess; } @NotNull public static String getExtension(@NotNull String fileName) { int index = fileName.lastIndexOf('.'); if (index < 0) return ""; return fileName.substring(index + 1); } @NotNull public static CharSequence getExtension(@NotNull CharSequence fileName) { int index = StringUtilRt.lastIndexOf(fileName, '.', 0, fileName.length()); if (index < 0) return ""; return fileName.subSequence(index + 1, fileName.length()); } public static boolean extensionEquals(@NotNull String fileName, @NotNull String extension) { int extLen = extension.length(); if (extLen == 0) { return fileName.indexOf('.') == -1; } int extStart = fileName.length() - extLen; return extStart >= 1 && fileName.charAt(extStart-1) == '.' && fileName.regionMatches(!SystemInfoRt.isFileSystemCaseSensitive, extStart, extension, 0, extLen); } @NotNull public static String toSystemDependentName(@NonNls @NotNull String fileName) { return toSystemDependentName(fileName, File.separatorChar); } @NotNull public static String toSystemDependentName(@NonNls @NotNull String fileName, final char separatorChar) { return fileName.replace('/', separatorChar).replace('\\', separatorChar); } @NotNull public static String toSystemIndependentName(@NonNls @NotNull String fileName) { return fileName.replace('\\', '/'); } @Nullable public static String getRelativePath(File base, File file) { if (base == null || file == null) return null; if (!base.isDirectory()) { base = base.getParentFile(); if (base == null) return null; } //noinspection FileEqualsUsage if (base.equals(file)) return "."; final String filePath = file.getAbsolutePath(); String basePath = base.getAbsolutePath(); return getRelativePath(basePath, filePath, File.separatorChar); } @Nullable public static String getRelativePath(@NotNull String basePath, @NotNull String filePath, final char separator) { return getRelativePath(basePath, filePath, separator, SystemInfoRt.isFileSystemCaseSensitive); } @Nullable public static String getRelativePath(@NotNull String basePath, @NotNull String filePath, final char separator, final boolean caseSensitive) { basePath = ensureEnds(basePath, separator); String basePathToCompare = caseSensitive ? basePath : basePath.toLowerCase(); String filePathToCompare = caseSensitive ? filePath : filePath.toLowerCase(); if (basePathToCompare.equals(ensureEnds(filePathToCompare, separator))) return "."; int len = 0; int lastSeparatorIndex = 0; // need this for cases like this: base="/temp/abc/base" and file="/temp/ab" while (len < filePath.length() && len < basePath.length() && filePathToCompare.charAt(len) == basePathToCompare.charAt(len)) { if (basePath.charAt(len) == separator) { lastSeparatorIndex = len; } len++; } if (len == 0) return null; StringBuilder relativePath = new StringBuilder(); for (int i = len; i < basePath.length(); i++) { if (basePath.charAt(i) == separator) { relativePath.append(".."); relativePath.append(separator); } } relativePath.append(filePath.substring(lastSeparatorIndex + 1)); return relativePath.toString(); } private static String ensureEnds(@NotNull String s, final char endsWith) { return StringUtilRt.endsWithChar(s, endsWith) ? s : s + endsWith; } @NotNull public static String getNameWithoutExtension(@NotNull String name) { int i = name.lastIndexOf('.'); if (i != -1) { name = name.substring(0, i); } return name; } @NotNull public static File createTempDirectory(@NotNull @NonNls String prefix, @Nullable @NonNls String suffix) throws IOException { return createTempDirectory(prefix, suffix, true); } @NotNull public static File createTempDirectory(@NotNull @NonNls String prefix, @Nullable @NonNls String suffix, boolean deleteOnExit) throws IOException { final File dir = new File(getTempDirectory()); return createTempDirectory(dir, prefix, suffix, deleteOnExit); } @NotNull public static File createTempDirectory(@NotNull File dir, @NotNull @NonNls String prefix, @Nullable @NonNls String suffix) throws IOException { return createTempDirectory(dir, prefix, suffix, true); } @NotNull public static File createTempDirectory(@NotNull File dir, @NotNull @NonNls String prefix, @Nullable @NonNls String suffix, boolean deleteOnExit) throws IOException { File file = doCreateTempFile(dir, prefix, suffix, true); if (deleteOnExit) { file.deleteOnExit(); } if (!file.isDirectory()) { throw new IOException("Cannot create directory: " + file); } return file; } @NotNull public static File createTempFile(@NotNull @NonNls String prefix, @Nullable @NonNls String suffix) throws IOException { return createTempFile(prefix, suffix, false); //false until TeamCity fixes its plugin } @NotNull public static File createTempFile(@NotNull @NonNls String prefix, @Nullable @NonNls String suffix, boolean deleteOnExit) throws IOException { final File dir = new File(getTempDirectory()); return createTempFile(dir, prefix, suffix, true, deleteOnExit); } @NotNull public static File createTempFile(@NonNls File dir, @NotNull @NonNls String prefix, @Nullable @NonNls String suffix) throws IOException { return createTempFile(dir, prefix, suffix, true, true); } @NotNull public static File createTempFile(@NonNls File dir, @NotNull @NonNls String prefix, @Nullable @NonNls String suffix, boolean create) throws IOException { return createTempFile(dir, prefix, suffix, create, true); } @NotNull public static File createTempFile(@NonNls File dir, @NotNull @NonNls String prefix, @Nullable @NonNls String suffix, boolean create, boolean deleteOnExit) throws IOException { File file = doCreateTempFile(dir, prefix, suffix, false); if (deleteOnExit) { file.deleteOnExit(); } if (!create) { if (!file.delete() && file.exists()) { throw new IOException("Cannot delete file: " + file); } } return file; } @NotNull private static File doCreateTempFile(@NotNull File dir, @NotNull @NonNls String prefix, @Nullable @NonNls String suffix, boolean isDirectory) throws IOException { //noinspection ResultOfMethodCallIgnored dir.mkdirs(); if (prefix.length() < 3) { prefix = (prefix + "___").substring(0, 3); } if (suffix == null) { suffix = ".tmp"; } int exceptionsCount = 0; while (true) { try { final File temp = createTemp(prefix, suffix, dir, isDirectory); return normalizeFile(temp); } catch (IOException e) { // Win32 createFileExclusively access denied if (++exceptionsCount >= 100) { throw e; } } } } @NotNull private static File createTemp(@NotNull String prefix, @NotNull String suffix, @NotNull File directory, boolean isDirectory) throws IOException { // normalize and use only the file name from the prefix prefix = new File(prefix).getName(); File f; int i = 0; do { String name = prefix + i + suffix; f = new File(directory, name); if (!name.equals(f.getName())) { throw new IOException("Unable to create temporary file " + f + " for name " + name); } i++; } while (f.exists()); boolean success = isDirectory ? f.mkdir() : f.createNewFile(); if (!success) { throw new IOException("Unable to create temporary file " + f); } return f; } @NotNull private static File normalizeFile(@NotNull File temp) throws IOException { final File canonical = temp.getCanonicalFile(); return SystemInfoRt.isWindows && canonical.getAbsolutePath().contains(" ") ? temp.getAbsoluteFile() : canonical; } @NotNull public static String getTempDirectory() { if (ourCanonicalTempPathCache == null) { ourCanonicalTempPathCache = calcCanonicalTempPath(); } return ourCanonicalTempPathCache; } @NotNull private static String calcCanonicalTempPath() { final File file = new File(System.getProperty("java.io.tmpdir")); try { final String canonical = file.getCanonicalPath(); if (!SystemInfoRt.isWindows || !canonical.contains(" ")) { return canonical; } } catch (IOException ignore) { } return file.getAbsolutePath(); } @TestOnly public static void resetCanonicalTempPathCache(final String tempPath) { ourCanonicalTempPathCache = tempPath; } @NotNull public static File generateRandomTemporaryPath() throws IOException { File file = new File(getTempDirectory(), UUID.randomUUID().toString()); int i = 0; while (file.exists() && i < 5) { file = new File(getTempDirectory(), UUID.randomUUID().toString()); ++i; } if (file.exists()) { throw new IOException("Couldn't generate unique random path."); } return normalizeFile(file); } /** * Set executable attribute, it makes sense only on non-windows platforms. * * @param path the path to use * @param executableFlag new value of executable attribute * @throws java.io.IOException if there is a problem with setting the flag */ public static void setExecutableAttribute(@NotNull String path, boolean executableFlag) throws IOException { final File file = new File(path); if (!file.setExecutable(executableFlag) && file.canExecute() != executableFlag) { LOG.warn("Can't set executable attribute of '" + path + "' to " + executableFlag); } } @NotNull public static String loadFile(@NotNull File file) throws IOException { return loadFile(file, null, false); } @NotNull public static String loadFile(@NotNull File file, boolean convertLineSeparators) throws IOException { return loadFile(file, null, convertLineSeparators); } @NotNull public static String loadFile(@NotNull File file, @Nullable @NonNls String encoding) throws IOException { return loadFile(file, encoding, false); } @NotNull public static String loadFile(@NotNull File file, @Nullable @NonNls String encoding, boolean convertLineSeparators) throws IOException { final String s = new String(loadFileText(file, encoding)); return convertLineSeparators ? StringUtilRt.convertLineSeparators(s) : s; } @NotNull public static char[] loadFileText(@NotNull File file) throws IOException { return loadFileText(file, (String)null); } @NotNull public static char[] loadFileText(@NotNull File file, @Nullable @NonNls String encoding) throws IOException { InputStream stream = new FileInputStream(file); @SuppressWarnings("IOResourceOpenedButNotSafelyClosed") Reader reader = encoding == null ? new InputStreamReader(stream) : new InputStreamReader(stream, encoding); try { return loadText(reader, (int)file.length()); } finally { reader.close(); } } @NotNull public static char[] loadFileText(@NotNull File file, @NotNull @NonNls Charset encoding) throws IOException { Reader reader = new InputStreamReader(new FileInputStream(file), encoding); try { return loadText(reader, (int)file.length()); } finally { reader.close(); } } @NotNull public static char[] loadText(@NotNull Reader reader, int length) throws IOException { char[] chars = new char[length]; int count = 0; while (count < chars.length) { int n = reader.read(chars, count, chars.length - count); if (n <= 0) break; count += n; } if (count == chars.length) { return chars; } else { char[] newChars = new char[count]; System.arraycopy(chars, 0, newChars, 0, count); return newChars; } } @NotNull public static List<String> loadLines(@NotNull File file) throws IOException { return loadLines(file.getPath()); } @NotNull public static List<String> loadLines(@NotNull File file, @Nullable @NonNls String encoding) throws IOException { return loadLines(file.getPath(), encoding); } @NotNull public static List<String> loadLines(@NotNull String path) throws IOException { return loadLines(path, null); } @NotNull public static List<String> loadLines(@NotNull String path, @Nullable @NonNls String encoding) throws IOException { InputStream stream = new FileInputStream(path); try { @SuppressWarnings("IOResourceOpenedButNotSafelyClosed") InputStreamReader in = encoding == null ? new InputStreamReader(stream) : new InputStreamReader(stream, encoding); BufferedReader reader = new BufferedReader(in); try { return loadLines(reader); } finally { reader.close(); } } finally { stream.close(); } } @NotNull public static List<String> loadLines(@NotNull BufferedReader reader) throws IOException { List<String> lines = new ArrayList<String>(); String line; while ((line = reader.readLine()) != null) { lines.add(line); } return lines; } @NotNull public static byte[] loadBytes(@NotNull InputStream stream) throws IOException { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); final byte[] bytes = BUFFER.get(); while (true) { int n = stream.read(bytes, 0, bytes.length); if (n <= 0) break; buffer.write(bytes, 0, n); } buffer.close(); return buffer.toByteArray(); } public static boolean isTooLarge(long len) { return len > LARGE_FOR_CONTENT_LOADING; } @NotNull public static byte[] loadBytes(@NotNull InputStream stream, int length) throws IOException { byte[] bytes = new byte[length]; int count = 0; while (count < length) { int n = stream.read(bytes, count, length - count); if (n <= 0) break; count += n; } return bytes; } /** * Get parent for the file. The method correctly * processes "." and ".." in file names. The name * remains relative if was relative before. * * @param file a file to analyze * @return a parent or the null if the file has no parent. */ @Nullable public static File getParentFile(@NotNull File file) { int skipCount = 0; File parentFile = file; while (true) { parentFile = parentFile.getParentFile(); if (parentFile == null) { return null; } if (".".equals(parentFile.getName())) { continue; } if ("..".equals(parentFile.getName())) { skipCount++; continue; } if (skipCount > 0) { skipCount--; continue; } return parentFile; } } /** * Warning! this method is _not_ symlinks-aware. Consider using com.intellij.openapi.util.io.FileUtil.delete() * @param file file or directory to delete * @return true if the file did not exist or was successfully deleted */ public static boolean delete(@NotNull File file) { if (NIO_FILE_API_AVAILABLE) { return deleteRecursivelyNIO(file); } return deleteRecursively(file); } protected static boolean deleteRecursivelyNIO(File file) { try { /* Files.walkFileTree(file.toPath(), new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.deleteIfExists(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { Files.deleteIfExists(dir); return FileVisitResult.CONTINUE; } }); */ final Object pathObject = ourFileToPathMethod.invoke(file); ourFilesWalkMethod.invoke(null, pathObject, ourDeletionVisitor); } catch (InvocationTargetException e) { final Throwable cause = e.getCause(); if (cause == null || !ourNoSuchFileExceptionClass.isInstance(cause)) { LOG.info(e); return false; } } catch (Exception e) { LOG.info(e); return false; } return true; } private static boolean deleteRecursively(@NotNull File file) { File[] files = file.listFiles(); if (files != null) { for (File child : files) { if (!deleteRecursively(child)) return false; } } return deleteFile(file); } public interface RepeatableIOOperation<T, E extends Throwable> { @Nullable T execute(boolean lastAttempt) throws E; } @Nullable public static <T, E extends Throwable> T doIOOperation(@NotNull RepeatableIOOperation<T, E> ioTask) throws E { for (int i = MAX_FILE_IO_ATTEMPTS; i > 0; i--) { T result = ioTask.execute(i == 1); if (result != null) return result; try { //noinspection BusyWait Thread.sleep(10); } catch (InterruptedException ignored) { } } return null; } protected static boolean deleteFile(@NotNull final File file) { Boolean result = doIOOperation(new RepeatableIOOperation<Boolean, RuntimeException>() { public Boolean execute(boolean lastAttempt) { if (file.delete() || !file.exists()) return Boolean.TRUE; else if (lastAttempt) return Boolean.FALSE; else return null; } }); return Boolean.TRUE.equals(result); } public static boolean ensureCanCreateFile(@NotNull File file) { if (file.exists()) return file.canWrite(); if (!createIfNotExists(file)) return false; return delete(file); } public static boolean createIfNotExists(@NotNull File file) { if (file.exists()) return true; try { if (!createParentDirs(file)) return false; OutputStream s = new FileOutputStream(file); s.close(); return true; } catch (IOException e) { LOG.info(e); return false; } } public static boolean createParentDirs(@NotNull File file) { if (!file.exists()) { final File parentFile = file.getParentFile(); if (parentFile != null) { return createDirectory(parentFile); } } return true; } public static boolean createDirectory(@NotNull File path) { return path.isDirectory() || path.mkdirs(); } public static void copy(@NotNull File fromFile, @NotNull File toFile) throws IOException { if (!ensureCanCreateFile(toFile)) { return; } FileOutputStream fos = new FileOutputStream(toFile); try { FileInputStream fis = new FileInputStream(fromFile); try { copy(fis, fos); } finally { fis.close(); } } finally { fos.close(); } long timeStamp = fromFile.lastModified(); if (timeStamp < 0) { LOG.warn("Invalid timestamp " + timeStamp + " of '" + fromFile + "'"); } else if (!toFile.setLastModified(timeStamp)) { LOG.warn("Unable to set timestamp " + timeStamp + " to '" + toFile + "'"); } } public static void copy(@NotNull InputStream inputStream, @NotNull OutputStream outputStream) throws IOException { if (USE_FILE_CHANNELS && inputStream instanceof FileInputStream && outputStream instanceof FileOutputStream) { final FileChannel fromChannel = ((FileInputStream)inputStream).getChannel(); try { final FileChannel toChannel = ((FileOutputStream)outputStream).getChannel(); try { fromChannel.transferTo(0, Long.MAX_VALUE, toChannel); } finally { toChannel.close(); } } finally { fromChannel.close(); } } else { final byte[] buffer = BUFFER.get(); while (true) { int read = inputStream.read(buffer); if (read < 0) break; outputStream.write(buffer, 0, read); } } } public static int getUserFileSizeLimit() { try { return Integer.parseInt(System.getProperty("idea.max.intellisense.filesize")) * KILOBYTE; } catch (NumberFormatException e) { return 2500 * KILOBYTE; } } }
avoiding toLowerCase() calls
platform/util-rt/src/com/intellij/openapi/util/io/FileUtilRt.java
avoiding toLowerCase() calls
Java
apache-2.0
90163c5982e8ebdb1cf7b54f9fc31a3b65ab1b7b
0
Distrotech/intellij-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,dslomov/intellij-community,clumsy/intellij-community,ahb0327/intellij-community,ftomassetti/intellij-community,kool79/intellij-community,muntasirsyed/intellij-community,vvv1559/intellij-community,kool79/intellij-community,fnouama/intellij-community,semonte/intellij-community,clumsy/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,signed/intellij-community,alphafoobar/intellij-community,amith01994/intellij-community,tmpgit/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,holmes/intellij-community,retomerz/intellij-community,izonder/intellij-community,Lekanich/intellij-community,Lekanich/intellij-community,lucafavatella/intellij-community,jagguli/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,petteyg/intellij-community,samthor/intellij-community,ThiagoGarciaAlves/intellij-community,supersven/intellij-community,holmes/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,adedayo/intellij-community,apixandru/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,asedunov/intellij-community,petteyg/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,diorcety/intellij-community,jagguli/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,supersven/intellij-community,amith01994/intellij-community,MER-GROUP/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,nicolargo/intellij-community,muntasirsyed/intellij-community,samthor/intellij-community,semonte/intellij-community,asedunov/intellij-community,apixandru/intellij-community,amith01994/intellij-community,vladmm/intellij-community,izonder/intellij-community,da1z/intellij-community,kool79/intellij-community,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,jagguli/intellij-community,ryano144/intellij-community,MER-GROUP/intellij-community,blademainer/intellij-community,caot/intellij-community,orekyuu/intellij-community,ryano144/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,adedayo/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,idea4bsd/idea4bsd,alphafoobar/intellij-community,apixandru/intellij-community,xfournet/intellij-community,orekyuu/intellij-community,MER-GROUP/intellij-community,Distrotech/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,fengbaicanhe/intellij-community,fengbaicanhe/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,izonder/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,diorcety/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,orekyuu/intellij-community,ThiagoGarciaAlves/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,gnuhub/intellij-community,kool79/intellij-community,suncycheng/intellij-community,kool79/intellij-community,ol-loginov/intellij-community,ryano144/intellij-community,samthor/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,caot/intellij-community,alphafoobar/intellij-community,signed/intellij-community,holmes/intellij-community,kdwink/intellij-community,ol-loginov/intellij-community,clumsy/intellij-community,holmes/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,orekyuu/intellij-community,signed/intellij-community,semonte/intellij-community,caot/intellij-community,michaelgallacher/intellij-community,diorcety/intellij-community,caot/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,kdwink/intellij-community,gnuhub/intellij-community,hurricup/intellij-community,adedayo/intellij-community,slisson/intellij-community,ahb0327/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,ahb0327/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,Lekanich/intellij-community,petteyg/intellij-community,semonte/intellij-community,vladmm/intellij-community,ryano144/intellij-community,fengbaicanhe/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,FHannes/intellij-community,Distrotech/intellij-community,vladmm/intellij-community,retomerz/intellij-community,vladmm/intellij-community,ThiagoGarciaAlves/intellij-community,clumsy/intellij-community,dslomov/intellij-community,vladmm/intellij-community,ol-loginov/intellij-community,signed/intellij-community,ftomassetti/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,retomerz/intellij-community,slisson/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,MichaelNedzelsky/intellij-community,adedayo/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,da1z/intellij-community,Lekanich/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,muntasirsyed/intellij-community,vvv1559/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,clumsy/intellij-community,allotria/intellij-community,caot/intellij-community,slisson/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,asedunov/intellij-community,robovm/robovm-studio,michaelgallacher/intellij-community,TangHao1987/intellij-community,Lekanich/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,wreckJ/intellij-community,kool79/intellij-community,retomerz/intellij-community,ol-loginov/intellij-community,izonder/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,alphafoobar/intellij-community,TangHao1987/intellij-community,kool79/intellij-community,tmpgit/intellij-community,akosyakov/intellij-community,SerCeMan/intellij-community,michaelgallacher/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,salguarnieri/intellij-community,petteyg/intellij-community,vvv1559/intellij-community,petteyg/intellij-community,samthor/intellij-community,supersven/intellij-community,kool79/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,alphafoobar/intellij-community,mglukhikh/intellij-community,amith01994/intellij-community,petteyg/intellij-community,retomerz/intellij-community,gnuhub/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,Distrotech/intellij-community,retomerz/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,jagguli/intellij-community,tmpgit/intellij-community,clumsy/intellij-community,ivan-fedorov/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,pwoodworth/intellij-community,MER-GROUP/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,ryano144/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,caot/intellij-community,apixandru/intellij-community,blademainer/intellij-community,salguarnieri/intellij-community,clumsy/intellij-community,supersven/intellij-community,blademainer/intellij-community,alphafoobar/intellij-community,allotria/intellij-community,fnouama/intellij-community,ibinti/intellij-community,da1z/intellij-community,allotria/intellij-community,holmes/intellij-community,slisson/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,caot/intellij-community,TangHao1987/intellij-community,Distrotech/intellij-community,ryano144/intellij-community,ibinti/intellij-community,Distrotech/intellij-community,nicolargo/intellij-community,fnouama/intellij-community,mglukhikh/intellij-community,robovm/robovm-studio,jagguli/intellij-community,fitermay/intellij-community,nicolargo/intellij-community,SerCeMan/intellij-community,slisson/intellij-community,ahb0327/intellij-community,ivan-fedorov/intellij-community,diorcety/intellij-community,blademainer/intellij-community,asedunov/intellij-community,wreckJ/intellij-community,semonte/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,holmes/intellij-community,pwoodworth/intellij-community,fnouama/intellij-community,semonte/intellij-community,signed/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,izonder/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,ahb0327/intellij-community,pwoodworth/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,ahb0327/intellij-community,mglukhikh/intellij-community,ftomassetti/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,samthor/intellij-community,xfournet/intellij-community,orekyuu/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,caot/intellij-community,Lekanich/intellij-community,gnuhub/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,holmes/intellij-community,holmes/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,adedayo/intellij-community,Lekanich/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,fnouama/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,tmpgit/intellij-community,amith01994/intellij-community,kool79/intellij-community,kdwink/intellij-community,fnouama/intellij-community,robovm/robovm-studio,lucafavatella/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,MER-GROUP/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,blademainer/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,amith01994/intellij-community,caot/intellij-community,alphafoobar/intellij-community,vladmm/intellij-community,holmes/intellij-community,diorcety/intellij-community,suncycheng/intellij-community,Distrotech/intellij-community,SerCeMan/intellij-community,da1z/intellij-community,wreckJ/intellij-community,ryano144/intellij-community,ibinti/intellij-community,clumsy/intellij-community,slisson/intellij-community,clumsy/intellij-community,caot/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,da1z/intellij-community,gnuhub/intellij-community,petteyg/intellij-community,da1z/intellij-community,holmes/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,MichaelNedzelsky/intellij-community,ol-loginov/intellij-community,youdonghai/intellij-community,gnuhub/intellij-community,diorcety/intellij-community,ftomassetti/intellij-community,ahb0327/intellij-community,SerCeMan/intellij-community,kdwink/intellij-community,amith01994/intellij-community,apixandru/intellij-community,blademainer/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,muntasirsyed/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,fnouama/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,diorcety/intellij-community,wreckJ/intellij-community,Distrotech/intellij-community,slisson/intellij-community,samthor/intellij-community,wreckJ/intellij-community,kdwink/intellij-community,ibinti/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,ibinti/intellij-community,gnuhub/intellij-community,muntasirsyed/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,hurricup/intellij-community,ftomassetti/intellij-community,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,nicolargo/intellij-community,dslomov/intellij-community,petteyg/intellij-community,izonder/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,adedayo/intellij-community,blademainer/intellij-community,robovm/robovm-studio,izonder/intellij-community,da1z/intellij-community,slisson/intellij-community,blademainer/intellij-community,fnouama/intellij-community,robovm/robovm-studio,supersven/intellij-community,adedayo/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,diorcety/intellij-community,ryano144/intellij-community,xfournet/intellij-community,ryano144/intellij-community,diorcety/intellij-community,Lekanich/intellij-community,allotria/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,supersven/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,nicolargo/intellij-community,youdonghai/intellij-community,ahb0327/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,slisson/intellij-community,robovm/robovm-studio,fnouama/intellij-community,nicolargo/intellij-community,MichaelNedzelsky/intellij-community,FHannes/intellij-community,diorcety/intellij-community,kool79/intellij-community,suncycheng/intellij-community,blademainer/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,izonder/intellij-community,SerCeMan/intellij-community,akosyakov/intellij-community,kdwink/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,retomerz/intellij-community,fitermay/intellij-community,da1z/intellij-community,caot/intellij-community,jagguli/intellij-community,adedayo/intellij-community,da1z/intellij-community,SerCeMan/intellij-community,vladmm/intellij-community,muntasirsyed/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,holmes/intellij-community,supersven/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,SerCeMan/intellij-community,adedayo/intellij-community,ftomassetti/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,retomerz/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,salguarnieri/intellij-community,jagguli/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,ryano144/intellij-community,dslomov/intellij-community,Distrotech/intellij-community,supersven/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,gnuhub/intellij-community,TangHao1987/intellij-community,salguarnieri/intellij-community,ryano144/intellij-community,jagguli/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,samthor/intellij-community,fnouama/intellij-community,fitermay/intellij-community,TangHao1987/intellij-community,orekyuu/intellij-community,suncycheng/intellij-community,dslomov/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,ol-loginov/intellij-community,slisson/intellij-community,youdonghai/intellij-community,signed/intellij-community,kool79/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,FHannes/intellij-community,retomerz/intellij-community,tmpgit/intellij-community,ivan-fedorov/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,michaelgallacher/intellij-community,TangHao1987/intellij-community,fengbaicanhe/intellij-community,youdonghai/intellij-community,allotria/intellij-community,suncycheng/intellij-community,tmpgit/intellij-community,vladmm/intellij-community,holmes/intellij-community,vladmm/intellij-community,ivan-fedorov/intellij-community,SerCeMan/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,da1z/intellij-community,xfournet/intellij-community,dslomov/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,MichaelNedzelsky/intellij-community,semonte/intellij-community,signed/intellij-community,signed/intellij-community,ahb0327/intellij-community,orekyuu/intellij-community,idea4bsd/idea4bsd,ftomassetti/intellij-community,Lekanich/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,samthor/intellij-community,signed/intellij-community,robovm/robovm-studio,MichaelNedzelsky/intellij-community,da1z/intellij-community,amith01994/intellij-community,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,vladmm/intellij-community,diorcety/intellij-community,vladmm/intellij-community,ryano144/intellij-community,ibinti/intellij-community,FHannes/intellij-community,petteyg/intellij-community,ibinti/intellij-community,blademainer/intellij-community,kdwink/intellij-community,petteyg/intellij-community,blademainer/intellij-community,ol-loginov/intellij-community,jagguli/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,samthor/intellij-community,robovm/robovm-studio,asedunov/intellij-community,wreckJ/intellij-community,allotria/intellij-community,dslomov/intellij-community,ivan-fedorov/intellij-community,pwoodworth/intellij-community,ol-loginov/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,Distrotech/intellij-community,caot/intellij-community,semonte/intellij-community,alphafoobar/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,semonte/intellij-community,TangHao1987/intellij-community,samthor/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,allotria/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,ol-loginov/intellij-community,SerCeMan/intellij-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,jagguli/intellij-community,akosyakov/intellij-community,tmpgit/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,retomerz/intellij-community,Distrotech/intellij-community,nicolargo/intellij-community,alphafoobar/intellij-community,amith01994/intellij-community,hurricup/intellij-community,dslomov/intellij-community,robovm/robovm-studio,tmpgit/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,slisson/intellij-community,asedunov/intellij-community,supersven/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,FHannes/intellij-community,signed/intellij-community,dslomov/intellij-community,robovm/robovm-studio,vvv1559/intellij-community,idea4bsd/idea4bsd,akosyakov/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,pwoodworth/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,michaelgallacher/intellij-community,TangHao1987/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,allotria/intellij-community,amith01994/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,retomerz/intellij-community,fitermay/intellij-community,supersven/intellij-community
/* * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.util.lang; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.util.ShutDownTracker; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.SmartList; import com.intellij.util.containers.HashMap; import com.intellij.util.containers.Stack; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.Nullable; import sun.misc.Resource; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; import java.net.URISyntaxException; import java.net.URL; import java.util.*; public class ClassPath { private final Stack<URL> myUrls = new Stack<URL>(); private final ArrayList<Loader> myLoaders = new ArrayList<Loader>(); private final HashMap<URL,Loader> myLoadersMap = new HashMap<URL, Loader>(); private final ClasspathCache myCache = new ClasspathCache(); @NonNls private static final String FILE_PROTOCOL = "file"; private static final boolean myDebugTime = false; private static final boolean ourDumpOrder = "true".equals(System.getProperty("idea.dump.order")); // private static final boolean ourPreloadClasses = "true".equals(System.getProperty("idea.preload.classes")); private final boolean myCanLockJars; private final boolean myCanUseCache; private static final long NS_THRESHOLD = 10000000L; private static long total; private static int requests; private static PrintStream ourOrder; private static long ourOrderSize; private static final Set<String> ourOrderedUrls = new HashSet<String>(); private final boolean myAcceptUnescapedUrls; private final boolean myPreloadJarContents; private static synchronized void printOrder(Loader loader, String url, Resource resource) { if (!ourOrderedUrls.add(url)) return; String home = FileUtil.toSystemIndependentName(PathManager.getHomePath()); try { ourOrderSize += resource.getContentLength(); } catch (IOException e) { System.out.println(e); } if (ourOrder == null) { final File orderFile = new File(PathManager.getBinPath() + File.separator + "order.txt"); try { if (!FileUtil.ensureCanCreateFile(orderFile)) return; ourOrder = new PrintStream(new FileOutputStream(orderFile, true)); ShutDownTracker.getInstance().registerShutdownTask(new Runnable() { @Override public void run() { ourOrder.close(); System.out.println(ourOrderSize); } }); } catch (IOException e) { return; } } if (ourOrder != null) { String jarURL = FileUtil.toSystemIndependentName(loader.getBaseURL().getFile()); jarURL = StringUtil.trimStart(jarURL, "file:/"); if (jarURL.startsWith(home)) { jarURL = jarURL.replaceFirst(home, ""); jarURL = StringUtil.trimEnd(jarURL, "!/"); ourOrder.println(url + ":" + jarURL); } } } /** @deprecated use {@link #ClassPath(java.util.List, boolean, boolean, boolean, boolean)} (to remove in IDEA 14) */ public ClassPath(URL[] urls, boolean canLockJars, boolean canUseCache) { this(Arrays.asList(urls), canLockJars, canUseCache, false, true); } /** @deprecated use {@link #ClassPath(java.util.List, boolean, boolean, boolean, boolean)} (to remove in IDEA 14) */ public ClassPath(URL[] urls, boolean canLockJars, boolean canUseCache, boolean acceptUnescapedUrls, boolean preloadJarContents) { this(Arrays.asList(urls), canLockJars, canUseCache, acceptUnescapedUrls, preloadJarContents); } public ClassPath(List<URL> urls, boolean canLockJars, boolean canUseCache, boolean acceptUnescapedUrls, boolean preloadJarContents) { myCanLockJars = canLockJars; myCanUseCache = canUseCache; myAcceptUnescapedUrls = acceptUnescapedUrls; myPreloadJarContents = preloadJarContents; push(urls); } // Accessed by reflection from PluginClassLoader // TODO: do we need it? void addURL(URL url) { push(Collections.singletonList(url)); } private void push(List<URL> urls) { if (!urls.isEmpty()) { synchronized (myUrls) { for (int i = urls.size() - 1; i >= 0; i--) { myUrls.push(urls.get(i)); } } } } @Nullable public Resource getResource(String s, boolean flag) { final long started = myDebugTime ? System.nanoTime():0; try { int i; if (myCanUseCache) { Resource prevResource = myCache.iterateLoaders(s, flag ? checkedIterator:uncheckedIterator, s, this); if (prevResource != null) return prevResource; synchronized (myUrls) { if (myUrls.isEmpty()) return null; } i = myLoaders.size(); } else { i = 0; } for (Loader loader; (loader = getLoader(i)) != null; i++) { if (myCanUseCache) { if (!myCache.loaderHasName(s, loader)) continue; } Resource resource = loader.getResource(s, flag); if (resource != null) { return resource; } } return null; } finally { if (myDebugTime) reportTime(started, s); } } public Enumeration<URL> getResources(final String name, final boolean check) { return new MyEnumeration(name, check); } @Nullable private synchronized Loader getLoader(int i) { while (myLoaders.size() < i + 1) { boolean lastOne; URL url; synchronized (myUrls) { if (myUrls.empty()) { if (myCanUseCache) myCache.nameSymbolsLoaded(); return null; } url = myUrls.pop(); lastOne = myUrls.isEmpty(); } if (myLoadersMap.containsKey(url)) continue; Loader loader; try { loader = getLoader(url, myLoaders.size()); if (loader == null) continue; } catch (IOException ioexception) { continue; } myLoaders.add(loader); myLoadersMap.put(url, loader); if (lastOne && myCanUseCache) { myCache.nameSymbolsLoaded(); } } return myLoaders.get(i); } @Nullable private Loader getLoader(final URL url, int index) throws IOException { String s; if (myAcceptUnescapedUrls) { s = url.getFile(); } else { try { s = url.toURI().getSchemeSpecificPart(); } catch (URISyntaxException thisShouldNotHappen) { thisShouldNotHappen.printStackTrace(); s = url.getFile(); } } Loader loader = null; if (s != null && new File(s).isDirectory()) { if (FILE_PROTOCOL.equals(url.getProtocol())) { loader = new FileLoader(url, index); } } else { JarLoader jarLoader = new JarLoader(url, myCanLockJars, index); if (myPreloadJarContents) { jarLoader.preLoadClasses(); } loader = jarLoader; } if (loader != null && myCanUseCache) { try { loader.buildCache(myCache); } catch (Throwable e) { // TODO: log can't create loader } } return loader; } private class MyEnumeration implements Enumeration<URL> { private int myIndex = 0; private Resource myRes = null; private final String myName; private final boolean myCheck; private final List<Loader> myLoaders; public MyEnumeration(String name, boolean check) { myName = name; myCheck = check; List<Loader> loaders = null; if (myCanUseCache) { synchronized (myUrls) { if (myUrls.isEmpty()) { loaders = new SmartList<Loader>(); myCache.iterateLoaders(name, myLoaderCollector, loaders, this); if (!name.endsWith("/")) { myCache.iterateLoaders(name.concat("/"), myLoaderCollector, loaders, this); } } } } myLoaders = loaders; } private boolean next() { if (myRes != null) return true; long started = myDebugTime ? System.nanoTime() : 0; Loader loader; try { if (myLoaders != null) { while (myIndex < myLoaders.size()) { loader = myLoaders.get(myIndex++); if (!myCache.loaderHasName(myName, loader)) { myRes = null; continue; } myRes = loader.getResource(myName, myCheck); if (myRes != null) return true; } } else { while ((loader = getLoader(myIndex++)) != null) { if (!myCache.loaderHasName(myName, loader)) continue; myRes = loader.getResource(myName, myCheck); if (myRes != null) return true; } } } finally { if (myDebugTime) reportTime(started, myName); } return false; } @Override public boolean hasMoreElements() { return next(); } @Override public URL nextElement() { if (!next()) { throw new NoSuchElementException(); } else { Resource resource = myRes; myRes = null; return resource.getURL(); } } } private void reportTime(long started, String msg) { long doneFor = System.nanoTime() - started; total += doneFor; ++requests; if (doneFor > NS_THRESHOLD) { System.out.println((doneFor/1000000) + " ms for " +msg); } if (requests % 1000 == 0) { System.out.println(toString() + ", requests:" + requests + ", time:" + (total / 1000000) + "ms"); } } private static class ResourceStringLoaderIterator extends ClasspathCache.LoaderIterator<Resource, String, ClassPath> { private final boolean myFlag; private ResourceStringLoaderIterator(boolean flag) { myFlag = flag; } @Override Resource process(Loader loader, String s, ClassPath classPath) { if (!classPath.myCache.loaderHasName(s, loader)) return null; final Resource resource = loader.getResource(s, myFlag); if (resource != null) { if (ourDumpOrder) { printOrder(loader, s, resource); } return resource; } return null; } } private static final ResourceStringLoaderIterator checkedIterator = new ResourceStringLoaderIterator(true); private static final ResourceStringLoaderIterator uncheckedIterator = new ResourceStringLoaderIterator(false); private static final LoaderCollector myLoaderCollector = new LoaderCollector(); private static class LoaderCollector extends ClasspathCache.LoaderIterator<Object, List<Loader>, Object> { @Override Object process(Loader loader, List<Loader> parameter, Object parameter2) { parameter.add(loader); return null; } } }
platform/util/src/com/intellij/util/lang/ClassPath.java
/* * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.util.lang; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.util.ShutDownTracker; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.SmartList; import com.intellij.util.containers.HashMap; import com.intellij.util.containers.Stack; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.Nullable; import sun.misc.Resource; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; import java.net.URISyntaxException; import java.net.URL; import java.util.*; public class ClassPath { private final Stack<URL> myUrls = new Stack<URL>(); private final ArrayList<Loader> myLoaders = new ArrayList<Loader>(); private final HashMap<URL,Loader> myLoadersMap = new HashMap<URL, Loader>(); private final ClasspathCache myCache = new ClasspathCache(); @NonNls private static final String FILE_PROTOCOL = "file"; private static final boolean myDebugTime = false; private static final boolean ourDumpOrder = "true".equals(System.getProperty("idea.dump.order")); // private static final boolean ourPreloadClasses = "true".equals(System.getProperty("idea.preload.classes")); private final boolean myCanLockJars; private final boolean myCanUseCache; private static final long NS_THRESHOLD = 10000000L; private static long total; private static int requests; private static PrintStream ourOrder; private static long ourOrderSize; private static final Set<String> ourOrderedUrls = new HashSet<String>(); private static final String HOME = FileUtil.toSystemIndependentName(PathManager.getHomePath()); private final boolean myAcceptUnescapedUrls; private final boolean myPreloadJarContents; private static synchronized void printOrder(Loader loader, String url, Resource resource) { if (!ourOrderedUrls.add(url)) return; try { ourOrderSize += resource.getContentLength(); } catch (IOException e) { System.out.println(e); } if (ourOrder == null) { final File orderFile = new File(PathManager.getBinPath() + File.separator + "order.txt"); try { if (!FileUtil.ensureCanCreateFile(orderFile)) return; ourOrder = new PrintStream(new FileOutputStream(orderFile, true)); ShutDownTracker.getInstance().registerShutdownTask(new Runnable() { @Override public void run() { ourOrder.close(); System.out.println(ourOrderSize); } }); } catch (IOException e) { return; } } if (ourOrder != null) { String jarURL = FileUtil.toSystemIndependentName(loader.getBaseURL().getFile()); jarURL = StringUtil.trimStart(jarURL, "file:/"); if (jarURL.startsWith(HOME)) { jarURL = jarURL.replaceFirst(HOME, ""); jarURL = StringUtil.trimEnd(jarURL, "!/"); ourOrder.println(url + ":" + jarURL); } } } /** @deprecated use {@link #ClassPath(java.util.List, boolean, boolean, boolean, boolean)} (to remove in IDEA 14) */ public ClassPath(URL[] urls, boolean canLockJars, boolean canUseCache) { this(Arrays.asList(urls), canLockJars, canUseCache, false, true); } /** @deprecated use {@link #ClassPath(java.util.List, boolean, boolean, boolean, boolean)} (to remove in IDEA 14) */ public ClassPath(URL[] urls, boolean canLockJars, boolean canUseCache, boolean acceptUnescapedUrls, boolean preloadJarContents) { this(Arrays.asList(urls), canLockJars, canUseCache, acceptUnescapedUrls, preloadJarContents); } public ClassPath(List<URL> urls, boolean canLockJars, boolean canUseCache, boolean acceptUnescapedUrls, boolean preloadJarContents) { myCanLockJars = canLockJars; myCanUseCache = canUseCache; myAcceptUnescapedUrls = acceptUnescapedUrls; myPreloadJarContents = preloadJarContents; push(urls); } // Accessed by reflection from PluginClassLoader // TODO: do we need it? void addURL(URL url) { push(Collections.singletonList(url)); } private void push(List<URL> urls) { if (!urls.isEmpty()) { synchronized (myUrls) { for (int i = urls.size() - 1; i >= 0; i--) { myUrls.push(urls.get(i)); } } } } @Nullable public Resource getResource(String s, boolean flag) { final long started = myDebugTime ? System.nanoTime():0; try { int i; if (myCanUseCache) { Resource prevResource = myCache.iterateLoaders(s, flag ? checkedIterator:uncheckedIterator, s, this); if (prevResource != null) return prevResource; synchronized (myUrls) { if (myUrls.isEmpty()) return null; } i = myLoaders.size(); } else { i = 0; } for (Loader loader; (loader = getLoader(i)) != null; i++) { if (myCanUseCache) { if (!myCache.loaderHasName(s, loader)) continue; } Resource resource = loader.getResource(s, flag); if (resource != null) { return resource; } } return null; } finally { if (myDebugTime) reportTime(started, s); } } public Enumeration<URL> getResources(final String name, final boolean check) { return new MyEnumeration(name, check); } @Nullable private synchronized Loader getLoader(int i) { while (myLoaders.size() < i + 1) { boolean lastOne; URL url; synchronized (myUrls) { if (myUrls.empty()) { if (myCanUseCache) myCache.nameSymbolsLoaded(); return null; } url = myUrls.pop(); lastOne = myUrls.isEmpty(); } if (myLoadersMap.containsKey(url)) continue; Loader loader; try { loader = getLoader(url, myLoaders.size()); if (loader == null) continue; } catch (IOException ioexception) { continue; } myLoaders.add(loader); myLoadersMap.put(url, loader); if (lastOne && myCanUseCache) { myCache.nameSymbolsLoaded(); } } return myLoaders.get(i); } @Nullable private Loader getLoader(final URL url, int index) throws IOException { String s; if (myAcceptUnescapedUrls) { s = url.getFile(); } else { try { s = url.toURI().getSchemeSpecificPart(); } catch (URISyntaxException thisShouldNotHappen) { thisShouldNotHappen.printStackTrace(); s = url.getFile(); } } Loader loader = null; if (s != null && new File(s).isDirectory()) { if (FILE_PROTOCOL.equals(url.getProtocol())) { loader = new FileLoader(url, index); } } else { JarLoader jarLoader = new JarLoader(url, myCanLockJars, index); if (myPreloadJarContents) { jarLoader.preLoadClasses(); } loader = jarLoader; } if (loader != null && myCanUseCache) { try { loader.buildCache(myCache); } catch (Throwable e) { // TODO: log can't create loader } } return loader; } private class MyEnumeration implements Enumeration<URL> { private int myIndex = 0; private Resource myRes = null; private final String myName; private final boolean myCheck; private final List<Loader> myLoaders; public MyEnumeration(String name, boolean check) { myName = name; myCheck = check; List<Loader> loaders = null; if (myCanUseCache) { synchronized (myUrls) { if (myUrls.isEmpty()) { loaders = new SmartList<Loader>(); myCache.iterateLoaders(name, myLoaderCollector, loaders, this); if (!name.endsWith("/")) { myCache.iterateLoaders(name.concat("/"), myLoaderCollector, loaders, this); } } } } myLoaders = loaders; } private boolean next() { if (myRes != null) return true; long started = myDebugTime ? System.nanoTime() : 0; Loader loader; try { if (myLoaders != null) { while (myIndex < myLoaders.size()) { loader = myLoaders.get(myIndex++); if (!myCache.loaderHasName(myName, loader)) { myRes = null; continue; } myRes = loader.getResource(myName, myCheck); if (myRes != null) return true; } } else { while ((loader = getLoader(myIndex++)) != null) { if (!myCache.loaderHasName(myName, loader)) continue; myRes = loader.getResource(myName, myCheck); if (myRes != null) return true; } } } finally { if (myDebugTime) reportTime(started, myName); } return false; } @Override public boolean hasMoreElements() { return next(); } @Override public URL nextElement() { if (!next()) { throw new NoSuchElementException(); } else { Resource resource = myRes; myRes = null; return resource.getURL(); } } } private void reportTime(long started, String msg) { long doneFor = System.nanoTime() - started; total += doneFor; ++requests; if (doneFor > NS_THRESHOLD) { System.out.println((doneFor/1000000) + " ms for " +msg); } if (requests % 1000 == 0) { System.out.println(toString() + ", requests:" + requests + ", time:" + (total / 1000000) + "ms"); } } private static class ResourceStringLoaderIterator extends ClasspathCache.LoaderIterator<Resource, String, ClassPath> { private final boolean myFlag; private ResourceStringLoaderIterator(boolean flag) { myFlag = flag; } @Override Resource process(Loader loader, String s, ClassPath classPath) { if (!classPath.myCache.loaderHasName(s, loader)) return null; final Resource resource = loader.getResource(s, myFlag); if (resource != null) { if (ourDumpOrder) { printOrder(loader, s, resource); } return resource; } return null; } } private static final ResourceStringLoaderIterator checkedIterator = new ResourceStringLoaderIterator(true); private static final ResourceStringLoaderIterator uncheckedIterator = new ResourceStringLoaderIterator(false); private static final LoaderCollector myLoaderCollector = new LoaderCollector(); private static class LoaderCollector extends ClasspathCache.LoaderIterator<Object, List<Loader>, Object> { @Override Object process(Loader loader, List<Loader> parameter, Object parameter2) { parameter.add(loader); return null; } } }
fix database tests build?
platform/util/src/com/intellij/util/lang/ClassPath.java
fix database tests build?
Java
apache-2.0
970da5874acbcd09e6b39d3ddd3abe5bec82f75e
0
fitermay/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,petteyg/intellij-community,amith01994/intellij-community,apixandru/intellij-community,semonte/intellij-community,dslomov/intellij-community,alphafoobar/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,amith01994/intellij-community,robovm/robovm-studio,caot/intellij-community,dslomov/intellij-community,pwoodworth/intellij-community,samthor/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,diorcety/intellij-community,asedunov/intellij-community,blademainer/intellij-community,SerCeMan/intellij-community,salguarnieri/intellij-community,nicolargo/intellij-community,TangHao1987/intellij-community,MER-GROUP/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,ahb0327/intellij-community,petteyg/intellij-community,fitermay/intellij-community,retomerz/intellij-community,robovm/robovm-studio,fengbaicanhe/intellij-community,nicolargo/intellij-community,supersven/intellij-community,allotria/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,xfournet/intellij-community,caot/intellij-community,adedayo/intellij-community,hurricup/intellij-community,clumsy/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,vladmm/intellij-community,retomerz/intellij-community,fengbaicanhe/intellij-community,retomerz/intellij-community,izonder/intellij-community,robovm/robovm-studio,kdwink/intellij-community,allotria/intellij-community,Lekanich/intellij-community,ibinti/intellij-community,gnuhub/intellij-community,diorcety/intellij-community,slisson/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,suncycheng/intellij-community,orekyuu/intellij-community,MER-GROUP/intellij-community,samthor/intellij-community,apixandru/intellij-community,diorcety/intellij-community,samthor/intellij-community,retomerz/intellij-community,alphafoobar/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,clumsy/intellij-community,kdwink/intellij-community,gnuhub/intellij-community,signed/intellij-community,holmes/intellij-community,ibinti/intellij-community,Distrotech/intellij-community,wreckJ/intellij-community,amith01994/intellij-community,ibinti/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,wreckJ/intellij-community,diorcety/intellij-community,xfournet/intellij-community,izonder/intellij-community,jagguli/intellij-community,gnuhub/intellij-community,petteyg/intellij-community,adedayo/intellij-community,diorcety/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,amith01994/intellij-community,izonder/intellij-community,akosyakov/intellij-community,MER-GROUP/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,samthor/intellij-community,ahb0327/intellij-community,da1z/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,slisson/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,xfournet/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,fnouama/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,ryano144/intellij-community,tmpgit/intellij-community,ol-loginov/intellij-community,MER-GROUP/intellij-community,akosyakov/intellij-community,SerCeMan/intellij-community,orekyuu/intellij-community,da1z/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,muntasirsyed/intellij-community,amith01994/intellij-community,blademainer/intellij-community,diorcety/intellij-community,samthor/intellij-community,ibinti/intellij-community,ftomassetti/intellij-community,Distrotech/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,adedayo/intellij-community,orekyuu/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,wreckJ/intellij-community,adedayo/intellij-community,ryano144/intellij-community,ibinti/intellij-community,caot/intellij-community,Lekanich/intellij-community,jagguli/intellij-community,asedunov/intellij-community,izonder/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,vladmm/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,jagguli/intellij-community,kool79/intellij-community,supersven/intellij-community,akosyakov/intellij-community,fnouama/intellij-community,semonte/intellij-community,ol-loginov/intellij-community,orekyuu/intellij-community,SerCeMan/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,Distrotech/intellij-community,alphafoobar/intellij-community,robovm/robovm-studio,Lekanich/intellij-community,da1z/intellij-community,petteyg/intellij-community,robovm/robovm-studio,da1z/intellij-community,dslomov/intellij-community,akosyakov/intellij-community,signed/intellij-community,jagguli/intellij-community,TangHao1987/intellij-community,clumsy/intellij-community,SerCeMan/intellij-community,akosyakov/intellij-community,fnouama/intellij-community,ryano144/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,ThiagoGarciaAlves/intellij-community,supersven/intellij-community,signed/intellij-community,alphafoobar/intellij-community,kdwink/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,ol-loginov/intellij-community,muntasirsyed/intellij-community,slisson/intellij-community,blademainer/intellij-community,salguarnieri/intellij-community,MER-GROUP/intellij-community,ryano144/intellij-community,blademainer/intellij-community,ivan-fedorov/intellij-community,ivan-fedorov/intellij-community,tmpgit/intellij-community,kdwink/intellij-community,vladmm/intellij-community,dslomov/intellij-community,youdonghai/intellij-community,kdwink/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,kool79/intellij-community,caot/intellij-community,vladmm/intellij-community,kool79/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,wreckJ/intellij-community,izonder/intellij-community,fnouama/intellij-community,vladmm/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,ftomassetti/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,diorcety/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,alphafoobar/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,nicolargo/intellij-community,clumsy/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,Lekanich/intellij-community,ivan-fedorov/intellij-community,retomerz/intellij-community,blademainer/intellij-community,clumsy/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,holmes/intellij-community,dslomov/intellij-community,gnuhub/intellij-community,caot/intellij-community,holmes/intellij-community,blademainer/intellij-community,mglukhikh/intellij-community,Lekanich/intellij-community,hurricup/intellij-community,izonder/intellij-community,caot/intellij-community,ibinti/intellij-community,TangHao1987/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,petteyg/intellij-community,jagguli/intellij-community,fitermay/intellij-community,orekyuu/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,jagguli/intellij-community,kool79/intellij-community,MER-GROUP/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,jagguli/intellij-community,FHannes/intellij-community,Lekanich/intellij-community,semonte/intellij-community,gnuhub/intellij-community,fengbaicanhe/intellij-community,ahb0327/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,ol-loginov/intellij-community,adedayo/intellij-community,da1z/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,petteyg/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,gnuhub/intellij-community,kool79/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,amith01994/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,ol-loginov/intellij-community,alphafoobar/intellij-community,TangHao1987/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,mglukhikh/intellij-community,caot/intellij-community,clumsy/intellij-community,semonte/intellij-community,youdonghai/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,nicolargo/intellij-community,slisson/intellij-community,robovm/robovm-studio,petteyg/intellij-community,da1z/intellij-community,suncycheng/intellij-community,tmpgit/intellij-community,fengbaicanhe/intellij-community,ryano144/intellij-community,da1z/intellij-community,kool79/intellij-community,amith01994/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,fengbaicanhe/intellij-community,allotria/intellij-community,amith01994/intellij-community,retomerz/intellij-community,muntasirsyed/intellij-community,akosyakov/intellij-community,hurricup/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,FHannes/intellij-community,da1z/intellij-community,xfournet/intellij-community,petteyg/intellij-community,clumsy/intellij-community,adedayo/intellij-community,fitermay/intellij-community,semonte/intellij-community,slisson/intellij-community,holmes/intellij-community,tmpgit/intellij-community,jagguli/intellij-community,apixandru/intellij-community,asedunov/intellij-community,MichaelNedzelsky/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,ibinti/intellij-community,amith01994/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,gnuhub/intellij-community,jagguli/intellij-community,fitermay/intellij-community,robovm/robovm-studio,salguarnieri/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,xfournet/intellij-community,ryano144/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,ivan-fedorov/intellij-community,holmes/intellij-community,ftomassetti/intellij-community,gnuhub/intellij-community,jagguli/intellij-community,apixandru/intellij-community,wreckJ/intellij-community,caot/intellij-community,ryano144/intellij-community,apixandru/intellij-community,kool79/intellij-community,fitermay/intellij-community,vladmm/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,amith01994/intellij-community,TangHao1987/intellij-community,vladmm/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,michaelgallacher/intellij-community,TangHao1987/intellij-community,Distrotech/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,caot/intellij-community,allotria/intellij-community,izonder/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,SerCeMan/intellij-community,pwoodworth/intellij-community,semonte/intellij-community,wreckJ/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,blademainer/intellij-community,tmpgit/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,MichaelNedzelsky/intellij-community,ahb0327/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,SerCeMan/intellij-community,lucafavatella/intellij-community,TangHao1987/intellij-community,slisson/intellij-community,supersven/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,vladmm/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,tmpgit/intellij-community,kdwink/intellij-community,supersven/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,kdwink/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,ahb0327/intellij-community,holmes/intellij-community,Distrotech/intellij-community,FHannes/intellij-community,asedunov/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,petteyg/intellij-community,kool79/intellij-community,da1z/intellij-community,jagguli/intellij-community,ryano144/intellij-community,vladmm/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,semonte/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,izonder/intellij-community,akosyakov/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,diorcety/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,blademainer/intellij-community,dslomov/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,ryano144/intellij-community,caot/intellij-community,alphafoobar/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,hurricup/intellij-community,ol-loginov/intellij-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,dslomov/intellij-community,dslomov/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,alphafoobar/intellij-community,TangHao1987/intellij-community,slisson/intellij-community,retomerz/intellij-community,samthor/intellij-community,supersven/intellij-community,fnouama/intellij-community,Lekanich/intellij-community,ol-loginov/intellij-community,TangHao1987/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,signed/intellij-community,akosyakov/intellij-community,allotria/intellij-community,alphafoobar/intellij-community,ryano144/intellij-community,SerCeMan/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,suncycheng/intellij-community,diorcety/intellij-community,diorcety/intellij-community,FHannes/intellij-community,samthor/intellij-community,Distrotech/intellij-community,blademainer/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,semonte/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,signed/intellij-community,ftomassetti/intellij-community,fnouama/intellij-community,ol-loginov/intellij-community,pwoodworth/intellij-community,signed/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,jagguli/intellij-community,asedunov/intellij-community,kool79/intellij-community,ftomassetti/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,adedayo/intellij-community,supersven/intellij-community,fitermay/intellij-community,signed/intellij-community,diorcety/intellij-community,FHannes/intellij-community,dslomov/intellij-community,nicolargo/intellij-community,supersven/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,caot/intellij-community,clumsy/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,tmpgit/intellij-community,ivan-fedorov/intellij-community,vladmm/intellij-community,samthor/intellij-community,signed/intellij-community,caot/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,wreckJ/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,vladmm/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,idea4bsd/idea4bsd,ftomassetti/intellij-community,alphafoobar/intellij-community,allotria/intellij-community,adedayo/intellij-community,robovm/robovm-studio,Lekanich/intellij-community,holmes/intellij-community,kdwink/intellij-community,ibinti/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,ahb0327/intellij-community,diorcety/intellij-community,Distrotech/intellij-community,FHannes/intellij-community,robovm/robovm-studio,salguarnieri/intellij-community,fnouama/intellij-community,semonte/intellij-community,supersven/intellij-community,da1z/intellij-community,tmpgit/intellij-community,kool79/intellij-community,ahb0327/intellij-community,kool79/intellij-community,muntasirsyed/intellij-community,nicolargo/intellij-community,amith01994/intellij-community,xfournet/intellij-community,alphafoobar/intellij-community,ftomassetti/intellij-community,kool79/intellij-community,MichaelNedzelsky/intellij-community,adedayo/intellij-community,SerCeMan/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,MER-GROUP/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,ahb0327/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,idea4bsd/idea4bsd,holmes/intellij-community,muntasirsyed/intellij-community,adedayo/intellij-community,robovm/robovm-studio,FHannes/intellij-community,xfournet/intellij-community,adedayo/intellij-community,semonte/intellij-community,fitermay/intellij-community,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,dslomov/intellij-community,holmes/intellij-community,samthor/intellij-community,petteyg/intellij-community,signed/intellij-community,signed/intellij-community,semonte/intellij-community,youdonghai/intellij-community,izonder/intellij-community,allotria/intellij-community,holmes/intellij-community,slisson/intellij-community,petteyg/intellij-community,retomerz/intellij-community,clumsy/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,samthor/intellij-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,nicolargo/intellij-community,izonder/intellij-community,allotria/intellij-community,retomerz/intellij-community,petteyg/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,SerCeMan/intellij-community,ryano144/intellij-community,lucafavatella/intellij-community,signed/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,pwoodworth/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community
/* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.psi.util; import com.intellij.psi.*; import com.intellij.util.Processor; import gnu.trove.THashSet; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.LinkedHashSet; import java.util.Set; public class InheritanceUtil { private InheritanceUtil() { } /** * @param aClass a class to check. * @param baseClass supposed base class. * @param checkDeep true to check deeper than aClass.super (see {@linkplain PsiClass#isInheritor(com.intellij.psi.PsiClass, boolean)}). * @return true if aClass is the baseClass or baseClass inheritor */ public static boolean isInheritorOrSelf(@Nullable PsiClass aClass, @Nullable PsiClass baseClass, boolean checkDeep) { if (aClass == null || baseClass == null) return false; PsiManager manager = aClass.getManager(); return manager.areElementsEquivalent(baseClass, aClass) || aClass.isInheritor(baseClass, checkDeep); } public static boolean processSupers(@Nullable PsiClass aClass, boolean includeSelf, @NotNull Processor<PsiClass> superProcessor) { if (aClass == null) return true; if (includeSelf && !superProcessor.process(aClass)) return false; return processSupers(aClass, superProcessor, new THashSet<PsiClass>()); } private static boolean processSupers(@NotNull PsiClass aClass, @NotNull Processor<PsiClass> superProcessor, @NotNull Set<PsiClass> visited) { if (!visited.add(aClass)) return true; for (final PsiClass intf : aClass.getInterfaces()) { if (!superProcessor.process(intf) || !processSupers(intf, superProcessor, visited)) return false; } final PsiClass superClass = aClass.getSuperClass(); if (superClass != null) { if (!superProcessor.process(superClass) || !processSupers(superClass, superProcessor, visited)) return false; } return true; } @Contract("null, _ -> false") public static boolean isInheritor(@Nullable PsiType type, @NotNull @NonNls final String baseClassName) { if (type instanceof PsiClassType) { return isInheritor(((PsiClassType)type).resolve(), baseClassName); } return false; } @Contract("null, _ -> false") public static boolean isInheritor(@Nullable PsiClass psiClass, @NotNull final String baseClassName) { return isInheritor(psiClass, false, baseClassName); } @Contract("null, _, _ -> false") public static boolean isInheritor(@Nullable PsiClass psiClass, final boolean strict, @NotNull final String baseClassName) { if (psiClass == null) { return false; } final PsiClass base = JavaPsiFacade.getInstance(psiClass.getProject()).findClass(baseClassName, psiClass.getResolveScope()); if (base == null) { return false; } return strict ? psiClass.isInheritor(base, true) : isInheritorOrSelf(psiClass, base, true); } /** * Gets all superclasses. Classes are added to result in DFS order * @param aClass * @param results * @param includeNonProject */ public static void getSuperClasses(@NotNull PsiClass aClass, @NotNull Set<PsiClass> results, boolean includeNonProject) { getSuperClassesOfList(aClass.getSuperTypes(), results, includeNonProject, new THashSet<PsiClass>(), aClass.getManager()); } public static LinkedHashSet<PsiClass> getSuperClasses(@NotNull PsiClass aClass) { LinkedHashSet<PsiClass> result = new LinkedHashSet<PsiClass>(); getSuperClasses(aClass, result, true); return result; } private static void getSuperClassesOfList(@NotNull PsiClassType[] types, @NotNull Set<PsiClass> results, boolean includeNonProject, @NotNull Set<PsiClass> visited, @NotNull PsiManager manager) { for (PsiClassType type : types) { PsiClass resolved = type.resolve(); if (resolved != null && visited.add(resolved)) { if (includeNonProject || manager.isInProject(resolved)) { results.add(resolved); } getSuperClassesOfList(resolved.getSuperTypes(), results, includeNonProject, visited, manager); } } } public static boolean hasEnclosingInstanceInScope(PsiClass aClass, PsiElement scope, final boolean isSuperClassAccepted, boolean isTypeParamsAccepted) { PsiManager manager = aClass.getManager(); PsiElement place = scope; while (place != null && place != aClass && !(place instanceof PsiFile)) { if (place instanceof PsiClass) { if (isSuperClassAccepted) { if (isInheritorOrSelf((PsiClass)place, aClass, true)) return true; } else { if (manager.areElementsEquivalent(place, aClass)) return true; } if (isTypeParamsAccepted && place instanceof PsiTypeParameter) { return true; } } if (place instanceof PsiModifierListOwner) { final PsiModifierList modifierList = ((PsiModifierListOwner)place).getModifierList(); if (modifierList != null && modifierList.hasModifierProperty(PsiModifier.STATIC)) { return false; } } place = place.getParent(); } return place == aClass; } }
java/java-psi-api/src/com/intellij/psi/util/InheritanceUtil.java
/* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.psi.util; import com.intellij.psi.*; import com.intellij.util.Processor; import gnu.trove.THashSet; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.LinkedHashSet; import java.util.Set; public class InheritanceUtil { private InheritanceUtil() { } /** * @param aClass a class to check. * @param baseClass supposed base class. * @param checkDeep true to check deeper than aClass.super (see {@linkplain PsiClass#isInheritor(com.intellij.psi.PsiClass, boolean)}). * @return true if aClass is the baseClass or baseClass inheritor */ public static boolean isInheritorOrSelf(@Nullable PsiClass aClass, @Nullable PsiClass baseClass, boolean checkDeep) { if (aClass == null || baseClass == null) return false; PsiManager manager = aClass.getManager(); return manager.areElementsEquivalent(baseClass, aClass) || aClass.isInheritor(baseClass, checkDeep); } public static boolean processSupers(@Nullable PsiClass aClass, boolean includeSelf, @NotNull Processor<PsiClass> superProcessor) { if (aClass == null) return true; if (includeSelf && !superProcessor.process(aClass)) return false; return processSupers(aClass, superProcessor, new THashSet<PsiClass>()); } private static boolean processSupers(@NotNull PsiClass aClass, @NotNull Processor<PsiClass> superProcessor, @NotNull Set<PsiClass> visited) { if (!visited.add(aClass)) return true; for (final PsiClass intf : aClass.getInterfaces()) { if (!superProcessor.process(intf) || !processSupers(intf, superProcessor, visited)) return false; } final PsiClass superClass = aClass.getSuperClass(); if (superClass != null) { if (!superProcessor.process(superClass) || !processSupers(superClass, superProcessor, visited)) return false; } return true; } @Contract("null, _ -> fail") public static boolean isInheritor(@Nullable PsiType type, @NotNull @NonNls final String baseClassName) { if (type instanceof PsiClassType) { return isInheritor(((PsiClassType)type).resolve(), baseClassName); } return false; } @Contract("null, _ -> fail") public static boolean isInheritor(@Nullable PsiClass psiClass, @NotNull final String baseClassName) { return isInheritor(psiClass, false, baseClassName); } @Contract("null, _, _ -> fail") public static boolean isInheritor(@Nullable PsiClass psiClass, final boolean strict, @NotNull final String baseClassName) { if (psiClass == null) { return false; } final PsiClass base = JavaPsiFacade.getInstance(psiClass.getProject()).findClass(baseClassName, psiClass.getResolveScope()); if (base == null) { return false; } return strict ? psiClass.isInheritor(base, true) : isInheritorOrSelf(psiClass, base, true); } /** * Gets all superclasses. Classes are added to result in DFS order * @param aClass * @param results * @param includeNonProject */ public static void getSuperClasses(@NotNull PsiClass aClass, @NotNull Set<PsiClass> results, boolean includeNonProject) { getSuperClassesOfList(aClass.getSuperTypes(), results, includeNonProject, new THashSet<PsiClass>(), aClass.getManager()); } public static LinkedHashSet<PsiClass> getSuperClasses(@NotNull PsiClass aClass) { LinkedHashSet<PsiClass> result = new LinkedHashSet<PsiClass>(); getSuperClasses(aClass, result, true); return result; } private static void getSuperClassesOfList(@NotNull PsiClassType[] types, @NotNull Set<PsiClass> results, boolean includeNonProject, @NotNull Set<PsiClass> visited, @NotNull PsiManager manager) { for (PsiClassType type : types) { PsiClass resolved = type.resolve(); if (resolved != null && visited.add(resolved)) { if (includeNonProject || manager.isInProject(resolved)) { results.add(resolved); } getSuperClassesOfList(resolved.getSuperTypes(), results, includeNonProject, visited, manager); } } } public static boolean hasEnclosingInstanceInScope(PsiClass aClass, PsiElement scope, final boolean isSuperClassAccepted, boolean isTypeParamsAccepted) { PsiManager manager = aClass.getManager(); PsiElement place = scope; while (place != null && place != aClass && !(place instanceof PsiFile)) { if (place instanceof PsiClass) { if (isSuperClassAccepted) { if (isInheritorOrSelf((PsiClass)place, aClass, true)) return true; } else { if (manager.areElementsEquivalent(place, aClass)) return true; } if (isTypeParamsAccepted && place instanceof PsiTypeParameter) { return true; } } if (place instanceof PsiModifierListOwner) { final PsiModifierList modifierList = ((PsiModifierListOwner)place).getModifierList(); if (modifierList != null && modifierList.hasModifierProperty(PsiModifier.STATIC)) { return false; } } place = place.getParent(); } return place == aClass; } }
fix contracts
java/java-psi-api/src/com/intellij/psi/util/InheritanceUtil.java
fix contracts
Java
apache-2.0
35755e9903123a57c8b6d81ef33667436685dfdc
0
ivan-fedorov/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,diorcety/intellij-community,slisson/intellij-community,amith01994/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,MichaelNedzelsky/intellij-community,supersven/intellij-community,gnuhub/intellij-community,kool79/intellij-community,MichaelNedzelsky/intellij-community,dslomov/intellij-community,TangHao1987/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,xfournet/intellij-community,apixandru/intellij-community,apixandru/intellij-community,TangHao1987/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,samthor/intellij-community,samthor/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,tmpgit/intellij-community,tmpgit/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,signed/intellij-community,robovm/robovm-studio,mglukhikh/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,kdwink/intellij-community,supersven/intellij-community,apixandru/intellij-community,adedayo/intellij-community,semonte/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,supersven/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,asedunov/intellij-community,ibinti/intellij-community,dslomov/intellij-community,ftomassetti/intellij-community,MER-GROUP/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,izonder/intellij-community,Distrotech/intellij-community,ThiagoGarciaAlves/intellij-community,fengbaicanhe/intellij-community,ahb0327/intellij-community,clumsy/intellij-community,holmes/intellij-community,salguarnieri/intellij-community,ThiagoGarciaAlves/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,muntasirsyed/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,samthor/intellij-community,kool79/intellij-community,akosyakov/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,kdwink/intellij-community,xfournet/intellij-community,kool79/intellij-community,blademainer/intellij-community,alphafoobar/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,ahb0327/intellij-community,semonte/intellij-community,asedunov/intellij-community,fnouama/intellij-community,dslomov/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,SerCeMan/intellij-community,salguarnieri/intellij-community,fnouama/intellij-community,gnuhub/intellij-community,nicolargo/intellij-community,signed/intellij-community,fitermay/intellij-community,fnouama/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,kdwink/intellij-community,robovm/robovm-studio,da1z/intellij-community,ftomassetti/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,kool79/intellij-community,jagguli/intellij-community,michaelgallacher/intellij-community,fnouama/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,semonte/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,fnouama/intellij-community,izonder/intellij-community,retomerz/intellij-community,allotria/intellij-community,fnouama/intellij-community,diorcety/intellij-community,ryano144/intellij-community,ol-loginov/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,TangHao1987/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,wreckJ/intellij-community,gnuhub/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,asedunov/intellij-community,jagguli/intellij-community,ftomassetti/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,ftomassetti/intellij-community,amith01994/intellij-community,izonder/intellij-community,amith01994/intellij-community,semonte/intellij-community,gnuhub/intellij-community,orekyuu/intellij-community,wreckJ/intellij-community,asedunov/intellij-community,semonte/intellij-community,clumsy/intellij-community,caot/intellij-community,signed/intellij-community,SerCeMan/intellij-community,mglukhikh/intellij-community,slisson/intellij-community,suncycheng/intellij-community,clumsy/intellij-community,MER-GROUP/intellij-community,blademainer/intellij-community,suncycheng/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,samthor/intellij-community,lucafavatella/intellij-community,robovm/robovm-studio,holmes/intellij-community,TangHao1987/intellij-community,ryano144/intellij-community,izonder/intellij-community,caot/intellij-community,holmes/intellij-community,supersven/intellij-community,gnuhub/intellij-community,petteyg/intellij-community,ryano144/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,da1z/intellij-community,kool79/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,Distrotech/intellij-community,jagguli/intellij-community,TangHao1987/intellij-community,semonte/intellij-community,blademainer/intellij-community,asedunov/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,amith01994/intellij-community,MER-GROUP/intellij-community,samthor/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,vladmm/intellij-community,hurricup/intellij-community,apixandru/intellij-community,jagguli/intellij-community,kdwink/intellij-community,da1z/intellij-community,dslomov/intellij-community,caot/intellij-community,vladmm/intellij-community,vladmm/intellij-community,samthor/intellij-community,hurricup/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,slisson/intellij-community,wreckJ/intellij-community,Lekanich/intellij-community,kool79/intellij-community,allotria/intellij-community,vladmm/intellij-community,ibinti/intellij-community,robovm/robovm-studio,robovm/robovm-studio,holmes/intellij-community,Distrotech/intellij-community,xfournet/intellij-community,FHannes/intellij-community,ryano144/intellij-community,ol-loginov/intellij-community,pwoodworth/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,orekyuu/intellij-community,wreckJ/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,jagguli/intellij-community,signed/intellij-community,Lekanich/intellij-community,hurricup/intellij-community,allotria/intellij-community,ftomassetti/intellij-community,holmes/intellij-community,alphafoobar/intellij-community,izonder/intellij-community,nicolargo/intellij-community,da1z/intellij-community,supersven/intellij-community,fitermay/intellij-community,nicolargo/intellij-community,blademainer/intellij-community,mglukhikh/intellij-community,Distrotech/intellij-community,xfournet/intellij-community,vladmm/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,asedunov/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,ol-loginov/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,orekyuu/intellij-community,youdonghai/intellij-community,supersven/intellij-community,clumsy/intellij-community,jagguli/intellij-community,pwoodworth/intellij-community,Lekanich/intellij-community,clumsy/intellij-community,blademainer/intellij-community,caot/intellij-community,Lekanich/intellij-community,blademainer/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,amith01994/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,hurricup/intellij-community,akosyakov/intellij-community,caot/intellij-community,fengbaicanhe/intellij-community,diorcety/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,ol-loginov/intellij-community,dslomov/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,orekyuu/intellij-community,xfournet/intellij-community,nicolargo/intellij-community,pwoodworth/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,adedayo/intellij-community,suncycheng/intellij-community,ryano144/intellij-community,allotria/intellij-community,samthor/intellij-community,Distrotech/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,pwoodworth/intellij-community,supersven/intellij-community,idea4bsd/idea4bsd,caot/intellij-community,fitermay/intellij-community,vladmm/intellij-community,izonder/intellij-community,muntasirsyed/intellij-community,samthor/intellij-community,ol-loginov/intellij-community,Distrotech/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,diorcety/intellij-community,SerCeMan/intellij-community,supersven/intellij-community,xfournet/intellij-community,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,petteyg/intellij-community,mglukhikh/intellij-community,wreckJ/intellij-community,kdwink/intellij-community,caot/intellij-community,petteyg/intellij-community,petteyg/intellij-community,vvv1559/intellij-community,ol-loginov/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,izonder/intellij-community,petteyg/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,ivan-fedorov/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,adedayo/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,blademainer/intellij-community,ivan-fedorov/intellij-community,slisson/intellij-community,da1z/intellij-community,blademainer/intellij-community,holmes/intellij-community,amith01994/intellij-community,diorcety/intellij-community,tmpgit/intellij-community,holmes/intellij-community,ibinti/intellij-community,orekyuu/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,samthor/intellij-community,Lekanich/intellij-community,FHannes/intellij-community,da1z/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,diorcety/intellij-community,samthor/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,lucafavatella/intellij-community,xfournet/intellij-community,TangHao1987/intellij-community,ibinti/intellij-community,jagguli/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,adedayo/intellij-community,SerCeMan/intellij-community,alphafoobar/intellij-community,xfournet/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,dslomov/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,ahb0327/intellij-community,petteyg/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,slisson/intellij-community,petteyg/intellij-community,FHannes/intellij-community,holmes/intellij-community,pwoodworth/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,wreckJ/intellij-community,salguarnieri/intellij-community,slisson/intellij-community,asedunov/intellij-community,petteyg/intellij-community,clumsy/intellij-community,ibinti/intellij-community,Distrotech/intellij-community,gnuhub/intellij-community,samthor/intellij-community,adedayo/intellij-community,retomerz/intellij-community,caot/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,amith01994/intellij-community,MichaelNedzelsky/intellij-community,blademainer/intellij-community,gnuhub/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,gnuhub/intellij-community,izonder/intellij-community,vvv1559/intellij-community,caot/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,vvv1559/intellij-community,gnuhub/intellij-community,slisson/intellij-community,Lekanich/intellij-community,muntasirsyed/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,signed/intellij-community,ryano144/intellij-community,suncycheng/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,Distrotech/intellij-community,robovm/robovm-studio,FHannes/intellij-community,signed/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,michaelgallacher/intellij-community,nicolargo/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,retomerz/intellij-community,slisson/intellij-community,diorcety/intellij-community,diorcety/intellij-community,fitermay/intellij-community,izonder/intellij-community,wreckJ/intellij-community,wreckJ/intellij-community,ryano144/intellij-community,adedayo/intellij-community,ryano144/intellij-community,hurricup/intellij-community,fitermay/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,adedayo/intellij-community,suncycheng/intellij-community,blademainer/intellij-community,slisson/intellij-community,allotria/intellij-community,ibinti/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,apixandru/intellij-community,signed/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,fengbaicanhe/intellij-community,dslomov/intellij-community,suncycheng/intellij-community,wreckJ/intellij-community,Lekanich/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,ivan-fedorov/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,petteyg/intellij-community,vvv1559/intellij-community,semonte/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,semonte/intellij-community,ol-loginov/intellij-community,MER-GROUP/intellij-community,ahb0327/intellij-community,akosyakov/intellij-community,lucafavatella/intellij-community,ol-loginov/intellij-community,apixandru/intellij-community,robovm/robovm-studio,fitermay/intellij-community,ftomassetti/intellij-community,alphafoobar/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,SerCeMan/intellij-community,ahb0327/intellij-community,pwoodworth/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,nicolargo/intellij-community,allotria/intellij-community,Lekanich/intellij-community,MichaelNedzelsky/intellij-community,robovm/robovm-studio,amith01994/intellij-community,diorcety/intellij-community,SerCeMan/intellij-community,lucafavatella/intellij-community,dslomov/intellij-community,MichaelNedzelsky/intellij-community,caot/intellij-community,caot/intellij-community,ftomassetti/intellij-community,gnuhub/intellij-community,kool79/intellij-community,SerCeMan/intellij-community,orekyuu/intellij-community,Distrotech/intellij-community,alphafoobar/intellij-community,fengbaicanhe/intellij-community,petteyg/intellij-community,salguarnieri/intellij-community,signed/intellij-community,alphafoobar/intellij-community,caot/intellij-community,holmes/intellij-community,retomerz/intellij-community,kool79/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,hurricup/intellij-community,xfournet/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,pwoodworth/intellij-community,retomerz/intellij-community,alphafoobar/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,jagguli/intellij-community,tmpgit/intellij-community,semonte/intellij-community,nicolargo/intellij-community,holmes/intellij-community,Lekanich/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,kool79/intellij-community,michaelgallacher/intellij-community,ol-loginov/intellij-community,suncycheng/intellij-community,ivan-fedorov/intellij-community,ol-loginov/intellij-community,fengbaicanhe/intellij-community,tmpgit/intellij-community,retomerz/intellij-community,da1z/intellij-community,fitermay/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,jagguli/intellij-community,kool79/intellij-community,asedunov/intellij-community,vladmm/intellij-community,adedayo/intellij-community,salguarnieri/intellij-community,ivan-fedorov/intellij-community,fengbaicanhe/intellij-community,alphafoobar/intellij-community,nicolargo/intellij-community,vladmm/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,TangHao1987/intellij-community,ivan-fedorov/intellij-community,Distrotech/intellij-community,signed/intellij-community,kool79/intellij-community,xfournet/intellij-community,apixandru/intellij-community,kdwink/intellij-community,alphafoobar/intellij-community,orekyuu/intellij-community,kdwink/intellij-community,adedayo/intellij-community,adedayo/intellij-community,da1z/intellij-community,akosyakov/intellij-community,TangHao1987/intellij-community,ftomassetti/intellij-community,pwoodworth/intellij-community,youdonghai/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,adedayo/intellij-community,kdwink/intellij-community,Distrotech/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,amith01994/intellij-community,signed/intellij-community,samthor/intellij-community,da1z/intellij-community,FHannes/intellij-community,SerCeMan/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,ahb0327/intellij-community,ryano144/intellij-community,fnouama/intellij-community,adedayo/intellij-community,hurricup/intellij-community,retomerz/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,allotria/intellij-community,tmpgit/intellij-community,izonder/intellij-community,kool79/intellij-community,ol-loginov/intellij-community,ThiagoGarciaAlves/intellij-community,TangHao1987/intellij-community,youdonghai/intellij-community,SerCeMan/intellij-community,robovm/robovm-studio,muntasirsyed/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,suncycheng/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,gnuhub/intellij-community,wreckJ/intellij-community,vladmm/intellij-community,signed/intellij-community,jagguli/intellij-community,MichaelNedzelsky/intellij-community,ftomassetti/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,idea4bsd/idea4bsd,supersven/intellij-community,tmpgit/intellij-community,blademainer/intellij-community,fengbaicanhe/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,kdwink/intellij-community,robovm/robovm-studio,retomerz/intellij-community,asedunov/intellij-community,semonte/intellij-community,amith01994/intellij-community,michaelgallacher/intellij-community,diorcety/intellij-community,nicolargo/intellij-community,fnouama/intellij-community,akosyakov/intellij-community,fnouama/intellij-community,ivan-fedorov/intellij-community,ftomassetti/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,supersven/intellij-community,semonte/intellij-community,FHannes/intellij-community,tmpgit/intellij-community
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.fileEditor; import org.jetbrains.annotations.NotNull; import com.intellij.pom.Navigatable; /** * File editor which supports possibility to navigate to {@link com.intellij.pom.Navigatable} element * * @author spleaner */ public interface NavigatableFileEditor extends FileEditor { /** * Check whatever the editor can navigate to the given element * * @return true if editor can navigate, false otherwise */ boolean canNavigateTo(@NotNull final Navigatable navigatable); /** * Navigate editor to the given navigatable if {@link #canNavigateTo(com.intellij.pom.Navigatable)} is true * * @param navigatable navigation target */ void navigateTo(@NotNull final Navigatable navigatable); }
platform/platform-api/src/com/intellij/openapi/fileEditor/NavigatableFileEditor.java
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.fileEditor; import org.jetbrains.annotations.NotNull; import com.intellij.pom.Navigatable; /** * File editor which supports possibility to navigate to {@link com.intellij.pom.Navigatable} element * * @author spleaner */ public interface NavigatableFileEditor extends FileEditor { /** * Check whatever the editor can navigate to the given element * * @param navigatable * @return true if editor can navigate, false otherwise */ boolean canNavigateTo(@NotNull final Navigatable navigatable); /** * Navigate editor to the given navigatable if {@link #canNavigateTo(com.intellij.pom.Navigatable)} is true * * @param navigatable navigation target */ void navigateTo(@NotNull final Navigatable navigatable); }
cleanup
platform/platform-api/src/com/intellij/openapi/fileEditor/NavigatableFileEditor.java
cleanup
Java
apache-2.0
ffd67ef5f6ff23521de5ded7a03a4c4895271303
0
Martinfx/yodaqa,Martinfx/yodaqa,Martinfx/yodaqa,vineetk1/yodaqa,vineetk1/yodaqa,vineetk1/yodaqa,Martinfx/yodaqa,vineetk1/yodaqa,Martinfx/yodaqa,vineetk1/yodaqa,vineetk1/yodaqa,Martinfx/yodaqa
package cz.brmlab.yodaqa.analysis.tycor; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.apache.uima.UimaContext; import org.apache.uima.analysis_engine.AnalysisEngineProcessException; import org.apache.uima.cas.FeatureStructure; import org.apache.uima.fit.component.JCasAnnotator_ImplBase; import org.apache.uima.fit.util.JCasUtil; import org.apache.uima.jcas.JCas; import org.apache.uima.resource.ResourceInitializationException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import cz.brmlab.yodaqa.analysis.ansscore.AnswerFV; import cz.brmlab.yodaqa.model.CandidateAnswer.AF_LATANone; import cz.brmlab.yodaqa.model.CandidateAnswer.AF_LATANoWordNet; import cz.brmlab.yodaqa.model.CandidateAnswer.AF_LATQNoWordNet; import cz.brmlab.yodaqa.model.CandidateAnswer.AF_NoTyCor; import cz.brmlab.yodaqa.model.CandidateAnswer.AF_SpWordNet; import cz.brmlab.yodaqa.model.CandidateAnswer.AF_TyCorADBp; import cz.brmlab.yodaqa.model.CandidateAnswer.AF_TyCorADBpOntology; import cz.brmlab.yodaqa.model.CandidateAnswer.AF_TyCorADBpProperty; import cz.brmlab.yodaqa.model.CandidateAnswer.AF_TyCorAFBOntology; import cz.brmlab.yodaqa.model.CandidateAnswer.AF_TyCorANE; import cz.brmlab.yodaqa.model.CandidateAnswer.AF_TyCorAQuantity; import cz.brmlab.yodaqa.model.CandidateAnswer.AF_TyCorAQuantityCD; import cz.brmlab.yodaqa.model.CandidateAnswer.AF_TyCorAWnInstance; import cz.brmlab.yodaqa.model.CandidateAnswer.AF_TyCorPassageDist; import cz.brmlab.yodaqa.model.CandidateAnswer.AF_TyCorSpAHit; import cz.brmlab.yodaqa.model.CandidateAnswer.AF_TyCorSpNoHit; import cz.brmlab.yodaqa.model.CandidateAnswer.AF_TyCorSpQHit; import cz.brmlab.yodaqa.model.CandidateAnswer.AF_TyCorSpQAHit; import cz.brmlab.yodaqa.model.CandidateAnswer.AF_TyCorSpMultiHit; import cz.brmlab.yodaqa.model.CandidateAnswer.AnswerFeature; import cz.brmlab.yodaqa.model.CandidateAnswer.AnswerInfo; import cz.brmlab.yodaqa.model.TyCor.DBpLAT; import cz.brmlab.yodaqa.model.TyCor.DBpOntologyLAT; import cz.brmlab.yodaqa.model.TyCor.DBpPropertyLAT; import cz.brmlab.yodaqa.model.TyCor.FBOntologyLAT; import cz.brmlab.yodaqa.model.TyCor.LAT; import cz.brmlab.yodaqa.model.TyCor.NELAT; import cz.brmlab.yodaqa.model.TyCor.QuantityLAT; import cz.brmlab.yodaqa.model.TyCor.QuantityCDLAT; import cz.brmlab.yodaqa.model.TyCor.WnInstanceLAT; import cz.brmlab.yodaqa.model.TyCor.WordnetLAT; /** * Estimate answer specificity in CandidateAnswerCAS via type coercion * by question LAT to answer LAT matching. * * Basically, we try to find any matches of answer LAT set with the * question LAT set, and generate AFs accordingly. The crucial aspect * is the mesh of LATWordnets that we pre-generated and that represent * various generalizations of the (hopefully specific) LATs we * generated earlier. * * There are many ways to approach this. We allow generalizations * of both the question and answer LATs to match, because e.g. when * asking about a "site" of Lindbergh's flight, "New York" will be * generated as a "city" and the match is "location". But clearly * direct ('hit') matches are better than 'sibling' matches. */ public class LATMatchTyCor extends JCasAnnotator_ImplBase { final Logger logger = LoggerFactory.getLogger(LATMatchTyCor.class); /** A single match of a (question, answer) LAT tuple. The match * has a total specificity (sum of constituent specificities). */ protected class LATMatch { public LAT lat1, lat2; public double specificity; public LATMatch(LAT lat1_, LAT lat2_) { lat1 = lat1_; lat2 = lat2_; specificity = lat1.getSpecificity() + lat2.getSpecificity(); } public LAT getLat1() { return lat1; } public LAT getLat2() { return lat2; } public double getSpecificity() { return specificity; } public LAT getBaseLat1() { return _getBaseLat(getLat1()); } public LAT getBaseLat2() { return _getBaseLat(getLat2()); } protected LAT _getBaseLat(LAT lat) { while (lat.getBaseLAT() != null) lat = lat.getBaseLAT(); return lat; } public void logMatch(Logger logger, String prefix) { logger.debug(prefix + " " + getBaseLat1().getText() + "-" + getBaseLat2().getText() + " match " + getLat1().getText() /* == LAT2 text */ + "/" + getLat1().getSynset() + " sp. " + getSpecificity() + " (q " + getLat1().getSpecificity() + ", a " + getLat2().getSpecificity() + ")"); } /** Record details on this LATMatch in the given AnswerFV * (and log it too). This is worth calling for all LATMatches * that are hits for at least one side. */ public void record(AnswerFV fv, String ansText) { if (lat1.getSpecificity() == 0) fv.setFeature(AF_TyCorSpQHit.class, 1.0); if (lat2.getSpecificity() == 0) fv.setFeature(AF_TyCorSpAHit.class, 1.0); if (lat1.getSpecificity() == 0 || lat2.getSpecificity() == 0) { /* Generate a TyCor if this has been a direct * match from at least one direction (i.e. not * just a "semantic sibling"). */ LAT baselat2 = getBaseLat2(); if (baselat2 instanceof NELAT) fv.setFeature(AF_TyCorANE.class, 1.0); else if (baselat2 instanceof DBpLAT) fv.setFeature(AF_TyCorADBp.class, 1.0); else if (baselat2 instanceof QuantityLAT) fv.setFeature(AF_TyCorAQuantity.class, 1.0); else if (baselat2 instanceof QuantityCDLAT) fv.setFeature(AF_TyCorAQuantityCD.class, 1.0); else if (baselat2 instanceof WnInstanceLAT) fv.setFeature(AF_TyCorAWnInstance.class, 1.0); else if (baselat2 instanceof DBpOntologyLAT) fv.setFeature(AF_TyCorADBpOntology.class, 1.0); else if (baselat2 instanceof DBpPropertyLAT) fv.setFeature(AF_TyCorADBpProperty.class, 1.0); else if (baselat2 instanceof FBOntologyLAT) fv.setFeature(AF_TyCorAFBOntology.class, 1.0); else assert(false); } if (lat1.getSpecificity() == 0 && lat2.getSpecificity() == 0) { /* If both LATs match sharp, that's a good * sign OTOH. */ logger.debug("sharp LAT match for <<{}>>", ansText); fv.setFeature(AF_TyCorSpQAHit.class, 1.0); } else { /* Fuzzy match, just produce a debug print * as well for grep's sake. */ if (lat1.getSpecificity() == 0) { logger.debug("q-hit LAT match for <<{}>>", ansText); } else if (lat2.getSpecificity() == 0) { logger.debug("a-hit LAT match for <<{}>>", ansText); } } } } /* Synset blacklist - this blacklist will not permit using these * LATWordnet LATs for generalization. Therefore, "language" * will not match "area" through "cognition" and "time" will * not match "region" via "measure". * * This covers only matching LATWordnet pairs! So when * LATByQuantity generates "measure" answer LAT, this will still * match all measure-derived question LATs. * * N.B. this is a generalization limit applied in addition to the * LATByWordnet Tops synset list. * * XXX: Compiled manually by cursory logs investigation. We should * build a TyCor dataset and train it by that. */ protected static Long wnwn_synsetbl_list[] = { /* communication/ */ 33319L, /* cognition/ */ 23451L, /* ability/ */ 5624029L, /* higher cognitive process/ */ 5778661L, /* relation/ */ 32220L, /* ability/ */ 5624029L, /* measure/ */ 33914L, /* instrumentality/ */ 3580409L, /* artifact/ */ 22119L, /* fundamental quantity/ */ 13597072L, /* organization/ */ 8024893L, /* group/ */ 31563L, /* unit/ */ 8206589L, /* attribute/ */ 24444L, /* trait/ */ 4623416L, /* device/ */ 3187746L, /* social group/ */ 7967506L, /* act/ */ 30657L, /* activity/ */ 408356L, /* state/ */ 24900L, /* extent/ */ 5130681L, /* magnitude/ */ 5097645L, /* organism/ */ 4475L, /* creation/ */ 3133774L, /* product/ */ 4014270L, /* abstraction/ */ 2137L, /* medium/ */ 6264799L, /* gathering/ */ 7991473L, /* idea/ */ 5842164L, /* kind/ */ 5847533L, /* property/ */ 4923519L, /* quality/ */ 4731092L, /* concept/ */ 5844071L, /* thing/ */ 2452L, /* possession/ */ 32912L, /* happening/ */ 7298313L, /* signal/ */ 6804229L, /* auditory communication/ */ 7123727L, /* event/ */ 29677L, /* group/ */ 31563L, }; protected Set<Long> wnwn_synsetbl; public void initialize(UimaContext aContext) throws ResourceInitializationException { if (wnwn_synsetbl == null) wnwn_synsetbl = new HashSet<Long>(Arrays.asList(wnwn_synsetbl_list)); super.initialize(aContext); } public void process(JCas jcas) throws AnalysisEngineProcessException { JCas questionView, answerView; try { questionView = jcas.getView("Question"); answerView = jcas.getView("Answer"); } catch (Exception e) { throw new AnalysisEngineProcessException(e); } boolean qNoWordnetLAT = !hasWordnetLAT(questionView); boolean aNoWordnetLAT = !hasWordnetLAT(answerView); boolean aNoLAT = JCasUtil.select(answerView, LAT.class).isEmpty(); AnswerInfo ai = JCasUtil.selectSingle(answerView, AnswerInfo.class); AnswerFV fv = new AnswerFV(ai); /* Find the best match. Note that this will also * process and generate features for other nice * (hit) matches encountered on the way. */ LATMatch match = matchLATs(questionView, answerView, fv); if (match != null) { fv.setFeature(AF_SpWordNet.class, Math.exp(match.getSpecificity())); /* We were the only ones doing type coercion here. */ } else if (!fv.isFeatureSet(AF_TyCorPassageDist.class)) { /* XXX: Make the following a separate annotator? * When we get another type coercion stage. */ /* There is no LAT generated for this answer at all; * a pretty interesting negative feature on its own? */ if (aNoLAT) { logger.debug("no LAT for <<{}>>", answerView.getDocumentText()); fv.setFeature(AF_LATANone.class, -1.0); /* There is no type coercion match, but wordnet LATs * generated for both question and answer. This means * we are fairly sure this answer is of a wrong type. */ } else if (!qNoWordnetLAT && !aNoWordnetLAT && !fv.isFeatureSet(AF_TyCorPassageDist.class)) { logger.debug("failed TyCor for <<{}>>", answerView.getDocumentText()); fv.setFeature(AF_NoTyCor.class, -1.0); } } if (qNoWordnetLAT) fv.setFeature(AF_LATQNoWordNet.class, -1.0); if (!aNoLAT && aNoWordnetLAT) fv.setFeature(AF_LATANoWordNet.class, -1.0); if (ai.getFeatures() != null) for (FeatureStructure af : ai.getFeatures().toArray()) ((AnswerFeature) af).removeFromIndexes(); ai.removeFromIndexes(); ai.setFeatures(fv.toFSArray(answerView)); ai.addToIndexes(); } /** Check whether a given CAS (view) contains an LAT featureset * associated with a WordNet object. This is an indicator that * there is some "non-weird" LAT generated. */ protected boolean hasWordnetLAT(JCas jcas) { /* This is not a simple matter of checking for WordnetLAT * as we may have some other LAT with synset associated and * non-expanded to WordnetLATs. */ for (LAT lat : JCasUtil.select(jcas, LAT.class)) if (lat.getSynset() != 0) return true; return false; } protected LATMatch matchLATs(JCas questionView, JCas answerView, AnswerFV fv) throws AnalysisEngineProcessException { Map<String, LAT> answerLats = new HashMap<String, LAT>(); LATMatch bestMatch = null; int hits = 0; /* FIXME: Allow matching LATs that have same text but * different senses. */ /* Load LATs from answerView. */ for (LAT la : JCasUtil.select(answerView, LAT.class)) { if (la.getIsHierarchical() && !(la instanceof WordnetLAT)) continue; LAT la0 = answerLats.get(la.getText()); if (la0 == null || la0.getSpecificity() < la.getSpecificity()) answerLats.put(la.getText(), la); } if (answerLats.isEmpty()) return null; /* Match LATs from questionView. */ for (LAT lq : JCasUtil.select(questionView, LAT.class)) { if (lq.getIsHierarchical() && !(lq instanceof WordnetLAT)) continue; LAT la = answerLats.get(lq.getText()); if (la == null) continue; if (lq.getSynset() != 0 && la.getSynset() != 0 && lq.getSynset() != la.getSynset()) continue; /* We have a match! */ LATMatch match = new LATMatch(lq, la); // match.logMatch(logger, " maybe "); if (match.getLat1().getSpecificity() == 0 || match.getLat2().getSpecificity() == 0) { /* A hit match too! Record it right away. * (We may encounter a variety of these. */ match.logMatch(logger, ".. TyCor hit"); match.record(fv, answerView.getDocumentText()); hits++; } if (bestMatch == null || match.getSpecificity() > bestMatch.getSpecificity()) { /* XXX: Technically, we should apply the * blacklist check for match.record() above * as well; in practice, we should never get * hit matches on the WordnetLATs. */ if (match.getLat1() instanceof WordnetLAT && match.getLat2() instanceof WordnetLAT && wnwn_synsetbl.contains(match.getLat1().getSynset())) { match.logMatch(logger, ".. ignoring blacklisted TyCor"); continue; } bestMatch = match; } } if (bestMatch != null) { bestMatch.logMatch(logger, ".. TyCor best"); if (hits == 0) { /* If we had to generalize both LATs, that * seems to be a negative signal that the * answer is less specifit than we want. */ logger.debug("generalizing both LATs for <<{}>>", answerView.getDocumentText()); fv.setFeature(AF_TyCorSpNoHit.class, -1.0); } else if (hits > 0) { /* Multiple hits, that's a positive signal * hopefully indicating strong evidence. */ logger.debug("multi-hit LAT match for <<{}>>", answerView.getDocumentText()); fv.setFeature(AF_TyCorSpMultiHit.class, 1.0); } } return bestMatch; } }
src/main/java/cz/brmlab/yodaqa/analysis/tycor/LATMatchTyCor.java
package cz.brmlab.yodaqa.analysis.tycor; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.apache.uima.UimaContext; import org.apache.uima.analysis_engine.AnalysisEngineProcessException; import org.apache.uima.cas.FeatureStructure; import org.apache.uima.fit.component.JCasAnnotator_ImplBase; import org.apache.uima.fit.util.JCasUtil; import org.apache.uima.jcas.JCas; import org.apache.uima.resource.ResourceInitializationException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import cz.brmlab.yodaqa.analysis.ansscore.AnswerFV; import cz.brmlab.yodaqa.model.CandidateAnswer.AF_LATANone; import cz.brmlab.yodaqa.model.CandidateAnswer.AF_LATANoWordNet; import cz.brmlab.yodaqa.model.CandidateAnswer.AF_LATQNoWordNet; import cz.brmlab.yodaqa.model.CandidateAnswer.AF_NoTyCor; import cz.brmlab.yodaqa.model.CandidateAnswer.AF_SpWordNet; import cz.brmlab.yodaqa.model.CandidateAnswer.AF_TyCorADBp; import cz.brmlab.yodaqa.model.CandidateAnswer.AF_TyCorADBpOntology; import cz.brmlab.yodaqa.model.CandidateAnswer.AF_TyCorADBpProperty; import cz.brmlab.yodaqa.model.CandidateAnswer.AF_TyCorAFBOntology; import cz.brmlab.yodaqa.model.CandidateAnswer.AF_TyCorANE; import cz.brmlab.yodaqa.model.CandidateAnswer.AF_TyCorAQuantity; import cz.brmlab.yodaqa.model.CandidateAnswer.AF_TyCorAQuantityCD; import cz.brmlab.yodaqa.model.CandidateAnswer.AF_TyCorAWnInstance; import cz.brmlab.yodaqa.model.CandidateAnswer.AF_TyCorPassageDist; import cz.brmlab.yodaqa.model.CandidateAnswer.AF_TyCorSpAHit; import cz.brmlab.yodaqa.model.CandidateAnswer.AF_TyCorSpNoHit; import cz.brmlab.yodaqa.model.CandidateAnswer.AF_TyCorSpQHit; import cz.brmlab.yodaqa.model.CandidateAnswer.AF_TyCorSpQAHit; import cz.brmlab.yodaqa.model.CandidateAnswer.AF_TyCorSpMultiHit; import cz.brmlab.yodaqa.model.CandidateAnswer.AnswerFeature; import cz.brmlab.yodaqa.model.CandidateAnswer.AnswerInfo; import cz.brmlab.yodaqa.model.TyCor.DBpLAT; import cz.brmlab.yodaqa.model.TyCor.DBpOntologyLAT; import cz.brmlab.yodaqa.model.TyCor.DBpPropertyLAT; import cz.brmlab.yodaqa.model.TyCor.FBOntologyLAT; import cz.brmlab.yodaqa.model.TyCor.LAT; import cz.brmlab.yodaqa.model.TyCor.NELAT; import cz.brmlab.yodaqa.model.TyCor.QuantityLAT; import cz.brmlab.yodaqa.model.TyCor.QuantityCDLAT; import cz.brmlab.yodaqa.model.TyCor.WnInstanceLAT; import cz.brmlab.yodaqa.model.TyCor.WordnetLAT; /** * Estimate answer specificity in CandidateAnswerCAS via type coercion * by question LAT to answer LAT matching. * * Basically, we try to find any matches of answer LAT set with the * question LAT set, and generate AFs accordingly. The crucial aspect * is the mesh of LATWordnets that we pre-generated and that represent * various generalizations of the (hopefully specific) LATs we * generated earlier. * * There are many ways to approach this. We allow generalizations * of both the question and answer LATs to match, because e.g. when * asking about a "site" of Lindbergh's flight, "New York" will be * generated as a "city" and the match is "location". But clearly * direct ('hit') matches are better than 'sibling' matches. */ public class LATMatchTyCor extends JCasAnnotator_ImplBase { final Logger logger = LoggerFactory.getLogger(LATMatchTyCor.class); /** A single match of a (question, answer) LAT tuple. The match * has a total specificity (sum of constituent specificities). */ protected class LATMatch { public LAT lat1, lat2; public double specificity; public LATMatch(LAT lat1_, LAT lat2_) { lat1 = lat1_; lat2 = lat2_; specificity = lat1.getSpecificity() + lat2.getSpecificity(); } public LAT getLat1() { return lat1; } public LAT getLat2() { return lat2; } public double getSpecificity() { return specificity; } public LAT getBaseLat1() { return _getBaseLat(getLat1()); } public LAT getBaseLat2() { return _getBaseLat(getLat2()); } protected LAT _getBaseLat(LAT lat) { while (lat.getBaseLAT() != null) lat = lat.getBaseLAT(); return lat; } public void logMatch(Logger logger, String prefix) { logger.debug(prefix + " " + getBaseLat1().getText() + "-" + getBaseLat2().getText() + " match " + getLat1().getText() /* == LAT2 text */ + "/" + getLat1().getSynset() + " sp. " + getSpecificity() + " (q " + getLat1().getSpecificity() + ", a " + getLat2().getSpecificity() + ")"); } /** Record details on this LATMatch in the given AnswerFV * (and log it too). This is worth calling for all LATMatches * that are hits for at least one side. */ public void record(AnswerFV fv, String ansText) { if (lat1.getSpecificity() == 0) fv.setFeature(AF_TyCorSpQHit.class, 1.0); if (lat2.getSpecificity() == 0) fv.setFeature(AF_TyCorSpAHit.class, 1.0); if (lat1.getSpecificity() == 0 || lat2.getSpecificity() == 0) { /* Generate a TyCor if this has been a direct * match from at least one direction (i.e. not * just a "semantic sibling"). */ LAT baselat2 = getBaseLat2(); if (baselat2 instanceof NELAT) fv.setFeature(AF_TyCorANE.class, 1.0); else if (baselat2 instanceof DBpLAT) fv.setFeature(AF_TyCorADBp.class, 1.0); else if (baselat2 instanceof QuantityLAT) fv.setFeature(AF_TyCorAQuantity.class, 1.0); else if (baselat2 instanceof QuantityCDLAT) fv.setFeature(AF_TyCorAQuantityCD.class, 1.0); else if (baselat2 instanceof WnInstanceLAT) fv.setFeature(AF_TyCorAWnInstance.class, 1.0); else if (baselat2 instanceof DBpOntologyLAT) fv.setFeature(AF_TyCorADBpOntology.class, 1.0); else if (baselat2 instanceof DBpPropertyLAT) fv.setFeature(AF_TyCorADBpProperty.class, 1.0); else if (baselat2 instanceof FBOntologyLAT) fv.setFeature(AF_TyCorAFBOntology.class, 1.0); else assert(false); } if (lat1.getSpecificity() == 0 && lat2.getSpecificity() == 0) { /* If both LATs match sharp, that's a good * sign OTOH. */ logger.debug("sharp LAT match for <<{}>>", ansText); fv.setFeature(AF_TyCorSpQAHit.class, 1.0); } else { /* Fuzzy match, just produce a debug print * as well for grep's sake. */ if (lat1.getSpecificity() == 0) { logger.debug("q-hit LAT match for <<{}>>", ansText); } else if (lat2.getSpecificity() == 0) { logger.debug("a-hit LAT match for <<{}>>", ansText); } } } } /* Synset blacklist - this blacklist will not permit using these * LATWordnet LATs for generalization. Therefore, "language" * will not match "area" through "cognition" and "time" will * not match "region" via "measure". * * This covers only matching LATWordnet pairs! So when * LATByQuantity generates "measure" answer LAT, this will still * match all measure-derived question LATs. * * N.B. this is a generalization limit applied in addition to the * LATByWordnet Tops synset list. * * XXX: Compiled manually by cursory logs investigation. We should * build a TyCor dataset and train it by that. */ protected static Long wnwn_synsetbl_list[] = { /* communication/ */ 33319L, /* cognition/ */ 23451L, /* ability/ */ 5624029L, /* higher cognitive process/ */ 5778661L, /* relation/ */ 32220L, /* ability/ */ 5624029L, /* measure/ */ 33914L, /* instrumentality/ */ 3580409L, /* artifact/ */ 22119L, /* fundamental quantity/ */ 13597072L, /* organization/ */ 8024893L, /* group/ */ 31563L, /* unit/ */ 8206589L, /* attribute/ */ 24444L, /* trait/ */ 4623416L, /* device/ */ 3187746L, /* social group/ */ 7967506L, /* act/ */ 30657L, /* activity/ */ 408356L, /* state/ */ 24900L, /* extent/ */ 5130681L, /* magnitude/ */ 5097645L, /* organism/ */ 4475L, /* creation/ */ 3133774L, /* product/ */ 4014270L, /* abstraction/ */ 2137L, /* medium/ */ 6264799L, /* gathering/ */ 7991473L, /* idea/ */ 5842164L, /* kind/ */ 5847533L, /* property/ */ 4923519L, /* quality/ */ 4731092L, /* concept/ */ 5844071L, /* thing/ */ 2452L, }; protected Set<Long> wnwn_synsetbl; public void initialize(UimaContext aContext) throws ResourceInitializationException { if (wnwn_synsetbl == null) wnwn_synsetbl = new HashSet<Long>(Arrays.asList(wnwn_synsetbl_list)); super.initialize(aContext); } public void process(JCas jcas) throws AnalysisEngineProcessException { JCas questionView, answerView; try { questionView = jcas.getView("Question"); answerView = jcas.getView("Answer"); } catch (Exception e) { throw new AnalysisEngineProcessException(e); } boolean qNoWordnetLAT = !hasWordnetLAT(questionView); boolean aNoWordnetLAT = !hasWordnetLAT(answerView); boolean aNoLAT = JCasUtil.select(answerView, LAT.class).isEmpty(); AnswerInfo ai = JCasUtil.selectSingle(answerView, AnswerInfo.class); AnswerFV fv = new AnswerFV(ai); /* Find the best match. Note that this will also * process and generate features for other nice * (hit) matches encountered on the way. */ LATMatch match = matchLATs(questionView, answerView, fv); if (match != null) { fv.setFeature(AF_SpWordNet.class, Math.exp(match.getSpecificity())); /* We were the only ones doing type coercion here. */ } else if (!fv.isFeatureSet(AF_TyCorPassageDist.class)) { /* XXX: Make the following a separate annotator? * When we get another type coercion stage. */ /* There is no LAT generated for this answer at all; * a pretty interesting negative feature on its own? */ if (aNoLAT) { logger.debug("no LAT for <<{}>>", answerView.getDocumentText()); fv.setFeature(AF_LATANone.class, -1.0); /* There is no type coercion match, but wordnet LATs * generated for both question and answer. This means * we are fairly sure this answer is of a wrong type. */ } else if (!qNoWordnetLAT && !aNoWordnetLAT && !fv.isFeatureSet(AF_TyCorPassageDist.class)) { logger.debug("failed TyCor for <<{}>>", answerView.getDocumentText()); fv.setFeature(AF_NoTyCor.class, -1.0); } } if (qNoWordnetLAT) fv.setFeature(AF_LATQNoWordNet.class, -1.0); if (!aNoLAT && aNoWordnetLAT) fv.setFeature(AF_LATANoWordNet.class, -1.0); if (ai.getFeatures() != null) for (FeatureStructure af : ai.getFeatures().toArray()) ((AnswerFeature) af).removeFromIndexes(); ai.removeFromIndexes(); ai.setFeatures(fv.toFSArray(answerView)); ai.addToIndexes(); } /** Check whether a given CAS (view) contains an LAT featureset * associated with a WordNet object. This is an indicator that * there is some "non-weird" LAT generated. */ protected boolean hasWordnetLAT(JCas jcas) { /* This is not a simple matter of checking for WordnetLAT * as we may have some other LAT with synset associated and * non-expanded to WordnetLATs. */ for (LAT lat : JCasUtil.select(jcas, LAT.class)) if (lat.getSynset() != 0) return true; return false; } protected LATMatch matchLATs(JCas questionView, JCas answerView, AnswerFV fv) throws AnalysisEngineProcessException { Map<String, LAT> answerLats = new HashMap<String, LAT>(); LATMatch bestMatch = null; int hits = 0; /* FIXME: Allow matching LATs that have same text but * different senses. */ /* Load LATs from answerView. */ for (LAT la : JCasUtil.select(answerView, LAT.class)) { if (la.getIsHierarchical() && !(la instanceof WordnetLAT)) continue; LAT la0 = answerLats.get(la.getText()); if (la0 == null || la0.getSpecificity() < la.getSpecificity()) answerLats.put(la.getText(), la); } if (answerLats.isEmpty()) return null; /* Match LATs from questionView. */ for (LAT lq : JCasUtil.select(questionView, LAT.class)) { if (lq.getIsHierarchical() && !(lq instanceof WordnetLAT)) continue; LAT la = answerLats.get(lq.getText()); if (la == null) continue; if (lq.getSynset() != 0 && la.getSynset() != 0 && lq.getSynset() != la.getSynset()) continue; /* We have a match! */ LATMatch match = new LATMatch(lq, la); // match.logMatch(logger, " maybe "); if (match.getLat1().getSpecificity() == 0 || match.getLat2().getSpecificity() == 0) { /* A hit match too! Record it right away. * (We may encounter a variety of these. */ match.logMatch(logger, ".. TyCor hit"); match.record(fv, answerView.getDocumentText()); hits++; } if (bestMatch == null || match.getSpecificity() > bestMatch.getSpecificity()) { /* XXX: Technically, we should apply the * blacklist check for match.record() above * as well; in practice, we should never get * hit matches on the WordnetLATs. */ if (match.getLat1() instanceof WordnetLAT && match.getLat2() instanceof WordnetLAT && wnwn_synsetbl.contains(match.getLat1().getSynset())) { match.logMatch(logger, ".. ignoring blacklisted TyCor"); continue; } bestMatch = match; } } if (bestMatch != null) { bestMatch.logMatch(logger, ".. TyCor best"); if (hits == 0) { /* If we had to generalize both LATs, that * seems to be a negative signal that the * answer is less specifit than we want. */ logger.debug("generalizing both LATs for <<{}>>", answerView.getDocumentText()); fv.setFeature(AF_TyCorSpNoHit.class, -1.0); } else if (hits > 0) { /* Multiple hits, that's a positive signal * hopefully indicating strong evidence. */ logger.debug("multi-hit LAT match for <<{}>>", answerView.getDocumentText()); fv.setFeature(AF_TyCorSpMultiHit.class, 1.0); } } return bestMatch; } }
LATMatchTyCor wnwn_synsetbl_list: +Some empirical problematic 'song' tycor matches
src/main/java/cz/brmlab/yodaqa/analysis/tycor/LATMatchTyCor.java
LATMatchTyCor wnwn_synsetbl_list: +Some empirical problematic 'song' tycor matches
Java
apache-2.0
325f6d3fff7d45d9d930e9d4bdf53e7186d305b7
0
semonte/intellij-community,allotria/intellij-community,FHannes/intellij-community,da1z/intellij-community,allotria/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,semonte/intellij-community,semonte/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,ibinti/intellij-community,da1z/intellij-community,apixandru/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,apixandru/intellij-community,fitermay/intellij-community,ibinti/intellij-community,ibinti/intellij-community,fitermay/intellij-community,signed/intellij-community,fitermay/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,semonte/intellij-community,FHannes/intellij-community,ibinti/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,signed/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,allotria/intellij-community,hurricup/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,FHannes/intellij-community,FHannes/intellij-community,xfournet/intellij-community,signed/intellij-community,asedunov/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,youdonghai/intellij-community,FHannes/intellij-community,xfournet/intellij-community,retomerz/intellij-community,da1z/intellij-community,semonte/intellij-community,da1z/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,allotria/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,da1z/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,semonte/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,signed/intellij-community,signed/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,retomerz/intellij-community,FHannes/intellij-community,signed/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,allotria/intellij-community,da1z/intellij-community,semonte/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,ibinti/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,signed/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,semonte/intellij-community,retomerz/intellij-community,allotria/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,apixandru/intellij-community,apixandru/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,vvv1559/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,fitermay/intellij-community,FHannes/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,hurricup/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,semonte/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,signed/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,allotria/intellij-community,apixandru/intellij-community,hurricup/intellij-community,hurricup/intellij-community,fitermay/intellij-community,FHannes/intellij-community,da1z/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,da1z/intellij-community,fitermay/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,fitermay/intellij-community,asedunov/intellij-community,asedunov/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,retomerz/intellij-community,retomerz/intellij-community,da1z/intellij-community,semonte/intellij-community,ibinti/intellij-community,retomerz/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,signed/intellij-community
package com.jetbrains.jsonSchema; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.CommonShortcuts; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory; import com.intellij.openapi.fileEditor.OpenFileDescriptor; import com.intellij.openapi.project.DumbAwareAction; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogBuilder; import com.intellij.openapi.ui.MessageType; import com.intellij.openapi.ui.TextFieldWithBrowseButton; import com.intellij.openapi.ui.popup.Balloon; import com.intellij.openapi.ui.popup.BalloonBuilder; import com.intellij.openapi.ui.popup.JBPopupFactory; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Getter; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.AnActionButton; import com.intellij.ui.AnActionButtonRunnable; import com.intellij.ui.ToolbarDecorator; import com.intellij.ui.components.JBLabel; import com.intellij.ui.components.JBPanel; import com.intellij.ui.components.JBRadioButton; import com.intellij.ui.components.JBTextField; import com.intellij.ui.table.TableView; import com.intellij.util.Alarm; import com.intellij.util.ui.*; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; /** * @author Irina.Chernushina on 2/2/2016. */ public class JsonSchemaMappingsView { private static final String ADD_SCHEMA_MAPPING = "settings.json.schema.add.mapping"; private TableView<JsonSchemaMappingsConfigurationBase.Item> myTableView; private ToolbarDecorator myDecorator; private JComponent myComponent; private Project myProject; private TextFieldWithBrowseButton mySchemaField; public JsonSchemaMappingsView(Project project) { createUI(project); } private void createUI(final Project project) { myProject = project; myTableView = new TableView<JsonSchemaMappingsConfigurationBase.Item>(); myTableView.getTableHeader().setVisible(false); myDecorator = ToolbarDecorator.createDecorator(myTableView); myDecorator .setRemoveAction(new AnActionButtonRunnable() { @Override public void run(AnActionButton button) { final int[] rows = myTableView.getSelectedRows(); if (rows != null && rows.length > 0) { int cnt = 0; for (int row : rows) { myTableView.getListTableModel().removeRow(row - cnt); ++ cnt; } myTableView.getListTableModel().fireTableDataChanged(); } } }) .setAddAction(new MyAddActionButtonRunnable(project)) .disableUpDownActions(); final JPanel wrapper = new JPanel(new BorderLayout()); final JPanel wrapper2 = new JPanel(new BorderLayout()); mySchemaField = new TextFieldWithBrowseButton(); SwingHelper.installFileCompletionAndBrowseDialog(myProject, mySchemaField, "Select JSON Schema File", FileChooserDescriptorFactory.createSingleFileDescriptor()); attachNavigateToSchema(); final JBLabel label = new JBLabel("JSON schema file:"); wrapper2.add(label, BorderLayout.WEST); label.setBorder(JBUI.Borders.empty(0,0,0,10)); wrapper2.add(mySchemaField, BorderLayout.CENTER); wrapper2.setBorder(JBUI.Borders.empty(0, 10, 10, 10)); wrapper.add(wrapper2, BorderLayout.NORTH); wrapper.add(myDecorator.createPanel(), BorderLayout.CENTER); myComponent = wrapper; } private void attachNavigateToSchema() { new DumbAwareAction() { @Override public void actionPerformed(AnActionEvent e) { final String pathToSchema = mySchemaField.getText(); if (StringUtil.isEmptyOrSpaces(pathToSchema)) return; final VirtualFile virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(new File(pathToSchema)); if (virtualFile == null) { BalloonBuilder balloonBuilder = JBPopupFactory.getInstance() .createHtmlTextBalloonBuilder("File not found", UIUtil.getBalloonErrorIcon(), MessageType.ERROR.getPopupBackground(), null); final Balloon balloon = balloonBuilder.setFadeoutTime(TimeUnit.SECONDS.toMillis(3)).createBalloon(); balloon.showInCenterOf(mySchemaField); return; } new OpenFileDescriptor(myProject, virtualFile).navigate(true); } }.registerCustomShortcutSet(CommonShortcuts.getEditSource(), mySchemaField); } public List<JsonSchemaMappingsConfigurationBase.Item> getData() { final List<JsonSchemaMappingsConfigurationBase.Item> items = myTableView.getListTableModel().getItems(); /*final List<JsonSchemaMappingsConfigurationBase.Item> copy = new ArrayList<JsonSchemaMappingsConfigurationBase.Item>(); for (JsonSchemaMappingsConfigurationBase.Item item : items) { if (myProject != null && myProject.getBasePath() != null && !item.isPattern()) { final String relativePath = FileUtil.getRelativePath(new File(myProject.getBasePath()), new File(item.getPath())); copy.add(new JsonSchemaMappingsConfigurationBase.Item(relativePath, item.isPattern(), item.isDirectory())); } else { copy.add(new JsonSchemaMappingsConfigurationBase.Item(item.getPath(), item.isPattern(), item.isDirectory())); } }*/ return items; } public void setItems(VirtualFile schemaFile, final List<JsonSchemaMappingsConfigurationBase.Item> data) { /*final ArrayList<JsonSchemaMappingsConfigurationBase.Item> copy = new ArrayList<JsonSchemaMappingsConfigurationBase.Item>(); if (myProject != null && myProject.getBasePath() != null) { for (JsonSchemaMappingsConfigurationBase.Item item : copy) { if (item.isPattern()) { copy.add(new JsonSchemaMappingsConfigurationBase.Item(new File(myProject.getBasePath(), item.getPath()).getPath(), item.isPattern(), item.isDirectory())); } else { copy.addAll(data); } } } else { copy.addAll(data); }*/ mySchemaField.setText(FileUtil.toSystemDependentName(schemaFile.getPath())); myTableView.setModelAndUpdateColumns(new ListTableModel<JsonSchemaMappingsConfigurationBase.Item>(createColumns(), new ArrayList<JsonSchemaMappingsConfigurationBase.Item>(data))); } public String getSchemaSubPath() { return FileUtil.toSystemDependentName(getRelativePath(myProject, mySchemaField.getText())); } private static ColumnInfo[] createColumns() { return new ColumnInfo[] { new ColumnInfo<JsonSchemaMappingsConfigurationBase.Item, String>("") { @Nullable @Override public String valueOf(JsonSchemaMappingsConfigurationBase.Item item) { final String prefix = item.isPattern() ? "Pattern: " : (item.isDirectory() ? "Directory: " : "File: "); return prefix + item.getPath(); } } }; } public JComponent getComponent() { return myComponent; } private class MyAddActionButtonRunnable implements AnActionButtonRunnable { private final Project myProject; public MyAddActionButtonRunnable(Project project) { myProject = project; } @Override public void run(AnActionButton button) { final JBPanel panel = new JBPanel(new GridBagLayout()); final GridBag bag = new GridBag(); final JBTextField patternField = new JBTextField(); final TextFieldWithBrowseButton directoryField = new TextFieldWithBrowseButton(); final TextFieldWithBrowseButton fileField = new TextFieldWithBrowseButton(); bag.setDefaultAnchor(GridBagConstraints.NORTHWEST); final JBRadioButton radioPattern = new JBRadioButton("Filename pattern:"); final JBRadioButton radioDirectory = new JBRadioButton("Files under:"); final JBRadioButton radioFile = new JBRadioButton("File:"); panel.add(radioDirectory, bag.nextLine().next().fillCellNone().weightx(0)); panel.add(directoryField, bag.next().fillCellHorizontally().weightx(1)); panel.add(radioPattern, bag.nextLine().next().fillCellNone().weightx(0)); panel.add(patternField, bag.next().fillCellHorizontally().weightx(1)); panel.add(radioFile, bag.nextLine().next().fillCellNone().weightx(0)); panel.add(fileField, bag.next().fillCellHorizontally().weightx(1)); SwingHelper.installFileCompletionAndBrowseDialog(myProject, directoryField, "Select Folder", FileChooserDescriptorFactory.createSingleFolderDescriptor()); SwingHelper.installFileCompletionAndBrowseDialog(myProject, fileField, "Select File", FileChooserDescriptorFactory.createSingleFileDescriptor()); final ButtonGroup group = new ButtonGroup(); group.add(radioPattern); group.add(radioDirectory); group.add(radioFile); radioDirectory.setSelected(true); patternField.setMinimumSize(new Dimension(JBUI.scale(200), UIUtil.getInformationIcon().getIconHeight())); patternField.getEmptyText().setText("Example: *.config.json"); final DialogBuilder builder = new DialogBuilder(); builder.setTitle("Add JSON Schema Mapping"); builder.setNorthPanel(panel); builder.setPreferredFocusComponent(directoryField); builder.setDimensionServiceKey("com.jetbrains.jsonSchema.JsonSchemaMappingsView#add"); builder.setHelpId(ADD_SCHEMA_MAPPING); final Getter<String> textGetter = new Getter<String>() { @Override public String get() { if (radioPattern.isSelected()) { return patternField.getText(); } final String text; if (radioDirectory.isSelected()) { text = directoryField.getText(); } else { text = fileField.getText(); } return getRelativePath(myProject, text); } }; final Alarm alarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD); final Runnable updaterValidator = new Runnable() { @Override public void run() { if (!patternField.isVisible()) return; patternField.setEnabled(radioPattern.isSelected()); directoryField.setEnabled(radioDirectory.isSelected()); fileField.setEnabled(radioFile.isSelected()); builder.setOkActionEnabled(!StringUtil.isEmptyOrSpaces(textGetter.get())); alarm.addRequest(this, 300, ModalityState.any()); } }; alarm.addRequest(updaterValidator, 300, ModalityState.any()); updaterValidator.run(); final ActionListener listener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { updaterValidator.run(); } }; radioPattern.addActionListener(listener); radioDirectory.addActionListener(listener); radioFile.addActionListener(listener); if (myProject == null || myProject.getBasePath() == null) { radioDirectory.setEnabled(false); radioFile.setEnabled(false); directoryField.setEnabled(false); fileField.setEnabled(false); } if (builder.showAndGet()) { final String pattern = textGetter.get(); final JsonSchemaMappingsConfigurationBase.Item item = new JsonSchemaMappingsConfigurationBase.Item(pattern, radioPattern.isSelected(), radioDirectory.isSelected()); myTableView.getListTableModel().addRow(item); //myTableView.getListTableModel().fireTableDataChanged(); } Disposer.dispose(alarm); } } private static String getRelativePath(@NotNull Project project, @NotNull String text) { if (project.isDefault()) return text; if (StringUtil.isEmptyOrSpaces(text)) return text; final String relativePath = FileUtil.getRelativePath(new File(project.getBasePath()), new File(text)); return relativePath == null ? text : relativePath; } }
json/src/com/jetbrains/jsonSchema/JsonSchemaMappingsView.java
package com.jetbrains.jsonSchema; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.CommonShortcuts; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory; import com.intellij.openapi.fileEditor.OpenFileDescriptor; import com.intellij.openapi.project.DumbAwareAction; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogBuilder; import com.intellij.openapi.ui.MessageType; import com.intellij.openapi.ui.TextFieldWithBrowseButton; import com.intellij.openapi.ui.popup.Balloon; import com.intellij.openapi.ui.popup.BalloonBuilder; import com.intellij.openapi.ui.popup.JBPopupFactory; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Getter; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.AnActionButton; import com.intellij.ui.AnActionButtonRunnable; import com.intellij.ui.ToolbarDecorator; import com.intellij.ui.components.JBLabel; import com.intellij.ui.components.JBPanel; import com.intellij.ui.components.JBRadioButton; import com.intellij.ui.components.JBTextField; import com.intellij.ui.table.TableView; import com.intellij.util.Alarm; import com.intellij.util.ui.*; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; /** * @author Irina.Chernushina on 2/2/2016. */ public class JsonSchemaMappingsView { private static final String ADD_SCHEMA_MAPPING = "settings.json.schema.add.mapping"; private TableView<JsonSchemaMappingsConfigurationBase.Item> myTableView; private ToolbarDecorator myDecorator; private JComponent myComponent; private Project myProject; private TextFieldWithBrowseButton mySchemaField; public JsonSchemaMappingsView(Project project) { createUI(project); } private void createUI(final Project project) { myProject = project; myTableView = new TableView<JsonSchemaMappingsConfigurationBase.Item>(); myTableView.getTableHeader().setVisible(false); myDecorator = ToolbarDecorator.createDecorator(myTableView); myDecorator .setRemoveAction(new AnActionButtonRunnable() { @Override public void run(AnActionButton button) { final int[] rows = myTableView.getSelectedRows(); if (rows != null && rows.length > 0) { int cnt = 0; for (int row : rows) { myTableView.getListTableModel().removeRow(row - cnt); ++ cnt; } myTableView.getListTableModel().fireTableDataChanged(); } } }) .setAddAction(new MyAddActionButtonRunnable(project)) .disableUpDownActions(); final JPanel wrapper = new JPanel(new BorderLayout()); final JPanel wrapper2 = new JPanel(new BorderLayout()); mySchemaField = new TextFieldWithBrowseButton(); SwingHelper.installFileCompletionAndBrowseDialog(myProject, mySchemaField, "Select JSON Schema File", FileChooserDescriptorFactory.createSingleFileDescriptor()); attachNavigateToSchema(); final JBLabel label = new JBLabel("JSON schema file:"); wrapper2.add(label, BorderLayout.WEST); label.setBorder(JBUI.Borders.empty(0,0,0,10)); wrapper2.add(mySchemaField, BorderLayout.CENTER); wrapper2.setBorder(JBUI.Borders.empty(0, 10, 10, 10)); wrapper.add(wrapper2, BorderLayout.NORTH); wrapper.add(myDecorator.createPanel(), BorderLayout.CENTER); myComponent = wrapper; } private void attachNavigateToSchema() { new DumbAwareAction() { @Override public void actionPerformed(AnActionEvent e) { final String pathToSchema = mySchemaField.getText(); if (StringUtil.isEmptyOrSpaces(pathToSchema)) return; final VirtualFile virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(new File(pathToSchema)); if (virtualFile == null) { BalloonBuilder balloonBuilder = JBPopupFactory.getInstance() .createHtmlTextBalloonBuilder("File not found", UIUtil.getBalloonErrorIcon(), MessageType.ERROR.getPopupBackground(), null); final Balloon balloon = balloonBuilder.setFadeoutTime(TimeUnit.SECONDS.toMillis(3)).createBalloon(); balloon.showInCenterOf(mySchemaField); return; } new OpenFileDescriptor(myProject, virtualFile).navigate(true); } }.registerCustomShortcutSet(CommonShortcuts.getEditSource(), mySchemaField); } public List<JsonSchemaMappingsConfigurationBase.Item> getData() { final List<JsonSchemaMappingsConfigurationBase.Item> items = myTableView.getListTableModel().getItems(); /*final List<JsonSchemaMappingsConfigurationBase.Item> copy = new ArrayList<JsonSchemaMappingsConfigurationBase.Item>(); for (JsonSchemaMappingsConfigurationBase.Item item : items) { if (myProject != null && myProject.getBasePath() != null && !item.isPattern()) { final String relativePath = FileUtil.getRelativePath(new File(myProject.getBasePath()), new File(item.getPath())); copy.add(new JsonSchemaMappingsConfigurationBase.Item(relativePath, item.isPattern(), item.isDirectory())); } else { copy.add(new JsonSchemaMappingsConfigurationBase.Item(item.getPath(), item.isPattern(), item.isDirectory())); } }*/ return items; } public void setItems(VirtualFile schemaFile, final List<JsonSchemaMappingsConfigurationBase.Item> data) { /*final ArrayList<JsonSchemaMappingsConfigurationBase.Item> copy = new ArrayList<JsonSchemaMappingsConfigurationBase.Item>(); if (myProject != null && myProject.getBasePath() != null) { for (JsonSchemaMappingsConfigurationBase.Item item : copy) { if (item.isPattern()) { copy.add(new JsonSchemaMappingsConfigurationBase.Item(new File(myProject.getBasePath(), item.getPath()).getPath(), item.isPattern(), item.isDirectory())); } else { copy.addAll(data); } } } else { copy.addAll(data); }*/ mySchemaField.setText(FileUtil.toSystemDependentName(schemaFile.getPath())); myTableView.setModelAndUpdateColumns(new ListTableModel<JsonSchemaMappingsConfigurationBase.Item>(createColumns(), new ArrayList<JsonSchemaMappingsConfigurationBase.Item>(data))); } public String getSchemaSubPath() { return FileUtil.toSystemDependentName(getRelativePath(myProject, mySchemaField.getText())); } private static ColumnInfo[] createColumns() { return new ColumnInfo[] { new ColumnInfo<JsonSchemaMappingsConfigurationBase.Item, String>("") { @Nullable @Override public String valueOf(JsonSchemaMappingsConfigurationBase.Item item) { final String prefix = item.isPattern() ? "Pattern: " : (item.isDirectory() ? "Directory: " : "File: "); return prefix + item.getPath(); } } }; } public JComponent getComponent() { return myComponent; } private class MyAddActionButtonRunnable implements AnActionButtonRunnable { private final Project myProject; public MyAddActionButtonRunnable(Project project) { myProject = project; } @Override public void run(AnActionButton button) { final JBPanel panel = new JBPanel(new GridBagLayout()); final GridBag bag = new GridBag(); final JBTextField patternField = new JBTextField(); final TextFieldWithBrowseButton directoryField = new TextFieldWithBrowseButton(); final TextFieldWithBrowseButton fileField = new TextFieldWithBrowseButton(); bag.setDefaultAnchor(GridBagConstraints.NORTHWEST); final JBRadioButton radioPattern = new JBRadioButton("Filename pattern:"); final JBRadioButton radioDirectory = new JBRadioButton("Files under:"); final JBRadioButton radioFile = new JBRadioButton("File:"); panel.add(radioDirectory, bag.nextLine().next().fillCellNone().weightx(0)); panel.add(directoryField, bag.next().fillCellHorizontally().weightx(1)); panel.add(radioPattern, bag.nextLine().next().fillCellNone().weightx(0)); panel.add(patternField, bag.next().fillCellHorizontally().weightx(1)); panel.add(radioFile, bag.nextLine().next().fillCellNone().weightx(0)); panel.add(fileField, bag.next().fillCellHorizontally().weightx(1)); SwingHelper.installFileCompletionAndBrowseDialog(myProject, directoryField, "Select Folder", FileChooserDescriptorFactory.createSingleFolderDescriptor()); SwingHelper.installFileCompletionAndBrowseDialog(myProject, fileField, "Select File", FileChooserDescriptorFactory.createSingleFileDescriptor()); final ButtonGroup group = new ButtonGroup(); group.add(radioPattern); group.add(radioDirectory); group.add(radioFile); radioDirectory.setSelected(true); patternField.setMinimumSize(new Dimension(JBUI.scale(200), UIUtil.getInformationIcon().getIconHeight())); patternField.getEmptyText().setText("Example: *.config.json"); final DialogBuilder builder = new DialogBuilder(); builder.setTitle("Add JSON Schema Mapping"); builder.setNorthPanel(panel); builder.setPreferredFocusComponent(directoryField); builder.setDimensionServiceKey("com.jetbrains.jsonSchema.JsonSchemaMappingsView#add"); builder.setHelpId(ADD_SCHEMA_MAPPING); final Getter<String> textGetter = new Getter<String>() { @Override public String get() { if (radioPattern.isSelected()) { return patternField.getText(); } final String text; if (radioDirectory.isSelected()) { text = directoryField.getText(); } else { text = fileField.getText(); } return getRelativePath(myProject, text); } }; final Alarm alarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD); final Runnable updaterValidator = new Runnable() { @Override public void run() { if (!patternField.isVisible()) return; patternField.setEnabled(radioPattern.isSelected()); directoryField.setEnabled(radioDirectory.isSelected()); fileField.setEnabled(radioFile.isSelected()); builder.setOkActionEnabled(!StringUtil.isEmptyOrSpaces(textGetter.get())); alarm.addRequest(this, 300, ModalityState.any()); } }; alarm.addRequest(updaterValidator, 300, ModalityState.any()); updaterValidator.run(); final ActionListener listener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { updaterValidator.run(); } }; radioPattern.addActionListener(listener); radioDirectory.addActionListener(listener); radioFile.addActionListener(listener); if (myProject == null || myProject.getBasePath() == null) { radioDirectory.setEnabled(false); radioFile.setEnabled(false); directoryField.setEnabled(false); fileField.setEnabled(false); } if (builder.showAndGet()) { final String pattern = textGetter.get(); final JsonSchemaMappingsConfigurationBase.Item item = new JsonSchemaMappingsConfigurationBase.Item(pattern, radioPattern.isSelected(), radioDirectory.isSelected()); myTableView.getListTableModel().addRow(item); //myTableView.getListTableModel().fireTableDataChanged(); } Disposer.dispose(alarm); } } private String getRelativePath(@NotNull Project project, @NotNull String text) { if (project.isDefault()) return text; final String relativePath = FileUtil.getRelativePath(new File(project.getBasePath()), new File(text)); return relativePath == null ? text : relativePath; } }
json schema, add mapping, be more sure about path not empty validation
json/src/com/jetbrains/jsonSchema/JsonSchemaMappingsView.java
json schema, add mapping, be more sure about path not empty validation
Java
apache-2.0
d41bdd48a45c71f3022003e5391249c46bdccedb
0
ftomassetti/intellij-community,orekyuu/intellij-community,supersven/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,vvv1559/intellij-community,dslomov/intellij-community,Distrotech/intellij-community,signed/intellij-community,slisson/intellij-community,orekyuu/intellij-community,MichaelNedzelsky/intellij-community,diorcety/intellij-community,lucafavatella/intellij-community,adedayo/intellij-community,apixandru/intellij-community,Distrotech/intellij-community,petteyg/intellij-community,vladmm/intellij-community,youdonghai/intellij-community,fengbaicanhe/intellij-community,supersven/intellij-community,Distrotech/intellij-community,orekyuu/intellij-community,apixandru/intellij-community,kdwink/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,jexp/idea2,clumsy/intellij-community,alphafoobar/intellij-community,dslomov/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,MichaelNedzelsky/intellij-community,clumsy/intellij-community,gnuhub/intellij-community,nicolargo/intellij-community,robovm/robovm-studio,ahb0327/intellij-community,adedayo/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,Distrotech/intellij-community,samthor/intellij-community,Distrotech/intellij-community,suncycheng/intellij-community,semonte/intellij-community,ivan-fedorov/intellij-community,robovm/robovm-studio,diorcety/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,asedunov/intellij-community,fnouama/intellij-community,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,supersven/intellij-community,nicolargo/intellij-community,adedayo/intellij-community,diorcety/intellij-community,allotria/intellij-community,allotria/intellij-community,semonte/intellij-community,ivan-fedorov/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,youdonghai/intellij-community,vladmm/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,jagguli/intellij-community,asedunov/intellij-community,ryano144/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,kool79/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,samthor/intellij-community,asedunov/intellij-community,fitermay/intellij-community,fitermay/intellij-community,holmes/intellij-community,gnuhub/intellij-community,muntasirsyed/intellij-community,samthor/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,wreckJ/intellij-community,jexp/idea2,petteyg/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,diorcety/intellij-community,vladmm/intellij-community,Lekanich/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,jagguli/intellij-community,ahb0327/intellij-community,supersven/intellij-community,petteyg/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,wreckJ/intellij-community,vladmm/intellij-community,izonder/intellij-community,jexp/idea2,pwoodworth/intellij-community,supersven/intellij-community,kool79/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,ryano144/intellij-community,blademainer/intellij-community,Lekanich/intellij-community,joewalnes/idea-community,muntasirsyed/intellij-community,dslomov/intellij-community,joewalnes/idea-community,ThiagoGarciaAlves/intellij-community,jexp/idea2,SerCeMan/intellij-community,akosyakov/intellij-community,caot/intellij-community,Lekanich/intellij-community,blademainer/intellij-community,consulo/consulo,mglukhikh/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,hurricup/intellij-community,ryano144/intellij-community,hurricup/intellij-community,fitermay/intellij-community,samthor/intellij-community,diorcety/intellij-community,fengbaicanhe/intellij-community,Lekanich/intellij-community,kdwink/intellij-community,fengbaicanhe/intellij-community,tmpgit/intellij-community,kdwink/intellij-community,Lekanich/intellij-community,ernestp/consulo,clumsy/intellij-community,signed/intellij-community,tmpgit/intellij-community,amith01994/intellij-community,hurricup/intellij-community,ryano144/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,hurricup/intellij-community,ibinti/intellij-community,slisson/intellij-community,MER-GROUP/intellij-community,Distrotech/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,semonte/intellij-community,caot/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,ftomassetti/intellij-community,allotria/intellij-community,tmpgit/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,consulo/consulo,FHannes/intellij-community,TangHao1987/intellij-community,ivan-fedorov/intellij-community,amith01994/intellij-community,ol-loginov/intellij-community,nicolargo/intellij-community,amith01994/intellij-community,ol-loginov/intellij-community,signed/intellij-community,izonder/intellij-community,amith01994/intellij-community,retomerz/intellij-community,semonte/intellij-community,tmpgit/intellij-community,orekyuu/intellij-community,alphafoobar/intellij-community,caot/intellij-community,hurricup/intellij-community,holmes/intellij-community,retomerz/intellij-community,fnouama/intellij-community,semonte/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,joewalnes/idea-community,akosyakov/intellij-community,TangHao1987/intellij-community,kool79/intellij-community,Lekanich/intellij-community,FHannes/intellij-community,gnuhub/intellij-community,Lekanich/intellij-community,fitermay/intellij-community,clumsy/intellij-community,ibinti/intellij-community,robovm/robovm-studio,blademainer/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,joewalnes/idea-community,holmes/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,caot/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,vvv1559/intellij-community,holmes/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,akosyakov/intellij-community,nicolargo/intellij-community,muntasirsyed/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,consulo/consulo,amith01994/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,SerCeMan/intellij-community,ibinti/intellij-community,amith01994/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,blademainer/intellij-community,jexp/idea2,lucafavatella/intellij-community,consulo/consulo,clumsy/intellij-community,retomerz/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community,joewalnes/idea-community,ol-loginov/intellij-community,salguarnieri/intellij-community,muntasirsyed/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,nicolargo/intellij-community,petteyg/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,ryano144/intellij-community,jagguli/intellij-community,ernestp/consulo,caot/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,TangHao1987/intellij-community,tmpgit/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,fnouama/intellij-community,suncycheng/intellij-community,izonder/intellij-community,joewalnes/idea-community,youdonghai/intellij-community,tmpgit/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,hurricup/intellij-community,kool79/intellij-community,vladmm/intellij-community,vladmm/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,slisson/intellij-community,petteyg/intellij-community,caot/intellij-community,lucafavatella/intellij-community,MichaelNedzelsky/intellij-community,ThiagoGarciaAlves/intellij-community,robovm/robovm-studio,fnouama/intellij-community,xfournet/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,samthor/intellij-community,ryano144/intellij-community,fengbaicanhe/intellij-community,lucafavatella/intellij-community,tmpgit/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,blademainer/intellij-community,wreckJ/intellij-community,tmpgit/intellij-community,alphafoobar/intellij-community,vladmm/intellij-community,allotria/intellij-community,wreckJ/intellij-community,jexp/idea2,Distrotech/intellij-community,fengbaicanhe/intellij-community,alphafoobar/intellij-community,slisson/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,ahb0327/intellij-community,ThiagoGarciaAlves/intellij-community,ol-loginov/intellij-community,retomerz/intellij-community,supersven/intellij-community,xfournet/intellij-community,joewalnes/idea-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,petteyg/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,fitermay/intellij-community,robovm/robovm-studio,SerCeMan/intellij-community,amith01994/intellij-community,retomerz/intellij-community,clumsy/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,robovm/robovm-studio,MichaelNedzelsky/intellij-community,TangHao1987/intellij-community,fnouama/intellij-community,ThiagoGarciaAlves/intellij-community,supersven/intellij-community,da1z/intellij-community,fnouama/intellij-community,pwoodworth/intellij-community,ivan-fedorov/intellij-community,diorcety/intellij-community,TangHao1987/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,samthor/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,vladmm/intellij-community,ryano144/intellij-community,semonte/intellij-community,retomerz/intellij-community,TangHao1987/intellij-community,hurricup/intellij-community,adedayo/intellij-community,retomerz/intellij-community,petteyg/intellij-community,ibinti/intellij-community,apixandru/intellij-community,blademainer/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,ftomassetti/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,amith01994/intellij-community,semonte/intellij-community,supersven/intellij-community,ivan-fedorov/intellij-community,Distrotech/intellij-community,tmpgit/intellij-community,izonder/intellij-community,SerCeMan/intellij-community,orekyuu/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,pwoodworth/intellij-community,orekyuu/intellij-community,akosyakov/intellij-community,slisson/intellij-community,holmes/intellij-community,gnuhub/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,xfournet/intellij-community,caot/intellij-community,pwoodworth/intellij-community,apixandru/intellij-community,izonder/intellij-community,fengbaicanhe/intellij-community,ernestp/consulo,idea4bsd/idea4bsd,adedayo/intellij-community,alphafoobar/intellij-community,MichaelNedzelsky/intellij-community,SerCeMan/intellij-community,jexp/idea2,petteyg/intellij-community,izonder/intellij-community,ernestp/consulo,blademainer/intellij-community,ahb0327/intellij-community,suncycheng/intellij-community,muntasirsyed/intellij-community,slisson/intellij-community,jexp/idea2,mglukhikh/intellij-community,slisson/intellij-community,ivan-fedorov/intellij-community,pwoodworth/intellij-community,joewalnes/idea-community,robovm/robovm-studio,kdwink/intellij-community,akosyakov/intellij-community,signed/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,fnouama/intellij-community,clumsy/intellij-community,da1z/intellij-community,signed/intellij-community,vladmm/intellij-community,caot/intellij-community,gnuhub/intellij-community,ftomassetti/intellij-community,diorcety/intellij-community,fitermay/intellij-community,ahb0327/intellij-community,michaelgallacher/intellij-community,akosyakov/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,ivan-fedorov/intellij-community,allotria/intellij-community,vladmm/intellij-community,adedayo/intellij-community,vladmm/intellij-community,holmes/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,alphafoobar/intellij-community,ahb0327/intellij-community,ftomassetti/intellij-community,holmes/intellij-community,kdwink/intellij-community,signed/intellij-community,signed/intellij-community,FHannes/intellij-community,petteyg/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,ryano144/intellij-community,ernestp/consulo,signed/intellij-community,amith01994/intellij-community,allotria/intellij-community,kool79/intellij-community,ol-loginov/intellij-community,jagguli/intellij-community,dslomov/intellij-community,FHannes/intellij-community,jagguli/intellij-community,apixandru/intellij-community,xfournet/intellij-community,nicolargo/intellij-community,suncycheng/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,amith01994/intellij-community,ibinti/intellij-community,dslomov/intellij-community,samthor/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,caot/intellij-community,ibinti/intellij-community,ernestp/consulo,dslomov/intellij-community,kool79/intellij-community,fitermay/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,MichaelNedzelsky/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,signed/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,MER-GROUP/intellij-community,jagguli/intellij-community,ryano144/intellij-community,diorcety/intellij-community,adedayo/intellij-community,holmes/intellij-community,alphafoobar/intellij-community,da1z/intellij-community,fnouama/intellij-community,fnouama/intellij-community,allotria/intellij-community,da1z/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,amith01994/intellij-community,fitermay/intellij-community,da1z/intellij-community,xfournet/intellij-community,retomerz/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,wreckJ/intellij-community,ahb0327/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,fitermay/intellij-community,allotria/intellij-community,da1z/intellij-community,Distrotech/intellij-community,vvv1559/intellij-community,caot/intellij-community,asedunov/intellij-community,clumsy/intellij-community,ryano144/intellij-community,ahb0327/intellij-community,da1z/intellij-community,semonte/intellij-community,xfournet/intellij-community,Lekanich/intellij-community,robovm/robovm-studio,salguarnieri/intellij-community,FHannes/intellij-community,alphafoobar/intellij-community,MichaelNedzelsky/intellij-community,MER-GROUP/intellij-community,jagguli/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,adedayo/intellij-community,SerCeMan/intellij-community,vvv1559/intellij-community,fengbaicanhe/intellij-community,kool79/intellij-community,salguarnieri/intellij-community,alphafoobar/intellij-community,idea4bsd/idea4bsd,MER-GROUP/intellij-community,FHannes/intellij-community,gnuhub/intellij-community,SerCeMan/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,tmpgit/intellij-community,gnuhub/intellij-community,hurricup/intellij-community,slisson/intellij-community,ryano144/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,diorcety/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,ThiagoGarciaAlves/intellij-community,supersven/intellij-community,alphafoobar/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,adedayo/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,wreckJ/intellij-community,robovm/robovm-studio,pwoodworth/intellij-community,hurricup/intellij-community,apixandru/intellij-community,joewalnes/idea-community,TangHao1987/intellij-community,clumsy/intellij-community,ivan-fedorov/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,semonte/intellij-community,allotria/intellij-community,samthor/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,retomerz/intellij-community,kdwink/intellij-community,ftomassetti/intellij-community,MER-GROUP/intellij-community,fengbaicanhe/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,holmes/intellij-community,samthor/intellij-community,da1z/intellij-community,SerCeMan/intellij-community,orekyuu/intellij-community,signed/intellij-community,izonder/intellij-community,tmpgit/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,tmpgit/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,asedunov/intellij-community,da1z/intellij-community,retomerz/intellij-community,jagguli/intellij-community,SerCeMan/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,petteyg/intellij-community,lucafavatella/intellij-community,caot/intellij-community,asedunov/intellij-community,amith01994/intellij-community,lucafavatella/intellij-community,caot/intellij-community,adedayo/intellij-community,suncycheng/intellij-community,consulo/consulo,izonder/intellij-community,robovm/robovm-studio,SerCeMan/intellij-community,holmes/intellij-community,muntasirsyed/intellij-community,fnouama/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,mglukhikh/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,dslomov/intellij-community,da1z/intellij-community,apixandru/intellij-community,petteyg/intellij-community,signed/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,muntasirsyed/intellij-community,samthor/intellij-community,orekyuu/intellij-community,gnuhub/intellij-community,robovm/robovm-studio,hurricup/intellij-community,supersven/intellij-community,kdwink/intellij-community,orekyuu/intellij-community,adedayo/intellij-community,kool79/intellij-community,orekyuu/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,FHannes/intellij-community,izonder/intellij-community,kdwink/intellij-community,retomerz/intellij-community,ibinti/intellij-community,diorcety/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,holmes/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,robovm/robovm-studio,nicolargo/intellij-community,ol-loginov/intellij-community,adedayo/intellij-community,izonder/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,FHannes/intellij-community,kool79/intellij-community,ibinti/intellij-community,clumsy/intellij-community,FHannes/intellij-community,slisson/intellij-community,fengbaicanhe/intellij-community,mglukhikh/intellij-community,kool79/intellij-community,Lekanich/intellij-community,slisson/intellij-community,consulo/consulo,FHannes/intellij-community,slisson/intellij-community,MER-GROUP/intellij-community,holmes/intellij-community,pwoodworth/intellij-community,petteyg/intellij-community,MichaelNedzelsky/intellij-community,Lekanich/intellij-community,muntasirsyed/intellij-community,signed/intellij-community
/* * Copyright (c) 2000-2006 JetBrains s.r.o. All Rights Reserved. */ /* * Created by IntelliJ IDEA. * User: yole * Date: 17.11.2006 * Time: 17:08:11 */ package com.intellij.openapi.vcs.changes.patch; import com.intellij.openapi.actionSystem.ActionPlaces; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.DataKeys; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.diff.ActionButtonPresentation; import com.intellij.openapi.diff.DiffManager; import com.intellij.openapi.diff.DiffRequestFactory; import com.intellij.openapi.diff.MergeRequest; import com.intellij.openapi.diff.impl.patch.ApplyPatchContext; import com.intellij.openapi.diff.impl.patch.ApplyPatchException; import com.intellij.openapi.diff.impl.patch.ApplyPatchStatus; import com.intellij.openapi.diff.impl.patch.FilePatch; import com.intellij.openapi.fileEditor.impl.LoadTextUtil; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.FileTypeManager; import com.intellij.openapi.fileTypes.StdFileTypes; import com.intellij.openapi.fileTypes.ex.FileTypeChooser; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.Ref; import com.intellij.openapi.vcs.VcsBundle; import com.intellij.openapi.vcs.FilePath; import com.intellij.openapi.vcs.ProjectLevelVcsManager; import com.intellij.openapi.vfs.ReadonlyStatusHandler; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.peer.PeerFactory; import com.intellij.util.Processor; import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class ApplyPatchAction extends AnAction { private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.vcs.changes.patch.ApplyPatchAction"); public void actionPerformed(AnActionEvent e) { final Project project = e.getData(DataKeys.PROJECT); final ApplyPatchDialog dialog = new ApplyPatchDialog(project); final VirtualFile vFile = e.getData(DataKeys.VIRTUAL_FILE); if (vFile != null && vFile.getFileType() == StdFileTypes.PATCH) { dialog.setFileName(vFile.getPresentableUrl()); } dialog.show(); if (dialog.getExitCode() != DialogWrapper.OK_EXIT_CODE) { return; } applyPatch(project, dialog.getPatches(), dialog.getApplyPatchContext()); } public static ApplyPatchStatus applyPatch(final Project project, final List<FilePatch> patches, final ApplyPatchContext context) { List<VirtualFile> filesToMakeWritable = new ArrayList<VirtualFile>(); if (!prepareFiles(project, patches, context, filesToMakeWritable)) { return ApplyPatchStatus.FAILURE; } final VirtualFile[] fileArray = filesToMakeWritable.toArray(new VirtualFile[filesToMakeWritable.size()]); final ReadonlyStatusHandler.OperationStatus readonlyStatus = ReadonlyStatusHandler.getInstance(project).ensureFilesWritable(fileArray); if (readonlyStatus.hasReadonlyFiles()) { return ApplyPatchStatus.FAILURE; } return applyFilePatches(project, patches, context, null); } public static ApplyPatchStatus applyFilePatches(final Project project, final List<FilePatch> patches, final ApplyPatchContext context, @Nullable final List<FilePath> affectedFiles) { final Ref<ApplyPatchStatus> statusRef = new Ref<ApplyPatchStatus>(); ApplicationManager.getApplication().runWriteAction(new Runnable() { public void run() { CommandProcessor.getInstance().executeCommand(project, new Runnable() { public void run() { ApplyPatchStatus status = null; for(FilePatch patch: patches) { final ApplyPatchStatus patchStatus = applySinglePatch(project, patch, context, affectedFiles); status = ApplyPatchStatus.and(status, patchStatus); } try { context.applyPendingRenames(); } catch (IOException e) { Messages.showErrorDialog(project, "Error renaming directories: " + e.getMessage(), VcsBundle.message("patch.apply.dialog.title")); } if (status == ApplyPatchStatus.ALREADY_APPLIED) { Messages.showInfoMessage(project, VcsBundle.message("patch.apply.already.applied"), VcsBundle.message("patch.apply.dialog.title")); } else if (status == ApplyPatchStatus.PARTIAL) { Messages.showInfoMessage(project, VcsBundle.message("patch.apply.partially.applied"), VcsBundle.message("patch.apply.dialog.title")); } statusRef.set(status); } }, VcsBundle.message("patch.apply.command"), null); } }); return statusRef.get(); } public static boolean prepareFiles(final Project project, final List<FilePatch> patches, final ApplyPatchContext context, final List<VirtualFile> filesToMakeWritable) { for(FilePatch patch: patches) { VirtualFile fileToPatch; try { fileToPatch = patch.findFileToPatch(context.getPrepareContext()); } catch (IOException e) { Messages.showErrorDialog(project, "Error when searching for file to patch: " + patch.getBeforeName() + ": " + e.getMessage(), "Apply Patch"); return false; } // security check to avoid overwriting system files with a patch if (fileToPatch != null && !ProjectRootManager.getInstance(project).getFileIndex().isInContent(fileToPatch) && ProjectLevelVcsManager.getInstance(project).getVcsRootFor(fileToPatch) == null) { Messages.showErrorDialog(project, "File to patch found outside content root: " + patch.getBeforeName(), "Apply Patch"); return false; } if (fileToPatch != null && !fileToPatch.isDirectory()) { filesToMakeWritable.add(fileToPatch); FileType fileType = fileToPatch.getFileType(); if (fileType == StdFileTypes.UNKNOWN) { fileType = FileTypeChooser.associateFileType(fileToPatch.getPresentableName()); if (fileType == null) { return false; } } } else if (patch.isNewFile()) { FileType fileType = FileTypeManager.getInstance().getFileTypeByFileName(patch.getBeforeFileName()); if (fileType == StdFileTypes.UNKNOWN) { fileType = FileTypeChooser.associateFileType(patch.getBeforeFileName()); if (fileType == null) { return false; } } } } return true; } private static ApplyPatchStatus applySinglePatch(final Project project, final FilePatch patch, final ApplyPatchContext context, @Nullable final List<FilePath> affectedFiles) { VirtualFile file; try { file = patch.findFileToPatch(context); } catch (IOException e) { Messages.showErrorDialog(project, "Error when searching for file to patch: " + patch.getBeforeName() + ": " + e.getMessage(), "Apply Patch"); return ApplyPatchStatus.FAILURE; } if (file == null) { Messages.showErrorDialog(project, "Cannot find file to patch: " + patch.getBeforeName(), "Apply Patch"); return ApplyPatchStatus.FAILURE; } try { if (affectedFiles != null) { affectedFiles.add(patch.getTarget(file)); } return patch.apply(file); } catch(ApplyPatchException ex) { if (!patch.isNewFile() && !patch.isDeletedFile()) { final DefaultPatchBaseVersionProvider provider = new DefaultPatchBaseVersionProvider(project); if (provider.canProvideContent(file, patch.getBeforeVersionId())) { final StringBuilder newText = new StringBuilder(); final Ref<CharSequence> contentRef = new Ref<CharSequence>(); final Ref<ApplyPatchStatus> statusRef = new Ref<ApplyPatchStatus>(); provider.getBaseVersionContent(file, patch.getBeforeVersionId(), new Processor<CharSequence>() { public boolean process(final CharSequence text) { newText.setLength(0); try { statusRef.set(patch.applyModifications(text, newText)); } catch(ApplyPatchException ex) { return true; // continue to older versions } contentRef.set(text); return false; } }); ApplyPatchStatus status = statusRef.get(); if (status != null) { if (status != ApplyPatchStatus.ALREADY_APPLIED) { return showMergeDialog(project, file, contentRef.get(), newText.toString()); } else { return status; } } } } Messages.showErrorDialog(project, VcsBundle.message("patch.apply.error", patch.getBeforeName(), ex.getMessage()), VcsBundle.message("patch.apply.dialog.title")); } catch (Exception ex) { LOG.error(ex); } return ApplyPatchStatus.FAILURE; } private static ApplyPatchStatus showMergeDialog(Project project, VirtualFile file, CharSequence content, final String patchedContent) { final DiffRequestFactory diffRequestFactory = PeerFactory.getInstance().getDiffRequestFactory(); CharSequence fileContent = LoadTextUtil.loadText(file); final MergeRequest request = diffRequestFactory.createMergeRequest(fileContent.toString(), patchedContent, content.toString(), file, project, ActionButtonPresentation.createApplyButton()); request.setVersionTitles(new String[] { VcsBundle.message("patch.apply.conflict.local.version"), VcsBundle.message("patch.apply.conflict.merged.version"), VcsBundle.message("patch.apply.conflict.patched.version") }); request.setWindowTitle(VcsBundle.message("patch.apply.conflict.title", file.getPresentableUrl())); DiffManager.getInstance().getDiffTool().show(request); if (request.getResult() == DialogWrapper.OK_EXIT_CODE) { return ApplyPatchStatus.SUCCESS; } return ApplyPatchStatus.FAILURE; } @Override public void update(AnActionEvent e) { Project project = e.getData(DataKeys.PROJECT); if (e.getPlace() == ActionPlaces.PROJECT_VIEW_POPUP) { VirtualFile vFile = e.getData(DataKeys.VIRTUAL_FILE); e.getPresentation().setVisible(project != null && vFile != null && vFile.getFileType() == StdFileTypes.PATCH); } else { e.getPresentation().setEnabled(project != null); } } }
source/com/intellij/openapi/vcs/changes/patch/ApplyPatchAction.java
/* * Copyright (c) 2000-2006 JetBrains s.r.o. All Rights Reserved. */ /* * Created by IntelliJ IDEA. * User: yole * Date: 17.11.2006 * Time: 17:08:11 */ package com.intellij.openapi.vcs.changes.patch; import com.intellij.openapi.actionSystem.ActionPlaces; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.DataKeys; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.diff.ActionButtonPresentation; import com.intellij.openapi.diff.DiffManager; import com.intellij.openapi.diff.DiffRequestFactory; import com.intellij.openapi.diff.MergeRequest; import com.intellij.openapi.diff.impl.patch.ApplyPatchContext; import com.intellij.openapi.diff.impl.patch.ApplyPatchException; import com.intellij.openapi.diff.impl.patch.ApplyPatchStatus; import com.intellij.openapi.diff.impl.patch.FilePatch; import com.intellij.openapi.fileEditor.impl.LoadTextUtil; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.FileTypeManager; import com.intellij.openapi.fileTypes.StdFileTypes; import com.intellij.openapi.fileTypes.ex.FileTypeChooser; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.Ref; import com.intellij.openapi.vcs.VcsBundle; import com.intellij.openapi.vcs.FilePath; import com.intellij.openapi.vfs.ReadonlyStatusHandler; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.peer.PeerFactory; import com.intellij.util.Processor; import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class ApplyPatchAction extends AnAction { private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.vcs.changes.patch.ApplyPatchAction"); public void actionPerformed(AnActionEvent e) { final Project project = e.getData(DataKeys.PROJECT); final ApplyPatchDialog dialog = new ApplyPatchDialog(project); final VirtualFile vFile = e.getData(DataKeys.VIRTUAL_FILE); if (vFile != null && vFile.getFileType() == StdFileTypes.PATCH) { dialog.setFileName(vFile.getPresentableUrl()); } dialog.show(); if (dialog.getExitCode() != DialogWrapper.OK_EXIT_CODE) { return; } applyPatch(project, dialog.getPatches(), dialog.getApplyPatchContext()); } public static ApplyPatchStatus applyPatch(final Project project, final List<FilePatch> patches, final ApplyPatchContext context) { List<VirtualFile> filesToMakeWritable = new ArrayList<VirtualFile>(); if (!prepareFiles(project, patches, context, filesToMakeWritable)) { return ApplyPatchStatus.FAILURE; } final VirtualFile[] fileArray = filesToMakeWritable.toArray(new VirtualFile[filesToMakeWritable.size()]); final ReadonlyStatusHandler.OperationStatus readonlyStatus = ReadonlyStatusHandler.getInstance(project).ensureFilesWritable(fileArray); if (readonlyStatus.hasReadonlyFiles()) { return ApplyPatchStatus.FAILURE; } return applyFilePatches(project, patches, context, null); } public static ApplyPatchStatus applyFilePatches(final Project project, final List<FilePatch> patches, final ApplyPatchContext context, @Nullable final List<FilePath> affectedFiles) { final Ref<ApplyPatchStatus> statusRef = new Ref<ApplyPatchStatus>(); ApplicationManager.getApplication().runWriteAction(new Runnable() { public void run() { CommandProcessor.getInstance().executeCommand(project, new Runnable() { public void run() { ApplyPatchStatus status = null; for(FilePatch patch: patches) { final ApplyPatchStatus patchStatus = applySinglePatch(project, patch, context, affectedFiles); status = ApplyPatchStatus.and(status, patchStatus); } try { context.applyPendingRenames(); } catch (IOException e) { Messages.showErrorDialog(project, "Error renaming directories: " + e.getMessage(), VcsBundle.message("patch.apply.dialog.title")); } if (status == ApplyPatchStatus.ALREADY_APPLIED) { Messages.showInfoMessage(project, VcsBundle.message("patch.apply.already.applied"), VcsBundle.message("patch.apply.dialog.title")); } else if (status == ApplyPatchStatus.PARTIAL) { Messages.showInfoMessage(project, VcsBundle.message("patch.apply.partially.applied"), VcsBundle.message("patch.apply.dialog.title")); } statusRef.set(status); } }, VcsBundle.message("patch.apply.command"), null); } }); return statusRef.get(); } public static boolean prepareFiles(final Project project, final List<FilePatch> patches, final ApplyPatchContext context, final List<VirtualFile> filesToMakeWritable) { for(FilePatch patch: patches) { VirtualFile fileToPatch; try { fileToPatch = patch.findFileToPatch(context.getPrepareContext()); } catch (IOException e) { Messages.showErrorDialog(project, "Error when searching for file to patch: " + patch.getBeforeName() + ": " + e.getMessage(), "Apply Patch"); return false; } // security check to avoid overwriting system files with a patch if (fileToPatch != null && !ProjectRootManager.getInstance(project).getFileIndex().isInContent(fileToPatch)) { Messages.showErrorDialog(project, "File to patch found outside content root: " + patch.getBeforeName(), "Apply Patch"); return false; } if (fileToPatch != null && !fileToPatch.isDirectory()) { filesToMakeWritable.add(fileToPatch); FileType fileType = fileToPatch.getFileType(); if (fileType == StdFileTypes.UNKNOWN) { fileType = FileTypeChooser.associateFileType(fileToPatch.getPresentableName()); if (fileType == null) { return false; } } } else if (patch.isNewFile()) { FileType fileType = FileTypeManager.getInstance().getFileTypeByFileName(patch.getBeforeFileName()); if (fileType == StdFileTypes.UNKNOWN) { fileType = FileTypeChooser.associateFileType(patch.getBeforeFileName()); if (fileType == null) { return false; } } } } return true; } private static ApplyPatchStatus applySinglePatch(final Project project, final FilePatch patch, final ApplyPatchContext context, @Nullable final List<FilePath> affectedFiles) { VirtualFile file; try { file = patch.findFileToPatch(context); } catch (IOException e) { Messages.showErrorDialog(project, "Error when searching for file to patch: " + patch.getBeforeName() + ": " + e.getMessage(), "Apply Patch"); return ApplyPatchStatus.FAILURE; } if (file == null) { Messages.showErrorDialog(project, "Cannot find file to patch: " + patch.getBeforeName(), "Apply Patch"); return ApplyPatchStatus.FAILURE; } try { if (affectedFiles != null) { affectedFiles.add(patch.getTarget(file)); } return patch.apply(file); } catch(ApplyPatchException ex) { if (!patch.isNewFile() && !patch.isDeletedFile()) { final DefaultPatchBaseVersionProvider provider = new DefaultPatchBaseVersionProvider(project); if (provider.canProvideContent(file, patch.getBeforeVersionId())) { final StringBuilder newText = new StringBuilder(); final Ref<CharSequence> contentRef = new Ref<CharSequence>(); final Ref<ApplyPatchStatus> statusRef = new Ref<ApplyPatchStatus>(); provider.getBaseVersionContent(file, patch.getBeforeVersionId(), new Processor<CharSequence>() { public boolean process(final CharSequence text) { newText.setLength(0); try { statusRef.set(patch.applyModifications(text, newText)); } catch(ApplyPatchException ex) { return true; // continue to older versions } contentRef.set(text); return false; } }); ApplyPatchStatus status = statusRef.get(); if (status != null) { if (status != ApplyPatchStatus.ALREADY_APPLIED) { return showMergeDialog(project, file, contentRef.get(), newText.toString()); } else { return status; } } } } Messages.showErrorDialog(project, VcsBundle.message("patch.apply.error", patch.getBeforeName(), ex.getMessage()), VcsBundle.message("patch.apply.dialog.title")); } catch (Exception ex) { LOG.error(ex); } return ApplyPatchStatus.FAILURE; } private static ApplyPatchStatus showMergeDialog(Project project, VirtualFile file, CharSequence content, final String patchedContent) { final DiffRequestFactory diffRequestFactory = PeerFactory.getInstance().getDiffRequestFactory(); CharSequence fileContent = LoadTextUtil.loadText(file); final MergeRequest request = diffRequestFactory.createMergeRequest(fileContent.toString(), patchedContent, content.toString(), file, project, ActionButtonPresentation.createApplyButton()); request.setVersionTitles(new String[] { VcsBundle.message("patch.apply.conflict.local.version"), VcsBundle.message("patch.apply.conflict.merged.version"), VcsBundle.message("patch.apply.conflict.patched.version") }); request.setWindowTitle(VcsBundle.message("patch.apply.conflict.title", file.getPresentableUrl())); DiffManager.getInstance().getDiffTool().show(request); if (request.getResult() == DialogWrapper.OK_EXIT_CODE) { return ApplyPatchStatus.SUCCESS; } return ApplyPatchStatus.FAILURE; } @Override public void update(AnActionEvent e) { Project project = e.getData(DataKeys.PROJECT); if (e.getPlace() == ActionPlaces.PROJECT_VIEW_POPUP) { VirtualFile vFile = e.getData(DataKeys.VIRTUAL_FILE); e.getPresentation().setVisible(project != null && vFile != null && vFile.getFileType() == StdFileTypes.PATCH); } else { e.getPresentation().setEnabled(project != null); } } }
relax restriction on out-of-content patches (IDEADEV-16706)
source/com/intellij/openapi/vcs/changes/patch/ApplyPatchAction.java
relax restriction on out-of-content patches (IDEADEV-16706)
Java
apache-2.0
5c21569cd532ae06c4a7a4580446ebe43903085d
0
Toporin/BitcoinWallet,ScripterRon/BitcoinWallet,ScripterRon/BitcoinWallet
/** * Copyright 2013-2014 Ronald W Hoffman * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ScripterRon.BitcoinWallet; import org.ScripterRon.BitcoinCore.Address; import org.ScripterRon.BitcoinCore.ECKey; import org.ScripterRon.BitcoinCore.OutPoint; import org.ScripterRon.BitcoinCore.SignedInput; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; /** * Build the input list for a new transaction */ public class BuildInputList { /** * Build the signed input list for creating a new transaction. The list will not * include pending transactions, spent transactions or transactions in the safe. * A coinbase transaction must be mature before it can be spent. * * @return Signed input list * @throws WalletException Unable to get list of unspent outputs */ public static List<SignedInput> buildSignedInputs() throws WalletException { List<SignedInput> inputList = new LinkedList<>(); // // Get the list of available transaction outputs // List<ReceiveTransaction> txList = Parameters.wallet.getReceiveTxList(); Iterator<ReceiveTransaction> it = txList.iterator(); while (it.hasNext()) { ReceiveTransaction tx = it.next(); if (tx.inSafe() || tx.isSpent()) { it.remove(); } else { int depth = Parameters.wallet.getTxDepth(tx.getTxHash()); if ((tx.isCoinBase() && depth < Parameters.COINBASE_MATURITY) || (!tx.isCoinBase() && depth < 1)) { it.remove(); } } } // // Sort the unspent outputs based on their value // Collections.sort(txList, (ReceiveTransaction rcv1, ReceiveTransaction rcv2) -> rcv1.getValue().compareTo(rcv2.getValue())); // // Build the list of signed inputs // for (ReceiveTransaction rcvTx : txList) { Address outAddress = rcvTx.getAddress(); ECKey key = null; for (ECKey chkKey : Parameters.keys) { if (Arrays.equals(chkKey.getPubKeyHash(), outAddress.getHash())) { key = chkKey; break; } } if (key == null) throw new WalletException(String.format("No key available for transaction output\n %s : %d", rcvTx.getTxHash().toString(), rcvTx.getTxIndex())); OutPoint outPoint = new OutPoint(rcvTx.getTxHash(), rcvTx.getTxIndex()); SignedInput input = new SignedInput(key, outPoint, rcvTx.getValue(), rcvTx.getScriptBytes()); inputList.add(input); } return inputList; } }
src/main/java/org/ScripterRon/BitcoinWallet/BuildInputList.java
/** * Copyright 2013-2014 Ronald W Hoffman * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ScripterRon.BitcoinWallet; import org.ScripterRon.BitcoinCore.Address; import org.ScripterRon.BitcoinCore.ECKey; import org.ScripterRon.BitcoinCore.OutPoint; import org.ScripterRon.BitcoinCore.SignedInput; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; /** * Build the input list for a new transaction */ public class BuildInputList { /** * Build the signed input list for creating a new transaction. The list will not * include unconfirmed transactions, spent transactions or transactions in the safe. * * @return Signed input list * @throws WalletException Unable to get list of unspent outputs */ public static List<SignedInput> buildSignedInputs() throws WalletException { List<SignedInput> inputList = new LinkedList<>(); // // Get the list of available transaction outputs // List<ReceiveTransaction> txList = Parameters.wallet.getReceiveTxList(); Iterator<ReceiveTransaction> it = txList.iterator(); while (it.hasNext()) { ReceiveTransaction tx = it.next(); if (tx.inSafe() || tx.isSpent()) { it.remove(); } else { int depth = Parameters.wallet.getTxDepth(tx.getTxHash()); if ((tx.isCoinBase() && depth < Parameters.COINBASE_MATURITY) || (!tx.isCoinBase() && depth < Parameters.TRANSACTION_CONFIRMED)) { it.remove(); } } } // // Sort the unspent outputs based on their value // Collections.sort(txList, (ReceiveTransaction rcv1, ReceiveTransaction rcv2) -> rcv1.getValue().compareTo(rcv2.getValue())); // // Build the list of signed inputs // for (ReceiveTransaction rcvTx : txList) { Address outAddress = rcvTx.getAddress(); ECKey key = null; for (ECKey chkKey : Parameters.keys) { if (Arrays.equals(chkKey.getPubKeyHash(), outAddress.getHash())) { key = chkKey; break; } } if (key == null) throw new WalletException(String.format("No key available for transaction output\n %s : %d", rcvTx.getTxHash().toString(), rcvTx.getTxIndex())); OutPoint outPoint = new OutPoint(rcvTx.getTxHash(), rcvTx.getTxIndex()); SignedInput input = new SignedInput(key, outPoint, rcvTx.getValue(), rcvTx.getScriptBytes()); inputList.add(input); } return inputList; } }
Allow building/confirmed transactions to be spent
src/main/java/org/ScripterRon/BitcoinWallet/BuildInputList.java
Allow building/confirmed transactions to be spent
Java
apache-2.0
587a4831d34c868b607d22a53dd8f281e7347ecc
0
donNewtonAlpha/onos,donNewtonAlpha/onos,y-higuchi/onos,y-higuchi/onos,kuujo/onos,opennetworkinglab/onos,oplinkoms/onos,LorenzReinhart/ONOSnew,oplinkoms/onos,oplinkoms/onos,oplinkoms/onos,donNewtonAlpha/onos,gkatsikas/onos,kuujo/onos,y-higuchi/onos,gkatsikas/onos,osinstom/onos,opennetworkinglab/onos,donNewtonAlpha/onos,sdnwiselab/onos,sdnwiselab/onos,oplinkoms/onos,LorenzReinhart/ONOSnew,sdnwiselab/onos,sdnwiselab/onos,LorenzReinhart/ONOSnew,osinstom/onos,opennetworkinglab/onos,sdnwiselab/onos,kuujo/onos,y-higuchi/onos,opennetworkinglab/onos,oplinkoms/onos,LorenzReinhart/ONOSnew,LorenzReinhart/ONOSnew,osinstom/onos,opennetworkinglab/onos,gkatsikas/onos,kuujo/onos,kuujo/onos,kuujo/onos,sdnwiselab/onos,opennetworkinglab/onos,y-higuchi/onos,kuujo/onos,donNewtonAlpha/onos,osinstom/onos,gkatsikas/onos,gkatsikas/onos,oplinkoms/onos,gkatsikas/onos,osinstom/onos
/* * Copyright 2016-present Open Networking Laboratory * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.bgp.cli; import org.apache.karaf.shell.commands.Argument; import org.apache.karaf.shell.commands.Command; import org.onosproject.bgp.controller.BgpController; import org.onosproject.bgp.controller.BgpLocalRib; import org.onosproject.bgpio.protocol.BgpLSNlri; import org.onosproject.bgpio.protocol.linkstate.BgpNodeLSIdentifier; import org.onosproject.bgpio.protocol.linkstate.BgpNodeLSNlriVer4; import org.onosproject.bgpio.protocol.linkstate.PathAttrNlriDetails; import org.onosproject.bgpio.protocol.linkstate.PathAttrNlriDetailsLocalRib; import org.onosproject.bgpio.protocol.linkstate.BgpLinkLSIdentifier; import org.onosproject.bgpio.protocol.linkstate.BgpPrefixLSIdentifier; import org.onosproject.bgpio.protocol.linkstate.NodeDescriptors; import org.onosproject.bgpio.protocol.linkstate.BgpLinkLsNlriVer4; import org.onosproject.bgpio.types.IPv4AddressTlv; import org.onosproject.bgpio.types.RouteDistinguisher; import org.onosproject.bgpio.types.BgpValueType; import org.onosproject.bgpio.types.LinkStateAttributes; import org.onosproject.bgpio.types.MpReachNlri; import org.onosproject.bgpio.types.AutonomousSystemTlv; import org.onosproject.bgpio.types.IsIsNonPseudonode; import org.onosproject.bgpio.types.LocalPref; import org.onosproject.bgpio.types.Origin; import org.onosproject.bgpio.types.attr.BgpAttrRouterIdV4; import org.onosproject.bgpio.types.attr.BgpLinkAttrMaxLinkBandwidth; import org.onosproject.bgpio.types.attr.BgpLinkAttrUnRsrvdLinkBandwidth; import org.onosproject.bgpio.types.attr.BgpLinkAttrTeDefaultMetric; import org.onosproject.bgpio.types.attr.BgpLinkAttrIgpMetric; import org.onosproject.cli.AbstractShellCommand; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map; import java.util.Set; import java.util.List; import java.util.Iterator; import java.util.Arrays; @Command(scope = "onos", name = "bgp-rib", description = "lists RIB configuration") public class BgpLocalRibDisplay extends AbstractShellCommand { private static final Logger log = LoggerFactory.getLogger(BgpLocalRibDisplay.class); private static final String NODETREE = "nodes"; private static final String LINKTREE = "links"; private static final String PREFIXTREE = "prefix"; private static final String VPNNODETREE = "vpnnodes"; private static final String VPNLINKTREE = "vpnlinkS"; private static final String VPNPREFIXTREE = "vpnprefix"; protected Origin origin; protected LocalPref localPref; protected BgpAttrRouterIdV4 bgpAttrRouterIdV4; protected IsIsNonPseudonode isIsNonPseudonode; protected AutonomousSystemTlv autonomousSystemTlv; protected IPv4AddressTlv iPv4AddressTlv; protected BgpLinkAttrMaxLinkBandwidth bgpLinkAttrMaxLinkBandwidth; protected BgpLinkAttrUnRsrvdLinkBandwidth bgpLinkAttrUnRsrvdLinkBandwidth; protected BgpLinkAttrTeDefaultMetric bgpLinkAttrTeDefaultMetric; protected BgpLinkAttrIgpMetric bgpLinkAttrIgpMetric; protected PathAttrNlriDetailsLocalRib pathAttrNlriDetailsLocalRib; protected MpReachNlri mpReachNlri; protected PathAttrNlriDetails pathAttrNlriDetails; protected BgpNodeLSNlriVer4.ProtocolType protocolType; protected BgpController bgpController = get(BgpController.class); protected BgpLocalRib bgpLocalRib = bgpController.bgpLocalRib(); Map<BgpNodeLSIdentifier, PathAttrNlriDetailsLocalRib> nodeTreeMap = bgpLocalRib.nodeTree(); Set<BgpNodeLSIdentifier> nodekeySet = nodeTreeMap.keySet(); Map<BgpLinkLSIdentifier, PathAttrNlriDetailsLocalRib> linkTreeMap = bgpLocalRib.linkTree(); Set<BgpLinkLSIdentifier> linkkeySet = linkTreeMap.keySet(); @Argument(index = 0, name = "name", description = "nodetree" + "\n" + "linktree" + "\n" + "prefixtree" + "\n" + "vpnnodetree" + "\n" + "vpnlinktree" + "\n" + "vpnprefixtree", required = true, multiValued = false) String name = null; @Argument(index = 1, name = "numberofentries", description = "numberofentries", required = false, multiValued = false) int numberofentries; @Argument(index = 2, name = "vpnId", description = "vpnId", required = false, multiValued = false) String vpnId = null; private int count = 0; @Override protected void execute() { switch (name) { case NODETREE: displayNodes(); break; case LINKTREE: displayLinks(); break; case PREFIXTREE: displayPrefix(); break; case VPNNODETREE: displayVpnNodes(); break; case VPNLINKTREE: displayVpnLinks(); break; case VPNPREFIXTREE: displayVpnPrefix(); break; default: System.out.print("Unknown Command"); break; } } private void displayNodes() { try { int counter = 0; print("Total number of entries = %s", nodeTreeMap.size()); for (BgpNodeLSIdentifier nodes : nodekeySet) { if (numberofentries > nodeTreeMap.size() || numberofentries < 0) { System.out.print("Wrong Argument"); break; } else if (counter < numberofentries) { pathAttrNlriDetailsLocalRib = nodeTreeMap.get(nodes); displayNode(); counter++; } else if (counter == 0) { pathAttrNlriDetailsLocalRib = nodeTreeMap.get(nodes); displayNode(); } } } catch (Exception e) { log.debug("Error occurred while displaying BGP nodes: {}", e.getMessage()); } } private void displayLinks() { try { int counter = 0; print("Total Number of entries = %d", linkTreeMap.size()); for (BgpLinkLSIdentifier links : linkkeySet) { if (numberofentries > linkTreeMap.size() || numberofentries < 0) { System.out.print("Wrong Argument"); break; } else if (counter < numberofentries) { pathAttrNlriDetailsLocalRib = linkTreeMap.get(links); print("Total number of entries = %d", linkTreeMap.size()); displayLink(); counter++; } else if (counter == 0) { pathAttrNlriDetailsLocalRib = linkTreeMap.get(links); displayLink(); } } } catch (Exception e) { log.debug("Error occurred while displaying BGP links: {}", e.getMessage()); } } private void displayPrefix() { try { this.bgpController = get(BgpController.class); bgpLocalRib = bgpController.bgpLocalRib(); Map<BgpPrefixLSIdentifier, PathAttrNlriDetailsLocalRib> prefixmap = bgpLocalRib.prefixTree(); Set<BgpPrefixLSIdentifier> prefixkeySet = prefixmap.keySet(); for (BgpPrefixLSIdentifier prefix : prefixkeySet) { pathAttrNlriDetailsLocalRib = prefixmap.get(prefix); pathAttrNlriDetails = pathAttrNlriDetailsLocalRib.localRibNlridetails(); print("No of entries = %d", prefixmap.size()); System.out.print(pathAttrNlriDetailsLocalRib.toString()); } } catch (Exception e) { log.debug("Error occurred while displaying BGP prefixes: {}", e.getMessage()); } } private void displayVpnNodes() { try { this.bgpController = get(BgpController.class); bgpLocalRib = bgpController.bgpLocalRib(); Map<RouteDistinguisher, Map<BgpNodeLSIdentifier, PathAttrNlriDetailsLocalRib>> vpnNode = bgpLocalRib.vpnNodeTree(); Set<RouteDistinguisher> vpnNodekeySet = vpnNode.keySet(); for (RouteDistinguisher vpnNodes : vpnNodekeySet) { boolean invalidProcess = true; if (vpnId != null && Integer.parseInt(vpnId.trim()) == vpnNodes.hashCode()) { invalidProcess = false; displayNodes(); } if (invalidProcess) { print("%s\n", "Id " + vpnId + "does not exist...!!!"); } } } catch (Exception e) { log.debug("Error occurred while displaying BGP nodes based on VPN : {}", e.getMessage()); } } private void displayVpnLinks() { try { this.bgpController = get(BgpController.class); bgpLocalRib = bgpController.bgpLocalRib(); Map<RouteDistinguisher, Map<BgpLinkLSIdentifier, PathAttrNlriDetailsLocalRib>> vpnLink = bgpLocalRib.vpnLinkTree(); Set<RouteDistinguisher> vpnLinkkeySet = vpnLink.keySet(); for (RouteDistinguisher vpnLinks : vpnLinkkeySet) { boolean invalidProcess = true; if (vpnId != null && Integer.parseInt(vpnId.trim()) == vpnLinks.hashCode()) { invalidProcess = false; displayLinks(); } if (invalidProcess) { print("%s\n", "Id " + vpnId + "does not exist...!!!"); } } } catch (Exception e) { log.debug("Error occurred while displaying BGP links based on VPN : {}", e.getMessage()); } } private void displayVpnPrefix() { try { this.bgpController = get(BgpController.class); bgpLocalRib = bgpController.bgpLocalRib(); Map<RouteDistinguisher, Map<BgpPrefixLSIdentifier, PathAttrNlriDetailsLocalRib>> vpnPrefix = bgpLocalRib.vpnPrefixTree(); Set<RouteDistinguisher> vpnPrefixkeySet = vpnPrefix.keySet(); for (RouteDistinguisher vpnprefixId : vpnPrefixkeySet) { boolean invalidProcess = true; if (vpnId != null && Integer.parseInt(vpnId.trim()) == vpnprefixId.hashCode()) { invalidProcess = false; displayPrefix(); } if (invalidProcess) { print("%s\n", "Id " + vpnId + "does not exist...!!!"); } } } catch (Exception e) { log.debug("Error occurred while displaying BGP prefixes based on VPN : {}", e.getMessage()); } } private void displayNode() { pathAttrNlriDetails = pathAttrNlriDetailsLocalRib.localRibNlridetails(); List<BgpValueType> bgpValueTypeList = pathAttrNlriDetails.pathAttributes(); protocolType = pathAttrNlriDetails.protocolID(); Iterator<BgpValueType> itrBgpValueType = bgpValueTypeList.iterator(); while (itrBgpValueType.hasNext()) { BgpValueType bgpValueType = itrBgpValueType.next(); if (bgpValueType instanceof Origin) { origin = (Origin) bgpValueType; } else if (bgpValueType instanceof LocalPref) { localPref = (LocalPref) bgpValueType; } else if (bgpValueType instanceof LinkStateAttributes) { LinkStateAttributes linkStateAttributes = (LinkStateAttributes) bgpValueType; List linkStateAttribiuteList = linkStateAttributes.linkStateAttributes(); Iterator<BgpValueType> linkStateAttribiteIterator = linkStateAttribiuteList.iterator(); while (linkStateAttribiteIterator.hasNext()) { BgpValueType bgpValueType1 = linkStateAttribiteIterator.next(); if (bgpValueType1 instanceof BgpAttrRouterIdV4) { bgpAttrRouterIdV4 = (BgpAttrRouterIdV4) bgpValueType1; } } } else if (bgpValueType instanceof MpReachNlri) { mpReachNlri = (MpReachNlri) bgpValueType; List<BgpLSNlri> bgpLSNlris = mpReachNlri.mpReachNlri(); Iterator<BgpLSNlri> bgpLsnlrisIterator = bgpLSNlris.iterator(); while (bgpLsnlrisIterator.hasNext()) { BgpLSNlri bgpLSNlri = bgpLsnlrisIterator.next(); if (bgpLSNlri instanceof BgpNodeLSNlriVer4) { BgpNodeLSNlriVer4 bgpNodeLSNlriVer4 = (BgpNodeLSNlriVer4) bgpLSNlri; BgpNodeLSIdentifier bgpNodeLSIdentifier = bgpNodeLSNlriVer4.getLocalNodeDescriptors(); NodeDescriptors nodeDescriptors = bgpNodeLSIdentifier.getNodedescriptors(); List<BgpValueType> bgpvalueTypesList = nodeDescriptors.getSubTlvs(); Iterator<BgpValueType> bgpValueTypeIterator = bgpvalueTypesList.iterator(); while (bgpValueTypeIterator.hasNext()) { BgpValueType valueType = bgpValueTypeIterator.next(); if (valueType instanceof IsIsNonPseudonode) { isIsNonPseudonode = (IsIsNonPseudonode) valueType; } } } } } } print("RibAsNumber = %s,PeerIdentifier = %s,RibIpAddress = %s,ProtocolType = %s,Origin = %s,LocalPref = %s," + "RouterID = %s,IsoNodeID = %s,NextHop = %s", pathAttrNlriDetailsLocalRib.localRibAsNum(), pathAttrNlriDetailsLocalRib.localRibIdentifier(), pathAttrNlriDetailsLocalRib.localRibIpAddress(), protocolType.toString(), origin.origin(), localPref.localPref(), bgpAttrRouterIdV4.attrRouterId(), Arrays.toString(isIsNonPseudonode.getIsoNodeId()), mpReachNlri.nexthop4()); } private void displayLink() { pathAttrNlriDetails = pathAttrNlriDetailsLocalRib.localRibNlridetails(); List<BgpValueType> valueTypes = pathAttrNlriDetails.pathAttributes(); Iterator<BgpValueType> itrBgpValueType = valueTypes.iterator(); while (itrBgpValueType.hasNext()) { BgpValueType bgpValueType = itrBgpValueType.next(); if (bgpValueType instanceof Origin) { origin = (Origin) bgpValueType; } else if (bgpValueType instanceof LocalPref) { localPref = (LocalPref) bgpValueType; } else if (bgpValueType instanceof LinkStateAttributes) { LinkStateAttributes linkStateAttributes = (LinkStateAttributes) bgpValueType; List linkStateAttributelist = linkStateAttributes.linkStateAttributes(); Iterator<BgpValueType> linkStateAttributeIterator = linkStateAttributelist.iterator(); while (linkStateAttributeIterator.hasNext()) { BgpValueType bgpValueType1 = linkStateAttributeIterator.next(); if (bgpValueType1 instanceof BgpAttrRouterIdV4) { bgpAttrRouterIdV4 = (BgpAttrRouterIdV4) bgpValueType1; } else if (bgpValueType1 instanceof BgpLinkAttrMaxLinkBandwidth) { bgpLinkAttrMaxLinkBandwidth = (BgpLinkAttrMaxLinkBandwidth) bgpValueType1; } else if (bgpValueType1 instanceof BgpLinkAttrUnRsrvdLinkBandwidth) { bgpLinkAttrUnRsrvdLinkBandwidth = (BgpLinkAttrUnRsrvdLinkBandwidth) bgpValueType1; } else if (bgpValueType1 instanceof BgpLinkAttrTeDefaultMetric) { bgpLinkAttrTeDefaultMetric = (BgpLinkAttrTeDefaultMetric) bgpValueType1; } else if (bgpValueType1 instanceof BgpLinkAttrIgpMetric) { bgpLinkAttrIgpMetric = (BgpLinkAttrIgpMetric) bgpValueType1; } } } else if (bgpValueType instanceof MpReachNlri) { mpReachNlri = (MpReachNlri) bgpValueType; List<BgpLSNlri> bgpLSNlris = mpReachNlri.mpReachNlri(); Iterator<BgpLSNlri> bgpLsnlrisIterator = bgpLSNlris.iterator(); while (bgpLsnlrisIterator.hasNext()) { BgpLSNlri bgpLSNlri = bgpLsnlrisIterator.next(); if (bgpLSNlri instanceof BgpLinkLsNlriVer4) { BgpLinkLsNlriVer4 bgpLinkLsNlriVer4 = (BgpLinkLsNlriVer4) bgpLSNlri; BgpLinkLSIdentifier bgpLinkLSIdentifier = bgpLinkLsNlriVer4.getLinkIdentifier(); NodeDescriptors localnodeDescriptors = bgpLinkLSIdentifier.localNodeDescriptors(); NodeDescriptors remotenodeDescriptors = bgpLinkLSIdentifier.remoteNodeDescriptors(); List<BgpValueType> linkDescriptors = bgpLinkLSIdentifier.linkDescriptors(); List<BgpValueType> subTlvList = localnodeDescriptors.getSubTlvs(); Iterator<BgpValueType> subTlvIterator = subTlvList.iterator(); while (subTlvIterator.hasNext()) { BgpValueType valueType = subTlvIterator.next(); if (valueType instanceof IsIsNonPseudonode) { isIsNonPseudonode = (IsIsNonPseudonode) valueType; } else if (valueType instanceof AutonomousSystemTlv) { autonomousSystemTlv = (AutonomousSystemTlv) valueType; } } List<BgpValueType> remotevalueTypes = remotenodeDescriptors.getSubTlvs(); Iterator<BgpValueType> remoteValueTypesIterator = remotevalueTypes.iterator(); while (remoteValueTypesIterator.hasNext()) { BgpValueType valueType = remoteValueTypesIterator.next(); if (valueType instanceof IsIsNonPseudonode) { isIsNonPseudonode = (IsIsNonPseudonode) valueType; } else if (valueType instanceof AutonomousSystemTlv) { autonomousSystemTlv = (AutonomousSystemTlv) valueType; } } Iterator<BgpValueType> listIterator = linkDescriptors.iterator(); while (listIterator.hasNext()) { BgpValueType valueType = listIterator.next(); if (valueType instanceof IPv4AddressTlv) { iPv4AddressTlv = (IPv4AddressTlv) valueType; } } } } } } print("PeerIdentifier = %s,Origin = %s,LocalPref = %s,RouterID = %s,MaxBandwidth = %s," + "UnreservedBandwidth = %s,DefaultMetric = %s,IGPMetric = %s,IsoNodeID = %s,ASNum = %s," + "IPAddress = %s,NextHop = %s", pathAttrNlriDetailsLocalRib.localRibIdentifier(), origin.origin(), localPref.localPref(), bgpAttrRouterIdV4.attrRouterId(), bgpLinkAttrMaxLinkBandwidth.linkAttrMaxLinkBandwidth(), bgpLinkAttrUnRsrvdLinkBandwidth.getLinkAttrUnRsrvdLinkBandwidth().toString(), bgpLinkAttrTeDefaultMetric.attrLinkDefTeMetric(), bgpLinkAttrIgpMetric.attrLinkIgpMetric(), Arrays.toString(isIsNonPseudonode.getIsoNodeId()), autonomousSystemTlv.getAsNum(), iPv4AddressTlv.address(), mpReachNlri.nexthop4().toString(), pathAttrNlriDetailsLocalRib.localRibIpAddress(), origin.origin(), localPref.localPref(), bgpAttrRouterIdV4.attrRouterId()); } }
providers/bgp/cli/src/main/java/org/onosproject/bgp/cli/BgpLocalRibDisplay.java
/* * Copyright 2016-present Open Networking Laboratory * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.bgp.cli; import org.apache.karaf.shell.commands.Argument; import org.apache.karaf.shell.commands.Command; import org.onosproject.bgp.controller.BgpController; import org.onosproject.bgp.controller.BgpLocalRib; import org.onosproject.bgpio.protocol.BgpLSNlri; import org.onosproject.bgpio.protocol.linkstate.BgpNodeLSIdentifier; import org.onosproject.bgpio.protocol.linkstate.BgpNodeLSNlriVer4; import org.onosproject.bgpio.protocol.linkstate.PathAttrNlriDetails; import org.onosproject.bgpio.protocol.linkstate.PathAttrNlriDetailsLocalRib; import org.onosproject.bgpio.protocol.linkstate.BgpLinkLSIdentifier; import org.onosproject.bgpio.protocol.linkstate.BgpPrefixLSIdentifier; import org.onosproject.bgpio.protocol.linkstate.NodeDescriptors; import org.onosproject.bgpio.protocol.linkstate.BgpLinkLsNlriVer4; import org.onosproject.bgpio.types.IPv4AddressTlv; import org.onosproject.bgpio.types.RouteDistinguisher; import org.onosproject.bgpio.types.BgpValueType; import org.onosproject.bgpio.types.LinkStateAttributes; import org.onosproject.bgpio.types.MpReachNlri; import org.onosproject.bgpio.types.AutonomousSystemTlv; import org.onosproject.bgpio.types.IsIsNonPseudonode; import org.onosproject.bgpio.types.LocalPref; import org.onosproject.bgpio.types.Origin; import org.onosproject.bgpio.types.attr.BgpAttrRouterIdV4; import org.onosproject.bgpio.types.attr.BgpLinkAttrMaxLinkBandwidth; import org.onosproject.bgpio.types.attr.BgpLinkAttrUnRsrvdLinkBandwidth; import org.onosproject.bgpio.types.attr.BgpLinkAttrTeDefaultMetric; import org.onosproject.bgpio.types.attr.BgpLinkAttrIgpMetric; import org.onosproject.cli.AbstractShellCommand; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map; import java.util.Set; import java.util.List; import java.util.Iterator; import java.util.Arrays; @Command(scope = "onos", name = "bgp-rib", description = "lists RIB configuration") public class BgpLocalRibDisplay extends AbstractShellCommand { private static final Logger log = LoggerFactory.getLogger(BgpLocalRibDisplay.class); private static final String NODETREE = "nodes"; private static final String LINKTREE = "links"; private static final String PREFIXTREE = "prefix"; private static final String VPNNODETREE = "vpnnodes"; private static final String VPNLINKTREE = "vpnlinkS"; private static final String VPNPREFIXTREE = "vpnprefix"; protected Origin origin; protected LocalPref localPref; protected BgpAttrRouterIdV4 bgpAttrRouterIdV4; protected IsIsNonPseudonode isIsNonPseudonode; protected AutonomousSystemTlv autonomousSystemTlv; protected IPv4AddressTlv iPv4AddressTlv; protected BgpLinkAttrMaxLinkBandwidth bgpLinkAttrMaxLinkBandwidth; protected BgpLinkAttrUnRsrvdLinkBandwidth bgpLinkAttrUnRsrvdLinkBandwidth; protected BgpLinkAttrTeDefaultMetric bgpLinkAttrTeDefaultMetric; protected BgpLinkAttrIgpMetric bgpLinkAttrIgpMetric; protected PathAttrNlriDetailsLocalRib pathAttrNlriDetailsLocalRib; protected MpReachNlri mpReachNlri; protected PathAttrNlriDetails pathAttrNlriDetails; protected BgpNodeLSNlriVer4.ProtocolType protocolType; protected BgpController bgpController = get(BgpController.class); protected BgpLocalRib bgpLocalRib = bgpController.bgpLocalRib(); Map<BgpNodeLSIdentifier, PathAttrNlriDetailsLocalRib> nodeTreeMap = bgpLocalRib.nodeTree(); Set<BgpNodeLSIdentifier> nodekeySet = nodeTreeMap.keySet(); Map<BgpLinkLSIdentifier, PathAttrNlriDetailsLocalRib> linkTreeMap = bgpLocalRib.linkTree(); Set<BgpLinkLSIdentifier> linkkeySet = linkTreeMap.keySet(); @Argument(index = 0, name = "name", description = "nodetree" + "\n" + "linktree" + "\n" + "prefixtree" + "\n" + "vpnnodetree" + "\n" + "vpnlinktree" + "\n" + "vpnprefixtree", required = true, multiValued = false) String name = null; @Argument(index = 1, name = "numberofentries", description = "numberofentries", required = false, multiValued = false) int numberofentries; @Argument(index = 2, name = "vpnId", description = "vpnId", required = false, multiValued = false) String vpnId = null; private int count = 0; @Override protected void execute() { switch (name) { case NODETREE: displayNodes(); break; case LINKTREE: displayLinks(); break; case PREFIXTREE: displayPrefix(); break; case VPNNODETREE: displayVpnNodes(); break; case VPNLINKTREE: displayVpnLinks(); break; case VPNPREFIXTREE: displayVpnPrefix(); break; default: System.out.print("Unknown Command"); break; } } private void displayNodes() { try { int counter = 0; print("Total number of entries = %s", nodeTreeMap.size()); for (BgpNodeLSIdentifier nodes : nodekeySet) { if (numberofentries > nodeTreeMap.size() || numberofentries < 0) { System.out.print("Wrong Argument"); break; } else if (counter < numberofentries) { pathAttrNlriDetailsLocalRib = nodeTreeMap.get(nodes); displayNode(); counter++; } else if (counter == 0) { pathAttrNlriDetailsLocalRib = nodeTreeMap.get(nodes); displayNode(); } } } catch (Exception e) { log.debug("Error occurred while displaying BGP nodes: {}", e.getMessage()); } } private void displayLinks() { try { int counter = 0; print("Total Number of entries = %d", linkTreeMap.size()); for (BgpLinkLSIdentifier links : linkkeySet) { if (numberofentries > linkTreeMap.size() || numberofentries < 0) { System.out.print("Wrong Argument"); break; } else if (counter < numberofentries) { pathAttrNlriDetailsLocalRib = linkTreeMap.get(links); print("Total number of entries = %d", linkTreeMap.size()); displayLink(); counter++; } else if (counter == 0) { pathAttrNlriDetailsLocalRib = linkTreeMap.get(links); displayLink(); } } } catch (Exception e) { log.debug("Error occurred while displaying BGP links: {}", e.getMessage()); } } private void displayPrefix() { try { this.bgpController = get(BgpController.class); bgpLocalRib = bgpController.bgpLocalRib(); Map<BgpPrefixLSIdentifier, PathAttrNlriDetailsLocalRib> prefixmap = bgpLocalRib.prefixTree(); Set<BgpPrefixLSIdentifier> prefixkeySet = prefixmap.keySet(); for (BgpPrefixLSIdentifier prefix : prefixkeySet) { pathAttrNlriDetailsLocalRib = prefixmap.get(prefix); pathAttrNlriDetails = pathAttrNlriDetailsLocalRib.localRibNlridetails(); print("No of entries = %d", prefixmap.size()); System.out.print(pathAttrNlriDetailsLocalRib.toString()); } } catch (Exception e) { log.debug("Error occurred while displaying BGP prefixes: {}", e.getMessage()); } } private void displayVpnNodes() { try { this.bgpController = get(BgpController.class); bgpLocalRib = bgpController.bgpLocalRib(); Map<RouteDistinguisher, Map<BgpNodeLSIdentifier, PathAttrNlriDetailsLocalRib>> vpnNode = bgpLocalRib.vpnNodeTree(); Set<RouteDistinguisher> vpnNodekeySet = vpnNode.keySet(); for (RouteDistinguisher vpnNodes : vpnNodekeySet) { boolean invalidProcess = true; if (vpnId != null && vpnId.trim().equals(vpnNodes.hashCode())) { invalidProcess = false; displayNodes(); } if (invalidProcess) { print("%s\n", "Id " + vpnId + "does not exist...!!!"); } } } catch (Exception e) { log.debug("Error occurred while displaying BGP nodes based on VPN : {}", e.getMessage()); } } private void displayVpnLinks() { try { this.bgpController = get(BgpController.class); bgpLocalRib = bgpController.bgpLocalRib(); Map<RouteDistinguisher, Map<BgpLinkLSIdentifier, PathAttrNlriDetailsLocalRib>> vpnLink = bgpLocalRib.vpnLinkTree(); Set<RouteDistinguisher> vpnLinkkeySet = vpnLink.keySet(); for (RouteDistinguisher vpnLinks : vpnLinkkeySet) { boolean invalidProcess = true; if (vpnId != null && vpnId.trim().equals(vpnLinks.hashCode())) { invalidProcess = false; displayLinks(); } if (invalidProcess) { print("%s\n", "Id " + vpnId + "does not exist...!!!"); } } } catch (Exception e) { log.debug("Error occurred while displaying BGP links based on VPN : {}", e.getMessage()); } } private void displayVpnPrefix() { try { this.bgpController = get(BgpController.class); bgpLocalRib = bgpController.bgpLocalRib(); Map<RouteDistinguisher, Map<BgpPrefixLSIdentifier, PathAttrNlriDetailsLocalRib>> vpnPrefix = bgpLocalRib.vpnPrefixTree(); Set<RouteDistinguisher> vpnPrefixkeySet = vpnPrefix.keySet(); for (RouteDistinguisher vpnprefixId : vpnPrefixkeySet) { boolean invalidProcess = true; if (vpnId != null && vpnId.trim().equals(vpnprefixId.hashCode())) { invalidProcess = false; displayPrefix(); } if (invalidProcess) { print("%s\n", "Id " + vpnId + "does not exist...!!!"); } } } catch (Exception e) { log.debug("Error occurred while displaying BGP prefixes based on VPN : {}", e.getMessage()); } } private void displayNode() { pathAttrNlriDetails = pathAttrNlriDetailsLocalRib.localRibNlridetails(); List<BgpValueType> bgpValueTypeList = pathAttrNlriDetails.pathAttributes(); protocolType = pathAttrNlriDetails.protocolID(); Iterator<BgpValueType> itrBgpValueType = bgpValueTypeList.iterator(); while (itrBgpValueType.hasNext()) { BgpValueType bgpValueType = itrBgpValueType.next(); if (bgpValueType instanceof Origin) { origin = (Origin) bgpValueType; } else if (bgpValueType instanceof LocalPref) { localPref = (LocalPref) bgpValueType; } else if (bgpValueType instanceof LinkStateAttributes) { LinkStateAttributes linkStateAttributes = (LinkStateAttributes) bgpValueType; List linkStateAttribiuteList = linkStateAttributes.linkStateAttributes(); Iterator<BgpValueType> linkStateAttribiteIterator = linkStateAttribiuteList.iterator(); while (linkStateAttribiteIterator.hasNext()) { BgpValueType bgpValueType1 = linkStateAttribiteIterator.next(); if (bgpValueType1 instanceof BgpAttrRouterIdV4) { bgpAttrRouterIdV4 = (BgpAttrRouterIdV4) bgpValueType1; } } } else if (bgpValueType instanceof MpReachNlri) { mpReachNlri = (MpReachNlri) bgpValueType; List<BgpLSNlri> bgpLSNlris = mpReachNlri.mpReachNlri(); Iterator<BgpLSNlri> bgpLsnlrisIterator = bgpLSNlris.iterator(); while (bgpLsnlrisIterator.hasNext()) { BgpLSNlri bgpLSNlri = bgpLsnlrisIterator.next(); if (bgpLSNlri instanceof BgpNodeLSNlriVer4) { BgpNodeLSNlriVer4 bgpNodeLSNlriVer4 = (BgpNodeLSNlriVer4) bgpLSNlri; BgpNodeLSIdentifier bgpNodeLSIdentifier = bgpNodeLSNlriVer4.getLocalNodeDescriptors(); NodeDescriptors nodeDescriptors = bgpNodeLSIdentifier.getNodedescriptors(); List<BgpValueType> bgpvalueTypesList = nodeDescriptors.getSubTlvs(); Iterator<BgpValueType> bgpValueTypeIterator = bgpvalueTypesList.iterator(); while (bgpValueTypeIterator.hasNext()) { BgpValueType valueType = bgpValueTypeIterator.next(); if (valueType instanceof IsIsNonPseudonode) { isIsNonPseudonode = (IsIsNonPseudonode) valueType; } } } } } } print("RibAsNumber = %s,PeerIdentifier = %s,RibIpAddress = %s,ProtocolType = %s,Origin = %s,LocalPref = %s," + "RouterID = %s,IsoNodeID = %s,NextHop = %s", pathAttrNlriDetailsLocalRib.localRibAsNum(), pathAttrNlriDetailsLocalRib.localRibIdentifier(), pathAttrNlriDetailsLocalRib.localRibIpAddress(), protocolType.toString(), origin.origin(), localPref.localPref(), bgpAttrRouterIdV4.attrRouterId(), Arrays.toString(isIsNonPseudonode.getIsoNodeId()), mpReachNlri.nexthop4()); } private void displayLink() { pathAttrNlriDetails = pathAttrNlriDetailsLocalRib.localRibNlridetails(); List<BgpValueType> valueTypes = pathAttrNlriDetails.pathAttributes(); Iterator<BgpValueType> itrBgpValueType = valueTypes.iterator(); while (itrBgpValueType.hasNext()) { BgpValueType bgpValueType = itrBgpValueType.next(); if (bgpValueType instanceof Origin) { origin = (Origin) bgpValueType; } else if (bgpValueType instanceof LocalPref) { localPref = (LocalPref) bgpValueType; } else if (bgpValueType instanceof LinkStateAttributes) { LinkStateAttributes linkStateAttributes = (LinkStateAttributes) bgpValueType; List linkStateAttributelist = linkStateAttributes.linkStateAttributes(); Iterator<BgpValueType> linkStateAttributeIterator = linkStateAttributelist.iterator(); while (linkStateAttributeIterator.hasNext()) { BgpValueType bgpValueType1 = linkStateAttributeIterator.next(); if (bgpValueType1 instanceof BgpAttrRouterIdV4) { bgpAttrRouterIdV4 = (BgpAttrRouterIdV4) bgpValueType1; } else if (bgpValueType1 instanceof BgpLinkAttrMaxLinkBandwidth) { bgpLinkAttrMaxLinkBandwidth = (BgpLinkAttrMaxLinkBandwidth) bgpValueType1; } else if (bgpValueType1 instanceof BgpLinkAttrUnRsrvdLinkBandwidth) { bgpLinkAttrUnRsrvdLinkBandwidth = (BgpLinkAttrUnRsrvdLinkBandwidth) bgpValueType1; } else if (bgpValueType1 instanceof BgpLinkAttrTeDefaultMetric) { bgpLinkAttrTeDefaultMetric = (BgpLinkAttrTeDefaultMetric) bgpValueType1; } else if (bgpValueType1 instanceof BgpLinkAttrIgpMetric) { bgpLinkAttrIgpMetric = (BgpLinkAttrIgpMetric) bgpValueType1; } } } else if (bgpValueType instanceof MpReachNlri) { mpReachNlri = (MpReachNlri) bgpValueType; List<BgpLSNlri> bgpLSNlris = mpReachNlri.mpReachNlri(); Iterator<BgpLSNlri> bgpLsnlrisIterator = bgpLSNlris.iterator(); while (bgpLsnlrisIterator.hasNext()) { BgpLSNlri bgpLSNlri = bgpLsnlrisIterator.next(); if (bgpLSNlri instanceof BgpLinkLsNlriVer4) { BgpLinkLsNlriVer4 bgpLinkLsNlriVer4 = (BgpLinkLsNlriVer4) bgpLSNlri; BgpLinkLSIdentifier bgpLinkLSIdentifier = bgpLinkLsNlriVer4.getLinkIdentifier(); NodeDescriptors localnodeDescriptors = bgpLinkLSIdentifier.localNodeDescriptors(); NodeDescriptors remotenodeDescriptors = bgpLinkLSIdentifier.remoteNodeDescriptors(); List<BgpValueType> linkDescriptors = bgpLinkLSIdentifier.linkDescriptors(); List<BgpValueType> subTlvList = localnodeDescriptors.getSubTlvs(); Iterator<BgpValueType> subTlvIterator = subTlvList.iterator(); while (subTlvIterator.hasNext()) { BgpValueType valueType = subTlvIterator.next(); if (valueType instanceof IsIsNonPseudonode) { isIsNonPseudonode = (IsIsNonPseudonode) valueType; } else if (valueType instanceof AutonomousSystemTlv) { autonomousSystemTlv = (AutonomousSystemTlv) valueType; } } List<BgpValueType> remotevalueTypes = remotenodeDescriptors.getSubTlvs(); Iterator<BgpValueType> remoteValueTypesIterator = remotevalueTypes.iterator(); while (remoteValueTypesIterator.hasNext()) { BgpValueType valueType = remoteValueTypesIterator.next(); if (valueType instanceof IsIsNonPseudonode) { isIsNonPseudonode = (IsIsNonPseudonode) valueType; } else if (valueType instanceof AutonomousSystemTlv) { autonomousSystemTlv = (AutonomousSystemTlv) valueType; } } Iterator<BgpValueType> listIterator = linkDescriptors.iterator(); while (listIterator.hasNext()) { BgpValueType valueType = listIterator.next(); if (valueType instanceof IPv4AddressTlv) { iPv4AddressTlv = (IPv4AddressTlv) valueType; } } } } } } print("PeerIdentifier = %s,Origin = %s,LocalPref = %s,RouterID = %s,MaxBandwidth = %s," + "UnreservedBandwidth = %s,DefaultMetric = %s,IGPMetric = %s,IsoNodeID = %s,ASNum = %s," + "IPAddress = %s,NextHop = %s", pathAttrNlriDetailsLocalRib.localRibIdentifier(), origin.origin(), localPref.localPref(), bgpAttrRouterIdV4.attrRouterId(), bgpLinkAttrMaxLinkBandwidth.linkAttrMaxLinkBandwidth(), bgpLinkAttrUnRsrvdLinkBandwidth.getLinkAttrUnRsrvdLinkBandwidth().toString(), bgpLinkAttrTeDefaultMetric.attrLinkDefTeMetric(), bgpLinkAttrIgpMetric.attrLinkIgpMetric(), Arrays.toString(isIsNonPseudonode.getIsoNodeId()), autonomousSystemTlv.getAsNum(), iPv4AddressTlv.address(), mpReachNlri.nexthop4().toString(), pathAttrNlriDetailsLocalRib.localRibIpAddress(), origin.origin(), localPref.localPref(), bgpAttrRouterIdV4.attrRouterId()); } }
[ONOS-5817] Modified string to integer comparisions Change-Id: Ic57dae62e27decedaa959dd50aefe46777e16e84
providers/bgp/cli/src/main/java/org/onosproject/bgp/cli/BgpLocalRibDisplay.java
[ONOS-5817] Modified string to integer comparisions
Java
apache-2.0
32d50033470311e8a32c9be0085249ec47b4ea8b
0
wreckJ/intellij-community,ivan-fedorov/intellij-community,adedayo/intellij-community,retomerz/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,supersven/intellij-community,ivan-fedorov/intellij-community,michaelgallacher/intellij-community,holmes/intellij-community,ahb0327/intellij-community,holmes/intellij-community,retomerz/intellij-community,da1z/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,blademainer/intellij-community,alphafoobar/intellij-community,petteyg/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,jagguli/intellij-community,apixandru/intellij-community,ryano144/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,allotria/intellij-community,semonte/intellij-community,da1z/intellij-community,dslomov/intellij-community,Distrotech/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,ftomassetti/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,jagguli/intellij-community,SerCeMan/intellij-community,izonder/intellij-community,muntasirsyed/intellij-community,salguarnieri/intellij-community,jagguli/intellij-community,allotria/intellij-community,allotria/intellij-community,fitermay/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,robovm/robovm-studio,ahb0327/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,izonder/intellij-community,kool79/intellij-community,ahb0327/intellij-community,izonder/intellij-community,kool79/intellij-community,caot/intellij-community,ryano144/intellij-community,tmpgit/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,MichaelNedzelsky/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,gnuhub/intellij-community,wreckJ/intellij-community,petteyg/intellij-community,vladmm/intellij-community,TangHao1987/intellij-community,Distrotech/intellij-community,holmes/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,jagguli/intellij-community,gnuhub/intellij-community,slisson/intellij-community,fnouama/intellij-community,petteyg/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,dslomov/intellij-community,blademainer/intellij-community,robovm/robovm-studio,amith01994/intellij-community,slisson/intellij-community,fitermay/intellij-community,samthor/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,signed/intellij-community,TangHao1987/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,retomerz/intellij-community,izonder/intellij-community,supersven/intellij-community,adedayo/intellij-community,robovm/robovm-studio,muntasirsyed/intellij-community,ftomassetti/intellij-community,ThiagoGarciaAlves/intellij-community,akosyakov/intellij-community,slisson/intellij-community,ryano144/intellij-community,retomerz/intellij-community,FHannes/intellij-community,hurricup/intellij-community,caot/intellij-community,xfournet/intellij-community,kdwink/intellij-community,ibinti/intellij-community,amith01994/intellij-community,supersven/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,SerCeMan/intellij-community,vladmm/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,samthor/intellij-community,robovm/robovm-studio,dslomov/intellij-community,alphafoobar/intellij-community,orekyuu/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,holmes/intellij-community,robovm/robovm-studio,wreckJ/intellij-community,izonder/intellij-community,supersven/intellij-community,kdwink/intellij-community,supersven/intellij-community,hurricup/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,SerCeMan/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,ftomassetti/intellij-community,ibinti/intellij-community,supersven/intellij-community,petteyg/intellij-community,nicolargo/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,tmpgit/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,MichaelNedzelsky/intellij-community,dslomov/intellij-community,amith01994/intellij-community,samthor/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,slisson/intellij-community,ivan-fedorov/intellij-community,holmes/intellij-community,clumsy/intellij-community,ryano144/intellij-community,fengbaicanhe/intellij-community,orekyuu/intellij-community,suncycheng/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,fitermay/intellij-community,gnuhub/intellij-community,apixandru/intellij-community,fengbaicanhe/intellij-community,adedayo/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,samthor/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,xfournet/intellij-community,allotria/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,apixandru/intellij-community,jagguli/intellij-community,samthor/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,ryano144/intellij-community,da1z/intellij-community,wreckJ/intellij-community,blademainer/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,xfournet/intellij-community,akosyakov/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,da1z/intellij-community,robovm/robovm-studio,FHannes/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,holmes/intellij-community,muntasirsyed/intellij-community,ryano144/intellij-community,orekyuu/intellij-community,Lekanich/intellij-community,alphafoobar/intellij-community,petteyg/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,fnouama/intellij-community,petteyg/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,semonte/intellij-community,kdwink/intellij-community,vladmm/intellij-community,suncycheng/intellij-community,robovm/robovm-studio,lucafavatella/intellij-community,orekyuu/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,SerCeMan/intellij-community,youdonghai/intellij-community,signed/intellij-community,kool79/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,pwoodworth/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,kdwink/intellij-community,alphafoobar/intellij-community,xfournet/intellij-community,adedayo/intellij-community,semonte/intellij-community,ryano144/intellij-community,MER-GROUP/intellij-community,kool79/intellij-community,supersven/intellij-community,Lekanich/intellij-community,Lekanich/intellij-community,robovm/robovm-studio,fengbaicanhe/intellij-community,vvv1559/intellij-community,orekyuu/intellij-community,ThiagoGarciaAlves/intellij-community,MichaelNedzelsky/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,blademainer/intellij-community,vladmm/intellij-community,ahb0327/intellij-community,Distrotech/intellij-community,slisson/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,holmes/intellij-community,blademainer/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,michaelgallacher/intellij-community,TangHao1987/intellij-community,pwoodworth/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,nicolargo/intellij-community,ryano144/intellij-community,allotria/intellij-community,clumsy/intellij-community,MichaelNedzelsky/intellij-community,Lekanich/intellij-community,gnuhub/intellij-community,Distrotech/intellij-community,lucafavatella/intellij-community,petteyg/intellij-community,vvv1559/intellij-community,adedayo/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,signed/intellij-community,fnouama/intellij-community,vvv1559/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,vladmm/intellij-community,fitermay/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,adedayo/intellij-community,vvv1559/intellij-community,vladmm/intellij-community,blademainer/intellij-community,semonte/intellij-community,fnouama/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,blademainer/intellij-community,supersven/intellij-community,amith01994/intellij-community,vladmm/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community,signed/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,alphafoobar/intellij-community,akosyakov/intellij-community,signed/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,blademainer/intellij-community,dslomov/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,ryano144/intellij-community,ftomassetti/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,amith01994/intellij-community,asedunov/intellij-community,allotria/intellij-community,pwoodworth/intellij-community,samthor/intellij-community,MichaelNedzelsky/intellij-community,clumsy/intellij-community,amith01994/intellij-community,amith01994/intellij-community,apixandru/intellij-community,alphafoobar/intellij-community,nicolargo/intellij-community,supersven/intellij-community,petteyg/intellij-community,signed/intellij-community,FHannes/intellij-community,clumsy/intellij-community,xfournet/intellij-community,TangHao1987/intellij-community,gnuhub/intellij-community,tmpgit/intellij-community,semonte/intellij-community,SerCeMan/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,michaelgallacher/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,retomerz/intellij-community,da1z/intellij-community,allotria/intellij-community,amith01994/intellij-community,da1z/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,petteyg/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,caot/intellij-community,vladmm/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,caot/intellij-community,nicolargo/intellij-community,blademainer/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,Lekanich/intellij-community,vladmm/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,Lekanich/intellij-community,da1z/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,signed/intellij-community,Distrotech/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,kool79/intellij-community,orekyuu/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,samthor/intellij-community,vladmm/intellij-community,ftomassetti/intellij-community,fnouama/intellij-community,petteyg/intellij-community,gnuhub/intellij-community,ftomassetti/intellij-community,kdwink/intellij-community,apixandru/intellij-community,supersven/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,Distrotech/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,semonte/intellij-community,orekyuu/intellij-community,adedayo/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,kdwink/intellij-community,alphafoobar/intellij-community,SerCeMan/intellij-community,MER-GROUP/intellij-community,Lekanich/intellij-community,allotria/intellij-community,da1z/intellij-community,adedayo/intellij-community,akosyakov/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,ibinti/intellij-community,ibinti/intellij-community,gnuhub/intellij-community,ahb0327/intellij-community,nicolargo/intellij-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,mglukhikh/intellij-community,amith01994/intellij-community,holmes/intellij-community,Distrotech/intellij-community,nicolargo/intellij-community,da1z/intellij-community,Distrotech/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,alphafoobar/intellij-community,amith01994/intellij-community,jagguli/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,kdwink/intellij-community,lucafavatella/intellij-community,ahb0327/intellij-community,holmes/intellij-community,slisson/intellij-community,caot/intellij-community,slisson/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,hurricup/intellij-community,signed/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,kdwink/intellij-community,nicolargo/intellij-community,nicolargo/intellij-community,wreckJ/intellij-community,mglukhikh/intellij-community,holmes/intellij-community,samthor/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,fengbaicanhe/intellij-community,kdwink/intellij-community,izonder/intellij-community,kool79/intellij-community,caot/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,TangHao1987/intellij-community,signed/intellij-community,jagguli/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,ftomassetti/intellij-community,tmpgit/intellij-community,dslomov/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,izonder/intellij-community,retomerz/intellij-community,signed/intellij-community,muntasirsyed/intellij-community,akosyakov/intellij-community,suncycheng/intellij-community,pwoodworth/intellij-community,vladmm/intellij-community,Lekanich/intellij-community,fnouama/intellij-community,da1z/intellij-community,suncycheng/intellij-community,kool79/intellij-community,caot/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,da1z/intellij-community,supersven/intellij-community,samthor/intellij-community,xfournet/intellij-community,Lekanich/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,kool79/intellij-community,tmpgit/intellij-community,fnouama/intellij-community,apixandru/intellij-community,blademainer/intellij-community,clumsy/intellij-community,youdonghai/intellij-community,fengbaicanhe/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,slisson/intellij-community,asedunov/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,petteyg/intellij-community,salguarnieri/intellij-community,ahb0327/intellij-community,FHannes/intellij-community,fnouama/intellij-community,tmpgit/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,fengbaicanhe/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,mglukhikh/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,adedayo/intellij-community,fengbaicanhe/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,adedayo/intellij-community,TangHao1987/intellij-community,ahb0327/intellij-community,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,MER-GROUP/intellij-community,muntasirsyed/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,caot/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,ftomassetti/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,wreckJ/intellij-community,pwoodworth/intellij-community,caot/intellij-community,holmes/intellij-community,fnouama/intellij-community,retomerz/intellij-community,ivan-fedorov/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,gnuhub/intellij-community,jagguli/intellij-community,asedunov/intellij-community,blademainer/intellij-community,semonte/intellij-community,tmpgit/intellij-community,supersven/intellij-community,fnouama/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,jagguli/intellij-community,semonte/intellij-community,ibinti/intellij-community,caot/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,pwoodworth/intellij-community,fnouama/intellij-community,caot/intellij-community,suncycheng/intellij-community,ryano144/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,clumsy/intellij-community,dslomov/intellij-community,youdonghai/intellij-community,slisson/intellij-community,alphafoobar/intellij-community,amith01994/intellij-community,apixandru/intellij-community,semonte/intellij-community,ahb0327/intellij-community,salguarnieri/intellij-community,caot/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,pwoodworth/intellij-community,Lekanich/intellij-community,petteyg/intellij-community,ahb0327/intellij-community,suncycheng/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,akosyakov/intellij-community,nicolargo/intellij-community,xfournet/intellij-community,orekyuu/intellij-community,muntasirsyed/intellij-community,gnuhub/intellij-community,hurricup/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,mglukhikh/intellij-community,Distrotech/intellij-community,izonder/intellij-community,wreckJ/intellij-community,robovm/robovm-studio,xfournet/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,kool79/intellij-community,ivan-fedorov/intellij-community,ivan-fedorov/intellij-community
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.codeInsight.daemon.impl; import com.intellij.codeInsight.daemon.ChangeLocalityDetector; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.EditorFactory; import com.intellij.openapi.editor.event.DocumentAdapter; import com.intellij.openapi.editor.event.DocumentEvent; import com.intellij.openapi.editor.ex.EditorMarkupModel; import com.intellij.openapi.extensions.ExtensionPointName; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectCoreUtil; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.psi.impl.PsiDocumentManagerBase; import com.intellij.psi.impl.PsiDocumentManagerImpl; import com.intellij.psi.impl.PsiDocumentTransactionListener; import com.intellij.psi.impl.PsiTreeChangeEventImpl; import com.intellij.util.SmartList; import com.intellij.util.messages.MessageBusConnection; import gnu.trove.THashMap; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collections; import java.util.List; import java.util.Map; class PsiChangeHandler extends PsiTreeChangeAdapter implements Disposable { private static final ExtensionPointName<ChangeLocalityDetector> EP_NAME = ExtensionPointName.create("com.intellij.daemon.changeLocalityDetector"); private /*NOT STATIC!!!*/ final Key<Boolean> UPDATE_ON_COMMIT_ENGAGED = Key.create("UPDATE_ON_COMMIT_ENGAGED"); private final Project myProject; private final Map<Document, List<Pair<PsiElement, Boolean>>> changedElements = new THashMap<Document, List<Pair<PsiElement, Boolean>>>(); private final FileStatusMap myFileStatusMap; PsiChangeHandler(@NotNull Project project, @NotNull final PsiDocumentManagerImpl documentManager, @NotNull EditorFactory editorFactory, @NotNull MessageBusConnection connection, @NotNull FileStatusMap fileStatusMap) { myProject = project; myFileStatusMap = fileStatusMap; editorFactory.getEventMulticaster().addDocumentListener(new DocumentAdapter() { @Override public void beforeDocumentChange(DocumentEvent e) { final Document document = e.getDocument(); if (documentManager.getSynchronizer().isInSynchronization(document)) return; if (documentManager.getCachedPsiFile(document) == null) return; if (document.getUserData(UPDATE_ON_COMMIT_ENGAGED) == null) { document.putUserData(UPDATE_ON_COMMIT_ENGAGED, Boolean.TRUE); PsiDocumentManagerBase.addRunOnCommit(document, new Runnable() { @Override public void run() { if (document.getUserData(UPDATE_ON_COMMIT_ENGAGED) != null) { updateChangesForDocument(document); document.putUserData(UPDATE_ON_COMMIT_ENGAGED, null); } } }); } } }, this); connection.subscribe(PsiDocumentTransactionListener.TOPIC, new PsiDocumentTransactionListener() { @Override public void transactionStarted(@NotNull final Document doc, @NotNull final PsiFile file) { } @Override public void transactionCompleted(@NotNull final Document document, @NotNull final PsiFile file) { updateChangesForDocument(document); document.putUserData(UPDATE_ON_COMMIT_ENGAGED, null); // ensure we don't call updateChangesForDocument() twice which can lead to whole file re-highlight } }); } @Override public void dispose() { } private void updateChangesForDocument(@NotNull final Document document) { if (DaemonListeners.isUnderIgnoredAction(null) || myProject.isDisposed()) return; List<Pair<PsiElement, Boolean>> toUpdate = changedElements.get(document); if (toUpdate == null) { // The document has been changed, but psi hasn't // We may still need to rehighlight the file if there were changes inside highlighted ranges. if (UpdateHighlightersUtil.isWhitespaceOptimizationAllowed(document)) return; // don't create PSI for files in other projects PsiElement file = PsiDocumentManager.getInstance(myProject).getCachedPsiFile(document); if (file == null) return; toUpdate = Collections.singletonList(Pair.create(file, true)); } Application application = ApplicationManager.getApplication(); final Editor editor = FileEditorManager.getInstance(myProject).getSelectedTextEditor(); if (editor != null && !application.isUnitTestMode()) { application.invokeLater(new Runnable() { @Override public void run() { if (!editor.isDisposed()) { EditorMarkupModel markupModel = (EditorMarkupModel)editor.getMarkupModel(); PsiFile file = PsiDocumentManager.getInstance(myProject).getPsiFile(editor.getDocument()); TrafficLightRenderer.setOrRefreshErrorStripeRenderer(markupModel, myProject, editor.getDocument(), file); } } }, ModalityState.stateForComponent(editor.getComponent()), myProject.getDisposed()); } for (Pair<PsiElement, Boolean> changedElement : toUpdate) { PsiElement element = changedElement.getFirst(); Boolean whiteSpaceOptimizationAllowed = changedElement.getSecond(); updateByChange(element, document, whiteSpaceOptimizationAllowed); } changedElements.remove(document); } @Override public void childAdded(@NotNull PsiTreeChangeEvent event) { queueElement(event.getParent(), true, event); } @Override public void childRemoved(@NotNull PsiTreeChangeEvent event) { queueElement(event.getParent(), true, event); } @Override public void childReplaced(@NotNull PsiTreeChangeEvent event) { queueElement(event.getNewChild(), typesEqual(event.getNewChild(), event.getOldChild()), event); } private static boolean typesEqual(final PsiElement newChild, final PsiElement oldChild) { return newChild != null && oldChild != null && newChild.getClass() == oldChild.getClass(); } @Override public void childrenChanged(@NotNull PsiTreeChangeEvent event) { if (((PsiTreeChangeEventImpl)event).isGenericChange()) { return; } queueElement(event.getParent(), true, event); } @Override public void beforeChildMovement(@NotNull PsiTreeChangeEvent event) { queueElement(event.getOldParent(), true, event); queueElement(event.getNewParent(), true, event); } @Override public void beforeChildrenChange(@NotNull PsiTreeChangeEvent event) { // this event sent always before every PSI change, even not significant one (like after quick typing/backspacing char) // mark file dirty just in case PsiFile psiFile = event.getFile(); if (psiFile != null) { myFileStatusMap.markFileScopeDirtyDefensively(psiFile, event); } } @Override public void propertyChanged(@NotNull PsiTreeChangeEvent event) { String propertyName = event.getPropertyName(); if (!propertyName.equals(PsiTreeChangeEvent.PROP_WRITABLE)) { Object oldValue = event.getOldValue(); if (oldValue instanceof VirtualFile && shouldBeIgnored((VirtualFile)oldValue)) { // ignore workspace.xml return; } myFileStatusMap.markAllFilesDirty(event); } } private void queueElement(@NotNull PsiElement child, final boolean whitespaceOptimizationAllowed, @NotNull PsiTreeChangeEvent event) { PsiFile file = event.getFile(); if (file == null) file = child.getContainingFile(); if (file == null) { myFileStatusMap.markAllFilesDirty(child); return; } if (!child.isValid()) return; Document document = PsiDocumentManager.getInstance(myProject).getCachedDocument(file); if (document != null) { List<Pair<PsiElement, Boolean>> toUpdate = changedElements.get(document); if (toUpdate == null) { toUpdate = new SmartList<Pair<PsiElement, Boolean>>(); changedElements.put(document, toUpdate); } toUpdate.add(Pair.create(child, whitespaceOptimizationAllowed)); } } private void updateByChange(@NotNull PsiElement child, @NotNull final Document document, final boolean whitespaceOptimizationAllowed) { final PsiFile file; try { file = child.getContainingFile(); } catch (PsiInvalidElementAccessException e) { myFileStatusMap.markAllFilesDirty(e); return; } if (file == null || file instanceof PsiCompiledElement) { myFileStatusMap.markAllFilesDirty(child); return; } VirtualFile virtualFile = file.getVirtualFile(); if (virtualFile != null && shouldBeIgnored(virtualFile)) { // ignore workspace.xml return; } int fileLength = file.getTextLength(); if (!file.getViewProvider().isPhysical()) { myFileStatusMap.markFileScopeDirty(document, new TextRange(0, fileLength), fileLength, "Non-physical file update: "+file); return; } PsiElement element = whitespaceOptimizationAllowed && UpdateHighlightersUtil.isWhitespaceOptimizationAllowed(document) ? child : child.getParent(); while (true) { if (element == null || element instanceof PsiFile || element instanceof PsiDirectory) { myFileStatusMap.markAllFilesDirty("Top element: "+element); return; } final PsiElement scope = getChangeHighlightingScope(element); if (scope != null) { myFileStatusMap.markFileScopeDirty(document, scope.getTextRange(), fileLength, "Scope: "+scope); return; } element = element.getParent(); } } private boolean shouldBeIgnored(@NotNull VirtualFile virtualFile) { return ProjectCoreUtil.isProjectOrWorkspaceFile(virtualFile) || ProjectRootManager.getInstance(myProject).getFileIndex().isExcluded(virtualFile); } @Nullable private static PsiElement getChangeHighlightingScope(@NotNull PsiElement element) { DefaultChangeLocalityDetector defaultDetector = null; for (ChangeLocalityDetector detector : Extensions.getExtensions(EP_NAME)) { if (detector instanceof DefaultChangeLocalityDetector) { // run default detector last assert defaultDetector == null : defaultDetector; defaultDetector = (DefaultChangeLocalityDetector)detector; continue; } final PsiElement scope = detector.getChangeHighlightingDirtyScopeFor(element); if (scope != null) return scope; } assert defaultDetector != null : "com.intellij.codeInsight.daemon.impl.DefaultChangeLocalityDetector is unregistered"; return defaultDetector.getChangeHighlightingDirtyScopeFor(element); } }
platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/PsiChangeHandler.java
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.codeInsight.daemon.impl; import com.intellij.codeInsight.daemon.ChangeLocalityDetector; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.EditorFactory; import com.intellij.openapi.editor.event.DocumentAdapter; import com.intellij.openapi.editor.event.DocumentEvent; import com.intellij.openapi.editor.ex.EditorMarkupModel; import com.intellij.openapi.extensions.ExtensionPointName; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectCoreUtil; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.psi.impl.PsiDocumentManagerBase; import com.intellij.psi.impl.PsiDocumentManagerImpl; import com.intellij.psi.impl.PsiDocumentTransactionListener; import com.intellij.psi.impl.PsiTreeChangeEventImpl; import com.intellij.util.SmartList; import com.intellij.util.messages.MessageBusConnection; import gnu.trove.THashMap; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collections; import java.util.List; import java.util.Map; class PsiChangeHandler extends PsiTreeChangeAdapter implements Disposable { private static final ExtensionPointName<ChangeLocalityDetector> EP_NAME = ExtensionPointName.create("com.intellij.daemon.changeLocalityDetector"); private /*NOT STATIC!!!*/ final Key<Boolean> UPDATE_ON_COMMIT_ENGAGED = Key.create("UPDATE_ON_COMMIT_ENGAGED"); private final Project myProject; private final Map<Document, List<Pair<PsiElement, Boolean>>> changedElements = new THashMap<Document, List<Pair<PsiElement, Boolean>>>(); private final FileStatusMap myFileStatusMap; PsiChangeHandler(@NotNull Project project, @NotNull final PsiDocumentManagerImpl documentManager, @NotNull EditorFactory editorFactory, @NotNull MessageBusConnection connection, @NotNull FileStatusMap fileStatusMap) { myProject = project; myFileStatusMap = fileStatusMap; editorFactory.getEventMulticaster().addDocumentListener(new DocumentAdapter() { @Override public void beforeDocumentChange(DocumentEvent e) { final Document document = e.getDocument(); if (documentManager.getSynchronizer().isInSynchronization(document)) return; if (documentManager.getCachedPsiFile(document) == null) return; if (document.getUserData(UPDATE_ON_COMMIT_ENGAGED) == null) { document.putUserData(UPDATE_ON_COMMIT_ENGAGED, Boolean.TRUE); PsiDocumentManagerBase.addRunOnCommit(document, new Runnable() { @Override public void run() { if (document.getUserData(UPDATE_ON_COMMIT_ENGAGED) != null) { updateChangesForDocument(document); document.putUserData(UPDATE_ON_COMMIT_ENGAGED, null); } } }); } } }, this); connection.subscribe(PsiDocumentTransactionListener.TOPIC, new PsiDocumentTransactionListener() { @Override public void transactionStarted(@NotNull final Document doc, @NotNull final PsiFile file) { } @Override public void transactionCompleted(@NotNull final Document document, @NotNull final PsiFile file) { updateChangesForDocument(document); document.putUserData(UPDATE_ON_COMMIT_ENGAGED, null); // ensure we don't call updateChangesForDocument() twice which can lead to whole file re-highlight } }); } @Override public void dispose() { } private void updateChangesForDocument(@NotNull final Document document) { if (DaemonListeners.isUnderIgnoredAction(null) || myProject.isDisposed()) return; List<Pair<PsiElement, Boolean>> toUpdate = changedElements.get(document); if (toUpdate == null) { // The document has been changed, but psi hasn't // We may still need to rehighlight the file if there were changes inside highlighted ranges. if (UpdateHighlightersUtil.isWhitespaceOptimizationAllowed(document)) return; // don't create PSI for files in other projects PsiElement file = PsiDocumentManager.getInstance(myProject).getCachedPsiFile(document); if (file == null) return; toUpdate = Collections.singletonList(Pair.create(file, true)); } Application application = ApplicationManager.getApplication(); final Editor editor = FileEditorManager.getInstance(myProject).getSelectedTextEditor(); if (editor != null && !application.isUnitTestMode()) { application.invokeLater(new Runnable() { @Override public void run() { if (!editor.isDisposed()) { EditorMarkupModel markupModel = (EditorMarkupModel)editor.getMarkupModel(); PsiFile file = PsiDocumentManager.getInstance(myProject).getPsiFile(editor.getDocument()); TrafficLightRenderer.setOrRefreshErrorStripeRenderer(markupModel, myProject, editor.getDocument(), file); } } }, ModalityState.stateForComponent(editor.getComponent()), myProject.getDisposed()); } for (Pair<PsiElement, Boolean> changedElement : toUpdate) { PsiElement element = changedElement.getFirst(); Boolean whiteSpaceOptimizationAllowed = changedElement.getSecond(); updateByChange(element, document, whiteSpaceOptimizationAllowed); } changedElements.remove(document); } @Override public void childAdded(@NotNull PsiTreeChangeEvent event) { queueElement(event.getParent(), true, event); } @Override public void childRemoved(@NotNull PsiTreeChangeEvent event) { queueElement(event.getParent(), true, event); } @Override public void childReplaced(@NotNull PsiTreeChangeEvent event) { queueElement(event.getNewChild(), typesEqual(event.getNewChild(), event.getOldChild()), event); } private static boolean typesEqual(final PsiElement newChild, final PsiElement oldChild) { return newChild != null && oldChild != null && newChild.getClass() == oldChild.getClass(); } @Override public void childrenChanged(@NotNull PsiTreeChangeEvent event) { if (((PsiTreeChangeEventImpl)event).isGenericChange()) { return; } queueElement(event.getParent(), true, event); } @Override public void beforeChildMovement(@NotNull PsiTreeChangeEvent event) { queueElement(event.getOldParent(), true, event); queueElement(event.getNewParent(), true, event); } @Override public void beforeChildrenChange(@NotNull PsiTreeChangeEvent event) { // this event sent always before every PSI change, even not significant one (like after quick typing/backspacing char) // mark file dirty just in case PsiFile psiFile = event.getFile(); if (psiFile != null) { myFileStatusMap.markFileScopeDirtyDefensively(psiFile, event); } } @Override public void propertyChanged(@NotNull PsiTreeChangeEvent event) { String propertyName = event.getPropertyName(); if (!propertyName.equals(PsiTreeChangeEvent.PROP_WRITABLE)) { Object oldValue = event.getOldValue(); if (oldValue instanceof VirtualFile && ProjectCoreUtil.isProjectOrWorkspaceFile((VirtualFile)oldValue)) { // ignore workspace.xml return; } myFileStatusMap.markAllFilesDirty(event); } } private void queueElement(@NotNull PsiElement child, final boolean whitespaceOptimizationAllowed, @NotNull PsiTreeChangeEvent event) { PsiFile file = event.getFile(); if (file == null) file = child.getContainingFile(); if (file == null) { myFileStatusMap.markAllFilesDirty(child); return; } if (!child.isValid()) return; Document document = PsiDocumentManager.getInstance(myProject).getCachedDocument(file); if (document != null) { List<Pair<PsiElement, Boolean>> toUpdate = changedElements.get(document); if (toUpdate == null) { toUpdate = new SmartList<Pair<PsiElement, Boolean>>(); changedElements.put(document, toUpdate); } toUpdate.add(Pair.create(child, whitespaceOptimizationAllowed)); } } private void updateByChange(@NotNull PsiElement child, @NotNull final Document document, final boolean whitespaceOptimizationAllowed) { final PsiFile file; try { file = child.getContainingFile(); } catch (PsiInvalidElementAccessException e) { myFileStatusMap.markAllFilesDirty(e); return; } if (file == null || file instanceof PsiCompiledElement) { myFileStatusMap.markAllFilesDirty(child); return; } VirtualFile virtualFile = file.getVirtualFile(); if (virtualFile != null && ProjectCoreUtil.isProjectOrWorkspaceFile(virtualFile)) { // ignore workspace.xml return; } int fileLength = file.getTextLength(); if (!file.getViewProvider().isPhysical()) { myFileStatusMap.markFileScopeDirty(document, new TextRange(0, fileLength), fileLength, "Non-physical file update: "+file); return; } PsiElement element = whitespaceOptimizationAllowed && UpdateHighlightersUtil.isWhitespaceOptimizationAllowed(document) ? child : child.getParent(); while (true) { if (element == null || element instanceof PsiFile || element instanceof PsiDirectory) { myFileStatusMap.markAllFilesDirty("Top element: "+element); return; } final PsiElement scope = getChangeHighlightingScope(element); if (scope != null) { myFileStatusMap.markFileScopeDirty(document, scope.getTextRange(), fileLength, "Scope: "+scope); return; } element = element.getParent(); } } @Nullable private static PsiElement getChangeHighlightingScope(@NotNull PsiElement element) { DefaultChangeLocalityDetector defaultDetector = null; for (ChangeLocalityDetector detector : Extensions.getExtensions(EP_NAME)) { if (detector instanceof DefaultChangeLocalityDetector) { // run default detector last assert defaultDetector == null : defaultDetector; defaultDetector = (DefaultChangeLocalityDetector)detector; continue; } final PsiElement scope = detector.getChangeHighlightingDirtyScopeFor(element); if (scope != null) return scope; } assert defaultDetector != null : "com.intellij.codeInsight.daemon.impl.DefaultChangeLocalityDetector is unregistered"; return defaultDetector.getChangeHighlightingDirtyScopeFor(element); } }
ignore excluded files modifications during highlighting
platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/PsiChangeHandler.java
ignore excluded files modifications during highlighting
Java
apache-2.0
25f1173819d791413a148c4b99667d4b0c3e03e7
0
kdwink/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,Lekanich/intellij-community,robovm/robovm-studio,apixandru/intellij-community,suncycheng/intellij-community,ol-loginov/intellij-community,MichaelNedzelsky/intellij-community,apixandru/intellij-community,fitermay/intellij-community,apixandru/intellij-community,MER-GROUP/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,Lekanich/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,robovm/robovm-studio,vvv1559/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,da1z/intellij-community,Distrotech/intellij-community,michaelgallacher/intellij-community,blademainer/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,fengbaicanhe/intellij-community,michaelgallacher/intellij-community,wreckJ/intellij-community,gnuhub/intellij-community,adedayo/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,ivan-fedorov/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community,ol-loginov/intellij-community,signed/intellij-community,salguarnieri/intellij-community,petteyg/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,dslomov/intellij-community,supersven/intellij-community,petteyg/intellij-community,signed/intellij-community,signed/intellij-community,nicolargo/intellij-community,SerCeMan/intellij-community,holmes/intellij-community,semonte/intellij-community,nicolargo/intellij-community,Lekanich/intellij-community,jagguli/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,ftomassetti/intellij-community,MichaelNedzelsky/intellij-community,dslomov/intellij-community,signed/intellij-community,pwoodworth/intellij-community,orekyuu/intellij-community,fnouama/intellij-community,fitermay/intellij-community,akosyakov/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,Distrotech/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,caot/intellij-community,ivan-fedorov/intellij-community,jagguli/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,jagguli/intellij-community,ahb0327/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,signed/intellij-community,samthor/intellij-community,ol-loginov/intellij-community,ryano144/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,suncycheng/intellij-community,izonder/intellij-community,vladmm/intellij-community,amith01994/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,Distrotech/intellij-community,asedunov/intellij-community,pwoodworth/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,caot/intellij-community,retomerz/intellij-community,izonder/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,caot/intellij-community,SerCeMan/intellij-community,slisson/intellij-community,slisson/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,holmes/intellij-community,MichaelNedzelsky/intellij-community,ryano144/intellij-community,asedunov/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,TangHao1987/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,robovm/robovm-studio,kool79/intellij-community,jagguli/intellij-community,Lekanich/intellij-community,Distrotech/intellij-community,samthor/intellij-community,xfournet/intellij-community,FHannes/intellij-community,petteyg/intellij-community,FHannes/intellij-community,alphafoobar/intellij-community,suncycheng/intellij-community,allotria/intellij-community,fitermay/intellij-community,MichaelNedzelsky/intellij-community,ahb0327/intellij-community,ryano144/intellij-community,diorcety/intellij-community,alphafoobar/intellij-community,da1z/intellij-community,pwoodworth/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,holmes/intellij-community,retomerz/intellij-community,nicolargo/intellij-community,tmpgit/intellij-community,gnuhub/intellij-community,ryano144/intellij-community,FHannes/intellij-community,vladmm/intellij-community,MichaelNedzelsky/intellij-community,supersven/intellij-community,hurricup/intellij-community,ibinti/intellij-community,Lekanich/intellij-community,ol-loginov/intellij-community,wreckJ/intellij-community,holmes/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,fnouama/intellij-community,hurricup/intellij-community,ivan-fedorov/intellij-community,xfournet/intellij-community,akosyakov/intellij-community,adedayo/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,gnuhub/intellij-community,vladmm/intellij-community,vladmm/intellij-community,ivan-fedorov/intellij-community,Lekanich/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,tmpgit/intellij-community,clumsy/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,holmes/intellij-community,vladmm/intellij-community,slisson/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,fnouama/intellij-community,pwoodworth/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,semonte/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,izonder/intellij-community,xfournet/intellij-community,fnouama/intellij-community,FHannes/intellij-community,amith01994/intellij-community,SerCeMan/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,dslomov/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,signed/intellij-community,diorcety/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,fnouama/intellij-community,idea4bsd/idea4bsd,Distrotech/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,nicolargo/intellij-community,da1z/intellij-community,ahb0327/intellij-community,diorcety/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,suncycheng/intellij-community,kool79/intellij-community,kdwink/intellij-community,petteyg/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,akosyakov/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,nicolargo/intellij-community,da1z/intellij-community,vvv1559/intellij-community,tmpgit/intellij-community,caot/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,adedayo/intellij-community,adedayo/intellij-community,kdwink/intellij-community,Distrotech/intellij-community,ftomassetti/intellij-community,adedayo/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,jagguli/intellij-community,FHannes/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,da1z/intellij-community,ibinti/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,izonder/intellij-community,da1z/intellij-community,wreckJ/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,dslomov/intellij-community,apixandru/intellij-community,gnuhub/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,fengbaicanhe/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,diorcety/intellij-community,vvv1559/intellij-community,caot/intellij-community,izonder/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,vvv1559/intellij-community,kool79/intellij-community,allotria/intellij-community,semonte/intellij-community,TangHao1987/intellij-community,nicolargo/intellij-community,da1z/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,idea4bsd/idea4bsd,robovm/robovm-studio,apixandru/intellij-community,ol-loginov/intellij-community,allotria/intellij-community,Lekanich/intellij-community,kdwink/intellij-community,clumsy/intellij-community,retomerz/intellij-community,semonte/intellij-community,holmes/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,clumsy/intellij-community,kool79/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,robovm/robovm-studio,lucafavatella/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,vladmm/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,petteyg/intellij-community,michaelgallacher/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,fnouama/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,supersven/intellij-community,apixandru/intellij-community,diorcety/intellij-community,amith01994/intellij-community,fnouama/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,muntasirsyed/intellij-community,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,caot/intellij-community,slisson/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,slisson/intellij-community,retomerz/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,SerCeMan/intellij-community,holmes/intellij-community,michaelgallacher/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,clumsy/intellij-community,da1z/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,ryano144/intellij-community,fengbaicanhe/intellij-community,amith01994/intellij-community,alphafoobar/intellij-community,supersven/intellij-community,michaelgallacher/intellij-community,kdwink/intellij-community,suncycheng/intellij-community,petteyg/intellij-community,caot/intellij-community,SerCeMan/intellij-community,SerCeMan/intellij-community,semonte/intellij-community,semonte/intellij-community,robovm/robovm-studio,asedunov/intellij-community,signed/intellij-community,suncycheng/intellij-community,orekyuu/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,kdwink/intellij-community,vladmm/intellij-community,samthor/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,clumsy/intellij-community,TangHao1987/intellij-community,pwoodworth/intellij-community,samthor/intellij-community,supersven/intellij-community,supersven/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,izonder/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,salguarnieri/intellij-community,slisson/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,ryano144/intellij-community,Lekanich/intellij-community,fengbaicanhe/intellij-community,TangHao1987/intellij-community,SerCeMan/intellij-community,tmpgit/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,kool79/intellij-community,adedayo/intellij-community,FHannes/intellij-community,ryano144/intellij-community,Lekanich/intellij-community,ThiagoGarciaAlves/intellij-community,tmpgit/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,orekyuu/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,semonte/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,slisson/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,adedayo/intellij-community,petteyg/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,muntasirsyed/intellij-community,fengbaicanhe/intellij-community,ftomassetti/intellij-community,dslomov/intellij-community,fengbaicanhe/intellij-community,supersven/intellij-community,amith01994/intellij-community,fitermay/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,gnuhub/intellij-community,clumsy/intellij-community,kool79/intellij-community,ahb0327/intellij-community,petteyg/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,dslomov/intellij-community,samthor/intellij-community,slisson/intellij-community,dslomov/intellij-community,izonder/intellij-community,caot/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,hurricup/intellij-community,xfournet/intellij-community,adedayo/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,suncycheng/intellij-community,alphafoobar/intellij-community,tmpgit/intellij-community,signed/intellij-community,ibinti/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,amith01994/intellij-community,nicolargo/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,slisson/intellij-community,hurricup/intellij-community,blademainer/intellij-community,fitermay/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,ahb0327/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,vvv1559/intellij-community,gnuhub/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community,retomerz/intellij-community,adedayo/intellij-community,signed/intellij-community,kool79/intellij-community,robovm/robovm-studio,fnouama/intellij-community,supersven/intellij-community,petteyg/intellij-community,signed/intellij-community,diorcety/intellij-community,retomerz/intellij-community,alphafoobar/intellij-community,retomerz/intellij-community,retomerz/intellij-community,allotria/intellij-community,holmes/intellij-community,petteyg/intellij-community,xfournet/intellij-community,fnouama/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,allotria/intellij-community,ftomassetti/intellij-community,ivan-fedorov/intellij-community,SerCeMan/intellij-community,MichaelNedzelsky/intellij-community,MER-GROUP/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,fitermay/intellij-community,apixandru/intellij-community,slisson/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,ahb0327/intellij-community,tmpgit/intellij-community,fnouama/intellij-community,allotria/intellij-community,samthor/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,ryano144/intellij-community,asedunov/intellij-community,supersven/intellij-community,hurricup/intellij-community,samthor/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,da1z/intellij-community,MichaelNedzelsky/intellij-community,nicolargo/intellij-community,idea4bsd/idea4bsd,MER-GROUP/intellij-community,samthor/intellij-community,slisson/intellij-community,samthor/intellij-community,Distrotech/intellij-community,semonte/intellij-community,pwoodworth/intellij-community,tmpgit/intellij-community,retomerz/intellij-community,diorcety/intellij-community,tmpgit/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,nicolargo/intellij-community,petteyg/intellij-community,adedayo/intellij-community,signed/intellij-community,ahb0327/intellij-community,amith01994/intellij-community,ol-loginov/intellij-community,idea4bsd/idea4bsd,robovm/robovm-studio,ahb0327/intellij-community,wreckJ/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,caot/intellij-community,adedayo/intellij-community,semonte/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,xfournet/intellij-community,holmes/intellij-community,kdwink/intellij-community,supersven/intellij-community,fnouama/intellij-community,vladmm/intellij-community,diorcety/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,ahb0327/intellij-community,jagguli/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,ivan-fedorov/intellij-community,holmes/intellij-community,kool79/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,hurricup/intellij-community,robovm/robovm-studio,ThiagoGarciaAlves/intellij-community,adedayo/intellij-community,kdwink/intellij-community,kool79/intellij-community,gnuhub/intellij-community,holmes/intellij-community,blademainer/intellij-community,suncycheng/intellij-community,kool79/intellij-community,suncycheng/intellij-community,da1z/intellij-community,vladmm/intellij-community,TangHao1987/intellij-community,caot/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,fengbaicanhe/intellij-community,kdwink/intellij-community,dslomov/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,blademainer/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,tmpgit/intellij-community,vvv1559/intellij-community,izonder/intellij-community,clumsy/intellij-community,fengbaicanhe/intellij-community,allotria/intellij-community,wreckJ/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,ryano144/intellij-community,hurricup/intellij-community,MichaelNedzelsky/intellij-community,caot/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,clumsy/intellij-community,ftomassetti/intellij-community,kdwink/intellij-community,caot/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,ftomassetti/intellij-community,pwoodworth/intellij-community,slisson/intellij-community,ol-loginov/intellij-community,tmpgit/intellij-community,hurricup/intellij-community,holmes/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,diorcety/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,blademainer/intellij-community,petteyg/intellij-community,TangHao1987/intellij-community,ryano144/intellij-community,samthor/intellij-community,fitermay/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,samthor/intellij-community,SerCeMan/intellij-community,gnuhub/intellij-community,nicolargo/intellij-community,amith01994/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,diorcety/intellij-community,ftomassetti/intellij-community,MichaelNedzelsky/intellij-community,ftomassetti/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,ivan-fedorov/intellij-community,blademainer/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,asedunov/intellij-community,xfournet/intellij-community,jagguli/intellij-community,wreckJ/intellij-community
package com.intellij.structuralsearch.plugin.ui; import com.intellij.navigation.ItemPresentation; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.fileEditor.FileEditor; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.structuralsearch.SSRBundle; import com.intellij.usages.Usage; import com.intellij.usages.UsageTarget; import com.intellij.usages.UsageView; import com.intellij.usages.UsageViewPresentation; import com.intellij.psi.PsiFile; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.util.Set; /** * Created by IntelliJ IDEA. * User: Maxim.Mossienko * Date: Mar 9, 2005 * Time: 2:47:49 PM * To change this template use File | Settings | File Templates. */ public class UsageViewContext { protected final SearchContext mySearchContext; private UsageView myUsageView; protected final Configuration myConfiguration; private Set<Usage> myExcludedSet; private SearchCommand myCommand; protected UsageViewContext(SearchContext _searchContext,Configuration _configuration) { myConfiguration = _configuration; mySearchContext = _searchContext; } public boolean isExcluded(Usage usage) { if (myExcludedSet == null) myExcludedSet = myUsageView.getExcludedUsages(); return myExcludedSet.contains(usage); } public UsageView getUsageView() { return myUsageView; } public void setUsageView(final UsageView usageView) { myUsageView = usageView; } public Configuration getConfiguration() { return myConfiguration; } public SearchCommand getCommand() { if (myCommand == null) setCommand(createCommand()); return myCommand; } private void setCommand(final SearchCommand command) { myCommand = command; } protected SearchCommand createCommand() { return new SearchCommand(mySearchContext.getProject(), this); } protected String _getPresentableText() { return myConfiguration.getMatchOptions().getSearchPattern(); } public UsageTarget getTarget() { return new MyUsageTarget(_getPresentableText()); } public void configure(final UsageViewPresentation presentation) { String s = _getPresentableText(); if (s.length() > 15) s = s.substring(0,15) + "..."; final String usagesString = SSRBundle.message("occurences.of", s); presentation.setUsagesString(usagesString); presentation.setTabText(StringUtil.capitalize(usagesString)); } private static class MyUsageTarget implements UsageTarget { private final String myPresentableText; MyUsageTarget(String str) { myPresentableText = str; } final ItemPresentation presentation = new ItemPresentation() { @Override public String getPresentableText() { return myPresentableText; } @Override public String getLocationString() { //noinspection HardCodedStringLiteral return "Do Not Know Where"; } @Override public Icon getIcon(boolean open) { return null; } }; @Override public void findUsages() { throw new UnsupportedOperationException(); } @Override public void findUsagesInEditor(@NotNull FileEditor editor) { throw new UnsupportedOperationException(); } @Override public void highlightUsages(PsiFile file, Editor editor, boolean clearHighlights) { throw new UnsupportedOperationException(); } @Override public boolean isValid() { return true; } @Override public boolean isReadOnly() { return true; } @Override public VirtualFile[] getFiles() { return null; } @Override public void update() { } @Override public String getName() { //noinspection HardCodedStringLiteral return "my name"; } @Override public ItemPresentation getPresentation() { return presentation; } @Override public void navigate(boolean requestFocus) { throw new UnsupportedOperationException(); } @Override public boolean canNavigate() { return false; } @Override public boolean canNavigateToSource() { return false; } } }
plugins/structuralsearch/source/com/intellij/structuralsearch/plugin/ui/UsageViewContext.java
package com.intellij.structuralsearch.plugin.ui; import com.intellij.navigation.ItemPresentation; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.fileEditor.FileEditor; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.structuralsearch.SSRBundle; import com.intellij.usages.Usage; import com.intellij.usages.UsageTarget; import com.intellij.usages.UsageView; import com.intellij.usages.UsageViewPresentation; import com.intellij.psi.PsiFile; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.util.Set; /** * Created by IntelliJ IDEA. * User: Maxim.Mossienko * Date: Mar 9, 2005 * Time: 2:47:49 PM * To change this template use File | Settings | File Templates. */ public class UsageViewContext { protected final SearchContext mySearchContext; private UsageView myUsageView; protected final Configuration myConfiguration; private Set<Usage> myExcludedSet; private SearchCommand myCommand; protected UsageViewContext(SearchContext _searchContext,Configuration _configuration) { myConfiguration = _configuration; mySearchContext = _searchContext; } public boolean isExcluded(Usage usage) { if (myExcludedSet == null) myExcludedSet = myUsageView.getExcludedUsages(); return myExcludedSet.contains(usage); } public UsageView getUsageView() { return myUsageView; } public void setUsageView(final UsageView usageView) { myUsageView = usageView; } public Configuration getConfiguration() { return myConfiguration; } public SearchCommand getCommand() { if (myCommand == null) setCommand(createCommand()); return myCommand; } private void setCommand(final SearchCommand command) { myCommand = command; } protected SearchCommand createCommand() { return new SearchCommand(mySearchContext.getProject(), this); } protected String _getPresentableText() { return myConfiguration.getMatchOptions().getSearchPattern(); } public UsageTarget getTarget() { return new MyUsageTarget(_getPresentableText()); } public void configure(final UsageViewPresentation presentation) { String s = _getPresentableText(); if (s.length() > 15) s = s.substring(0,15) + "..."; final String usagesString = SSRBundle.message("occurences.of", s); presentation.setUsagesString(usagesString); presentation.setTabText(StringUtil.capitalize(usagesString)); } private static class MyUsageTarget implements UsageTarget { private final String myPresentableText; MyUsageTarget(String str) { myPresentableText = str; } final ItemPresentation presentation = new ItemPresentation() { public String getPresentableText() { return myPresentableText; } public String getLocationString() { //noinspection HardCodedStringLiteral return "Do Not Know Where"; } public Icon getIcon(boolean open) { return null; } }; public void findUsages() { throw new UnsupportedOperationException(); } public void findUsagesInEditor(@NotNull FileEditor editor) { throw new UnsupportedOperationException(); } public void highlightUsages(PsiFile file, Editor editor, boolean clearHighlights) { throw new UnsupportedOperationException(); } public boolean isValid() { return true; } public boolean isReadOnly() { return true; } public VirtualFile[] getFiles() { return null; } public void update() { } public String getName() { //noinspection HardCodedStringLiteral return "my name"; } public ItemPresentation getPresentation() { return presentation; } public void navigate(boolean requestFocus) { throw new UnsupportedOperationException(); } public boolean canNavigate() { return false; } public boolean canNavigateToSource() { return false; } } }
cleanup
plugins/structuralsearch/source/com/intellij/structuralsearch/plugin/ui/UsageViewContext.java
cleanup
Java
apache-2.0
error: pathspec 'src/main/java/xdean/jex/util/function/Predicates.java' did not match any file(s) known to git
91c7d1e2c022dbd2d27a4d13fdcc44a4145bbe04
1
XDean/Java-EX
package xdean.jex.util.function; import java.util.Objects; import java.util.function.Function; import java.util.function.Predicate; public class Predicates { public static <T> Predicate<T> is(T t) { return o -> o == t; } public static <T> Predicate<T> not(T t) { return o -> o != t; } public static <T> Predicate<T> isEquals(T t) { return o -> Objects.equals(o, t); } public static <T> Predicate<T> notEquals(T t) { return o -> !Objects.equals(o, t); } public static <F, T> Predicate<F> its(Function<F, T> keySelector, Predicate<T> p) { return o -> p.test(keySelector.apply(o)); } }
src/main/java/xdean/jex/util/function/Predicates.java
Predicates
src/main/java/xdean/jex/util/function/Predicates.java
Predicates
Java
apache-2.0
error: pathspec 'src/test/org/apache/solr/analysis/HTMLStripReaderTest.java' did not match any file(s) known to git
784586df47ed52f403ddf1cf3f4d3a94c3bc2ce5
1
apache/solr,apache/solr,apache/solr,apache/solr,apache/solr
package org.apache.solr.analysis; /** * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import junit.framework.TestCase; import java.io.StringReader; import java.io.IOException; import java.io.FileReader; import java.io.File; import java.io.Reader; import java.util.Set; import java.util.HashSet; import java.util.Collections; public class HTMLStripReaderTest extends TestCase { public HTMLStripReaderTest(String s) { super(s); } protected void setUp() { } protected void tearDown() { } //this is some text here is a link and another link . This is an entity: & plus a <. Here is an & // public void test() throws IOException { String html = "<div class=\"foo\">this is some text</div> here is a <a href=\"#bar\">link</a> and " + "another <a href=\"http://lucene.apache.org/\">link</a>. " + "This is an entity: &amp; plus a &lt;. Here is an &. <!-- is a comment -->"; String gold = " this is some text here is a link and " + "another link . " + "This is an entity: & plus a <. Here is an &. "; HTMLStripReader reader = new HTMLStripReader(new StringReader(html)); StringBuilder builder = new StringBuilder(); int ch = -1; char [] goldArray = gold.toCharArray(); int position = 0; while ((ch = reader.read()) != -1){ char theChar = (char) ch; builder.append(theChar); assertTrue("\"" + theChar + "\"" + " at position: " + position + " does not equal: " + goldArray[position] + " Buffer so far: " + builder + "<EOB>", theChar == goldArray[position]); position++; } assertTrue(gold + " is not equal to " + builder.toString(), gold.equals(builder.toString()) == true); } //Some sanity checks, but not a full-fledged check public void testHTML() throws Exception { HTMLStripReader reader = new HTMLStripReader(new FileReader(new File("htmlStripReaderTest.html"))); StringBuilder builder = new StringBuilder(); int ch = -1; while ((ch = reader.read()) != -1){ builder.append((char)ch); } String str = builder.toString(); assertTrue("Entity not properly escaped", str.indexOf("&lt;") == -1);//there is one > in the text assertTrue("Forrest should have been stripped out", str.indexOf("forrest") == -1 && str.indexOf("Forrest") == -1); assertTrue("File should start with 'Welcome to Solr' after trimming", str.trim().startsWith("Welcome to Solr")); assertTrue("File should start with 'Foundation.' after trimming", str.trim().endsWith("Foundation.")); } public void testReserved() throws Exception { String test = "aaa bbb <reserved ccc=\"ddddd\"> eeee </reserved> ffff <reserved ggg=\"hhhh\"/> <other/>"; Set<String> set = new HashSet<String>(); set.add("reserved"); Reader reader = new HTMLStripReader(new StringReader(test), set); StringBuilder builder = new StringBuilder(); int ch = 0; while ((ch = reader.read()) != -1){ builder.append((char)ch); } String result = builder.toString(); System.out.println("Result: " + result); assertTrue("Escaped tag not preserved: " + result.indexOf("reserved"), result.indexOf("reserved") == 9); assertTrue("Escaped tag not preserved: " + result.indexOf("reserved", 15), result.indexOf("reserved", 15) == 38); assertTrue("Escaped tag not preserved: " + result.indexOf("reserved", 41), result.indexOf("reserved", 41) == 54); assertTrue("Other tag should be removed", result.indexOf("other") == -1); } public void testStrip() throws Exception { String test = "{{aaaaaaaa|aaaaaaaaa|aaa [[aaaaaa aaaaaa]] [[aaaaaaaaa]]|aaaaaaaaa (aaaaaa)}}\n" + "{{aaaaaaaaa}}\n" + "'''aaaaaaaaa''' aa a [[aaaaaaaaa aaaaaaaaaa]] aa aaaaa aa aaaaaaaaa aaa aaaaaaaaa aaaaaaaa aa aaaaaaaaa aa aaa aaaa aa aaaaaaaaaa " + "[[aaaaaaaaaa]] ([[aa.]] \"[[aaaaa]]\"<ttt>aaaa aaaaaaaaaaaaa aaaaaaaaaa aaaa aaaaa: \"a aaaaaaaaaaa aaaa aa aaaaaaaa aa aaa aaaaaaaaa " + "aaaaa aa aaa aaaaaaaaaa aaaaaaa ''aaa aaaaaaaaaa'', aaaaaaaaa aa aaa aaaaa, aaa ''aaaaaaaaaa'', aaaaaaaaa aa aaa aaaaaaaaaaaaaa aa a aaaaaaaaa aaaaaa. aaaaaaaaaa, aaaa aaaaaaaa, " + "aaaa aa aaa aaa aaaa aaaaaaaaaa aa a aaaaaaa aaa aaaaa, aaa aaaa aa aaaaaaaa aa aaaaaaaaa'a ''a aaaaaa'' aaaaaaaaaa aa aaa aaaaa aa aaa aaa aaaaaaa aa aaaaaaaaaa aa aaaa aaa aaa " + "aaaa aa a aaaaaaaaa aaaaa aaaa aaaaaa aaa aaaaaaa aaaaaaaaa, aaa aa aaaaaaaaa, aaa aaaaa aa aaa aaaaaaaa. aaaaaaaaa aaaaaaa aaa aaaa aa aaaaaaa, aaaaaaaaaaa aaaaaaaaa aaaaaaaaa " + "aaa aaaa aaaaaaaa aa aaa aaaaa.\" -aaaaaaa, aaaa. aaaaaaaaa," + " aaaaaaaa aaaaa aaaa, a. aa-aa</ttt>) aaa aaaaaaaaaa aaa aaaaaaaaaaa.<ttt bbbb=bbbbbbbbbbb>''aaaaaaaaa''. aaaaaaaa¾aaa aaaaaaaaaa. aaaa. aaaaaaaa¾aaa aaaaaaaaaa aaaaaaa aaaaaaa. " + "[[aa aaaaaa]] [[aaaa]] <tttb://ccc.cccccccccc.ccc/cc/ccccccc-ccccccc>. aaaaaaaaa aa \"a aaaaaaa aa aaaaaaaaa aaa aaaaaaaaa aaaaaaa aa aaa aaaaaa aaaa aaaaaaaaaa aa aaaa aaaaaaa aaa " + "aaaaaaaaaaa.\"</ttt><ttt dddd=dddddddddddd>''aaaaaaaaa''. aaa aaaaaaa aaaaaaaaa aaaaaaaaaaaa aa aaaaaaaaaa. aaaa. a. aa" + " \"aaaaaaaaa aa aaa aaaa aaaa a aaaaaaa aaaaaaa aaa aaaaa, aa aaaaaaaaaa, aa aaaa aaaaaaaa aaa aaaaaaaaa.\"</ttt> aaa aaaa \"aaaaaaaaa\" " + "aa [[aaaaaaaaa|aaaaaaa aaaa]] aaa [[aaaaa aaaaaaaa|aaaaa]] ''[[aaaaaaaaaa:???????|???????]]'' (\"aaaaaaa [[aaaaaa]]a\" aa \"aaaaaaa aaaaaa\")." + " aaaa \"aaaaaaaaa\", aa aaa aaaa aaaaaaa aaaaaaa, aa aaa aaaaaa aaaa aaa aaaaa aa [[aaaaaaaaa]] (aaa aaaa aaaa [[aaaaaaaaaaa aaaaaaaaa]]) aaa " + "aaaaaaaaaaa aaa aaaaaa aa aaaaaaaaa. \n" + "\n" + "aaaaa aaa a aaaaaaa aa aaaaa aaa aaaaaaaaaa aa aaaaaaaaa aaaa aaaaaaa aaaaaa aa aaaaaaaaaa.<ttt>aaaaaaaaaa, aaaa aaaaaaaaaaa. ''aaaaaaaaa: a " + "aaaaaaaaaa aa aaaaaaaaaaaaa aaaaaaaa'', aaaaaaa aaaaa aaaaaaaaaaaa, aaaa, a.a</ttt><tttt>{{aaaa aaaaaaa|aaaaaa=a.a. aaaaaa|aaaaa=aaa aaaaaaaaa " + "aaaaaaaaa aa aaaaaaaaa aaaaaaa|aaaa=aaaa|aaaaaaa=aaaaaaa aaaaaaaaa aaaaaaaaa|aaaaaa=aa|aaaaa=a|aaaaa=aaa-aaa|aaa=aa.aaaa/aaaaaa}}</ttt> aaaaaaa," + " aaa aaaaaaaaa aaa aaa aaaaaaaaaaaa aaaa aaaaaaaaaaaaa aaa aaa aaa aa aaaa aaa aaaaaaaa aaaaaaaaa.<ttt>aaaaaa, aaaaaaa. aaaaaaaaa. a aaaaaaaaa aa " + "aaaaaaaaaaaa aaaaaaaaa aaaaaaaaaa, aaaaaaa aaaaaaa, aaaaaa a. aaa aaaaaa, aaaaaa. aaaaaaaaa aaaaaaaaaa, aaaa, a.aaa</ttt> aaaaa aaaa aaa aaaaaaaaaaa" + " aaaaa, \"aaaaa aa aa aaaaaa aaaaaaaa aaaaaaaa aaaa aaa aaaaaaaaaa aaaa, aaa aaaaa aaaaaaaaaa aaaaaaaaaa aa aaaa aaaaa a aaaaaaa [[aaaaaa aaaaaaaaaaa]].\"<ttt>aaaaaaaaa. " + "aaa aaaaaa aaaaaaaaa aa aaaaaaaaaa, aaaaaa aaaaaaaaaa aaaaa, aaaa, a. aa</ttt> aaaaaaaaa aaaaaaaa aaaaaaa aaa aaa aa aaa aaaa aaaaa aa aaaaaaaaaaaa aaa aaaaaaaaaa.<ttt>aaaaaaaa, " + "aaaaaa aaaaaaa \"aaaaaaaaa aaaaaaaa aaa aaa aaaaaaa aaaaa aaaaaaaa aa aaaaa, aaaa-aaaa\" [a. aaa]</ttt>\n" + "==aaaaaaa==\n" + "===aaa-aaaaaaaaaa aaaaaaa===\n" + "{{aaaa|aaaaaaa aa aaaaaaaaa}}\n" + "{{aaaaa aa aaaaaaaaaa}}\n" + "aaaaaaaaaa aa aaa aaaaa aaa aaaaaaaaaaaa aaaaaaaaa aaa a aaaa aaaaaaa aaaaa aa aaa aaaaaaaaa aa aaa aaaaaaaaa aaaaaaaa aa aaaaaaaaaa aaaaaaa aaaaaa. aaaa aaaaa aaaa aaaaaaaaa aaaaaa " + "aaa aa aaaaaaaa aa aaaaa aa aaa aa aaaaa aa aaa [[aaaaaa]] aaaa [[aaaaa|aaa aaa]],<ttt eeee=\"eeeeee\">aaaaa aaaaaaaaa, [aaaa://aaaaaaaa.aaaaaa.aaa/aaaaaaaaaaaaaaaaaa/aaaaaaaaa/aaaaaaaaaaaaaaaa.aaaa " + "\"aaaaaaaaa\", aaaa aaa aaaaaaaaaaaaa aaaaaaaaaa, aaaa]</ttt> aaaaaa aaaa aa a aaaaaaaaaaaaa" + " aaaaa.<ttt>{{aaaaaaa|[aaaa://aaa.aaaaaaaaaaaaaaaaa.aaa/aaa/aaaaaa/aaaaa--aaaaaaaaa.aaa]|aa.a&aaaa;[[aaaaaaaa|aaa]]" + "<!-- ggggggggggg/ggg, gggggg ggggg -->}}</aaa> [[aaaa aa aaaaaa]], aaa aaaaaaa aa [[aaaaaaaa]] aaaa aaaaaaaaaa aaaaaa aaaaa aaaaaaa aaaaaaaaa aaaaaa.<ttt ffff=\"ffffff\"/>\n" + "\n" + "aaaaaaaaa aa aaa aaaaaa aaaaa, aaaaaaa, aaa aaa aaaaa aa aaa aaaaaaa aaaaaaaaa aaaaaaa aa aaa [[aaa aa aaaaaaaaaaaaa|aaaaaaaaaaaaa]], aaaaaaaaaaaa [[aaaaaaaa]]'a aaaaaaaaa aaa aaa aaaaa " + "aaaaaaaaaa aa aaaaaaa.<ttt hhhh=hhhhhhh>''aaaaaaaaa'', aaaaaaaaa¨ aaaaaaa¨ aaaaaa aaaaaaaaaaaa aaaa (aa aaaaaaa) aaaa://aa.aaaaaaa.aaa.aaa © aaaa-aaaa aaaaaaaaa aaaaaaaaaaa. aaa aaaaaa aaaaaaaa\n" + "</ttt> aaa aaaa \"aaaaaaaaa\" aaa aaaaaaaaaa aaaa aa a aaaa aa [[aaaaa]], aaa aa aaa [[aaaaaa aaaaaaaaaa]] aaaa aaaaaa aaaa aa aaa ''aaaaaŽa'' aaa aaaaaaa aa aaa aaa aaaa aa a aaaaaaaa " + "aaaaa,<ttt>aaaaaaa, aaaa. ''aaaaaaaaa'', aaaaaa: aaaaaaaa aaaaa aaa., aaaa. aa. aa</ttt> aaaaaa aaa [[aaaaaaa (aaaaaaaa)|aaaaaaa]] aaaaaaa aa a \"aaaaaaaaaaaaa aaaaaaaaaa\" aa aa [[aaaaaaaa]]. " + "aa aaa aa aaaa aaaaaaaaa aaaaaaa aaaa [[aaaaaaa aaaaaa]] aaaaa aaaaaaa aaa aaaaaaaaaa, aaaaa aa aaaaaaaaaa aa aaaa aa aa aaa aaaaa aaaaaaaaaa aa aaaaaa aaaaaaaaa aaaaaaa." + "<ttt>[aaaa://aaaaa.aaaaaaaa.aaa/aaaaaaa/aaaaaa/ aaaaaaa aaaaaa] aaaaaaaa aaaaaaaaaaaa aa aaaaaaaaaa, aaaaa aaaaaaaaa aaa [[aa aaaaaaa]] [[aaaa]]; aaaaaaaaaaa aaaaaaaa aaa [[aaa aa]] [[aaaa]]</ttt>\n" + "\n" + "[[aaaaa aaaaaaaaaa]] aa ''[[aaa aaaaaaaaaaaa aa aaaaaa]]'' (aaaa) aaaa aaa aaaa [[zzzzzzz]] aa aaaaaaaa"; Reader reader = new HTMLStripReader(new StringReader(test)); Reader noStrip = new StringReader(test); int ch = 0; int ch2 = 0; int i = 0; StringBuilder builder = new StringBuilder(); while ((ch = reader.read()) != -1 && (ch2 = noStrip.read()) != -1){ //System.out.println("char[" + i + "] = '" + (char)ch + "' NS: '" + (char)ch2 + "'" + ((ch != ch2 && (ch2 != 't' || ch2 != '<' || ch2 != '>')) ? "<<<<<<<<<<<<<<<<<<<<<<<<" : "")); assertTrue(ch + " does not equal: " + "t or < or > ::: String: " + builder.toString(), ch == ch2 || ch == ' '/*&& ch != '<' && ch != '>'*/); builder.append((char)ch); i++; } } }
src/test/org/apache/solr/analysis/HTMLStripReaderTest.java
SOLR-42: test missed from previous commit git-svn-id: 3b1ff1236863b4d63a22e4dae568675c2e247730@609334 13f79535-47bb-0310-9956-ffa450edef68
src/test/org/apache/solr/analysis/HTMLStripReaderTest.java
SOLR-42: test missed from previous commit
Java
apache-2.0
error: pathspec 'dmm4j-core/src/main/java/dmm4j/conf/PropertyConfiguration.java' did not match any file(s) known to git
ffceb761d2c6826aa8b52c7cefd82208962eadf1
1
nikuyoshi/dmm4j
/* * Copyright 2015 Hiroki Uchida * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dmm4j.conf; import java.io.*; import java.util.ArrayList; import java.util.Map; import java.util.Properties; /** * @author nikuyoshi */ public final class PropertyConfiguration extends ConfigurationBase implements java.io.Serializable { private static final String DEBUG = "debug"; private static final String USER = "user"; private static final String PASSWORD = "password"; private static final String HTTP_PRETTY_DEBUG = "http.prettyDebug"; private static final String HTTP_GZIP = "http.gzip"; private static final String HTTP_PROXY_HOST = "http.proxyHost"; private static final String HTTP_PROXY_HOST_FALLBACK = "http.proxyHost"; private static final String HTTP_PROXY_USER = "http.proxyUser"; private static final String HTTP_PROXY_PASSWORD = "http.proxyPassword"; private static final String HTTP_PROXY_PORT = "http.proxyPort"; private static final String HTTP_PROXY_PORT_FALLBACK = "http.proxyPort"; private static final String HTTP_CONNECTION_TIMEOUT = "http.connectionTimeout"; private static final String HTTP_READ_TIMEOUT = "http.readTimeout"; private static final String HTTP_STREAMING_READ_TIMEOUT = "http.streamingReadTimeout"; private static final String HTTP_RETRY_COUNT = "http.retryCount"; private static final String HTTP_RETRY_INTERVAL_SECS = "http.retryIntervalSecs"; private static final String OAUTH_CONSUMER_KEY = "oauth.consumerKey"; private static final String OAUTH_CONSUMER_SECRET = "oauth.consumerSecret"; private static final String OAUTH_ACCESS_TOKEN = "oauth.accessToken"; private static final String OAUTH_ACCESS_TOKEN_SECRET = "oauth.accessTokenSecret"; private static final String OAUTH2_TOKEN_TYPE = "oauth2.tokenType"; private static final String OAUTH2_ACCESS_TOKEN = "oauth2.accessToken"; private static final String OAUTH2_SCOPE = "oauth2.scope"; private static final String OAUTH_REQUEST_TOKEN_URL = "oauth.requestTokenURL"; private static final String OAUTH_AUTHORIZATION_URL = "oauth.authorizationURL"; private static final String OAUTH_ACCESS_TOKEN_URL = "oauth.accessTokenURL"; private static final String OAUTH_AUTHENTICATION_URL = "oauth.authenticationURL"; private static final String OAUTH2_TOKEN_URL = "oauth2.tokenURL"; private static final String OAUTH2_INVALIDATE_TOKEN_URL = "oauth2.invalidateTokenURL"; private static final String REST_BASE_URL = "restBaseURL"; private static final String STREAM_BASE_URL = "streamBaseURL"; private static final String USER_STREAM_BASE_URL = "userStreamBaseURL"; private static final String SITE_STREAM_BASE_URL = "siteStreamBaseURL"; private static final String ASYNC_NUM_THREADS = "async.numThreads"; private static final String ASYNC_DAEMON_ENABLED = "async.daemonEnabled"; private static final String CONTRIBUTING_TO = "contributingTo"; private static final String ASYNC_DISPATCHER_IMPL = "async.dispatcherImpl"; private static final String INCLUDE_MY_RETWEET = "includeMyRetweet"; private static final String INCLUDE_ENTITIES = "includeEntities"; private static final String LOGGER_FACTORY = "loggerFactory"; private static final String JSON_STORE_ENABLED = "jsonStoreEnabled"; private static final String MBEAN_ENABLED = "mbeanEnabled"; private static final String STREAM_USER_REPLIES_ALL = "stream.user.repliesAll"; private static final String STREAM_USER_WITH_FOLLOWINGS = "stream.user.withFollowings"; private static final String STREAM_STALL_WARNINGS_ENABLED = "stream.enableStallWarnings"; private static final String APPLICATION_ONLY_AUTH_ENABLED = "enableApplicationOnlyAuth"; private static final String MEDIA_PROVIDER = "media.provider"; private static final String MEDIA_PROVIDER_API_KEY = "media.providerAPIKey"; private static final String MEDIA_PROVIDER_PARAMETERS = "media.providerParameters"; private static final long serialVersionUID = -7262615247923693252L; private String OAuth2Scope; public PropertyConfiguration(InputStream is) { super(); Properties props = new Properties(); loadProperties(props, is); setFieldsWithTreePath(props, "/"); } public PropertyConfiguration(Properties props) { this(props, "/"); } public PropertyConfiguration(Properties props, String treePath) { super(); setFieldsWithTreePath(props, treePath); } PropertyConfiguration(String treePath) { super(); Properties props; // load from system properties try { props = (Properties) System.getProperties().clone(); try { Map<String, String> envMap = System.getenv(); for (String key : envMap.keySet()) { props.setProperty(key, envMap.get(key)); } } catch (SecurityException ignore) { } normalize(props); } catch (SecurityException ignore) { // Unsigned applets are not allowed to access System properties props = new Properties(); } final String TWITTER4J_PROPERTIES = "twitter4j.properties"; // override System properties with ./twitter4j.properties in the classpath loadProperties(props, "." + File.separatorChar + TWITTER4J_PROPERTIES); // then, override with /twitter4j.properties in the classpath loadProperties(props, Configuration.class.getResourceAsStream("/" + TWITTER4J_PROPERTIES)); // then, override with /WEB/INF/twitter4j.properties in the classpath loadProperties(props, Configuration.class.getResourceAsStream("/WEB-INF/" + TWITTER4J_PROPERTIES)); // for Google App Engine try { loadProperties(props, new FileInputStream("WEB-INF/" + TWITTER4J_PROPERTIES)); } catch (SecurityException ignore) { } catch (FileNotFoundException ignore) { } setFieldsWithTreePath(props, treePath); } /** * Creates a root PropertyConfiguration. This constructor is equivalent to new PropertyConfiguration("/"). */ PropertyConfiguration() { this("/"); } private boolean notNull(Properties props, String prefix, String name) { return props.getProperty(prefix + name) != null; } private boolean loadProperties(Properties props, String path) { FileInputStream fis = null; try { File file = new File(path); if (file.exists() && file.isFile()) { fis = new FileInputStream(file); props.load(fis); normalize(props); return true; } } catch (Exception ignore) { } finally { try { if (fis != null) { fis.close(); } } catch (IOException ignore) { } } return false; } private boolean loadProperties(Properties props, InputStream is) { try { props.load(is); normalize(props); return true; } catch (Exception ignore) { } return false; } private void normalize(Properties props) { ArrayList<String> toBeNormalized = new ArrayList<String>(10); for (Object key : props.keySet()) { String keyStr = (String) key; if (-1 != (keyStr.indexOf("twitter4j."))) { toBeNormalized.add(keyStr); } } for (String keyStr : toBeNormalized) { String property = props.getProperty(keyStr); int index = keyStr.indexOf("twitter4j."); String newKey = keyStr.substring(0, index) + keyStr.substring(index + 10); props.setProperty(newKey, property); } } /** * passing "/foo/bar" as treePath will result:<br> * 1. load [twitter4j.]restBaseURL<br> * 2. override the value with foo.[twitter4j.]restBaseURL<br> * 3. override the value with foo.bar.[twitter4j.]restBaseURL<br> * * @param props properties to be loaded * @param treePath the path */ private void setFieldsWithTreePath(Properties props, String treePath) { setFieldsWithPrefix(props, ""); String[] splitArray = treePath.split("/"); String prefix = null; for (String split : splitArray) { if (!"".equals(split)) { if (null == prefix) { prefix = split + "."; } else { prefix += split + "."; } setFieldsWithPrefix(props, prefix); } } } private void setFieldsWithPrefix(Properties props, String prefix) { if (notNull(props, prefix, DEBUG)) { setDebug(getBoolean(props, prefix, DEBUG)); } if (notNull(props, prefix, USER)) { setUser(getString(props, prefix, USER)); } if (notNull(props, prefix, PASSWORD)) { setPassword(getString(props, prefix, PASSWORD)); } if (notNull(props, prefix, HTTP_PRETTY_DEBUG)) { setPrettyDebugEnabled(getBoolean(props, prefix, HTTP_PRETTY_DEBUG)); } if (notNull(props, prefix, HTTP_GZIP)) { setGZIPEnabled(getBoolean(props, prefix, HTTP_GZIP)); } if (notNull(props, prefix, HTTP_PROXY_HOST)) { setHttpProxyHost(getString(props, prefix, HTTP_PROXY_HOST)); } else if (notNull(props, prefix, HTTP_PROXY_HOST_FALLBACK)) { setHttpProxyHost(getString(props, prefix, HTTP_PROXY_HOST_FALLBACK)); } if (notNull(props, prefix, HTTP_PROXY_USER)) { setHttpProxyUser(getString(props, prefix, HTTP_PROXY_USER)); } if (notNull(props, prefix, HTTP_PROXY_PASSWORD)) { setHttpProxyPassword(getString(props, prefix, HTTP_PROXY_PASSWORD)); } if (notNull(props, prefix, HTTP_PROXY_PORT)) { setHttpProxyPort(getIntProperty(props, prefix, HTTP_PROXY_PORT)); } else if (notNull(props, prefix, HTTP_PROXY_PORT_FALLBACK)) { setHttpProxyPort(getIntProperty(props, prefix, HTTP_PROXY_PORT_FALLBACK)); } if (notNull(props, prefix, HTTP_CONNECTION_TIMEOUT)) { setHttpConnectionTimeout(getIntProperty(props, prefix, HTTP_CONNECTION_TIMEOUT)); } if (notNull(props, prefix, HTTP_READ_TIMEOUT)) { setHttpReadTimeout(getIntProperty(props, prefix, HTTP_READ_TIMEOUT)); } if (notNull(props, prefix, HTTP_STREAMING_READ_TIMEOUT)) { setHttpStreamingReadTimeout(getIntProperty(props, prefix, HTTP_STREAMING_READ_TIMEOUT)); } if (notNull(props, prefix, HTTP_RETRY_COUNT)) { setHttpRetryCount(getIntProperty(props, prefix, HTTP_RETRY_COUNT)); } if (notNull(props, prefix, HTTP_RETRY_INTERVAL_SECS)) { setHttpRetryIntervalSeconds(getIntProperty(props, prefix, HTTP_RETRY_INTERVAL_SECS)); } if (notNull(props, prefix, OAUTH_CONSUMER_KEY)) { setOAuthConsumerKey(getString(props, prefix, OAUTH_CONSUMER_KEY)); } if (notNull(props, prefix, OAUTH_CONSUMER_SECRET)) { setOAuthConsumerSecret(getString(props, prefix, OAUTH_CONSUMER_SECRET)); } if (notNull(props, prefix, OAUTH_ACCESS_TOKEN)) { setOAuthAccessToken(getString(props, prefix, OAUTH_ACCESS_TOKEN)); } if (notNull(props, prefix, OAUTH_ACCESS_TOKEN_SECRET)) { setOAuthAccessTokenSecret(getString(props, prefix, OAUTH_ACCESS_TOKEN_SECRET)); } if (notNull(props, prefix, OAUTH2_TOKEN_TYPE)) { setOAuth2TokenType(getString(props, prefix, OAUTH2_TOKEN_TYPE)); } if (notNull(props, prefix, OAUTH2_ACCESS_TOKEN)) { setOAuth2AccessToken(getString(props, prefix, OAUTH2_ACCESS_TOKEN)); } if (notNull(props, prefix, OAUTH2_SCOPE)) { setOAuth2Scope(getString(props, prefix, OAUTH2_SCOPE)); } if (notNull(props, prefix, ASYNC_NUM_THREADS)) { setAsyncNumThreads(getIntProperty(props, prefix, ASYNC_NUM_THREADS)); } if (notNull(props, prefix, ASYNC_DAEMON_ENABLED)) { setDaemonEnabled(getBoolean(props, prefix, ASYNC_DAEMON_ENABLED)); } if (notNull(props, prefix, CONTRIBUTING_TO)) { setContributingTo(getLongProperty(props, prefix, CONTRIBUTING_TO)); } if (notNull(props, prefix, ASYNC_DISPATCHER_IMPL)) { setDispatcherImpl(getString(props, prefix, ASYNC_DISPATCHER_IMPL)); } if (notNull(props, prefix, OAUTH_REQUEST_TOKEN_URL)) { setOAuthRequestTokenURL(getString(props, prefix, OAUTH_REQUEST_TOKEN_URL)); } if (notNull(props, prefix, OAUTH_AUTHORIZATION_URL)) { setOAuthAuthorizationURL(getString(props, prefix, OAUTH_AUTHORIZATION_URL)); } if (notNull(props, prefix, OAUTH_ACCESS_TOKEN_URL)) { setOAuthAccessTokenURL(getString(props, prefix, OAUTH_ACCESS_TOKEN_URL)); } if (notNull(props, prefix, OAUTH_AUTHENTICATION_URL)) { setOAuthAuthenticationURL(getString(props, prefix, OAUTH_AUTHENTICATION_URL)); } if (notNull(props, prefix, OAUTH2_TOKEN_URL)) { setOAuth2TokenURL(getString(props, prefix, OAUTH2_TOKEN_URL)); } if (notNull(props, prefix, OAUTH2_INVALIDATE_TOKEN_URL)) { setOAuth2InvalidateTokenURL(getString(props, prefix, OAUTH2_INVALIDATE_TOKEN_URL)); } if (notNull(props, prefix, REST_BASE_URL)) { setRestBaseURL(getString(props, prefix, REST_BASE_URL)); } if (notNull(props, prefix, STREAM_BASE_URL)) { setStreamBaseURL(getString(props, prefix, STREAM_BASE_URL)); } if (notNull(props, prefix, USER_STREAM_BASE_URL)) { setUserStreamBaseURL(getString(props, prefix, USER_STREAM_BASE_URL)); } if (notNull(props, prefix, SITE_STREAM_BASE_URL)) { setSiteStreamBaseURL(getString(props, prefix, SITE_STREAM_BASE_URL)); } if (notNull(props, prefix, INCLUDE_MY_RETWEET)) { setIncludeMyRetweetEnabled(getBoolean(props, prefix, INCLUDE_MY_RETWEET)); } if (notNull(props, prefix, INCLUDE_ENTITIES)) { setIncludeEntitiesEnabled(getBoolean(props, prefix, INCLUDE_ENTITIES)); } if (notNull(props, prefix, LOGGER_FACTORY)) { setLoggerFactory(getString(props, prefix, LOGGER_FACTORY)); } if (notNull(props, prefix, JSON_STORE_ENABLED)) { setJSONStoreEnabled(getBoolean(props, prefix, JSON_STORE_ENABLED)); } if (notNull(props, prefix, MBEAN_ENABLED)) { setMBeanEnabled(getBoolean(props, prefix, MBEAN_ENABLED)); } if (notNull(props, prefix, STREAM_USER_REPLIES_ALL)) { setUserStreamRepliesAllEnabled(getBoolean(props, prefix, STREAM_USER_REPLIES_ALL)); } if (notNull(props, prefix, STREAM_USER_WITH_FOLLOWINGS)) { setUserStreamWithFollowingsEnabled(getBoolean(props, prefix, STREAM_USER_WITH_FOLLOWINGS)); } if (notNull(props, prefix, STREAM_STALL_WARNINGS_ENABLED)) { setStallWarningsEnabled(getBoolean(props, prefix, STREAM_STALL_WARNINGS_ENABLED)); } if (notNull(props, prefix, APPLICATION_ONLY_AUTH_ENABLED)) { setApplicationOnlyAuthEnabled(getBoolean(props, prefix, APPLICATION_ONLY_AUTH_ENABLED)); } if (notNull(props, prefix, MEDIA_PROVIDER)) { setMediaProvider(getString(props, prefix, MEDIA_PROVIDER)); } if (notNull(props, prefix, MEDIA_PROVIDER_API_KEY)) { setMediaProviderAPIKey(getString(props, prefix, MEDIA_PROVIDER_API_KEY)); } if (notNull(props, prefix, MEDIA_PROVIDER_PARAMETERS)) { String[] propsAry = getString(props, prefix, MEDIA_PROVIDER_PARAMETERS).split("&"); Properties p = new Properties(); for (String str : propsAry) { String[] parameter = str.split("="); p.setProperty(parameter[0], parameter[1]); } setMediaProviderParameters(p); } cacheInstance(); } boolean getBoolean(Properties props, String prefix, String name) { String value = props.getProperty(prefix + name); return Boolean.valueOf(value); } int getIntProperty(Properties props, String prefix, String name) { String value = props.getProperty(prefix + name); try { return Integer.parseInt(value); } catch (NumberFormatException nfe) { return -1; } } long getLongProperty(Properties props, String prefix, String name) { String value = props.getProperty(prefix + name); try { return Long.parseLong(value); } catch (NumberFormatException nfe) { return -1L; } } String getString(Properties props, String prefix, String name) { return props.getProperty(prefix + name); } // assures equality after deserialization protected Object readResolve() throws ObjectStreamException { return super.readResolve(); } }
dmm4j-core/src/main/java/dmm4j/conf/PropertyConfiguration.java
Add PropertyConfiguration
dmm4j-core/src/main/java/dmm4j/conf/PropertyConfiguration.java
Add PropertyConfiguration
Java
apache-2.0
error: pathspec 'src/test/java/org/xmlbeam/tests/bugs/TestFloatReturnsNull.java' did not match any file(s) known to git
bbfc13ab70bf68ff15ce5ad95a35e1c3ff174dc9
1
SvenEwald/xmlbeam,SvenEwald/xmlbeam,SvenEwald/xmlbeam
/** * Copyright 2014 Sven Ewald * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.xmlbeam.tests.bugs; import static org.junit.Assert.assertNull; import org.junit.Test; import org.xmlbeam.XBProjector; import org.xmlbeam.annotation.XBRead; import org.xmlbeam.types.DefaultTypeConverter; import org.xmlbeam.types.DefaultTypeConverter.Conversion; /** * */ public class TestFloatReturnsNull { public interface Issue19 { @XBRead("/foo/@nonexisting") Float getFloat(); } @Test public void testIssue19() { final XBProjector projector = new XBProjector(); Conversion<Float> floatConversion = new Conversion<Float>(null) { @Override public Float convert(final String data) { return Float.valueOf(data); } }; projector.config().getTypeConverterAs(DefaultTypeConverter.class).setConversionForType(Float.class, floatConversion); final Issue19 issue19 = projector.projectXMLString("<foo/>", Issue19.class); assertNull(issue19.getFloat()); } }
src/test/java/org/xmlbeam/tests/bugs/TestFloatReturnsNull.java
Added to verify issue19
src/test/java/org/xmlbeam/tests/bugs/TestFloatReturnsNull.java
Added to verify issue19
Java
apache-2.0
error: pathspec 'src/main/java/org/realityforge/replicant/server/ChannelLink.java' did not match any file(s) known to git
345383dbfe8969b270dc69022811fcb167e64d67
1
realityforge/replicant,realityforge/replicant
package org.realityforge.replicant.server; import javax.annotation.Nonnull; /** * A representation indicating that an entity message will cause another channel to be subscribed. */ public final class ChannelLink { @Nonnull private final ChannelDescriptor _targetChannel; public ChannelLink( @Nonnull final ChannelDescriptor targetChannel ) { _targetChannel = targetChannel; } @Nonnull public ChannelDescriptor getTargetChannel() { return _targetChannel; } @Override public boolean equals( final Object o ) { if ( this == o ) { return true; } if ( o == null || getClass() != o.getClass() ) { return false; } final ChannelLink that = (ChannelLink) o; return _targetChannel.equals( that._targetChannel ); } @Override public int hashCode() { return _targetChannel.hashCode(); } }
src/main/java/org/realityforge/replicant/server/ChannelLink.java
A simple representation of a link between an entity and other channels
src/main/java/org/realityforge/replicant/server/ChannelLink.java
A simple representation of a link between an entity and other channels
Java
apache-2.0
error: pathspec 'shared/src/main/java/de/qaware/chronix/shared/DataModels/Pair.java' did not match any file(s) known to git
a1308f2e4456b075373ec8e06745b3c198cecb41
1
ChronixDB/chronix.benchmark,mcqueentc/chronix.benchmark
package de.qaware.chronix.shared.DataModels; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; /** * Created by f.lautenschlager on 05.05.2015. */ public final class Pair<T, R> { private final T first; private final R second; public static <T, R> Pair<T, R> of(T first, R second) { return new Pair<>(first, second); } private Pair(T first, R second) { this.first = first; this.second = second; } public T getFirst() { return first; } public R getSecond() { return second; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair<?, ?> pair = (Pair<?, ?>) o; return new EqualsBuilder() .append(first, pair.first) .append(second, pair.second) .isEquals(); } @Override public int hashCode() { return new HashCodeBuilder(17, 37) .append(first) .append(second) .toHashCode(); } @Override public String toString() { return "Pair{" + "first=" + first + ", second=" + second + '}'; } }
shared/src/main/java/de/qaware/chronix/shared/DataModels/Pair.java
added Pair impl
shared/src/main/java/de/qaware/chronix/shared/DataModels/Pair.java
added Pair impl
Java
apache-2.0
error: pathspec 'src/net/java/sip/communicator/impl/protocol/sip/SipStatusEnum.java' did not match any file(s) known to git
b459950c6765682a270ef425807b4480584a4df6
1
bhatvv/jitsi,tuijldert/jitsi,tuijldert/jitsi,mckayclarey/jitsi,mckayclarey/jitsi,459below/jitsi,dkcreinoso/jitsi,damencho/jitsi,tuijldert/jitsi,bhatvv/jitsi,martin7890/jitsi,HelioGuilherme66/jitsi,laborautonomo/jitsi,pplatek/jitsi,459below/jitsi,dkcreinoso/jitsi,gpolitis/jitsi,jitsi/jitsi,ibauersachs/jitsi,marclaporte/jitsi,level7systems/jitsi,jibaro/jitsi,ibauersachs/jitsi,HelioGuilherme66/jitsi,marclaporte/jitsi,bebo/jitsi,cobratbq/jitsi,gpolitis/jitsi,ringdna/jitsi,laborautonomo/jitsi,ringdna/jitsi,HelioGuilherme66/jitsi,cobratbq/jitsi,cobratbq/jitsi,damencho/jitsi,ibauersachs/jitsi,level7systems/jitsi,HelioGuilherme66/jitsi,ringdna/jitsi,ringdna/jitsi,Metaswitch/jitsi,gpolitis/jitsi,level7systems/jitsi,459below/jitsi,iant-gmbh/jitsi,marclaporte/jitsi,dkcreinoso/jitsi,tuijldert/jitsi,martin7890/jitsi,bebo/jitsi,cobratbq/jitsi,marclaporte/jitsi,laborautonomo/jitsi,bhatvv/jitsi,459below/jitsi,Metaswitch/jitsi,gpolitis/jitsi,pplatek/jitsi,procandi/jitsi,jibaro/jitsi,HelioGuilherme66/jitsi,iant-gmbh/jitsi,jitsi/jitsi,laborautonomo/jitsi,pplatek/jitsi,procandi/jitsi,ringdna/jitsi,jitsi/jitsi,Metaswitch/jitsi,damencho/jitsi,jibaro/jitsi,laborautonomo/jitsi,ibauersachs/jitsi,damencho/jitsi,dkcreinoso/jitsi,bebo/jitsi,procandi/jitsi,iant-gmbh/jitsi,dkcreinoso/jitsi,ibauersachs/jitsi,jitsi/jitsi,mckayclarey/jitsi,mckayclarey/jitsi,bebo/jitsi,jibaro/jitsi,martin7890/jitsi,iant-gmbh/jitsi,marclaporte/jitsi,cobratbq/jitsi,level7systems/jitsi,bhatvv/jitsi,martin7890/jitsi,procandi/jitsi,bebo/jitsi,459below/jitsi,bhatvv/jitsi,damencho/jitsi,jibaro/jitsi,pplatek/jitsi,jitsi/jitsi,tuijldert/jitsi,procandi/jitsi,gpolitis/jitsi,level7systems/jitsi,pplatek/jitsi,mckayclarey/jitsi,martin7890/jitsi,iant-gmbh/jitsi,Metaswitch/jitsi
/* * SIP Communicator, the OpenSource Java VoIP and Instant Messaging client. * * Distributable under LGPL license. * See terms of license at gnu.org. */ package net.java.sip.communicator.impl.protocol.sip; import java.util.*; import net.java.sip.communicator.service.protocol.*; import net.java.sip.communicator.util.*; import java.io.*; /** * An implementation of <tt>PresenceStatus</tt> that enumerates all states that * a SIP contact can currently have. * * @author Emil Ivov */ public class SipStatusEnum extends PresenceStatus { private static final Logger logger = Logger.getLogger(SipStatusEnum.class); /** * Indicates an Offline status or status with 0 connectivity. */ public static final SipStatusEnum OFFLINE = new SipStatusEnum( 0 , "Offline" , loadIcon("resources/images/sip/sip16x16-offline.png")); /** * The DND status. Indicates that the user has connectivity but prefers * not to be contacted. */ public static final SipStatusEnum DO_NOT_DISTURB = new SipStatusEnum( 30 , "Do Not Disturb", loadIcon("resources/images/sip/sip16x16-dnd.png")); /** * The Online status. Indicate that the user is able and willing to * communicate. */ public static final SipStatusEnum ONLINE = new SipStatusEnum( 65 , "Online" , loadIcon("resources/images/sip/sip16x16-online.png")); /** * Initialize the list of supported status states. */ private static List supportedStatusSet = new LinkedList(); static { supportedStatusSet.add(OFFLINE); supportedStatusSet.add(DO_NOT_DISTURB); supportedStatusSet.add(ONLINE); } /** * Creates an instance of <tt>SipPresneceStatus</tt> with the * specified parameters. * @param status the connectivity level of the new presence status instance * @param statusName the name of the presence status. * @param statusIcon the icon associated with this status */ private SipStatusEnum(int status, String statusName, byte[] statusIcon) { super(status, statusName, statusIcon); } /** * Returns an iterator over all status instances supproted by the sip * provider. * @return an <tt>Iterator</tt> over all status instances supported by the * sip provider. */ static Iterator supportedStatusSet() { return supportedStatusSet.iterator(); } /** * Loads an image from a given image path. * @param imagePath The path to the image resource. * @return The image extracted from the resource at the specified path. */ public static byte[] loadIcon(String imagePath) { InputStream is = SipStatusEnum.class.getClassLoader() .getResourceAsStream(imagePath); byte[] icon = null; try { icon = new byte[is.available()]; is.read(icon); } catch (IOException exc) { logger.error("Failed to load icon: " + imagePath, exc); } return icon; } }
src/net/java/sip/communicator/impl/protocol/sip/SipStatusEnum.java
adding phoney presence for the sip provider A number of phoney states that are currently supported by sip presence.
src/net/java/sip/communicator/impl/protocol/sip/SipStatusEnum.java
adding phoney presence for the sip provider
Java
apache-2.0
error: pathspec 'plugin/src/main/java/org/wso2/carbon/uuf/maven/model/Instructions.java' did not match any file(s) known to git
6a51529dae06881121b4b17071ca6eec092b7123
1
this/carbon-uuf-maven-tools,sajithar/carbon-uuf-maven-plugin,this/carbon-uuf-maven-tools,this/carbon-uuf-maven-tools
/* * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.uuf.maven.model; /** * Bean class that represent OSGi bundling instructions specified inside a {@code <configurations>} tag in a POM file. * * @since 1.0.0 */ public class Instructions { private String importPackage; /** * Returns the import packages entry ({@code <Import-Package>}) in this instructions. * * @return import package entry */ public String getImportPackage() { return importPackage; } /** * Sets the import package entry entry ({@code <Import-Package>}) in this instructions. * * @param importPackage import package entry to be set */ public void setImportPackage(String importPackage) { this.importPackage = importPackage; } }
plugin/src/main/java/org/wso2/carbon/uuf/maven/model/Instructions.java
created Instructions model class
plugin/src/main/java/org/wso2/carbon/uuf/maven/model/Instructions.java
created Instructions model class
Java
apache-2.0
error: pathspec 'modules/extension/src/main/java/org/makersoft/web/mvc/RestController.java' did not match any file(s) known to git
05cbd20934ced937dbf05215329a9be43d2c0e50
1
makersoft/makereap,makersoft/makereap
/* * @(#)RestController.java 2013-1-28 下午3:25:17 * * Copyright (c) 2011-2013 Makersoft.org all rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * */ package org.makersoft.web.mvc; /** * RestController. */ public abstract class RestController { public static final String index = "index"; public static final String edit = "edit"; public static final String _new = "_new"; // public String get }
modules/extension/src/main/java/org/makersoft/web/mvc/RestController.java
Rest controller super class for future
modules/extension/src/main/java/org/makersoft/web/mvc/RestController.java
Rest controller super class for future
Java
apache-2.0
error: pathspec 'servo-core/src/test/java/com/netflix/servo/jmx/JmxMonitorRegistryTest.java' did not match any file(s) known to git
c2764c4d6f6fc0c8f3975ad29a989fa5cd1471d6
1
gorcz/servo,dmuino/servo,eonezhang/servo,eonezhang/servo,sensaid/servo,dmuino/servo,rspieldenner/servo,fengshao0907/servo,fengshao0907/servo,brharrington/servo,sensaid/servo,ccortezb/servo,ccortezb/servo,Netflix/servo,entelesis/servo,brharrington/servo,entelesis/servo
/* * #%L * servo * %% * Copyright (C) 2011 - 2012 Netflix * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package com.netflix.servo.jmx; import com.google.common.collect.ImmutableMap; import com.netflix.servo.BasicTagList; import com.netflix.servo.TagList; import com.netflix.servo.MonitorRegistry; import com.netflix.servo.util.BasicCounter; import java.util.Map; import java.util.Properties; import java.util.Set; import org.testng.annotations.Test; import static org.testng.Assert.*; public class JmxMonitorRegistryTest { private JmxMonitorRegistry newInstance() { return new JmxMonitorRegistry(); } @Test(expectedExceptions = NullPointerException.class) public void testRegisterNull() throws Exception { MonitorRegistry registry = newInstance(); registry.registerObject(null); } @Test(expectedExceptions = NullPointerException.class) public void testUnRegisterNull() throws Exception { MonitorRegistry registry = newInstance(); registry.unRegisterObject(null); } @Test public void testUnRegisterObject() throws Exception { MonitorRegistry registry = newInstance(); Object o1 = new BasicCounter("one"); Object o2 = new BasicCounter("two"); registry.registerObject(o1); registry.registerObject(o2); Set<Object> objects = registry.getRegisteredObjects(); assertEquals(objects.size(), 2); assertTrue(objects.contains(o1)); assertTrue(objects.contains(o2)); registry.unRegisterObject(o1); objects = registry.getRegisteredObjects(); assertEquals(objects.size(), 1); assertFalse(objects.contains(o1)); assertTrue(objects.contains(o2)); registry.unRegisterObject(o2); objects = registry.getRegisteredObjects(); assertEquals(objects.size(), 0); assertFalse(objects.contains(o1)); assertFalse(objects.contains(o2)); } @Test public void testGetRegisteredObjectsEmpty() throws Exception { MonitorRegistry registry = newInstance(); Set<Object> objects = registry.getRegisteredObjects(); assertEquals(objects.size(), 0); } @Test public void testGetRegisteredObjects() throws Exception { MonitorRegistry registry = newInstance(); Object o1 = new BasicCounter("one"); Object o2 = new BasicCounter("two"); registry.registerObject(o1); registry.registerObject(o2); Set<Object> objects = registry.getRegisteredObjects(); assertEquals(objects.size(), 2); assertTrue(objects.contains(o1)); assertTrue(objects.contains(o2)); } }
servo-core/src/test/java/com/netflix/servo/jmx/JmxMonitorRegistryTest.java
minimal test case for JmxMonitorRegistry
servo-core/src/test/java/com/netflix/servo/jmx/JmxMonitorRegistryTest.java
minimal test case for JmxMonitorRegistry
Java
apache-2.0
error: pathspec 'src/org/ensembl/healthcheck/testcase/generic/MultipleComponentAssemblyMapping.java' did not match any file(s) known to git
ce1057191261649f5c96cabf8567e1e3d9720bcd
1
thomasmaurel/ensj-healthcheck,thomasmaurel/ensj-healthcheck,Ensembl/ensj-healthcheck,thomasmaurel/ensj-healthcheck,thomasmaurel/ensj-healthcheck,Ensembl/ensj-healthcheck,Ensembl/ensj-healthcheck,Ensembl/ensj-healthcheck
/* * Copyright (C) 2004 EBI, GRL * * This library is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License as published by the Free Software * Foundation; either version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with * this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, * Suite 330, Boston, MA 02111-1307 USA */ package org.ensembl.healthcheck.testcase.generic; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.ensembl.healthcheck.DatabaseRegistryEntry; import org.ensembl.healthcheck.ReportManager; import org.ensembl.healthcheck.testcase.Priority; import org.ensembl.healthcheck.testcase.SingleDatabaseTestCase; import org.ensembl.healthcheck.util.Utils; /** * Check for cases where components map to multiple parts of the assembly but * the chained mapper is *not* specified for that pair of coordinate systems in * the meta table. */ public class MultipleComponentAssemblyMapping extends SingleDatabaseTestCase { /** * Creates a new instance of AssemblyMultipleOverlap. */ public MultipleComponentAssemblyMapping() { addToGroup("post_genebuild"); addToGroup("release"); setDescription("Check for cases where components map to multiple parts of the assembly but the chained mapper is *not* specified for that pair of coordinate systems in the meta table."); setPriority(Priority.AMBER); setEffect("Will cause problems with sequence retrieval for the affected region, and possibly website crashes."); setFix("Specify the chained mapper (#) in the assembly.mapping entry for these two coordinate systems."); } /** * Run the test. * * @param dbre * The database to use. * @return true if the test passed. * */ public boolean run(DatabaseRegistryEntry dbre) { boolean result = true; Connection con = dbre.getConnection(); // cache coord system name to ID Map coordSystemNameToID = new HashMap(); Statement stmt = null; try { stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM coord_system"); while (rs.next()) { coordSystemNameToID.put(rs.getString("name"), new Long(rs.getLong("coord_system_id"))); } } catch (Exception e) { result = false; e.printStackTrace(); } // build up SQL that filters out assembly mappings that already use the // chained mapper String constraint = ""; String[] mappings = getColumnValues(con, "SELECT meta_value FROM meta WHERE meta_key='assembly.mapping' AND meta_value LIKE '%#%'"); Pattern assemblyMappingPattern = Pattern .compile("^([a-zA-Z0-9.]+)(:[a-zA-Z0-9._]+)?[\\|#]([a-zA-Z0-9._]+)(:[a-zA-Z0-9._]+)?([\\|#]([a-zA-Z0-9.]+)(:[a-zA-Z0-9._]+)?)?$"); for (int i = 0; i < mappings.length; i++) { Matcher matcher = assemblyMappingPattern.matcher(mappings[i]); if (matcher.matches()) { String cs1 = matcher.group(1); String cs2 = matcher.group(3); String cs3 = matcher.group(6); // TODO - ignoring cs3 for now long csID1 = ((Long) (coordSystemNameToID.get(cs1))).longValue(); long csID2 = ((Long) (coordSystemNameToID.get(cs2))).longValue(); logger.fine("Chained mapping for " + cs1 + " (ID " + csID1 + ") - " + cs2 + " (ID " + csID2 + ")"); constraint += "AND NOT ((s2.coord_system_id = " + csID1 + " AND s1.coord_system_id = " + csID2 + ") OR (s2.coord_system_id = " + csID2 + " AND s1.coord_system_id = " + csID1 + "))"; } } logger.fine(constraint); // now find components that map to multiple assemblies but whose coordinate // systems are not using a chained mapper String sql = "SELECT a.cmp_seq_region_id, a.asm_seq_region_id, s1.coord_system_id " + "FROM assembly a, seq_region s1, seq_region s2 " + "WHERE a.asm_seq_region_id=s1.seq_region_id AND a.cmp_seq_region_id = s2.seq_region_id " + constraint + "ORDER BY s1.coord_system_id, a.cmp_seq_region_id"; try { ResultSet rs = stmt.executeQuery(sql); long oldCoordSystemID = 0; Map list = new HashMap(); while (rs.next()) { long cmpID = rs.getLong("cmp_seq_region_id"); long asmID = rs.getLong("asm_seq_region_id"); long coordSystemID = rs.getLong("coord_system_id"); // allow mapping to different coordinate systems if (coordSystemID != oldCoordSystemID) { list.clear(); oldCoordSystemID = coordSystemID; } Long LcmpID = new Long(cmpID); String value = (String) list.get(LcmpID); if (value != null) { String newValue = value + "," + asmID; list.put(new Long(cmpID), newValue); //ReportManager.problem(this, con, "Component with ID " + cmpID // + " is linked to more than one assembly mapping for coord_system with ID " + coordSystemID + " (" + newValue + ")"); System.out.println("Component with ID " + cmpID + " is linked to more than one assembly mapping for coord_system with ID " + coordSystemID + " (" + newValue + ")"); result = false; } else { list.put(LcmpID, "" + asmID); } } // while rs } catch (Exception e) { result = false; System.err.println("Error executing SQL: " + sql); e.printStackTrace(); } if (result) { ReportManager.correct(this, con, "No problems with assembly - meta table mismatches"); } return result; } // run // ------------------------------------------------------------------------- } // MultipleComponentAssemblyMapper
src/org/ensembl/healthcheck/testcase/generic/MultipleComponentAssemblyMapping.java
Check for cases where components map to multiple parts of the assembly but the chained mapper is *not* specified for that pair of coordinate systems in the meta table. Caused problems in cat for release 48.
src/org/ensembl/healthcheck/testcase/generic/MultipleComponentAssemblyMapping.java
Check for cases where components map to multiple parts of the assembly but the chained mapper is *not* specified for that pair of coordinate systems in the meta table. Caused problems in cat for release 48.
Java
apache-2.0
error: pathspec 'cache/play-caffeine-cache/src/main/java/play/cache/caffeine/CaffeineDefaultExpiry.java' did not match any file(s) known to git
53dbdf2624242adf60bdc03f1a5ea19ae5803102
1
benmccann/playframework,marcospereira/playframework,playframework/playframework,marcospereira/playframework,benmccann/playframework,benmccann/playframework,playframework/playframework,mkurz/playframework,marcospereira/playframework,wegtam/playframework,benmccann/playframework,wegtam/playframework,playframework/playframework,marcospereira/playframework,mkurz/playframework,mkurz/playframework,wegtam/playframework,wegtam/playframework,mkurz/playframework
/* * Copyright (C) 2009-2019 Lightbend Inc. <https://www.lightbend.com> */ package play.cache.caffeine; import com.github.benmanes.caffeine.cache.Expiry; import javax.annotation.Nonnull; public final class CaffeineDefaultExpiry implements Expiry<Object, Object> { @Override public long expireAfterCreate(@Nonnull Object key, @Nonnull Object value, long currentTime) { return Long.MAX_VALUE; } @Override public long expireAfterUpdate( @Nonnull Object key, @Nonnull Object value, long currentTime, long currentDuration) { return currentDuration; } @Override public long expireAfterRead( @Nonnull Object key, @Nonnull Object value, long currentTime, long currentDuration) { return currentDuration; } }
cache/play-caffeine-cache/src/main/java/play/cache/caffeine/CaffeineDefaultExpiry.java
removed class causes binary compatibility issue, re-created CaffeineDefaultExpiry.java for this reason "class play.cache.caffeine.CaffeineDefaultExpiry does not have a correspondent in current version"
cache/play-caffeine-cache/src/main/java/play/cache/caffeine/CaffeineDefaultExpiry.java
removed class causes binary compatibility issue, re-created CaffeineDefaultExpiry.java for this reason
Java
apache-2.0
error: pathspec 'src/test/java/org/apache/commons/digester3/substitution/VariableExpansionTestCase.java' did not match any file(s) known to git
5d15e1ad293047194f66f7b75b95567dae4d6246
1
apache/commons-digester,apache/commons-digester,callMeDimit/commons-digester,callMeDimit/commons-digester,mohanaraosv/commons-digester,callMeDimit/commons-digester,apache/commons-digester,mohanaraosv/commons-digester,mohanaraosv/commons-digester
/* $Id$ * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.digester3.substitution; import static org.apache.commons.digester3.DigesterLoader.newLoader; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; import java.io.IOException; import java.io.StringReader; import java.util.HashMap; import java.util.LinkedList; import org.apache.commons.digester3.AbstractRulesModule; import org.apache.commons.digester3.Digester; import org.apache.commons.digester3.RulesBinder; import org.apache.commons.digester3.RulesModule; import org.apache.commons.digester3.SimpleTestBean; import org.junit.Test; import org.xml.sax.SAXException; /** * Test Case for the variable expansion facility in Digester. * * @author Simon Kitching * @version $Revision$ $Date$ */ public class VariableExpansionTestCase { // --------------------------------------------------- Overall Test Methods // method used in tests4 private LinkedList<SimpleTestBean> simpleTestBeans = new LinkedList<SimpleTestBean>(); public void addSimpleTestBean(SimpleTestBean bean) { this.simpleTestBeans.add(bean); } // implementation of source shared by the variable expander and // is updatable during digesting via an Ant-like property element private HashMap<String, Object> mutableSource=new HashMap<String, Object>(); /** * Used in test case "testExpansionWithMutableSource", where the * set of variables available to be substituted into the xml is * updated as the xml is parsed. */ public void addProperty(String key, String value) { this.mutableSource.put(key, value); } /** * Creates a Digester configured to show Ant-like capability. * * @return a Digester with rules and variable substitutor */ private Digester createDigesterThatCanDoAnt() throws Exception { MultiVariableExpander expander = new MultiVariableExpander(); expander.addSource("$", this.mutableSource); return newLoader(new AbstractRulesModule() { @Override protected void configure() { forPattern("root/property") .callMethod("addProperty").withParamTypes(String.class, String.class) .then() .callParam().ofIndex(0).fromAttribute("name") .then() .callParam().ofIndex(1).fromAttribute("value"); forPattern("root/bean") .createObject().ofType(SimpleTestBean.class) .then() .setProperties() .then() .setNext("addSimpleTestBean"); } }) .setSubstitutor(new VariableSubstitutor(expander)) .newDigester(); } // ------------------------------------------------ Individual Test Methods /** * Test that by default no expansion occurs. */ @Test public void testNoExpansion() throws Exception { String xml = "<root alpha='${attr1}' beta='var{attr2}'/>"; StringReader input = new StringReader(xml); Object root = newLoader(new RulesModule() { public void configure(RulesBinder binder) { binder.forPattern("root").createObject().ofType(SimpleTestBean.class) .then().setProperties(); } }).newDigester().parse(input); assertNotNull("Digester returned no object", root); SimpleTestBean bean = (SimpleTestBean) root; assertEquals("${attr1}", bean.getAlpha()); assertEquals("var{attr2}", bean.getBeta()); } /** * Test that a MultiVariableExpander with no sources does no expansion. */ @Test public void testExpansionWithNoSource() throws Exception { String xml = "<root alpha='${attr1}' beta='var{attr2}'/>"; StringReader input = new StringReader(xml); Object root = newLoader(new AbstractRulesModule() { @Override protected void configure() { forPattern("root").createObject().ofType(SimpleTestBean.class) .then().setProperties(); } }) .setSubstitutor(new VariableSubstitutor(new MultiVariableExpander())) .newDigester() .parse(input); assertNotNull("Digester returned no object", root); SimpleTestBean bean = (SimpleTestBean) root; assertEquals("${attr1}", bean.getAlpha()); assertEquals("var{attr2}", bean.getBeta()); } /** * Test that a MultiVariableExpander with multiple sources works. * It also tests that expansion works ok where multiple elements * exist. */ @Test public void testExpansionWithMultipleSources() throws Exception { // Configure the digester as required HashMap<String, Object> source1 = new HashMap<String, Object>(); source1.put("attr1", "source1.attr1"); source1.put("attr2", "source1.attr2"); // should not be used HashMap<String, Object> source2 = new HashMap<String, Object>(); source2.put("attr1", "source2.attr1"); // should not be used source2.put("attr2", "source2.attr2"); MultiVariableExpander expander = new MultiVariableExpander(); expander.addSource("$", source1); expander.addSource("var", source2); String xml = "<root>" + "<bean alpha='${attr1}' beta='var{attr1}'/>" + "<bean alpha='${attr2}' beta='var{attr2}'/>" + "</root>"; StringReader input = new StringReader(xml); Digester digester = newLoader(new AbstractRulesModule() { @Override public void configure() { forPattern("root/bean").createObject().ofType(SimpleTestBean.class) .then().setProperties() .then().setNext("addSimpleTestBean"); } }) .setSubstitutor(new VariableSubstitutor(expander)) .newDigester(); // Parse our test input. this.simpleTestBeans.clear(); digester.push(this); digester.parse(input); assertEquals(2, this.simpleTestBeans.size()); { SimpleTestBean bean = this.simpleTestBeans.get(0); assertEquals("source1.attr1", bean.getAlpha()); assertEquals("source2.attr1", bean.getBeta()); } { SimpleTestBean bean = this.simpleTestBeans.get(1); assertEquals("source1.attr2", bean.getAlpha()); assertEquals("source2.attr2", bean.getBeta()); } } /** * Test expansion of text in element bodies. */ @Test public void testBodyExpansion() throws Exception { // Configure the digester as required HashMap<String, Object> nouns = new HashMap<String, Object>(); nouns.put("1", "brillig"); nouns.put("2", "slithy toves"); nouns.put("3", "wabe"); HashMap<String, Object> verbs = new HashMap<String, Object>(); verbs.put("1", "gyre"); verbs.put("2", "gimble"); MultiVariableExpander expander = new MultiVariableExpander(); expander.addSource("noun", nouns); expander.addSource("verb", verbs); String xml = "<root>" + "Twas noun{1} and the noun{2}" + " did verb{1} and verb{2} in the noun{3}" + "</root>"; StringReader input = new StringReader(xml); Object root = newLoader(new RulesModule() { public void configure(RulesBinder rulesBinder) { rulesBinder.forPattern("root") .createObject().ofType(SimpleTestBean.class) .then() .setBeanProperty().withName("alpha"); } }) .setSubstitutor(new VariableSubstitutor(expander)) .newDigester() .parse(input); assertNotNull("Digester returned no object", root); SimpleTestBean bean = (SimpleTestBean) root; assertEquals( "Twas brillig and the slithy toves" + " did gyre and gimble in the wabe", bean.getAlpha()); } /** * Test that an unknown variable causes a RuntimeException. */ @Test public void testExpansionException() throws Exception { // Configure the digester as required MultiVariableExpander expander = new MultiVariableExpander(); expander.addSource("$", new HashMap<String, Object>()); String xml = "<root alpha='${attr1}'/>"; StringReader input = new StringReader(xml); Digester digester = newLoader(new AbstractRulesModule() { @Override protected void configure() { forPattern("root").createObject().ofType(SimpleTestBean.class) .then().setProperties(); } }) .setSubstitutor(new VariableSubstitutor(expander)) .newDigester(); // Parse our test input. try { digester.parse(input); fail("Exception expected due to unknown variable."); } catch(SAXException e) { // expected, due to reference to undefined variable } } /** * First of two tests added to verify that the substitution * framework is capable of processing Ant-like properties. * * The tests above essentially verify that if a property * was pre-set (e.g. using the "-D" option to Ant), then * the property could be expanded via a variable used either * in an attribute or in body text. * * This test shows that if properties were also set while * processing a document, you could still perform variable * expansion (i.e. just like using the "property" task in Ant). * * @throws IOException * @throws SAXException */ @Test public void testExpansionWithMutableSource() throws Exception { String xml = "<root>" + "<property name='attr' value='prop.value'/>" + "<bean alpha='${attr}'/>" + "</root>"; StringReader input = new StringReader(xml); Digester digester = createDigesterThatCanDoAnt(); simpleTestBeans.clear(); digester.push(this); digester.parse(input); assertEquals(1, simpleTestBeans.size()); SimpleTestBean bean = simpleTestBeans.get(0); assertEquals("prop.value", bean.getAlpha()); } /** * Second of two tests added to verify that the substitution * framework is capable of processing Ant-like properties. * * This test shows that if properties were also set while * processing a document, the resulting variables could also * be expanded within a property element. This is thus * effectively a "closure" test, since it shows that the * mechanism used to bind properties is also capable of * having property values that are driven by property variables. * * @throws IOException * @throws SAXException */ @Test public void testExpansionOfPropertyInProperty() throws Exception { String xml = "<root>" + "<property name='attr1' value='prop.value1'/>" + "<property name='attr2' value='substituted-${attr1}'/>" + "<bean alpha='${attr2}'/>" + "</root>"; StringReader input = new StringReader(xml); Digester digester = createDigesterThatCanDoAnt(); simpleTestBeans.clear(); digester.push(this); digester.parse(input); assertEquals(1, simpleTestBeans.size()); SimpleTestBean bean = simpleTestBeans.get(0); assertEquals("substituted-prop.value1", bean.getAlpha()); } }
src/test/java/org/apache/commons/digester3/substitution/VariableExpansionTestCase.java
first checkin of VariableExpansionTestCase, an adapted version of the proper on /trunk old testcases continue pass! git-svn-id: c3d1f7498fb08a2885afe49e111c402c6cd8f5f6@1067466 13f79535-47bb-0310-9956-ffa450edef68
src/test/java/org/apache/commons/digester3/substitution/VariableExpansionTestCase.java
first checkin of VariableExpansionTestCase, an adapted version of the proper on /trunk old testcases continue pass!
Java
apache-2.0
error: pathspec 'runners/spark/src/test/java/org/apache/beam/runners/spark/SparkRunnerRegistrarTest.java' did not match any file(s) known to git
f424b8d87aa491a29cf3c5cc3c162ee3e38aaf01
1
wtanaka/beam,rangadi/beam,robertwb/incubator-beam,iemejia/incubator-beam,chamikaramj/beam,chamikaramj/beam,dhalperi/incubator-beam,yk5/beam,markflyhigh/incubator-beam,lukecwik/incubator-beam,robertwb/incubator-beam,chamikaramj/incubator-beam,apache/beam,vikkyrk/incubator-beam,tgroh/beam,lukecwik/incubator-beam,chamikaramj/incubator-beam,charlesccychen/beam,manuzhang/beam,amarouni/incubator-beam,sammcveety/incubator-beam,tweise/beam,amitsela/beam,chamikaramj/beam,tgroh/incubator-beam,chamikaramj/beam,ravwojdyla/incubator-beam,apache/beam,dhalperi/beam,rangadi/beam,rangadi/beam,robertwb/incubator-beam,sammcveety/incubator-beam,RyanSkraba/beam,tgroh/beam,tgroh/beam,staslev/beam,chamikaramj/beam,xsm110/Apache-Beam,mxm/incubator-beam,chamikaramj/beam,apache/beam,lukecwik/incubator-beam,RyanSkraba/beam,robertwb/incubator-beam,wangyum/beam,markflyhigh/incubator-beam,apache/beam,staslev/incubator-beam,chamikaramj/beam,jbonofre/incubator-beam,apache/beam,apache/beam,lukecwik/incubator-beam,rangadi/incubator-beam,jasonkuster/beam,robertwb/incubator-beam,apache/beam,amitsela/beam,manuzhang/beam,iemejia/incubator-beam,rangadi/beam,staslev/beam,lukecwik/incubator-beam,manuzhang/incubator-beam,josauder/AOP_incubator_beam,markflyhigh/incubator-beam,robertwb/incubator-beam,robertwb/incubator-beam,charlesccychen/beam,yk5/beam,jbonofre/beam,dhalperi/beam,sammcveety/incubator-beam,RyanSkraba/beam,charlesccychen/beam,jbonofre/incubator-beam,wangyum/beam,ravwojdyla/incubator-beam,staslev/incubator-beam,peihe/incubator-beam,yk5/beam,RyanSkraba/beam,amitsela/beam,apache/beam,chamikaramj/beam,charlesccychen/beam,apache/beam,robertwb/incubator-beam,eljefe6a/incubator-beam,lukecwik/incubator-beam,tweise/incubator-beam,RyanSkraba/beam,peihe/incubator-beam,xsm110/Apache-Beam,lukecwik/incubator-beam,ravwojdyla/incubator-beam,RyanSkraba/beam,peihe/incubator-beam,mxm/incubator-beam,wtanaka/beam,charlesccychen/beam,jbonofre/beam,wtanaka/beam,eljefe6a/incubator-beam,charlesccychen/incubator-beam,tgroh/beam,rangadi/beam,markflyhigh/incubator-beam,xsm110/Apache-Beam,chamikaramj/beam,joshualitt/incubator-beam,lukecwik/incubator-beam,markflyhigh/incubator-beam,wangyum/beam,amitsela/incubator-beam,joshualitt/incubator-beam,jasonkuster/incubator-beam,charlesccychen/beam,amitsela/incubator-beam,rangadi/incubator-beam,amarouni/incubator-beam,chamikaramj/beam,markflyhigh/incubator-beam,lukecwik/incubator-beam,rangadi/incubator-beam,jbonofre/beam,RyanSkraba/beam,dhalperi/incubator-beam,jbonofre/beam,eljefe6a/incubator-beam,rangadi/beam,vikkyrk/incubator-beam,tweise/beam,wangyum/beam,jasonkuster/incubator-beam,tweise/incubator-beam,markflyhigh/incubator-beam,manuzhang/beam,staslev/beam,tgroh/incubator-beam,charlesccychen/incubator-beam,rangadi/beam,dhalperi/beam,lukecwik/incubator-beam,robertwb/incubator-beam,manuzhang/incubator-beam,vikkyrk/incubator-beam,charlesccychen/beam,charlesccychen/incubator-beam,jasonkuster/beam,robertwb/incubator-beam,apache/beam,apache/beam,jasonkuster/beam,josauder/AOP_incubator_beam
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.beam.runners.spark; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import org.apache.beam.sdk.options.PipelineOptionsRegistrar; import org.apache.beam.sdk.runners.PipelineRunnerRegistrar; import org.junit.Test; import java.util.ServiceLoader; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; /** * Test {@link SparkRunnerRegistrar}. */ public class SparkRunnerRegistrarTest { @Test public void testOptions() { assertEquals( ImmutableList.of(SparkPipelineOptions.class, SparkStreamingPipelineOptions.class), new SparkRunnerRegistrar.Options().getPipelineOptions()); } @Test public void testRunners() { assertEquals(ImmutableList.of(SparkPipelineRunner.class), new SparkRunnerRegistrar.Runner().getPipelineRunners()); } @Test public void testServiceLoaderForOptions() { for (PipelineOptionsRegistrar registrar : Lists.newArrayList(ServiceLoader.load(PipelineOptionsRegistrar.class).iterator())) { if (registrar instanceof SparkRunnerRegistrar.Options) { return; } } fail("Expected to find " + SparkRunnerRegistrar.Options.class); } @Test public void testServiceLoaderForRunner() { for (PipelineRunnerRegistrar registrar : Lists.newArrayList(ServiceLoader.load(PipelineRunnerRegistrar.class).iterator())) { if (registrar instanceof SparkRunnerRegistrar.Runner) { return; } } fail("Expected to find " + SparkRunnerRegistrar.Runner.class); } }
runners/spark/src/test/java/org/apache/beam/runners/spark/SparkRunnerRegistrarTest.java
Add a unit test for the SparkRunnerRegistrar
runners/spark/src/test/java/org/apache/beam/runners/spark/SparkRunnerRegistrarTest.java
Add a unit test for the SparkRunnerRegistrar
Java
apache-2.0
error: pathspec 'engine/src/test/java/org/camunda/bpm/engine/test/api/history/removaltime/cleanup/HistoryCleanupScheduleBatchesTest.java' did not match any file(s) known to git
95984e48f36be1d0a0617a9ffa94a136b5e022e4
1
falko/camunda-bpm-platform,xasx/camunda-bpm-platform,camunda/camunda-bpm-platform,camunda/camunda-bpm-platform,xasx/camunda-bpm-platform,falko/camunda-bpm-platform,xasx/camunda-bpm-platform,camunda/camunda-bpm-platform,falko/camunda-bpm-platform,camunda/camunda-bpm-platform,langfr/camunda-bpm-platform,langfr/camunda-bpm-platform,langfr/camunda-bpm-platform,falko/camunda-bpm-platform,xasx/camunda-bpm-platform,ingorichtsmeier/camunda-bpm-platform,ingorichtsmeier/camunda-bpm-platform,camunda/camunda-bpm-platform,langfr/camunda-bpm-platform,falko/camunda-bpm-platform,xasx/camunda-bpm-platform,langfr/camunda-bpm-platform,ingorichtsmeier/camunda-bpm-platform,xasx/camunda-bpm-platform,langfr/camunda-bpm-platform,falko/camunda-bpm-platform,ingorichtsmeier/camunda-bpm-platform,ingorichtsmeier/camunda-bpm-platform,camunda/camunda-bpm-platform,ingorichtsmeier/camunda-bpm-platform
/* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.camunda.bpm.engine.test.api.history.removaltime.cleanup; import org.camunda.bpm.engine.ProcessEngineConfiguration; import org.camunda.bpm.engine.RuntimeService; import org.camunda.bpm.engine.TaskService; import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl; import org.camunda.bpm.engine.impl.history.event.HistoryEventTypes; import org.camunda.bpm.engine.impl.util.ClockUtil; import org.camunda.bpm.engine.runtime.Job; import org.camunda.bpm.engine.test.util.ProcessEngineBootstrapRule; import org.camunda.bpm.engine.test.util.ProcessEngineTestRule; import org.camunda.bpm.engine.test.util.ProvidedProcessEngineRule; import org.camunda.bpm.model.bpmn.Bpmn; import org.camunda.bpm.model.bpmn.BpmnModelInstance; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.RuleChain; import java.util.Collections; import java.util.Date; import java.util.List; import static org.apache.commons.lang.time.DateUtils.addDays; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; /** * @author Tassilo Weidner */ public class HistoryCleanupScheduleBatchesTest extends AbstractHistoryCleanupSchedulerTest { public ProcessEngineBootstrapRule bootstrapRule = new ProcessEngineBootstrapRule() { public ProcessEngineConfiguration configureEngine(ProcessEngineConfigurationImpl configuration) { return configure(configuration, HistoryEventTypes.BATCH_START, HistoryEventTypes.BATCH_END); } }; public ProvidedProcessEngineRule engineRule = new ProvidedProcessEngineRule(bootstrapRule); public ProcessEngineTestRule testRule = new ProcessEngineTestRule(engineRule); @Before public void init() { engineConfiguration = engineRule.getProcessEngineConfiguration(); initEngineConfiguration(engineConfiguration); historyService = engineRule.getHistoryService(); managementService = engineRule.getManagementService(); runtimeService = engineRule.getRuntimeService(); taskService = engineRule.getTaskService(); } @Rule public RuleChain ruleChain = RuleChain.outerRule(bootstrapRule).around(engineRule).around(testRule); protected RuntimeService runtimeService; protected TaskService taskService; protected final String PROCESS_KEY = "process"; protected final BpmnModelInstance PROCESS = Bpmn.createExecutableProcess(PROCESS_KEY) .camundaHistoryTimeToLive(5) .startEvent() .userTask() .endEvent().done(); protected final String CALLING_PROCESS_KEY = "callingProcess"; protected final BpmnModelInstance CALLING_PROCESS = Bpmn.createExecutableProcess(CALLING_PROCESS_KEY) .startEvent() .callActivity() .calledElement(PROCESS_KEY) .multiInstance() .cardinality("5") .multiInstanceDone() .endEvent().done(); protected final Date END_DATE = new Date(1363608000000L); @Test public void shouldScheduleToNow() { // given engineConfiguration.setBatchOperationHistoryTimeToLive("P5D"); engineConfiguration.setHistoryCleanupBatchSize(5); engineConfiguration.initHistoryCleanup(); testRule.deploy(PROCESS); testRule.deploy(CALLING_PROCESS); runtimeService.startProcessInstanceByKey(CALLING_PROCESS_KEY).getId(); for (int i = 0; i < 5; i++) { String processInstanceId = runtimeService.createProcessInstanceQuery().list().get(0).getId(); runtimeService.deleteProcessInstancesAsync(Collections.singletonList(processInstanceId), "aDeleteReason"); ClockUtil.setCurrentTime(END_DATE); String jobId = managementService.createJobQuery().singleResult().getId(); managementService.executeJob(jobId); jobIds.add(jobId); List<Job> jobs = managementService.createJobQuery().list(); for (Job job : jobs) { managementService.executeJob(job.getId()); jobIds.add(job.getId()); } } Date removalTime = addDays(END_DATE, 5); ClockUtil.setCurrentTime(removalTime); // when runHistoryCleanup(); Job job = historyService.findHistoryCleanupJobs().get(0); // then assertThat(job.getDuedate(), is(removalTime)); } @Test public void shouldScheduleToLater() { // given engineConfiguration.setBatchOperationHistoryTimeToLive("P5D"); engineConfiguration.setHistoryCleanupBatchSize(6); engineConfiguration.initHistoryCleanup(); testRule.deploy(PROCESS); testRule.deploy(CALLING_PROCESS); runtimeService.startProcessInstanceByKey(CALLING_PROCESS_KEY).getId(); for (int i = 0; i < 5; i++) { String processInstanceId = runtimeService.createProcessInstanceQuery().list().get(0).getId(); runtimeService.deleteProcessInstancesAsync(Collections.singletonList(processInstanceId), "aDeleteReason"); ClockUtil.setCurrentTime(END_DATE); String jobId = managementService.createJobQuery().singleResult().getId(); managementService.executeJob(jobId); jobIds.add(jobId); List<Job> jobs = managementService.createJobQuery().list(); for (Job job : jobs) { managementService.executeJob(job.getId()); jobIds.add(job.getId()); } } Date removalTime = addDays(END_DATE, 5); ClockUtil.setCurrentTime(removalTime); // when runHistoryCleanup(); Job job = historyService.findHistoryCleanupJobs().get(0); // then assertThat(job.getDuedate(), is(removalTime)); } }
engine/src/test/java/org/camunda/bpm/engine/test/api/history/removaltime/cleanup/HistoryCleanupScheduleBatchesTest.java
test(engine): add scheduler test for historic batches related to CAM-9423
engine/src/test/java/org/camunda/bpm/engine/test/api/history/removaltime/cleanup/HistoryCleanupScheduleBatchesTest.java
test(engine): add scheduler test for historic batches
Java
artistic-2.0
error: pathspec 'star.java' did not match any file(s) known to git
b971a395155bef19fbdbb81f12795e4154fd673f
1
minexu/xian1
public class Movie{ public void play(){ All Star Converse } }
star.java
测试往 github网络上 传输代码
star.java
测试往 github网络上 传输代码
Java
bsd-2-clause
error: pathspec 'utils/UniqueTraces.java' did not match any file(s) known to git
7e5b08f3bd6989e2de5f35c2c41b603a9e03d6b1
1
scifio/scifio
// // UniqueTraces.java // import java.io.*; import java.util.Vector; /** * Reads in a bunch of stack traces from standard input, * filters out duplicates and outputs what's left. */ public class UniqueTraces { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); Vector traces = new Vector(); StringBuffer buf = null; while (true) { String line = in.readLine(); if (line == null) break; if (!line.startsWith(" ") && !line.startsWith("\t")) { // start of a new stack trace if (buf == null) buf = new StringBuffer(); // first stack trace else { // record previous stack trace traces.add(buf.toString()); buf.setLength(0); } // in the middle of a stack trace } buf.append(line); buf.append("\n"); } traces.add(buf.toString()); String[] traceStrings = new String[traces.size()]; traces.copyInto(traceStrings); for (int i=0; i<traceStrings.length; i++) { String s = traceStrings[i]; boolean match = false; for (int j=0; j<traceStrings.length; j++) { if (i != j && s.equals(traceStrings[j])) { match = true; break; } } if (!match) System.out.print(s); } } }
utils/UniqueTraces.java
A simple utility to filter out duplicate stack traces.
utils/UniqueTraces.java
A simple utility to filter out duplicate stack traces.
Java
bsd-2-clause
error: pathspec 'components/loci-legacy/src/loci/legacy/adapter/AdapterTools.java' did not match any file(s) known to git
a0b5f3da5ad4d5cbd337df529d983d173a170e28
1
scifio/scifio
/* * #%L * OME SCIFIO package for reading and converting scientific file formats. * %% * Copyright (C) 2005 - 2012 Open Microscopy Environment: * - Board of Regents of the University of Wisconsin-Madison * - Glencoe Software, Inc. * - University of Dundee * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are * those of the authors and should not be interpreted as representing official * policies, either expressed or implied, of any organization. * #L% */ package loci.legacy.adapter; import java.util.HashMap; import loci.common.adapter.CodedEnumAdapter; import loci.common.adapter.IRandomAccessAdapter; import loci.common.adapter.StatusListenerAdapter; import loci.common.adapter.StatusReporterAdapter; /** * A collection of {@link LegacyAdapter}s for wrapping (and thereby delegating) * between Legacy classes and their Modern equivalents. * <p> * As adapters use HashTables to manage delegation between instances, this utility * ensures that a single instance of every mapping is statically available, to avoid unnecessary * or repetitive wrappings. * </p> * * @author Mark Hiner */ public final class AdapterTools { /** Maps LegacyAdapter classes to an instance of that clas, so that a single instance is maintained. * This is necessary because each adapter maintains its own static mapping of Legacy and Modern classes. */ private static HashMap<Class<? extends LegacyAdapter<?, ?>>, Object> adapterMap = new HashMap<Class<? extends LegacyAdapter<?, ?>>, Object>(); // Manually populate the map of adapters static { AdapterTools.adapterMap.put(IRandomAccessAdapter.class, new IRandomAccessAdapter()); AdapterTools.adapterMap.put(CodedEnumAdapter.class, new CodedEnumAdapter()); AdapterTools.adapterMap.put(StatusListenerAdapter.class, new StatusListenerAdapter()); AdapterTools.adapterMap.put(StatusReporterAdapter.class, new StatusReporterAdapter()); } // -- Adapter Retrieval -- /** * Looks up the adapter instance * @return An adapter for converting between legacy and modern IRandomAccess objects */ @SuppressWarnings("unchecked") public static <T> T getAdapter(Class<T> adapterClass) { Object adapter = adapterMap.get(adapterClass); // this cast is safe if an adapter was found. return adapter == null ? null : (T)adapter; } }
components/loci-legacy/src/loci/legacy/adapter/AdapterTools.java
Added static AdapterTools utility All adapters maintain a mapping between legacy and modern classes. To avoid duplication of these classes, and thus the maps (which would not necessarily be synchronized) it makes sense to have a single active instance of each adapter. These instances can then be accessed via a single static entry point. AdapterTools serves as that entry point. It uses a static initializer to populate its mapping of adapter classes to adapter instances, and getAdapter(Clas<Adapter>) to query into that mapping. Note that future adapters must be manually added to the static initializer, or adapters need to be converted to some mechanism of discovery.
components/loci-legacy/src/loci/legacy/adapter/AdapterTools.java
Added static AdapterTools utility
Java
mit
453dde1e60b29c11b4b77c5d58497acbe9e416b1
0
Narwhalprime/simcity201-team-project
package bank; import agent.Agent; import bank.interfaces.Manager; import bank.interfaces.Teller; import bank.interfaces.BankCustomer; import bank.gui.Account; import bank.gui.Bank; import simcity.gui.SimCityGui; import java.util.*; /** * bank Host Agent */ //We only have 2 types of agents in this prototype. A customer and an agent that //does all the rest. Rather than calling the other agent a waiter, we called him //the HostAgent. A Host is the manager of a bank who sees that all //is proceeded as he wishes. public class ManagerAgent extends Agent implements Manager { public class WaitingCustomer { BankCustomer bankCustomer; State state; Action action; private int accountNum; private double requestAmt; public WaitingCustomer(BankCustomer bc){ bankCustomer = bc; state = State.waiting; } public void setAccountNum(int accNum){ accountNum = accNum; } public int getAccountNum(){ return accountNum; } public void setRequestAmt(double ra){ requestAmt = ra; } public double getRequestAmt(){ return requestAmt; } } List<WaitingCustomer> waitingCustomers = Collections.synchronizedList(new ArrayList<WaitingCustomer>());; enum State{entered, waiting, leaving, busy, idle}; enum Action{none, newAccount, deposit, withdraw}; List<Account> accounts = Collections.synchronizedList(new ArrayList<Account>()); class MyTeller { Teller teller; TellerState state; public MyTeller(Teller t){ teller = t; state = TellerState.idle; } } enum TellerState{idle, busy}; public List<MyTeller> tellers = Collections.synchronizedList(new ArrayList<MyTeller>()); private Bank bank; private SimCityGui simCityGui; private String name; public ManagerAgent(String name, Bank b, SimCityGui bg) { super(); bank = b; simCityGui = bg; this.name = name; } public String getMaitreDName() { return name; } public String getName() { return name; } // Messages public void msgTellerFree(Teller teller, BankCustomer bankCustomer){ synchronized(tellers){ for(MyTeller t : tellers){ if(t.teller == teller){ t.state = TellerState.idle; break; } } } synchronized(waitingCustomers){ for(WaitingCustomer wc : waitingCustomers){ if(wc.bankCustomer == bankCustomer){ wc.state = State.leaving; break; } } } stateChanged(); } public void msgCustomerHere(BankCustomer bca){ boolean found = false; synchronized(waitingCustomers){ for(WaitingCustomer wc : waitingCustomers){ if(wc.bankCustomer == bca){ wc.state = State.entered; found = true; break; } } } if(found == false){ waitingCustomers.add(new WaitingCustomer(bca)); } } public void msgRequestAccount(BankCustomer bc, double amount){ synchronized(waitingCustomers){ print("msgRequestAccount"); for(WaitingCustomer wc : waitingCustomers){ if(wc.bankCustomer == bc){ wc.setAccountNum(-1); wc.setRequestAmt(amount); wc.action = Action.newAccount; break; } } } stateChanged(); } public void msgRequestDeposit(BankCustomer bc, int accountNumber, double amount){ WaitingCustomer waitingCustomer = null; synchronized(waitingCustomers){ for(WaitingCustomer wc : waitingCustomers){ if(wc.bankCustomer == bc){ waitingCustomer = wc; wc.setAccountNum(accountNumber); wc.setRequestAmt(amount); break; } } } waitingCustomer.action = Action.deposit; stateChanged(); } public void msgRequestWithdrawal(BankCustomer bc, int accountNumber, double amount){ synchronized(waitingCustomers){ for(WaitingCustomer wc : waitingCustomers){ if(wc.bankCustomer == bc){ wc.setAccountNum(accountNumber); wc.setRequestAmt(amount); wc.action = Action.withdraw; break; } } } stateChanged(); } /** * Scheduler. Determine what action is called for, and do it. */ protected boolean pickAndExecuteAnAction() { synchronized(waitingCustomers){ for(WaitingCustomer wc : waitingCustomers){ if(wc.state == State.waiting){ synchronized(tellers){ for(MyTeller mt : tellers){ if(mt.state == TellerState.idle){ assignTeller(mt, wc); return true; } } } } } } synchronized(waitingCustomers){ for(WaitingCustomer wc : waitingCustomers){ if(wc.state == State.entered){ synchronized(tellers){ for(MyTeller mt : tellers){ if(mt.state == TellerState.idle){ assignTeller(mt, wc); return true; } } } } tellerBusy(wc); return true; } } synchronized(waitingCustomers){ for(WaitingCustomer wc : waitingCustomers){ if(wc.state == State.leaving){ updatePersonInfo(wc); return true; } } } return false; //we have tried all our rules and found //nothing to do. So return false to main loop of abstract agent //and wait. } // Actions private void assignTeller(MyTeller mt, WaitingCustomer wc){ wc.bankCustomer.msgGoToTeller(mt.teller); print(wc.toString() + " " + wc.action); if(wc.action == Action.newAccount){ wc.bankCustomer.msgRequestNewAccount(wc.requestAmt); } else if(wc.action == Action.deposit){ wc.bankCustomer.msgRequestDeposit(wc.requestAmt, wc.accountNum); } else if(wc.action == Action.withdraw){ print("RA: "+wc.requestAmt); wc.bankCustomer.msgRequestWithdraw(wc.requestAmt, wc.accountNum); } wc.state = State.busy; mt.teller.msgNewCustomer(wc.bankCustomer); mt.state = TellerState.busy; wc.action = Action.none; } private void tellerBusy(WaitingCustomer wc){ wc.state = State.waiting; } private void updatePersonInfo(WaitingCustomer wc){ BankCustomer bc = wc.bankCustomer; print(bc.getAccountNum() + " $" + bc.getBalance()); wc.state = State.idle; bank.msgLeave(wc.bankCustomer, bc.getAccountNum(), bc.getChange(), bc.getLoanAmount(), bc.getLoanTime()); } public void addAccount(Account acc){ accounts.add(acc); } public List<Account> getAccounts(){ return accounts; } public void addTeller(TellerAgent t){ MyTeller mt = new MyTeller(t); tellers.add(mt); //? //tellers.add(new MyTeller(t)); stateChanged(); } public SimCityGui getGui(){ return simCityGui; } }
src/bank/ManagerAgent.java
package bank; import agent.Agent; import bank.interfaces.Manager; import bank.interfaces.Teller; import bank.interfaces.BankCustomer; import bank.gui.Account; import bank.gui.Bank; import simcity.gui.SimCityGui; import java.util.*; /** * bank Host Agent */ //We only have 2 types of agents in this prototype. A customer and an agent that //does all the rest. Rather than calling the other agent a waiter, we called him //the HostAgent. A Host is the manager of a bank who sees that all //is proceeded as he wishes. public class ManagerAgent extends Agent implements Manager { public class WaitingCustomer { BankCustomer bankCustomer; State state; Action action; private int accountNum; private double requestAmt; public WaitingCustomer(BankCustomer bc){ bankCustomer = bc; state = State.waiting; } public void setAccountNum(int accNum){ accountNum = accNum; } public int getAccountNum(){ return accountNum; } public void setRequestAmt(double ra){ requestAmt = ra; } public double getRequestAmt(){ return requestAmt; } } List<WaitingCustomer> waitingCustomers = Collections.synchronizedList(new ArrayList<WaitingCustomer>());; enum State{entered, waiting, leaving, busy, idle}; enum Action{newAccount, deposit, withdraw}; List<Account> accounts = Collections.synchronizedList(new ArrayList<Account>()); class MyTeller { Teller teller; TellerState state; public MyTeller(Teller t){ teller = t; state = TellerState.idle; } } enum TellerState{idle, busy}; public List<MyTeller> tellers = Collections.synchronizedList(new ArrayList<MyTeller>()); private Bank bank; private SimCityGui simCityGui; private String name; public ManagerAgent(String name, Bank b, SimCityGui bg) { super(); bank = b; simCityGui = bg; this.name = name; } public String getMaitreDName() { return name; } public String getName() { return name; } // Messages public void msgTellerFree(Teller teller, BankCustomer bankCustomer){ synchronized(tellers){ for(MyTeller t : tellers){ if(t.teller == teller){ t.state = TellerState.idle; break; } } } synchronized(waitingCustomers){ for(WaitingCustomer wc : waitingCustomers){ if(wc.bankCustomer == bankCustomer){ wc.state = State.leaving; break; } } } stateChanged(); } public void msgCustomerHere(BankCustomer bca){ boolean found = false; synchronized(waitingCustomers){ for(WaitingCustomer wc : waitingCustomers){ if(wc.bankCustomer == bca){ wc.state = State.entered; found = true; break; } } } if(found == false){ waitingCustomers.add(new WaitingCustomer(bca)); } } public void msgRequestAccount(BankCustomer bc, double amount){ synchronized(waitingCustomers){ print("msgRequestAccount"); for(WaitingCustomer wc : waitingCustomers){ if(wc.bankCustomer == bc){ wc.setAccountNum(-1); wc.setRequestAmt(amount); wc.action = Action.newAccount; break; } } } stateChanged(); } public void msgRequestDeposit(BankCustomer bc, int accountNumber, double amount){ WaitingCustomer waitingCustomer = null; synchronized(waitingCustomers){ for(WaitingCustomer wc : waitingCustomers){ if(wc.bankCustomer == bc){ waitingCustomer = wc; wc.setAccountNum(accountNumber); wc.setRequestAmt(amount); break; } } } waitingCustomer.action = Action.deposit; stateChanged(); } public void msgRequestWithdrawal(BankCustomer bc, int accountNumber, double amount){ synchronized(waitingCustomers){ for(WaitingCustomer wc : waitingCustomers){ if(wc.bankCustomer == bc){ wc.setAccountNum(accountNumber); wc.setRequestAmt(amount); wc.action = Action.withdraw; break; } } } stateChanged(); } /** * Scheduler. Determine what action is called for, and do it. */ protected boolean pickAndExecuteAnAction() { synchronized(waitingCustomers){ for(WaitingCustomer wc : waitingCustomers){ if(wc.state == State.waiting){ synchronized(tellers){ for(MyTeller mt : tellers){ if(mt.state == TellerState.idle){ assignTeller(mt, wc); return true; } } } } } } synchronized(waitingCustomers){ for(WaitingCustomer wc : waitingCustomers){ if(wc.state == State.entered){ synchronized(tellers){ for(MyTeller mt : tellers){ if(mt.state == TellerState.idle){ assignTeller(mt, wc); return true; } } } } tellerBusy(wc); return true; } } synchronized(waitingCustomers){ for(WaitingCustomer wc : waitingCustomers){ if(wc.state == State.leaving){ updatePersonInfo(wc); return true; } } } return false; //we have tried all our rules and found //nothing to do. So return false to main loop of abstract agent //and wait. } // Actions private void assignTeller(MyTeller mt, WaitingCustomer wc){ wc.bankCustomer.msgGoToTeller(mt.teller); print(wc.toString() + " " + wc.action); if(wc.action == Action.newAccount){ wc.bankCustomer.msgRequestNewAccount(wc.requestAmt); } else if(wc.action == Action.deposit){ wc.bankCustomer.msgRequestDeposit(wc.requestAmt, wc.accountNum); } else if(wc.action == Action.withdraw){ print("RA: "+wc.requestAmt); wc.bankCustomer.msgRequestWithdraw(wc.requestAmt, wc.accountNum); } wc.state = State.busy; mt.teller.msgNewCustomer(wc.bankCustomer); mt.state = TellerState.busy; } private void tellerBusy(WaitingCustomer wc){ wc.state = State.waiting; } private void updatePersonInfo(WaitingCustomer wc){ BankCustomer bc = wc.bankCustomer; print(bc.getAccountNum() + " $" + bc.getBalance()); wc.state = State.idle; bank.msgLeave(wc.bankCustomer, bc.getAccountNum(), bc.getChange(), bc.getLoanAmount(), bc.getLoanTime()); } public void addAccount(Account acc){ accounts.add(acc); } public List<Account> getAccounts(){ return accounts; } public void addTeller(TellerAgent t){ MyTeller mt = new MyTeller(t); tellers.add(mt); //? //tellers.add(new MyTeller(t)); stateChanged(); } public SimCityGui getGui(){ return simCityGui; } }
added a none state in the bank
src/bank/ManagerAgent.java
added a none state in the bank
Java
mit
9b5a306e77f335297fae1eacb08fe27e471bd41b
0
monsendag/goldfish,ntnu-smartmedia/goldfish,monsendag/goldfish,monsendag/goldfish,ntnu-smartmedia/goldfish,ntnu-smartmedia/goldfish
package edu.ntnu.idi.goldfish; import edu.ntnu.idi.goldfish.configurations.Config; import edu.ntnu.idi.goldfish.configurations.Lynx; import edu.ntnu.idi.goldfish.preprocessors.*; import edu.ntnu.idi.goldfish.preprocessors.PreprocessorClustering.ClusterDataset; import edu.ntnu.idi.goldfish.preprocessors.PreprocessorClustering.Clusterer; import edu.ntnu.idi.goldfish.preprocessors.PreprocessorClustering.DistFunc; import edu.ntnu.idi.goldfish.preprocessors.PreprocessorIBK.DistanceWeighting; import edu.ntnu.idi.goldfish.preprocessors.PreprocessorIBK.ErrorMinimization; import edu.ntnu.idi.goldfish.preprocessors.PreprocessorIBK.NeighborSearchMethod; import edu.ntnu.idi.goldfish.preprocessors.PreprocessorPuddis.PredMethod; import edu.ntnu.idi.goldfish.preprocessors.PreprocessorSMOreg.Kernel; import edu.ntnu.idi.goldfish.preprocessors.PreprocessorStat.PredictionMethod; import org.apache.commons.lang3.StringUtils; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static edu.ntnu.idi.goldfish.DataSet.*; public class Main { public int i = 1; public static DataSet set; // disable Mahout logging output static { System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.NoOpLog"); } public static void main(String[] args) throws Exception { new Main(); } public Main() throws Exception { List<Config> configs = new ArrayList<>(); ResultList results = new ResultList(); Columns cols = new Columns(); cols.add("name", "average", "RMSE", "evalTime"); Config config; /***********************************************************************************/ // Baseline if(false) { Config baseLine = new Lynx() .set("name", "baseline") .set("model", yowBaseline.getModel()) .set("average", 5000); configs.add(baseLine); } /***********************************************************************************/ // PreprocessorStat // if(false) { Config stat = new Lynx() .set("name", "stat") .set("model", yowImplicit.getModel()) .set("preprocessor", PreprocessorStat.class) .set("average", 5000); for (int minT = 15000; minT <= 30000; minT += 5000) { for (double corrLimit = 0.4; corrLimit <= 0.8; corrLimit += 0.1) { for (PredictionMethod method : PredictionMethod.values()) { config = stat.clone() .set("minTimeOnPage", minT) .set("correlationLimit", corrLimit) .set("predictionMethod", method); configs.add(config); } } } cols.add("minTimeOnPage", "correlationLimit", "predictionMethod"); } /***********************************************************************************/ // PreprocessorClustering // if(false) { Config clustering = new Lynx() .set("name", "clustering") .set("model", yowImplicit.getModel()) .set("preprocessor", PreprocessorClustering.class) .set("average", 10000); for(Clusterer clusterer : Arrays.asList(Clusterer.SimpleKMeans, Clusterer.XMeans, Clusterer.DensityBased)) { for(ClusterDataset dataset : ClusterDataset.values()) { for (DistFunc distFunc : Arrays.asList(DistFunc.Euclidean, DistFunc.Manhattan)) { config = clustering.clone() .set("clusterer", clusterer) .set("clusterDataset", dataset) .set("distFunc", distFunc); configs.add(config); } } } for(Clusterer clusterer : Arrays.asList(Clusterer.Cobweb, Clusterer.EM, Clusterer.FarthestFirst)) { for(ClusterDataset dataset : ClusterDataset.values()) { config = clustering.clone() .set("clusterer", clusterer) .set("clusterDataset", dataset) .set("distFunc", DistFunc.None); configs.add(config); } } for (ClusterDataset dataset : ClusterDataset.values()) { config = clustering.clone() .set("clusterer", Clusterer.XMeans) .set("clusterDataset", dataset) .set("distFunc", DistFunc.Chebyshev); configs.add(config); } cols.add("clusterer", "clusterDataset", "distFunc"); } /***********************************************************************************/ // PreprocessorMLR // if(false) { Config mlr = new Lynx() .set("name", "MLR") .set("model", yowImplicit.getModel()) .set("preprocessor", PreprocessorMLR.class) .set("average", 5000); for (int i = 1; i <= 3; i++) { config = mlr.clone() .set("IVs", i); configs.add(config); } cols.add("IVs"); } /***********************************************************************************/ // PreprocessorSMOreg // if(false) { Config smoreg = new Lynx() .set("name", "smoreg") .set("model", yowImplicit.getModel()) .set("preprocessor", PreprocessorSMOreg.class) .set("average", 5000); for(double Cn = -10; Cn <= 10; Cn += 1) { // RBFKernel for(double gammaN = -6; gammaN <= 6; gammaN += 1) { config = smoreg.clone() .set("kernel", Kernel.RBFKernel) .set("C", Math.pow(2, Cn)) .set("kernelGamma", Math.pow(2, gammaN)); configs.add(config); } // PolyKernel, NormalizedPolyKernel List<Kernel> kernels = Arrays.asList(Kernel.PolyKernel, Kernel.NormalizedPolyKernel); for(Kernel kernel : kernels) { for(double exponentN = -6; exponentN <= 6; exponentN += 0.5) { config = smoreg.clone() .set("kernel", kernel) .set("C", Cn) .set("kernelExponent", Math.pow(2, exponentN)); configs.add(config); } } } cols.add("kernel", "C", "kernelGamma", "kernelExponent"); } /***********************************************************************************/ // PreprocessorANN // if(false) { Config ann = new Lynx() .set("name", "ann") .set("model", yowImplicit.getModel()) .set("preprocessor", PreprocessorANN.class) .set("average", 5000); for (double learningRate = 0.1; learningRate <= 1; learningRate += 0.1) { for (double momentum = 0.1; momentum <= 1; momentum += 0.1) { config = ann.clone() .set("learningRate", learningRate) .set("momentum", momentum) .set("epochs", 500) .set("neurons", "a"); configs.add(config); } } cols.add("learningRate"); } /***********************************************************************************/ // PreprocessorIBK // if(false) { Config ibk = new Lynx() .set("name", "ibk") .set("model", yowImplicit.getModel()) .set("preprocessor", PreprocessorIBK.class) .set("window", 0) .set("average", 5000); for(DistanceWeighting weighting : DistanceWeighting.values()) { for(ErrorMinimization minimization : ErrorMinimization.values()) { for(NeighborSearchMethod method : NeighborSearchMethod.values()) { for (int K = 1; K < 10; K++) { config = ibk.clone() .set("K", K) .set("distanceMeasure", weighting) .set("minimization", minimization) .set("method", method); configs.add(config); } } } } } /***********************************************************************************/ // PreprocessorNaiveBayes // if(false) { Config naivebayes = new Lynx() .set("name", "naivebayes") .set("model", yowImplicit.getModel()) .set("preprocessor", PreprocessorNaiveBayes.class) .set("average", 5000); configs.add(naivebayes); } /***********************************************************************************/ StopWatch.start("total evaluation"); System.out.format("Starting evaluation of %d configurations \n", configs.size()); Evaluator.evaluate(configs, results, res -> System.out.println((this.i++) + "|"+res.toString(cols.getPrintFormats()))); System.out.println(StringUtils.repeat("=", 190)); results.printSummary(cols.getPrintFormats()); System.out.format("Evaluated %d configurations in %s \n", configs.size(), StopWatch.str("total evaluation")); results.save(cols.getSaveFormats()); } }
src/edu/ntnu/idi/goldfish/Main.java
package edu.ntnu.idi.goldfish; import edu.ntnu.idi.goldfish.configurations.Config; import edu.ntnu.idi.goldfish.configurations.Lynx; import edu.ntnu.idi.goldfish.preprocessors.*; import edu.ntnu.idi.goldfish.preprocessors.PreprocessorClustering.ClusterDataset; import edu.ntnu.idi.goldfish.preprocessors.PreprocessorClustering.Clusterer; import edu.ntnu.idi.goldfish.preprocessors.PreprocessorClustering.DistFunc; import edu.ntnu.idi.goldfish.preprocessors.PreprocessorIBK.DistanceWeighting; import edu.ntnu.idi.goldfish.preprocessors.PreprocessorIBK.ErrorMinimization; import edu.ntnu.idi.goldfish.preprocessors.PreprocessorIBK.NeighborSearchMethod; import edu.ntnu.idi.goldfish.preprocessors.PreprocessorPuddis.PredMethod; import edu.ntnu.idi.goldfish.preprocessors.PreprocessorSMOreg.Kernel; import edu.ntnu.idi.goldfish.preprocessors.PreprocessorStat.PredictionMethod; import org.apache.commons.lang3.StringUtils; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static edu.ntnu.idi.goldfish.DataSet.*; public class Main { public int i = 1; public static DataSet set; // disable Mahout logging output static { System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.NoOpLog"); } public static void main(String[] args) throws Exception { new Main(); } public Main() throws Exception { List<Config> configs = new ArrayList<>(); ResultList results = new ResultList(); Columns cols = new Columns(); cols.add("name", "average", "RMSE", "evalTime"); Config config; /***********************************************************************************/ // Baseline if(false) { Config baseLine = new Lynx() .set("name", "baseline") .set("model", yowBaseline.getModel()) .set("average", 5000); configs.add(baseLine); } /***********************************************************************************/ // PreprocessorPuddis if(false) { Config puddis = new Lynx() .set("name", "puddis") .set("model", yowSMImplicit.getModel()) .set("preprocessor", PreprocessorPuddis.class) .set("average", 10000); for (int minT = 15000; minT <= 30000; minT += 5000) { for (double corrLimit = 0.4; corrLimit <= 0.8; corrLimit += 0.1) { for (PredMethod method : PredMethod.values()) { config = puddis.clone() .set("minTimeOnPage", minT) .set("correlationLimit", corrLimit) .set("predictionMethod", method); // configs.add(conf); } } } cols.add("minTimeOnPage", "correlationLimit", "predictionMethod"); } /***********************************************************************************/ // PreprocessorStat // if(false) { Config stat = new Lynx() .set("name", "stat") .set("model", yowImplicit.getModel()) .set("preprocessor", PreprocessorStat.class) .set("average", 5000); for (int minT = 15000; minT <= 30000; minT += 5000) { for (double corrLimit = 0.4; corrLimit <= 0.8; corrLimit += 0.1) { for (PredictionMethod method : PredictionMethod.values()) { config = stat.clone() .set("minTimeOnPage", minT) .set("correlationLimit", corrLimit) .set("predictionMethod", method); configs.add(config); } } } cols.add("minTimeOnPage", "correlationLimit", "predictionMethod"); } /***********************************************************************************/ // PreprocessorClustering // if(false) { Config clustering = new Lynx() .set("name", "clustering") .set("model", yowImplicit.getModel()) .set("preprocessor", PreprocessorClustering.class) .set("average", 10000); for(Clusterer clusterer : Arrays.asList(Clusterer.SimpleKMeans, Clusterer.XMeans, Clusterer.DensityBased)) { for(ClusterDataset dataset : ClusterDataset.values()) { for (DistFunc distFunc : Arrays.asList(DistFunc.Euclidean, DistFunc.Manhattan)) { config = clustering.clone() .set("clusterer", clusterer) .set("clusterDataset", dataset) .set("distFunc", distFunc); configs.add(config); } } } for(Clusterer clusterer : Arrays.asList(Clusterer.Cobweb, Clusterer.EM, Clusterer.FarthestFirst)) { for(ClusterDataset dataset : ClusterDataset.values()) { config = clustering.clone() .set("clusterer", clusterer) .set("clusterDataset", dataset) .set("distFunc", DistFunc.None); configs.add(config); } } for (ClusterDataset dataset : ClusterDataset.values()) { config = clustering.clone() .set("clusterer", Clusterer.XMeans) .set("clusterDataset", dataset) .set("distFunc", DistFunc.Chebyshev); configs.add(config); } cols.add("clusterer", "clusterDataset", "distFunc"); } /***********************************************************************************/ // PreprocessorMLR // if(false) { Config mlr = new Lynx() .set("name", "MLR") .set("model", yowImplicit.getModel()) .set("preprocessor", PreprocessorMLR.class) .set("average", 5000); for (int i = 1; i <= 3; i++) { config = mlr.clone() .set("IVs", i); configs.add(config); } cols.add("IVs"); } /***********************************************************************************/ // PreprocessorSMOreg // if(false) { Config smoreg = new Lynx() .set("name", "smoreg") .set("model", yowImplicit.getModel()) .set("preprocessor", PreprocessorSMOreg.class) .set("average", 5000); for(double Cn = -10; Cn <= 10; Cn += 1) { // RBFKernel for(double gammaN = -6; gammaN <= 6; gammaN += 1) { config = smoreg.clone() .set("kernel", Kernel.RBFKernel) .set("C", Math.pow(2, Cn)) .set("kernelGamma", Math.pow(2, gammaN)); configs.add(config); } // PolyKernel, NormalizedPolyKernel List<Kernel> kernels = Arrays.asList(Kernel.PolyKernel, Kernel.NormalizedPolyKernel); for(Kernel kernel : kernels) { for(double exponentN = -6; exponentN <= 6; exponentN += 0.5) { config = smoreg.clone() .set("kernel", kernel) .set("C", Cn) .set("kernelExponent", Math.pow(2, exponentN)); configs.add(config); } } } cols.add("kernel", "C", "kernelGamma", "kernelExponent"); } /***********************************************************************************/ // PreprocessorANN // if(false) { Config ann = new Lynx() .set("name", "ann") .set("model", yowImplicit.getModel()) .set("preprocessor", PreprocessorANN.class) .set("average", 5000); for (double learningRate = 0.1; learningRate <= 1; learningRate += 0.1) { for (double momentum = 0.1; momentum <= 1; momentum += 0.1) { config = ann.clone() .set("learningRate", learningRate) .set("momentum", momentum) .set("epochs", 500) .set("neurons", "a"); configs.add(config); } } cols.add("learningRate"); } /***********************************************************************************/ // PreprocessorIBK // if(false) { Config ibk = new Lynx() .set("name", "ibk") .set("model", yowImplicit.getModel()) .set("preprocessor", PreprocessorIBK.class) .set("window", 0) .set("average", 5000); for(DistanceWeighting weighting : DistanceWeighting.values()) { for(ErrorMinimization minimization : ErrorMinimization.values()) { for(NeighborSearchMethod method : NeighborSearchMethod.values()) { for (int K = 1; K < 10; K++) { config = ibk.clone() .set("K", K) .set("distanceMeasure", weighting) .set("minimization", minimization) .set("method", method); configs.add(config); } } } } } /***********************************************************************************/ // PreprocessorNaiveBayes // if(false) { Config naivebayes = new Lynx() .set("name", "naivebayes") .set("model", yowImplicit.getModel()) .set("preprocessor", PreprocessorNaiveBayes.class) .set("average", 5000); configs.add(naivebayes); } /***********************************************************************************/ StopWatch.start("total evaluation"); System.out.format("Starting evaluation of %d configurations \n", configs.size()); Evaluator.evaluate(configs, results, res -> System.out.println((this.i++) + "|"+res.toString(cols.getPrintFormats()))); System.out.println(StringUtils.repeat("=", 190)); results.printSummary(cols.getPrintFormats()); System.out.format("Evaluated %d configurations in %s \n", configs.size(), StopWatch.str("total evaluation")); results.save(cols.getSaveFormats()); } }
Remove calls to preprocessorPuddis Replaced by PreprocessorStat. Can be retrieved in VCS if needed.
src/edu/ntnu/idi/goldfish/Main.java
Remove calls to preprocessorPuddis
Java
mit
11b4365bdc3fd0bbdcdf29912dad221823b32570
0
Detharon/Slovo
package com.dth.slovo; /** * WordProcessor is a small class that normalizes the {@code String} * by altering it in numerous ways, so that the resulting {@code String} * will only contain a sequence of alphabetic characters. * * <p>For example, in the following code, strings {code "a"}, {code "b"}, * and {code "c"} will contain "happy" in all cases. * <blockquote> * WordProcessor processor = new WordProcessor(); * String a = processor.processWord(" happy "); * String b = processor.processWord(".happy!"); * String c = processor.processWord(" HaPPy!"); * </blockquote> */ public class WordProcessor { /** * Processes the {@code String} by subjecting it to the * following changes: * <ul> * <li> Removing leading and trailing white spaces * <li> Removing leading and trailing punctuation marks * <li> Converting to lowercase. * </ul> * * @param word the input {@code String} that will be processed. * * @return the normalized {@code String}, if the input contained * at least one alphabetic character. Otherwise returns * an empty {@code String}. */ public String processWord(String word) { // Initialize the StringBuilder and trim the string StringBuilder temp = new StringBuilder(word.trim()); // If it's empty, return null if (temp.length() == 0) { return null; } // Remove leading punctuation marks while (temp.length() > 0 && !Character.isAlphabetic(temp.charAt(0))) { temp.deleteCharAt(0); } if (temp.length() == 0) { return null; } // Remove trailing punctuation marks while (temp.length() > 0 && !Character.isAlphabetic(temp.charAt(temp.length() - 1))) { temp.deleteCharAt(temp.length() - 1); } if (temp.length() == 0) { return null; } // To lowercase for (int i = 0; i < temp.length(); i++) { temp.setCharAt(i, Character.toLowerCase(temp.charAt(i))); } return temp.toString(); } }
src/main/java/com/dth/slovo/WordProcessor.java
package com.dth.slovo; public class WordProcessor { /** Class * */ public WordProcessor(){} public String processWord(String word) { // Initialize StringBuilder and trim the string StringBuilder temp = new StringBuilder(word.trim()); // If its empty, return null if (temp.length() == 0) return null; // Remove leading punctuation marks while (temp.length() > 0 && !Character.isAlphabetic(temp.charAt(0))) { temp.deleteCharAt(0); } if (temp.length() == 0) return null; // Remove trailing punctuation marks while (temp.length() > 0 && !Character.isAlphabetic(temp.charAt(temp.length() - 1))) { temp.deleteCharAt(temp.length() - 1); } if (temp.length() == 0) return null; // To lowercase for (int i = 0; i < temp.length(); i++) { char c = temp.charAt(i); temp.setCharAt(i, Character.toLowerCase(c)); } return temp.toString(); } }
Add WordProcessor javadoc * Javadoc entries has been created for the WordProcessor class and its method.
src/main/java/com/dth/slovo/WordProcessor.java
Add WordProcessor javadoc
Java
mit
663d8f82af232d8d036f619e39b76df6e2885339
0
dxiao/PPBunnies,dxiao/PPBunnies,dxiao/PPBunnies
package com.gravity.root; import java.util.List; import java.util.Random; import org.newdawn.slick.Music; import org.newdawn.slick.SlickException; import org.newdawn.slick.Sound; import com.google.common.collect.Lists; public final class GameSounds { private GameSounds() { } @SuppressWarnings("unused") private static final Music gameMusic; private static final List<Sound> jumpSounds; private static final List<Sound> slingshotSounds; private static final Music gameMusic3; private static final Random random; static { try { gameMusic = new Music("./assets/Sound/Forminas.wav"); jumpSounds = Lists.newArrayList( new Sound("./assets/Sound/jump_ha.ogg"), new Sound("./assets/Sound/jump_ho.ogg"), new Sound("./assets/Sound/jump_woo.ogg"), new Sound("./assets/Sound/jump_hup.ogg")); slingshotSounds = Lists.newArrayList( new Sound("./assets/Sound/slingshot_1.ogg"), new Sound("./assets/Sound/slingshot_2.ogg"), new Sound("./assets/Sound/slingshot_3.ogg"), new Sound("./assets/Sound/slingshot_4.ogg"), new Sound("./assets/Sound/slingshot_5.ogg")); gameMusic3 = new Music("./assets/Sound/Caketown 1.ogg"); } catch (SlickException e) { throw new RuntimeException(e); } random = new Random(); } public static void playBGM() { gameMusic3.loop(); } private static void playRandomSound(List<Sound> sounds) { sounds.get(random.nextInt(sounds.size())).play(); } public static void playJumpSound() { playRandomSound(jumpSounds); } public static void playSlingshotSound() { playRandomSound(slingshotSounds); } }
Platformer/src/com/gravity/root/GameSounds.java
package com.gravity.root; import java.util.List; import java.util.Random; import org.newdawn.slick.Music; import org.newdawn.slick.SlickException; import org.newdawn.slick.Sound; import com.google.common.collect.Lists; public final class GameSounds { private GameSounds() { } @SuppressWarnings("unused") private static final Music gameMusic; private static final List<Sound> jumpSounds; private static final List<Sound> slingshotSounds; private static final Music gameMusic3; private static final Random random; static { try { gameMusic = new Music("./assets/Sound/Forminas.wav"); jumpSounds = Lists.newArrayList( new Sound("./assets/Sound/jump_ha.wav"), new Sound("./assets/Sound/jump_ho.wav"), new Sound("./assets/Sound/jump_woo.wav"), new Sound("./assets/Sound/jump_hup.wav")); slingshotSounds = Lists.newArrayList( new Sound("./assets/Sound/slingshot_1.ogg"), new Sound("./assets/Sound/slingshot_2.ogg"), new Sound("./assets/Sound/slingshot_3.ogg"), new Sound("./assets/Sound/slingshot_4.ogg"), new Sound("./assets/Sound/slingshot_5.ogg")); gameMusic3 = new Music("./assets/Sound/Caketown 1.ogg"); } catch (SlickException e) { throw new RuntimeException(e); } random = new Random(); } public static void playBGM() { gameMusic3.loop(); } private static void playRandomSound(List<Sound> sounds) { sounds.get(random.nextInt(sounds.size())).play(); } public static void playJumpSound() { playRandomSound(jumpSounds); } public static void playSlingshotSound() { playRandomSound(slingshotSounds); } }
fixed sound file names
Platformer/src/com/gravity/root/GameSounds.java
fixed sound file names
Java
mit
63f0754790edaad60210f57f5bd76385c0579b9c
0
erickzanardo/spectre
package org.eck.spec; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import org.junit.runner.Description; import org.junit.runner.Runner; import org.junit.runner.notification.Failure; import org.junit.runner.notification.RunNotifier; @SuppressWarnings("rawtypes") public class SpectreRunner extends Runner { private List<SpectreTestEntry> specs = new ArrayList<SpectreTestEntry>(); private Class aClass; private Object instance; private Description spec; public SpectreRunner(Class aClass) { this.aClass = aClass; try { this.instance = this.aClass.newInstance(); } catch (InstantiationException | IllegalAccessException e1) { e1.printStackTrace(); } SpectreSession.instance().setSpecs(specs); SpectreSession.instance().setCurrentClass(aClass); spec = Description.createSuiteDescription(this.aClass.getName(), this.aClass.getAnnotations()); Method[] methods = aClass.getMethods(); for (Method method : methods) { if (method.getName().toLowerCase().endsWith("spec")) { Description methodSpec = Description.createTestDescription(method.getName(), method.getName()); spec.addChild(methodSpec); SpectreSession.instance().setCurrentContext(new SpecContext(methodSpec)); try { method.invoke(instance); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { e.printStackTrace(); } } } } @Override public Description getDescription() { return spec; } @Override public void run(RunNotifier runNotifier) { for (SpectreTestEntry entry : specs) { runNotifier.fireTestStarted(entry.getSpec()); try { entry.getIt().execute(); } catch (AssertionError | Exception e) { Failure failure = new Failure(entry.getSpec(), e); runNotifier.fireTestFailure(failure); } runNotifier.fireTestFinished(entry.getSpec()); } } }
src/main/java/org/eck/spec/SpectreRunner.java
package org.eck.spec; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import org.junit.ComparisonFailure; import org.junit.runner.Description; import org.junit.runner.Runner; import org.junit.runner.notification.Failure; import org.junit.runner.notification.RunNotifier; @SuppressWarnings("rawtypes") public class SpectreRunner extends Runner { private List<SpectreTestEntry> specs = new ArrayList<SpectreTestEntry>(); private Class aClass; private Object instance; private Description spec; public SpectreRunner(Class aClass) { this.aClass = aClass; try { this.instance = this.aClass.newInstance(); } catch (InstantiationException | IllegalAccessException e1) { e1.printStackTrace(); } SpectreSession.instance().setSpecs(specs); SpectreSession.instance().setCurrentClass(aClass); spec = Description.createSuiteDescription(this.aClass.getName(), this.aClass.getAnnotations()); Method[] methods = aClass.getMethods(); for (Method method : methods) { if (method.getName().toLowerCase().endsWith("spec")) { Description methodSpec = Description.createTestDescription(method.getName(), method.getName()); spec.addChild(methodSpec); SpectreSession.instance().setCurrentContext(new SpecContext(methodSpec)); try { method.invoke(instance); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { e.printStackTrace(); } } } } @Override public Description getDescription() { return spec; } @Override public void run(RunNotifier runNotifier) { for (SpectreTestEntry entry : specs) { runNotifier.fireTestStarted(entry.getSpec()); try { entry.getIt().execute(); } catch (ComparisonFailure e) { Failure failure = new Failure(entry.getSpec(), e); runNotifier.fireTestFailure(failure); } runNotifier.fireTestFinished(entry.getSpec()); } } }
Fixing runner
src/main/java/org/eck/spec/SpectreRunner.java
Fixing runner
Java
mit
1c9ad5d4907bfcf799ea6244c85718fc37e595e4
0
clarklight/nfcaes,clarklight/nfcaes
package com.clark.nfcaes.plugin; import com.nxp.nfclib.classic.IMFClassic; import com.nxp.nfclib.exceptions.PlusException; import com.nxp.nfclib.exceptions.ReaderException; import com.nxp.nfclib.exceptions.SAMException; import com.nxp.nfclib.exceptions.SmartCardException; import com.nxp.nfclib.icode.ICodeSLI; import com.nxp.nfclib.icode.IICodeSLI; import com.nxp.nfclib.icode.IICodeSLIL; import com.nxp.nfclib.icode.IICodeSLIS; import com.nxp.nfclib.icode.IICodeSLIX; import com.nxp.nfclib.icode.IICodeSLIX2; import com.nxp.nfclib.icode.IICodeSLIXL; import com.nxp.nfclib.icode.IICodeSLIXS; import com.nxp.nfclib.ndef.FormatException; import com.nxp.nfclib.ndef.NdefMessage; import com.nxp.nfclib.ndef.NdefRecord; import com.nxp.nfclib.ntag.INTag; import com.nxp.nfclib.ntag.INTag203x; import com.nxp.nfclib.ntag.INTag210; import com.nxp.nfclib.ntag.INTag213215216; import com.nxp.nfclib.ntag.INTag213F216F; import com.nxp.nfclib.ntag.INTagI2C; import com.nxp.nfclib.plus.IPlusSL1; import com.nxp.nfclib.ultralight.IUltralight; import com.nxp.nfclib.ultralight.IUltralightC; import com.nxp.nfclib.ultralight.IUltralightEV1; import com.nxp.nfclib.utils.NxpLogUtils; import com.nxp.nfclib.utils.Utilities; import com.nxp.nfcliblite.Interface.NxpNfcLibLite; import com.nxp.nfcliblite.Interface.Nxpnfcliblitecallback; import com.nxp.nfcliblite.cards.IDESFireEV1; import com.nxp.nfcliblite.cards.IPlus; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.PluginResult; import org.apache.cordova.PluginResult.Status; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import android.content.Intent; import android.nfc.NfcAdapter; import android.nfc.Tag; public class MifarePlugin extends CordovaPlugin { private NxpNfcLibLite libInstance = null; private IDESFireEV1 mDESFire; private static final String LOGTAG = "MifarePlugin"; private static final String ACTION_INIT = "init"; private static final String ACTION_AUTHENTICATE = "Authenticate"; private static final String ACTION_ENCRYPT = "Encrypt"; private static final String ACTION_DECRYPT = "Decrypt"; private static final String ACTION_PERSONALIZE = "Personalize"; private static final String ACTION_UPDATEMASTERKEY = "Updatemasterkey"; private static final String ACTION_WRITE_TAG_DATA = "writeTag"; private static final String TAG_EVENT_DETECTED = "onTagDetected"; private static final String TAG_EVENT_ERROR = "onTagError"; private static final String TAG_EVENT_ERROR_TYPE_SECURITY = "Security"; private static final String TAG_EVENT_ERROR_TYPE_IOREAD = "IORead"; private static final String TAG_EVENT_ERROR_TYPE_CARD = "Card"; static final String TAG = "SampleNxpNfcLibLite"; /** Create lib lite instance. */ private NxpNfcLibLite libInstance = null; /** Mifare DESFire instance initiated. */ private IDESFireEV1 mDESFire; /** Mifare MFClassic instance initiated. */ private IMFClassic classic; /** Mifare Ultralight instance initiated. */ private IUltralight mifareUL; /** Mifare Ultralight instance initiated. */ private IUltralightC objUlCardC; /** Mifare Ultralight EV1 instance initiated. */ private IUltralightEV1 objUlCardEV1; /** Mifare Plus instance initiated. */ private IPlus plus; /** Mifare Plus SL1 instance initiated. */ private IPlusSL1 plusSL1; /** ICode SLI instance initiated. */ private IICodeSLI iCodeSli; /** ICode SLI-L instance initiated. */ private IICodeSLIL iCodeSliL; /** ICode SLI-S instance initiated. */ private IICodeSLIS iCodeSliS; /** ICode SLI-X instance initiated. */ private IICodeSLIX iCodeSliX; /** ICode SLI-XL instance initiated. */ private IICodeSLIXL iCodeSliXL; /** ICode SLI-XS instance initiated. */ private IICodeSLIXS iCodeSliXS; /** ICode SLIX2 instance initiated. */ private IICodeSLIX2 iCodeSliX2; /** Create imageView instance. */ private ImageView mImageView = null; // private static Handler mHandler; /** Create Textview instance initiated. */ private TextView tv = null; /** * Ultralight First User Memory Page Number. */ private static final int DEFAULT_PAGENO_ULTRALIGHT = 4; /** * Variable DATA Contain a String. */ private static final String DATA = "This is the data"; /** * KEY_APP_MASTER key used for encrypt data. */ private static final String KEY_APP_MASTER = "This is my key "; /** */ private byte[] bytesKey = null; /** */ private Cipher cipher = null; /** */ private IvParameterSpec iv = null; public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { showMessage("Card Detected : " + mDESFire.getCardDetails().cardName, 'n'); if (ACTION_INIT.equals(action)) { result = init(args.getJSONObject(0), callbackContext); } else if (ACTION_WRITE_TAG_DATA.equals(action)) { result = writeTag(args.getJSONObject(0), callbackContext); } else if (ACTION_AUTHENTICATE.equals(action)) { result = authenticate(args.getJSONObject(0), callbackContext); }else if (ACTION_ENCRYPT.equals(action)) { result = encrypt(args.getJSONObject(0), callbackContext); } return true; } private void init(CallbackContext callbackContext) { Log.d(TAG, "Enabling plugin " + getIntent()); startNfc(); if (!recycledIntent()) { parseMessage(); } callbackContext.success(); } private void registerDefaultTag(CallbackContext callbackContext) { addTagFilter(); callbackContext.success(); } }
src/android/src/com/clark/nfc/plugin/test.java
package com.clark.nfc.plugin; import com.nxp.nfclib.classic.IMFClassic; import com.nxp.nfclib.exceptions.PlusException; import com.nxp.nfclib.exceptions.ReaderException; import com.nxp.nfclib.exceptions.SAMException; import com.nxp.nfclib.exceptions.SmartCardException; import com.nxp.nfclib.icode.ICodeSLI; import com.nxp.nfclib.icode.IICodeSLI; import com.nxp.nfclib.icode.IICodeSLIL; import com.nxp.nfclib.icode.IICodeSLIS; import com.nxp.nfclib.icode.IICodeSLIX; import com.nxp.nfclib.icode.IICodeSLIX2; import com.nxp.nfclib.icode.IICodeSLIXL; import com.nxp.nfclib.icode.IICodeSLIXS; import com.nxp.nfclib.ndef.FormatException; import com.nxp.nfclib.ndef.NdefMessage; import com.nxp.nfclib.ndef.NdefRecord; import com.nxp.nfclib.ntag.INTag; import com.nxp.nfclib.ntag.INTag203x; import com.nxp.nfclib.ntag.INTag210; import com.nxp.nfclib.ntag.INTag213215216; import com.nxp.nfclib.ntag.INTag213F216F; import com.nxp.nfclib.ntag.INTagI2C; import com.nxp.nfclib.plus.IPlusSL1; import com.nxp.nfclib.ultralight.IUltralight; import com.nxp.nfclib.ultralight.IUltralightC; import com.nxp.nfclib.ultralight.IUltralightEV1; import com.nxp.nfclib.utils.NxpLogUtils; import com.nxp.nfclib.utils.Utilities; import com.nxp.nfcliblite.Interface.NxpNfcLibLite; import com.nxp.nfcliblite.Interface.Nxpnfcliblitecallback; import com.nxp.nfcliblite.cards.IDESFireEV1; import com.nxp.nfcliblite.cards.IPlus; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.PluginResult; import org.apache.cordova.PluginResult.Status; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import android.content.Intent; import android.nfc.NfcAdapter; import android.nfc.Tag; public class MifarePlugin extends CordovaPlugin { private NxpNfcLibLite libInstance = null; private IDESFireEV1 mDESFire; private static final String LOGTAG = "MifarePlugin"; private static final String ACTION_INIT = "init"; private static final String ACTION_AUTHENTICATE = "Authenticate"; private static final String ACTION_ENCRYPT = "Encrypt"; private static final String ACTION_DECRYPT = "Decrypt"; private static final String ACTION_PERSONALIZE = "Personalize"; private static final String ACTION_UPDATEMASTERKEY = "Updatemasterkey"; private static final String ACTION_WRITE_TAG_DATA = "writeTag"; private static final String TAG_EVENT_DETECTED = "onTagDetected"; private static final String TAG_EVENT_ERROR = "onTagError"; private static final String TAG_EVENT_ERROR_TYPE_SECURITY = "Security"; private static final String TAG_EVENT_ERROR_TYPE_IOREAD = "IORead"; private static final String TAG_EVENT_ERROR_TYPE_CARD = "Card"; static final String TAG = "SampleNxpNfcLibLite"; /** Create lib lite instance. */ private NxpNfcLibLite libInstance = null; /** Mifare DESFire instance initiated. */ private IDESFireEV1 mDESFire; /** Mifare MFClassic instance initiated. */ private IMFClassic classic; /** Mifare Ultralight instance initiated. */ private IUltralight mifareUL; /** Mifare Ultralight instance initiated. */ private IUltralightC objUlCardC; /** Mifare Ultralight EV1 instance initiated. */ private IUltralightEV1 objUlCardEV1; /** Mifare Plus instance initiated. */ private IPlus plus; /** Mifare Plus SL1 instance initiated. */ private IPlusSL1 plusSL1; /** ICode SLI instance initiated. */ private IICodeSLI iCodeSli; /** ICode SLI-L instance initiated. */ private IICodeSLIL iCodeSliL; /** ICode SLI-S instance initiated. */ private IICodeSLIS iCodeSliS; /** ICode SLI-X instance initiated. */ private IICodeSLIX iCodeSliX; /** ICode SLI-XL instance initiated. */ private IICodeSLIXL iCodeSliXL; /** ICode SLI-XS instance initiated. */ private IICodeSLIXS iCodeSliXS; /** ICode SLIX2 instance initiated. */ private IICodeSLIX2 iCodeSliX2; /** Create imageView instance. */ private ImageView mImageView = null; // private static Handler mHandler; /** Create Textview instance initiated. */ private TextView tv = null; /** * Ultralight First User Memory Page Number. */ private static final int DEFAULT_PAGENO_ULTRALIGHT = 4; /** * Variable DATA Contain a String. */ private static final String DATA = "This is the data"; /** * KEY_APP_MASTER key used for encrypt data. */ private static final String KEY_APP_MASTER = "This is my key "; /** */ private byte[] bytesKey = null; /** */ private Cipher cipher = null; /** */ private IvParameterSpec iv = null; public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { showMessage("Card Detected : " + mDESFire.getCardDetails().cardName, 'n'); if (ACTION_INIT.equals(action)) { result = init(args.getJSONObject(0), callbackContext); } else if (ACTION_WRITE_TAG_DATA.equals(action)) { result = writeTag(args.getJSONObject(0), callbackContext); } else if (ACTION_AUTHENTICATE.equals(action)) { result = authenticate(args.getJSONObject(0), callbackContext); }else if (ACTION_ENCRYPT.equals(action)) { result = encrypt(args.getJSONObject(0), callbackContext); } return true; } private void init(CallbackContext callbackContext) { Log.d(TAG, "Enabling plugin " + getIntent()); startNfc(); if (!recycledIntent()) { parseMessage(); } callbackContext.success(); } private void registerDefaultTag(CallbackContext callbackContext) { addTagFilter(); callbackContext.success(); } }
Update test.java
src/android/src/com/clark/nfc/plugin/test.java
Update test.java
Java
cc0-1.0
5e0fb8b001655767e3e0005db223ce2fb149e97a
0
tommyettinger/Finnegan
package james.joyce; import java.io.Serializable; import java.text.Normalizer; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * A text generator for producing sentences and/or words in nonsense languages that fit a theme. This does not use an * existing word list as a basis for its output, so it may or may not produce existing words occasionally, but you can * safely assume it won't generate a meaningful sentence except in the absolute unlikeliest of cases. The name comes * from the novel Finnegan's Wake by James Joyce, which employed vaguely similar creative manipulation of language. * <br> * "Thaw! The last word in stolentelling!" * <br> * -- James Joyce, Finnegan's Wake * <br> * "bababadalgharaghtakamminarronnkonnbronntonnerronntuonnthunntrovarrhounawnskawntoohoohoordenenthurnuk!" * <br> * -- James Joyce, Finnegan's Wake * <br> * CC0 Licensed, originally by Tommy Ettinger. This class is meant to be copied into your own source code, not included * as a library. There is absolutely no need to attribute me if you use this, and you can change it without obstacle. */ public class Finnegan implements Serializable { public static class RNG implements Serializable { private static final long serialVersionUID = 4378460257281186370L; /** * 2 raised to the 53, - 1. */ private static final long DOUBLE_MASK = (1L << 53) - 1; /** * 2 raised to the -53. */ private static final double NORM_53 = 1. / (1L << 53); public long state; public RNG() { state = Double.doubleToLongBits(Math.random()); } public RNG(long seed) { state = seed; } /** * Can return any long, positive or negative, of any size permissible in a 64-bit signed integer. * * @return any long, all 64 bits are random */ public long nextLong() { long z = (state += 0x9E3779B97F4A7C15L); z = (z ^ (z >>> 30)) * 0xBF58476D1CE4E5B9L; z = (z ^ (z >>> 27)) * 0x94D049BB133111EBL; return z ^ (z >>> 31); } /** * Can return any int, positive or negative, of any size permissible in a 32-bit signed integer. * * @return any int, all 32 bits are random */ public int nextInt() { return (int) nextLong(); } /** * Exclusive on the upper bound n. The lower bound is 0. * * @param n the upper bound; should be positive * @return a random int less than n and at least equal to 0 */ public int nextInt(final int n) { if (n <= 0) throw new IllegalArgumentException(); final int bits = nextInt() >>> 1; return bits % n; } /** * Inclusive lower, exclusive upper. * * @param lower the lower bound, inclusive, can be positive or negative * @param upper the upper bound, exclusive, should be positive, must be greater than lower * @return a random int at least equal to lower and less than upper */ public int nextInt(final int lower, final int upper) { if (upper - lower <= 0) throw new IllegalArgumentException(); return lower + nextInt(upper - lower); } /** * Exclusive on the upper bound n. The lower bound is 0. * * @param n the upper bound; should be positive * @return a random long less than n */ public long nextLong(final long n) { if (n <= 0) throw new IllegalArgumentException(); //for(;;) { final long bits = nextLong() >>> 1; return bits % n; //long value = bits % n; //value = (value < 0) ? -value : value; //if ( bits - value + ( n - 1 ) >= 0 ) return value; //} } /** * Inclusive lower, exclusive upper. * * @param lower the lower bound, inclusive, can be positive or negative * @param upper the upper bound, exclusive, should be positive, must be greater than lower * @return a random long at least equal to lower and less than upper */ public long nextLong(final long lower, final long upper) { if (upper - lower <= 0) throw new IllegalArgumentException(); return lower + nextLong(upper - lower); } /** * Gets a uniform random double in the range [0.0,1.0) * * @return a random double at least equal to 0.0 and less than 1.0 */ public double nextDouble() { return (nextLong() & DOUBLE_MASK) * NORM_53; } /** * Gets a uniform random double in the range [0.0,outer) given a positive parameter outer. If outer * is negative, it will be the (exclusive) lower bound and 0.0 will be the (inclusive) upper bound. * * @param outer the exclusive outer bound, can be negative * @return a random double between 0.0 (inclusive) and outer (exclusive) */ public double nextDouble(final double outer) { return nextDouble() * outer; } public <T> T getRandomElement(T[] array) { if (array.length < 1) { return null; } return array[nextInt(array.length)]; } /** * Shuffle an array using the Fisher-Yates algorithm. * * @param elements an array of T; will not be modified * @param <T> can be any non-primitive type. * @return a shuffled copy of elements */ public <T> T[] shuffle(T[] elements) { T[] array = elements.clone(); int n = array.length; for (int i = 0; i < n; i++) { int r = i + nextInt(n - i); T t = array[r]; array[r] = array[i]; array[i] = t; } return array; } /** * Shuffle a {@link List} using the Fisher-Yates algorithm. * @param elements a List of T; will not be modified * @param <T> can be any non-primitive type. * @return a shuffled ArrayList containing the whole of elements in pseudo-random order. */ public <T> ArrayList<T> shuffle(List<T> elements) { ArrayList<T> al = new ArrayList<T>(elements); int n = al.size(); for (int i = 0; i < n; i++) { Collections.swap(al, i + nextInt(n - i), i); } return al; } /** * Gets a random portion of a List and returns it as a new List. Will only use a given position in the given * List at most once; does this by shuffling a copy of the List and getting a section of it. * @param data a List of T; will not be modified. * @param count the non-negative number of elements to randomly take from data * @param <T> can be any non-primitive type * @return a List of T that has length equal to the smaller of count or data.length */ public <T> List<T> randomPortion(List<T> data, int count) { return shuffle(data).subList(0, Math.min(count, data.size())); } public long getState() { return state; } public void setState(long state) { this.state = state; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; RNG rng = (RNG) o; return state == rng.state; } @Override public int hashCode() { return (int) (state ^ (state >>> 32)); } @Override public String toString() { return "RNG{" + "state=" + state + '}'; } } private static final long serialVersionUID = -2578460257281186352L; public final String[] openingVowels, midVowels, openingConsonants, midConsonants, closingConsonants, vowelSplitters, closingSyllables; public boolean clean; public final LinkedHashMap<Integer, Double> syllableFrequencies; protected double totalSyllableFrequency = 0.0; public final double vowelStartFrequency, vowelEndFrequency, vowelSplitFrequency, syllableEndFrequency; protected final Pattern[] sanityChecks; public ArrayList<Modifier> modifiers; protected static final Pattern repeats = Pattern.compile("(.)\\1+"), diacritics = Pattern.compile("[\\u0300-\\u036F\\u1DC0-\\u1DFF]+"); public static final Pattern[] vulgarChecks = new Pattern[] { Pattern.compile("[SsξCcсςС][hнН].*[dtтτТΤf]"), Pattern.compile("([PpрρРΡ][hнН])|[KkкκКΚFfDdCcсςС].{1,4}[KkкκКΚCcсςСxхжχХЖΧ]"), // lots of these end in a 'k' sound, huh Pattern.compile("[BbъыбвβЪЫБВΒ]..?.?[cсςС][hнН]"), Pattern.compile("[WwшщψШЩHhнН]..?[rяЯ]"), Pattern.compile("[TtтτТΤ]..?[tтτТΤ]"), Pattern.compile("([PpрρРΡ][hнН])|[Ff]..?[rяЯ][tтτТΤ]"), Pattern.compile("([Ssξ][hнН])|[j][iτιΙ].?[sξzΖ]"), Pattern.compile("[AaаαАΑΛ][NnийИЙΝ]..?[SsξlιζzΖ]"), Pattern.compile("[AaаαАΑΛ][sξ][sξ]"), Pattern.compile(".[uμυν][hнН]?[nийИЙΝ]+[tтτТΤ]"), Pattern.compile("[NnFf]..?g"), // might as well remove two possible slurs with one check Pattern.compile("[PpрρРΡ][eеёзξεЕЁЗΞΕΣioоюσοОЮΟuμυν][eеёзξεЕЁЗΞΕΣoоюσοОЮΟs]"), // the grab bag of juvenile words Pattern.compile("[MmмМΜ]..?[rяЯ].?d"), // should pick up the #1 obscenity from Spanish and French Pattern.compile("[Gg][hнН]?[aаαАΑΛeеёзξεЕЁЗΞΕΣ][yуλγУΥeеёзξεЕЁЗΞΕΣ]") // could be inappropriate for random text }, englishSanityChecks = new Pattern[] { Pattern.compile("[AEIOUaeiou]{3}"), Pattern.compile("(\\w)\\1\\1"), Pattern.compile("(.)\\1(.)\\2"), Pattern.compile("[Aa][ae]"), Pattern.compile("[Uu][umlkj]"), Pattern.compile("[Ii][iyqkhrl]"), Pattern.compile("[Oo][c]"), Pattern.compile("[Yy][aeiou]{2}"), Pattern.compile("[Rr][aeiouy]+[xrhp]"), Pattern.compile("[Qq]u[yu]"), Pattern.compile("[^oai]uch"), Pattern.compile("[^tcsz]hh"), Pattern.compile("[Hh][tcszi]h"), Pattern.compile("[Tt]t[^aeiouy]{2}"), Pattern.compile("[IYiy]h[^aeiouy ]"), Pattern.compile("[szSZrlRL][^aeiou][rlsz]"), Pattern.compile("[UIuiYy][wy]"), Pattern.compile("^[UIui][ae]"), Pattern.compile("q$") }, japaneseSanityChecks = new Pattern[] { Pattern.compile("[AEIOUaeiou]{3}"), Pattern.compile("(\\w)\\1\\1"), Pattern.compile("[Tt]s[^u]"), Pattern.compile("[Ff][^u]"), Pattern.compile("[Yy][^auo]"), Pattern.compile("[Tt][ui]"), Pattern.compile("[SsZzDd]i"), Pattern.compile("[Hh]u"), }; public RNG rng; public static final char[][] accentedVowels = new char[][]{ new char[]{ 'à', 'á', 'â', 'ã', 'ä', 'å', 'æ', 'ā', 'ă', 'ą', 'ǻ', 'ǽ' }, new char[]{ 'è', 'é', 'ê', 'ë', 'ē', 'ĕ', 'ė', 'ę', 'ě' }, new char[]{ 'ì', 'í', 'î', 'ï', 'ĩ', 'ī', 'ĭ', 'į', 'ı', }, new char[]{ 'ò', 'ó', 'ô', 'õ', 'ö', 'ø', 'ō', 'ŏ', 'ő', 'œ', 'ǿ' }, new char[]{ 'ù', 'ú', 'û', 'ü', 'ũ', 'ū', 'ŭ', 'ů', 'ű', 'ų' } }, accentedConsonants = new char[][] { new char[]{ 'b' }, new char[]{ 'c', 'ç', 'ć', 'ĉ', 'ċ', 'č', }, new char[]{ 'd', 'þ', 'ð', 'ď', 'đ', }, new char[]{ 'f' }, new char[]{ 'g', 'ĝ', 'ğ', 'ġ', 'ģ', }, new char[]{ 'h', 'ĥ', 'ħ', }, new char[]{ 'j', 'ĵ', 'ȷ', }, new char[]{ 'k', 'ķ', }, new char[]{ 'l', 'ĺ', 'ļ', 'ľ', 'ŀ', 'ł', }, new char[]{ 'm', }, new char[]{ 'n', 'ñ', 'ń', 'ņ', 'ň', 'ŋ', }, new char[]{ 'p', }, new char[]{ 'q', }, new char[]{ 'r', 'ŕ', 'ŗ', 'ř', }, new char[]{ 's', 'ś', 'ŝ', 'ş', 'š', 'ș', }, new char[]{ 't', 'ţ', 'ť', 'ț', }, new char[]{ 'v', }, new char[]{ 'w', 'ŵ', 'ẁ', 'ẃ', 'ẅ', }, new char[]{ 'x', }, new char[]{ 'y', 'ý', 'ÿ', 'ŷ', 'ỳ', }, new char[]{ 'z', 'ź', 'ż', 'ž', }, }; /** * Removes accented characters from a string; if the "base" characters are non-English anyway then the result won't * be an ASCII string, but otherwise it probably will be. * <br> * Credit to user hashable from http://stackoverflow.com/a/1215117 * * @param str a string that may contain accented characters * @return a string with all accented characters replaced with their (possibly ASCII) counterparts */ public String removeAccents(CharSequence str) { String alteredString = Normalizer.normalize(str, Normalizer.Form.NFD); alteredString = diacritics.matcher(alteredString).replaceAll("") .replace('æ', 'a') .replace('œ', 'o') .replace('ø', 'o') .replace('Æ', 'A') .replace('Œ', 'O') .replace('Ø', 'O'); return alteredString; } /** * Ia! Ia! Cthulhu Rl'yeh ftaghn! Useful for generating cultist ramblings or unreadable occult texts. * <br> * Zvrugg pialuk, ya'as irlemrugle'eith iposh hmo-es nyeighi, glikreirk shaivro'ei! */ public static final Finnegan LOVECRAFT = new Finnegan( new String[]{"a", "i", "o", "e", "u", "a", "i", "o", "e", "u", "ia", "ai", "aa", "ei"}, new String[]{}, new String[]{"s", "t", "k", "n", "y", "p", "k", "l", "g", "gl", "th", "sh", "ny", "ft", "hm", "zvr", "cth"}, new String[]{"h", "gl", "gr", "nd", "mr", "vr", "kr"}, new String[]{"l", "p", "s", "t", "n", "k", "g", "x", "rl", "th", "gg", "gh", "ts", "lt", "rk", "kh", "sh", "ng", "shk"}, new String[]{"aghn", "ulhu", "urath", "oigor", "alos", "'yeh", "achtal", "urath", "ikhet", "adzek"}, new String[]{"'", "-"}, new int[]{1, 2, 3}, new double[]{6, 7, 2}, 0.4, 0.31, 0.07, 0.04, null, true); /** * Imitation English; may seem closer to Dutch in some generated text, and is not exactly the best imitation. * Should seem pretty fake to many readers; does not filter out dictionary words but does perform basic vulgarity * filtering. If you want to avoid generating other words, you can subclass Finnegan and modify word() . * <br> * Mont tiste frot; mousation hauddes? * Lily wrely stiebes; flarrousseal gapestist. */ public static final Finnegan ENGLISH = new Finnegan( new String[]{ "a", "a", "a", "a", "o", "o", "o", "e", "e", "e", "e", "e", "i", "i", "i", "i", "u", "a", "a", "a", "a", "o", "o", "o", "e", "e", "e", "e", "e", "i", "i", "i", "i", "u", "a", "a", "a", "o", "o", "e", "e", "e", "i", "i", "i", "u", "a", "a", "a", "o", "o", "e", "e", "e", "i", "i", "i", "u", "au", "ai", "ai", "ou", "ea", "ie", "io", "ei", }, new String[]{"u", "u", "oa", "oo", "oo", "oo", "ee", "ee", "ee", "ee",}, new String[]{ "b", "bl", "br", "c", "cl", "cr", "ch", "d", "dr", "f", "fl", "fr", "g", "gl", "gr", "h", "j", "k", "l", "m", "n", "p", "pl", "pr", "qu", "r", "s", "sh", "sk", "st", "sp", "sl", "sm", "sn", "t", "tr", "th", "thr", "v", "w", "y", "z", "b", "bl", "br", "c", "cl", "cr", "ch", "d", "dr", "f", "fl", "fr", "g", "gr", "h", "j", "k", "l", "m", "n", "p", "pl", "pr", "r", "s", "sh", "st", "sp", "sl", "t", "tr", "th", "w", "y", "b", "br", "c", "ch", "d", "dr", "f", "g", "h", "j", "l", "m", "n", "p", "r", "s", "sh", "st", "sl", "t", "tr", "th", "b", "d", "f", "g", "h", "l", "m", "n", "p", "r", "s", "sh", "t", "th", "b", "d", "f", "g", "h", "l", "m", "n", "p", "r", "s", "sh", "t", "th", "r", "s", "t", "l", "n", "str", "spr", "spl", "wr", "kn", "kn", "gn", }, new String[]{"x", "cst", "bs", "ff", "lg", "g", "gs", "ll", "ltr", "mb", "mn", "mm", "ng", "ng", "ngl", "nt", "ns", "nn", "ps", "mbl", "mpr", "pp", "ppl", "ppr", "rr", "rr", "rr", "rl", "rtn", "ngr", "ss", "sc", "rst", "tt", "tt", "ts", "ltr", "zz" }, new String[]{"b", "rb", "bb", "c", "rc", "ld", "d", "ds", "dd", "f", "ff", "lf", "rf", "rg", "gs", "ch", "lch", "rch", "tch", "ck", "ck", "lk", "rk", "l", "ll", "lm", "m", "rm", "mp", "n", "nk", "nch", "nd", "ng", "ng", "nt", "ns", "lp", "rp", "p", "r", "rn", "rts", "s", "s", "s", "s", "ss", "ss", "st", "ls", "t", "t", "ts", "w", "wn", "x", "ly", "lly", "z", "b", "c", "d", "f", "g", "k", "l", "m", "n", "p", "r", "s", "t", "w", }, new String[]{"ate", "ite", "ism", "ist", "er", "er", "er", "ed", "ed", "ed", "es", "es", "ied", "y", "y", "y", "y", "ate", "ite", "ism", "ist", "er", "er", "er", "ed", "ed", "ed", "es", "es", "ied", "y", "y", "y", "y", "ate", "ite", "ism", "ist", "er", "er", "er", "ed", "ed", "ed", "es", "es", "ied", "y", "y", "y", "y", "ay", "ay", "ey", "oy", "ay", "ay", "ey", "oy", "ough", "aught", "ant", "ont", "oe", "ance", "ell", "eal", "oa", "urt", "ut", "iom", "ion", "ion", "ision", "ation", "ation", "ition", "ough", "aught", "ant", "ont", "oe", "ance", "ell", "eal", "oa", "urt", "ut", "iom", "ion", "ion", "ision", "ation", "ation", "ition", "ily", "ily", "ily", "adly", "owly", "oorly", "ardly", "iedly", }, new String[]{}, new int[]{1, 2, 3, 4}, new double[]{7, 8, 4, 1}, 0.22, 0.1, 0.0, 0.25, englishSanityChecks, true); /** * Imitation ancient Greek, romanized to use the Latin alphabet. Likely to seem pretty fake to many readers. * <br> * Psuilas alor; aipeomarta le liaspa... */ public static final Finnegan GREEK_ROMANIZED = new Finnegan( new String[]{"a", "a", "a", "o", "o", "o", "e", "e", "i", "i", "i", "au", "ai", "ai", "oi", "oi", "ia", "io", "ou", "ou", "eo", "ei"}, new String[]{"ui", "ei"}, new String[]{"rh", "s", "z", "t", "t", "k", "ch", "n", "th", "kth", "m", "p", "ps", "b", "l", "kr", "g", "phth"}, new String[]{"lph", "pl", "l", "l", "kr", "nch", "nx", "ps"}, new String[]{"s", "p", "t", "ch", "n", "m", "s", "p", "t", "ch", "n", "m", "b", "g", "st", "rst", "rt", "sp", "rk", "ph", "x", "z", "nk", "ng", "th"}, new String[]{"os", "os", "is", "us", "um", "eum", "ium", "iam", "us", "um", "es", "anes", "eros", "or", "ophon", "on", "otron"}, new String[]{}, new int[]{1, 2, 3}, new double[]{5, 7, 4}, 0.45, 0.45, 0.0, 0.3, null, true); /** * Imitation ancient Greek, using the original Greek alphabet. People may try to translate it and get gibberish. * Make sure the font you use to render this supports the Greek alphabet! In the GDX display module, the "smooth" * fonts support all the Greek you need for this. * <br> * Ψυιλασ αλορ; αιπεομαρτα λε λιασπα... */ public static final Finnegan GREEK_AUTHENTIC = new Finnegan( new String[]{"α", "α", "α", "ο", "ο", "ο", "ε", "ε", "ι", "ι", "ι", "αυ", "αι", "αι", "οι", "οι", "ια", "ιο", "ου", "ου", "εο", "ει"}, new String[]{"υι", "ει"}, new String[]{"ρ", "σ", "ζ", "τ", "τ", "κ", "χ", "ν", "θ", "κθ", "μ", "π", "ψ", "β", "λ", "κρ", "γ", "φθ"}, new String[]{"λφ", "πλ", "λ", "λ", "κρ", "γχ", "γξ", "ψ"}, new String[]{"σ", "π", "τ", "χ", "ν", "μ", "σ", "π", "τ", "χ", "ν", "μ", "β", "γ", "στ", "ρστ", "ρτ", "σπ", "ρκ", "φ", "ξ", "ζ", "γκ", "γγ", "θ"}, new String[]{"ος", "ος", "ις", "υς", "υμ", "ευμ", "ιυμ", "ιαμ", "υς", "υμ", "ες", "ανες", "ερος", "ορ", "οφον", "ον", "οτρον"}, new String[]{}, new int[]{1, 2, 3}, new double[]{5, 7, 4}, 0.45, 0.45, 0.0, 0.3, null, true); /** * Imitation modern French, using (too many of) the accented vowels that are present in the language. Translating it * will produce gibberish if it produces anything at all. In the GDX display module, the "smooth" and "unicode" * fonts support all the accented characters you need for this. * <br><br> * Fa veau, ja ri avé re orçe jai braï aisté. */ public static final Finnegan FRENCH = new Finnegan( new String[]{"a", "a", "a", "e", "e", "e", "i", "i", "o", "u", "a", "a", "a", "e", "e", "e", "i", "i", "o", "a", "a", "a", "e", "e", "e", "i", "i", "o", "u", "a", "a", "a", "e", "e", "e", "i", "i", "o", "a", "a", "e", "e", "i", "o", "a", "a", "a", "e", "e", "e", "i", "i", "o", "ai", "oi", "oui", "au", "œu", "ou" }, new String[]{ "ai", "aie", "aou", "eau", "oi", "oui", "oie", "eu", "eu", "à", "â", "ai", "aî", "aï", "aie", "aou", "aoû", "au", "ay", "e", "é", "ée", "è", "ê", "eau", "ei", "eî", "eu", "eû", "i", "î", "ï", "o", "ô", "oe", "oê", "oë", "œu", "oi", "oie", "oï", "ou", "oû", "oy", "u", "û", "ue", "a", "a", "a", "e", "e", "e", "i", "i", "o", "u", "a", "a", "a", "e", "e", "e", "i", "i", "o", "a", "a", "e", "e", "i", "o", "a", "a", "a", "e", "e", "e", "i", "i", "o", }, new String[]{"tr", "ch", "m", "b", "b", "br", "j", "j", "j", "j", "g", "t", "t", "t", "c", "d", "f", "f", "h", "n", "l", "l", "s", "s", "s", "r", "r", "r", "v", "v", "p", "pl", "pr", "bl", "br", "dr", "gl", "gr"}, new String[]{"cqu", "gu", "qu", "rqu", "nt", "ng", "ngu", "mb", "ll", "nd", "ndr", "nct", "st", "xt", "mbr", "pl", "g", "gg", "ggr", "gl", "m", "m", "mm", "v", "v", "f", "f", "f", "ff", "b", "b", "bb", "d", "d", "dd", "s", "s", "s", "ss", "ss", "ss", "cl", "cr", "ng", "ç", "ç", "rç"}, new String[]{}, new String[]{"e", "e", "e", "e", "e", "é", "é", "er", "er", "er", "er", "er", "es", "es", "es", "es", "es", "es", "e", "e", "e", "e", "e", "é", "é", "er", "er", "er", "er", "er", "er", "es", "es", "es", "es", "es", "e", "e", "e", "e", "e", "é", "é", "é", "er", "er", "er", "er", "er", "es", "es", "es", "es", "es", "ent", "em", "en", "en", "aim", "ain", "an", "oin", "ien", "iere", "ors", "anse", "ombs", "ommes", "ancs", "ends", "œufs", "erfs", "ongs", "aps", "ats", "ives", "ui", "illes", "aen", "aon", "am", "an", "eun", "ein", "age", "age", "uile", "uin", "um", "un", "un", "un", "aille", "ouille", "eille", "ille", "eur", "it", "ot", "oi", "oi", "oi", "aire", "om", "on", "on", "im", "in", "in", "ien", "ien", "ion", "il", "eil", "oin", "oint", "iguïté", "ience", "incte", "ang", "ong", "acré", "eau", "ouche", "oux", "oux", "ect", "ecri", "agne", "uer", "aix", "eth", "ut", "ant", "anc", "anc", "anche", "ioche", "eaux", "ive", "eur", "ancois", "ecois"}, new String[]{}, new int[]{1, 2, 3}, new double[]{18, 7, 2}, 0.35, 1.0, 0.0, 0.55, null, true); /** * Imitation modern Russian, romanized to use the Latin alphabet. Likely to seem pretty fake to many readers. * <br> * Zhydotuf ruts pitsas, gogutiar shyskuchebab - gichapofeglor giunuz ieskaziuzhin. */ public static final Finnegan RUSSIAN_ROMANIZED = new Finnegan( new String[]{"a", "e", "e", "i", "i", "o", "u", "ie", "y", "e", "iu", "ia", "y", "a", "a", "o", "u"}, new String[]{}, new String[]{"b", "v", "g", "d", "k", "l", "p", "r", "s", "t", "f", "kh", "ts", "b", "v", "g", "d", "k", "l", "p", "r", "s", "t", "f", "kh", "ts", "b", "v", "g", "d", "k", "l", "p", "r", "s", "t", "f", "zh", "m", "n", "z", "ch", "sh", "shch", "br", "sk", "tr", "bl", "gl", "kr", "gr"}, new String[]{"bl", "br", "pl", "dzh", "tr", "gl", "gr", "kr"}, new String[]{"b", "v", "g", "d", "zh", "z", "k", "l", "m", "n", "p", "r", "s", "t", "f", "kh", "ts", "ch", "sh", "v", "f", "sk", "sk", "sk", "s", "b", "d", "d", "n", "r", "r"}, new String[]{"odka", "odna", "usk", "ask", "usky", "ad", "ar", "ovich", "ev", "ov", "of", "agda", "etsky", "ich", "on", "akh", "iev", "ian"}, new String[]{}, new int[]{1, 2, 3, 4, 5, 6}, new double[]{4, 5, 6, 5, 3, 1}, 0.1, 0.2, 0.0, 0.12, englishSanityChecks, true); /** * Imitation modern Russian, using the authentic Cyrillic alphabet used in Russia and other countries. * Make sure the font you use to render this supports the Cyrillic alphabet! * In the GDX display module, the "smooth" fonts support all the Cyrillic alphabet you need for this. * <br> * Жыдотуф руц пйцас, гогутяр шыскучэбаб - гйчапофёглор гюнуз ъсказюжин. */ public static final Finnegan RUSSIAN_AUTHENTIC = new Finnegan( new String[]{"а", "е", "ё", "и", "й", "о", "у", "ъ", "ы", "э", "ю", "я", "ы", "а", "а", "о", "у"}, new String[]{}, new String[]{"б", "в", "г", "д", "к", "л", "п", "р", "с", "т", "ф", "х", "ц", "б", "в", "г", "д", "к", "л", "п", "р", "с", "т", "ф", "х", "ц", "б", "в", "г", "д", "к", "л", "п", "р", "с", "т", "ф", "ж", "м", "н", "з", "ч", "ш", "щ", "бр", "ск", "тр", "бл", "гл", "кр", "гр"}, new String[]{"бл", "бр", "пл", "дж", "тр", "гл", "гр", "кр"}, new String[]{"б", "в", "г", "д", "ж", "з", "к", "л", "м", "н", "п", "р", "с", "т", "ф", "х", "ц", "ч", "ш", "в", "ф", "ск", "ск", "ск", "с", "б", "д", "д", "н", "р", "р"}, new String[]{"одка", "одна", "уск", "аск", "ускы", "ад", "ар", "овйч", "ев", "ов", "оф", "агда", "ёцкы", "йч", "он", "ах", "ъв", "ян"}, new String[]{}, new int[]{1, 2, 3, 4, 5, 6}, new double[]{4, 5, 6, 5, 3, 1}, 0.1, 0.2, 0.0, 0.12, null, true); /** * Imitation Japanese, romanized to use the Latin alphabet. Likely to seem pretty fake to many readers. Excellent * when mixed, but keep in mind the sanity checks that are used to make this generate viable words in Japanese also * can carry over to a mixed language if JAPANESE_ROMANIZED is mixed with a Finnegan that does not have sanity * checks, like any non-Latin-script ones. If this is the parameter to mix() called on a Finnegan like FRENCH or * RUSSIAN_ROMANIZED (but not RUSSIAN_AUTHENTIC), the sanity check carryover probably won't happen, and the word * structure won't have the mostly-syllable-based aesthetic that JAPANESE_ROMANIZED generates. * <br> * Narurehyounan nikase keho... */ public static final Finnegan JAPANESE_ROMANIZED = new Finnegan( new String[]{"a", "a", "a", "a", "e", "e", "i", "i", "i", "i", "o", "o", "o", "u", "ou", "u", "ai", "ai"}, new String[]{}, new String[]{"k", "ky", "s", "sh", "t", "ts", "ch", "n", "ny", "h", "f", "hy", "m", "my", "y", "r", "ry", "g", "gy", "z", "j", "d", "b", "by", "p", "py", "k", "t", "n", "s", "k", "t", "d", "s", "sh", "sh", "g", "r", "b", "k", "t", "n", "s", "k", "t", "b", "s", "sh", "sh", "g", "r", "b", "k", "t", "n", "s", "k", "t", "z", "s", "sh", "sh", "ch", "ry", "ts" }, new String[]{"k", "ky", "s", "sh", "t", "ts", "ch", "n", "ny", "h", "f", "hy", "m", "my", "y", "r", "ry", "g", "gy", "z", "j", "d", "b", "by", "p", "py", "k", "t", "d", "s", "k", "t", "d", "s", "sh", "sh", "y", "j", "p", "r", "d", "k", "t", "b", "s", "k", "t", "b", "s", "sh", "sh", "y", "j", "p", "r", "d", "k", "t", "z", "s", "f", "g", "z", "b", "d", "ts", "nn", "nn", "nn", "nd", "nz", "mm", "kk", "kk", "tt", "ss", "ssh", "tch"}, new String[]{"n"}, new String[]{}, new String[]{}, new int[]{1, 2, 3, 4, 5}, new double[]{5, 4, 5, 4, 3}, 0.3, 0.9, 0.0, 0.0, japaneseSanityChecks, true); /** * Swahili is one of the more commonly-spoken languages in sub-Saharan Africa, and serves mainly as a shared language * that is often learned after becoming fluent in one of many other (vaguely-similar) languages of the area. An * example sentence in Swahili, that this might try to imitate aesthetically, is "Mtoto mdogo amekisoma," meaning * "The small child reads it" (where it is a book). A notable language feature used here is the redoubling of words, * which is used in Swahili to emphasize or alter the meaning of the doubled word; here, it always repeats exactly * and can't make minor changes like a real language might. This generates things like "gata-gata", "hapi-hapi", and * "mimamzu-mimamzu", always separating with a hyphen here. * <br> * As an aside, please try to avoid the ugly stereotypes that fantasy media often assigns to speakers of African-like * languages when using this or any of the generators. Many fantasy tropes come from older literature written with * major cultural biases, and real-world cultural elements can be much more interesting to players than yet another * depiction of a "jungle savage" with stereotypical traits. Consider drawing from existing lists of real-world * technological discoveries, like https://en.wikipedia.org/wiki/History_of_science_and_technology_in_Africa , for * inspiration when world-building; though some groups may not have developed agriculture by early medieval times, * their neighbors may be working iron and studying astronomy just a short distance away. * <br> * Kondueyu; ma mpiyamdabota mise-mise nizakwaja alamsa amja, homa nkajupomba. */ public static final Finnegan SWAHILI = new Finnegan( new String[]{"a", "i", "o", "e", "u", "a", "a", "i", "o", "o", "e", "u", "a", "a", "i", "o", "o", "u", "a", "a", "i", "i", "o", "a","a","a","a","a", "a", "i", "o", "e", "u", "a", "a", "i", "o", "o", "e", "u", "a", "a", "i", "o", "o", "u", "a", "a", "i", "i", "o", "a","a","a","a","a", "aa", "aa", "ue", "uo", "ii", "ea"}, new String[]{}, new String[]{ "b", "h", "j", "l", "s", "y", "m", "n", "b", "ch", "h", "j", "l", "s", "y", "z", "m", "n", "b", "ch", "f", "g", "h", "j", "k", "l", "p", "s", "y", "z", "m", "n", "b", "ch", "d", "f", "g", "h", "j", "k", "l", "p", "s", "t", "y", "z", "m", "n", "kw", "b", "ch", "d", "f", "g", "h", "j", "k", "l", "p", "s", "t", "v", "w", "y", "z", "m", "n", "kw", "b", "h", "j", "l", "s", "y", "m", "n", "b", "ch", "h", "j", "l", "s", "y", "z", "m", "n", "b", "ch", "f", "g", "h", "j", "k", "l", "p", "s", "y", "z", "m", "n", "b", "ch", "d", "f", "g", "h", "j", "k", "l", "p", "s", "t", "y", "z", "m", "n", "kw", "b", "ch", "d", "f", "g", "h", "j", "k", "l", "p", "s", "t", "v", "w", "y", "z", "m", "n", "kw", "b", "h", "j", "l", "s", "y", "m", "n", "b", "ch", "h", "j", "l", "s", "y", "z", "m", "n", "b", "ch", "f", "g", "h", "j", "k", "l", "p", "s", "y", "z", "m", "n", "b", "ch", "d", "f", "g", "h", "j", "k", "l", "p", "s", "t", "y", "z", "m", "n", "kw", "b", "ch", "d", "f", "g", "h", "j", "k", "l", "p", "s", "t", "v", "w", "y", "z", "m", "n", "kw", "b", "h", "j", "l", "s", "y", "m", "n", "b", "ch", "h", "j", "l", "s", "y", "z", "m", "n", "b", "ch", "f", "g", "h", "j", "k", "l", "p", "s", "y", "z", "m", "n", "b", "ch", "d", "f", "g", "h", "j", "k", "l", "p", "s", "t", "y", "z", "m", "n", "kw", "b", "ch", "d", "f", "g", "h", "j", "k", "l", "p", "s", "t", "v", "w", "y", "z", "m", "n", "kw", "nb", "nj", "ns", "nz", "nb", "nch", "nj", "ns", "ny", "nz", "nb", "nch", "nf", "ng", "nj", "nk", "np", "ns", "nz", "nb", "nch", "nd", "nf", "ng", "nj", "nk", "np", "ns", "nt", "nz", "nb", "nch", "nd", "nf", "ng", "nj", "nk", "np", "ns", "nt", "nv", "nw", "nz", "mb", "ms", "my", "mz", "mb", "mch","ms", "my", "mz", "mb", "mch", "mk", "mp", "ms", "my", "mz", "mb", "mch", "md", "mk", "mp", "ms", "mt", "my", "mz", "mb", "mch", "md", "mf", "mg", "mj", "mk", "mp", "ms", "mt", "mv", "mw", "my", "mz", "sh", "sh", "sh", "ny", "kw", "dh", "th", "sh", "ny", "dh", "th", "sh", "gh", "r", "ny", "dh", "th", "sh", "gh", "r", "ny", }, new String[]{ "b", "h", "j", "l", "s", "y", "m", "n", "b", "ch", "h", "j", "l", "s", "y", "z", "m", "n", "b", "ch", "f", "g", "h", "j", "k", "l", "p", "s", "y", "z", "m", "n", "b", "ch", "d", "f", "g", "h", "j", "k", "l", "p", "s", "t", "y", "z", "m", "n", "kw", "b", "ch", "d", "f", "g", "h", "j", "k", "l", "p", "s", "t", "v", "w", "y", "z", "m", "n", "kw", "b", "h", "j", "l", "s", "y", "m", "n", "b", "ch", "h", "j", "l", "s", "y", "z", "m", "n", "b", "ch", "f", "g", "h", "j", "k", "l", "p", "s", "y", "z", "m", "n", "b", "ch", "d", "f", "g", "h", "j", "k", "l", "p", "s", "t", "y", "z", "m", "n", "kw", "b", "ch", "d", "f", "g", "h", "j", "k", "l", "p", "s", "t", "v", "w", "y", "z", "m", "n", "kw", "b", "h", "j", "l", "s", "y", "m", "n", "b", "ch", "h", "j", "l", "s", "y", "z", "m", "n", "b", "ch", "f", "g", "h", "j", "k", "l", "p", "s", "y", "z", "m", "n", "b", "ch", "d", "f", "g", "h", "j", "k", "l", "p", "s", "t", "y", "z", "m", "n", "kw", "b", "ch", "d", "f", "g", "h", "j", "k", "l", "p", "s", "t", "v", "w", "y", "z", "m", "n", "kw", "b", "h", "j", "l", "s", "y", "m", "n", "b", "ch", "h", "j", "l", "s", "y", "z", "m", "n", "b", "ch", "f", "g", "h", "j", "k", "l", "p", "s", "y", "z", "m", "n", "b", "ch", "d", "f", "g", "h", "j", "k", "l", "p", "s", "t", "y", "z", "m", "n", "kw", "b", "ch", "d", "f", "g", "h", "j", "k", "l", "p", "s", "t", "v", "w", "y", "z", "m", "n", "kw", "nb", "nj", "ns", "nz", "nb", "nch", "nj", "ns", "ny", "nz", "nb", "nch", "nf", "ng", "nj", "nk", "np", "ns", "nz", "nb", "nch", "nd", "nf", "ng", "nj", "nk", "np", "ns", "nt", "nz", "nb", "nch", "nd", "nf", "ng", "nj", "nk", "np", "ns", "nt", "nw", "nz", "mb", "ms", "my", "mz", "mb", "mch","ms", "my", "mz", "mb", "mch", "mk", "mp", "ms", "my", "mz", "mb", "mch", "md", "mk", "mp", "ms", "mt", "my", "mz", "mb", "mch", "md", "mf", "mg", "mj", "mk", "mp", "ms", "mt", "mw", "my", "mz", "sh", "sh", "sh", "ny", "kw", "dh", "th", "sh", "ny", "dh", "th", "sh", "gh", "r", "ny", "dh", "th", "sh", "gh", "r", "ny", "ng", "ng", "ng", "ng", "ng" }, new String[]{""}, new String[]{"a-@2a", "a-@2a", "a-@3a","a-@2a", "a-@2a", "a-@3a","i-@2i", "i-@2i", "i-@3i", "e-@2e", "e-@2e", "e-@3e", "u-@2u", "u-@2u", "u-@3u", }, new String[]{}, new int[]{1, 2, 3, 4, 5}, new double[]{1, 7, 6, 4, 2}, 0.2, 1.0, 0.0, 0.25, null, true); /** * Imitation Somali, using the Latin alphabet. Due to uncommon word structure, unusual allowed combinations of * letters, and no common word roots with most familiar languages, this may seem like an unidentifiable or "alien" * language to most readers. However, it's based on the Latin writing system for the Somali language (probably * closest to the northern dialect), which due to the previously mentioned properties, makes it especially good for * mixing with other languages to make letter combinations that seem strange to appear. It is unlikely that this * particular generated language style will be familiar to readers, so it probably won't have existing stereotypes * associated with the text. One early comment this received was, "it looks like a bunch of letters semi-randomly * thrown together", which is probably a typical response (the comment was made by someone fluent in German and * English, and most Western European languages are about as far as you can get from Somali). * <br> * Libor cat naqoxekh dhuugad gisiqir? */ public static final Finnegan SOMALI = new Finnegan( new String[]{"a", "a", "a", "a", "a", "a", "a", "aa", "aa", "aa", "e", "e", "ee", "i", "i", "i", "i", "ii", "o", "o", "o", "oo", "u", "u", "u", "uu", "uu", }, new String[]{}, new String[]{"b", "t", "j", "x", "kh", "d", "r", "s", "sh", "dh", "c", "g", "f", "q", "k", "l", "m", "n", "w", "h", "y", "x", "g", "b", "d", "s", "m", "dh", "n", "r", "g", "b", "s", "dh", }, new String[]{ "bb", "gg", "dd", "bb", "dd", "rr", "ddh", "cc", "gg", "ff", "ll", "mm", "nn", "bb", "gg", "dd", "bb", "dd", "gg", "bb", "gg", "dd", "bb", "dd", "gg", "cy", "fk", "ft", "nt", "rt", "lt", "qm", "rdh", "rsh", "lq", "my", "gy", "by", "lkh", "rx", "md", "bd", "dg", "fd", "mf", "dh", "dh", "dh", "dh", }, new String[]{ "b", "t", "j", "x", "kh", "d", "r", "s", "sh", "c", "g", "f", "q", "k", "l", "m", "n", "h", "x", "g", "b", "d", "s", "m", "q", "n", "r", "b", "t", "j", "x", "kh", "d", "r", "s", "sh", "c", "g", "f", "q", "k", "l", "m", "n", "h", "x", "g", "b", "d", "s", "m", "q", "n", "r", "b", "t", "j", "x", "kh", "d", "r", "s", "sh", "c", "g", "f", "q", "k", "l", "m", "n", "g", "b", "d", "s", "q", "n", "r", "b", "t", "x", "kh", "d", "r", "s", "sh", "g", "f", "q", "k", "l", "m", "n", "g", "b", "d", "s", "r", "n", "b", "t", "kh", "d", "r", "s", "sh", "g", "f", "q", "k", "l", "m", "n", "g", "b", "d", "s", "r", "n", "b", "t", "d", "r", "s", "sh", "g", "f", "q", "k", "l", "m", "n", "g", "b", "d", "s", "r", "n", }, new String[]{"aw", "ow", "ay", "ey", "oy", "ay", "ay"}, new String[]{}, new int[]{1, 2, 3, 4, 5}, new double[]{5, 4, 5, 4, 1}, 0.25, 0.3, 0.0, 0.08, null, true); /** * Imitation Hindi, romanized to use the Latin alphabet using accented glyphs similar to the IAST standard. * You can get this to produce actual IAST glyphs by calling removeModifiers() on this, but most fonts do not * support the glyphs that needs. If the modifier that does this is not removed, then the IAST standard glyphs * {@code "ṛṝḷḹḍṭṅṇṣṃḥ"} become {@code "ŗŕļĺđţńņşĕĭ"}, with the nth glyph in the first string being substituted * with the nth glyph in the second string. * <br> * Darvāga yar; ghađhinopŕauka āĕrdur, conśaigaijo śabhodhaĕđū jiviđaudu. */ public static final Finnegan HINDI_ROMANIZED = new Finnegan( new String[]{ "a", "a", "a", "a", "a", "a", "ā", "ā", "i", "i", "i", "i", "ī", "ī", "u", "u", "u", "ū", "e", "ai", "ai", "o", "o", "o", "au", "a", "a", "a", "a", "a", "a", "ā", "ā", "i", "i", "i", "i", "ī", "ī", "u", "u", "u", "ū", "e", "ai", "ai", "o", "o", "o", "au", "a", "a", "a", "a", "a", "a", "ā", "ā", "i", "i", "i", "i", "ī", "ī", "u", "u", "u", "ū", "e", "ai", "ai", "o", "o", "o", "au", "a", "a", "a", "a", "a", "a", "ā", "ā", "i", "i", "i", "i", "ī", "ī", "u", "u", "u", "ū", "e", "ai", "ai", "o", "o", "o", "au", "a", "a", "a", "a", "a", "a", "ā", "ā", "i", "i", "i", "i", "ī", "i", "i", "ī", "ī", "u", "u", "u", "ū", "u", "ū", "u", "ū", "e", "ai", "ai", "o", "o", "o", "au", "a", "a", "a", "a", "a", "a", "ā", "ā", "i", "i", "i", "i", "ī", "i", "i", "ī", "ī", "u", "u", "u", "ū", "u", "ū", "u", "ū", "e", "ai", "ai", "o", "o", "o", "au", "a", "a", "a", "a", "a", "a", "ā", "ā", "i", "i", "i", "i", "ī", "i", "i", "ī", "ī", "u", "u", "u", "ū", "u", "ū", "u", "ū", "e", "ai", "ai", "o", "o", "o", "au", "a", "a", "a", "a", "a", "a", "ā", "ā", "i", "i", "i", "i", "ī", "i", "i", "ī", "ī", "u", "u", "u", "ū", "u", "ū", "u", "ū", "e", "ai", "ai", "o", "o", "o", "au", "aṃ", "aṃ", "aṃ", "aṃ", "aṃ", "āṃ", "āṃ", "iṃ", "iṃ", "iṃ", "īṃ", "īṃ", "uṃ", "uṃ", "ūṃ", "aiṃ", "aiṃ", "oṃ", "oṃ", "oṃ", "auṃ", //"aḥ", "aḥ", "aḥ", "aḥ", "aḥ", "āḥ", "āḥ", "iḥ", "iḥ", "iḥ", "īḥ", "īḥ", //"uḥ", "uḥ", "ūḥ", "aiḥ", "aiḥ", "oḥ", "oḥ", "oḥ", "auḥ", }, new String[]{"a'","i'","u'", "o'", "a'","i'","u'", "o'", }, new String[]{ "k", "k", "k", "k", "k", "k", "k", "k", "kṛ", "kṝ", "kḷ", "c", "c", "c", "c", "c", "c", "cṛ", "cṝ", "cḷ", "ṭ", "t", "t", "t", "t", "t", "t", "t", "t", "t", "tṛ", "tṝ", "tṛ", "tṝ", "p", "p", "p", "p", "p", "p", "p", "p", "p", "p", "pṛ", "pṝ", "pḷ", "pḹ", "pṛ", "pṝ", "p", "p", "kh", "kh", "kh", "kh", "kh", "kh", "kh", "kh", "kh", "kh", "khṛ", "khṝ", "khḷ", "khḹ", "ch", "ch", "ch", "ch", "ch", "ch", "ch", "ch", "ch", "chṛ", "chṝ", "chḷ", "chḹ", "ṭh", "th", "th", "th", "th", "th", "th", "th", "th", "th", "thṛ", "thṝ", "thḷ", "thḹ", "ph", "ph", "ph", "ph", "ph", "ph", "ph", "phṛ", "phṝ", "phḷ", "phḹ", "g", "j", "ḍ", "d", "b", "gh", "jh", "ḍh", "dh", "bh", "ṅ", "ñ", "ṇ", "n", "m", "h", "y", "r", "l", "v", "ś", "ṣ", "s", "g", "j", "ḍ", "d", "b", "gh", "jh", "ḍh", "dh", "bh", "ṅ", "ñ", "ṇ", "n", "m", "h", "y", "r", "l", "v", "ś", "ṣ", "s", "g", "j", "ḍ", "d", "b", "gh", "jh", "ḍh", "dh", "bh", "ṅ", "ñ", "ṇ", "n", "m", "h", "y", "r", "l", "v", "ś", "ṣ", "s", "g", "j", "ḍ", "d", "b", "gh", "jh", "ḍh", "dh", "bh", "ṅ", "ñ", "ṇ", "n", "m", "h", "y", "r", "l", "v", "ś", "ṣ", "s", "g", "j", "ḍ", "d", "b", "gh", "jh", "ḍh", "dh", "bh", "ṅ", "ñ", "ṇ", "n", "m", "h", "y", "r", "l", "v", "ś", "ṣ", "s", "g", "j", "ḍ", "d", "b", "gh", "jh", "ḍh", "dh", "bh", "ṅ", "ñ", "ṇ", "n", "m", "h", "y", "r", "l", "v", "ś", "ṣ", "s", "g", "j", "ḍ", "d", "b", "gh", "jh", "ḍh", "dh", "bh", "ṅ", "ñ", "ṇ", "n", "m", "h", "y", "r", "l", "v", "ś", "ṣ", "s", "g", "j", "ḍ", "d", "b", "gh", "ḍh", "dh", "bh", "ṅ", "ñ", "ṇ", "n", "m", "h", "y", "r", "l", "v", "ś", "ṣ", "s", "g", "j", "ḍ", "d", "b", "gh", "ḍh", "dh", "bh", "ṅ", "ṇ", "n", "m", "h", "y", "r", "l", "v", "ṣ", "s", "g", "j", "ḍ", "d", "b", "gh", "ḍh", "dh", "bh", "ṅ", "ṇ", "n", "m", "h", "y", "r", "l", "v", "ṣ", "s", "g", "ḍ", "d", "b", "gh", "ḍh", "dh", "bh", "n", "m", "v", "s", "g", "ḍ", "d", "b", "g", "d", "b", "dh", "bh", "n", "m", "v", "g", "ḍ", "d", "b", "g", "d", "b", "dh", "bh", "n", "m", "v", }, new String[]{ "k", "k", "k", "k", "k", "nk", "rk", "k", "k", "k", "k", "k", "nk", "rk", "k", "k", "k", "k", "k", "nk", "rk", "k", "k", "k", "k", "k", "nk", "rk", "k", "k", "k", "k", "k", "nk", "rk", "k", "k", "k", "k", "k", "nk", "rk", "k", "k", "k", "k", "k", "nk", "rk", "k", "k", "k", "k", "k", "nk", "rk", "kṛ", "kṛ", "kṛ", "kṛ", "kṛ", "nkṛ", "rkṛ", "kṝ", "kṝ", "kṝ", "kṝ", "kṝ", "nkṝ", "rkṝ", "kḷ", "kḷ", "kḷ", "kḷ", "kḷ", "nkḷ", "rkḷ", "c", "c", "c", "c", "c", "c", "cṛ", "cṝ", "cḷ", "ṭ", "t", "t", "t", "t", "t", "nt", "rt", "ṭ", "t", "t", "t", "t", "nt", "rt", "ṭ", "t", "t", "t", "t", "nt", "rt", "ṭ", "t", "t", "t", "t", "nt", "rt", "ṭ", "t", "t", "t", "t", "nt", "rt", "ṭ", "t", "t", "t", "t", "nt", "rt", "ṭ", "t", "t", "t", "t", "nt", "rt", "ṭ", "t", "t", "t", "t", "nt", "rt", "ṭ", "t", "t", "t", "t", "nt", "rt", "tṛ", "tṛ", "tṛ", "tṛ", "tṛ", "ntṛ", "rtṛ", "tṝ", "tṝ", "tṝ", "tṝ", "tṝ", "ntṝ", "rtṝ", "tṛ", "tṛ", "tṛ", "tṛ", "tṛ", "ntṛ", "rtṛ", "tṝ", "tṝ", "tṝ", "tṝ", "tṝ", "ntṝ", "rtṝ", "p", "p", "p", "p", "p", "np", "rp", "p", "p", "p", "p", "p", "np", "rp", "p", "p", "p", "p", "p", "np", "rp", "p", "p", "p", "p", "p", "np", "rp", "p", "p", "p", "p", "p", "np", "rp", "p", "p", "p", "p", "p", "np", "rp", "p", "p", "p", "p", "p", "np", "rp", "p", "p", "p", "p", "p", "np", "rp", "p", "p", "p", "p", "p", "np", "rp", "p", "p", "p", "p", "p", "np", "rp", "pṛ", "pṛ", "pṛ", "pṛ", "pṛ", "npṛ", "rpṛ", "pṝ", "pṝ", "pṝ", "pṝ", "pṝ", "npṝ", "rpṝ", "pḷ", "pḷ", "pḷ", "pḷ", "pḷ", "npḷ", "rpḷ", "pḹ", "pḹ", "pḹ", "pḹ", "pḹ", "npḹ", "rpḹ", "pṛ", "pṛ", "pṛ", "pṛ", "pṛ", "npṛ", "rpṛ", "pṝ", "pṝ", "pṝ", "pṝ", "pṝ", "npṝ", "rpṝ", "p", "p", "p", "p", "p", "np", "rp", "p", "p", "p", "p", "p", "np", "rp", "kh", "kh", "kh", "kh", "kh", "nkh", "rkh", "kh", "kh", "kh", "kh", "kh", "nkh", "rkh", "kh", "kh", "kh", "kh", "kh", "nkh", "rkh", "kh", "kh", "kh", "kh", "kh", "nkh", "rkh", "kh", "kh", "kh", "kh", "kh", "nkh", "rkh", "kh", "kh", "kh", "kh", "kh", "nkh", "rkh", "kh", "kh", "kh", "kh", "kh", "nkh", "rkh", "kh", "kh", "kh", "kh", "kh", "nkh", "rkh", "kh", "kh", "kh", "kh", "kh", "nkh", "rkh", "kh", "kh", "kh", "kh", "kh", "nkh", "rkh", "khṛ", "khṛ", "khṛ", "khṛ", "khṛ", "nkhṛ", "rkhṛ", "khṝ", "khṝ", "khṝ", "khṝ", "khṝ", "nkhṝ", "rkhṝ", "khḷ", "khḷ", "khḷ", "khḷ", "khḷ", "nkhḷ", "rkhḷ", "khḹ", "khḹ", "khḹ", "khḹ", "khḹ", "nkhḹ", "rkhḹ", "ch", "ch", "ch", "ch", "ch", "ch", "ch", "ch", "ch", "chṛ", "chṝ", "chḷ", "chḹ", "ṭh", "th", "th", "th", "th", "th", "nth", "rth", "th", "th", "th", "th", "th", "nth", "rth", "th", "th", "th", "th", "th", "nth", "rth", "th", "th", "th", "th", "th", "nth", "rth", "th", "th", "th", "th", "th", "nth", "rth", "th", "th", "th", "th", "th", "nth", "rth", "th", "th", "th", "th", "th", "nth", "rth", "th", "th", "th", "th", "th", "nth", "rth", "th", "th", "th", "th", "th", "nth", "rth", "thṛ", "thṛ", "thṛ", "thṛ", "thṛ", "nthṛ", "rthṛ", "thṝ", "thṝ", "thṝ", "thṝ", "thṝ", "nthṝ", "rthṝ", "thḷ", "thḷ", "thḷ", "thḷ", "thḷ", "nthḷ", "rthḷ", "thḹ", "thḹ", "thḹ", "thḹ", "thḹ", "nthḹ", "rthḹ", "ph", "ph", "ph", "ph", "ph", "nph", "rph", "ph", "ph", "ph", "ph", "ph", "nph", "rph", "ph", "ph", "ph", "ph", "ph", "nph", "rph", "ph", "ph", "ph", "ph", "ph", "nph", "rph", "ph", "ph", "ph", "ph", "ph", "nph", "rph", "ph", "ph", "ph", "ph", "ph", "nph", "rph", "ph", "ph", "ph", "ph", "ph", "nph", "rph", "phṛ", "phṛ", "phṛ", "phṛ", "phṛ", "nphṛ", "rphṛ", "phṝ", "phṝ", "phṝ", "phṝ", "phṝ", "nphṝ", "rphṝ", "phḷ", "phḷ", "phḷ", "phḷ", "phḷ", "nphḷ", "rphḷ", "phḹ", "phḹ", "phḹ", "phḹ", "phḹ", "nphḹ", "rphḹ", "g", "g", "g", "g", "g", "ng", "rg", "j", "j", "j", "j", "j", "nj", "rj", "ḍ", "ḍ", "ḍ", "ḍ", "ḍ", "nḍ", "rḍ", "d", "d", "d", "d", "d", "nd", "rd", "b", "b", "b", "b", "b", "nb", "rb", "gh", "gh", "gh", "gh", "gh", "ngh", "rgh", "jh", "ḍh", "ḍh", "ḍh", "ḍh", "ḍh", "nḍh", "rḍh", "dh", "dh", "dh", "dh", "dh", "ndh", "rdh", "bh", "bh", "bh", "bh", "bh", "nbh", "rbh", "ṅ", "ñ", "ṇ", "n", "m", "m", "m", "m", "m", "nm", "rm", "h", "y", "y", "y", "y", "y", "ny", "ry", "r", "l", "v", "v", "v", "v", "v", "nv", "rv", "ś", "ś", "ś", "ś", "ś", "nś", "rś", "ṣ", "ṣ", "ṣ", "ṣ", "ṣ", "nṣ", "rṣ", "s", "s", "s", "s", "s", "ns", "rs", "g", "g", "g", "g", "g", "ng", "rg", "j", "j", "j", "j", "j", "nj", "rj", "ḍ", "ḍ", "ḍ", "ḍ", "ḍ", "nḍ", "rḍ", "d", "d", "d", "d", "d", "nd", "rd", "b", "b", "b", "b", "b", "nb", "rb", "gh", "gh", "gh", "gh", "gh", "ngh", "rgh", "jh", "ḍh", "ḍh", "ḍh", "ḍh", "ḍh", "nḍh", "rḍh", "dh", "dh", "dh", "dh", "dh", "ndh", "rdh", "bh", "bh", "bh", "bh", "bh", "nbh", "rbh", "ṅ", "ñ", "ṇ", "n", "m", "m", "m", "m", "m", "nm", "rm", "h", "y", "y", "y", "y", "y", "ny", "ry", "r", "l", "v", "v", "v", "v", "v", "nv", "rv", "ś", "ś", "ś", "ś", "ś", "nś", "rś", "ṣ", "ṣ", "ṣ", "ṣ", "ṣ", "nṣ", "rṣ", "s", "s", "s", "s", "s", "ns", "rs", "g", "g", "g", "g", "g", "ng", "rg", "j", "j", "j", "j", "j", "nj", "rj", "ḍ", "ḍ", "ḍ", "ḍ", "ḍ", "nḍ", "rḍ", "d", "d", "d", "d", "d", "nd", "rd", "b", "b", "b", "b", "b", "nb", "rb", "gh", "gh", "gh", "gh", "gh", "ngh", "rgh", "jh", "ḍh", "ḍh", "ḍh", "ḍh", "ḍh", "nḍh", "rḍh", "dh", "dh", "dh", "dh", "dh", "ndh", "rdh", "bh", "bh", "bh", "bh", "bh", "nbh", "rbh", "ṅ", "ñ", "ṇ", "n", "m", "m", "m", "m", "m", "nm", "rm", "h", "y", "y", "y", "y", "y", "ny", "ry", "r", "l", "v", "v", "v", "v", "v", "nv", "rv", "ś", "ś", "ś", "ś", "ś", "nś", "rś", "ṣ", "ṣ", "ṣ", "ṣ", "ṣ", "nṣ", "rṣ", "s", "s", "s", "s", "s", "ns", "rs", "g", "g", "g", "g", "g", "ng", "rg", "j", "j", "j", "j", "j", "nj", "rj", "ḍ", "ḍ", "ḍ", "ḍ", "ḍ", "nḍ", "rḍ", "d", "d", "d", "d", "d", "nd", "rd", "b", "b", "b", "b", "b", "nb", "rb", "gh", "gh", "gh", "gh", "gh", "ngh", "rgh", "jh", "ḍh", "ḍh", "ḍh", "ḍh", "ḍh", "nḍh", "rḍh", "dh", "dh", "dh", "dh", "dh", "ndh", "rdh", "bh", "bh", "bh", "bh", "bh", "nbh", "rbh", "ṅ", "ñ", "ṇ", "n", "m", "m", "m", "m", "m", "nm", "rm", "h", "y", "y", "y", "y", "y", "ny", "ry", "r", "l", "v", "v", "v", "v", "v", "nv", "rv", "ś", "ś", "ś", "ś", "ś", "nś", "rś", "ṣ", "ṣ", "ṣ", "ṣ", "ṣ", "nṣ", "rṣ", "s", "s", "s", "s", "s", "ns", "rs", "g", "g", "g", "g", "g", "ng", "rg", "j", "j", "j", "j", "j", "nj", "rj", "ḍ", "ḍ", "ḍ", "ḍ", "ḍ", "nḍ", "rḍ", "d", "d", "d", "d", "d", "nd", "rd", "b", "b", "b", "b", "b", "nb", "rb", "gh", "gh", "gh", "gh", "gh", "ngh", "rgh", "jh", "ḍh", "ḍh", "ḍh", "ḍh", "ḍh", "nḍh", "rḍh", "dh", "dh", "dh", "dh", "dh", "ndh", "rdh", "bh", "bh", "bh", "bh", "bh", "nbh", "rbh", "ṅ", "ñ", "ṇ", "n", "m", "m", "m", "m", "m", "nm", "rm", "h", "y", "y", "y", "y", "y", "ny", "ry", "r", "l", "v", "v", "v", "v", "v", "nv", "rv", "ś", "ś", "ś", "ś", "ś", "nś", "rś", "ṣ", "ṣ", "ṣ", "ṣ", "ṣ", "nṣ", "rṣ", "s", "s", "s", "s", "s", "ns", "rs", "g", "g", "g", "g", "g", "ng", "rg", "j", "j", "j", "j", "j", "nj", "rj", "ḍ", "ḍ", "ḍ", "ḍ", "ḍ", "nḍ", "rḍ", "d", "d", "d", "d", "d", "nd", "rd", "b", "b", "b", "b", "b", "nb", "rb", "gh", "gh", "gh", "gh", "gh", "ngh", "rgh", "jh", "ḍh", "ḍh", "ḍh", "ḍh", "ḍh", "nḍh", "rḍh", "dh", "dh", "dh", "dh", "dh", "ndh", "rdh", "bh", "bh", "bh", "bh", "bh", "nbh", "rbh", "ṅ", "ñ", "ṇ", "n", "m", "m", "m", "m", "m", "nm", "rm", "h", "y", "y", "y", "y", "y", "ny", "ry", "r", "l", "v", "v", "v", "v", "v", "nv", "rv", "ś", "ś", "ś", "ś", "ś", "nś", "rś", "ṣ", "ṣ", "ṣ", "ṣ", "ṣ", "nṣ", "rṣ", "s", "s", "s", "s", "s", "ns", "rs", "g", "g", "g", "g", "g", "ng", "rg", "j", "j", "j", "j", "j", "nj", "rj", "ḍ", "ḍ", "ḍ", "ḍ", "ḍ", "nḍ", "rḍ", "d", "d", "d", "d", "d", "nd", "rd", "b", "b", "b", "b", "b", "nb", "rb", "gh", "gh", "gh", "gh", "gh", "ngh", "rgh", "jh", "ḍh", "ḍh", "ḍh", "ḍh", "ḍh", "nḍh", "rḍh", "dh", "dh", "dh", "dh", "dh", "ndh", "rdh", "bh", "bh", "bh", "bh", "bh", "nbh", "rbh", "ṅ", "ñ", "ṇ", "n", "m", "m", "m", "m", "m", "nm", "rm", "h", "y", "y", "y", "y", "y", "ny", "ry", "r", "l", "v", "v", "v", "v", "v", "nv", "rv", "ś", "ś", "ś", "ś", "ś", "nś", "rś", "ṣ", "ṣ", "ṣ", "ṣ", "ṣ", "nṣ", "rṣ", "s", "s", "s", "s", "s", "ns", "rs", "g", "g", "g", "g", "g", "ng", "rg", "j", "j", "j", "j", "j", "nj", "rj", "ḍ", "ḍ", "ḍ", "ḍ", "ḍ", "nḍ", "rḍ", "d", "d", "d", "d", "d", "nd", "rd", "b", "b", "b", "b", "b", "nb", "rb", "gh", "gh", "gh", "gh", "gh", "ngh", "rgh", "ḍh", "ḍh", "ḍh", "ḍh", "ḍh", "nḍh", "rḍh", "dh", "dh", "dh", "dh", "dh", "ndh", "rdh", "bh", "bh", "bh", "bh", "bh", "nbh", "rbh", "ṅ", "ñ", "ṇ", "n", "m", "m", "m", "m", "m", "nm", "rm", "h", "y", "y", "y", "y", "y", "ny", "ry", "r", "l", "v", "v", "v", "v", "v", "nv", "rv", "ś", "ś", "ś", "ś", "ś", "nś", "rś", "ṣ", "ṣ", "ṣ", "ṣ", "ṣ", "nṣ", "rṣ", "s", "s", "s", "s", "s", "ns", "rs", "g", "g", "g", "g", "g", "ng", "rg", "j", "j", "j", "j", "j", "nj", "rj", "ḍ", "ḍ", "ḍ", "ḍ", "ḍ", "nḍ", "rḍ", "d", "d", "d", "d", "d", "nd", "rd", "b", "b", "b", "b", "b", "nb", "rb", "gh", "gh", "gh", "gh", "gh", "ngh", "rgh", "ḍh", "ḍh", "ḍh", "ḍh", "ḍh", "nḍh", "rḍh", "dh", "dh", "dh", "dh", "dh", "ndh", "rdh", "bh", "bh", "bh", "bh", "bh", "nbh", "rbh", "ṅ", "ṇ", "n", "m", "m", "m", "m", "m", "nm", "rm", "h", "y", "y", "y", "y", "y", "ny", "ry", "r", "l", "v", "v", "v", "v", "v", "nv", "rv", "ṣ", "ṣ", "ṣ", "ṣ", "ṣ", "nṣ", "rṣ", "s", "s", "s", "s", "s", "ns", "rs", "g", "g", "g", "g", "g", "ng", "rg", "j", "j", "j", "j", "j", "nj", "rj", "ḍ", "ḍ", "ḍ", "ḍ", "ḍ", "nḍ", "rḍ", "d", "d", "d", "d", "d", "nd", "rd", "b", "b", "b", "b", "b", "nb", "rb", "gh", "gh", "gh", "gh", "gh", "ngh", "rgh", "ḍh", "ḍh", "ḍh", "ḍh", "ḍh", "nḍh", "rḍh", "dh", "dh", "dh", "dh", "dh", "ndh", "rdh", "bh", "bh", "bh", "bh", "bh", "nbh", "rbh", "ṅ", "ṇ", "n", "m", "m", "m", "m", "m", "nm", "rm", "h", "y", "y", "y", "y", "y", "ny", "ry", "r", "l", "v", "v", "v", "v", "v", "nv", "rv", "ṣ", "ṣ", "ṣ", "ṣ", "ṣ", "nṣ", "rṣ", "s", "s", "s", "s", "s", "ns", "rs", "g", "g", "g", "g", "g", "ng", "rg", "ḍ", "ḍ", "ḍ", "ḍ", "ḍ", "nḍ", "rḍ", "d", "d", "d", "d", "d", "nd", "rd", "b", "b", "b", "b", "b", "nb", "rb", "gh", "gh", "gh", "gh", "gh", "ngh", "rgh", "ḍh", "ḍh", "ḍh", "ḍh", "ḍh", "nḍh", "rḍh", "dh", "dh", "dh", "dh", "dh", "ndh", "rdh", "bh", "bh", "bh", "bh", "bh", "nbh", "rbh", "n", "m", "m", "m", "m", "m", "nm", "rm", "v", "v", "v", "v", "v", "nv", "rv", "s", "s", "s", "s", "s", "ns", "rs", "g", "g", "g", "g", "g", "ng", "rg", "ḍ", "ḍ", "ḍ", "ḍ", "ḍ", "nḍ", "rḍ", "d", "d", "d", "d", "d", "nd", "rd", "b", "b", "b", "b", "b", "nb", "rb", "g", "g", "g", "g", "g", "ng", "rg", "d", "d", "d", "d", "d", "nd", "rd", "b", "b", "b", "b", "b", "nb", "rb", "dh", "dh", "dh", "dh", "dh", "ndh", "rdh", "bh", "bh", "bh", "bh", "bh", "nbh", "rbh", "n", "m", "m", "m", "m", "m", "nm", "rm", "v", "v", "v", "v", "v", "nv", "rv", "g", "g", "g", "g", "g", "ng", "rg", "ḍ", "ḍ", "ḍ", "ḍ", "ḍ", "nḍ", "rḍ", "d", "d", "d", "d", "d", "nd", "rd", "b", "b", "b", "b", "b", "nb", "rb", "g", "g", "g", "g", "g", "ng", "rg", "d", "d", "d", "d", "d", "nd", "rd", "b", "b", "b", "b", "b", "nb", "rb", "dh", "dh", "dh", "dh", "dh", "ndh", "rdh", "bh", "bh", "bh", "bh", "bh", "nbh", "rbh", "n", "m", "m", "m", "m", "m", "nm", "rm", "v", "v", "v", "v", "v", "nv", "rv", }, new String[]{"t", "d", "m", "r", "dh", "b", "t", "d", "m", "r", "dh", "bh", "nt", "nt", "nk", "ṣ"}, new String[]{"it", "it", "ati", "adva", "aṣ", "arma", "ardha", "abi", "ab", "aya"}, new String[]{}, new int[]{1, 2, 3, 4, 5}, new double[]{1, 2, 3, 3, 1}, 0.15, 0.75, 0.0, 0.12, null, true) .addModifiers(Modifier.replacementTable("ṛṝḷḹḍṭṅṇṣṃḥ", "ŗŕļĺđţńņşĕĭ")); /** * A mix of four different languages, using only ASCII characters, that is meant for generating single words for * creature or place names in fantasy settings. * <br> * Adeni, Sainane, Caneros, Sune, Alade, Tidifi, Muni, Gito, Lixoi, Bovi... */ public static final Finnegan FANTASY_NAME = GREEK_ROMANIZED.mix( RUSSIAN_ROMANIZED.mix( FRENCH.removeAccents().mix( JAPANESE_ROMANIZED, 0.5), 0.85), 0.925); /** * A mix of four different languages with some accented characters added onto an ASCII base, that can be good for * generating single words for creature or place names in fantasy settings that should have a "fancy" feeling from * having unnecessary accents added primarily for visual reasons. * <br> * Askieno, Blarcīnũn, Mēmida, Zizhounkô, Blęrinaf, Zemĭ, Mónazôr, Renerstă, Uskus, Toufounôr... */ public static final Finnegan FANCY_FANTASY_NAME = FANTASY_NAME.addAccents(0.47, 0.07); /** * Zero-arg constructor for a Finnegan; produces a Finnegan equivalent to Finnegan.ENGLISH . */ public Finnegan() { this( new String[]{ "a", "a", "a", "a", "o", "o", "o", "e", "e", "e", "e", "e", "i", "i", "i", "i", "u", "a", "a", "a", "a", "o", "o", "o", "e", "e", "e", "e", "e", "i", "i", "i", "i", "u", "a", "a", "a", "o", "o", "e", "e", "e", "i", "i", "i", "u", "a", "a", "a", "o", "o", "e", "e", "e", "i", "i", "i", "u", "au", "ai", "ai", "ou", "ea", "ie", "io", "ei", }, new String[]{"u", "u", "oa", "oo", "oo", "oo", "ee", "ee", "ee", "ee",}, new String[]{ "b", "bl", "br", "c", "cl", "cr", "ch", "d", "dr", "f", "fl", "fr", "g", "gl", "gr", "h", "j", "k", "l", "m", "n", "p", "pl", "pr", "qu", "r", "s", "sh", "sk", "st", "sp", "sl", "sm", "sn", "t", "tr", "th", "thr", "v", "w", "y", "z", "b", "bl", "br", "c", "cl", "cr", "ch", "d", "dr", "f", "fl", "fr", "g", "gr", "h", "j", "k", "l", "m", "n", "p", "pl", "pr", "r", "s", "sh", "st", "sp", "sl", "t", "tr", "th", "w", "y", "b", "br", "c", "ch", "d", "dr", "f", "g", "h", "j", "l", "m", "n", "p", "r", "s", "sh", "st", "sl", "t", "tr", "th", "b", "d", "f", "g", "h", "l", "m", "n", "p", "r", "s", "sh", "t", "th", "b", "d", "f", "g", "h", "l", "m", "n", "p", "r", "s", "sh", "t", "th", "r", "s", "t", "l", "n", "str", "spr", "spl", "wr", "kn", "kn", "gn", }, new String[]{"x", "cst", "bs", "ff", "lg", "g", "gs", "ll", "ltr", "mb", "mn", "mm", "ng", "ng", "ngl", "nt", "ns", "nn", "ps", "mbl", "mpr", "pp", "ppl", "ppr", "rr", "rr", "rr", "rl", "rtn", "ngr", "ss", "sc", "rst", "tt", "tt", "ts", "ltr", "zz" }, new String[]{"b", "rb", "bb", "c", "rc", "ld", "d", "ds", "dd", "f", "ff", "lf", "rf", "rg", "gs", "ch", "lch", "rch", "tch", "ck", "ck", "lk", "rk", "l", "ll", "lm", "m", "rm", "mp", "n", "nk", "nch", "nd", "ng", "ng", "nt", "ns", "lp", "rp", "p", "r", "rn", "rts", "s", "s", "s", "s", "ss", "ss", "st", "ls", "t", "t", "ts", "w", "wn", "x", "ly", "lly", "z", "b", "c", "d", "f", "g", "k", "l", "m", "n", "p", "r", "s", "t", "w", }, new String[]{"ate", "ite", "ism", "ist", "er", "er", "er", "ed", "ed", "ed", "es", "es", "ied", "y", "y", "y", "y", "ate", "ite", "ism", "ist", "er", "er", "er", "ed", "ed", "ed", "es", "es", "ied", "y", "y", "y", "y", "ate", "ite", "ism", "ist", "er", "er", "er", "ed", "ed", "ed", "es", "es", "ied", "y", "y", "y", "y", "ay", "ay", "ey", "oy", "ay", "ay", "ey", "oy", "ough", "aught", "ant", "ont", "oe", "ance", "ell", "eal", "oa", "urt", "ut", "iom", "ion", "ion", "ision", "ation", "ation", "ition", "ough", "aught", "ant", "ont", "oe", "ance", "ell", "eal", "oa", "urt", "ut", "iom", "ion", "ion", "ision", "ation", "ation", "ition", "ily", "ily", "ily", "adly", "owly", "oorly", "ardly", "iedly", }, new String[]{}, new int[]{1, 2, 3, 4}, new double[]{7, 8, 4, 1}, 0.22, 0.1, 0.0, 0.25, englishSanityChecks, true); } /** * This is a very complicated constructor! Maybe look at the calls to this to initialize static members of this * class, LOVECRAFT and GREEK_ROMANIZED. * * @param openingVowels String array where each element is a vowel or group of vowels that may appear at the start * of a word or in the middle; elements may be repeated to make them more common * @param midVowels String array where each element is a vowel or group of vowels that may appear in the * middle of the word; all openingVowels are automatically copied into this internally. * Elements may be repeated to make them more common * @param openingConsonants String array where each element is a consonant or consonant cluster that can appear * at the start of a word; elements may be repeated to make them more common * @param midConsonants String array where each element is a consonant or consonant cluster than can appear * between vowels; all closingConsonants are automatically copied into this internally. * Elements may be repeated to make them more common * @param closingConsonants String array where each element is a consonant or consonant cluster than can appear * at the end of a word; elements may be repeated to make them more common * @param closingSyllables String array where each element is a syllable starting with a vowel and ending in * whatever the word should end in; elements may be repeated to make them more common * @param vowelSplitters String array where each element is a mark that goes between vowels, so if "-" is in this, * then "a-a" may be possible; elements may be repeated to make them more common * @param syllableLengths int array where each element is a possible number of syllables a word can use; closely * tied to syllableFrequencies * @param syllableFrequencies double array where each element corresponds to an element in syllableLengths and * represents how often each syllable count should appear relative to other counts; there * is no need to restrict the numbers to add up to any other number * @param vowelStartFrequency a double between 0.0 and 1.0 that determines how often words start with vowels; * higher numbers yield more words starting with vowels * @param vowelEndFrequency a double between 0.0 and 1.0 that determines how often words end with vowels; higher * numbers yield more words ending in vowels * @param vowelSplitFrequency a double between 0.0 and 1.0 that, if vowelSplitters is not empty, determines how * often a vowel will be split into two vowels separated by one of those splitters * @param syllableEndFrequency a double between 0.0 and 1.0 that determines how often an element of * closingSyllables is used instead of ending normally */ public Finnegan(String[] openingVowels, String[] midVowels, String[] openingConsonants, String[] midConsonants, String[] closingConsonants, String[] closingSyllables, String[] vowelSplitters, int[] syllableLengths, double[] syllableFrequencies, double vowelStartFrequency, double vowelEndFrequency, double vowelSplitFrequency, double syllableEndFrequency) { this(openingVowels, midVowels, openingConsonants, midConsonants, closingConsonants, closingSyllables, vowelSplitters, syllableLengths, syllableFrequencies, vowelStartFrequency, vowelEndFrequency, vowelSplitFrequency, syllableEndFrequency, englishSanityChecks, true); } /** * This is a very complicated constructor! Maybe look at the calls to this to initialize static members of this * class, LOVECRAFT and GREEK_ROMANIZED. * * @param openingVowels String array where each element is a vowel or group of vowels that may appear at the start * of a word or in the middle; elements may be repeated to make them more common * @param midVowels String array where each element is a vowel or group of vowels that may appear in the * middle of the word; all openingVowels are automatically copied into this internally. * Elements may be repeated to make them more common * @param openingConsonants String array where each element is a consonant or consonant cluster that can appear * at the start of a word; elements may be repeated to make them more common * @param midConsonants String array where each element is a consonant or consonant cluster than can appear * between vowels; all closingConsonants are automatically copied into this internally. * Elements may be repeated to make them more common * @param closingConsonants String array where each element is a consonant or consonant cluster than can appear * at the end of a word; elements may be repeated to make them more common * @param closingSyllables String array where each element is a syllable starting with a vowel and ending in * whatever the word should end in; elements may be repeated to make them more common * @param vowelSplitters String array where each element is a mark that goes between vowels, so if "-" is in this, * then "a-a" may be possible; elements may be repeated to make them more common * @param syllableLengths int array where each element is a possible number of syllables a word can use; closely * tied to syllableFrequencies * @param syllableFrequencies double array where each element corresponds to an element in syllableLengths and * represents how often each syllable count should appear relative to other counts; there * is no need to restrict the numbers to add up to any other number * @param vowelStartFrequency a double between 0.0 and 1.0 that determines how often words start with vowels; * higher numbers yield more words starting with vowels * @param vowelEndFrequency a double between 0.0 and 1.0 that determines how often words end with vowels; higher * numbers yield more words ending in vowels * @param vowelSplitFrequency a double between 0.0 and 1.0 that, if vowelSplitters is not empty, determines how * often a vowel will be split into two vowels separated by one of those splitters * @param syllableEndFrequency a double between 0.0 and 1.0 that determines how often an element of * closingSyllables is used instead of ending normally * @param sane true to perform sanity checks for pronounce-able sounds to most English speakers, replacing many * words that are impossible to say; slows down generation slightly, irrelevant for non-Latin alphabets * @param clean true to perform vulgarity/obscenity checks on the word, replacing it if it is too close to a * common English vulgarity, obscenity, or slur/epithet; slows down generation slightly */ public Finnegan(String[] openingVowels, String[] midVowels, String[] openingConsonants, String[] midConsonants, String[] closingConsonants, String[] closingSyllables, String[] vowelSplitters, int[] syllableLengths, double[] syllableFrequencies, double vowelStartFrequency, double vowelEndFrequency, double vowelSplitFrequency, double syllableEndFrequency, Pattern[] sane, boolean clean) { rng = new RNG(hash64(openingVowels, midVowels, openingConsonants, midConsonants, closingConsonants, closingSyllables, vowelSplitters) ^ hash64(syllableLengths) ^ (hash64(syllableFrequencies) << 31) ^ Double.doubleToLongBits(vowelStartFrequency + 19.0 * (vowelEndFrequency + 19.0 * (vowelSplitFrequency + 19.0 * syllableEndFrequency)))); this.openingVowels = openingVowels; this.midVowels = new String[openingVowels.length + midVowels.length]; System.arraycopy(midVowels, 0, this.midVowels, 0, midVowels.length); System.arraycopy(openingVowels, 0, this.midVowels, midVowels.length, openingVowels.length); this.openingConsonants = openingConsonants; this.midConsonants = new String[midConsonants.length + closingConsonants.length]; System.arraycopy(midConsonants, 0, this.midConsonants, 0, midConsonants.length); System.arraycopy(closingConsonants, 0, this.midConsonants, midConsonants.length, closingConsonants.length); this.closingConsonants = closingConsonants; this.vowelSplitters = vowelSplitters; this.closingSyllables = closingSyllables; this.syllableFrequencies = new LinkedHashMap<Integer, Double>(syllableLengths.length); for (int i = 0; i < syllableLengths.length && i < syllableFrequencies.length; i++) { this.syllableFrequencies.put(syllableLengths[i], syllableFrequencies[i]); } for (Double freq : this.syllableFrequencies.values()) { totalSyllableFrequency += freq; } if (vowelStartFrequency > 1.0) this.vowelStartFrequency = 1.0 / vowelStartFrequency; else this.vowelStartFrequency = vowelStartFrequency; if (vowelEndFrequency > 1.0) this.vowelEndFrequency = 1.0 / vowelEndFrequency; else this.vowelEndFrequency = vowelEndFrequency; if (vowelSplitters.length == 0) this.vowelSplitFrequency = 0.0; else if (vowelSplitFrequency > 1.0) this.vowelSplitFrequency = 1.0 / vowelSplitFrequency; else this.vowelSplitFrequency = vowelSplitFrequency; if (closingSyllables.length == 0) this.syllableEndFrequency = 0.0; else if (syllableEndFrequency > 1.0) this.syllableEndFrequency = 1.0 / syllableEndFrequency; else this.syllableEndFrequency = syllableEndFrequency; this.clean = clean; this.sanityChecks = sane; modifiers = new ArrayList<Modifier>(16); } private Finnegan(String[] openingVowels, String[] midVowels, String[] openingConsonants, String[] midConsonants, String[] closingConsonants, String[] closingSyllables, String[] vowelSplitters, LinkedHashMap<Integer, Double> syllableFrequencies, double vowelStartFrequency, double vowelEndFrequency, double vowelSplitFrequency, double syllableEndFrequency, Pattern[] sanityChecks, boolean clean, RNG rng, Collection<Modifier> modifiers) { this.openingVowels = copyStrings(openingVowels); this.midVowels = copyStrings(midVowels); this.openingConsonants = copyStrings(openingConsonants); this.midConsonants = copyStrings(midConsonants); this.closingConsonants = copyStrings(closingConsonants); this.closingSyllables = copyStrings(closingSyllables); this.vowelSplitters = copyStrings(vowelSplitters); this.syllableFrequencies = new LinkedHashMap<Integer, Double>(syllableFrequencies); this.vowelStartFrequency = vowelStartFrequency; this.vowelEndFrequency = vowelEndFrequency; this.vowelSplitFrequency = vowelSplitFrequency; this.syllableEndFrequency = syllableEndFrequency; for (Double freq : this.syllableFrequencies.values()) { totalSyllableFrequency += freq; } if (sanityChecks == null) this.sanityChecks = null; else { this.sanityChecks = new Pattern[sanityChecks.length]; System.arraycopy(sanityChecks, 0, this.sanityChecks, 0, sanityChecks.length); } this.clean = clean; this.rng = new RNG(rng.state); this.modifiers = new ArrayList<Modifier>(modifiers); } protected boolean checkAll(CharSequence testing, Pattern[] checks) { String fixed = removeAccents(testing); for (int i = 0; i < checks.length; i++) { if(checks[i].matcher(fixed).find()) return false; } return true; } /** * Generate a word from this Finnegan, using and changing the current seed. * @param capitalize true if the word should start with a capital letter, false otherwise * @return a word in the fake language as a String */ public String word(boolean capitalize) { return word(rng.state, capitalize); } /** * Generate a word from this Finnegan using the specified seed. * * @param seed the RNG seed to use for the randomized string building * @param capitalize true if the word should start with a capital letter, false otherwise * @return a word in the fake language as a String */ public String word(long seed, boolean capitalize) { rng.state = seed; while(true) { StringBuffer sb = new StringBuffer(20); double syllableChance = rng.nextDouble(totalSyllableFrequency); int syllables = 1, i = 0; for (Map.Entry<Integer, Double> kv : syllableFrequencies.entrySet()) { if (syllableChance < kv.getValue()) { syllables = kv.getKey(); break; } else syllableChance -= kv.getValue(); } if (rng.nextDouble() < vowelStartFrequency) { sb.append(rng.getRandomElement(openingVowels)); sb.append(rng.getRandomElement(midConsonants)); i++; } else { sb.append(rng.getRandomElement(openingConsonants)); } for (; i < syllables - 1; i++) { sb.append(rng.getRandomElement(midVowels)); if (rng.nextDouble() < vowelSplitFrequency) { sb.append(rng.getRandomElement(vowelSplitters)); sb.append(rng.getRandomElement(midVowels)); } sb.append(rng.getRandomElement(midConsonants)); } if (rng.nextDouble() < syllableEndFrequency) { String close = rng.getRandomElement(closingSyllables); if((close.contains("@1") && syllables == 1) || (close.contains("@2") && syllables == 2) || (close.contains("@3") && syllables == 3) ) { sb.append(close.replaceAll("@\\d", sb.toString())); } else if(!close.contains("@")) sb.append(close); else if (rng.nextDouble() < vowelEndFrequency) { sb.append(rng.getRandomElement(midVowels)); if (rng.nextDouble() < vowelSplitFrequency) { sb.append(rng.getRandomElement(vowelSplitters)); sb.append(rng.getRandomElement(midVowels)); } } } else { sb.append(rng.getRandomElement(midVowels)); if (rng.nextDouble() < vowelSplitFrequency) { sb.append(rng.getRandomElement(vowelSplitters)); sb.append(rng.getRandomElement(midVowels)); } if (rng.nextDouble() >= vowelEndFrequency) { sb.append(rng.getRandomElement(closingConsonants)); if (rng.nextDouble() < syllableEndFrequency) { String close = rng.getRandomElement(closingSyllables); if((close.contains("@1") && syllables == 1) || (close.contains("@2") && syllables == 2) || (close.contains("@3") && syllables == 3) ) { sb.append(close.replaceAll("@\\d", sb.toString())); } else if(!close.contains("@")) sb.append(close); } } } if(sanityChecks != null && !checkAll(sb, sanityChecks)) continue; for(Modifier mod : modifiers) { sb = mod.modify(rng, sb); } if (capitalize) sb.setCharAt(0, Character.toUpperCase(sb.charAt(0))); if(clean && !checkAll(sb, vulgarChecks)) continue; return sb.toString(); } } /** * Generate a word from this Finnegan using the specified RNG, with usually the specified syllable count * * @param capitalize true if the word should start with a capital letter, false otherwise * @param approxSyllables the number of syllables to try to generate * @return a word in the fake language as a String */ public String word(boolean capitalize, int approxSyllables) { return word(rng.state, capitalize, approxSyllables); } /** * Generate a word from this Finnegan using the specified RNG, with usually the specified syllable count * * @param seed the RNG seed to use for the randomized string building * @param capitalize true if the word should start with a capital letter, false otherwise * @param approxSyllables the number of syllables to try to generate * @return a word in the fake language as a String */ public String word(long seed, boolean capitalize, int approxSyllables) { rng.setState(seed); if(approxSyllables <= 0) { String finished = rng.getRandomElement(openingVowels); if(capitalize) return finished.substring(0, 1).toUpperCase(); else return finished.substring(0, 1); } while(true) { StringBuffer sb = new StringBuffer(20); int i = 0; if (rng.nextDouble() < vowelStartFrequency) { sb.append(rng.getRandomElement(openingVowels)); sb.append(rng.getRandomElement(midConsonants)); i++; } else { sb.append(rng.getRandomElement(openingConsonants)); } for (; i < approxSyllables - 1; i++) { sb.append(rng.getRandomElement(midVowels)); if (rng.nextDouble() < vowelSplitFrequency) { sb.append(rng.getRandomElement(vowelSplitters)); sb.append(rng.getRandomElement(midVowels)); } sb.append(rng.getRandomElement(midConsonants)); } if (rng.nextDouble() < syllableEndFrequency) { String close = rng.getRandomElement(closingSyllables); if((close.contains("@1") && approxSyllables == 1) || (close.contains("@2") && approxSyllables == 2) || (close.contains("@3") && approxSyllables == 3) ) { sb.append(close.replaceAll("@\\d", sb.toString())); } else if(!close.contains("@")) sb.append(close); else if (rng.nextDouble() < vowelEndFrequency) { sb.append(rng.getRandomElement(midVowels)); if (rng.nextDouble() < vowelSplitFrequency) { sb.append(rng.getRandomElement(vowelSplitters)); sb.append(rng.getRandomElement(midVowels)); } } } else { sb.append(rng.getRandomElement(midVowels)); if (rng.nextDouble() < vowelSplitFrequency) { sb.append(rng.getRandomElement(vowelSplitters)); sb.append(rng.getRandomElement(midVowels)); } if (rng.nextDouble() >= vowelEndFrequency) { sb.append(rng.getRandomElement(closingConsonants)); if (rng.nextDouble() < syllableEndFrequency) { String close = rng.getRandomElement(closingSyllables); if((close.contains("@1") && approxSyllables == 1) || (close.contains("@2") && approxSyllables == 2) || (close.contains("@3") && approxSyllables == 3) ) { close = close.replaceAll("@\\d", sb.toString()); sb.append(close); } else if(!close.contains("@")) sb.append(close); } } } if(sanityChecks != null && !checkAll(sb, sanityChecks)) continue; for(Modifier mod : modifiers) { sb = mod.modify(rng, sb); } if (capitalize) sb.setCharAt(0, Character.toUpperCase(sb.charAt(0))); if(clean && !checkAll(sb, vulgarChecks)) continue; return sb.toString(); } } /** * Generate a sentence from this Finnegan, using and changing the current seed. * @param minWords an int for the minimum number of words in a sentence; should be at least 1 * @param maxWords an int for the maximum number of words in a sentence; should be at least equal to minWords * @return a sentence in the gibberish language as a String */ public String sentence(int minWords, int maxWords) { return sentence(rng.state, minWords, maxWords, new String[]{",", ",", ",", ";"}, new String[]{".", ".", ".", "!", "?", "..."}, 0.2); } /** * Generate a sentence from this Finnegan, using and changing the current seed. * * @param minWords an int for the minimum number of words in a sentence; should be at least 1 * @param maxWords an int for the maximum number of words in a sentence; should be at least equal to minWords * @param midPunctuation a String array where each element is a comma, semicolon, or the like that goes before a * space in the middle of a sentence * @param endPunctuation a String array where each element is a period, question mark, or the like that goes at * the very end of a sentence * @param midPunctuationFrequency a double between 0.0 and 1.0 that determines how often Strings from * midPunctuation should be inserted before spaces * @return a sentence in the gibberish language as a String */ public String sentence(int minWords, int maxWords, String[] midPunctuation, String[] endPunctuation, double midPunctuationFrequency) { return sentence(rng.state, minWords, maxWords, midPunctuation, endPunctuation, midPunctuationFrequency); } /** * Generate a sentence from this Finnegan using the specific starting RNG seed. * * @param seed the RNG seed to use for the randomized string building * @param minWords an int for the minimum number of words in a sentence; should be at least 1 * @param maxWords an int for the maximum number of words in a sentence; should be at least equal to minWords * @param midPunctuation a String array where each element is a comma, semicolon, or the like that goes before a * space in the middle of a sentence * @param endPunctuation a String array where each element is a period, question mark, or the like that goes at * the very end of a sentence * @param midPunctuationFrequency a double between 0.0 and 1.0 that determines how often Strings from * midPunctuation should be inserted before spaces * @return a sentence in the gibberish language as a String */ public String sentence(long seed, int minWords, int maxWords, String[] midPunctuation, String[] endPunctuation, double midPunctuationFrequency) { rng.state = seed; if (minWords < 1) minWords = 1; if (minWords > maxWords) maxWords = minWords; if (midPunctuationFrequency > 1.0) { midPunctuationFrequency = 1.0 / midPunctuationFrequency; } StringBuilder sb = new StringBuilder(12 * maxWords); sb.append(word(true)); for (int i = 1; i < minWords; i++) { if (rng.nextDouble() < midPunctuationFrequency) { sb.append(rng.getRandomElement(midPunctuation)); } sb.append(' '); sb.append(word(false)); } for (int i = minWords; i < maxWords && rng.nextInt(2 * maxWords) > i; i++) { if (rng.nextDouble() < midPunctuationFrequency) { sb.append(rng.getRandomElement(midPunctuation)); } sb.append(' '); sb.append(word(false)); } sb.append(rng.getRandomElement(endPunctuation)); return sb.toString(); } /** * Generate a sentence from this Finnegan that fits in the given length limit.. * * @param minWords an int for the minimum number of words in a sentence; should be at least 1 * @param maxWords an int for the maximum number of words in a sentence; should be at least equal to minWords * @param midPunctuation a String array where each element is a comma, semicolon, or the like that goes before a * space in the middle of a sentence * @param endPunctuation a String array where each element is a period, question mark, or the like that goes at * the very end of a sentence * @param midPunctuationFrequency a double between 0.0 and 1.0 that determines how often Strings from * midPunctuation should be inserted before spaces * @param maxChars the longest string length this can produce; should be at least {@code 6 * minWords} * @return a sentence in the gibberish language as a String */ public String sentence(int minWords, int maxWords, String[] midPunctuation, String[] endPunctuation, double midPunctuationFrequency, int maxChars) { return sentence(rng.state, minWords, maxWords, midPunctuation, endPunctuation, midPunctuationFrequency, maxChars); } /** * Generate a sentence from this Finnegan using the specific starting RNG seed that fits in the given length limit. * * @param seed the RNG seed to use for the randomized string building * @param minWords an int for the minimum number of words in a sentence; should be at least 1 * @param maxWords an int for the maximum number of words in a sentence; should be at least equal to minWords * @param midPunctuation a String array where each element is a comma, semicolon, or the like that goes before a * space in the middle of a sentence * @param endPunctuation a String array where each element is a period, question mark, or the like that goes at * the very end of a sentence * @param midPunctuationFrequency a double between 0.0 and 1.0 that determines how often Strings from * midPunctuation should be inserted before spaces * @param maxChars the longest string length this can produce; should be at least {@code 6 * minWords} * @return a sentence in the gibberish language as a String */ public String sentence(long seed, int minWords, int maxWords, String[] midPunctuation, String[] endPunctuation, double midPunctuationFrequency, int maxChars) { rng.state = seed; if (minWords < 1) minWords = 1; if (minWords > maxWords) maxWords = minWords; if (midPunctuationFrequency > 1.0) { midPunctuationFrequency = 1.0 / midPunctuationFrequency; } if(maxChars < 4) return "!"; if(maxChars <= 5 * minWords) { minWords = 1; maxWords = 1; } int frustration = 0; StringBuilder sb = new StringBuilder(maxChars); String next = word(true); while (next.length() >= maxChars - 1 && frustration < 50) { next = word(true); frustration++; } if(frustration >= 50) return "!"; sb.append(next); for (int i = 1; i < minWords && frustration < 50 && sb.length() < maxChars - 7; i++) { if (rng.nextDouble() < midPunctuationFrequency && sb.length() < maxChars - 3) { sb.append(rng.getRandomElement(midPunctuation)); } next = word(false); while (sb.length() + next.length() >= maxChars - 2 && frustration < 50) { next = word(false); frustration++; } if(frustration >= 50) break; sb.append(' '); sb.append(next); } for (int i = minWords; i < maxWords && sb.length() < maxChars - 7 && rng.nextInt(2 * maxWords) > i && frustration < 50; i++) { if (rng.nextDouble() < midPunctuationFrequency && sb.length() < maxChars - 3) { sb.append(rng.getRandomElement(midPunctuation)); } next = word(false); while (sb.length() + next.length() >= maxChars - 2 && frustration < 50) { next = word(false); frustration++; } if(frustration >= 50) break; sb.append(' '); sb.append(next); } next = rng.getRandomElement(endPunctuation); if(sb.length() + next.length() >= maxChars) next = "."; sb.append(next); if(sb.length() > maxChars) return "!"; return sb.toString(); } protected String[] merge1000(String[] me, String[] other, double otherInfluence) { if(other.length <= 0 && me.length <= 0) return new String[]{}; String[] ret = new String[1000]; int otherCount = (int) (1000 * otherInfluence); int idx = 0; if (other.length > 0) { String[] tmp = rng.shuffle(other); for (idx = 0; idx < otherCount; idx++) { ret[idx] = tmp[idx % tmp.length]; } } if (me.length > 0) { String[] tmp = rng.shuffle(me); for (; idx < 1000; idx++) { ret[idx] = tmp[idx % tmp.length]; } } else { for (; idx < 1000; idx++) { ret[idx] = other[idx % other.length]; } } return ret; } protected String[] accentVowels(String[] me, double influence) { String[] ret = new String[1000]; int otherCount = (int) (1000 * influence); int idx = 0; Matcher matcher; if (me.length > 0) { String[] tmp = rng.shuffle(me); for (idx = 0; idx < otherCount; idx++) { ret[idx] = tmp[idx % tmp.length] .replace('a', accentedVowels[0][rng.nextInt(accentedVowels[0].length)]) .replace('e', accentedVowels[1][rng.nextInt(accentedVowels[1].length)]) .replace('i', accentedVowels[2][rng.nextInt(accentedVowels[2].length)]) .replace('o', accentedVowels[3][rng.nextInt(accentedVowels[3].length)]) .replace('u', accentedVowels[4][rng.nextInt(accentedVowels[4].length)]); matcher = repeats.matcher(ret[idx]); if (matcher.find()) { ret[idx] = matcher.replaceAll(rng.getRandomElement(me)); } } for (; idx < 1000; idx++) { ret[idx] = tmp[idx % tmp.length]; } } else return new String[]{}; return ret; } protected String[] accentConsonants(String[] me, double influence) { String[] ret = new String[1000]; int otherCount = (int) (1000 * influence); int idx = 0; Matcher matcher; if (me.length > 0) { String[] tmp = rng.shuffle(me); for (idx = 0; idx < otherCount; idx++) { ret[idx] = tmp[idx % tmp.length] //0 .replace('c', accentedConsonants[1][rng.nextInt(accentedConsonants[1].length)]) .replace('d', accentedConsonants[2][rng.nextInt(accentedConsonants[2].length)]) .replace('f', accentedConsonants[3][rng.nextInt(accentedConsonants[3].length)]) .replace('g', accentedConsonants[4][rng.nextInt(accentedConsonants[4].length)]) .replace('h', accentedConsonants[5][rng.nextInt(accentedConsonants[5].length)]) .replace('j', accentedConsonants[6][rng.nextInt(accentedConsonants[6].length)]) .replace('k', accentedConsonants[7][rng.nextInt(accentedConsonants[7].length)]) .replace('l', accentedConsonants[8][rng.nextInt(accentedConsonants[8].length)]) //9 .replace('n', accentedConsonants[10][rng.nextInt(accentedConsonants[10].length)]) //11 //12 .replace('r', accentedConsonants[13][rng.nextInt(accentedConsonants[13].length)]) .replace('s', accentedConsonants[14][rng.nextInt(accentedConsonants[14].length)]) .replace('t', accentedConsonants[15][rng.nextInt(accentedConsonants[15].length)]) //16 .replace('w', accentedConsonants[17][rng.nextInt(accentedConsonants[17].length)]) //18 .replace('y', accentedConsonants[19][rng.nextInt(accentedConsonants[19].length)]) .replace('z', accentedConsonants[20][rng.nextInt(accentedConsonants[20].length)]); matcher = repeats.matcher(ret[idx]); if (matcher.find()) { ret[idx] = matcher.replaceAll(rng.getRandomElement(me)); } } for (; idx < 1000; idx++) { ret[idx] = tmp[idx % tmp.length]; } } else return new String[]{}; return ret; } protected String[] accentBoth(String[] me, double vowelInfluence, double consonantInfluence) { String[] ret = new String[1000]; int idx = 0; Matcher matcher; if (me.length > 0) { String[] tmp = rng.shuffle(me); for (idx = 0; idx < 1000; idx++) { boolean subVowel = rng.nextDouble() < vowelInfluence, subCon = rng.nextDouble() < consonantInfluence; if (subVowel && subCon) { ret[idx] = tmp[idx % tmp.length] .replace('a', accentedVowels[0][rng.nextInt(accentedVowels[0].length)]) .replace('e', accentedVowels[1][rng.nextInt(accentedVowels[1].length)]) .replace('i', accentedVowels[2][rng.nextInt(accentedVowels[2].length)]) .replace('o', accentedVowels[3][rng.nextInt(accentedVowels[3].length)]) .replace('u', accentedVowels[4][rng.nextInt(accentedVowels[4].length)]) //0 .replace('c', accentedConsonants[1][rng.nextInt(accentedConsonants[1].length)]) .replace('d', accentedConsonants[2][rng.nextInt(accentedConsonants[2].length)]) .replace('f', accentedConsonants[3][rng.nextInt(accentedConsonants[3].length)]) .replace('g', accentedConsonants[4][rng.nextInt(accentedConsonants[4].length)]) .replace('h', accentedConsonants[5][rng.nextInt(accentedConsonants[5].length)]) .replace('j', accentedConsonants[6][rng.nextInt(accentedConsonants[6].length)]) .replace('k', accentedConsonants[7][rng.nextInt(accentedConsonants[7].length)]) .replace('l', accentedConsonants[8][rng.nextInt(accentedConsonants[8].length)]) //9 .replace('n', accentedConsonants[10][rng.nextInt(accentedConsonants[10].length)]) //11 //12 .replace('r', accentedConsonants[13][rng.nextInt(accentedConsonants[13].length)]) .replace('s', accentedConsonants[14][rng.nextInt(accentedConsonants[14].length)]) .replace('t', accentedConsonants[15][rng.nextInt(accentedConsonants[15].length)]) //16 .replace('w', accentedConsonants[17][rng.nextInt(accentedConsonants[17].length)]) //18 .replace('y', accentedConsonants[19][rng.nextInt(accentedConsonants[19].length)]) .replace('z', accentedConsonants[20][rng.nextInt(accentedConsonants[20].length)]); matcher = repeats.matcher(ret[idx]); if (matcher.find()) { ret[idx] = matcher.replaceAll(rng.getRandomElement(me)); } } else if (subVowel) { ret[idx] = tmp[idx % tmp.length] .replace('a', accentedVowels[0][rng.nextInt(accentedVowels[0].length)]) .replace('e', accentedVowels[1][rng.nextInt(accentedVowels[1].length)]) .replace('i', accentedVowels[2][rng.nextInt(accentedVowels[2].length)]) .replace('o', accentedVowels[3][rng.nextInt(accentedVowels[3].length)]) .replace('u', accentedVowels[4][rng.nextInt(accentedVowels[4].length)]); matcher = repeats.matcher(ret[idx]); if (matcher.find()) { ret[idx] = matcher.replaceAll(rng.getRandomElement(me)); } } else if (subCon) { ret[idx] = tmp[idx % tmp.length] //0 .replace('c', accentedConsonants[1][rng.nextInt(accentedConsonants[1].length)]) .replace('d', accentedConsonants[2][rng.nextInt(accentedConsonants[2].length)]) .replace('f', accentedConsonants[3][rng.nextInt(accentedConsonants[3].length)]) .replace('g', accentedConsonants[4][rng.nextInt(accentedConsonants[4].length)]) .replace('h', accentedConsonants[5][rng.nextInt(accentedConsonants[5].length)]) .replace('j', accentedConsonants[6][rng.nextInt(accentedConsonants[6].length)]) .replace('k', accentedConsonants[7][rng.nextInt(accentedConsonants[7].length)]) .replace('l', accentedConsonants[8][rng.nextInt(accentedConsonants[8].length)]) //9 .replace('n', accentedConsonants[10][rng.nextInt(accentedConsonants[10].length)]) //11 //12 .replace('r', accentedConsonants[13][rng.nextInt(accentedConsonants[13].length)]) .replace('s', accentedConsonants[14][rng.nextInt(accentedConsonants[14].length)]) .replace('t', accentedConsonants[15][rng.nextInt(accentedConsonants[15].length)]) //16 .replace('w', accentedConsonants[17][rng.nextInt(accentedConsonants[17].length)]) //18 .replace('y', accentedConsonants[19][rng.nextInt(accentedConsonants[19].length)]) .replace('z', accentedConsonants[20][rng.nextInt(accentedConsonants[20].length)]); matcher = repeats.matcher(ret[idx]); if (matcher.find()) { ret[idx] = matcher.replaceAll(rng.getRandomElement(me)); } } else ret[idx] = tmp[idx % tmp.length]; } } else return new String[]{}; return ret; } public Finnegan mix(Finnegan other, double otherInfluence) { otherInfluence = Math.max(0.0, Math.min(otherInfluence, 1.0)); double myInfluence = 1.0 - otherInfluence; long oldState = rng.state; rng.state = (hashCode() & 0xffffffffL) | ((other.hashCode() & 0xffffffffL) << 32) ^ Double.doubleToLongBits(otherInfluence); String[] ov = merge1000(openingVowels, other.openingVowels, otherInfluence), mv = merge1000(midVowels, other.midVowels, otherInfluence), oc = merge1000(openingConsonants, other.openingConsonants, otherInfluence), mc = merge1000(midConsonants, other.midConsonants, otherInfluence), cc = merge1000(closingConsonants, other.closingConsonants, otherInfluence), cs = merge1000(closingSyllables, other.closingSyllables, otherInfluence), splitters = merge1000(vowelSplitters, other.vowelSplitters, otherInfluence); LinkedHashMap<Integer, Double> freqs = new LinkedHashMap<Integer, Double>(syllableFrequencies); for (Map.Entry<Integer, Double> kv : other.syllableFrequencies.entrySet()) { if (freqs.containsKey(kv.getKey())) freqs.put(kv.getKey(), kv.getValue() + freqs.get(kv.getKey())); else freqs.put(kv.getKey(), kv.getValue()); } List<Modifier> mods = new ArrayList<Modifier>((int)(Math.ceil(modifiers.size() * myInfluence) + Math.ceil(other.modifiers.size() * otherInfluence))); mods.addAll(rng.randomPortion(modifiers, (int)Math.ceil(modifiers.size() * myInfluence))); mods.addAll(rng.randomPortion(other.modifiers, (int)Math.ceil(other.modifiers.size() * otherInfluence))); Finnegan finished = new Finnegan(ov, mv, oc, mc, cc, cs, splitters, freqs, vowelStartFrequency * myInfluence + other.vowelStartFrequency * otherInfluence, vowelEndFrequency * myInfluence + other.vowelEndFrequency * otherInfluence, vowelSplitFrequency * myInfluence + other.vowelSplitFrequency * otherInfluence, syllableEndFrequency * myInfluence + other.syllableEndFrequency * otherInfluence, (sanityChecks == null) ? other.sanityChecks : sanityChecks, true, new RNG(rng.state), mods); rng.state = oldState; return finished; } public Finnegan addAccents(double vowelInfluence, double consonantInfluence) { vowelInfluence = Math.max(0.0, Math.min(vowelInfluence, 1.0)); consonantInfluence = Math.max(0.0, Math.min(consonantInfluence, 1.0)); long oldState = rng.state; rng.state = (hashCode() & 0xffffffffL) ^ ((Double.doubleToLongBits(vowelInfluence) & 0xffffffffL) | (Double.doubleToLongBits(consonantInfluence) << 32)); String[] ov = accentVowels(openingVowels, vowelInfluence), mv = accentVowels(midVowels, vowelInfluence), oc = accentConsonants(openingConsonants, consonantInfluence), mc = accentConsonants(midConsonants, consonantInfluence), cc = accentConsonants(closingConsonants, consonantInfluence), cs = accentBoth(closingSyllables, vowelInfluence, consonantInfluence); int[] lens = new int[syllableFrequencies.size()]; double[] odds = new double[syllableFrequencies.size()]; int i = 0; for (Map.Entry<Integer, Double> kv : syllableFrequencies.entrySet()) { lens[i] = kv.getKey(); odds[i++] = kv.getValue(); } Finnegan finished = new Finnegan(ov, mv, oc, mc, cc, cs, vowelSplitters, lens, odds, vowelStartFrequency, vowelEndFrequency, vowelSplitFrequency, syllableEndFrequency, sanityChecks, clean); finished.rng.state = rng.state; rng.state = oldState; return finished; } static String[] copyStrings(String[] start) { String[] next = new String[start.length]; System.arraycopy(start, 0, next, 0, start.length); return next; } public Finnegan removeAccents() { String[] ov = openingVowels.clone(), mv = midVowels.clone(), oc = openingConsonants.clone(), mc = midConsonants.clone(), cc = closingConsonants.clone(), cs = closingSyllables.clone(); for (int i = 0; i < ov.length; i++) { ov[i] = removeAccents(openingVowels[i]); } for (int i = 0; i < mv.length; i++) { mv[i] = removeAccents(midVowels[i]); } for (int i = 0; i < oc.length; i++) { oc[i] = removeAccents(openingConsonants[i]); } for (int i = 0; i < mc.length; i++) { mc[i] = removeAccents(midConsonants[i]); } for (int i = 0; i < cc.length; i++) { cc[i] = removeAccents(closingConsonants[i]); } for (int i = 0; i < cs.length; i++) { cs[i] = removeAccents(closingSyllables[i]); } int[] lens = new int[syllableFrequencies.size()]; double[] odds = new double[syllableFrequencies.size()]; int i = 0; for (Map.Entry<Integer, Double> kv : syllableFrequencies.entrySet()) { lens[i] = kv.getKey(); odds[i++] = kv.getValue(); } Finnegan finished = new Finnegan(ov, mv, oc, mc, cc, cs, vowelSplitters, lens, odds, vowelStartFrequency, vowelEndFrequency, vowelSplitFrequency, syllableEndFrequency, sanityChecks, clean); finished.rng.state = rng.state; return finished; } /** * Adds the specified Modifier objects from a Collection to a copy of this Finnegan and returns it. * You can obtain a Modifier with the static constants in the Finnegan.Modifier nested class, the * Finnegan.modifier() method, or Modifier's constructor. * @param mods an array or vararg of Modifier objects * @return a copy of this with the Modifiers added */ public Finnegan addModifiers(Collection<Modifier> mods) { Finnegan next = copy(); next.modifiers.addAll(mods); return next; } /** * Adds the specified Modifier objects to a copy of this Finnegan and returns it. * You can obtain a Modifier with the static constants in the Finnegan.Modifier nested class, the * Finnegan.modifier() method, or Modifier's constructor. * @param mods an array or vararg of Modifier objects * @return a copy of this with the Modifiers added */ public Finnegan addModifiers(Modifier... mods) { Finnegan next = copy(); Collections.addAll(next.modifiers, mods); return next; } /** * Creates a copy of this Finnegan with no modifiers. * @return a copy of this Finnegan with modifiers removed. */ public Finnegan removeModifiers() { Finnegan next = copy(); next.modifiers.clear(); return next; } public static Modifier modifier(String pattern, String replacement) { return new Modifier(pattern, replacement); } public static Modifier modifier(String pattern, String replacement, double chance) { return new Modifier(pattern, replacement, chance); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Finnegan finnegan = (Finnegan) o; if (clean != finnegan.clean) return false; if (Double.compare(finnegan.totalSyllableFrequency, totalSyllableFrequency) != 0) return false; if (Double.compare(finnegan.vowelStartFrequency, vowelStartFrequency) != 0) return false; if (Double.compare(finnegan.vowelEndFrequency, vowelEndFrequency) != 0) return false; if (Double.compare(finnegan.vowelSplitFrequency, vowelSplitFrequency) != 0) return false; if (Double.compare(finnegan.syllableEndFrequency, syllableEndFrequency) != 0) return false; // Probably incorrect - comparing Object[] arrays with Arrays.equals if (!Arrays.equals(openingVowels, finnegan.openingVowels)) return false; // Probably incorrect - comparing Object[] arrays with Arrays.equals if (!Arrays.equals(midVowels, finnegan.midVowels)) return false; // Probably incorrect - comparing Object[] arrays with Arrays.equals if (!Arrays.equals(openingConsonants, finnegan.openingConsonants)) return false; // Probably incorrect - comparing Object[] arrays with Arrays.equals if (!Arrays.equals(midConsonants, finnegan.midConsonants)) return false; // Probably incorrect - comparing Object[] arrays with Arrays.equals if (!Arrays.equals(closingConsonants, finnegan.closingConsonants)) return false; // Probably incorrect - comparing Object[] arrays with Arrays.equals if (!Arrays.equals(vowelSplitters, finnegan.vowelSplitters)) return false; // Probably incorrect - comparing Object[] arrays with Arrays.equals if (!Arrays.equals(closingSyllables, finnegan.closingSyllables)) return false; if (syllableFrequencies != null ? !syllableFrequencies.equals(finnegan.syllableFrequencies) : finnegan.syllableFrequencies != null) return false; // Probably incorrect - comparing Object[] arrays with Arrays.equals if (!Arrays.equals(sanityChecks, finnegan.sanityChecks)) return false; if(rng != null ? !rng.equals(finnegan.rng) : finnegan.rng != null) return false; return modifiers != null ? modifiers.equals(finnegan.modifiers) : finnegan.modifiers == null; } @Override public int hashCode() { long result, temp; result = hash64(openingVowels); result = 31 * result + hash64(midVowels); result = 31 * result + hash64(openingConsonants); result = 31 * result + hash64(midConsonants); result = 31 * result + hash64(closingConsonants); result = 31 * result + hash64(vowelSplitters); result = 31 * result + hash64(closingSyllables); result = 31 * result + (clean ? 1 : 0); result = 31 * result + (syllableFrequencies != null ? syllableFrequencies.hashCode() : 0); temp = Double.doubleToLongBits(totalSyllableFrequency); result = 31 * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(vowelStartFrequency); result = 31 * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(vowelEndFrequency); result = 31 * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(vowelSplitFrequency); result = 31 * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(syllableEndFrequency); result = 31 * result + (int) (temp ^ (temp >>> 32)); result = 31 * result + (sanityChecks != null ? sanityChecks.length + 1 : 0); result = 31 * result + (modifiers != null ? modifiers.hashCode() : 0); result = 31 * result + (rng != null ? rng.hashCode() : 0); return (int)result; } @Override public String toString() { return "Finnegan{" + "openingVowels=" + Arrays.toString(openingVowels) + ", midVowels=" + Arrays.toString(midVowels) + ", openingConsonants=" + Arrays.toString(openingConsonants) + ", midConsonants=" + Arrays.toString(midConsonants) + ", closingConsonants=" + Arrays.toString(closingConsonants) + ", vowelSplitters=" + Arrays.toString(vowelSplitters) + ", closingSyllables=" + Arrays.toString(closingSyllables) + ", syllableFrequencies=" + syllableFrequencies + ", totalSyllableFrequency=" + totalSyllableFrequency + ", vowelStartFrequency=" + vowelStartFrequency + ", vowelEndFrequency=" + vowelEndFrequency + ", vowelSplitFrequency=" + vowelSplitFrequency + ", syllableEndFrequency=" + syllableEndFrequency + ", sanityChecks=" + Arrays.toString(sanityChecks) + ", clean=" + clean + ", modifiers=" + modifiers + ", RNG=" + rng + '}'; } public long getSeed() { return rng.state; } public void setSeed(long seed) { rng.state = seed; } static long hash64(char[] data) { if(data == null) return 0; long h = -3750763034362895579L, len = data.length; for (int i = 0; i < len; i++) { h ^= data[i] & 0xff; h *= 1099511628211L; h ^= data[i] >>> 8; h *= 1099511628211L; } return h; } static long hash64(int[] data) { if(data == null) return 0; long h = -3750763034362895579L, len = data.length; for (int i = 0; i < len; i++) { h ^= data[i] & 0xff; h *= 1099511628211L; h ^= (data[i] >>> 8) & 0xff; h *= 1099511628211L; h ^= (data[i] >>> 16) & 0xff; h *= 1099511628211L; h ^= data[i] >>> 24; h *= 1099511628211L; } return h; } static long hash64(double[] data) { if(data == null) return 0; long h = -3750763034362895579L, len = data.length, t; for (int i = 0; i < len; i++) { t = Double.doubleToRawLongBits(data[i]); h ^= (t & 0xff); h *= 1099511628211L; h ^= ((t >>> 8) & 0xff); h *= 1099511628211L; h ^= ((t >>> 16) & 0xff); h *= 1099511628211L; h ^= ((t >>> 24) & 0xff); h *= 1099511628211L; h ^= ((t >>> 32) & 0xff); h *= 1099511628211L; h ^= ((t >>> 40) & 0xff); h *= 1099511628211L; h ^= ((t >>> 48) & 0xff); h *= 1099511628211L; h ^= (t >>> 56); h *= 1099511628211L; } return h; } static long hash64(String s) { if(s == null) return 0; return hash64(s.toCharArray()); } static long hash64(String[] data) { if(data == null) return 0; long h = -3750763034362895579L, len = data.length, t; for (int i = 0; i < len; i++) { t = hash64(data[i]); h ^= (t & 0xff); h *= 1099511628211L; h ^= ((t >>> 8) & 0xff); h *= 1099511628211L; h ^= ((t >>> 16) & 0xff); h *= 1099511628211L; h ^= ((t >>> 24) & 0xff); h *= 1099511628211L; h ^= ((t >>> 32) & 0xff); h *= 1099511628211L; h ^= ((t >>> 40) & 0xff); h *= 1099511628211L; h ^= ((t >>> 48) & 0xff); h *= 1099511628211L; h ^= (t >>> 56); h *= 1099511628211L; } return h; } static long hash64(String[]... data) { if(data == null) return 0; long h = -3750763034362895579L, len = data.length, t; for (int i = 0; i < len; i++) { t = hash64(data[i]); h ^= (t & 0xff); h *= 1099511628211L; h ^= ((t >>> 8) & 0xff); h *= 1099511628211L; h ^= ((t >>> 16) & 0xff); h *= 1099511628211L; h ^= ((t >>> 24) & 0xff); h *= 1099511628211L; h ^= ((t >>> 32) & 0xff); h *= 1099511628211L; h ^= ((t >>> 40) & 0xff); h *= 1099511628211L; h ^= ((t >>> 48) & 0xff); h *= 1099511628211L; h ^= (t >>> 56); h *= 1099511628211L; } return h; } public Finnegan copy() { return new Finnegan(openingVowels, midVowels, openingConsonants, midConsonants, closingConsonants, closingSyllables, vowelSplitters, syllableFrequencies, vowelStartFrequency, vowelEndFrequency, vowelSplitFrequency, syllableEndFrequency, sanityChecks, clean, rng, modifiers); } public static class Modifier implements Serializable { private static final long serialVersionUID = 1734863678490422371L; public final Alteration[] alterations; public Modifier() { this("sh?", "th"); } public Modifier(String pattern, String replacement) { alterations = new Alteration[]{new Alteration(pattern, replacement)}; } public Modifier(String pattern, String replacement, double chance) { alterations = new Alteration[]{new Alteration(pattern, replacement, chance)}; } public Modifier(Alteration... alts) { alterations = (alts == null) ? new Alteration[0] : alts; } public StringBuffer modify(RNG rng, StringBuffer sb) { StringBuffer sb2; for(Alteration alt : alterations) { Matcher m = alt.pattern.matcher(sb); sb2 = new StringBuffer(); while (m.find()) { if(rng.nextDouble() < alt.chance) m.appendReplacement(sb2, alt.replacer); else m.appendReplacement(sb2, m.group()); } m.appendTail(sb2); sb = sb2; } return sb; } /** * For a character who always pronounces 's', 'ss', and 'sh' as 'th'. */ public static final Modifier LISP = new Modifier("[sśŝşšș]+h?", "th"); /** * For a character who always lengthens 's' and 'z' sounds not starting a word. */ public static final Modifier HISS = new Modifier("(.)([sśŝşšșzźżž])+", "$1$2$2$2"); /** * For a character who has a 20% chance to repeat a starting consonant or vowel. */ public static final Modifier STUTTER = new Modifier( new Alteration("^([^aàáâãäåæāăąǻǽeèéêëēĕėęěiìíîïĩīĭįıoòóôõöøōŏőœǿuùúûüũūŭůűųyýÿŷỳαοειυаеёийъыэюяоу]+)", "$1-$1", 0.2), new Alteration("^([aàáâãäåæāăąǻǽeèéêëēĕėęěiìíîïĩīĭįıoòóôõöøōŏőœǿuùúûüũūŭůűųαοειυаеёийъыэюяоу]+)", "$1-$1", 0.2)); /** * For a language that has a 40% chance to repeat a single Latin vowel (a, e, o, or a variant on one of them * like æ or ö). */ public static final Modifier DOUBLE_VOWELS = new Modifier( "([aàáâãäåæāăąǻǽeèéêëēĕėęěòóôõöøōŏőœǿ])([^aàáâãäåæāăąǻǽeèéêëēĕėęěiìíîïĩīĭįıoòóôõöøōŏőœǿuùúûüũūŭůűųyýÿŷỳ]|$)", "$1$1$2", 0.4); /** * For a language that has a 50% chance to repeat a single consonant. */ public static final Modifier DOUBLE_CONSONANTS = new Modifier("([aàáâãäåæāăąǻǽeèéêëēĕėęěiìíîïĩīĭįıoòóôõöøōŏőœǿuùúûüũūŭůűųyýÿŷỳαοειυаеёийъыэюяоу]|^)" + "([^aàáâãäåæāăąǻǽeèéêëēĕėęěiìíîïĩīĭįıoòóôõöøōŏőœǿuùúûüũūŭůűųyýÿŷỳαοειυаеёийъыэюяоуqwhjx])" + "([aàáâãäåæāăąǻǽeèéêëēĕėęěiìíîïĩīĭįıoòóôõöøōŏőœǿuùúûüũūŭůűųyýÿŷỳαοειυаеёийъыэюяоу]|$)", "$1$2$2$3", 0.5); /** * For a language that never repeats the same letter twice in a row. */ public static final Modifier NO_DOUBLES = new Modifier("(.)\\1", "$1"); /** * Creates a Modifier that will replace the nth char in initial with the nth char in change. Expects initial and * change to be the same length, but will use the lesser length if they are not equal-length. Because of the * state of the text at the time modifiers are run, only lower-case letters need to be searched for. * @param initial a String containing lower-case letters or other symbols to be swapped out of a text * @param change a String containing characters that will replace occurrences of characters in initial * @return a Modifier that can be added to a Finnegan with its addModifiers() method */ public static Modifier replacementTable(String initial, String change) { Alteration[] alts = new Alteration[Math.min(initial.length(), change.length())]; for (int i = 0; i < alts.length; i++) { //literal string syntax; avoids sensitive escaping issues and also doesn't need a character class, // which is slightly slower and has some odd escaping cases. alts[i] = new Alteration("\\Q" + initial.charAt(i) + "\\E", change.substring(i, i+1)); } return new Modifier(alts); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Modifier modifier = (Modifier) o; // Probably incorrect - comparing Object[] arrays with Arrays.equals return Arrays.equals(alterations, modifier.alterations); } @Override public int hashCode() { return Arrays.hashCode(alterations); } @Override public String toString() { return "Modifier{" + "alterations=" + Arrays.toString(alterations) + '}'; } } public static class Alteration implements Serializable { private static final long serialVersionUID = -2138854697837563188L; public Pattern pattern; public String replacer; public double chance; public Alteration() { this("[sśŝşšș]+h?", "th"); } public Alteration(String pattern, String replacement) { this.pattern = Pattern.compile(pattern); replacer = replacement; chance = 1.0; } public Alteration(String pattern, String replacement, double chance) { this.pattern = Pattern.compile(pattern); replacer = replacement; this.chance = chance; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Alteration that = (Alteration) o; if (Double.compare(that.chance, chance) != 0) return false; return replacer.equals(that.replacer); } @Override public int hashCode() { long result; long temp; result = hash64(replacer); result = 31 * result + pattern.hashCode(); temp = Double.doubleToLongBits(chance); result = 31 * result + (temp ^ (temp >>> 32)); return (int)result; } @Override public String toString() { return "Alteration{" + "pattern=" + pattern + "replacer=" + replacer + ", chance=" + chance + '}'; } } }
example/src/main/java/james/joyce/Finnegan.java
package james.joyce; import java.io.Serializable; import java.text.Normalizer; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * A text generator for producing sentences and/or words in nonsense languages that fit a theme. This does not use an * existing word list as a basis for its output, so it may or may not produce existing words occasionally, but you can * safely assume it won't generate a meaningful sentence except in the absolute unlikeliest of cases. The name comes * from the novel Finnegan's Wake by James Joyce, which employed vaguely similar creative manipulation of language. * <br> * "Thaw! The last word in stolentelling!" * <br> * -- James Joyce, Finnegan's Wake * <br> * "bababadalgharaghtakamminarronnkonnbronntonnerronntuonnthunntrovarrhounawnskawntoohoohoordenenthurnuk!" * <br> * -- James Joyce, Finnegan's Wake * <br> * CC0 Licensed, originally by Tommy Ettinger. This class is meant to be copied into your own source code, not included * as a library. There is absolutely no need to attribute me if you use this, and you can change it without obstacle. */ public class Finnegan implements Serializable { public class RNG implements Serializable { private static final long serialVersionUID = 4378460257281186370L; /** * 2 raised to the 53, - 1. */ private static final long DOUBLE_MASK = (1L << 53) - 1; /** * 2 raised to the -53. */ private static final double NORM_53 = 1. / (1L << 53); public long state; public RNG() { state = Double.doubleToLongBits(Math.random()); } public RNG(long seed) { state = seed; } /** * Can return any long, positive or negative, of any size permissible in a 64-bit signed integer. * * @return any long, all 64 bits are random */ public long nextLong() { long z = (state += 0x9E3779B97F4A7C15L); z = (z ^ (z >>> 30)) * 0xBF58476D1CE4E5B9L; z = (z ^ (z >>> 27)) * 0x94D049BB133111EBL; return z ^ (z >>> 31); } /** * Can return any int, positive or negative, of any size permissible in a 32-bit signed integer. * * @return any int, all 32 bits are random */ public int nextInt() { return (int) nextLong(); } /** * Exclusive on the upper bound n. The lower bound is 0. * * @param n the upper bound; should be positive * @return a random int less than n and at least equal to 0 */ public int nextInt(final int n) { if (n <= 0) throw new IllegalArgumentException(); final int bits = nextInt() >>> 1; return bits % n; } /** * Inclusive lower, exclusive upper. * * @param lower the lower bound, inclusive, can be positive or negative * @param upper the upper bound, exclusive, should be positive, must be greater than lower * @return a random int at least equal to lower and less than upper */ public int nextInt(final int lower, final int upper) { if (upper - lower <= 0) throw new IllegalArgumentException(); return lower + nextInt(upper - lower); } /** * Exclusive on the upper bound n. The lower bound is 0. * * @param n the upper bound; should be positive * @return a random long less than n */ public long nextLong(final long n) { if (n <= 0) throw new IllegalArgumentException(); //for(;;) { final long bits = nextLong() >>> 1; return bits % n; //long value = bits % n; //value = (value < 0) ? -value : value; //if ( bits - value + ( n - 1 ) >= 0 ) return value; //} } /** * Inclusive lower, exclusive upper. * * @param lower the lower bound, inclusive, can be positive or negative * @param upper the upper bound, exclusive, should be positive, must be greater than lower * @return a random long at least equal to lower and less than upper */ public long nextLong(final long lower, final long upper) { if (upper - lower <= 0) throw new IllegalArgumentException(); return lower + nextLong(upper - lower); } /** * Gets a uniform random double in the range [0.0,1.0) * * @return a random double at least equal to 0.0 and less than 1.0 */ public double nextDouble() { return (nextLong() & DOUBLE_MASK) * NORM_53; } /** * Gets a uniform random double in the range [0.0,outer) given a positive parameter outer. If outer * is negative, it will be the (exclusive) lower bound and 0.0 will be the (inclusive) upper bound. * * @param outer the exclusive outer bound, can be negative * @return a random double between 0.0 (inclusive) and outer (exclusive) */ public double nextDouble(final double outer) { return nextDouble() * outer; } public <T> T getRandomElement(T[] array) { if (array.length < 1) { return null; } return array[nextInt(array.length)]; } /** * Shuffle an array using the Fisher-Yates algorithm. * * @param elements an array of T; will not be modified * @param <T> can be any non-primitive type. * @return a shuffled copy of elements */ public <T> T[] shuffle(T[] elements) { T[] array = elements.clone(); int n = array.length; for (int i = 0; i < n; i++) { int r = i + nextInt(n - i); T t = array[r]; array[r] = array[i]; array[i] = t; } return array; } /** * Shuffle a {@link List} using the Fisher-Yates algorithm. * @param elements a List of T; will not be modified * @param <T> can be any non-primitive type. * @return a shuffled ArrayList containing the whole of elements in pseudo-random order. */ public <T> ArrayList<T> shuffle(List<T> elements) { ArrayList<T> al = new ArrayList<T>(elements); int n = al.size(); for (int i = 0; i < n; i++) { Collections.swap(al, i + nextInt(n - i), i); } return al; } /** * Gets a random portion of a List and returns it as a new List. Will only use a given position in the given * List at most once; does this by shuffling a copy of the List and getting a section of it. * @param data a List of T; will not be modified. * @param count the non-negative number of elements to randomly take from data * @param <T> can be any non-primitive type * @return a List of T that has length equal to the smaller of count or data.length */ public <T> List<T> randomPortion(List<T> data, int count) { return shuffle(data).subList(0, Math.min(count, data.size())); } public long getState() { return state; } public void setState(long state) { this.state = state; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; RNG rng = (RNG) o; return state == rng.state; } @Override public int hashCode() { return (int) (state ^ (state >>> 32)); } @Override public String toString() { return "RNG{" + "state=" + state + '}'; } } private static final long serialVersionUID = -2578460257281186352L; public final String[] openingVowels, midVowels, openingConsonants, midConsonants, closingConsonants, vowelSplitters, closingSyllables; public boolean clean; public final LinkedHashMap<Integer, Double> syllableFrequencies; protected double totalSyllableFrequency = 0.0; public final double vowelStartFrequency, vowelEndFrequency, vowelSplitFrequency, syllableEndFrequency; protected final Pattern[] sanityChecks; public ArrayList<Modifier> modifiers; protected static final Pattern repeats = Pattern.compile("(.)\\1+"), diacritics = Pattern.compile("[\\u0300-\\u036F\\u1DC0-\\u1DFF]+"); public static final Pattern[] vulgarChecks = new Pattern[] { Pattern.compile("[SsξCcсςС][hнН].*[dtтτТΤf]"), Pattern.compile("([PpрρРΡ][hнН])|[KkкκКΚFfDdCcсςС].{1,4}[KkкκКΚCcсςСxхжχХЖΧ]"), // lots of these end in a 'k' sound, huh Pattern.compile("[BbъыбвβЪЫБВΒ]..?.?[cсςС][hнН]"), Pattern.compile("[WwшщψШЩHhнН]..?[rяЯ]"), Pattern.compile("[TtтτТΤ]..?[tтτТΤ]"), Pattern.compile("([PpрρРΡ][hнН])|[Ff]..?[rяЯ][tтτТΤ]"), Pattern.compile("([Ssξ][hнН])|[j][iτιΙ].?[sξzΖ]"), Pattern.compile("[AaаαАΑΛ][NnийИЙΝ]..?[SsξlιζzΖ]"), Pattern.compile("[AaаαАΑΛ][sξ][sξ]"), Pattern.compile(".[uμυν][hнН]?[nийИЙΝ]+[tтτТΤ]"), Pattern.compile("[NnFf]..?g"), // might as well remove two possible slurs with one check Pattern.compile("[PpрρРΡ][eеёзξεЕЁЗΞΕΣioоюσοОЮΟuμυν][eеёзξεЕЁЗΞΕΣoоюσοОЮΟs]"), // the grab bag of juvenile words Pattern.compile("[MmмМΜ]..?[rяЯ].?d"), // should pick up the #1 obscenity from Spanish and French Pattern.compile("[Gg][hнН]?[aаαАΑΛeеёзξεЕЁЗΞΕΣ][yуλγУΥeеёзξεЕЁЗΞΕΣ]") // could be inappropriate for random text }, englishSanityChecks = new Pattern[] { Pattern.compile("[AEIOUaeiou]{3}"), Pattern.compile("(\\w)\\1\\1"), Pattern.compile("(.)\\1(.)\\2"), Pattern.compile("[Aa][ae]"), Pattern.compile("[Uu][umlkj]"), Pattern.compile("[Ii][iyqkhrl]"), Pattern.compile("[Oo][c]"), Pattern.compile("[Yy][aeiou]{2}"), Pattern.compile("[Rr][aeiouy]+[xrhp]"), Pattern.compile("[Qq]u[yu]"), Pattern.compile("[^oai]uch"), Pattern.compile("[^tcsz]hh"), Pattern.compile("[Hh][tcszi]h"), Pattern.compile("[Tt]t[^aeiouy]{2}"), Pattern.compile("[IYiy]h[^aeiouy ]"), Pattern.compile("[szSZrlRL][^aeiou][rlsz]"), Pattern.compile("[UIuiYy][wy]"), Pattern.compile("^[UIui][ae]"), Pattern.compile("q$") }, japaneseSanityChecks = new Pattern[] { Pattern.compile("[AEIOUaeiou]{3}"), Pattern.compile("(\\w)\\1\\1"), Pattern.compile("[Tt]s[^u]"), Pattern.compile("[Ff][^u]"), Pattern.compile("[Yy][^auo]"), Pattern.compile("[Tt][ui]"), Pattern.compile("[SsZzDd]i"), Pattern.compile("[Hh]u"), }; public RNG rng; public static final char[][] accentedVowels = new char[][]{ new char[]{ 'à', 'á', 'â', 'ã', 'ä', 'å', 'æ', 'ā', 'ă', 'ą', 'ǻ', 'ǽ' }, new char[]{ 'è', 'é', 'ê', 'ë', 'ē', 'ĕ', 'ė', 'ę', 'ě' }, new char[]{ 'ì', 'í', 'î', 'ï', 'ĩ', 'ī', 'ĭ', 'į', 'ı', }, new char[]{ 'ò', 'ó', 'ô', 'õ', 'ö', 'ø', 'ō', 'ŏ', 'ő', 'œ', 'ǿ' }, new char[]{ 'ù', 'ú', 'û', 'ü', 'ũ', 'ū', 'ŭ', 'ů', 'ű', 'ų' } }, accentedConsonants = new char[][] { new char[]{ 'b' }, new char[]{ 'c', 'ç', 'ć', 'ĉ', 'ċ', 'č', }, new char[]{ 'd', 'þ', 'ð', 'ď', 'đ', }, new char[]{ 'f' }, new char[]{ 'g', 'ĝ', 'ğ', 'ġ', 'ģ', }, new char[]{ 'h', 'ĥ', 'ħ', }, new char[]{ 'j', 'ĵ', 'ȷ', }, new char[]{ 'k', 'ķ', }, new char[]{ 'l', 'ĺ', 'ļ', 'ľ', 'ŀ', 'ł', }, new char[]{ 'm', }, new char[]{ 'n', 'ñ', 'ń', 'ņ', 'ň', 'ŋ', }, new char[]{ 'p', }, new char[]{ 'q', }, new char[]{ 'r', 'ŕ', 'ŗ', 'ř', }, new char[]{ 's', 'ś', 'ŝ', 'ş', 'š', 'ș', }, new char[]{ 't', 'ţ', 'ť', 'ț', }, new char[]{ 'v', }, new char[]{ 'w', 'ŵ', 'ẁ', 'ẃ', 'ẅ', }, new char[]{ 'x', }, new char[]{ 'y', 'ý', 'ÿ', 'ŷ', 'ỳ', }, new char[]{ 'z', 'ź', 'ż', 'ž', }, }; /** * Removes accented characters from a string; if the "base" characters are non-English anyway then the result won't * be an ASCII string, but otherwise it probably will be. * <br> * Credit to user hashable from http://stackoverflow.com/a/1215117 * * @param str a string that may contain accented characters * @return a string with all accented characters replaced with their (possibly ASCII) counterparts */ public String removeAccents(CharSequence str) { String alteredString = Normalizer.normalize(str, Normalizer.Form.NFD); alteredString = diacritics.matcher(alteredString).replaceAll("") .replace('æ', 'a') .replace('œ', 'o') .replace('ø', 'o') .replace('Æ', 'A') .replace('Œ', 'O') .replace('Ø', 'O'); return alteredString; } /** * Ia! Ia! Cthulhu Rl'yeh ftaghn! Useful for generating cultist ramblings or unreadable occult texts. * <br> * Zvrugg pialuk, ya'as irlemrugle'eith iposh hmo-es nyeighi, glikreirk shaivro'ei! */ public static final Finnegan LOVECRAFT = new Finnegan( new String[]{"a", "i", "o", "e", "u", "a", "i", "o", "e", "u", "ia", "ai", "aa", "ei"}, new String[]{}, new String[]{"s", "t", "k", "n", "y", "p", "k", "l", "g", "gl", "th", "sh", "ny", "ft", "hm", "zvr", "cth"}, new String[]{"h", "gl", "gr", "nd", "mr", "vr", "kr"}, new String[]{"l", "p", "s", "t", "n", "k", "g", "x", "rl", "th", "gg", "gh", "ts", "lt", "rk", "kh", "sh", "ng", "shk"}, new String[]{"aghn", "ulhu", "urath", "oigor", "alos", "'yeh", "achtal", "urath", "ikhet", "adzek"}, new String[]{"'", "-"}, new int[]{1, 2, 3}, new double[]{6, 7, 2}, 0.4, 0.31, 0.07, 0.04, null, true); /** * Imitation English; may seem closer to Dutch in some generated text, and is not exactly the best imitation. * Should seem pretty fake to many readers; does not filter out dictionary words but does perform basic vulgarity * filtering. If you want to avoid generating other words, you can subclass Finnegan and modify word() . * <br> * Mont tiste frot; mousation hauddes? * Lily wrely stiebes; flarrousseal gapestist. */ public static final Finnegan ENGLISH = new Finnegan( new String[]{ "a", "a", "a", "a", "o", "o", "o", "e", "e", "e", "e", "e", "i", "i", "i", "i", "u", "a", "a", "a", "a", "o", "o", "o", "e", "e", "e", "e", "e", "i", "i", "i", "i", "u", "a", "a", "a", "o", "o", "e", "e", "e", "i", "i", "i", "u", "a", "a", "a", "o", "o", "e", "e", "e", "i", "i", "i", "u", "au", "ai", "ai", "ou", "ea", "ie", "io", "ei", }, new String[]{"u", "u", "oa", "oo", "oo", "oo", "ee", "ee", "ee", "ee",}, new String[]{ "b", "bl", "br", "c", "cl", "cr", "ch", "d", "dr", "f", "fl", "fr", "g", "gl", "gr", "h", "j", "k", "l", "m", "n", "p", "pl", "pr", "qu", "r", "s", "sh", "sk", "st", "sp", "sl", "sm", "sn", "t", "tr", "th", "thr", "v", "w", "y", "z", "b", "bl", "br", "c", "cl", "cr", "ch", "d", "dr", "f", "fl", "fr", "g", "gr", "h", "j", "k", "l", "m", "n", "p", "pl", "pr", "r", "s", "sh", "st", "sp", "sl", "t", "tr", "th", "w", "y", "b", "br", "c", "ch", "d", "dr", "f", "g", "h", "j", "l", "m", "n", "p", "r", "s", "sh", "st", "sl", "t", "tr", "th", "b", "d", "f", "g", "h", "l", "m", "n", "p", "r", "s", "sh", "t", "th", "b", "d", "f", "g", "h", "l", "m", "n", "p", "r", "s", "sh", "t", "th", "r", "s", "t", "l", "n", "str", "spr", "spl", "wr", "kn", "kn", "gn", }, new String[]{"x", "cst", "bs", "ff", "lg", "g", "gs", "ll", "ltr", "mb", "mn", "mm", "ng", "ng", "ngl", "nt", "ns", "nn", "ps", "mbl", "mpr", "pp", "ppl", "ppr", "rr", "rr", "rr", "rl", "rtn", "ngr", "ss", "sc", "rst", "tt", "tt", "ts", "ltr", "zz" }, new String[]{"b", "rb", "bb", "c", "rc", "ld", "d", "ds", "dd", "f", "ff", "lf", "rf", "rg", "gs", "ch", "lch", "rch", "tch", "ck", "ck", "lk", "rk", "l", "ll", "lm", "m", "rm", "mp", "n", "nk", "nch", "nd", "ng", "ng", "nt", "ns", "lp", "rp", "p", "r", "rn", "rts", "s", "s", "s", "s", "ss", "ss", "st", "ls", "t", "t", "ts", "w", "wn", "x", "ly", "lly", "z", "b", "c", "d", "f", "g", "k", "l", "m", "n", "p", "r", "s", "t", "w", }, new String[]{"ate", "ite", "ism", "ist", "er", "er", "er", "ed", "ed", "ed", "es", "es", "ied", "y", "y", "y", "y", "ate", "ite", "ism", "ist", "er", "er", "er", "ed", "ed", "ed", "es", "es", "ied", "y", "y", "y", "y", "ate", "ite", "ism", "ist", "er", "er", "er", "ed", "ed", "ed", "es", "es", "ied", "y", "y", "y", "y", "ay", "ay", "ey", "oy", "ay", "ay", "ey", "oy", "ough", "aught", "ant", "ont", "oe", "ance", "ell", "eal", "oa", "urt", "ut", "iom", "ion", "ion", "ision", "ation", "ation", "ition", "ough", "aught", "ant", "ont", "oe", "ance", "ell", "eal", "oa", "urt", "ut", "iom", "ion", "ion", "ision", "ation", "ation", "ition", "ily", "ily", "ily", "adly", "owly", "oorly", "ardly", "iedly", }, new String[]{}, new int[]{1, 2, 3, 4}, new double[]{7, 8, 4, 1}, 0.22, 0.1, 0.0, 0.25, englishSanityChecks, true); /** * Imitation ancient Greek, romanized to use the Latin alphabet. Likely to seem pretty fake to many readers. * <br> * Psuilas alor; aipeomarta le liaspa... */ public static final Finnegan GREEK_ROMANIZED = new Finnegan( new String[]{"a", "a", "a", "o", "o", "o", "e", "e", "i", "i", "i", "au", "ai", "ai", "oi", "oi", "ia", "io", "ou", "ou", "eo", "ei"}, new String[]{"ui", "ei"}, new String[]{"rh", "s", "z", "t", "t", "k", "ch", "n", "th", "kth", "m", "p", "ps", "b", "l", "kr", "g", "phth"}, new String[]{"lph", "pl", "l", "l", "kr", "nch", "nx", "ps"}, new String[]{"s", "p", "t", "ch", "n", "m", "s", "p", "t", "ch", "n", "m", "b", "g", "st", "rst", "rt", "sp", "rk", "ph", "x", "z", "nk", "ng", "th"}, new String[]{"os", "os", "is", "us", "um", "eum", "ium", "iam", "us", "um", "es", "anes", "eros", "or", "ophon", "on", "otron"}, new String[]{}, new int[]{1, 2, 3}, new double[]{5, 7, 4}, 0.45, 0.45, 0.0, 0.3, null, true); /** * Imitation ancient Greek, using the original Greek alphabet. People may try to translate it and get gibberish. * Make sure the font you use to render this supports the Greek alphabet! In the GDX display module, the "smooth" * fonts support all the Greek you need for this. * <br> * Ψυιλασ αλορ; αιπεομαρτα λε λιασπα... */ public static final Finnegan GREEK_AUTHENTIC = new Finnegan( new String[]{"α", "α", "α", "ο", "ο", "ο", "ε", "ε", "ι", "ι", "ι", "αυ", "αι", "αι", "οι", "οι", "ια", "ιο", "ου", "ου", "εο", "ει"}, new String[]{"υι", "ει"}, new String[]{"ρ", "σ", "ζ", "τ", "τ", "κ", "χ", "ν", "θ", "κθ", "μ", "π", "ψ", "β", "λ", "κρ", "γ", "φθ"}, new String[]{"λφ", "πλ", "λ", "λ", "κρ", "γχ", "γξ", "ψ"}, new String[]{"σ", "π", "τ", "χ", "ν", "μ", "σ", "π", "τ", "χ", "ν", "μ", "β", "γ", "στ", "ρστ", "ρτ", "σπ", "ρκ", "φ", "ξ", "ζ", "γκ", "γγ", "θ"}, new String[]{"ος", "ος", "ις", "υς", "υμ", "ευμ", "ιυμ", "ιαμ", "υς", "υμ", "ες", "ανες", "ερος", "ορ", "οφον", "ον", "οτρον"}, new String[]{}, new int[]{1, 2, 3}, new double[]{5, 7, 4}, 0.45, 0.45, 0.0, 0.3, null, true); /** * Imitation modern French, using (too many of) the accented vowels that are present in the language. Translating it * will produce gibberish if it produces anything at all. In the GDX display module, the "smooth" and "unicode" * fonts support all the accented characters you need for this. * <br><br> * Fa veau, ja ri avé re orçe jai braï aisté. */ public static final Finnegan FRENCH = new Finnegan( new String[]{"a", "a", "a", "e", "e", "e", "i", "i", "o", "u", "a", "a", "a", "e", "e", "e", "i", "i", "o", "a", "a", "a", "e", "e", "e", "i", "i", "o", "u", "a", "a", "a", "e", "e", "e", "i", "i", "o", "a", "a", "e", "e", "i", "o", "a", "a", "a", "e", "e", "e", "i", "i", "o", "ai", "oi", "oui", "au", "œu", "ou" }, new String[]{ "ai", "aie", "aou", "eau", "oi", "oui", "oie", "eu", "eu", "à", "â", "ai", "aî", "aï", "aie", "aou", "aoû", "au", "ay", "e", "é", "ée", "è", "ê", "eau", "ei", "eî", "eu", "eû", "i", "î", "ï", "o", "ô", "oe", "oê", "oë", "œu", "oi", "oie", "oï", "ou", "oû", "oy", "u", "û", "ue", "a", "a", "a", "e", "e", "e", "i", "i", "o", "u", "a", "a", "a", "e", "e", "e", "i", "i", "o", "a", "a", "e", "e", "i", "o", "a", "a", "a", "e", "e", "e", "i", "i", "o", }, new String[]{"tr", "ch", "m", "b", "b", "br", "j", "j", "j", "j", "g", "t", "t", "t", "c", "d", "f", "f", "h", "n", "l", "l", "s", "s", "s", "r", "r", "r", "v", "v", "p", "pl", "pr", "bl", "br", "dr", "gl", "gr"}, new String[]{"cqu", "gu", "qu", "rqu", "nt", "ng", "ngu", "mb", "ll", "nd", "ndr", "nct", "st", "xt", "mbr", "pl", "g", "gg", "ggr", "gl", "m", "m", "mm", "v", "v", "f", "f", "f", "ff", "b", "b", "bb", "d", "d", "dd", "s", "s", "s", "ss", "ss", "ss", "cl", "cr", "ng", "ç", "ç", "rç"}, new String[]{}, new String[]{"e", "e", "e", "e", "e", "é", "é", "er", "er", "er", "er", "er", "es", "es", "es", "es", "es", "es", "e", "e", "e", "e", "e", "é", "é", "er", "er", "er", "er", "er", "er", "es", "es", "es", "es", "es", "e", "e", "e", "e", "e", "é", "é", "é", "er", "er", "er", "er", "er", "es", "es", "es", "es", "es", "ent", "em", "en", "en", "aim", "ain", "an", "oin", "ien", "iere", "ors", "anse", "ombs", "ommes", "ancs", "ends", "œufs", "erfs", "ongs", "aps", "ats", "ives", "ui", "illes", "aen", "aon", "am", "an", "eun", "ein", "age", "age", "uile", "uin", "um", "un", "un", "un", "aille", "ouille", "eille", "ille", "eur", "it", "ot", "oi", "oi", "oi", "aire", "om", "on", "on", "im", "in", "in", "ien", "ien", "ion", "il", "eil", "oin", "oint", "iguïté", "ience", "incte", "ang", "ong", "acré", "eau", "ouche", "oux", "oux", "ect", "ecri", "agne", "uer", "aix", "eth", "ut", "ant", "anc", "anc", "anche", "ioche", "eaux", "ive", "eur", "ancois", "ecois"}, new String[]{}, new int[]{1, 2, 3}, new double[]{18, 7, 2}, 0.35, 1.0, 0.0, 0.55, null, true); /** * Imitation modern Russian, romanized to use the Latin alphabet. Likely to seem pretty fake to many readers. * <br> * Zhydotuf ruts pitsas, gogutiar shyskuchebab - gichapofeglor giunuz ieskaziuzhin. */ public static final Finnegan RUSSIAN_ROMANIZED = new Finnegan( new String[]{"a", "e", "e", "i", "i", "o", "u", "ie", "y", "e", "iu", "ia", "y", "a", "a", "o", "u"}, new String[]{}, new String[]{"b", "v", "g", "d", "k", "l", "p", "r", "s", "t", "f", "kh", "ts", "b", "v", "g", "d", "k", "l", "p", "r", "s", "t", "f", "kh", "ts", "b", "v", "g", "d", "k", "l", "p", "r", "s", "t", "f", "zh", "m", "n", "z", "ch", "sh", "shch", "br", "sk", "tr", "bl", "gl", "kr", "gr"}, new String[]{"bl", "br", "pl", "dzh", "tr", "gl", "gr", "kr"}, new String[]{"b", "v", "g", "d", "zh", "z", "k", "l", "m", "n", "p", "r", "s", "t", "f", "kh", "ts", "ch", "sh", "v", "f", "sk", "sk", "sk", "s", "b", "d", "d", "n", "r", "r"}, new String[]{"odka", "odna", "usk", "ask", "usky", "ad", "ar", "ovich", "ev", "ov", "of", "agda", "etsky", "ich", "on", "akh", "iev", "ian"}, new String[]{}, new int[]{1, 2, 3, 4, 5, 6}, new double[]{4, 5, 6, 5, 3, 1}, 0.1, 0.2, 0.0, 0.12, englishSanityChecks, true); /** * Imitation modern Russian, using the authentic Cyrillic alphabet used in Russia and other countries. * Make sure the font you use to render this supports the Cyrillic alphabet! * In the GDX display module, the "smooth" fonts support all the Cyrillic alphabet you need for this. * <br> * Жыдотуф руц пйцас, гогутяр шыскучэбаб - гйчапофёглор гюнуз ъсказюжин. */ public static final Finnegan RUSSIAN_AUTHENTIC = new Finnegan( new String[]{"а", "е", "ё", "и", "й", "о", "у", "ъ", "ы", "э", "ю", "я", "ы", "а", "а", "о", "у"}, new String[]{}, new String[]{"б", "в", "г", "д", "к", "л", "п", "р", "с", "т", "ф", "х", "ц", "б", "в", "г", "д", "к", "л", "п", "р", "с", "т", "ф", "х", "ц", "б", "в", "г", "д", "к", "л", "п", "р", "с", "т", "ф", "ж", "м", "н", "з", "ч", "ш", "щ", "бр", "ск", "тр", "бл", "гл", "кр", "гр"}, new String[]{"бл", "бр", "пл", "дж", "тр", "гл", "гр", "кр"}, new String[]{"б", "в", "г", "д", "ж", "з", "к", "л", "м", "н", "п", "р", "с", "т", "ф", "х", "ц", "ч", "ш", "в", "ф", "ск", "ск", "ск", "с", "б", "д", "д", "н", "р", "р"}, new String[]{"одка", "одна", "уск", "аск", "ускы", "ад", "ар", "овйч", "ев", "ов", "оф", "агда", "ёцкы", "йч", "он", "ах", "ъв", "ян"}, new String[]{}, new int[]{1, 2, 3, 4, 5, 6}, new double[]{4, 5, 6, 5, 3, 1}, 0.1, 0.2, 0.0, 0.12, null, true); /** * Imitation Japanese, romanized to use the Latin alphabet. Likely to seem pretty fake to many readers. Excellent * when mixed, but keep in mind the sanity checks that are used to make this generate viable words in Japanese also * can carry over to a mixed language if JAPANESE_ROMANIZED is mixed with a Finnegan that does not have sanity * checks, like any non-Latin-script ones. If this is the parameter to mix() called on a Finnegan like FRENCH or * RUSSIAN_ROMANIZED (but not RUSSIAN_AUTHENTIC), the sanity check carryover probably won't happen, and the word * structure won't have the mostly-syllable-based aesthetic that JAPANESE_ROMANIZED generates. * <br> * Narurehyounan nikase keho... */ public static final Finnegan JAPANESE_ROMANIZED = new Finnegan( new String[]{"a", "a", "a", "a", "e", "e", "i", "i", "i", "i", "o", "o", "o", "u", "ou", "u", "ai", "ai"}, new String[]{}, new String[]{"k", "ky", "s", "sh", "t", "ts", "ch", "n", "ny", "h", "f", "hy", "m", "my", "y", "r", "ry", "g", "gy", "z", "j", "d", "b", "by", "p", "py", "k", "t", "n", "s", "k", "t", "d", "s", "sh", "sh", "g", "r", "b", "k", "t", "n", "s", "k", "t", "b", "s", "sh", "sh", "g", "r", "b", "k", "t", "n", "s", "k", "t", "z", "s", "sh", "sh", "ch", "ry", "ts" }, new String[]{"k", "ky", "s", "sh", "t", "ts", "ch", "n", "ny", "h", "f", "hy", "m", "my", "y", "r", "ry", "g", "gy", "z", "j", "d", "b", "by", "p", "py", "k", "t", "d", "s", "k", "t", "d", "s", "sh", "sh", "y", "j", "p", "r", "d", "k", "t", "b", "s", "k", "t", "b", "s", "sh", "sh", "y", "j", "p", "r", "d", "k", "t", "z", "s", "f", "g", "z", "b", "d", "ts", "nn", "nn", "nn", "nd", "nz", "mm", "kk", "kk", "tt", "ss", "ssh", "tch"}, new String[]{"n"}, new String[]{}, new String[]{}, new int[]{1, 2, 3, 4, 5}, new double[]{5, 4, 5, 4, 3}, 0.3, 0.9, 0.0, 0.0, japaneseSanityChecks, true); /** * Swahili is one of the more commonly-spoken languages in sub-Saharan Africa, and serves mainly as a shared language * that is often learned after becoming fluent in one of many other (vaguely-similar) languages of the area. An * example sentence in Swahili, that this might try to imitate aesthetically, is "Mtoto mdogo amekisoma," meaning * "The small child reads it" (where it is a book). A notable language feature used here is the redoubling of words, * which is used in Swahili to emphasize or alter the meaning of the doubled word; here, it always repeats exactly * and can't make minor changes like a real language might. This generates things like "gata-gata", "hapi-hapi", and * "mimamzu-mimamzu", always separating with a hyphen here. * <br> * As an aside, please try to avoid the ugly stereotypes that fantasy media often assigns to speakers of African-like * languages when using this or any of the generators. Many fantasy tropes come from older literature written with * major cultural biases, and real-world cultural elements can be much more interesting to players than yet another * depiction of a "jungle savage" with stereotypical traits. Consider drawing from existing lists of real-world * technological discoveries, like https://en.wikipedia.org/wiki/History_of_science_and_technology_in_Africa , for * inspiration when world-building; though some groups may not have developed agriculture by early medieval times, * their neighbors may be working iron and studying astronomy just a short distance away. * <br> * Kondueyu; ma mpiyamdabota mise-mise nizakwaja alamsa amja, homa nkajupomba. */ public static final Finnegan SWAHILI = new Finnegan( new String[]{"a", "i", "o", "e", "u", "a", "a", "i", "o", "o", "e", "u", "a", "a", "i", "o", "o", "u", "a", "a", "i", "i", "o", "a","a","a","a","a", "a", "i", "o", "e", "u", "a", "a", "i", "o", "o", "e", "u", "a", "a", "i", "o", "o", "u", "a", "a", "i", "i", "o", "a","a","a","a","a", "aa", "aa", "ue", "uo", "ii", "ea"}, new String[]{}, new String[]{ "b", "h", "j", "l", "s", "y", "m", "n", "b", "ch", "h", "j", "l", "s", "y", "z", "m", "n", "b", "ch", "f", "g", "h", "j", "k", "l", "p", "s", "y", "z", "m", "n", "b", "ch", "d", "f", "g", "h", "j", "k", "l", "p", "s", "t", "y", "z", "m", "n", "kw", "b", "ch", "d", "f", "g", "h", "j", "k", "l", "p", "s", "t", "v", "w", "y", "z", "m", "n", "kw", "b", "h", "j", "l", "s", "y", "m", "n", "b", "ch", "h", "j", "l", "s", "y", "z", "m", "n", "b", "ch", "f", "g", "h", "j", "k", "l", "p", "s", "y", "z", "m", "n", "b", "ch", "d", "f", "g", "h", "j", "k", "l", "p", "s", "t", "y", "z", "m", "n", "kw", "b", "ch", "d", "f", "g", "h", "j", "k", "l", "p", "s", "t", "v", "w", "y", "z", "m", "n", "kw", "b", "h", "j", "l", "s", "y", "m", "n", "b", "ch", "h", "j", "l", "s", "y", "z", "m", "n", "b", "ch", "f", "g", "h", "j", "k", "l", "p", "s", "y", "z", "m", "n", "b", "ch", "d", "f", "g", "h", "j", "k", "l", "p", "s", "t", "y", "z", "m", "n", "kw", "b", "ch", "d", "f", "g", "h", "j", "k", "l", "p", "s", "t", "v", "w", "y", "z", "m", "n", "kw", "b", "h", "j", "l", "s", "y", "m", "n", "b", "ch", "h", "j", "l", "s", "y", "z", "m", "n", "b", "ch", "f", "g", "h", "j", "k", "l", "p", "s", "y", "z", "m", "n", "b", "ch", "d", "f", "g", "h", "j", "k", "l", "p", "s", "t", "y", "z", "m", "n", "kw", "b", "ch", "d", "f", "g", "h", "j", "k", "l", "p", "s", "t", "v", "w", "y", "z", "m", "n", "kw", "nb", "nj", "ns", "nz", "nb", "nch", "nj", "ns", "ny", "nz", "nb", "nch", "nf", "ng", "nj", "nk", "np", "ns", "nz", "nb", "nch", "nd", "nf", "ng", "nj", "nk", "np", "ns", "nt", "nz", "nb", "nch", "nd", "nf", "ng", "nj", "nk", "np", "ns", "nt", "nv", "nw", "nz", "mb", "ms", "my", "mz", "mb", "mch","ms", "my", "mz", "mb", "mch", "mk", "mp", "ms", "my", "mz", "mb", "mch", "md", "mk", "mp", "ms", "mt", "my", "mz", "mb", "mch", "md", "mf", "mg", "mj", "mk", "mp", "ms", "mt", "mv", "mw", "my", "mz", "sh", "sh", "sh", "ny", "kw", "dh", "th", "sh", "ny", "dh", "th", "sh", "gh", "r", "ny", "dh", "th", "sh", "gh", "r", "ny", }, new String[]{ "b", "h", "j", "l", "s", "y", "m", "n", "b", "ch", "h", "j", "l", "s", "y", "z", "m", "n", "b", "ch", "f", "g", "h", "j", "k", "l", "p", "s", "y", "z", "m", "n", "b", "ch", "d", "f", "g", "h", "j", "k", "l", "p", "s", "t", "y", "z", "m", "n", "kw", "b", "ch", "d", "f", "g", "h", "j", "k", "l", "p", "s", "t", "v", "w", "y", "z", "m", "n", "kw", "b", "h", "j", "l", "s", "y", "m", "n", "b", "ch", "h", "j", "l", "s", "y", "z", "m", "n", "b", "ch", "f", "g", "h", "j", "k", "l", "p", "s", "y", "z", "m", "n", "b", "ch", "d", "f", "g", "h", "j", "k", "l", "p", "s", "t", "y", "z", "m", "n", "kw", "b", "ch", "d", "f", "g", "h", "j", "k", "l", "p", "s", "t", "v", "w", "y", "z", "m", "n", "kw", "b", "h", "j", "l", "s", "y", "m", "n", "b", "ch", "h", "j", "l", "s", "y", "z", "m", "n", "b", "ch", "f", "g", "h", "j", "k", "l", "p", "s", "y", "z", "m", "n", "b", "ch", "d", "f", "g", "h", "j", "k", "l", "p", "s", "t", "y", "z", "m", "n", "kw", "b", "ch", "d", "f", "g", "h", "j", "k", "l", "p", "s", "t", "v", "w", "y", "z", "m", "n", "kw", "b", "h", "j", "l", "s", "y", "m", "n", "b", "ch", "h", "j", "l", "s", "y", "z", "m", "n", "b", "ch", "f", "g", "h", "j", "k", "l", "p", "s", "y", "z", "m", "n", "b", "ch", "d", "f", "g", "h", "j", "k", "l", "p", "s", "t", "y", "z", "m", "n", "kw", "b", "ch", "d", "f", "g", "h", "j", "k", "l", "p", "s", "t", "v", "w", "y", "z", "m", "n", "kw", "nb", "nj", "ns", "nz", "nb", "nch", "nj", "ns", "ny", "nz", "nb", "nch", "nf", "ng", "nj", "nk", "np", "ns", "nz", "nb", "nch", "nd", "nf", "ng", "nj", "nk", "np", "ns", "nt", "nz", "nb", "nch", "nd", "nf", "ng", "nj", "nk", "np", "ns", "nt", "nw", "nz", "mb", "ms", "my", "mz", "mb", "mch","ms", "my", "mz", "mb", "mch", "mk", "mp", "ms", "my", "mz", "mb", "mch", "md", "mk", "mp", "ms", "mt", "my", "mz", "mb", "mch", "md", "mf", "mg", "mj", "mk", "mp", "ms", "mt", "mw", "my", "mz", "sh", "sh", "sh", "ny", "kw", "dh", "th", "sh", "ny", "dh", "th", "sh", "gh", "r", "ny", "dh", "th", "sh", "gh", "r", "ny", "ng", "ng", "ng", "ng", "ng" }, new String[]{""}, new String[]{"a-@2a", "a-@2a", "a-@3a","a-@2a", "a-@2a", "a-@3a","i-@2i", "i-@2i", "i-@3i", "e-@2e", "e-@2e", "e-@3e", "u-@2u", "u-@2u", "u-@3u", }, new String[]{}, new int[]{1, 2, 3, 4, 5}, new double[]{1, 7, 6, 4, 2}, 0.2, 1.0, 0.0, 0.25, null, true); /** * Imitation Somali, using the Latin alphabet. Due to uncommon word structure, unusual allowed combinations of * letters, and no common word roots with most familiar languages, this may seem like an unidentifiable or "alien" * language to most readers. However, it's based on the Latin writing system for the Somali language (probably * closest to the northern dialect), which due to the previously mentioned properties, makes it especially good for * mixing with other languages to make letter combinations that seem strange to appear. It is unlikely that this * particular generated language style will be familiar to readers, so it probably won't have existing stereotypes * associated with the text. One early comment this received was, "it looks like a bunch of letters semi-randomly * thrown together", which is probably a typical response (the comment was made by someone fluent in German and * English, and most Western European languages are about as far as you can get from Somali). * <br> * Libor cat naqoxekh dhuugad gisiqir? */ public static final Finnegan SOMALI = new Finnegan( new String[]{"a", "a", "a", "a", "a", "a", "a", "aa", "aa", "aa", "e", "e", "ee", "i", "i", "i", "i", "ii", "o", "o", "o", "oo", "u", "u", "u", "uu", "uu", }, new String[]{}, new String[]{"b", "t", "j", "x", "kh", "d", "r", "s", "sh", "dh", "c", "g", "f", "q", "k", "l", "m", "n", "w", "h", "y", "x", "g", "b", "d", "s", "m", "dh", "n", "r", "g", "b", "s", "dh", }, new String[]{ "bb", "gg", "dd", "bb", "dd", "rr", "ddh", "cc", "gg", "ff", "ll", "mm", "nn", "bb", "gg", "dd", "bb", "dd", "gg", "bb", "gg", "dd", "bb", "dd", "gg", "cy", "fk", "ft", "nt", "rt", "lt", "qm", "rdh", "rsh", "lq", "my", "gy", "by", "lkh", "rx", "md", "bd", "dg", "fd", "mf", "dh", "dh", "dh", "dh", }, new String[]{ "b", "t", "j", "x", "kh", "d", "r", "s", "sh", "c", "g", "f", "q", "k", "l", "m", "n", "h", "x", "g", "b", "d", "s", "m", "q", "n", "r", "b", "t", "j", "x", "kh", "d", "r", "s", "sh", "c", "g", "f", "q", "k", "l", "m", "n", "h", "x", "g", "b", "d", "s", "m", "q", "n", "r", "b", "t", "j", "x", "kh", "d", "r", "s", "sh", "c", "g", "f", "q", "k", "l", "m", "n", "g", "b", "d", "s", "q", "n", "r", "b", "t", "x", "kh", "d", "r", "s", "sh", "g", "f", "q", "k", "l", "m", "n", "g", "b", "d", "s", "r", "n", "b", "t", "kh", "d", "r", "s", "sh", "g", "f", "q", "k", "l", "m", "n", "g", "b", "d", "s", "r", "n", "b", "t", "d", "r", "s", "sh", "g", "f", "q", "k", "l", "m", "n", "g", "b", "d", "s", "r", "n", }, new String[]{"aw", "ow", "ay", "ey", "oy", "ay", "ay"}, new String[]{}, new int[]{1, 2, 3, 4, 5}, new double[]{5, 4, 5, 4, 1}, 0.25, 0.3, 0.0, 0.08, null, true); /** * Imitation Hindi, romanized to use the Latin alphabet using accented glyphs similar to the IAST standard. * You can get this to produce actual IAST glyphs by calling removeModifiers() on this, but most fonts do not * support the glyphs that needs. If the modifier that does this is not removed, then the IAST standard glyphs * {@code "ṛṝḷḹḍṭṅṇṣṃḥ"} become {@code "ŗŕļĺđţńņşĕĭ"}, with the nth glyph in the first string being substituted * with the nth glyph in the second string. * <br> * Darvāga yar; ghađhinopŕauka āĕrdur, conśaigaijo śabhodhaĕđū jiviđaudu. */ public static final Finnegan HINDI_ROMANIZED = new Finnegan( new String[]{ "a", "a", "a", "a", "a", "a", "ā", "ā", "i", "i", "i", "i", "ī", "ī", "u", "u", "u", "ū", "e", "ai", "ai", "o", "o", "o", "au", "a", "a", "a", "a", "a", "a", "ā", "ā", "i", "i", "i", "i", "ī", "ī", "u", "u", "u", "ū", "e", "ai", "ai", "o", "o", "o", "au", "a", "a", "a", "a", "a", "a", "ā", "ā", "i", "i", "i", "i", "ī", "ī", "u", "u", "u", "ū", "e", "ai", "ai", "o", "o", "o", "au", "a", "a", "a", "a", "a", "a", "ā", "ā", "i", "i", "i", "i", "ī", "ī", "u", "u", "u", "ū", "e", "ai", "ai", "o", "o", "o", "au", "a", "a", "a", "a", "a", "a", "ā", "ā", "i", "i", "i", "i", "ī", "i", "i", "ī", "ī", "u", "u", "u", "ū", "u", "ū", "u", "ū", "e", "ai", "ai", "o", "o", "o", "au", "a", "a", "a", "a", "a", "a", "ā", "ā", "i", "i", "i", "i", "ī", "i", "i", "ī", "ī", "u", "u", "u", "ū", "u", "ū", "u", "ū", "e", "ai", "ai", "o", "o", "o", "au", "a", "a", "a", "a", "a", "a", "ā", "ā", "i", "i", "i", "i", "ī", "i", "i", "ī", "ī", "u", "u", "u", "ū", "u", "ū", "u", "ū", "e", "ai", "ai", "o", "o", "o", "au", "a", "a", "a", "a", "a", "a", "ā", "ā", "i", "i", "i", "i", "ī", "i", "i", "ī", "ī", "u", "u", "u", "ū", "u", "ū", "u", "ū", "e", "ai", "ai", "o", "o", "o", "au", "aṃ", "aṃ", "aṃ", "aṃ", "aṃ", "āṃ", "āṃ", "iṃ", "iṃ", "iṃ", "īṃ", "īṃ", "uṃ", "uṃ", "ūṃ", "aiṃ", "aiṃ", "oṃ", "oṃ", "oṃ", "auṃ", //"aḥ", "aḥ", "aḥ", "aḥ", "aḥ", "āḥ", "āḥ", "iḥ", "iḥ", "iḥ", "īḥ", "īḥ", //"uḥ", "uḥ", "ūḥ", "aiḥ", "aiḥ", "oḥ", "oḥ", "oḥ", "auḥ", }, new String[]{"a'","i'","u'", "o'", "a'","i'","u'", "o'", }, new String[]{ "k", "k", "k", "k", "k", "k", "k", "k", "kṛ", "kṝ", "kḷ", "c", "c", "c", "c", "c", "c", "cṛ", "cṝ", "cḷ", "ṭ", "t", "t", "t", "t", "t", "t", "t", "t", "t", "tṛ", "tṝ", "tṛ", "tṝ", "p", "p", "p", "p", "p", "p", "p", "p", "p", "p", "pṛ", "pṝ", "pḷ", "pḹ", "pṛ", "pṝ", "p", "p", "kh", "kh", "kh", "kh", "kh", "kh", "kh", "kh", "kh", "kh", "khṛ", "khṝ", "khḷ", "khḹ", "ch", "ch", "ch", "ch", "ch", "ch", "ch", "ch", "ch", "chṛ", "chṝ", "chḷ", "chḹ", "ṭh", "th", "th", "th", "th", "th", "th", "th", "th", "th", "thṛ", "thṝ", "thḷ", "thḹ", "ph", "ph", "ph", "ph", "ph", "ph", "ph", "phṛ", "phṝ", "phḷ", "phḹ", "g", "j", "ḍ", "d", "b", "gh", "jh", "ḍh", "dh", "bh", "ṅ", "ñ", "ṇ", "n", "m", "h", "y", "r", "l", "v", "ś", "ṣ", "s", "g", "j", "ḍ", "d", "b", "gh", "jh", "ḍh", "dh", "bh", "ṅ", "ñ", "ṇ", "n", "m", "h", "y", "r", "l", "v", "ś", "ṣ", "s", "g", "j", "ḍ", "d", "b", "gh", "jh", "ḍh", "dh", "bh", "ṅ", "ñ", "ṇ", "n", "m", "h", "y", "r", "l", "v", "ś", "ṣ", "s", "g", "j", "ḍ", "d", "b", "gh", "jh", "ḍh", "dh", "bh", "ṅ", "ñ", "ṇ", "n", "m", "h", "y", "r", "l", "v", "ś", "ṣ", "s", "g", "j", "ḍ", "d", "b", "gh", "jh", "ḍh", "dh", "bh", "ṅ", "ñ", "ṇ", "n", "m", "h", "y", "r", "l", "v", "ś", "ṣ", "s", "g", "j", "ḍ", "d", "b", "gh", "jh", "ḍh", "dh", "bh", "ṅ", "ñ", "ṇ", "n", "m", "h", "y", "r", "l", "v", "ś", "ṣ", "s", "g", "j", "ḍ", "d", "b", "gh", "jh", "ḍh", "dh", "bh", "ṅ", "ñ", "ṇ", "n", "m", "h", "y", "r", "l", "v", "ś", "ṣ", "s", "g", "j", "ḍ", "d", "b", "gh", "ḍh", "dh", "bh", "ṅ", "ñ", "ṇ", "n", "m", "h", "y", "r", "l", "v", "ś", "ṣ", "s", "g", "j", "ḍ", "d", "b", "gh", "ḍh", "dh", "bh", "ṅ", "ṇ", "n", "m", "h", "y", "r", "l", "v", "ṣ", "s", "g", "j", "ḍ", "d", "b", "gh", "ḍh", "dh", "bh", "ṅ", "ṇ", "n", "m", "h", "y", "r", "l", "v", "ṣ", "s", "g", "ḍ", "d", "b", "gh", "ḍh", "dh", "bh", "n", "m", "v", "s", "g", "ḍ", "d", "b", "g", "d", "b", "dh", "bh", "n", "m", "v", "g", "ḍ", "d", "b", "g", "d", "b", "dh", "bh", "n", "m", "v", }, new String[]{ "k", "k", "k", "k", "k", "nk", "rk", "k", "k", "k", "k", "k", "nk", "rk", "k", "k", "k", "k", "k", "nk", "rk", "k", "k", "k", "k", "k", "nk", "rk", "k", "k", "k", "k", "k", "nk", "rk", "k", "k", "k", "k", "k", "nk", "rk", "k", "k", "k", "k", "k", "nk", "rk", "k", "k", "k", "k", "k", "nk", "rk", "kṛ", "kṛ", "kṛ", "kṛ", "kṛ", "nkṛ", "rkṛ", "kṝ", "kṝ", "kṝ", "kṝ", "kṝ", "nkṝ", "rkṝ", "kḷ", "kḷ", "kḷ", "kḷ", "kḷ", "nkḷ", "rkḷ", "c", "c", "c", "c", "c", "c", "cṛ", "cṝ", "cḷ", "ṭ", "t", "t", "t", "t", "t", "nt", "rt", "ṭ", "t", "t", "t", "t", "nt", "rt", "ṭ", "t", "t", "t", "t", "nt", "rt", "ṭ", "t", "t", "t", "t", "nt", "rt", "ṭ", "t", "t", "t", "t", "nt", "rt", "ṭ", "t", "t", "t", "t", "nt", "rt", "ṭ", "t", "t", "t", "t", "nt", "rt", "ṭ", "t", "t", "t", "t", "nt", "rt", "ṭ", "t", "t", "t", "t", "nt", "rt", "tṛ", "tṛ", "tṛ", "tṛ", "tṛ", "ntṛ", "rtṛ", "tṝ", "tṝ", "tṝ", "tṝ", "tṝ", "ntṝ", "rtṝ", "tṛ", "tṛ", "tṛ", "tṛ", "tṛ", "ntṛ", "rtṛ", "tṝ", "tṝ", "tṝ", "tṝ", "tṝ", "ntṝ", "rtṝ", "p", "p", "p", "p", "p", "np", "rp", "p", "p", "p", "p", "p", "np", "rp", "p", "p", "p", "p", "p", "np", "rp", "p", "p", "p", "p", "p", "np", "rp", "p", "p", "p", "p", "p", "np", "rp", "p", "p", "p", "p", "p", "np", "rp", "p", "p", "p", "p", "p", "np", "rp", "p", "p", "p", "p", "p", "np", "rp", "p", "p", "p", "p", "p", "np", "rp", "p", "p", "p", "p", "p", "np", "rp", "pṛ", "pṛ", "pṛ", "pṛ", "pṛ", "npṛ", "rpṛ", "pṝ", "pṝ", "pṝ", "pṝ", "pṝ", "npṝ", "rpṝ", "pḷ", "pḷ", "pḷ", "pḷ", "pḷ", "npḷ", "rpḷ", "pḹ", "pḹ", "pḹ", "pḹ", "pḹ", "npḹ", "rpḹ", "pṛ", "pṛ", "pṛ", "pṛ", "pṛ", "npṛ", "rpṛ", "pṝ", "pṝ", "pṝ", "pṝ", "pṝ", "npṝ", "rpṝ", "p", "p", "p", "p", "p", "np", "rp", "p", "p", "p", "p", "p", "np", "rp", "kh", "kh", "kh", "kh", "kh", "nkh", "rkh", "kh", "kh", "kh", "kh", "kh", "nkh", "rkh", "kh", "kh", "kh", "kh", "kh", "nkh", "rkh", "kh", "kh", "kh", "kh", "kh", "nkh", "rkh", "kh", "kh", "kh", "kh", "kh", "nkh", "rkh", "kh", "kh", "kh", "kh", "kh", "nkh", "rkh", "kh", "kh", "kh", "kh", "kh", "nkh", "rkh", "kh", "kh", "kh", "kh", "kh", "nkh", "rkh", "kh", "kh", "kh", "kh", "kh", "nkh", "rkh", "kh", "kh", "kh", "kh", "kh", "nkh", "rkh", "khṛ", "khṛ", "khṛ", "khṛ", "khṛ", "nkhṛ", "rkhṛ", "khṝ", "khṝ", "khṝ", "khṝ", "khṝ", "nkhṝ", "rkhṝ", "khḷ", "khḷ", "khḷ", "khḷ", "khḷ", "nkhḷ", "rkhḷ", "khḹ", "khḹ", "khḹ", "khḹ", "khḹ", "nkhḹ", "rkhḹ", "ch", "ch", "ch", "ch", "ch", "ch", "ch", "ch", "ch", "chṛ", "chṝ", "chḷ", "chḹ", "ṭh", "th", "th", "th", "th", "th", "nth", "rth", "th", "th", "th", "th", "th", "nth", "rth", "th", "th", "th", "th", "th", "nth", "rth", "th", "th", "th", "th", "th", "nth", "rth", "th", "th", "th", "th", "th", "nth", "rth", "th", "th", "th", "th", "th", "nth", "rth", "th", "th", "th", "th", "th", "nth", "rth", "th", "th", "th", "th", "th", "nth", "rth", "th", "th", "th", "th", "th", "nth", "rth", "thṛ", "thṛ", "thṛ", "thṛ", "thṛ", "nthṛ", "rthṛ", "thṝ", "thṝ", "thṝ", "thṝ", "thṝ", "nthṝ", "rthṝ", "thḷ", "thḷ", "thḷ", "thḷ", "thḷ", "nthḷ", "rthḷ", "thḹ", "thḹ", "thḹ", "thḹ", "thḹ", "nthḹ", "rthḹ", "ph", "ph", "ph", "ph", "ph", "nph", "rph", "ph", "ph", "ph", "ph", "ph", "nph", "rph", "ph", "ph", "ph", "ph", "ph", "nph", "rph", "ph", "ph", "ph", "ph", "ph", "nph", "rph", "ph", "ph", "ph", "ph", "ph", "nph", "rph", "ph", "ph", "ph", "ph", "ph", "nph", "rph", "ph", "ph", "ph", "ph", "ph", "nph", "rph", "phṛ", "phṛ", "phṛ", "phṛ", "phṛ", "nphṛ", "rphṛ", "phṝ", "phṝ", "phṝ", "phṝ", "phṝ", "nphṝ", "rphṝ", "phḷ", "phḷ", "phḷ", "phḷ", "phḷ", "nphḷ", "rphḷ", "phḹ", "phḹ", "phḹ", "phḹ", "phḹ", "nphḹ", "rphḹ", "g", "g", "g", "g", "g", "ng", "rg", "j", "j", "j", "j", "j", "nj", "rj", "ḍ", "ḍ", "ḍ", "ḍ", "ḍ", "nḍ", "rḍ", "d", "d", "d", "d", "d", "nd", "rd", "b", "b", "b", "b", "b", "nb", "rb", "gh", "gh", "gh", "gh", "gh", "ngh", "rgh", "jh", "ḍh", "ḍh", "ḍh", "ḍh", "ḍh", "nḍh", "rḍh", "dh", "dh", "dh", "dh", "dh", "ndh", "rdh", "bh", "bh", "bh", "bh", "bh", "nbh", "rbh", "ṅ", "ñ", "ṇ", "n", "m", "m", "m", "m", "m", "nm", "rm", "h", "y", "y", "y", "y", "y", "ny", "ry", "r", "l", "v", "v", "v", "v", "v", "nv", "rv", "ś", "ś", "ś", "ś", "ś", "nś", "rś", "ṣ", "ṣ", "ṣ", "ṣ", "ṣ", "nṣ", "rṣ", "s", "s", "s", "s", "s", "ns", "rs", "g", "g", "g", "g", "g", "ng", "rg", "j", "j", "j", "j", "j", "nj", "rj", "ḍ", "ḍ", "ḍ", "ḍ", "ḍ", "nḍ", "rḍ", "d", "d", "d", "d", "d", "nd", "rd", "b", "b", "b", "b", "b", "nb", "rb", "gh", "gh", "gh", "gh", "gh", "ngh", "rgh", "jh", "ḍh", "ḍh", "ḍh", "ḍh", "ḍh", "nḍh", "rḍh", "dh", "dh", "dh", "dh", "dh", "ndh", "rdh", "bh", "bh", "bh", "bh", "bh", "nbh", "rbh", "ṅ", "ñ", "ṇ", "n", "m", "m", "m", "m", "m", "nm", "rm", "h", "y", "y", "y", "y", "y", "ny", "ry", "r", "l", "v", "v", "v", "v", "v", "nv", "rv", "ś", "ś", "ś", "ś", "ś", "nś", "rś", "ṣ", "ṣ", "ṣ", "ṣ", "ṣ", "nṣ", "rṣ", "s", "s", "s", "s", "s", "ns", "rs", "g", "g", "g", "g", "g", "ng", "rg", "j", "j", "j", "j", "j", "nj", "rj", "ḍ", "ḍ", "ḍ", "ḍ", "ḍ", "nḍ", "rḍ", "d", "d", "d", "d", "d", "nd", "rd", "b", "b", "b", "b", "b", "nb", "rb", "gh", "gh", "gh", "gh", "gh", "ngh", "rgh", "jh", "ḍh", "ḍh", "ḍh", "ḍh", "ḍh", "nḍh", "rḍh", "dh", "dh", "dh", "dh", "dh", "ndh", "rdh", "bh", "bh", "bh", "bh", "bh", "nbh", "rbh", "ṅ", "ñ", "ṇ", "n", "m", "m", "m", "m", "m", "nm", "rm", "h", "y", "y", "y", "y", "y", "ny", "ry", "r", "l", "v", "v", "v", "v", "v", "nv", "rv", "ś", "ś", "ś", "ś", "ś", "nś", "rś", "ṣ", "ṣ", "ṣ", "ṣ", "ṣ", "nṣ", "rṣ", "s", "s", "s", "s", "s", "ns", "rs", "g", "g", "g", "g", "g", "ng", "rg", "j", "j", "j", "j", "j", "nj", "rj", "ḍ", "ḍ", "ḍ", "ḍ", "ḍ", "nḍ", "rḍ", "d", "d", "d", "d", "d", "nd", "rd", "b", "b", "b", "b", "b", "nb", "rb", "gh", "gh", "gh", "gh", "gh", "ngh", "rgh", "jh", "ḍh", "ḍh", "ḍh", "ḍh", "ḍh", "nḍh", "rḍh", "dh", "dh", "dh", "dh", "dh", "ndh", "rdh", "bh", "bh", "bh", "bh", "bh", "nbh", "rbh", "ṅ", "ñ", "ṇ", "n", "m", "m", "m", "m", "m", "nm", "rm", "h", "y", "y", "y", "y", "y", "ny", "ry", "r", "l", "v", "v", "v", "v", "v", "nv", "rv", "ś", "ś", "ś", "ś", "ś", "nś", "rś", "ṣ", "ṣ", "ṣ", "ṣ", "ṣ", "nṣ", "rṣ", "s", "s", "s", "s", "s", "ns", "rs", "g", "g", "g", "g", "g", "ng", "rg", "j", "j", "j", "j", "j", "nj", "rj", "ḍ", "ḍ", "ḍ", "ḍ", "ḍ", "nḍ", "rḍ", "d", "d", "d", "d", "d", "nd", "rd", "b", "b", "b", "b", "b", "nb", "rb", "gh", "gh", "gh", "gh", "gh", "ngh", "rgh", "jh", "ḍh", "ḍh", "ḍh", "ḍh", "ḍh", "nḍh", "rḍh", "dh", "dh", "dh", "dh", "dh", "ndh", "rdh", "bh", "bh", "bh", "bh", "bh", "nbh", "rbh", "ṅ", "ñ", "ṇ", "n", "m", "m", "m", "m", "m", "nm", "rm", "h", "y", "y", "y", "y", "y", "ny", "ry", "r", "l", "v", "v", "v", "v", "v", "nv", "rv", "ś", "ś", "ś", "ś", "ś", "nś", "rś", "ṣ", "ṣ", "ṣ", "ṣ", "ṣ", "nṣ", "rṣ", "s", "s", "s", "s", "s", "ns", "rs", "g", "g", "g", "g", "g", "ng", "rg", "j", "j", "j", "j", "j", "nj", "rj", "ḍ", "ḍ", "ḍ", "ḍ", "ḍ", "nḍ", "rḍ", "d", "d", "d", "d", "d", "nd", "rd", "b", "b", "b", "b", "b", "nb", "rb", "gh", "gh", "gh", "gh", "gh", "ngh", "rgh", "jh", "ḍh", "ḍh", "ḍh", "ḍh", "ḍh", "nḍh", "rḍh", "dh", "dh", "dh", "dh", "dh", "ndh", "rdh", "bh", "bh", "bh", "bh", "bh", "nbh", "rbh", "ṅ", "ñ", "ṇ", "n", "m", "m", "m", "m", "m", "nm", "rm", "h", "y", "y", "y", "y", "y", "ny", "ry", "r", "l", "v", "v", "v", "v", "v", "nv", "rv", "ś", "ś", "ś", "ś", "ś", "nś", "rś", "ṣ", "ṣ", "ṣ", "ṣ", "ṣ", "nṣ", "rṣ", "s", "s", "s", "s", "s", "ns", "rs", "g", "g", "g", "g", "g", "ng", "rg", "j", "j", "j", "j", "j", "nj", "rj", "ḍ", "ḍ", "ḍ", "ḍ", "ḍ", "nḍ", "rḍ", "d", "d", "d", "d", "d", "nd", "rd", "b", "b", "b", "b", "b", "nb", "rb", "gh", "gh", "gh", "gh", "gh", "ngh", "rgh", "jh", "ḍh", "ḍh", "ḍh", "ḍh", "ḍh", "nḍh", "rḍh", "dh", "dh", "dh", "dh", "dh", "ndh", "rdh", "bh", "bh", "bh", "bh", "bh", "nbh", "rbh", "ṅ", "ñ", "ṇ", "n", "m", "m", "m", "m", "m", "nm", "rm", "h", "y", "y", "y", "y", "y", "ny", "ry", "r", "l", "v", "v", "v", "v", "v", "nv", "rv", "ś", "ś", "ś", "ś", "ś", "nś", "rś", "ṣ", "ṣ", "ṣ", "ṣ", "ṣ", "nṣ", "rṣ", "s", "s", "s", "s", "s", "ns", "rs", "g", "g", "g", "g", "g", "ng", "rg", "j", "j", "j", "j", "j", "nj", "rj", "ḍ", "ḍ", "ḍ", "ḍ", "ḍ", "nḍ", "rḍ", "d", "d", "d", "d", "d", "nd", "rd", "b", "b", "b", "b", "b", "nb", "rb", "gh", "gh", "gh", "gh", "gh", "ngh", "rgh", "ḍh", "ḍh", "ḍh", "ḍh", "ḍh", "nḍh", "rḍh", "dh", "dh", "dh", "dh", "dh", "ndh", "rdh", "bh", "bh", "bh", "bh", "bh", "nbh", "rbh", "ṅ", "ñ", "ṇ", "n", "m", "m", "m", "m", "m", "nm", "rm", "h", "y", "y", "y", "y", "y", "ny", "ry", "r", "l", "v", "v", "v", "v", "v", "nv", "rv", "ś", "ś", "ś", "ś", "ś", "nś", "rś", "ṣ", "ṣ", "ṣ", "ṣ", "ṣ", "nṣ", "rṣ", "s", "s", "s", "s", "s", "ns", "rs", "g", "g", "g", "g", "g", "ng", "rg", "j", "j", "j", "j", "j", "nj", "rj", "ḍ", "ḍ", "ḍ", "ḍ", "ḍ", "nḍ", "rḍ", "d", "d", "d", "d", "d", "nd", "rd", "b", "b", "b", "b", "b", "nb", "rb", "gh", "gh", "gh", "gh", "gh", "ngh", "rgh", "ḍh", "ḍh", "ḍh", "ḍh", "ḍh", "nḍh", "rḍh", "dh", "dh", "dh", "dh", "dh", "ndh", "rdh", "bh", "bh", "bh", "bh", "bh", "nbh", "rbh", "ṅ", "ṇ", "n", "m", "m", "m", "m", "m", "nm", "rm", "h", "y", "y", "y", "y", "y", "ny", "ry", "r", "l", "v", "v", "v", "v", "v", "nv", "rv", "ṣ", "ṣ", "ṣ", "ṣ", "ṣ", "nṣ", "rṣ", "s", "s", "s", "s", "s", "ns", "rs", "g", "g", "g", "g", "g", "ng", "rg", "j", "j", "j", "j", "j", "nj", "rj", "ḍ", "ḍ", "ḍ", "ḍ", "ḍ", "nḍ", "rḍ", "d", "d", "d", "d", "d", "nd", "rd", "b", "b", "b", "b", "b", "nb", "rb", "gh", "gh", "gh", "gh", "gh", "ngh", "rgh", "ḍh", "ḍh", "ḍh", "ḍh", "ḍh", "nḍh", "rḍh", "dh", "dh", "dh", "dh", "dh", "ndh", "rdh", "bh", "bh", "bh", "bh", "bh", "nbh", "rbh", "ṅ", "ṇ", "n", "m", "m", "m", "m", "m", "nm", "rm", "h", "y", "y", "y", "y", "y", "ny", "ry", "r", "l", "v", "v", "v", "v", "v", "nv", "rv", "ṣ", "ṣ", "ṣ", "ṣ", "ṣ", "nṣ", "rṣ", "s", "s", "s", "s", "s", "ns", "rs", "g", "g", "g", "g", "g", "ng", "rg", "ḍ", "ḍ", "ḍ", "ḍ", "ḍ", "nḍ", "rḍ", "d", "d", "d", "d", "d", "nd", "rd", "b", "b", "b", "b", "b", "nb", "rb", "gh", "gh", "gh", "gh", "gh", "ngh", "rgh", "ḍh", "ḍh", "ḍh", "ḍh", "ḍh", "nḍh", "rḍh", "dh", "dh", "dh", "dh", "dh", "ndh", "rdh", "bh", "bh", "bh", "bh", "bh", "nbh", "rbh", "n", "m", "m", "m", "m", "m", "nm", "rm", "v", "v", "v", "v", "v", "nv", "rv", "s", "s", "s", "s", "s", "ns", "rs", "g", "g", "g", "g", "g", "ng", "rg", "ḍ", "ḍ", "ḍ", "ḍ", "ḍ", "nḍ", "rḍ", "d", "d", "d", "d", "d", "nd", "rd", "b", "b", "b", "b", "b", "nb", "rb", "g", "g", "g", "g", "g", "ng", "rg", "d", "d", "d", "d", "d", "nd", "rd", "b", "b", "b", "b", "b", "nb", "rb", "dh", "dh", "dh", "dh", "dh", "ndh", "rdh", "bh", "bh", "bh", "bh", "bh", "nbh", "rbh", "n", "m", "m", "m", "m", "m", "nm", "rm", "v", "v", "v", "v", "v", "nv", "rv", "g", "g", "g", "g", "g", "ng", "rg", "ḍ", "ḍ", "ḍ", "ḍ", "ḍ", "nḍ", "rḍ", "d", "d", "d", "d", "d", "nd", "rd", "b", "b", "b", "b", "b", "nb", "rb", "g", "g", "g", "g", "g", "ng", "rg", "d", "d", "d", "d", "d", "nd", "rd", "b", "b", "b", "b", "b", "nb", "rb", "dh", "dh", "dh", "dh", "dh", "ndh", "rdh", "bh", "bh", "bh", "bh", "bh", "nbh", "rbh", "n", "m", "m", "m", "m", "m", "nm", "rm", "v", "v", "v", "v", "v", "nv", "rv", }, new String[]{"t", "d", "m", "r", "dh", "b", "t", "d", "m", "r", "dh", "bh", "nt", "nt", "nk", "ṣ"}, new String[]{"it", "it", "ati", "adva", "aṣ", "arma", "ardha", "abi", "ab", "aya"}, new String[]{}, new int[]{1, 2, 3, 4, 5}, new double[]{1, 2, 3, 3, 1}, 0.15, 0.75, 0.0, 0.12, null, true) .addModifiers(Modifier.replacementTable("ṛṝḷḹḍṭṅṇṣṃḥ", "ŗŕļĺđţńņşĕĭ")); /** * A mix of four different languages, using only ASCII characters, that is meant for generating single words for * creature or place names in fantasy settings. * <br> * Adeni, Sainane, Caneros, Sune, Alade, Tidifi, Muni, Gito, Lixoi, Bovi... */ public static final Finnegan FANTASY_NAME = GREEK_ROMANIZED.mix( RUSSIAN_ROMANIZED.mix( FRENCH.removeAccents().mix( JAPANESE_ROMANIZED, 0.5), 0.85), 0.925); /** * A mix of four different languages with some accented characters added onto an ASCII base, that can be good for * generating single words for creature or place names in fantasy settings that should have a "fancy" feeling from * having unnecessary accents added primarily for visual reasons. * <br> * Askieno, Blarcīnũn, Mēmida, Zizhounkô, Blęrinaf, Zemĭ, Mónazôr, Renerstă, Uskus, Toufounôr... */ public static final Finnegan FANCY_FANTASY_NAME = FANTASY_NAME.addAccents(0.47, 0.07); /** * Zero-arg constructor for a Finnegan; produces a Finnegan equivalent to Finnegan.ENGLISH . */ public Finnegan() { this( new String[]{ "a", "a", "a", "a", "o", "o", "o", "e", "e", "e", "e", "e", "i", "i", "i", "i", "u", "a", "a", "a", "a", "o", "o", "o", "e", "e", "e", "e", "e", "i", "i", "i", "i", "u", "a", "a", "a", "o", "o", "e", "e", "e", "i", "i", "i", "u", "a", "a", "a", "o", "o", "e", "e", "e", "i", "i", "i", "u", "au", "ai", "ai", "ou", "ea", "ie", "io", "ei", }, new String[]{"u", "u", "oa", "oo", "oo", "oo", "ee", "ee", "ee", "ee",}, new String[]{ "b", "bl", "br", "c", "cl", "cr", "ch", "d", "dr", "f", "fl", "fr", "g", "gl", "gr", "h", "j", "k", "l", "m", "n", "p", "pl", "pr", "qu", "r", "s", "sh", "sk", "st", "sp", "sl", "sm", "sn", "t", "tr", "th", "thr", "v", "w", "y", "z", "b", "bl", "br", "c", "cl", "cr", "ch", "d", "dr", "f", "fl", "fr", "g", "gr", "h", "j", "k", "l", "m", "n", "p", "pl", "pr", "r", "s", "sh", "st", "sp", "sl", "t", "tr", "th", "w", "y", "b", "br", "c", "ch", "d", "dr", "f", "g", "h", "j", "l", "m", "n", "p", "r", "s", "sh", "st", "sl", "t", "tr", "th", "b", "d", "f", "g", "h", "l", "m", "n", "p", "r", "s", "sh", "t", "th", "b", "d", "f", "g", "h", "l", "m", "n", "p", "r", "s", "sh", "t", "th", "r", "s", "t", "l", "n", "str", "spr", "spl", "wr", "kn", "kn", "gn", }, new String[]{"x", "cst", "bs", "ff", "lg", "g", "gs", "ll", "ltr", "mb", "mn", "mm", "ng", "ng", "ngl", "nt", "ns", "nn", "ps", "mbl", "mpr", "pp", "ppl", "ppr", "rr", "rr", "rr", "rl", "rtn", "ngr", "ss", "sc", "rst", "tt", "tt", "ts", "ltr", "zz" }, new String[]{"b", "rb", "bb", "c", "rc", "ld", "d", "ds", "dd", "f", "ff", "lf", "rf", "rg", "gs", "ch", "lch", "rch", "tch", "ck", "ck", "lk", "rk", "l", "ll", "lm", "m", "rm", "mp", "n", "nk", "nch", "nd", "ng", "ng", "nt", "ns", "lp", "rp", "p", "r", "rn", "rts", "s", "s", "s", "s", "ss", "ss", "st", "ls", "t", "t", "ts", "w", "wn", "x", "ly", "lly", "z", "b", "c", "d", "f", "g", "k", "l", "m", "n", "p", "r", "s", "t", "w", }, new String[]{"ate", "ite", "ism", "ist", "er", "er", "er", "ed", "ed", "ed", "es", "es", "ied", "y", "y", "y", "y", "ate", "ite", "ism", "ist", "er", "er", "er", "ed", "ed", "ed", "es", "es", "ied", "y", "y", "y", "y", "ate", "ite", "ism", "ist", "er", "er", "er", "ed", "ed", "ed", "es", "es", "ied", "y", "y", "y", "y", "ay", "ay", "ey", "oy", "ay", "ay", "ey", "oy", "ough", "aught", "ant", "ont", "oe", "ance", "ell", "eal", "oa", "urt", "ut", "iom", "ion", "ion", "ision", "ation", "ation", "ition", "ough", "aught", "ant", "ont", "oe", "ance", "ell", "eal", "oa", "urt", "ut", "iom", "ion", "ion", "ision", "ation", "ation", "ition", "ily", "ily", "ily", "adly", "owly", "oorly", "ardly", "iedly", }, new String[]{}, new int[]{1, 2, 3, 4}, new double[]{7, 8, 4, 1}, 0.22, 0.1, 0.0, 0.25, englishSanityChecks, true); } /** * This is a very complicated constructor! Maybe look at the calls to this to initialize static members of this * class, LOVECRAFT and GREEK_ROMANIZED. * * @param openingVowels String array where each element is a vowel or group of vowels that may appear at the start * of a word or in the middle; elements may be repeated to make them more common * @param midVowels String array where each element is a vowel or group of vowels that may appear in the * middle of the word; all openingVowels are automatically copied into this internally. * Elements may be repeated to make them more common * @param openingConsonants String array where each element is a consonant or consonant cluster that can appear * at the start of a word; elements may be repeated to make them more common * @param midConsonants String array where each element is a consonant or consonant cluster than can appear * between vowels; all closingConsonants are automatically copied into this internally. * Elements may be repeated to make them more common * @param closingConsonants String array where each element is a consonant or consonant cluster than can appear * at the end of a word; elements may be repeated to make them more common * @param closingSyllables String array where each element is a syllable starting with a vowel and ending in * whatever the word should end in; elements may be repeated to make them more common * @param vowelSplitters String array where each element is a mark that goes between vowels, so if "-" is in this, * then "a-a" may be possible; elements may be repeated to make them more common * @param syllableLengths int array where each element is a possible number of syllables a word can use; closely * tied to syllableFrequencies * @param syllableFrequencies double array where each element corresponds to an element in syllableLengths and * represents how often each syllable count should appear relative to other counts; there * is no need to restrict the numbers to add up to any other number * @param vowelStartFrequency a double between 0.0 and 1.0 that determines how often words start with vowels; * higher numbers yield more words starting with vowels * @param vowelEndFrequency a double between 0.0 and 1.0 that determines how often words end with vowels; higher * numbers yield more words ending in vowels * @param vowelSplitFrequency a double between 0.0 and 1.0 that, if vowelSplitters is not empty, determines how * often a vowel will be split into two vowels separated by one of those splitters * @param syllableEndFrequency a double between 0.0 and 1.0 that determines how often an element of * closingSyllables is used instead of ending normally */ public Finnegan(String[] openingVowels, String[] midVowels, String[] openingConsonants, String[] midConsonants, String[] closingConsonants, String[] closingSyllables, String[] vowelSplitters, int[] syllableLengths, double[] syllableFrequencies, double vowelStartFrequency, double vowelEndFrequency, double vowelSplitFrequency, double syllableEndFrequency) { this(openingVowels, midVowels, openingConsonants, midConsonants, closingConsonants, closingSyllables, vowelSplitters, syllableLengths, syllableFrequencies, vowelStartFrequency, vowelEndFrequency, vowelSplitFrequency, syllableEndFrequency, englishSanityChecks, true); } /** * This is a very complicated constructor! Maybe look at the calls to this to initialize static members of this * class, LOVECRAFT and GREEK_ROMANIZED. * * @param openingVowels String array where each element is a vowel or group of vowels that may appear at the start * of a word or in the middle; elements may be repeated to make them more common * @param midVowels String array where each element is a vowel or group of vowels that may appear in the * middle of the word; all openingVowels are automatically copied into this internally. * Elements may be repeated to make them more common * @param openingConsonants String array where each element is a consonant or consonant cluster that can appear * at the start of a word; elements may be repeated to make them more common * @param midConsonants String array where each element is a consonant or consonant cluster than can appear * between vowels; all closingConsonants are automatically copied into this internally. * Elements may be repeated to make them more common * @param closingConsonants String array where each element is a consonant or consonant cluster than can appear * at the end of a word; elements may be repeated to make them more common * @param closingSyllables String array where each element is a syllable starting with a vowel and ending in * whatever the word should end in; elements may be repeated to make them more common * @param vowelSplitters String array where each element is a mark that goes between vowels, so if "-" is in this, * then "a-a" may be possible; elements may be repeated to make them more common * @param syllableLengths int array where each element is a possible number of syllables a word can use; closely * tied to syllableFrequencies * @param syllableFrequencies double array where each element corresponds to an element in syllableLengths and * represents how often each syllable count should appear relative to other counts; there * is no need to restrict the numbers to add up to any other number * @param vowelStartFrequency a double between 0.0 and 1.0 that determines how often words start with vowels; * higher numbers yield more words starting with vowels * @param vowelEndFrequency a double between 0.0 and 1.0 that determines how often words end with vowels; higher * numbers yield more words ending in vowels * @param vowelSplitFrequency a double between 0.0 and 1.0 that, if vowelSplitters is not empty, determines how * often a vowel will be split into two vowels separated by one of those splitters * @param syllableEndFrequency a double between 0.0 and 1.0 that determines how often an element of * closingSyllables is used instead of ending normally * @param sane true to perform sanity checks for pronounce-able sounds to most English speakers, replacing many * words that are impossible to say; slows down generation slightly, irrelevant for non-Latin alphabets * @param clean true to perform vulgarity/obscenity checks on the word, replacing it if it is too close to a * common English vulgarity, obscenity, or slur/epithet; slows down generation slightly */ public Finnegan(String[] openingVowels, String[] midVowels, String[] openingConsonants, String[] midConsonants, String[] closingConsonants, String[] closingSyllables, String[] vowelSplitters, int[] syllableLengths, double[] syllableFrequencies, double vowelStartFrequency, double vowelEndFrequency, double vowelSplitFrequency, double syllableEndFrequency, Pattern[] sane, boolean clean) { rng = new RNG(hash64(openingVowels, midVowels, openingConsonants, midConsonants, closingConsonants, closingSyllables, vowelSplitters) ^ hash64(syllableLengths) ^ (hash64(syllableFrequencies) << 31) ^ Double.doubleToLongBits(vowelStartFrequency + 19.0 * (vowelEndFrequency + 19.0 * (vowelSplitFrequency + 19.0 * syllableEndFrequency)))); this.openingVowels = openingVowels; this.midVowels = new String[openingVowels.length + midVowels.length]; System.arraycopy(midVowels, 0, this.midVowels, 0, midVowels.length); System.arraycopy(openingVowels, 0, this.midVowels, midVowels.length, openingVowels.length); this.openingConsonants = openingConsonants; this.midConsonants = new String[midConsonants.length + closingConsonants.length]; System.arraycopy(midConsonants, 0, this.midConsonants, 0, midConsonants.length); System.arraycopy(closingConsonants, 0, this.midConsonants, midConsonants.length, closingConsonants.length); this.closingConsonants = closingConsonants; this.vowelSplitters = vowelSplitters; this.closingSyllables = closingSyllables; this.syllableFrequencies = new LinkedHashMap<Integer, Double>(syllableLengths.length); for (int i = 0; i < syllableLengths.length && i < syllableFrequencies.length; i++) { this.syllableFrequencies.put(syllableLengths[i], syllableFrequencies[i]); } for (Double freq : this.syllableFrequencies.values()) { totalSyllableFrequency += freq; } if (vowelStartFrequency > 1.0) this.vowelStartFrequency = 1.0 / vowelStartFrequency; else this.vowelStartFrequency = vowelStartFrequency; if (vowelEndFrequency > 1.0) this.vowelEndFrequency = 1.0 / vowelEndFrequency; else this.vowelEndFrequency = vowelEndFrequency; if (vowelSplitters.length == 0) this.vowelSplitFrequency = 0.0; else if (vowelSplitFrequency > 1.0) this.vowelSplitFrequency = 1.0 / vowelSplitFrequency; else this.vowelSplitFrequency = vowelSplitFrequency; if (closingSyllables.length == 0) this.syllableEndFrequency = 0.0; else if (syllableEndFrequency > 1.0) this.syllableEndFrequency = 1.0 / syllableEndFrequency; else this.syllableEndFrequency = syllableEndFrequency; this.clean = clean; this.sanityChecks = sane; modifiers = new ArrayList<Modifier>(16); } private Finnegan(String[] openingVowels, String[] midVowels, String[] openingConsonants, String[] midConsonants, String[] closingConsonants, String[] closingSyllables, String[] vowelSplitters, LinkedHashMap<Integer, Double> syllableFrequencies, double vowelStartFrequency, double vowelEndFrequency, double vowelSplitFrequency, double syllableEndFrequency, Pattern[] sanityChecks, boolean clean, RNG rng, Collection<Modifier> modifiers) { this.openingVowels = copyStrings(openingVowels); this.midVowels = copyStrings(midVowels); this.openingConsonants = copyStrings(openingConsonants); this.midConsonants = copyStrings(midConsonants); this.closingConsonants = copyStrings(closingConsonants); this.closingSyllables = copyStrings(closingSyllables); this.vowelSplitters = copyStrings(vowelSplitters); this.syllableFrequencies = new LinkedHashMap<Integer, Double>(syllableFrequencies); this.vowelStartFrequency = vowelStartFrequency; this.vowelEndFrequency = vowelEndFrequency; this.vowelSplitFrequency = vowelSplitFrequency; this.syllableEndFrequency = syllableEndFrequency; for (Double freq : this.syllableFrequencies.values()) { totalSyllableFrequency += freq; } if (sanityChecks == null) this.sanityChecks = null; else { this.sanityChecks = new Pattern[sanityChecks.length]; System.arraycopy(sanityChecks, 0, this.sanityChecks, 0, sanityChecks.length); } this.clean = clean; this.rng = new RNG(rng.state); this.modifiers = new ArrayList<Modifier>(modifiers); } protected boolean checkAll(CharSequence testing, Pattern[] checks) { String fixed = removeAccents(testing); for (int i = 0; i < checks.length; i++) { if(checks[i].matcher(fixed).find()) return false; } return true; } /** * Generate a word from this Finnegan, using and changing the current seed. * @param capitalize true if the word should start with a capital letter, false otherwise * @return a word in the fake language as a String */ public String word(boolean capitalize) { return word(rng.state, capitalize); } /** * Generate a word from this Finnegan using the specified seed. * * @param seed the RNG seed to use for the randomized string building * @param capitalize true if the word should start with a capital letter, false otherwise * @return a word in the fake language as a String */ public String word(long seed, boolean capitalize) { rng.state = seed; while(true) { StringBuffer sb = new StringBuffer(20); double syllableChance = rng.nextDouble(totalSyllableFrequency); int syllables = 1, i = 0; for (Map.Entry<Integer, Double> kv : syllableFrequencies.entrySet()) { if (syllableChance < kv.getValue()) { syllables = kv.getKey(); break; } else syllableChance -= kv.getValue(); } if (rng.nextDouble() < vowelStartFrequency) { sb.append(rng.getRandomElement(openingVowels)); sb.append(rng.getRandomElement(midConsonants)); i++; } else { sb.append(rng.getRandomElement(openingConsonants)); } for (; i < syllables - 1; i++) { sb.append(rng.getRandomElement(midVowels)); if (rng.nextDouble() < vowelSplitFrequency) { sb.append(rng.getRandomElement(vowelSplitters)); sb.append(rng.getRandomElement(midVowels)); } sb.append(rng.getRandomElement(midConsonants)); } if (rng.nextDouble() < syllableEndFrequency) { String close = rng.getRandomElement(closingSyllables); if((close.contains("@1") && syllables == 1) || (close.contains("@2") && syllables == 2) || (close.contains("@3") && syllables == 3) ) { sb.append(close.replaceAll("@\\d", sb.toString())); } else if(!close.contains("@")) sb.append(close); else if (rng.nextDouble() < vowelEndFrequency) { sb.append(rng.getRandomElement(midVowels)); if (rng.nextDouble() < vowelSplitFrequency) { sb.append(rng.getRandomElement(vowelSplitters)); sb.append(rng.getRandomElement(midVowels)); } } } else { sb.append(rng.getRandomElement(midVowels)); if (rng.nextDouble() < vowelSplitFrequency) { sb.append(rng.getRandomElement(vowelSplitters)); sb.append(rng.getRandomElement(midVowels)); } if (rng.nextDouble() >= vowelEndFrequency) { sb.append(rng.getRandomElement(closingConsonants)); if (rng.nextDouble() < syllableEndFrequency) { String close = rng.getRandomElement(closingSyllables); if((close.contains("@1") && syllables == 1) || (close.contains("@2") && syllables == 2) || (close.contains("@3") && syllables == 3) ) { sb.append(close.replaceAll("@\\d", sb.toString())); } else if(!close.contains("@")) sb.append(close); } } } if(sanityChecks != null && !checkAll(sb, sanityChecks)) continue; for(Modifier mod : modifiers) { sb = mod.modify(rng, sb); } if (capitalize) sb.setCharAt(0, Character.toUpperCase(sb.charAt(0))); if(clean && !checkAll(sb, vulgarChecks)) continue; return sb.toString(); } } /** * Generate a word from this Finnegan using the specified RNG, with usually the specified syllable count * * @param capitalize true if the word should start with a capital letter, false otherwise * @param approxSyllables the number of syllables to try to generate * @return a word in the fake language as a String */ public String word(boolean capitalize, int approxSyllables) { return word(rng.state, capitalize, approxSyllables); } /** * Generate a word from this Finnegan using the specified RNG, with usually the specified syllable count * * @param seed the RNG seed to use for the randomized string building * @param capitalize true if the word should start with a capital letter, false otherwise * @param approxSyllables the number of syllables to try to generate * @return a word in the fake language as a String */ public String word(long seed, boolean capitalize, int approxSyllables) { rng.setState(seed); if(approxSyllables <= 0) { String finished = rng.getRandomElement(openingVowels); if(capitalize) return finished.substring(0, 1).toUpperCase(); else return finished.substring(0, 1); } while(true) { StringBuffer sb = new StringBuffer(20); int i = 0; if (rng.nextDouble() < vowelStartFrequency) { sb.append(rng.getRandomElement(openingVowels)); sb.append(rng.getRandomElement(midConsonants)); i++; } else { sb.append(rng.getRandomElement(openingConsonants)); } for (; i < approxSyllables - 1; i++) { sb.append(rng.getRandomElement(midVowels)); if (rng.nextDouble() < vowelSplitFrequency) { sb.append(rng.getRandomElement(vowelSplitters)); sb.append(rng.getRandomElement(midVowels)); } sb.append(rng.getRandomElement(midConsonants)); } if (rng.nextDouble() < syllableEndFrequency) { String close = rng.getRandomElement(closingSyllables); if((close.contains("@1") && approxSyllables == 1) || (close.contains("@2") && approxSyllables == 2) || (close.contains("@3") && approxSyllables == 3) ) { sb.append(close.replaceAll("@\\d", sb.toString())); } else if(!close.contains("@")) sb.append(close); else if (rng.nextDouble() < vowelEndFrequency) { sb.append(rng.getRandomElement(midVowels)); if (rng.nextDouble() < vowelSplitFrequency) { sb.append(rng.getRandomElement(vowelSplitters)); sb.append(rng.getRandomElement(midVowels)); } } } else { sb.append(rng.getRandomElement(midVowels)); if (rng.nextDouble() < vowelSplitFrequency) { sb.append(rng.getRandomElement(vowelSplitters)); sb.append(rng.getRandomElement(midVowels)); } if (rng.nextDouble() >= vowelEndFrequency) { sb.append(rng.getRandomElement(closingConsonants)); if (rng.nextDouble() < syllableEndFrequency) { String close = rng.getRandomElement(closingSyllables); if((close.contains("@1") && approxSyllables == 1) || (close.contains("@2") && approxSyllables == 2) || (close.contains("@3") && approxSyllables == 3) ) { close = close.replaceAll("@\\d", sb.toString()); sb.append(close); } else if(!close.contains("@")) sb.append(close); } } } if(sanityChecks != null && !checkAll(sb, sanityChecks)) continue; for(Modifier mod : modifiers) { sb = mod.modify(rng, sb); } if (capitalize) sb.setCharAt(0, Character.toUpperCase(sb.charAt(0))); if(clean && !checkAll(sb, vulgarChecks)) continue; return sb.toString(); } } /** * Generate a sentence from this Finnegan, using and changing the current seed. * @param minWords an int for the minimum number of words in a sentence; should be at least 1 * @param maxWords an int for the maximum number of words in a sentence; should be at least equal to minWords * @return a sentence in the gibberish language as a String */ public String sentence(int minWords, int maxWords) { return sentence(rng.state, minWords, maxWords, new String[]{",", ",", ",", ";"}, new String[]{".", ".", ".", "!", "?", "..."}, 0.2); } /** * Generate a sentence from this Finnegan, using and changing the current seed. * * @param minWords an int for the minimum number of words in a sentence; should be at least 1 * @param maxWords an int for the maximum number of words in a sentence; should be at least equal to minWords * @param midPunctuation a String array where each element is a comma, semicolon, or the like that goes before a * space in the middle of a sentence * @param endPunctuation a String array where each element is a period, question mark, or the like that goes at * the very end of a sentence * @param midPunctuationFrequency a double between 0.0 and 1.0 that determines how often Strings from * midPunctuation should be inserted before spaces * @return a sentence in the gibberish language as a String */ public String sentence(int minWords, int maxWords, String[] midPunctuation, String[] endPunctuation, double midPunctuationFrequency) { return sentence(rng.state, minWords, maxWords, midPunctuation, endPunctuation, midPunctuationFrequency); } /** * Generate a sentence from this Finnegan using the specific starting RNG seed. * * @param seed the RNG seed to use for the randomized string building * @param minWords an int for the minimum number of words in a sentence; should be at least 1 * @param maxWords an int for the maximum number of words in a sentence; should be at least equal to minWords * @param midPunctuation a String array where each element is a comma, semicolon, or the like that goes before a * space in the middle of a sentence * @param endPunctuation a String array where each element is a period, question mark, or the like that goes at * the very end of a sentence * @param midPunctuationFrequency a double between 0.0 and 1.0 that determines how often Strings from * midPunctuation should be inserted before spaces * @return a sentence in the gibberish language as a String */ public String sentence(long seed, int minWords, int maxWords, String[] midPunctuation, String[] endPunctuation, double midPunctuationFrequency) { rng.state = seed; if (minWords < 1) minWords = 1; if (minWords > maxWords) maxWords = minWords; if (midPunctuationFrequency > 1.0) { midPunctuationFrequency = 1.0 / midPunctuationFrequency; } StringBuilder sb = new StringBuilder(12 * maxWords); sb.append(word(true)); for (int i = 1; i < minWords; i++) { if (rng.nextDouble() < midPunctuationFrequency) { sb.append(rng.getRandomElement(midPunctuation)); } sb.append(' '); sb.append(word(false)); } for (int i = minWords; i < maxWords && rng.nextInt(2 * maxWords) > i; i++) { if (rng.nextDouble() < midPunctuationFrequency) { sb.append(rng.getRandomElement(midPunctuation)); } sb.append(' '); sb.append(word(false)); } sb.append(rng.getRandomElement(endPunctuation)); return sb.toString(); } /** * Generate a sentence from this Finnegan that fits in the given length limit.. * * @param minWords an int for the minimum number of words in a sentence; should be at least 1 * @param maxWords an int for the maximum number of words in a sentence; should be at least equal to minWords * @param midPunctuation a String array where each element is a comma, semicolon, or the like that goes before a * space in the middle of a sentence * @param endPunctuation a String array where each element is a period, question mark, or the like that goes at * the very end of a sentence * @param midPunctuationFrequency a double between 0.0 and 1.0 that determines how often Strings from * midPunctuation should be inserted before spaces * @param maxChars the longest string length this can produce; should be at least {@code 6 * minWords} * @return a sentence in the gibberish language as a String */ public String sentence(int minWords, int maxWords, String[] midPunctuation, String[] endPunctuation, double midPunctuationFrequency, int maxChars) { return sentence(rng.state, minWords, maxWords, midPunctuation, endPunctuation, midPunctuationFrequency, maxChars); } /** * Generate a sentence from this Finnegan using the specific starting RNG seed that fits in the given length limit. * * @param seed the RNG seed to use for the randomized string building * @param minWords an int for the minimum number of words in a sentence; should be at least 1 * @param maxWords an int for the maximum number of words in a sentence; should be at least equal to minWords * @param midPunctuation a String array where each element is a comma, semicolon, or the like that goes before a * space in the middle of a sentence * @param endPunctuation a String array where each element is a period, question mark, or the like that goes at * the very end of a sentence * @param midPunctuationFrequency a double between 0.0 and 1.0 that determines how often Strings from * midPunctuation should be inserted before spaces * @param maxChars the longest string length this can produce; should be at least {@code 6 * minWords} * @return a sentence in the gibberish language as a String */ public String sentence(long seed, int minWords, int maxWords, String[] midPunctuation, String[] endPunctuation, double midPunctuationFrequency, int maxChars) { rng.state = seed; if (minWords < 1) minWords = 1; if (minWords > maxWords) maxWords = minWords; if (midPunctuationFrequency > 1.0) { midPunctuationFrequency = 1.0 / midPunctuationFrequency; } if(maxChars < 4) return "!"; if(maxChars <= 5 * minWords) { minWords = 1; maxWords = 1; } int frustration = 0; StringBuilder sb = new StringBuilder(maxChars); String next = word(true); while (next.length() >= maxChars - 1 && frustration < 50) { next = word(true); frustration++; } if(frustration >= 50) return "!"; sb.append(next); for (int i = 1; i < minWords && frustration < 50 && sb.length() < maxChars - 7; i++) { if (rng.nextDouble() < midPunctuationFrequency && sb.length() < maxChars - 3) { sb.append(rng.getRandomElement(midPunctuation)); } next = word(false); while (sb.length() + next.length() >= maxChars - 2 && frustration < 50) { next = word(false); frustration++; } if(frustration >= 50) break; sb.append(' '); sb.append(next); } for (int i = minWords; i < maxWords && sb.length() < maxChars - 7 && rng.nextInt(2 * maxWords) > i && frustration < 50; i++) { if (rng.nextDouble() < midPunctuationFrequency && sb.length() < maxChars - 3) { sb.append(rng.getRandomElement(midPunctuation)); } next = word(false); while (sb.length() + next.length() >= maxChars - 2 && frustration < 50) { next = word(false); frustration++; } if(frustration >= 50) break; sb.append(' '); sb.append(next); } next = rng.getRandomElement(endPunctuation); if(sb.length() + next.length() >= maxChars) next = "."; sb.append(next); if(sb.length() > maxChars) return "!"; return sb.toString(); } protected String[] merge1000(String[] me, String[] other, double otherInfluence) { if(other.length <= 0 && me.length <= 0) return new String[]{}; String[] ret = new String[1000]; int otherCount = (int) (1000 * otherInfluence); int idx = 0; if (other.length > 0) { String[] tmp = rng.shuffle(other); for (idx = 0; idx < otherCount; idx++) { ret[idx] = tmp[idx % tmp.length]; } } if (me.length > 0) { String[] tmp = rng.shuffle(me); for (; idx < 1000; idx++) { ret[idx] = tmp[idx % tmp.length]; } } else { for (; idx < 1000; idx++) { ret[idx] = other[idx % other.length]; } } return ret; } protected String[] accentVowels(String[] me, double influence) { String[] ret = new String[1000]; int otherCount = (int) (1000 * influence); int idx = 0; Matcher matcher; if (me.length > 0) { String[] tmp = rng.shuffle(me); for (idx = 0; idx < otherCount; idx++) { ret[idx] = tmp[idx % tmp.length] .replace('a', accentedVowels[0][rng.nextInt(accentedVowels[0].length)]) .replace('e', accentedVowels[1][rng.nextInt(accentedVowels[1].length)]) .replace('i', accentedVowels[2][rng.nextInt(accentedVowels[2].length)]) .replace('o', accentedVowels[3][rng.nextInt(accentedVowels[3].length)]) .replace('u', accentedVowels[4][rng.nextInt(accentedVowels[4].length)]); matcher = repeats.matcher(ret[idx]); if (matcher.find()) { ret[idx] = matcher.replaceAll(rng.getRandomElement(me)); } } for (; idx < 1000; idx++) { ret[idx] = tmp[idx % tmp.length]; } } else return new String[]{}; return ret; } protected String[] accentConsonants(String[] me, double influence) { String[] ret = new String[1000]; int otherCount = (int) (1000 * influence); int idx = 0; Matcher matcher; if (me.length > 0) { String[] tmp = rng.shuffle(me); for (idx = 0; idx < otherCount; idx++) { ret[idx] = tmp[idx % tmp.length] //0 .replace('c', accentedConsonants[1][rng.nextInt(accentedConsonants[1].length)]) .replace('d', accentedConsonants[2][rng.nextInt(accentedConsonants[2].length)]) .replace('f', accentedConsonants[3][rng.nextInt(accentedConsonants[3].length)]) .replace('g', accentedConsonants[4][rng.nextInt(accentedConsonants[4].length)]) .replace('h', accentedConsonants[5][rng.nextInt(accentedConsonants[5].length)]) .replace('j', accentedConsonants[6][rng.nextInt(accentedConsonants[6].length)]) .replace('k', accentedConsonants[7][rng.nextInt(accentedConsonants[7].length)]) .replace('l', accentedConsonants[8][rng.nextInt(accentedConsonants[8].length)]) //9 .replace('n', accentedConsonants[10][rng.nextInt(accentedConsonants[10].length)]) //11 //12 .replace('r', accentedConsonants[13][rng.nextInt(accentedConsonants[13].length)]) .replace('s', accentedConsonants[14][rng.nextInt(accentedConsonants[14].length)]) .replace('t', accentedConsonants[15][rng.nextInt(accentedConsonants[15].length)]) //16 .replace('w', accentedConsonants[17][rng.nextInt(accentedConsonants[17].length)]) //18 .replace('y', accentedConsonants[19][rng.nextInt(accentedConsonants[19].length)]) .replace('z', accentedConsonants[20][rng.nextInt(accentedConsonants[20].length)]); matcher = repeats.matcher(ret[idx]); if (matcher.find()) { ret[idx] = matcher.replaceAll(rng.getRandomElement(me)); } } for (; idx < 1000; idx++) { ret[idx] = tmp[idx % tmp.length]; } } else return new String[]{}; return ret; } protected String[] accentBoth(String[] me, double vowelInfluence, double consonantInfluence) { String[] ret = new String[1000]; int idx = 0; Matcher matcher; if (me.length > 0) { String[] tmp = rng.shuffle(me); for (idx = 0; idx < 1000; idx++) { boolean subVowel = rng.nextDouble() < vowelInfluence, subCon = rng.nextDouble() < consonantInfluence; if (subVowel && subCon) { ret[idx] = tmp[idx % tmp.length] .replace('a', accentedVowels[0][rng.nextInt(accentedVowels[0].length)]) .replace('e', accentedVowels[1][rng.nextInt(accentedVowels[1].length)]) .replace('i', accentedVowels[2][rng.nextInt(accentedVowels[2].length)]) .replace('o', accentedVowels[3][rng.nextInt(accentedVowels[3].length)]) .replace('u', accentedVowels[4][rng.nextInt(accentedVowels[4].length)]) //0 .replace('c', accentedConsonants[1][rng.nextInt(accentedConsonants[1].length)]) .replace('d', accentedConsonants[2][rng.nextInt(accentedConsonants[2].length)]) .replace('f', accentedConsonants[3][rng.nextInt(accentedConsonants[3].length)]) .replace('g', accentedConsonants[4][rng.nextInt(accentedConsonants[4].length)]) .replace('h', accentedConsonants[5][rng.nextInt(accentedConsonants[5].length)]) .replace('j', accentedConsonants[6][rng.nextInt(accentedConsonants[6].length)]) .replace('k', accentedConsonants[7][rng.nextInt(accentedConsonants[7].length)]) .replace('l', accentedConsonants[8][rng.nextInt(accentedConsonants[8].length)]) //9 .replace('n', accentedConsonants[10][rng.nextInt(accentedConsonants[10].length)]) //11 //12 .replace('r', accentedConsonants[13][rng.nextInt(accentedConsonants[13].length)]) .replace('s', accentedConsonants[14][rng.nextInt(accentedConsonants[14].length)]) .replace('t', accentedConsonants[15][rng.nextInt(accentedConsonants[15].length)]) //16 .replace('w', accentedConsonants[17][rng.nextInt(accentedConsonants[17].length)]) //18 .replace('y', accentedConsonants[19][rng.nextInt(accentedConsonants[19].length)]) .replace('z', accentedConsonants[20][rng.nextInt(accentedConsonants[20].length)]); matcher = repeats.matcher(ret[idx]); if (matcher.find()) { ret[idx] = matcher.replaceAll(rng.getRandomElement(me)); } } else if (subVowel) { ret[idx] = tmp[idx % tmp.length] .replace('a', accentedVowels[0][rng.nextInt(accentedVowels[0].length)]) .replace('e', accentedVowels[1][rng.nextInt(accentedVowels[1].length)]) .replace('i', accentedVowels[2][rng.nextInt(accentedVowels[2].length)]) .replace('o', accentedVowels[3][rng.nextInt(accentedVowels[3].length)]) .replace('u', accentedVowels[4][rng.nextInt(accentedVowels[4].length)]); matcher = repeats.matcher(ret[idx]); if (matcher.find()) { ret[idx] = matcher.replaceAll(rng.getRandomElement(me)); } } else if (subCon) { ret[idx] = tmp[idx % tmp.length] //0 .replace('c', accentedConsonants[1][rng.nextInt(accentedConsonants[1].length)]) .replace('d', accentedConsonants[2][rng.nextInt(accentedConsonants[2].length)]) .replace('f', accentedConsonants[3][rng.nextInt(accentedConsonants[3].length)]) .replace('g', accentedConsonants[4][rng.nextInt(accentedConsonants[4].length)]) .replace('h', accentedConsonants[5][rng.nextInt(accentedConsonants[5].length)]) .replace('j', accentedConsonants[6][rng.nextInt(accentedConsonants[6].length)]) .replace('k', accentedConsonants[7][rng.nextInt(accentedConsonants[7].length)]) .replace('l', accentedConsonants[8][rng.nextInt(accentedConsonants[8].length)]) //9 .replace('n', accentedConsonants[10][rng.nextInt(accentedConsonants[10].length)]) //11 //12 .replace('r', accentedConsonants[13][rng.nextInt(accentedConsonants[13].length)]) .replace('s', accentedConsonants[14][rng.nextInt(accentedConsonants[14].length)]) .replace('t', accentedConsonants[15][rng.nextInt(accentedConsonants[15].length)]) //16 .replace('w', accentedConsonants[17][rng.nextInt(accentedConsonants[17].length)]) //18 .replace('y', accentedConsonants[19][rng.nextInt(accentedConsonants[19].length)]) .replace('z', accentedConsonants[20][rng.nextInt(accentedConsonants[20].length)]); matcher = repeats.matcher(ret[idx]); if (matcher.find()) { ret[idx] = matcher.replaceAll(rng.getRandomElement(me)); } } else ret[idx] = tmp[idx % tmp.length]; } } else return new String[]{}; return ret; } public Finnegan mix(Finnegan other, double otherInfluence) { otherInfluence = Math.max(0.0, Math.min(otherInfluence, 1.0)); double myInfluence = 1.0 - otherInfluence; long oldState = rng.state; rng.state = (hashCode() & 0xffffffffL) | ((other.hashCode() & 0xffffffffL) << 32) ^ Double.doubleToLongBits(otherInfluence); String[] ov = merge1000(openingVowels, other.openingVowels, otherInfluence), mv = merge1000(midVowels, other.midVowels, otherInfluence), oc = merge1000(openingConsonants, other.openingConsonants, otherInfluence), mc = merge1000(midConsonants, other.midConsonants, otherInfluence), cc = merge1000(closingConsonants, other.closingConsonants, otherInfluence), cs = merge1000(closingSyllables, other.closingSyllables, otherInfluence), splitters = merge1000(vowelSplitters, other.vowelSplitters, otherInfluence); LinkedHashMap<Integer, Double> freqs = new LinkedHashMap<Integer, Double>(syllableFrequencies); for (Map.Entry<Integer, Double> kv : other.syllableFrequencies.entrySet()) { if (freqs.containsKey(kv.getKey())) freqs.put(kv.getKey(), kv.getValue() + freqs.get(kv.getKey())); else freqs.put(kv.getKey(), kv.getValue()); } List<Modifier> mods = new ArrayList<Modifier>((int)(Math.ceil(modifiers.size() * myInfluence) + Math.ceil(other.modifiers.size() * otherInfluence))); mods.addAll(rng.randomPortion(modifiers, (int)Math.ceil(modifiers.size() * myInfluence))); mods.addAll(rng.randomPortion(other.modifiers, (int)Math.ceil(other.modifiers.size() * otherInfluence))); Finnegan finished = new Finnegan(ov, mv, oc, mc, cc, cs, splitters, freqs, vowelStartFrequency * myInfluence + other.vowelStartFrequency * otherInfluence, vowelEndFrequency * myInfluence + other.vowelEndFrequency * otherInfluence, vowelSplitFrequency * myInfluence + other.vowelSplitFrequency * otherInfluence, syllableEndFrequency * myInfluence + other.syllableEndFrequency * otherInfluence, (sanityChecks == null) ? other.sanityChecks : sanityChecks, true, new RNG(rng.state), mods); rng.state = oldState; return finished; } public Finnegan addAccents(double vowelInfluence, double consonantInfluence) { vowelInfluence = Math.max(0.0, Math.min(vowelInfluence, 1.0)); consonantInfluence = Math.max(0.0, Math.min(consonantInfluence, 1.0)); long oldState = rng.state; rng.state = (hashCode() & 0xffffffffL) ^ ((Double.doubleToLongBits(vowelInfluence) & 0xffffffffL) | (Double.doubleToLongBits(consonantInfluence) << 32)); String[] ov = accentVowels(openingVowels, vowelInfluence), mv = accentVowels(midVowels, vowelInfluence), oc = accentConsonants(openingConsonants, consonantInfluence), mc = accentConsonants(midConsonants, consonantInfluence), cc = accentConsonants(closingConsonants, consonantInfluence), cs = accentBoth(closingSyllables, vowelInfluence, consonantInfluence); int[] lens = new int[syllableFrequencies.size()]; double[] odds = new double[syllableFrequencies.size()]; int i = 0; for (Map.Entry<Integer, Double> kv : syllableFrequencies.entrySet()) { lens[i] = kv.getKey(); odds[i++] = kv.getValue(); } Finnegan finished = new Finnegan(ov, mv, oc, mc, cc, cs, vowelSplitters, lens, odds, vowelStartFrequency, vowelEndFrequency, vowelSplitFrequency, syllableEndFrequency, sanityChecks, clean); finished.rng.state = rng.state; rng.state = oldState; return finished; } static String[] copyStrings(String[] start) { String[] next = new String[start.length]; System.arraycopy(start, 0, next, 0, start.length); return next; } public Finnegan removeAccents() { String[] ov = openingVowels.clone(), mv = midVowels.clone(), oc = openingConsonants.clone(), mc = midConsonants.clone(), cc = closingConsonants.clone(), cs = closingSyllables.clone(); for (int i = 0; i < ov.length; i++) { ov[i] = removeAccents(openingVowels[i]); } for (int i = 0; i < mv.length; i++) { mv[i] = removeAccents(midVowels[i]); } for (int i = 0; i < oc.length; i++) { oc[i] = removeAccents(openingConsonants[i]); } for (int i = 0; i < mc.length; i++) { mc[i] = removeAccents(midConsonants[i]); } for (int i = 0; i < cc.length; i++) { cc[i] = removeAccents(closingConsonants[i]); } for (int i = 0; i < cs.length; i++) { cs[i] = removeAccents(closingSyllables[i]); } int[] lens = new int[syllableFrequencies.size()]; double[] odds = new double[syllableFrequencies.size()]; int i = 0; for (Map.Entry<Integer, Double> kv : syllableFrequencies.entrySet()) { lens[i] = kv.getKey(); odds[i++] = kv.getValue(); } Finnegan finished = new Finnegan(ov, mv, oc, mc, cc, cs, vowelSplitters, lens, odds, vowelStartFrequency, vowelEndFrequency, vowelSplitFrequency, syllableEndFrequency, sanityChecks, clean); finished.rng.state = rng.state; return finished; } /** * Adds the specified Modifier objects from a Collection to a copy of this Finnegan and returns it. * You can obtain a Modifier with the static constants in the Finnegan.Modifier nested class, the * Finnegan.modifier() method, or Modifier's constructor. * @param mods an array or vararg of Modifier objects * @return a copy of this with the Modifiers added */ public Finnegan addModifiers(Collection<Modifier> mods) { Finnegan next = copy(); next.modifiers.addAll(mods); return next; } /** * Adds the specified Modifier objects to a copy of this Finnegan and returns it. * You can obtain a Modifier with the static constants in the Finnegan.Modifier nested class, the * Finnegan.modifier() method, or Modifier's constructor. * @param mods an array or vararg of Modifier objects * @return a copy of this with the Modifiers added */ public Finnegan addModifiers(Modifier... mods) { Finnegan next = copy(); Collections.addAll(next.modifiers, mods); return next; } /** * Creates a copy of this Finnegan with no modifiers. * @return a copy of this Finnegan with modifiers removed. */ public Finnegan removeModifiers() { Finnegan next = copy(); next.modifiers.clear(); return next; } public static Modifier modifier(String pattern, String replacement) { return new Modifier(pattern, replacement); } public static Modifier modifier(String pattern, String replacement, double chance) { return new Modifier(pattern, replacement, chance); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Finnegan finnegan = (Finnegan) o; if (clean != finnegan.clean) return false; if (Double.compare(finnegan.totalSyllableFrequency, totalSyllableFrequency) != 0) return false; if (Double.compare(finnegan.vowelStartFrequency, vowelStartFrequency) != 0) return false; if (Double.compare(finnegan.vowelEndFrequency, vowelEndFrequency) != 0) return false; if (Double.compare(finnegan.vowelSplitFrequency, vowelSplitFrequency) != 0) return false; if (Double.compare(finnegan.syllableEndFrequency, syllableEndFrequency) != 0) return false; // Probably incorrect - comparing Object[] arrays with Arrays.equals if (!Arrays.equals(openingVowels, finnegan.openingVowels)) return false; // Probably incorrect - comparing Object[] arrays with Arrays.equals if (!Arrays.equals(midVowels, finnegan.midVowels)) return false; // Probably incorrect - comparing Object[] arrays with Arrays.equals if (!Arrays.equals(openingConsonants, finnegan.openingConsonants)) return false; // Probably incorrect - comparing Object[] arrays with Arrays.equals if (!Arrays.equals(midConsonants, finnegan.midConsonants)) return false; // Probably incorrect - comparing Object[] arrays with Arrays.equals if (!Arrays.equals(closingConsonants, finnegan.closingConsonants)) return false; // Probably incorrect - comparing Object[] arrays with Arrays.equals if (!Arrays.equals(vowelSplitters, finnegan.vowelSplitters)) return false; // Probably incorrect - comparing Object[] arrays with Arrays.equals if (!Arrays.equals(closingSyllables, finnegan.closingSyllables)) return false; if (syllableFrequencies != null ? !syllableFrequencies.equals(finnegan.syllableFrequencies) : finnegan.syllableFrequencies != null) return false; // Probably incorrect - comparing Object[] arrays with Arrays.equals if (!Arrays.equals(sanityChecks, finnegan.sanityChecks)) return false; if(rng != null ? !rng.equals(finnegan.rng) : finnegan.rng != null) return false; return modifiers != null ? modifiers.equals(finnegan.modifiers) : finnegan.modifiers == null; } @Override public int hashCode() { long result, temp; result = hash64(openingVowels); result = 31 * result + hash64(midVowels); result = 31 * result + hash64(openingConsonants); result = 31 * result + hash64(midConsonants); result = 31 * result + hash64(closingConsonants); result = 31 * result + hash64(vowelSplitters); result = 31 * result + hash64(closingSyllables); result = 31 * result + (clean ? 1 : 0); result = 31 * result + (syllableFrequencies != null ? syllableFrequencies.hashCode() : 0); temp = Double.doubleToLongBits(totalSyllableFrequency); result = 31 * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(vowelStartFrequency); result = 31 * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(vowelEndFrequency); result = 31 * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(vowelSplitFrequency); result = 31 * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(syllableEndFrequency); result = 31 * result + (int) (temp ^ (temp >>> 32)); result = 31 * result + (sanityChecks != null ? sanityChecks.length + 1 : 0); result = 31 * result + (modifiers != null ? modifiers.hashCode() : 0); result = 31 * result + (rng != null ? rng.hashCode() : 0); return (int)result; } @Override public String toString() { return "Finnegan{" + "openingVowels=" + Arrays.toString(openingVowels) + ", midVowels=" + Arrays.toString(midVowels) + ", openingConsonants=" + Arrays.toString(openingConsonants) + ", midConsonants=" + Arrays.toString(midConsonants) + ", closingConsonants=" + Arrays.toString(closingConsonants) + ", vowelSplitters=" + Arrays.toString(vowelSplitters) + ", closingSyllables=" + Arrays.toString(closingSyllables) + ", syllableFrequencies=" + syllableFrequencies + ", totalSyllableFrequency=" + totalSyllableFrequency + ", vowelStartFrequency=" + vowelStartFrequency + ", vowelEndFrequency=" + vowelEndFrequency + ", vowelSplitFrequency=" + vowelSplitFrequency + ", syllableEndFrequency=" + syllableEndFrequency + ", sanityChecks=" + Arrays.toString(sanityChecks) + ", clean=" + clean + ", modifiers=" + modifiers + ", RNG=" + rng + '}'; } public long getSeed() { return rng.state; } public void setSeed(long seed) { rng.state = seed; } static long hash64(char[] data) { if(data == null) return 0; long h = -3750763034362895579L, len = data.length; for (int i = 0; i < len; i++) { h ^= data[i] & 0xff; h *= 1099511628211L; h ^= data[i] >>> 8; h *= 1099511628211L; } return h; } static long hash64(int[] data) { if(data == null) return 0; long h = -3750763034362895579L, len = data.length; for (int i = 0; i < len; i++) { h ^= data[i] & 0xff; h *= 1099511628211L; h ^= (data[i] >>> 8) & 0xff; h *= 1099511628211L; h ^= (data[i] >>> 16) & 0xff; h *= 1099511628211L; h ^= data[i] >>> 24; h *= 1099511628211L; } return h; } static long hash64(double[] data) { if(data == null) return 0; long h = -3750763034362895579L, len = data.length, t; for (int i = 0; i < len; i++) { t = Double.doubleToRawLongBits(data[i]); h ^= (t & 0xff); h *= 1099511628211L; h ^= ((t >>> 8) & 0xff); h *= 1099511628211L; h ^= ((t >>> 16) & 0xff); h *= 1099511628211L; h ^= ((t >>> 24) & 0xff); h *= 1099511628211L; h ^= ((t >>> 32) & 0xff); h *= 1099511628211L; h ^= ((t >>> 40) & 0xff); h *= 1099511628211L; h ^= ((t >>> 48) & 0xff); h *= 1099511628211L; h ^= (t >>> 56); h *= 1099511628211L; } return h; } static long hash64(String s) { if(s == null) return 0; return hash64(s.toCharArray()); } static long hash64(String[] data) { if(data == null) return 0; long h = -3750763034362895579L, len = data.length, t; for (int i = 0; i < len; i++) { t = hash64(data[i]); h ^= (t & 0xff); h *= 1099511628211L; h ^= ((t >>> 8) & 0xff); h *= 1099511628211L; h ^= ((t >>> 16) & 0xff); h *= 1099511628211L; h ^= ((t >>> 24) & 0xff); h *= 1099511628211L; h ^= ((t >>> 32) & 0xff); h *= 1099511628211L; h ^= ((t >>> 40) & 0xff); h *= 1099511628211L; h ^= ((t >>> 48) & 0xff); h *= 1099511628211L; h ^= (t >>> 56); h *= 1099511628211L; } return h; } static long hash64(String[]... data) { if(data == null) return 0; long h = -3750763034362895579L, len = data.length, t; for (int i = 0; i < len; i++) { t = hash64(data[i]); h ^= (t & 0xff); h *= 1099511628211L; h ^= ((t >>> 8) & 0xff); h *= 1099511628211L; h ^= ((t >>> 16) & 0xff); h *= 1099511628211L; h ^= ((t >>> 24) & 0xff); h *= 1099511628211L; h ^= ((t >>> 32) & 0xff); h *= 1099511628211L; h ^= ((t >>> 40) & 0xff); h *= 1099511628211L; h ^= ((t >>> 48) & 0xff); h *= 1099511628211L; h ^= (t >>> 56); h *= 1099511628211L; } return h; } public Finnegan copy() { return new Finnegan(openingVowels, midVowels, openingConsonants, midConsonants, closingConsonants, closingSyllables, vowelSplitters, syllableFrequencies, vowelStartFrequency, vowelEndFrequency, vowelSplitFrequency, syllableEndFrequency, sanityChecks, clean, rng, modifiers); } public static class Modifier implements Serializable { private static final long serialVersionUID = 1734863678490422371L; public final Alteration[] alterations; public Modifier() { this("sh?", "th"); } public Modifier(String pattern, String replacement) { alterations = new Alteration[]{new Alteration(pattern, replacement)}; } public Modifier(String pattern, String replacement, double chance) { alterations = new Alteration[]{new Alteration(pattern, replacement, chance)}; } public Modifier(Alteration... alts) { alterations = (alts == null) ? new Alteration[0] : alts; } public StringBuffer modify(RNG rng, StringBuffer sb) { StringBuffer sb2; for(Alteration alt : alterations) { Matcher m = alt.pattern.matcher(sb); sb2 = new StringBuffer(); while (m.find()) { if(rng.nextDouble() < alt.chance) m.appendReplacement(sb2, alt.replacer); else m.appendReplacement(sb2, m.group()); } m.appendTail(sb2); sb = sb2; } return sb; } /** * For a character who always pronounces 's', 'ss', and 'sh' as 'th'. */ public static final Modifier LISP = new Modifier("[sśŝşšș]+h?", "th"); /** * For a character who always lengthens 's' and 'z' sounds not starting a word. */ public static final Modifier HISS = new Modifier("(.)([sśŝşšșzźżž])+", "$1$2$2$2"); /** * For a character who has a 20% chance to repeat a starting consonant or vowel. */ public static final Modifier STUTTER = new Modifier( new Alteration("^([^aàáâãäåæāăąǻǽeèéêëēĕėęěiìíîïĩīĭįıoòóôõöøōŏőœǿuùúûüũūŭůűųyýÿŷỳαοειυаеёийъыэюяоу]+)", "$1-$1", 0.2), new Alteration("^([aàáâãäåæāăąǻǽeèéêëēĕėęěiìíîïĩīĭįıoòóôõöøōŏőœǿuùúûüũūŭůűųαοειυаеёийъыэюяоу]+)", "$1-$1", 0.2)); /** * For a language that has a 40% chance to repeat a single Latin vowel (a, e, o, or a variant on one of them * like æ or ö). */ public static final Modifier DOUBLE_VOWELS = new Modifier( "([aàáâãäåæāăąǻǽeèéêëēĕėęěòóôõöøōŏőœǿ])([^aàáâãäåæāăąǻǽeèéêëēĕėęěiìíîïĩīĭįıoòóôõöøōŏőœǿuùúûüũūŭůűųyýÿŷỳ]|$)", "$1$1$2", 0.4); /** * For a language that has a 50% chance to repeat a single consonant. */ public static final Modifier DOUBLE_CONSONANTS = new Modifier("([aàáâãäåæāăąǻǽeèéêëēĕėęěiìíîïĩīĭįıoòóôõöøōŏőœǿuùúûüũūŭůűųyýÿŷỳαοειυаеёийъыэюяоу]|^)" + "([^aàáâãäåæāăąǻǽeèéêëēĕėęěiìíîïĩīĭįıoòóôõöøōŏőœǿuùúûüũūŭůűųyýÿŷỳαοειυаеёийъыэюяоуqwhjx])" + "([aàáâãäåæāăąǻǽeèéêëēĕėęěiìíîïĩīĭįıoòóôõöøōŏőœǿuùúûüũūŭůűųyýÿŷỳαοειυаеёийъыэюяоу]|$)", "$1$2$2$3", 0.5); /** * For a language that never repeats the same letter twice in a row. */ public static final Modifier NO_DOUBLES = new Modifier("(.)\\1", "$1"); /** * Creates a Modifier that will replace the nth char in initial with the nth char in change. Expects initial and * change to be the same length, but will use the lesser length if they are not equal-length. Because of the * state of the text at the time modifiers are run, only lower-case letters need to be searched for. * @param initial a String containing lower-case letters or other symbols to be swapped out of a text * @param change a String containing characters that will replace occurrences of characters in initial * @return a Modifier that can be added to a Finnegan with its addModifiers() method */ public static Modifier replacementTable(String initial, String change) { Alteration[] alts = new Alteration[Math.min(initial.length(), change.length())]; for (int i = 0; i < alts.length; i++) { //literal string syntax; avoids sensitive escaping issues and also doesn't need a character class, // which is slightly slower and has some odd escaping cases. alts[i] = new Alteration("\\Q" + initial.charAt(i) + "\\E", change.substring(i, i+1)); } return new Modifier(alts); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Modifier modifier = (Modifier) o; // Probably incorrect - comparing Object[] arrays with Arrays.equals return Arrays.equals(alterations, modifier.alterations); } @Override public int hashCode() { return Arrays.hashCode(alterations); } @Override public String toString() { return "Modifier{" + "alterations=" + Arrays.toString(alterations) + '}'; } } public static class Alteration implements Serializable { private static final long serialVersionUID = -2138854697837563188L; public Pattern pattern; public String replacer; public double chance; public Alteration() { this("[sśŝşšș]+h?", "th"); } public Alteration(String pattern, String replacement) { this.pattern = Pattern.compile(pattern); replacer = replacement; chance = 1.0; } public Alteration(String pattern, String replacement, double chance) { this.pattern = Pattern.compile(pattern); replacer = replacement; this.chance = chance; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Alteration that = (Alteration) o; if (Double.compare(that.chance, chance) != 0) return false; return replacer.equals(that.replacer); } @Override public int hashCode() { long result; long temp; result = hash64(replacer); result = 31 * result + pattern.hashCode(); temp = Double.doubleToLongBits(chance); result = 31 * result + (temp ^ (temp >>> 32)); return (int)result; } @Override public String toString() { return "Alteration{" + "pattern=" + pattern + "replacer=" + replacer + ", chance=" + chance + '}'; } } }
Tiny improvement. See Gabber for recent changes. Gabber is here, https://github.com/tommyettinger/Gabber . It is not a single-file library, and it does have a dependency (RegExodus, which allows regular expressions that work on GWT and also adds some special custom replacement features to the regex support). This does allow it to be quite a bit more powerful, though, and it can cipher English text into a fictional language, randomly generate a fictional language from any seed, and do a bit of useful processing for normal English text as well. The README should be updated soon.
example/src/main/java/james/joyce/Finnegan.java
Tiny improvement. See Gabber for recent changes.
Java
epl-1.0
3980cd547c9fb621682f327b6c52806c269b1184
0
inocybe/odl-controller,tx1103mark/controller,tx1103mark/controller,tx1103mark/controller,522986491/controller,Sushma7785/OpenDayLight-Load-Balancer,opendaylight/controller,inocybe/odl-controller,tx1103mark/controller,522986491/controller,Sushma7785/OpenDayLight-Load-Balancer,Johnson-Chou/test,Johnson-Chou/test
/* * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.controller.sal.connect.util; import com.google.common.base.Preconditions; import java.net.InetSocketAddress; import org.opendaylight.controller.config.api.ModuleIdentifier; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Host; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.HostBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId; import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes; import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node; import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey; import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.network.topology.topology.topology.types.TopologyNetconf; import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology; import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.TopologyId; import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology; import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyKey; import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; public final class RemoteDeviceId { private final String name; private final org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier path; private final InstanceIdentifier<Node> bindingPath; private final NodeKey key; private final org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier topologyPath; private final InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node> topologyBindingPath; private InetSocketAddress address; private Host host; @Deprecated public RemoteDeviceId(final ModuleIdentifier identifier) { this(Preconditions.checkNotNull(identifier).getInstanceName()); } public RemoteDeviceId(final ModuleIdentifier identifier, Host host) { this(identifier); this.host = host; } public RemoteDeviceId(final ModuleIdentifier identifier, InetSocketAddress address) { this(identifier); this.address = address; this.host = buildHost(); } @Deprecated public RemoteDeviceId(final String name) { Preconditions.checkNotNull(name); this.name = name; this.key = new NodeKey(new NodeId(name)); this.path = createBIPath(name); this.bindingPath = createBindingPath(key); this.topologyPath = createBIPathForTopology(name); this.topologyBindingPath = createBindingPathForTopology(key); } public RemoteDeviceId(final String name, InetSocketAddress address) { this(name); this.address = address; this.host = buildHost(); } private static InstanceIdentifier<Node> createBindingPath(final NodeKey key) { return InstanceIdentifier.builder(Nodes.class).child(Node.class, key).build(); } private static org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier createBIPath(final String name) { final org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder builder = org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.builder(); builder.node(Nodes.QNAME).node(Node.QNAME).nodeWithKey(Node.QNAME, QName.create(Node.QNAME.getNamespace(), Node.QNAME.getRevision(), "id"), name); return builder.build(); } private static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node> createBindingPathForTopology(final NodeKey key) { final InstanceIdentifier<NetworkTopology> networkTopology = InstanceIdentifier.builder(NetworkTopology.class).build(); final KeyedInstanceIdentifier<Topology, TopologyKey> topology = networkTopology.child(Topology.class, new TopologyKey(new TopologyId(TopologyNetconf.QNAME.getLocalName()))); return topology .child(org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node.class, new org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey (new org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId(key.getId().getValue()))); } private static org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier createBIPathForTopology(final String name) { final org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder builder = org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.builder(); builder .node(NetworkTopology.QNAME) .node(Topology.QNAME) .nodeWithKey(Topology.QNAME, QName.create(Topology.QNAME, "topology-id"), TopologyNetconf.QNAME.getLocalName()) .node(org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node.QNAME) .nodeWithKey(org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node.QNAME, QName.create(org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node.QNAME, "node-id"), name); return builder.build(); } private Host buildHost() { return HostBuilder.getDefaultInstance(address.getHostString()); } public String getName() { return name; } public InstanceIdentifier<Node> getBindingPath() { return bindingPath; } public org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier getPath() { return path; } public NodeKey getBindingKey() { return key; } public InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node> getTopologyBindingPath() { return topologyBindingPath; } public YangInstanceIdentifier getTopologyPath() { return topologyPath; } public InetSocketAddress getAddress() { return address; } public Host getHost() { return host; } @Override public String toString() { return "RemoteDevice{" + name +'}'; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof RemoteDeviceId)) { return false; } final RemoteDeviceId that = (RemoteDeviceId) o; if (!name.equals(that.name)) { return false; } if (!bindingPath.equals(that.bindingPath)) { return false; } return true; } @Override public int hashCode() { int result = name.hashCode(); result = 31 * result + bindingPath.hashCode(); return result; } }
opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/sal/connect/util/RemoteDeviceId.java
/* * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.controller.sal.connect.util; import com.google.common.base.Preconditions; import java.net.InetSocketAddress; import org.opendaylight.controller.config.api.ModuleIdentifier; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Host; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.HostBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId; import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes; import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node; import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey; import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.network.topology.topology.topology.types.TopologyNetconf; import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology; import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.TopologyId; import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology; import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyKey; import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; public final class RemoteDeviceId { private final String name; private final org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier path; private final InstanceIdentifier<Node> bindingPath; private final NodeKey key; private final org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier topologyPath; private final InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node> topologyBindingPath; private InetSocketAddress address; private Host host; @Deprecated public RemoteDeviceId(final ModuleIdentifier identifier) { this(Preconditions.checkNotNull(identifier).getInstanceName()); } public RemoteDeviceId(final ModuleIdentifier identifier, Host host) { this(identifier); this.host = host; } public RemoteDeviceId(final ModuleIdentifier identifier, InetSocketAddress address) { this(identifier); this.address = address; this.host = buildHost(); } @Deprecated public RemoteDeviceId(final String name) { Preconditions.checkNotNull(name); this.name = name; this.key = new NodeKey(new NodeId(name)); this.path = createBIPath(name); this.bindingPath = createBindingPath(key); this.topologyPath = createBIPathForTopology(name); this.topologyBindingPath = createBindingPathForTopology(key); } public RemoteDeviceId(final String name, InetSocketAddress address) { this(name); this.address = address; this.host = buildHost(); } private static InstanceIdentifier<Node> createBindingPath(final NodeKey key) { return InstanceIdentifier.builder(Nodes.class).child(Node.class, key).build(); } private static org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier createBIPath(final String name) { final org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder builder = org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.builder(); builder.node(Nodes.QNAME).node(Node.QNAME).nodeWithKey(Node.QNAME, QName.create(Node.QNAME.getNamespace(), Node.QNAME.getRevision(), "id"), name); return builder.build(); } private static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node> createBindingPathForTopology(final NodeKey key) { final InstanceIdentifier<NetworkTopology> networkTopology = InstanceIdentifier.builder(NetworkTopology.class).build(); final KeyedInstanceIdentifier<Topology, TopologyKey> topology = networkTopology.child(Topology.class, new TopologyKey(new TopologyId(TopologyNetconf.QNAME.getLocalName()))); return topology .child(org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node.class, new org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey (new org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId(key.getId().getValue()))); } private static org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier createBIPathForTopology(final String name) { final org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder builder = org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.builder(); builder .node(NetworkTopology.QNAME) .node(Topology.QNAME) .nodeWithKey(Topology.QNAME, QName.create(Topology.QNAME, "topology-id"), TopologyNetconf.QNAME.getLocalName()) .node(org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node.QNAME) .nodeWithKey(org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node.QNAME, QName.create(org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node.QNAME, "node-id"), name); return builder.build(); } private Host buildHost() { return address.getAddress().getHostAddress() != null ? HostBuilder.getDefaultInstance(address.getAddress().getHostAddress()) : HostBuilder.getDefaultInstance(address.getAddress().getHostName()); } public String getName() { return name; } public InstanceIdentifier<Node> getBindingPath() { return bindingPath; } public org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier getPath() { return path; } public NodeKey getBindingKey() { return key; } public InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node> getTopologyBindingPath() { return topologyBindingPath; } public YangInstanceIdentifier getTopologyPath() { return topologyPath; } public InetSocketAddress getAddress() { return address; } public Host getHost() { return host; } @Override public String toString() { return "RemoteDevice{" + name +'}'; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof RemoteDeviceId)) { return false; } final RemoteDeviceId that = (RemoteDeviceId) o; if (!name.equals(that.name)) { return false; } if (!bindingPath.equals(that.bindingPath)) { return false; } return true; } @Override public int hashCode() { int result = name.hashCode(); result = 31 * result + bindingPath.hashCode(); return result; } }
BUG-3878 Prevent null pointer in nc for unresolved addresses Unresolved address is not a reason for config pusher failure. Use host string instead of resolved address string representation. Change-Id: Ieba345077860cd55325ca49980c3fb9edd66051c Signed-off-by: Maros Marsalek <a544a3532fb445ec334131e35bc3fd119321dec7@cisco.com>
opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/sal/connect/util/RemoteDeviceId.java
BUG-3878 Prevent null pointer in nc for unresolved addresses
Java
mpl-2.0
5e30ac1fb228827714a4da2d79f83263e5daaa8f
0
Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV
package org.helioviewer.jhv.io; import java.io.IOException; import java.net.MalformedURLException; import java.net.SocketTimeoutException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.UnknownHostException; import java.util.Locale; import java.util.concurrent.Callable; import java.util.concurrent.atomic.AtomicReference; import org.helioviewer.jhv.base.DownloadStream; import org.helioviewer.jhv.base.EventDispatchQueue; import org.helioviewer.jhv.base.logging.Log; import org.helioviewer.jhv.base.message.Message; import org.helioviewer.jhv.base.time.TimeUtils; import org.helioviewer.jhv.viewmodel.view.View; import org.helioviewer.jhv.viewmodel.view.fitsview.FITSView; import org.helioviewer.jhv.viewmodel.view.jp2view.JP2Image; import org.helioviewer.jhv.viewmodel.view.jp2view.JP2ImageCallisto; import org.helioviewer.jhv.viewmodel.view.jp2view.JP2View; import org.helioviewer.jhv.viewmodel.view.jp2view.JP2ViewCallisto; import org.helioviewer.jhv.viewmodel.view.simpleimageview.SimpleImageView; /** * This class provides methods to download files from a server. * * Most of the methods only will work with the current Helioviewer server * because they modify links and requests that they will fit with the API. */ public class APIRequestManager { public static final int CADENCE_ANY = -100; public static class APIRequest { public final String server; public final int sourceId; public final long startTime; public final long endTime; public final int cadence; public APIRequest(String server, int sourceId, long startTime, long endTime, int cadence) { this.server = server; this.sourceId = sourceId; this.startTime = startTime; this.endTime = endTime; this.cadence = cadence; } } /** * Method does remote opening. If image series, file is downloaded. * * @param server * @param sourceId * sourceId of the requested image * @param startTime * start time of the requested image * @param endTime * end time of the requested image * @param cadence * cadence between two frames * @param message * display error message * @return new view * @throws IOException */ public static View requestAndOpenRemoteFile(String server, int sourceId, long startTime, long endTime, int cadence, boolean message) throws IOException { String fileRequest, jpipRequest; if (startTime == endTime) { fileRequest = DataSources.getServerSetting(server, "API.jp2images.path") + "sourceId=" + Integer.toString(sourceId) + "&date=" + TimeUtils.apiDateFormat.format(startTime) + "&json=true"; jpipRequest = fileRequest + "&jpip=true"; cadence = CADENCE_ANY; } else { fileRequest = DataSources.getServerSetting(server, "API.jp2series.path") + "sourceId=" + Integer.toString(sourceId) + "&startTime=" + TimeUtils.apiDateFormat.format(startTime) + "&endTime=" + TimeUtils.apiDateFormat.format(endTime); if (cadence != CADENCE_ANY) { fileRequest += "&cadence=" + Integer.toString(cadence); } jpipRequest = fileRequest + "&jpip=true&verbose=true&linked=true"; } return requestData(jpipRequest, fileRequest, new APIRequest(server, sourceId, startTime, endTime, cadence), message); } private static View requestData(String _jpipRequest, String fileRequest, APIRequest apiRequest, boolean errorMessage) throws IOException { try { URL jpipRequest = new URL(_jpipRequest); URI downloadUri = new URI(fileRequest); APIResponse response = new APIResponse(new DownloadStream(jpipRequest).getInput()); // Could we handle the answer from the server if (!response.hasData()) { Log.error("Could not understand server answer from " + jpipRequest); if (errorMessage) { Message.err("Invalid Server reply", "The server data could not be parsed.", false); } return null; } // Just some error from the server String error = response.getString("error"); if (error != null) { Log.error("Data query returned error: " + error); if (errorMessage) { Message.err("Error getting the data", Message.formatMessageString(error), false); } return null; } // Try to load if (response.getURI() != null) { // The server wants to load us the data String message = response.getString("message"); if (message != null && errorMessage) { Message.warn("Warning", Message.formatMessageString(message)); } return loadView(response.getURI(), downloadUri, apiRequest); } else { // We did not get a reply to load data or no reply at all String message = response.getString("message"); if (message != null) { Log.error("No data to load returned from " + jpipRequest); Log.error("Server message: " + message); if (errorMessage) { Message.err("Server could not return data", Message.formatMessageString(message), false); } } else { Log.error("Did not find URI in response to " + jpipRequest); if (errorMessage) { Message.err("No data source response", "While quering the data source, the server did not provide an answer.", false); } } } } catch (MalformedURLException e) { Log.error("APIRequestManager.requestData() > Malformed JPIP request URL: " + _jpipRequest); } catch (URISyntaxException e) { Log.error("APIRequestManager.requestData() > URI syntax exception: " + fileRequest); } catch (UnknownHostException e) { Log.debug("APIRequestManager.requestData() > Error will be thrown", e); throw new IOException("Unknown Host: " + e.getMessage()); } catch (SocketTimeoutException e) { Log.error("Socket timeout while requesting JPIP URL", e); Message.err("Socket timeout", "Socket timeout while requesting JPIP URL", false); } catch (IOException e) { Log.debug("APIRequestManager.requestData() > Error will be thrown", e); throw new IOException("Error in the server communication: " + e.getMessage()); } return null; } /** * Loads a new image located at the given URI. * * Depending on the file type, a different implementation of the View is * chosen. If there is no implementation available for the given type, an * exception is thrown. * * @param uri * URI representing the location of the image * @param downloadURI * URI from which the whole file can be downloaded * @return View containing the image * @throws IOException */ public static View loadView(URI uri, URI downloadURI, APIRequest apiRequest) throws IOException { if (uri == null || uri.getScheme() == null) { throw new IOException("Invalid URI"); } try { String loc = uri.toString().toLowerCase(Locale.ENGLISH); if (loc.endsWith(".fits") || loc.endsWith(".fts")) { return new FITSView(uri); } else if (loc.endsWith(".png") || loc.endsWith(".jpg") || loc.endsWith(".jpeg")) { return new SimpleImageView(uri); } else { JP2Image jp2Image; if (loc.contains("callisto")) jp2Image = new JP2ImageCallisto(uri, downloadURI); else jp2Image = new JP2Image(uri, downloadURI); JP2View view = EventDispatchQueue.invokeAndWait(new AllocateJP2View(jp2Image)); view.setAPIRequest(apiRequest); return view; } } catch (InterruptedException e) { // nothing } catch (Exception e) { Log.debug("APIRequestManager.loadView(\"" + uri + "\", \"" + downloadURI + "\") ", e); throw new IOException(e.getMessage()); } return null; } private static class AllocateJP2View implements Callable<JP2View> { private final AtomicReference<JP2Image> refJP2Image = new AtomicReference<JP2Image>(); public AllocateJP2View(JP2Image jp2Image) { refJP2Image.set(jp2Image); } @Override public JP2View call() { JP2View view; JP2Image jp2Image = refJP2Image.get(); if (jp2Image instanceof JP2ImageCallisto) { view = new JP2ViewCallisto(); } else { view = new JP2View(); } view.setJP2Image(jp2Image); return view; } } }
src/jhv/src/org/helioviewer/jhv/io/APIRequestManager.java
package org.helioviewer.jhv.io; import java.io.IOException; import java.net.MalformedURLException; import java.net.SocketTimeoutException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.UnknownHostException; import java.util.Locale; import java.util.concurrent.Callable; import java.util.concurrent.atomic.AtomicReference; import org.helioviewer.jhv.base.DownloadStream; import org.helioviewer.jhv.base.EventDispatchQueue; import org.helioviewer.jhv.base.logging.Log; import org.helioviewer.jhv.base.message.Message; import org.helioviewer.jhv.base.time.TimeUtils; import org.helioviewer.jhv.viewmodel.view.View; import org.helioviewer.jhv.viewmodel.view.fitsview.FITSView; import org.helioviewer.jhv.viewmodel.view.jp2view.JP2Image; import org.helioviewer.jhv.viewmodel.view.jp2view.JP2ImageCallisto; import org.helioviewer.jhv.viewmodel.view.jp2view.JP2View; import org.helioviewer.jhv.viewmodel.view.jp2view.JP2ViewCallisto; import org.helioviewer.jhv.viewmodel.view.simpleimageview.SimpleImageView; /** * This class provides methods to download files from a server. * * Most of the methods only will work with the current Helioviewer server * because they modify links and requests that they will fit with the API. */ public class APIRequestManager { public static final int CADENCE_ANY = -100; public static class APIRequest { public final String server; public final int sourceId; public final long startTime; public final long endTime; public final int cadence; public APIRequest(String server, int sourceId, long startTime, long endTime, int cadence) { this.server = server; this.sourceId = sourceId; this.startTime = startTime; this.endTime = endTime; this.cadence = cadence; } } /** * Sends an request to the server to compute where the nearest image is * located on the server. * * @param server * @param sourceId * sourceId of the requested image * @param startTime * time if the requested image * @param message * display error message * @return view of the nearest image file on the server * @throws IOException */ private static View loadImage(String server, int sourceId, long startTime, boolean message) throws IOException { String fileRequest = DataSources.getServerSetting(server, "API.jp2images.path") + "sourceId=" + Integer.toString(sourceId) + "&date=" + TimeUtils.apiDateFormat.format(startTime) + "&json=true"; String jpipRequest = fileRequest + "&jpip=true"; return requestData(jpipRequest, fileRequest, new APIRequest(server, sourceId, startTime, startTime, CADENCE_ANY), message); } /** * Sends an request to the server to compute where the image series is * located on the server. * * @param server * @param sourceId * sourceId of the requested image series * @param startTime * start time of the requested image series * @param endTime * end time of the requested image series * @param cadence * cadence between to images of the image series * @param message * display error message * @return view of the file which represents the image series on the server * @throws IOException */ private static View loadImageSeries(String server, int sourceId, long startTime, long endTime, int cadence, boolean message) throws IOException { String fileRequest = DataSources.getServerSetting(server, "API.jp2series.path") + "sourceId=" + Integer.toString(sourceId) + "&startTime=" + TimeUtils.apiDateFormat.format(startTime) + "&endTime=" + TimeUtils.apiDateFormat.format(endTime); if (cadence != CADENCE_ANY) { fileRequest += "&cadence=" + Integer.toString(cadence); } String jpipRequest = fileRequest + "&jpip=true&verbose=true&linked=true"; return requestData(jpipRequest, fileRequest, new APIRequest(server, sourceId, startTime, endTime, cadence), message); } private static View requestData(String _jpipRequest, String fileRequest, APIRequest apiRequest, boolean errorMessage) throws IOException { try { URL jpipRequest = new URL(_jpipRequest); URI downloadUri = new URI(fileRequest); APIResponse response = new APIResponse(new DownloadStream(jpipRequest).getInput()); // Could we handle the answer from the server if (!response.hasData()) { Log.error("Could not understand server answer from " + jpipRequest); if (errorMessage) { Message.err("Invalid Server reply", "The server data could not be parsed.", false); } return null; } // Just some error from the server String error = response.getString("error"); if (error != null) { Log.error("Data query returned error: " + error); if (errorMessage) { Message.err("Error getting the data", Message.formatMessageString(error), false); } return null; } // Try to load if (response.getURI() != null) { // The server wants to load us the data String message = response.getString("message"); if (message != null && errorMessage) { Message.warn("Warning", Message.formatMessageString(message)); } return loadView(response.getURI(), downloadUri, apiRequest); } else { // We did not get a reply to load data or no reply at all String message = response.getString("message"); if (message != null) { Log.error("No data to load returned from " + jpipRequest); Log.error("Server message: " + message); if (errorMessage) { Message.err("Server could not return data", Message.formatMessageString(message), false); } } else { Log.error("Did not find URI in response to " + jpipRequest); if (errorMessage) { Message.err("No data source response", "While quering the data source, the server did not provide an answer.", false); } } } } catch (MalformedURLException e) { Log.error("APIRequestManager.requestData() > Malformed JPIP request URL: " + _jpipRequest); } catch (URISyntaxException e) { Log.error("APIRequestManager.requestData() > URI syntax exception: " + fileRequest); } catch (UnknownHostException e) { Log.debug("APIRequestManager.requestData() > Error will be thrown", e); throw new IOException("Unknown Host: " + e.getMessage()); } catch (SocketTimeoutException e) { Log.error("Socket timeout while requesting JPIP URL", e); Message.err("Socket timeout", "Socket timeout while requesting JPIP URL", false); } catch (IOException e) { Log.debug("APIRequestManager.requestData() > Error will be thrown", e); throw new IOException("Error in the server communication: " + e.getMessage()); } return null; } /** * Method does remote opening. If image series, file is downloaded. * * @param server * @param sourceId * sourceId of the requested image * @param startTime * start time of the requested image * @param endTime * end time of the requested image * @param cadence * cadence between two frames * @param message * display error message * @return new view * @throws IOException */ public static View requestAndOpenRemoteFile(String server, int sourceId, long startTime, long endTime, int cadence, boolean message) throws IOException { if (startTime == endTime) { return loadImage(server, sourceId, startTime, message); } else { return loadImageSeries(server, sourceId, startTime, endTime, cadence, message); } } /** * Loads a new image located at the given URI. * * Depending on the file type, a different implementation of the View is * chosen. If there is no implementation available for the given type, an * exception is thrown. * * @param uri * URI representing the location of the image * @param downloadURI * URI from which the whole file can be downloaded * @return View containing the image * @throws IOException */ public static View loadView(URI uri, URI downloadURI, APIRequest apiRequest) throws IOException { if (uri == null || uri.getScheme() == null) { throw new IOException("Invalid URI"); } try { String loc = uri.toString().toLowerCase(Locale.ENGLISH); if (loc.endsWith(".fits") || loc.endsWith(".fts")) { return new FITSView(uri); } else if (loc.endsWith(".png") || loc.endsWith(".jpg") || loc.endsWith(".jpeg")) { return new SimpleImageView(uri); } else { JP2Image jp2Image; if (loc.contains("callisto")) jp2Image = new JP2ImageCallisto(uri, downloadURI); else jp2Image = new JP2Image(uri, downloadURI); JP2View view = EventDispatchQueue.invokeAndWait(new AllocateJP2View(jp2Image)); view.setAPIRequest(apiRequest); return view; } } catch (InterruptedException e) { // nothing } catch (Exception e) { Log.debug("APIRequestManager.loadView(\"" + uri + "\", \"" + downloadURI + "\") ", e); throw new IOException(e.getMessage()); } return null; } private static class AllocateJP2View implements Callable<JP2View> { private final AtomicReference<JP2Image> refJP2Image = new AtomicReference<JP2Image>(); public AllocateJP2View(JP2Image jp2Image) { refJP2Image.set(jp2Image); } @Override public JP2View call() { JP2View view; JP2Image jp2Image = refJP2Image.get(); if (jp2Image instanceof JP2ImageCallisto) { view = new JP2ViewCallisto(); } else { view = new JP2View(); } view.setJP2Image(jp2Image); return view; } } }
Reduce git-svn-id: 4e353c0944fe8da334633afc35765ef362dec675@7766 b4e469a2-07ce-4b26-9273-4d7d95a670c7
src/jhv/src/org/helioviewer/jhv/io/APIRequestManager.java
Reduce
Java
mpl-2.0
d5a71296f9a353d27fbc121ef6423859dc7e95f1
0
lv7777/egit_test,ashwinrayaprolu1984/rhino,tuchida/rhino,qhanam/rhino,Angelfirenze/rhino,tntim96/rhino-jscover,Angelfirenze/rhino,tntim96/htmlunit-rhino-fork,ashwinrayaprolu1984/rhino,tntim96/rhino-jscover,tuchida/rhino,lv7777/egit_test,lv7777/egit_test,swannodette/rhino,sainaen/rhino,AlexTrotsenko/rhino,sam/htmlunit-rhino-fork,AlexTrotsenko/rhino,jsdoc3/rhino,Pilarbrist/rhino,AlexTrotsenko/rhino,ashwinrayaprolu1984/rhino,jsdoc3/rhino,sainaen/rhino,AlexTrotsenko/rhino,sainaen/rhino,Angelfirenze/rhino,Pilarbrist/rhino,tntim96/rhino-jscover-repackaged,sainaen/rhino,tuchida/rhino,tejassaoji/RhinoCoarseTainting,swannodette/rhino,AlexTrotsenko/rhino,rasmuserik/rhino,qhanam/rhino,Angelfirenze/rhino,ashwinrayaprolu1984/rhino,rasmuserik/rhino,Pilarbrist/rhino,sam/htmlunit-rhino-fork,qhanam/rhino,sam/htmlunit-rhino-fork,sam/htmlunit-rhino-fork,Pilarbrist/rhino,AlexTrotsenko/rhino,Angelfirenze/rhino,swannodette/rhino,sainaen/rhino,tuchida/rhino,swannodette/rhino,jsdoc3/rhino,tejassaoji/RhinoCoarseTainting,qhanam/rhino,swannodette/rhino,lv7777/egit_test,swannodette/rhino,tejassaoji/RhinoCoarseTainting,sainaen/rhino,sam/htmlunit-rhino-fork,InstantWebP2P/rhino-android,sam/htmlunit-rhino-fork,tejassaoji/RhinoCoarseTainting,Distrotech/rhino,ashwinrayaprolu1984/rhino,Pilarbrist/rhino,lv7777/egit_test,Pilarbrist/rhino,tntim96/htmlunit-rhino-fork,AlexTrotsenko/rhino,tntim96/rhino-apigee,tntim96/rhino-apigee,lv7777/egit_test,InstantWebP2P/rhino-android,ashwinrayaprolu1984/rhino,lv7777/egit_test,tejassaoji/RhinoCoarseTainting,tntim96/rhino-jscover-repackaged,tuchida/rhino,swannodette/rhino,tuchida/rhino,Angelfirenze/rhino,tejassaoji/RhinoCoarseTainting,tuchida/rhino,Angelfirenze/rhino,ashwinrayaprolu1984/rhino,Pilarbrist/rhino,tntim96/rhino-apigee,Distrotech/rhino,sam/htmlunit-rhino-fork,tejassaoji/RhinoCoarseTainting,sainaen/rhino
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * The contents of this file are subject to the Netscape Public * License Version 1.1 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.mozilla.org/NPL/ * * Software distributed under the License is distributed on an "AS * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or * implied. See the License for the specific language governing * rights and limitations under the License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is Netscape * Communications Corporation. Portions created by Netscape are * Copyright (C) 1997-1999 Netscape Communications Corporation. All * Rights Reserved. * * Contributor(s): * Norris Boyd * Igor Bukanov * Mike McCabe * * Alternatively, the contents of this file may be used under the * terms of the GNU Public License (the "GPL"), in which case the * provisions of the GPL are applicable instead of those above. * If you wish to allow use of your version of this file only * under the terms of the GPL and not to allow others to use your * version of this file under the NPL, indicate your decision by * deleting the provisions above and replace them with the notice * and other provisions required by the GPL. If you do not delete * the provisions above, a recipient may use your version of this * file under either the NPL or the GPL. */ package org.mozilla.javascript; import java.io.Serializable; import java.lang.reflect.Method; /** * This class implements the global native object (function and value * properties only). * * See ECMA 15.1.[12]. * * @author Mike Shaver */ public class NativeGlobal implements Serializable, IdFunctionMaster { public static void init(Context cx, Scriptable scope, boolean sealed) { NativeGlobal obj = new NativeGlobal(); obj.scopeSlaveFlag = true; for (int id = 1; id <= LAST_SCOPE_FUNCTION_ID; ++id) { String name; switch (id) { case Id_decodeURI: name = "decodeURI"; break; case Id_decodeURIComponent: name = "decodeURIComponent"; break; case Id_encodeURI: name = "encodeURI"; break; case Id_encodeURIComponent: name = "encodeURIComponent"; break; case Id_escape: name = "escape"; break; case Id_eval: name = "eval"; break; case Id_isFinite: name = "isFinite"; break; case Id_isNaN: name = "isNaN"; break; case Id_parseFloat: name = "parseFloat"; break; case Id_parseInt: name = "parseInt"; break; case Id_unescape: name = "unescape"; break; case Id_uneval: name = "uneval"; break; default: Kit.codeBug(); name = null; } IdFunction.define(scope, name, obj, id, ScriptableObject.DONTENUM, sealed); } ScriptableObject.defineProperty(scope, "NaN", ScriptRuntime.NaNobj, ScriptableObject.DONTENUM); ScriptableObject.defineProperty(scope, "Infinity", new Double(Double.POSITIVE_INFINITY), ScriptableObject.DONTENUM); ScriptableObject.defineProperty(scope, "undefined", Undefined.instance, ScriptableObject.DONTENUM); String[] errorMethods = Kit.semicolonSplit("" +"ConversionError;" +"EvalError;" +"RangeError;" +"ReferenceError;" +"SyntaxError;" +"TypeError;" +"URIError;" +"InternalError;" +"JavaException;" ); /* Each error constructor gets its own Error object as a prototype, with the 'name' property set to the name of the error. */ for (int i = 0; i < errorMethods.length; i++) { String name = errorMethods[i]; Scriptable errorProto = ScriptRuntime. newObject(cx, scope, "Error", ScriptRuntime.emptyArgs); errorProto.put("name", errorProto, name); IdFunction ctor = new IdFunction(obj, name, Id_new_CommonError); ctor.initAsConstructor(scope, errorProto); if (sealed) { ctor.sealObject(); if (errorProto instanceof ScriptableObject) { ((ScriptableObject)errorProto).sealObject(); } } ScriptableObject.defineProperty(scope, name, ctor, ScriptableObject.DONTENUM); } } public Object execMethod(int methodId, IdFunction function, Context cx, Scriptable scope, Scriptable thisObj, Object[] args) throws JavaScriptException { if (scopeSlaveFlag) { switch (methodId) { case Id_decodeURI: case Id_decodeURIComponent: { String str = ScriptRuntime.toString(args, 0); return decode(cx, str, methodId == Id_decodeURI); } case Id_encodeURI: case Id_encodeURIComponent: { String str = ScriptRuntime.toString(args, 0); return encode(cx, str, methodId == Id_encodeURI); } case Id_escape: return js_escape(cx, args); case Id_eval: return js_eval(cx, scope, args); case Id_isFinite: { if (args.length < 1) return Boolean.FALSE; double d = ScriptRuntime.toNumber(args[0]); return (d != d || d == Double.POSITIVE_INFINITY || d == Double.NEGATIVE_INFINITY) ? Boolean.FALSE : Boolean.TRUE; } case Id_isNaN: { // The global method isNaN, as per ECMA-262 15.1.2.6. if (args.length < 1) return Boolean.TRUE; double d = ScriptRuntime.toNumber(args[0]); return (d != d) ? Boolean.TRUE : Boolean.FALSE; } case Id_parseFloat: return js_parseFloat(cx, args); case Id_parseInt: return js_parseInt(cx, args); case Id_unescape: return js_unescape(cx, args); case Id_uneval: { Object value = (args.length != 0) ? args[0] : Undefined.instance; return ScriptRuntime.uneval(cx, scope, value); } case Id_new_CommonError: // The implementation of all the ECMA error constructors // (SyntaxError, TypeError, etc.) return NativeError.make(cx, scope, function, args); } } throw IdFunction.onBadMethodId(this, methodId); } public int methodArity(int methodId) { if (scopeSlaveFlag) { switch (methodId) { case Id_decodeURI: return 1; case Id_decodeURIComponent: return 1; case Id_encodeURI: return 1; case Id_encodeURIComponent: return 1; case Id_escape: return 1; case Id_eval: return 1; case Id_isFinite: return 1; case Id_isNaN: return 1; case Id_parseFloat: return 1; case Id_parseInt: return 2; case Id_unescape: return 1; case Id_uneval: return 1; case Id_new_CommonError: return 1; } } return -1; } /** * The global method parseInt, as per ECMA-262 15.1.2.2. */ private Object js_parseInt(Context cx, Object[] args) { String s = ScriptRuntime.toString(args, 0); int radix = ScriptRuntime.toInt32(args, 1); int len = s.length(); if (len == 0) return ScriptRuntime.NaNobj; boolean negative = false; int start = 0; char c; do { c = s.charAt(start); if (!Character.isWhitespace(c)) break; start++; } while (start < len); if (c == '+' || (negative = (c == '-'))) start++; final int NO_RADIX = -1; if (radix == 0) { radix = NO_RADIX; } else if (radix < 2 || radix > 36) { return ScriptRuntime.NaNobj; } else if (radix == 16 && len - start > 1 && s.charAt(start) == '0') { c = s.charAt(start+1); if (c == 'x' || c == 'X') start += 2; } if (radix == NO_RADIX) { radix = 10; if (len - start > 1 && s.charAt(start) == '0') { c = s.charAt(start+1); if (c == 'x' || c == 'X') { radix = 16; start += 2; } else if ('0' <= c && c <= '9') { radix = 8; start++; } } } double d = ScriptRuntime.stringToNumber(s, start, radix); return new Double(negative ? -d : d); } /** * The global method parseFloat, as per ECMA-262 15.1.2.3. * * @param cx unused * @param thisObj unused * @param args the arguments to parseFloat, ignoring args[>=1] * @param funObj unused */ private Object js_parseFloat(Context cx, Object[] args) { if (args.length < 1) return ScriptRuntime.NaNobj; String s = ScriptRuntime.toString(args[0]); int len = s.length(); if (len == 0) return ScriptRuntime.NaNobj; int i; char c; // Scan forward to the first digit or . for (i=0; TokenStream.isJSSpace(c = s.charAt(i)) && i+1 < len; i++) /* empty */ ; int start = i; if (c == '+' || c == '-') c = s.charAt(++i); if (c == 'I') { // check for "Infinity" double d; if (i+8 <= len && s.substring(i, i+8).equals("Infinity")) d = s.charAt(start) == '-' ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY; else return ScriptRuntime.NaNobj; return new Double(d); } // Find the end of the legal bit int decimal = -1; int exponent = -1; for (; i < len; i++) { switch (s.charAt(i)) { case '.': if (decimal != -1) // Only allow a single decimal point. break; decimal = i; continue; case 'e': case 'E': if (exponent != -1) break; exponent = i; continue; case '+': case '-': // Only allow '+' or '-' after 'e' or 'E' if (exponent != i-1) break; continue; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': continue; default: break; } break; } s = s.substring(start, i); try { return Double.valueOf(s); } catch (NumberFormatException ex) { return ScriptRuntime.NaNobj; } } /** * The global method escape, as per ECMA-262 15.1.2.4. * Includes code for the 'mask' argument supported by the C escape * method, which used to be part of the browser imbedding. Blame * for the strange constant names should be directed there. */ private Object js_escape(Context cx, Object[] args) { final int URL_XALPHAS = 1, URL_XPALPHAS = 2, URL_PATH = 4; String s = ScriptRuntime.toString(args, 0); int mask = URL_XALPHAS | URL_XPALPHAS | URL_PATH; if (args.length > 1) { // the 'mask' argument. Non-ECMA. double d = ScriptRuntime.toNumber(args[1]); if (d != d || ((mask = (int) d) != d) || 0 != (mask & ~(URL_XALPHAS | URL_XPALPHAS | URL_PATH))) { String message = Context.getMessage0("msg.bad.esc.mask"); cx.reportError(message); // do the ecma thing, in case reportError returns. mask = URL_XALPHAS | URL_XPALPHAS | URL_PATH; } } StringBuffer sb = null; for (int k = 0, L = s.length(); k != L; ++k) { int c = s.charAt(k); if (mask != 0 && ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '@' || c == '*' || c == '_' || c == '-' || c == '.' || (0 != (mask & URL_PATH) && (c == '/' || c == '+')))) { if (sb != null) { sb.append((char)c); } } else { if (sb == null) { sb = new StringBuffer(L + 3); sb.append(s); sb.setLength(k); } int hexSize; if (c < 256) { if (c == ' ' && mask == URL_XPALPHAS) { sb.append('+'); continue; } sb.append('%'); hexSize = 2; } else { sb.append('%'); sb.append('u'); hexSize = 4; } // append hexadecimal form of c left-padded with 0 for (int shift = (hexSize - 1) * 4; shift >= 0; shift -= 4) { int digit = 0xf & (c >> shift); int hc = (digit < 10) ? '0' + digit : 'A' - 10 + digit; sb.append((char)hc); } } } return (sb == null) ? s : sb.toString(); } /** * The global unescape method, as per ECMA-262 15.1.2.5. */ private Object js_unescape(Context cx, Object[] args) { String s = ScriptRuntime.toString(args, 0); int firstEscapePos = s.indexOf('%'); if (firstEscapePos >= 0) { int L = s.length(); char[] buf = s.toCharArray(); int destination = firstEscapePos; for (int k = firstEscapePos; k != L;) { char c = buf[k]; ++k; if (c == '%' && k != L) { int end, start; if (buf[k] == 'u') { start = k + 1; end = k + 5; } else { start = k; end = k + 2; } if (end <= L) { int x = 0; for (int i = start; i != end; ++i) { x = (x << 4) | TokenStream.xDigitToInt(buf[i]); } if (x >= 0) { c = (char)x; k = end; } } } buf[destination] = c; ++destination; } s = new String(buf, 0, destination); } return s; } private Object js_eval(Context cx, Scriptable scope, Object[] args) throws JavaScriptException { String m = ScriptRuntime.getMessage1("msg.cant.call.indirect", "eval"); throw NativeGlobal.constructError(cx, "EvalError", m, scope); } static boolean isEvalFunction(Object functionObj) { if (functionObj instanceof IdFunction) { IdFunction function = (IdFunction)functionObj; if (function.master instanceof NativeGlobal && function.getMethodId() == Id_eval) { return true; } } return false; } /** * @deprecated Use {@link ScriptRuntime#constructError(String,String)} * instead. */ public static EcmaError constructError(Context cx, String error, String message, Scriptable scope) { return ScriptRuntime.constructError(error, message); } /** * @deprecated Use * {@link ScriptRuntime#constructError(String,String,String,int,int,String)} * instead. */ public static EcmaError constructError(Context cx, String error, String message, Scriptable scope, String sourceName, int lineNumber, int columnNumber, String lineSource) { return ScriptRuntime.constructError(error, message, sourceName, lineNumber, lineSource, columnNumber); } /* * ECMA 3, 15.1.3 URI Handling Function Properties * * The following are implementations of the algorithms * given in the ECMA specification for the hidden functions * 'Encode' and 'Decode'. */ private static String encode(Context cx, String str, boolean fullUri) { byte[] utf8buf = null; StringBuffer sb = null; for (int k = 0, length = str.length(); k != length; ++k) { char C = str.charAt(k); if (encodeUnescaped(C, fullUri)) { if (sb != null) { sb.append(C); } } else { if (sb == null) { sb = new StringBuffer(length + 3); sb.append(str); sb.setLength(k); utf8buf = new byte[6]; } if (0xDC00 <= C && C <= 0xDFFF) { throw cx.reportRuntimeError0("msg.bad.uri"); } int V; if (C < 0xD800 || 0xDBFF < C) { V = C; } else { k++; if (k == length) { throw cx.reportRuntimeError0("msg.bad.uri"); } char C2 = str.charAt(k); if (!(0xDC00 <= C2 && C2 <= 0xDFFF)) { throw cx.reportRuntimeError0("msg.bad.uri"); } V = ((C - 0xD800) << 10) + (C2 - 0xDC00) + 0x10000; } int L = oneUcs4ToUtf8Char(utf8buf, V); for (int j = 0; j < L; j++) { int d = 0xff & utf8buf[j]; sb.append('%'); sb.append(toHexChar(d >>> 4)); sb.append(toHexChar(d & 0xf)); } } } return (sb == null) ? str : sb.toString(); } private static char toHexChar(int i) { if (i >> 4 != 0) Kit.codeBug(); return (char)((i < 10) ? i + '0' : i - 10 + 'a'); } private static int unHex(char c) { if ('A' <= c && c <= 'F') { return c - 'A' + 10; } else if ('a' <= c && c <= 'f') { return c - 'a' + 10; } else if ('0' <= c && c <= '9') { return c - '0'; } else { return -1; } } private static int unHex(char c1, char c2) { int i1 = unHex(c1); int i2 = unHex(c2); if (i1 >= 0 && i2 >= 0) { return (i1 << 4) | i2; } return -1; } private static String decode(Context cx, String str, boolean fullUri) { char[] buf = null; int bufTop = 0; for (int k = 0, length = str.length(); k != length;) { char C = str.charAt(k); if (C != '%') { if (buf != null) { buf[bufTop++] = C; } ++k; } else { if (buf == null) { // decode always compress so result can not be bigger then // str.length() buf = new char[length]; str.getChars(0, k, buf, 0); bufTop = k; } int start = k; if (k + 3 > length) throw cx.reportRuntimeError0("msg.bad.uri"); int B = unHex(str.charAt(k + 1), str.charAt(k + 2)); if (B < 0) throw cx.reportRuntimeError0("msg.bad.uri"); k += 3; if ((B & 0x80) == 0) { C = (char)B; } else { // Decode UTF-8 sequence into ucs4Char and encode it into // UTF-16 int utf8Tail, ucs4Char, minUcs4Char; if ((B & 0xC0) == 0x80) { // First UTF-8 should be ouside 0x80..0xBF throw cx.reportRuntimeError0("msg.bad.uri"); } else if ((B & 0x20) == 0) { utf8Tail = 1; ucs4Char = B & 0x1F; minUcs4Char = 0x80; } else if ((B & 0x10) == 0) { utf8Tail = 2; ucs4Char = B & 0x0F; minUcs4Char = 0x800; } else if ((B & 0x08) == 0) { utf8Tail = 3; ucs4Char = B & 0x07; minUcs4Char = 0x10000; } else if ((B & 0x04) == 0) { utf8Tail = 4; ucs4Char = B & 0x03; minUcs4Char = 0x200000; } else if ((B & 0x02) == 0) { utf8Tail = 5; ucs4Char = B & 0x01; minUcs4Char = 0x4000000; } else { // First UTF-8 can not be 0xFF or 0xFE throw cx.reportRuntimeError0("msg.bad.uri"); } if (k + 3 * utf8Tail > length) throw cx.reportRuntimeError0("msg.bad.uri"); for (int j = 0; j != utf8Tail; j++) { if (str.charAt(k) != '%') throw cx.reportRuntimeError0("msg.bad.uri"); B = unHex(str.charAt(k + 1), str.charAt(k + 2)); if (B < 0 || (B & 0xC0) != 0x80) throw cx.reportRuntimeError0("msg.bad.uri"); ucs4Char = (ucs4Char << 6) | (B & 0x3F); k += 3; } // Check for overlongs and other should-not-present codes if (ucs4Char < minUcs4Char || ucs4Char == 0xFFFE || ucs4Char == 0xFFFF) { ucs4Char = 0xFFFD; } if (ucs4Char >= 0x10000) { ucs4Char -= 0x10000; if (ucs4Char > 0xFFFFF) throw cx.reportRuntimeError0("msg.bad.uri"); char H = (char)((ucs4Char >>> 10) + 0xD800); C = (char)((ucs4Char & 0x3FF) + 0xDC00); buf[bufTop++] = H; } else { C = (char)ucs4Char; } } if (fullUri && URI_DECODE_RESERVED.indexOf(C) >= 0) { for (int x = start; x != k; x++) { buf[bufTop++] = str.charAt(x); } } else { buf[bufTop++] = C; } } } return (buf == null) ? str : new String(buf, 0, bufTop); } private static boolean encodeUnescaped(char c, boolean fullUri) { if (('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z') || ('0' <= c && c <= '9')) { return true; } if ("-_.!~*'()".indexOf(c) >= 0) return true; if (fullUri) { return URI_DECODE_RESERVED.indexOf(c) >= 0; } return false; } private static final String URI_DECODE_RESERVED = ";/?:@&=+$,#"; /* Convert one UCS-4 char and write it into a UTF-8 buffer, which must be * at least 6 bytes long. Return the number of UTF-8 bytes of data written. */ private static int oneUcs4ToUtf8Char(byte[] utf8Buffer, int ucs4Char) { int utf8Length = 1; //JS_ASSERT(ucs4Char <= 0x7FFFFFFF); if ((ucs4Char & ~0x7F) == 0) utf8Buffer[0] = (byte)ucs4Char; else { int i; int a = ucs4Char >>> 11; utf8Length = 2; while (a != 0) { a >>>= 5; utf8Length++; } i = utf8Length; while (--i > 0) { utf8Buffer[i] = (byte)((ucs4Char & 0x3F) | 0x80); ucs4Char >>>= 6; } utf8Buffer[0] = (byte)(0x100 - (1 << (8-utf8Length)) + ucs4Char); } return utf8Length; } private static final int Id_decodeURI = 1, Id_decodeURIComponent = 2, Id_encodeURI = 3, Id_encodeURIComponent = 4, Id_escape = 5, Id_eval = 6, Id_isFinite = 7, Id_isNaN = 8, Id_parseFloat = 9, Id_parseInt = 10, Id_unescape = 11, Id_uneval = 12, LAST_SCOPE_FUNCTION_ID = 12, Id_new_CommonError = 13; private boolean scopeSlaveFlag; }
src/org/mozilla/javascript/NativeGlobal.java
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * The contents of this file are subject to the Netscape Public * License Version 1.1 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.mozilla.org/NPL/ * * Software distributed under the License is distributed on an "AS * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or * implied. See the License for the specific language governing * rights and limitations under the License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is Netscape * Communications Corporation. Portions created by Netscape are * Copyright (C) 1997-1999 Netscape Communications Corporation. All * Rights Reserved. * * Contributor(s): * Norris Boyd * Igor Bukanov * Mike McCabe * * Alternatively, the contents of this file may be used under the * terms of the GNU Public License (the "GPL"), in which case the * provisions of the GPL are applicable instead of those above. * If you wish to allow use of your version of this file only * under the terms of the GPL and not to allow others to use your * version of this file under the NPL, indicate your decision by * deleting the provisions above and replace them with the notice * and other provisions required by the GPL. If you do not delete * the provisions above, a recipient may use your version of this * file under either the NPL or the GPL. */ package org.mozilla.javascript; import java.io.Serializable; import java.lang.reflect.Method; /** * This class implements the global native object (function and value * properties only). * * See ECMA 15.1.[12]. * * @author Mike Shaver */ public class NativeGlobal implements Serializable, IdFunctionMaster { public static void init(Context cx, Scriptable scope, boolean sealed) { NativeGlobal obj = new NativeGlobal(); obj.scopeSlaveFlag = true; for (int id = 1; id <= LAST_SCOPE_FUNCTION_ID; ++id) { String name; switch (id) { case Id_decodeURI: name = "decodeURI"; break; case Id_decodeURIComponent: name = "decodeURIComponent"; break; case Id_encodeURI: name = "encodeURI"; break; case Id_encodeURIComponent: name = "encodeURIComponent"; break; case Id_escape: name = "escape"; break; case Id_eval: name = "eval"; break; case Id_isFinite: name = "isFinite"; break; case Id_isNaN: name = "isNaN"; break; case Id_parseFloat: name = "parseFloat"; break; case Id_parseInt: name = "parseInt"; break; case Id_unescape: name = "unescape"; break; case Id_uneval: name = "uneval"; break; default: Kit.codeBug(); name = null; } IdFunction.define(scope, name, obj, id, ScriptableObject.DONTENUM, sealed); } ScriptableObject.defineProperty(scope, "NaN", ScriptRuntime.NaNobj, ScriptableObject.DONTENUM); ScriptableObject.defineProperty(scope, "Infinity", new Double(Double.POSITIVE_INFINITY), ScriptableObject.DONTENUM); ScriptableObject.defineProperty(scope, "undefined", Undefined.instance, ScriptableObject.DONTENUM); String[] errorMethods = Kit.semicolonSplit("" +"ConversionError;" +"EvalError;" +"RangeError;" +"ReferenceError;" +"SyntaxError;" +"TypeError;" +"URIError;" +"InternalError;" +"JavaException;" ); /* Each error constructor gets its own Error object as a prototype, with the 'name' property set to the name of the error. */ for (int i = 0; i < errorMethods.length; i++) { String name = errorMethods[i]; Scriptable errorProto = ScriptRuntime. newObject(cx, scope, "Error", ScriptRuntime.emptyArgs); errorProto.put("name", errorProto, name); IdFunction ctor = new IdFunction(obj, name, Id_new_CommonError); ctor.initAsConstructor(scope, errorProto); if (sealed) { ctor.sealObject(); if (errorProto instanceof ScriptableObject) { ((ScriptableObject)errorProto).sealObject(); } } ScriptableObject.defineProperty(scope, name, ctor, ScriptableObject.DONTENUM); } } public Object execMethod(int methodId, IdFunction function, Context cx, Scriptable scope, Scriptable thisObj, Object[] args) throws JavaScriptException { if (scopeSlaveFlag) { switch (methodId) { case Id_decodeURI: case Id_decodeURIComponent: { String str = ScriptRuntime.toString(args, 0); return decode(cx, str, methodId == Id_decodeURI); } case Id_encodeURI: case Id_encodeURIComponent: { String str = ScriptRuntime.toString(args, 0); return encode(cx, str, methodId == Id_encodeURI); } case Id_escape: return js_escape(cx, args); case Id_eval: return js_eval(cx, scope, args); case Id_isFinite: { if (args.length < 1) return Boolean.FALSE; double d = ScriptRuntime.toNumber(args[0]); return (d != d || d == Double.POSITIVE_INFINITY || d == Double.NEGATIVE_INFINITY) ? Boolean.FALSE : Boolean.TRUE; } case Id_isNaN: { // The global method isNaN, as per ECMA-262 15.1.2.6. if (args.length < 1) return Boolean.TRUE; double d = ScriptRuntime.toNumber(args[0]); return (d != d) ? Boolean.TRUE : Boolean.FALSE; } case Id_parseFloat: return js_parseFloat(cx, args); case Id_parseInt: return js_parseInt(cx, args); case Id_unescape: return js_unescape(cx, args); case Id_uneval: { Object value = (args.length != 0) ? args[0] : Undefined.instance; return ScriptRuntime.uneval(cx, scope, value); } case Id_new_CommonError: // The implementation of all the ECMA error constructors // (SyntaxError, TypeError, etc.) return NativeError.make(cx, scope, function, args); } } throw IdFunction.onBadMethodId(this, methodId); } public int methodArity(int methodId) { if (scopeSlaveFlag) { switch (methodId) { case Id_decodeURI: return 1; case Id_decodeURIComponent: return 1; case Id_encodeURI: return 1; case Id_encodeURIComponent: return 1; case Id_escape: return 1; case Id_eval: return 1; case Id_isFinite: return 1; case Id_isNaN: return 1; case Id_parseFloat: return 1; case Id_parseInt: return 2; case Id_unescape: return 1; case Id_uneval: return 1; case Id_new_CommonError: return 1; } } return -1; } /** * The global method parseInt, as per ECMA-262 15.1.2.2. */ private Object js_parseInt(Context cx, Object[] args) { String s = ScriptRuntime.toString(args, 0); int radix = ScriptRuntime.toInt32(args, 1); int len = s.length(); if (len == 0) return ScriptRuntime.NaNobj; boolean negative = false; int start = 0; char c; do { c = s.charAt(start); if (!Character.isWhitespace(c)) break; start++; } while (start < len); if (c == '+' || (negative = (c == '-'))) start++; final int NO_RADIX = -1; if (radix == 0) { radix = NO_RADIX; } else if (radix < 2 || radix > 36) { return ScriptRuntime.NaNobj; } else if (radix == 16 && len - start > 1 && s.charAt(start) == '0') { c = s.charAt(start+1); if (c == 'x' || c == 'X') start += 2; } if (radix == NO_RADIX) { radix = 10; if (len - start > 1 && s.charAt(start) == '0') { c = s.charAt(start+1); if (c == 'x' || c == 'X') { radix = 16; start += 2; } else if ('0' <= c && c <= '9') { radix = 8; start++; } } } double d = ScriptRuntime.stringToNumber(s, start, radix); return new Double(negative ? -d : d); } /** * The global method parseFloat, as per ECMA-262 15.1.2.3. * * @param cx unused * @param thisObj unused * @param args the arguments to parseFloat, ignoring args[>=1] * @param funObj unused */ private Object js_parseFloat(Context cx, Object[] args) { if (args.length < 1) return ScriptRuntime.NaNobj; String s = ScriptRuntime.toString(args[0]); int len = s.length(); if (len == 0) return ScriptRuntime.NaNobj; int i; char c; // Scan forward to the first digit or . for (i=0; TokenStream.isJSSpace(c = s.charAt(i)) && i+1 < len; i++) /* empty */ ; int start = i; if (c == '+' || c == '-') c = s.charAt(++i); if (c == 'I') { // check for "Infinity" double d; if (i+8 <= len && s.substring(i, i+8).equals("Infinity")) d = s.charAt(start) == '-' ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY; else return ScriptRuntime.NaNobj; return new Double(d); } // Find the end of the legal bit int decimal = -1; int exponent = -1; for (; i < len; i++) { switch (s.charAt(i)) { case '.': if (decimal != -1) // Only allow a single decimal point. break; decimal = i; continue; case 'e': case 'E': if (exponent != -1) break; exponent = i; continue; case '+': case '-': // Only allow '+' or '-' after 'e' or 'E' if (exponent != i-1) break; continue; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': continue; default: break; } break; } s = s.substring(start, i); try { return Double.valueOf(s); } catch (NumberFormatException ex) { return ScriptRuntime.NaNobj; } } /** * The global method escape, as per ECMA-262 15.1.2.4. * Includes code for the 'mask' argument supported by the C escape * method, which used to be part of the browser imbedding. Blame * for the strange constant names should be directed there. */ private Object js_escape(Context cx, Object[] args) { final int URL_XALPHAS = 1, URL_XPALPHAS = 2, URL_PATH = 4; String s = ScriptRuntime.toString(args, 0); int mask = URL_XALPHAS | URL_XPALPHAS | URL_PATH; if (args.length > 1) { // the 'mask' argument. Non-ECMA. double d = ScriptRuntime.toNumber(args[1]); if (d != d || ((mask = (int) d) != d) || 0 != (mask & ~(URL_XALPHAS | URL_XPALPHAS | URL_PATH))) { String message = Context.getMessage0("msg.bad.esc.mask"); cx.reportError(message); // do the ecma thing, in case reportError returns. mask = URL_XALPHAS | URL_XPALPHAS | URL_PATH; } } StringBuffer sb = null; for (int k = 0, L = s.length(); k != L; ++k) { int c = s.charAt(k); if (mask != 0 && ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '@' || c == '*' || c == '_' || c == '-' || c == '.' || (0 != (mask & URL_PATH) && (c == '/' || c == '+')))) { if (sb != null) { sb.append((char)c); } } else { if (sb == null) { sb = new StringBuffer(L + 3); sb.append(s); sb.setLength(k); } int hexSize; if (c < 256) { if (c == ' ' && mask == URL_XPALPHAS) { sb.append('+'); continue; } sb.append('%'); hexSize = 2; } else { sb.append('%'); sb.append('u'); hexSize = 4; } // append hexadecimal form of c left-padded with 0 for (int shift = (hexSize - 1) * 4; shift >= 0; shift -= 4) { int digit = 0xf & (c >> shift); int hc = (digit < 10) ? '0' + digit : 'A' - 10 + digit; sb.append((char)hc); } } } return (sb == null) ? s : sb.toString(); } /** * The global unescape method, as per ECMA-262 15.1.2.5. */ private Object js_unescape(Context cx, Object[] args) { String s = ScriptRuntime.toString(args, 0); int firstEscapePos = s.indexOf('%'); if (firstEscapePos >= 0) { int L = s.length(); char[] buf = s.toCharArray(); int destination = firstEscapePos; for (int k = firstEscapePos; k != L;) { char c = buf[k]; ++k; if (c == '%' && k != L) { int end, start; if (buf[k] == 'u') { start = k + 1; end = k + 5; } else { start = k; end = k + 2; } if (end <= L) { int x = 0; for (int i = start; i != end; ++i) { x = (x << 4) | TokenStream.xDigitToInt(buf[i]); } if (x >= 0) { c = (char)x; k = end; } } } buf[destination] = c; ++destination; } s = new String(buf, 0, destination); } return s; } private Object js_eval(Context cx, Scriptable scope, Object[] args) throws JavaScriptException { String m = ScriptRuntime.getMessage1("msg.cant.call.indirect", "eval"); throw NativeGlobal.constructError(cx, "EvalError", m, scope); } static boolean isEvalFunction(Object functionObj) { if (functionObj instanceof IdFunction) { IdFunction function = (IdFunction)functionObj; if (function.master instanceof NativeGlobal && function.getMethodId() == Id_eval) { return true; } } return false; } /** * @deprecated Use {@link ScriptRuntime#constructError(String,String)} * instead. */ public static EcmaError constructError(Context cx, String error, String message, Scriptable scope) { return ScriptRuntime.constructError(error, message); } /** * @deprecated Use * {@link ScriptRuntime#constructError(String,String,String,int,int,String)} * instead. */ public static EcmaError constructError(Context cx, String error, String message, Scriptable scope, String sourceName, int lineNumber, int columnNumber, String lineSource) { return ScriptRuntime.constructError(error, message, sourceName, lineNumber, lineSource, columnNumber); } /* * ECMA 3, 15.1.3 URI Handling Function Properties * * The following are implementations of the algorithms * given in the ECMA specification for the hidden functions * 'Encode' and 'Decode'. */ private static String encode(Context cx, String str, boolean fullUri) { byte[] utf8buf = null; StringBuffer sb = null; for (int k = 0, length = str.length(); k != length; ++k) { char C = str.charAt(k); if (encodeUnescaped(C, fullUri)) { if (sb != null) { sb.append(C); } } else { if (0xDC00 <= C && C <= 0xDFFF) { throw cx.reportRuntimeError0("msg.bad.uri"); } int V; if (C < 0xD800 || 0xDBFF < C) { V = C; } else { k++; if (k == length) { throw cx.reportRuntimeError0("msg.bad.uri"); } char C2 = str.charAt(k); if (!(0xDC00 <= C2 && C2 <= 0xDFFF)) { throw cx.reportRuntimeError0("msg.bad.uri"); } V = ((C - 0xD800) << 10) + (C2 - 0xDC00) + 0x10000; } if (utf8buf == null) { utf8buf = new byte[6]; sb = new StringBuffer(length + 3); sb.append(str); sb.setLength(k); } int L = oneUcs4ToUtf8Char(utf8buf, V); for (int j = 0; j < L; j++) { int d = 0xff & utf8buf[j]; sb.append('%'); sb.append(toHexChar(d >>> 4)); sb.append(toHexChar(d & 0xf)); } } } return (sb == null) ? str : sb.toString(); } private static char toHexChar(int i) { if (i >> 4 != 0) Kit.codeBug(); return (char)((i < 10) ? i + '0' : i - 10 + 'a'); } private static int unHex(char c) { if ('A' <= c && c <= 'F') { return c - 'A' + 10; } else if ('a' <= c && c <= 'f') { return c - 'a' + 10; } else if ('0' <= c && c <= '9') { return c - '0'; } else { return -1; } } private static int unHex(char c1, char c2) { int i1 = unHex(c1); int i2 = unHex(c2); if (i1 >= 0 && i2 >= 0) { return (i1 << 4) | i2; } return -1; } private static String decode(Context cx, String str, boolean fullUri) { char[] buf = null; int bufTop = 0; for (int k = 0, length = str.length(); k != length;) { char C = str.charAt(k); if (C != '%') { if (buf != null) { buf[bufTop++] = C; } ++k; } else { if (buf == null) { // decode always compress so result can not be bigger then // str.length() buf = new char[length]; str.getChars(0, k, buf, 0); bufTop = k; } int start = k; if (k + 3 > length) throw cx.reportRuntimeError0("msg.bad.uri"); int B = unHex(str.charAt(k + 1), str.charAt(k + 2)); if (B < 0) throw cx.reportRuntimeError0("msg.bad.uri"); k += 3; if ((B & 0x80) == 0) { C = (char)B; } else { // Decode UTF-8 sequence into ucs4Char and encode it into // UTF-16 int utf8Tail, ucs4Char, minUcs4Char; if ((B & 0xC0) == 0x80) { // First UTF-8 should be ouside 0x80..0xBF throw cx.reportRuntimeError0("msg.bad.uri"); } else if ((B & 0x20) == 0) { utf8Tail = 1; ucs4Char = B & 0x1F; minUcs4Char = 0x80; } else if ((B & 0x10) == 0) { utf8Tail = 2; ucs4Char = B & 0x0F; minUcs4Char = 0x800; } else if ((B & 0x08) == 0) { utf8Tail = 3; ucs4Char = B & 0x07; minUcs4Char = 0x10000; } else if ((B & 0x04) == 0) { utf8Tail = 4; ucs4Char = B & 0x03; minUcs4Char = 0x200000; } else if ((B & 0x02) == 0) { utf8Tail = 5; ucs4Char = B & 0x01; minUcs4Char = 0x4000000; } else { // First UTF-8 can not be 0xFF or 0xFE throw cx.reportRuntimeError0("msg.bad.uri"); } if (k + 3 * utf8Tail > length) throw cx.reportRuntimeError0("msg.bad.uri"); for (int j = 0; j != utf8Tail; j++) { if (str.charAt(k) != '%') throw cx.reportRuntimeError0("msg.bad.uri"); B = unHex(str.charAt(k + 1), str.charAt(k + 2)); if (B < 0 || (B & 0xC0) != 0x80) throw cx.reportRuntimeError0("msg.bad.uri"); ucs4Char = (ucs4Char << 6) | (B & 0x3F); k += 3; } // Check for overlongs and other should-not-present codes if (ucs4Char < minUcs4Char || ucs4Char == 0xFFFE || ucs4Char == 0xFFFF) { ucs4Char = 0xFFFD; } if (ucs4Char >= 0x10000) { ucs4Char -= 0x10000; if (ucs4Char > 0xFFFFF) throw cx.reportRuntimeError0("msg.bad.uri"); char H = (char)((ucs4Char >>> 10) + 0xD800); C = (char)((ucs4Char & 0x3FF) + 0xDC00); buf[bufTop++] = H; } else { C = (char)ucs4Char; } } if (fullUri && URI_DECODE_RESERVED.indexOf(C) >= 0) { for (int x = start; x != k; x++) { buf[bufTop++] = str.charAt(x); } } else { buf[bufTop++] = C; } } } return (buf == null) ? str : new String(buf, 0, bufTop); } private static boolean encodeUnescaped(char c, boolean fullUri) { if (('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z') || ('0' <= c && c <= '9')) { return true; } if ("-_.!~*'()".indexOf(c) >= 0) return true; if (fullUri) { return URI_DECODE_RESERVED.indexOf(c) >= 0; } return false; } private static final String URI_DECODE_RESERVED = ";/?:@&=+$,#"; /* Convert one UCS-4 char and write it into a UTF-8 buffer, which must be * at least 6 bytes long. Return the number of UTF-8 bytes of data written. */ private static int oneUcs4ToUtf8Char(byte[] utf8Buffer, int ucs4Char) { int utf8Length = 1; //JS_ASSERT(ucs4Char <= 0x7FFFFFFF); if ((ucs4Char & ~0x7F) == 0) utf8Buffer[0] = (byte)ucs4Char; else { int i; int a = ucs4Char >>> 11; utf8Length = 2; while (a != 0) { a >>>= 5; utf8Length++; } i = utf8Length; while (--i > 0) { utf8Buffer[i] = (byte)((ucs4Char & 0x3F) | 0x80); ucs4Char >>>= 6; } utf8Buffer[0] = (byte)(0x100 - (1 << (8-utf8Length)) + ucs4Char); } return utf8Length; } private static final int Id_decodeURI = 1, Id_decodeURIComponent = 2, Id_encodeURI = 3, Id_encodeURIComponent = 4, Id_escape = 5, Id_eval = 6, Id_isFinite = 7, Id_isNaN = 8, Id_parseFloat = 9, Id_parseInt = 10, Id_unescape = 11, Id_uneval = 12, LAST_SCOPE_FUNCTION_ID = 12, Id_new_CommonError = 13; private boolean scopeSlaveFlag; }
Fixing NativeGlobal.encode: it was broken for chars beyond 0xFFFF as it sb.setLength(k) was called after k was increased to consume the second char from UTF-16 encoding to build UCS-4.
src/org/mozilla/javascript/NativeGlobal.java
Fixing NativeGlobal.encode: it was broken for chars beyond 0xFFFF as it sb.setLength(k) was called after k was increased to consume the second char from UTF-16 encoding to build UCS-4.
Java
agpl-3.0
5ff0c32eaf2c97ac924c49b768ba823c09afa229
0
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
bc820118-2e60-11e5-9284-b827eb9e62be
hello.java
bc7c9c14-2e60-11e5-9284-b827eb9e62be
bc820118-2e60-11e5-9284-b827eb9e62be
hello.java
bc820118-2e60-11e5-9284-b827eb9e62be
Java
agpl-3.0
05faa5b3ae4ec0818c7dc7e26e547c47af886cfe
0
rkfg/jbot,rkfg/jbot
package me.rkfg.xmpp.bot.irc; import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.net.ssl.SSLSocketFactory; import org.pircbotx.Configuration; import org.pircbotx.Configuration.Builder; import org.pircbotx.PircBotX; import org.pircbotx.exception.IrcException; import org.pircbotx.hooks.ListenerAdapter; import org.pircbotx.hooks.events.ConnectEvent; import org.pircbotx.hooks.events.MessageEvent; import org.pircbotx.hooks.events.PrivateMessageEvent; import me.rkfg.xmpp.bot.BotBase; import me.rkfg.xmpp.bot.message.IRCMessage; import me.rkfg.xmpp.bot.plugins.MessagePlugin; import ru.ppsrk.gwt.client.LogicException; public class IRCBot extends BotBase { private PircBotX bot; private int maxLength; private class Listener extends ListenerAdapter { @Override public void onMessage(MessageEvent event) throws Exception { processMessage(new IRCMessage(event)); } @Override public void onPrivateMessage(PrivateMessageEvent event) throws Exception { processMessage(new IRCMessage(event)); } @Override public void onConnect(ConnectEvent event) throws Exception { String modes = sm.getStringSetting("ircModes"); if (modes != null && !modes.isEmpty()) { bot.sendIRC().mode(bot.getNick(), modes); } } private void processMessage(IRCMessage ircMessage) { String body = ircMessage.getBody(); for (MessagePlugin plugin : plugins) { Pattern pattern = plugin.getPattern(); if (pattern != null) { Matcher matcher = pattern.matcher(body); if (matcher.find()) { try { String result = plugin.process(ircMessage, matcher); if (result != null && !result.isEmpty()) { postprocessMessage(result).forEach(l -> ircMessage.getOriginalMessage().respond(l)); break; } } catch (Exception e) { log.warn("{}", e); } } } } } } @Override protected void init() { super.init(); MessageParser.init(); } @Override public int run() throws LogicException { init(); sm.setDefault("maxLine", "256"); sm.setDefault("ircPort", "6667"); sm.setDefault("ircSsl", "0"); maxLength = sm.getIntegerSetting("maxLine"); final Builder builder = new Configuration.Builder().setLogin(sm.getStringSetting("login")).setName(sm.getStringSetting("nick")) .setNickservPassword(sm.getStringSetting("password")) .addServer(sm.getStringSetting("ircServer"), sm.getIntegerSetting("ircPort")) .addAutoJoinChannel("#" + sm.getStringSetting("join")).addListener(new Listener()).setAutoReconnect(true) .setAutoReconnectDelay(5000).setMessageDelay(100); if ("1".equals(sm.getStringSetting("ircSsl"))) { builder.setSocketFactory(SSLSocketFactory.getDefault()); } builder.setVersion("jbot by rkfg https://github.com/rkfg/jbot"); builder.setRealName(builder.getVersion()); Configuration conf = builder.buildConfiguration(); while (!Thread.interrupted()) { try { bot = new PircBotX(conf); bot.startBot(); } catch (IOException | IrcException e) { log.warn("{}", e); return 2; } } return 0; } @Override public String sendMessage(String message, String mucName) { postprocessMessage(message).forEach(msg -> bot.sendIRC().message(mucName, msg)); return null; } @Override public void sendMessage(String message) { postprocessMessage(message).forEach(l -> bot.getUserBot().getChannels().forEach(c -> c.send().message(l))); } private List<String> postprocessMessage(String message) { return new MessageParser(message, maxLength).process(); } @Override public Set<String> getRoomsWithUser(String userId) { return Collections.emptySet(); } @Override public boolean isDirectChat(String roomId) { return !roomId.startsWith("#"); } @Override public Protocol getProtocol() { return Protocol.IRC; } @Override public void joinRoom(String roomName) { bot.sendIRC().joinChannel(roomName); } @Override public void leaveRoom(String roomName) { bot.getUserBot().getChannels().stream().filter(c -> c.getName().equals(roomName)).forEach(c -> c.send().part()); } }
src/main/java/me/rkfg/xmpp/bot/irc/IRCBot.java
package me.rkfg.xmpp.bot.irc; import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.net.ssl.SSLSocketFactory; import org.pircbotx.Configuration; import org.pircbotx.Configuration.Builder; import org.pircbotx.PircBotX; import org.pircbotx.exception.IrcException; import org.pircbotx.hooks.ListenerAdapter; import org.pircbotx.hooks.events.ConnectEvent; import org.pircbotx.hooks.events.MessageEvent; import org.pircbotx.hooks.events.PrivateMessageEvent; import me.rkfg.xmpp.bot.BotBase; import me.rkfg.xmpp.bot.IBot; import me.rkfg.xmpp.bot.message.IRCMessage; import me.rkfg.xmpp.bot.plugins.MessagePlugin; import ru.ppsrk.gwt.client.LogicException; public class IRCBot extends BotBase implements IBot { private PircBotX bot; private int maxLength; private class Listener extends ListenerAdapter { @Override public void onMessage(MessageEvent event) throws Exception { processMessage(new IRCMessage(event)); } @Override public void onPrivateMessage(PrivateMessageEvent event) throws Exception { processMessage(new IRCMessage(event)); } @Override public void onConnect(ConnectEvent event) throws Exception { String modes = sm.getStringSetting("ircModes"); if (modes != null && !modes.isEmpty()) { bot.sendIRC().mode(bot.getNick(), modes); } } private void processMessage(IRCMessage ircMessage) { String body = ircMessage.getBody(); for (MessagePlugin plugin : plugins) { Pattern pattern = plugin.getPattern(); if (pattern != null) { Matcher matcher = pattern.matcher(body); if (matcher.find()) { try { String result = plugin.process(ircMessage, matcher); if (result != null && !result.isEmpty()) { postprocessMessage(result).forEach(l -> ircMessage.getOriginalMessage().respond(l)); break; } } catch (Exception e) { log.warn("{}", e); } } } } } } @Override protected void init() { super.init(); MessageParser.init(); } @Override public int run() throws LogicException { init(); sm.setDefault("maxLine", "256"); sm.setDefault("ircPort", "6667"); sm.setDefault("ircSsl", "0"); maxLength = sm.getIntegerSetting("maxLine"); final Builder builder = new Configuration.Builder().setLogin(sm.getStringSetting("login")).setName(sm.getStringSetting("nick")) .setNickservPassword(sm.getStringSetting("password")) .addServer(sm.getStringSetting("ircServer"), sm.getIntegerSetting("ircPort")) .addAutoJoinChannel("#" + sm.getStringSetting("join")).addListener(new Listener()).setAutoReconnect(true) .setAutoReconnectDelay(5000).setMessageDelay(100); if ("1".equals(sm.getStringSetting("ircSsl"))) { builder.setSocketFactory(SSLSocketFactory.getDefault()); } builder.setVersion("jbot by rkfg https://github.com/rkfg/jbot"); builder.setRealName(builder.getVersion()); Configuration conf = builder.buildConfiguration(); while (!Thread.interrupted()) { try { bot = new PircBotX(conf); bot.startBot(); } catch (IOException | IrcException e) { log.warn("{}", e); return 2; } } return 0; } @Override public String sendMessage(String message, String mucName) { postprocessMessage(message).forEach(msg -> bot.sendIRC().message(mucName, msg)); return null; } @Override public void sendMessage(String message) { postprocessMessage(message).forEach(l -> bot.getUserBot().getChannels().forEach(c -> c.send().message(l))); } private List<String> postprocessMessage(String message) { return new MessageParser(message, maxLength).process(); } @Override public Set<String> getRoomsWithUser(String userId) { return Collections.emptySet(); } @Override public boolean isDirectChat(String roomId) { return !roomId.startsWith("#"); } @Override public Protocol getProtocol() { return Protocol.IRC; } @Override public void joinRoom(String roomName) { bot.sendIRC().joinChannel(roomName); } @Override public void leaveRoom(String roomName) { bot.getUserBot().getChannels().stream().filter(c -> c.getName().equals(roomName)).forEach(c -> c.send().part()); } }
Remove redundant interface
src/main/java/me/rkfg/xmpp/bot/irc/IRCBot.java
Remove redundant interface
Java
agpl-3.0
4d7bfb2a76ff5b7a34cdc1dc227bd55a65b3a1f3
0
Audiveris/audiveris,Audiveris/audiveris
//----------------------------------------------------------------------------// // // // S h e e t P a i n t e r // // // // Copyright (C) Herve Bitteur 2000-2006. All rights reserved. // // This software is released under the terms of the GNU General Public // // License. Please contact the author at herve.bitteur@laposte.net // // to report bugs & suggestions. // //----------------------------------------------------------------------------// // package omr.score.visitor; import omr.glyph.Glyph; import omr.score.Measure; import omr.score.Score; import omr.score.Staff; import omr.score.SystemPart; import omr.sheet.Ending; import omr.sheet.Ledger; import omr.sheet.Sheet; import omr.sheet.StaffInfo; import omr.sheet.SystemInfo; import omr.stick.Stick; import omr.ui.view.Zoom; import omr.util.Logger; import java.awt.*; /** * Class <code>SheetPainter</code> defines for every node in Score hierarchy * the rendering of related sections (with preset colors) in the dedicated * <b>Sheet</b> display. * * <p>Nota: It has been extended to deal with rendering of initial sheet * elements. * * @author Herv&eacute Bitteur * @version $Id$ */ public class SheetPainter extends AbstractScoreVisitor { //~ Static fields/initializers --------------------------------------------- /** Usual logger utility */ private static final Logger logger = Logger.getLogger(SheetPainter.class); //~ Instance fields -------------------------------------------------------- /** Graphic context */ private final Graphics g; /** Display zoom */ private final Zoom z; //~ Constructors ----------------------------------------------------------- //--------------// // SheetPainter // //--------------// /** * Creates a new SheetPainter object. * * * @param g Graphic context * @param z zoom factor */ public SheetPainter (Graphics g, Zoom z) { this.g = g; this.z = z; } //~ Methods ---------------------------------------------------------------- //---------------// // visit Measure // //---------------// @Override public boolean visit (Measure measure) { // Render the measure ending barline, if within the clipping area measure.getBarline() .render(g, z); return true; } //-------------// // visit Score // //-------------// @Override public boolean visit (Score score) { score.acceptChildren(this); return false; } //-------------// // visit Staff // //-------------// @Override public boolean visit (Staff staff) { StaffInfo info = staff.getInfo(); // Render the staff lines, if within the clipping area if ((info != null) && info.render(g, z)) { return true; } else { return false; } } //------------------// // visit SystemPart // //------------------// @Override public boolean visit (SystemPart part) { // Render the part starting barline, if any if (part.getStartingBarline() != null) { part.getStartingBarline() .render(g, z); } return true; } /** * Although a Sheet is not part of the Score hierarchy, this visitor has * been specifically extended to render all physical info of a sheet * * @param sheet the sheet to render initial elements */ //-------------// // visit Sheet // //-------------// public boolean visit (Sheet sheet) { // Use specific color g.setColor(Color.lightGray); Score score = sheet.getScore(); if ((score != null) && (score.getSystems() .size() > 0)) { // Normal (full) rendering of the score score.accept(this); } else { // Render what we have got so far if (sheet.LinesAreDone()) { for (StaffInfo staff : sheet.getStaves()) { staff.render(g, z); } } } if (sheet.BarsAreDone()) { for (SystemInfo system : sheet.getSystems()) { // Check that this system is visible Rectangle box = new Rectangle( 0, system.getAreaTop(), Integer.MAX_VALUE, system.getAreaBottom() - system.getAreaTop() + 1); z.scale(box); if (box.intersects(g.getClipBounds())) { g.setColor(Color.lightGray); // Staff lines for (StaffInfo staff : system.getStaves()) { staff.render(g, z); } // Bar lines for (Stick bar : system.getBars()) { bar.renderLine(g, z); } g.setColor(Color.black); // Stems for (Glyph glyph : system.getGlyphs()) { if (glyph.isStem()) { Stick stick = (Stick) glyph; stick.renderLine(g, z); } } // Ledgers for (Ledger ledger : system.getLedgers()) { ledger.render(g, z); } // Endings for (Ending ending : system.getEndings()) { ending.render(g, z); } } } } else { // Horizontals if (sheet.HorizontalsAreDone()) { // Ledgers for (Ledger ledger : sheet.getHorizontals() .getLedgers()) { ledger.render(g, z); } // Endings for (Ending ending : sheet.getHorizontals() .getEndings()) { ending.render(g, z); } } } return true; } }
src/main/omr/score/visitor/SheetPainter.java
//----------------------------------------------------------------------------// // // // R e n d e r i n g V i s i t o r // // // // Copyright (C) Herve Bitteur 2000-2006. All rights reserved. // // This software is released under the terms of the GNU General Public // // License. Please contact the author at herve.bitteur@laposte.net // // to report bugs & suggestions. // //----------------------------------------------------------------------------// // package omr.score.visitor; import omr.glyph.Glyph; import omr.score.Barline; import omr.score.Beam; import omr.score.Chord; import omr.score.Clef; import omr.score.KeySignature; import omr.score.Measure; import omr.score.MeasureNode; import omr.score.Note; import omr.score.PartNode; import omr.score.Score; import omr.score.ScoreNode; import omr.score.Slur; import omr.score.Staff; import omr.score.System; import omr.score.SystemPart; import omr.score.TimeSignature; import omr.sheet.Ending; import omr.sheet.Ledger; import omr.sheet.Sheet; import omr.sheet.StaffInfo; import omr.sheet.SystemInfo; import omr.stick.Stick; import omr.ui.view.Zoom; import omr.util.Logger; import java.awt.*; /** * Class <code>SheetPainter</code> defines for every node in Score hierarchy * the rendering of related sections (with preset colors) in the dedicated * <b>Sheet</b> display. * * <p>Nota: It has been extended to deal with rendering of initial sheet * elements. * * @author Herv&eacute Bitteur * @version $Id$ */ public class SheetPainter implements Visitor { //~ Static fields/initializers --------------------------------------------- /** Usual logger utility */ private static final Logger logger = Logger.getLogger(SheetPainter.class); //~ Instance fields -------------------------------------------------------- /** Graphic context */ private final Graphics g; /** Display zoom */ private final Zoom z; //~ Constructors ----------------------------------------------------------- //--------------// // SheetPainter // //--------------// /** * Creates a new SheetPainter object. * * * @param g Graphic context * @param z zoom factor */ public SheetPainter (Graphics g, Zoom z) { this.g = g; this.z = z; } //~ Methods ---------------------------------------------------------------- //---------------// // visit Barline // //---------------// public boolean visit (Barline barline) { return true; } //------------// // visit Beam // //------------// public boolean visit (Beam beam) { return true; } //-------------// // visit Chord // //-------------// public boolean visit (Chord chord) { return true; } //------------// // visit Clef // //------------// public boolean visit (Clef clef) { return true; } //--------------------// // visit KeySignature // //--------------------// public boolean visit (KeySignature keySignature) { return true; } //---------------// // visit Measure // //---------------// public boolean visit (Measure measure) { // Render the measure ending barline, if within the clipping area measure.getBarline() .render(g, z); return true; } //-------------------// // visit MeasureNode // //-------------------// public boolean visit (MeasureNode node) { return true; } //------------// // visit Note // //------------// public boolean visit (Note node) { return true; } //----------------// // visit PartNode // //----------------// public boolean visit (PartNode node) { return true; } //-----------------// // visit ScoreNode // //-----------------// public boolean visit (ScoreNode musicNode) { return true; } //-------------// // visit Score // //-------------// public boolean visit (Score score) { score.acceptChildren(this); return false; } //------------// // visit Slur // //------------// public boolean visit (Slur slur) { return true; } //-------------// // visit Staff // //-------------// public boolean visit (Staff staff) { StaffInfo info = staff.getInfo(); // Render the staff lines, if within the clipping area if ((info != null) && info.render(g, z)) { return true; } else { return false; } } //--------------// // visit System // //--------------// public boolean visit (System system) { return true; } //------------------// // visit SystemPart // //------------------// public boolean visit (SystemPart part) { // Render the part starting barline, if any if (part.getStartingBarline() != null) { part.getStartingBarline() .render(g, z); } return true; } //---------------------// // visit TimeSignature // //---------------------// public boolean visit (TimeSignature timeSignature) { return true; } /** * Although a Sheet is not part of the Score hierarchy, this visitor has * been specifically extended to render all physical info of a sheet * * @param sheet the sheet to render initial elements */ //-------------// // visit Sheet // //-------------// public boolean visit (Sheet sheet) { // Use specific color g.setColor(Color.lightGray); Score score = sheet.getScore(); if ((score != null) && (score.getSystems() .size() > 0)) { // Normal (full) rendering of the score score.accept(this); } else { // Render what we have got so far if (sheet.LinesAreDone()) { for (StaffInfo staff : sheet.getStaves()) { staff.render(g, z); } } } if (sheet.BarsAreDone()) { for (SystemInfo system : sheet.getSystems()) { // Check that this system is visible Rectangle box = new Rectangle( 0, system.getAreaTop(), Integer.MAX_VALUE, system.getAreaBottom() - system.getAreaTop() + 1); z.scale(box); if (box.intersects(g.getClipBounds())) { g.setColor(Color.lightGray); // Staff lines for (StaffInfo staff : system.getStaves()) { staff.render(g, z); } // Bar lines for (Stick bar : system.getBars()) { bar.renderLine(g, z); } g.setColor(Color.black); // Stems for (Glyph glyph : system.getGlyphs()) { if (glyph.isStem()) { Stick stick = (Stick) glyph; stick.renderLine(g, z); } } // Ledgers for (Ledger ledger : system.getLedgers()) { ledger.render(g, z); } // Endings for (Ending ending : system.getEndings()) { ending.render(g, z); } } } } else { // Horizontals if (sheet.HorizontalsAreDone()) { // Ledgers for (Ledger ledger : sheet.getHorizontals() .getLedgers()) { ledger.render(g, z); } // Endings for (Ending ending : sheet.getHorizontals() .getEndings()) { ending.render(g, z); } } } return true; } }
Use of AbstractScoreVisitor
src/main/omr/score/visitor/SheetPainter.java
Use of AbstractScoreVisitor
Java
lgpl-2.1
8116c598e50cc2bd8c7e8a59b9dbb422de3c9537
0
simoc/mapyrus,simoc/mapyrus,simoc/mapyrus
/* * This file is part of Mapyrus, software for plotting maps. * Copyright (C) 2003, 2004, 2005 Simon Chenery. * * Mapyrus is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Mapyrus is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Mapyrus; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* * @(#) $Id$ */ package org.mapyrus; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.Shape; import java.awt.Stroke; import java.awt.font.FontRenderContext; import java.awt.font.GlyphVector; import java.awt.geom.AffineTransform; import java.awt.geom.GeneralPath; import java.awt.geom.PathIterator; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintStream; import java.io.PrintWriter; import java.io.StringReader; import java.io.StringWriter; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.StringTokenizer; import java.util.zip.GZIPOutputStream; import org.mapyrus.font.AdobeFontMetricsManager; import org.mapyrus.font.PostScriptFont; import org.mapyrus.font.StringDimension; import org.mapyrus.font.TrueTypeFont; import org.mapyrus.image.ImageIOWrapper; import org.mapyrus.io.ASCII85Writer; import org.mapyrus.io.WildcardFile; import org.mapyrus.ps.PostScriptFile; /** * Abstraction of a graphics format. Provides methods to create new * output files and then draw to them, independent of the graphics * format. */ public class OutputFormat { /* * Type of output currently being generated. */ private static final int INTERNAL_IMAGE = 1; private static final int IMAGE_FILE = 2; /* * Output to window on screen. */ private static final int SCREEN_WINDOW = 3; /* * PostScript output can be created as either moveto-lineto-stroke * commands to draw shapes on page or as an single image covering * the whole page containing all drawn shapes. */ private static final int POSTSCRIPT_GEOMETRY = 4; private static final int POSTSCRIPT_IMAGE = 5; /* * Portable Documnet Format output. */ private static final int PDF = 6; /* * Scalable Vector Graphics (SVG) output. */ private static final int SVG = 7; /* * HTML image map being created in combination with an image. */ private static final int IMAGEMAP = 8; /* * Type of justification for labels on page, as used * in a word processor and in HTML tags. */ public static final int JUSTIFY_LEFT = 1; public static final int JUSTIFY_CENTER = 2; public static final int JUSTIFY_RIGHT = 4; public static final int JUSTIFY_TOP = 8; public static final int JUSTIFY_MIDDLE = 16; public static final int JUSTIFY_BOTTOM = 32; /* * File or image that drawing commands are * writing to. */ private int mOutputType; private String mFormatName; private BufferedImage mImage; private String mFilename; private PrintWriter mWriter; private OutputStream mOutputStream; private Graphics2D mGraphics2D; private boolean mIsPipedOutput; private boolean mIsStandardOutput; private boolean mIsUpdatingFile; private Process mOutputProcess; private File mTempFile; private PrintWriter mImageMapWriter; /* * Frequently used fonts. */ private FontCache mFontCache; /* * List of font definitions included in this PostScript file and list of fonts * used in this file but not defined. */ private HashSet mSuppliedFontResources; private HashSet mNeededFontResources; /* * Fonts which are to be re-encoded to ISOLatin1 in PostScript file. * This is normally done so that extended symbols (such as degree symbol) * can be used. */ private HashSet mEncodeAsISOLatin1; /* * Adobe Font Metrics files containing character width information for all fonts. */ private AdobeFontMetricsManager mAdobeFontMetrics; private ArrayList mAfmFiles; /* * List of TrueType fonts to load using Java Font.createFont() method. */ private HashMap mTTFFonts; /* * Page dimensions and resolution. */ private double mPageWidth; private double mPageHeight; private double mResolution; /* * Justification for labels as fraction of string height and width * to move string in X and Y direction to achieve correct justification. */ private double mJustificationShiftX; private double mJustificationShiftY; /* * Rotation of current font in radians, with 0 horizontal, * measured counter-clockwise. */ private double mFontRotation; /* * If non-zero, gives linewidth to use for drawing outlines of * each character of labels. */ private double mFontOutlineWidth; private Font mBaseFont; /* * Mask containing protected areas of the page. */ private PageMask mPageMask; /* * Counts clip paths and gradient fills set for SVG output * so each clip path and gradient can be given a unique id. */ private int mClipPathCounter; private boolean mIsClipPathActive; private int mGradientCounter; /* * File offset of each object in PDF file and buffers containing * all geometry and images to be included in PDF file. */ private ArrayList mPDFFileOffsets; private StringWriter mPDFGeometryStringWriter; private PrintWriter mPDFGeometryWriter; private ArrayList mPDFImageObjects; /* * Format for writing coordinate values. */ private DecimalFormat mCoordinateDecimal = new DecimalFormat("#.###", Constants.US_DECIMAL_FORMAT_SYMBOLS); /** * Write PostScript file header, including document structuring conventions (DSC). * @param width width of page in mm. * @param height height of page in mm. * @param resolution resolution of page in DPI. * @param turnPage flag true when page is to be rotated 90 degrees. * @param fontList list of PostScript fonts to include in header. * @param backgroundColor background color for page, or null if no background. */ private void writePostScriptHeader(double width, double height, int resolution, boolean turnPage, ArrayList fontList, Color backgroundColor) throws IOException, MapyrusException { long widthInPoints = Math.round(width / Constants.MM_PER_INCH * Constants.POINTS_PER_INCH); long heightInPoints = Math.round(height / Constants.MM_PER_INCH * Constants.POINTS_PER_INCH); StringBuffer sb = new StringBuffer("%!PS-Adobe-3.0"); if (mFormatName.equals("eps") || mFormatName.equals("epsimage")) sb.append(" EPSF-3.0"); writeLine(mWriter, sb.toString()); if (turnPage) writeLine(mWriter, "%%BoundingBox: 0 0 " + heightInPoints + " " + widthInPoints); else writeLine(mWriter, "%%BoundingBox: 0 0 " + widthInPoints + " " + heightInPoints); if ((!mFormatName.equals("eps")) && (!mFormatName.equals("epsimage"))) writeLine(mWriter, "%%Pages: 1"); writeLine(mWriter, "%%DocumentData: Clean7Bit"); writeLine(mWriter, "%%LanguageLevel: 2"); writeLine(mWriter, "%%Creator: (" + Constants.PROGRAM_NAME + " " + Constants.getVersion() + ")"); writeLine(mWriter, "%%OperatorMessage: (Mapyrus Output...)"); Date now = new Date(); writeLine(mWriter, "%%CreationDate: (" + now.toString() + ")"); String username = System.getProperty("user.name"); if (username != null) writeLine(mWriter, "%%For: (" + username + ")"); /* * List fonts included in this PostScript file. */ writeLine(mWriter, "%%DocumentRequiredResources: (atend)"); if (fontList.size() > 0) { sb = new StringBuffer("%%DocumentSuppliedResources: font"); Iterator it = fontList.iterator(); while (it.hasNext()) { PostScriptFont psFont = (PostScriptFont)(it.next()); sb.append(" ").append(psFont.getName()); mSuppliedFontResources.add(psFont.getName()); } writeLine(mWriter, sb.toString()); } writeLine(mWriter, "%%EndComments"); writeLine(mWriter, ""); writeLine(mWriter, "% Resolution " + resolution + " DPI"); /* * Inline font definitions. */ writeLine(mWriter, "%%BeginSetup"); Iterator it = fontList.iterator(); while (it.hasNext()) { PostScriptFont psFont = (PostScriptFont)(it.next()); writeLine(mWriter, "%%BeginResource: font " + psFont.getName()); String fontDefinition = psFont.getFontDefinition(); writeLine(mWriter, fontDefinition); writeLine(mWriter, "%%EndResource"); } writeLine(mWriter, "%%EndSetup"); /* * Set color and linestyle to reasonable default values. * Taken from 'initgraphics' operator example in PostScript Language * Reference Manual. */ writeLine(mWriter, "1 setlinewidth 0 setlinecap 0 setlinejoin"); writeLine(mWriter, "[] 0 setdash 0 setgray 10 setmiterlimit"); if (turnPage) { /* * Turn page 90 degrees so that a landscape orientation page appears * on a portrait page. */ writeLine(mWriter, "% Turn page 90 degrees."); writeLine(mWriter, "90 rotate 0 " + heightInPoints + " neg translate"); } /* * Prevent anything being displayed outside bounding box we've just defined. */ writeLine(mWriter, "0 0 " + widthInPoints + " " + heightInPoints + " rectclip"); /* * Set background color for page. */ writeLine(mWriter, "/RG { setrgbcolor } bind def"); if (backgroundColor != null) { float c[] = backgroundColor.getRGBColorComponents(null); writeLine(mWriter, "gsave"); writeLine(mWriter, mCoordinateDecimal.format(c[0]) + " " + mCoordinateDecimal.format(c[1]) + " " + mCoordinateDecimal.format(c[2]) + " RG"); writeLine(mWriter, "0 0 " + widthInPoints + " " + heightInPoints + " rectfill"); writeLine(mWriter, "grestore"); } /* * Define shorter names for most commonly used operations. * Bind all operators names to improve performance (see 3.11 of * PostScript Language Reference Manual). */ writeLine(mWriter, "/m { moveto } bind def /l { lineto } bind def"); writeLine(mWriter, "/c { curveto } bind def /h { closepath } bind def"); writeLine(mWriter, "/S { stroke } bind def /f { fill } bind def"); writeLine(mWriter, "/W { clip } bind def /n { newpath } bind def"); writeLine(mWriter, "/ju { /fjy exch def /fjx exch def } bind def"); /* * Define font and dictionary entries for font size and justification. * Don't bind these as font loading operators may be overridden in interpreter. */ writeLine(mWriter, "/font {"); writeLine(mWriter, "/foutline exch def"); writeLine(mWriter, "/frot exch radtodeg def"); writeLine(mWriter, "/fsize exch def findfont fsize scalefont setfont } def"); writeLine(mWriter, "/radtodeg { 180 mul 3.1415629 div } bind def"); /* * Draw text string, after setting correct position, rotation, * justifying it horizontally and vertically for current font size * and shifting it down a number of lines if it is part of a multi-line * string. * * Line number (starting at 0) and string to show are passed to this procedure. */ writeLine(mWriter, "/t { gsave currentpoint translate frot rotate"); writeLine(mWriter, "dup stringwidth pop fjx mul"); writeLine(mWriter, "3 -1 roll neg fjy add fsize mul"); writeLine(mWriter, "rmoveto foutline 0 gt"); writeLine(mWriter, "{false charpath foutline w 0 j 0 J 2 M stroke} {show} ifelse"); writeLine(mWriter, "grestore newpath } bind def"); writeLine(mWriter, "/w { setlinewidth } bind def"); writeLine(mWriter, "/J { setlinecap } bind def"); writeLine(mWriter, "/j { setlinejoin } bind def"); writeLine(mWriter, "/M { setmiterlimit } bind def"); writeLine(mWriter, "/d { setdash } bind def"); /* * Use new dictionary in saved state so that variables we define * do not overwrite variables in parent state. */ writeLine(mWriter, "/q { gsave 4 dict begin } bind def"); writeLine(mWriter, "/Q { end grestore } bind def"); writeLine(mWriter, ""); } /** * Write PDF file header. * @param width width of page in mm. * @param height height of page in mm. * @param resolution resolution of page in DPI. * @param turnPage flag true when page is to be rotated 90 degrees. * @param fontList list of PostScript fonts to include in header. * @param backgroundColor background color for page, or null if no background. */ private void writePDFHeader(double width, double height, int resolution, boolean turnPage, ArrayList fontList, Color backgroundColor) throws IOException, MapyrusException { long widthInPoints = Math.round(width / Constants.MM_PER_INCH * Constants.POINTS_PER_INCH); long heightInPoints = Math.round(height / Constants.MM_PER_INCH * Constants.POINTS_PER_INCH); mPDFFileOffsets = new ArrayList(); int nChars = writeLine(mWriter, "%PDF-1.4"); mPDFFileOffsets.add(new Integer(nChars)); nChars += writeLine(mWriter, "1 0 obj"); nChars += writeLine(mWriter, "<<"); nChars += writeLine(mWriter, "/Type /Catalog"); nChars += writeLine(mWriter, "/Outlines 2 0 R"); nChars += writeLine(mWriter, "/Pages 3 0 R"); nChars += writeLine(mWriter, ">>"); nChars += writeLine(mWriter, "endobj"); mPDFFileOffsets.add(new Integer(nChars)); nChars += writeLine(mWriter, "2 0 obj"); nChars += writeLine(mWriter, "<<"); nChars += writeLine(mWriter, "/Type /Outlines"); nChars += writeLine(mWriter, "/Count 0"); nChars += writeLine(mWriter, ">>"); nChars += writeLine(mWriter, "endobj"); mWriter.flush(); mPDFFileOffsets.add(new Integer(nChars)); nChars += writeLine(mWriter, "3 0 obj"); nChars += writeLine(mWriter, "<<"); nChars += writeLine(mWriter, "/Type /Pages"); nChars += writeLine(mWriter, "/Kids [4 0 R]"); nChars += writeLine(mWriter, "/Count 1"); nChars += writeLine(mWriter, ">>"); nChars += writeLine(mWriter, "endobj"); mPDFFileOffsets.add(new Integer(nChars)); nChars += writeLine(mWriter, "4 0 obj"); nChars += writeLine(mWriter, "<<"); nChars += writeLine(mWriter, "/Type /Page"); String mediaBox; if (turnPage) mediaBox = "/MediaBox [0 0 " + heightInPoints + " " + widthInPoints + "]"; else mediaBox = "/MediaBox [0 0 " + widthInPoints + " " + heightInPoints + "]"; nChars += writeLine(mWriter, mediaBox); nChars += writeLine(mWriter, "/Contents 5 0 R"); nChars += writeLine(mWriter, "/Resources 6 0 R"); nChars += writeLine(mWriter, ">>"); nChars += writeLine(mWriter, "endobj"); mPDFFileOffsets.add(new Integer(nChars)); mPDFImageObjects = new ArrayList(); mPDFGeometryStringWriter = new StringWriter(); mPDFGeometryWriter = new PrintWriter(mPDFGeometryStringWriter); if (turnPage) { /* * Turn page 90 degrees so that a landscape orientation page appears * on a portrait page. */ writeLine(mPDFGeometryWriter, "0 1 -1 0 0 0 cm"); writeLine(mPDFGeometryWriter, "1 0 0 1 0 " + (-heightInPoints) + " cm"); } if (backgroundColor != null) { /* * Write object to set page background. */ float components[] = backgroundColor.getColorComponents(null); writeLine(mPDFGeometryWriter, "q"); writeLine(mPDFGeometryWriter, "0 0 " + widthInPoints + " " + heightInPoints + " re"); for (int i = 0; i < components.length; i++) writeLine(mPDFGeometryWriter, mCoordinateDecimal.format(components[i])); writeLine(mPDFGeometryWriter, "rg f Q"); } /* * Set scale so that we can give all coordinate positions in millimetres. */ double scale = Constants.POINTS_PER_INCH / Constants.MM_PER_INCH; writeLine(mPDFGeometryWriter, scale + " 0 0 " + scale + " 0 0 cm"); } /* * Set scale in PostScript file so that we can give all coordinate * positions in millimetres. */ private void writePostScriptScaling() { /* * Set plotting units to millimetres. */ writeLine(mWriter, "% Set scaling so that (x, y) coordinates are given in millimetres"); writeLine(mWriter, Constants.POINTS_PER_INCH + " " + Constants.MM_PER_INCH + " div dup scale"); } /** * Write SVG file header, starting with XML waffle. * @param width width of page in mm. * @param height height of page in mm. * @param backgroundColor background color for page, or null if no background. */ private void writeSVGHeader(double width, double height, Color backgroundColor) { writeLine(mWriter, "<?xml version=\"1.0\" encoding=\"ISO-8859-1\" standalone=\"no\"?>"); Date now = new Date(); writeLine(mWriter, "<!-- Created by " + Constants.PROGRAM_NAME + " " + Constants.getVersion() + " on " + now.toString() + " -->"); double pxPerMM = Constants.getScreenResolution() / Constants.MM_PER_INCH; writeLine(mWriter, "<svg width=\"" + mCoordinateDecimal.format(width * pxPerMM) + "\""); writeLine(mWriter, " height=\"" + mCoordinateDecimal.format(height * pxPerMM) + "\""); writeLine(mWriter, " version=\"1.1\""); writeLine(mWriter, " overflow=\"hidden\""); writeLine(mWriter, " xml:space=\"preserve\""); writeLine(mWriter, " xmlns=\"http://www.w3.org/2000/svg\">"); if (backgroundColor != null) { writeLine(mWriter, "<rect x=\"0\" y=\"0\" width=\"100%\""); writeLine(mWriter, " height=\"100%\" stroke=\"none\""); writeLine(mWriter, " fill=\"" + ColorDatabase.toHexString(backgroundColor) + "\" fill-opacity=\"1\"/>"); } /* * Set scaling so that units can be given in millimetres. * Set reasonable default values for rarely used settings that are * not given each time a shape is displayed. */ writeLine(mWriter, "<g transform=\"scale(" + pxPerMM + ")\""); writeLine(mWriter, " style=\"fill-rule:nonzero;fill-opacity:1;stroke-opacity:1;stroke-dasharray:none;\""); writeLine(mWriter, " clip-rule=\"nonzero\">"); } /** * Sets correct rendering hints and transformation * for buffered image we will plot to. * @param resolution resolution for page in DPI. * @param backgroundColor background color for page, or null if no background. * @param lineAliasing flag true if lines should be drawn with anti-aliasing. * @param labelAliasing flag true if labels should be drawn with anti-aliasing. */ private void setupBufferedImage(double resolution, Color backgroundColor, boolean lineAntiAliasing, boolean labelAntiAliasing) { double scale; scale = resolution / Constants.MM_PER_INCH; /* * Set background of entire image to desired color. */ if (backgroundColor != null) { Color originalColor = mGraphics2D.getColor(); mGraphics2D.setColor(backgroundColor); mGraphics2D.fillRect(0, 0, mImage.getWidth(), mImage.getHeight()); mGraphics2D.setColor(originalColor); } /* * Set transform with origin in lower-left corner and * Y axis increasing upwards. */ mGraphics2D.translate(0, mImage.getHeight()); mGraphics2D.scale(scale, -scale); /* * Set anti-aliasing for labels and lines if the user wants it. */ if (lineAntiAliasing) { mGraphics2D.addRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)); } else { mGraphics2D.addRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF)); } if (labelAntiAliasing) { mGraphics2D.addRenderingHints(new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON)); } else { mGraphics2D.addRenderingHints(new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF)); } } /** * Indicates whether an image format is supported or not. * @param formatName * @return true if creation of images in given format is supported. */ private boolean isSupportedImageFormat(String formatName) { boolean found = false; String knownFormats[] = ImageIOWrapper.getWriterFormatNames(); for (int i = 0; i < knownFormats.length && found == false; i++) { if (formatName.equalsIgnoreCase(knownFormats[i])) { found = true; } } return(found); } /** * Return PostScript commands to re-encode a font in ISOLatin1 encoding. * @param fontName name of font to re-encode. * @return string containing PostScript commands to re-encode font. */ private String isoLatinEncode(String fontName) { /* * Re-encoding commands taken from section 5.6.1 of Adobe PostScript * Language Reference Manual (2nd Edition). */ return("/" + fontName + " findfont" + Constants.LINE_SEPARATOR + "dup length dict begin" + Constants.LINE_SEPARATOR + "{1 index /FID ne {def} {pop pop} ifelse} forall" + Constants.LINE_SEPARATOR + "/Encoding ISOLatin1Encoding def" + Constants.LINE_SEPARATOR + "currentdict" + Constants.LINE_SEPARATOR + "end" + Constants.LINE_SEPARATOR + "/" + fontName + " exch definefont pop"); } private void setOutput(String filename, double width, double height, String extras, PrintStream stdoutStream) throws IOException, MapyrusException { /* * Parse list of additional options given by caller. */ ArrayList fontList = new ArrayList(); mEncodeAsISOLatin1 = new HashSet(); mTTFFonts = new HashMap(); mAfmFiles = new ArrayList(); mIsUpdatingFile = false; int resolution; boolean turnPage = false; Color backgroundColor = null; boolean labelAntiAliasing = true; boolean lineAntiAliasing = false; boolean compressOutput = false; Rectangle2D existingBoundingBox = null; if (mOutputType == POSTSCRIPT_GEOMETRY) resolution = 300; else resolution = Constants.getScreenResolution(); /* * Reading all font metrics information takes some time. * Wait until we really need it before loading it. */ mAdobeFontMetrics = null; StringTokenizer st = new StringTokenizer(extras); while (st.hasMoreTokens()) { String token = st.nextToken(); if (token.startsWith("pfafiles=")) { /* * Build list of font filenames user wants * to include in this PostScript file. */ StringTokenizer st2 = new StringTokenizer(token.substring(9), ","); while (st2.hasMoreTokens()) { String pfaFilename = st2.nextToken(); if (pfaFilename.length() > 0) { /* * Accept wildcards in filenames. */ WildcardFile wildcard = new WildcardFile(pfaFilename); Iterator it = wildcard.getMatchingFiles().iterator(); while (it.hasNext()) fontList.add(new PostScriptFont((String)it.next())); } } } if (token.startsWith("afmfiles=")) { StringTokenizer st2 = new StringTokenizer(token.substring(9), ","); while (st2.hasMoreTokens()) { String afmFilename = st2.nextToken(); if (afmFilename.length() > 0) { /* * Accept wildcards in filenames. */ WildcardFile wildcard = new WildcardFile(afmFilename); Iterator it = wildcard.getMatchingFiles().iterator(); while (it.hasNext()) { mAfmFiles.add(it.next()); } } } } else if (token.startsWith("isolatinfonts=")) { /* * Build list of fonts to encode in ISOLatin1. */ StringTokenizer st2 = new StringTokenizer(token.substring(14), ","); while (st2.hasMoreTokens()) { String fontName = st2.nextToken(); if (fontName.length() > 0) mEncodeAsISOLatin1.add(fontName); } } else if (token.startsWith("resolution=")) { String r = token.substring(11); try { resolution = Integer.parseInt(r); } catch (NumberFormatException e) { throw new MapyrusException(MapyrusMessages.get(MapyrusMessages.INVALID_PAGE_RESOLUTION) + ": " + r); } if (resolution < 1) { throw new MapyrusException(MapyrusMessages.get(MapyrusMessages.INVALID_PAGE_RESOLUTION) + ": " + r); } } else if (token.startsWith("ttffiles=")) { /* * Build list of TrueType font filenames user wants * to open with Java methods. */ StringTokenizer st2 = new StringTokenizer(token.substring(9), ","); while (st2.hasMoreTokens()) { String ttfFilename = st2.nextToken(); /* * Accept wildcards in filenames. */ if (ttfFilename.length() > 0) { WildcardFile wildcard = new WildcardFile(ttfFilename); Iterator it = wildcard.getMatchingFiles().iterator(); while (it.hasNext()) { String s = (String)it.next(); TrueTypeFont ttf = new TrueTypeFont(s); String fontName = ttf.getName(); mTTFFonts.put(fontName, ttf); mTTFFonts.put(fontName.toLowerCase(), ttf); mTTFFonts.put(fontName.toUpperCase(), ttf); } } } } else if (token.startsWith("turnpage=")) { String flag = token.substring(9); turnPage = flag.equalsIgnoreCase("true"); } else if (token.startsWith("labelantialiasing=")) { String flag = token.substring(18); labelAntiAliasing = flag.equalsIgnoreCase("true"); } else if (token.startsWith("lineantialiasing=")) { String flag = token.substring(17); lineAntiAliasing = flag.equalsIgnoreCase("true"); } else if (token.startsWith("update=") && mOutputType != SVG && mOutputType != PDF) { String flag = token.substring(7); mIsUpdatingFile = flag.equalsIgnoreCase("true"); } else if (token.startsWith("compress=")) { String flag = token.substring(9); compressOutput = flag.equalsIgnoreCase("true"); } else if (token.startsWith("imagemap=") && mOutputType == IMAGE_FILE) { mImageMapWriter = new PrintWriter(new FileWriter(token.substring(9))); } else if (token.startsWith("background=")) { String colorName = token.substring(11); backgroundColor = ColorDatabase.getColor(colorName, 255); if (backgroundColor == null) { throw new MapyrusException(MapyrusMessages.get(MapyrusMessages.COLOR_NOT_FOUND) + ": " + colorName); } } } if ((mOutputType == POSTSCRIPT_GEOMETRY || mOutputType == POSTSCRIPT_IMAGE || mOutputType == PDF || mOutputType == IMAGE_FILE || mOutputType == SVG) && (!mIsUpdatingFile)) { /* * Should we pipe the output to another program * instead of writing a file? */ mIsPipedOutput = filename.startsWith("|"); /* * Are we writing to standard output instead of to a file? */ mIsStandardOutput = filename.equals("-"); if (mIsPipedOutput) { String pipeCommand = filename.substring(1).trim(); String []cmdArray; if (Constants.getOSName().indexOf("WIN") >= 0) cmdArray = new String[]{pipeCommand}; else cmdArray = new String[]{"sh", "-c", pipeCommand}; mOutputProcess = Runtime.getRuntime().exec(cmdArray); mOutputStream = mOutputProcess.getOutputStream(); } else { if (mIsStandardOutput) mOutputStream = stdoutStream; else mOutputStream = new FileOutputStream(filename); } /* * Compress output too if the user wants it. */ if (compressOutput) mOutputStream = new GZIPOutputStream(mOutputStream); } File f = new File(filename); if (mIsUpdatingFile) { if (!f.canWrite()) { throw new IOException(MapyrusMessages.get(MapyrusMessages.READ_ONLY) + ": " + filename); } } /* * Setup file we are writing to. */ if (mOutputType == POSTSCRIPT_GEOMETRY || mOutputType == POSTSCRIPT_IMAGE || mOutputType == PDF) { if (mIsUpdatingFile) { PostScriptFile ps = new PostScriptFile(filename); if (ps.getNumberOfPages() > 1) { throw new MapyrusException(MapyrusMessages.get(MapyrusMessages.NOT_PS_FILE) + ": " + filename); } /* * Use size of existing PostScript file as size for new page. */ existingBoundingBox = ps.getBoundingBox(); width = existingBoundingBox.getMaxX() / Constants.POINTS_PER_INCH * Constants.MM_PER_INCH; height = existingBoundingBox.getMaxY() / Constants.POINTS_PER_INCH * Constants.MM_PER_INCH; /* * Start writing to a temporary file in same directory. We'll replace the * original file at the end when the file is successfully completed. */ mTempFile = File.createTempFile(Constants.PROGRAM_NAME, null, new File(filename).getAbsoluteFile().getParentFile()); mOutputStream = new FileOutputStream(mTempFile); } mWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(mOutputStream))); mSuppliedFontResources = new HashSet(); if (mOutputType == PDF) writePDFHeader(width, height, resolution, turnPage, fontList, backgroundColor); else writePostScriptHeader(width, height, resolution, turnPage, fontList, backgroundColor); mNeededFontResources = new HashSet(); if (mIsUpdatingFile) { /* * Append contents of existing file as an included document * to the new file we are creating. */ writeLine(mWriter, "save"); writeLine(mWriter, "/showpage {} def"); writeLine(mWriter, "%%BeginDocument: " + filename); BufferedReader r = null; try { r = new BufferedReader(new FileReader(filename)); String line; while ((line = r.readLine()) != null) { writeLine(mWriter, line); } } finally { try { if (r != null) r.close(); } catch (IOException e) { } } writeLine(mWriter, "%%EndDocument"); writeLine(mWriter, "restore"); } if (mOutputType != PDF) writePostScriptScaling(); } else if (mOutputType == SVG) { mWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(mOutputStream))); writeSVGHeader(width, height, backgroundColor); /* * Create a graphics context we can use for saving current graphics * state whilst drawing. */ BufferedImage anyImage = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB); mGraphics2D = (Graphics2D)anyImage.getGraphics(); } if (mOutputType != POSTSCRIPT_GEOMETRY && mOutputType != SVG && mOutputType != PDF) { /* * Create image to draw into. */ if (mOutputType == IMAGE_FILE || mOutputType == SCREEN_WINDOW || mOutputType == POSTSCRIPT_IMAGE) { if (mIsUpdatingFile && mOutputType == IMAGE_FILE) { /* * Read existing image for editing. * Set page width and height to size of existing image. */ mImage = ImageIOWrapper.read(f, Color.BLACK); if (mImage == null) { throw new MapyrusException(MapyrusMessages.get(MapyrusMessages.INVALID_FORMAT) + ": " + filename); } width = mImage.getWidth() / (resolution / Constants.MM_PER_INCH); height = mImage.getHeight() / (resolution / Constants.MM_PER_INCH); } else { /* * Create a BufferedImage to draw into. We'll save it to a file * when user has finished drawing to it. */ int widthInPixels = (int)Math.round(width / Constants.MM_PER_INCH * resolution); int heightInPixels = (int)Math.round(height / Constants.MM_PER_INCH * resolution); int imageType; /* * Create images with transparency for all formats except * JPEG and PPM (which do not support it). */ if (mFormatName.equals("jpg") || mFormatName.equals("jpeg") || mFormatName.equals("ppm")) imageType = BufferedImage.TYPE_3BYTE_BGR; else imageType = BufferedImage.TYPE_INT_ARGB; mImage = new BufferedImage(widthInPixels, heightInPixels, imageType); } } else if (mOutputType == INTERNAL_IMAGE) { /* * Calculate width of page, based on image and resolution given * by user. */ width = mImage.getWidth() / (resolution / Constants.MM_PER_INCH); height = mImage.getHeight() / (resolution / Constants.MM_PER_INCH); } mGraphics2D = (Graphics2D)(mImage.getGraphics()); setupBufferedImage(resolution, backgroundColor, lineAntiAliasing, labelAntiAliasing); } if (mImageMapWriter != null) { /* * Create image map. */ mImageMapWriter.println("<!-- HTML Imagemap created by Mapyrus for image " + filename + " -->"); mImageMapWriter.println("<!-- Surround contents of this file with <map name=\"foo\"> ... </map> and -->"); mImageMapWriter.println("<!-- combine it with the image using HTML like <img src=\"" + filename + "\" usemap=\"#foo\"> -->"); } mFilename = filename; mPageWidth = width; mPageHeight = height; mResolution = Constants.MM_PER_INCH / resolution; mFontCache = new FontCache(); mJustificationShiftX = mJustificationShiftY = 0.0; mFontOutlineWidth = 0.0; /* * Set impossible current font rotation so first font * accessed will be loaded. */ mFontRotation = Double.MAX_VALUE; /* * Do not allocate page mask until needed to save memory. */ mPageMask = null; } /** * Creates new graphics file, ready for drawing to. * @param filename name of image file output will be saved to. * If filename begins with '|' character then output is piped as * input to that command. * @param format is the graphics format to use. * @param width is the page width (in mm). * @param height is the page height (in mm). * @param extras contains extra settings for this output. * @param stdoutStream standard output stream for program. */ public OutputFormat(String filename, String format, double width, double height, String extras, PrintStream stdoutStream) throws IOException, MapyrusException { mFormatName = format.toLowerCase(); /* * Check that Java can write this image format to a file. */ if (mFormatName.equals("ps") || mFormatName.equals("postscript") || mFormatName.equals("application/postscript")) { mFormatName = "ps"; mOutputType = POSTSCRIPT_GEOMETRY; } else if (mFormatName.equals("eps")) { mOutputType = POSTSCRIPT_GEOMETRY; } else if (mFormatName.equals("epsimage")) { mOutputType = POSTSCRIPT_IMAGE; } else if (mFormatName.equals("pdf") || mFormatName.equals("application/pdf")) { mOutputType = PDF; } else if (mFormatName.equals("svg") || mFormatName.equals("image/svg+xml")) { mFormatName = "svg"; mOutputType = SVG; } else if (mFormatName.equals("screen")) { mOutputType = SCREEN_WINDOW; } else { if (mFormatName.equals("image/x-portable-pixmap")) mFormatName = "ppm"; else if (mFormatName.startsWith("image/")) mFormatName = mFormatName.substring(6); if (!isSupportedImageFormat(mFormatName)) { throw new MapyrusException(MapyrusMessages.get(MapyrusMessages.INVALID_FORMAT) + ": " + format); } mOutputType = IMAGE_FILE; } setOutput(filename, width, height, extras, stdoutStream); } /** * Sets image for drawing into. * @param image is buffered image to draw into. * @param extras contains extra settings for this output. */ public OutputFormat(BufferedImage image, String extras) throws IOException, MapyrusException { mOutputType = INTERNAL_IMAGE; mImage = image; mFormatName = "png"; PrintStream dummyStdout = new PrintStream(new ByteArrayOutputStream()); setOutput("", 0, 0, extras, dummyStdout); } /** * Return page width. * @return width in millimetres. */ public double getPageWidth() { return(mPageWidth); } /** * Return page height. * @return height in millimetres. */ public double getPageHeight() { return(mPageHeight); } /** * Return file format of page. * @return file format of page in lowercase. */ public String getPageFormat() { return(mFormatName); } /** * Return resolution of page as a distance measurement. * @return distance in millimetres between centres of adjacent pixels. */ public double getResolution() { return(mResolution); } /** * Returns height and width of a string, drawn to current page. * @param s string to calculate width for. * @param fontName name of font to calculate dimensions for. * @param fontSize size of characters in millimetres. * @return height and width of string in millimetres. */ public StringDimension getStringDimension(String s, String fontName, double fontSize) throws IOException, MapyrusException { StringDimension retval = new StringDimension(); BufferedReader stringReader = new BufferedReader(new StringReader(s)); double width = 0, height = 0; String token; double tokenWidth; /* * Break multi-line strings into separate lines so we * can find the width of the longest line. */ while ((token = stringReader.readLine()) != null) { if (mOutputType == POSTSCRIPT_GEOMETRY) { /* * Load Font Metrics information only when it is needed. */ if (mAdobeFontMetrics == null) mAdobeFontMetrics = new AdobeFontMetricsManager(mAfmFiles, mEncodeAsISOLatin1); double pointSize = fontSize / Constants.MM_PER_INCH * Constants.POINTS_PER_INCH; tokenWidth = mAdobeFontMetrics.getStringWidth(fontName, pointSize, token); tokenWidth = tokenWidth / Constants.POINTS_PER_INCH * Constants.MM_PER_INCH; if (tokenWidth > width) width = tokenWidth; height += fontSize; } else { /* * Use Java2D calculation for bounding box of string displayed with * horizontal font. */ FontRenderContext frc = mGraphics2D.getFontRenderContext(); Rectangle2D bounds = mBaseFont.getStringBounds(token, frc); tokenWidth = bounds.getWidth(); if (tokenWidth > width) width = tokenWidth; height += bounds.getHeight(); } } retval.setSize(width, height); return(retval); } /** * Return mask for this page. * @return page mask. */ public PageMask getPageMask() { if (mPageMask == null) { mPageMask = new PageMask((int)Math.round(mPageWidth), (int)Math.round(mPageHeight)); } return(mPageMask); } /* * Write a line to PostScript, PDF or SVG file. * @return number of characters written to file. */ private int writeLine(PrintWriter writer, String line) { writer.write(line); writer.write("\r\n"); return(line.length() + 2); } /** * Write image to PostScript file. * @param image image to write. * @param x center position on page for image. * @param y center position on page for image. * @param width width of image in millimetres. * @param height height of image in millimetres. * @param rotation rotation angle for image. */ private void writePostScriptImage(BufferedImage image, double x, double y, double width, double height, double rotation) throws IOException, MapyrusException { int pixelWidth, pixelHeight; int step; pixelWidth = image.getWidth(); pixelHeight = image.getHeight(); /* * Calculate reduction in image size so that it is * an appropriate size for the resolution of the page. */ if (pixelWidth <= 16 || pixelHeight <= 16) { step = 1; } else { double bestPixelWidth = width / mResolution; double bestPixelHeight = height / mResolution; /* * Keep reducing image 1/2, 1/3, 1/4, ... until it reaches the * resolution of the page. Use that reduction for image. */ step = 1; while (pixelHeight / (step + 1) > bestPixelHeight && pixelWidth / (step + 1) > bestPixelWidth) { step++; } } int reducedPixelWidth = (pixelWidth + step - 1) / step; int reducedPixelHeight = (pixelHeight + step - 1) / step; /* * Check if image is a single color. * Draw single color images with transparent background * using PostScript 'imagemask' operator. * Draw other images as RGB images using 'image' operator. */ Color singleColor = getSingleImageColor(image); /* * Write PostScript image directionary entry to draw image. * Taken from Adobe PostScript Language Reference Manual * (2nd Edition), p. 234. */ writeLine(mWriter, "q"); writeLine(mWriter, "/DeviceRGB setcolorspace"); writeLine(mWriter, x + " " + y + " translate"); writeLine(mWriter, rotation + " radtodeg rotate"); writeLine(mWriter, width + " " + height + " scale"); /* * Image is centred at each point. * Shift image left and down half it's size so that it is displayed centred. */ writeLine(mWriter, "-0.5 -0.5 translate"); /* * Set color for drawing single color images. */ if (singleColor != null) { float []c = singleColor.getColorComponents(null); writeLine(mWriter, mCoordinateDecimal.format(c[0]) + " " + mCoordinateDecimal.format(c[1]) + " " + mCoordinateDecimal.format(c[2]) + " RG"); } writeLine(mWriter, "% original image size " + pixelWidth + "x" + pixelHeight + " with reduction factor " + step); writeLine(mWriter, "<<"); writeLine(mWriter, "/ImageType 1"); writeLine(mWriter, "/Width " + reducedPixelWidth); writeLine(mWriter, "/Height " + reducedPixelHeight); if (singleColor != null) { writeLine(mWriter, "/BitsPerComponent 1"); writeLine(mWriter, "/Decode [0 1]"); } else { writeLine(mWriter, "/BitsPerComponent 8"); writeLine(mWriter, "/Decode [0 1 0 1 0 1]"); } writeLine(mWriter, "/ImageMatrix [" + reducedPixelWidth + " 0 0 " + -reducedPixelHeight + " 0 " + reducedPixelHeight + "]"); writeLine(mWriter, "/DataSource currentfile /ASCII85Decode filter"); writeLine(mWriter, ">>"); if (singleColor != null) writeLine(mWriter, "imagemask"); else writeLine(mWriter, "image"); /* * Write ASCII85 encoded string containing all pixel values. */ ASCII85Writer ascii85 = new ASCII85Writer(mWriter); int byteValue = 0; int bitCounter = 0; for (int row = 0; row < pixelHeight; row += step) { for (int col = 0; col < pixelWidth; col += step) { int pixel = image.getRGB(col, row); if (singleColor != null) { /* * Pixel is set in PostScript image if it is transparent. */ int nextBit = ((pixel >> 24) == 0) ? 1 : 0; /* * Store next pixel value as a single bit in a byte. * If we've completed a byte or reached the end of a row * then write byte out and begin next byte. */ nextBit <<= (7 - bitCounter); byteValue |= nextBit; bitCounter++; if (bitCounter == 8 || (col + step >= pixelWidth)) { ascii85.write(byteValue); byteValue = bitCounter = 0; } } else { /* * Ignore transparency, we want only red, green, blue components * of pixel. */ int blue = (pixel & 0xff); int green = ((pixel >> 8) & 0xff); int red = ((pixel >> 16) & 0xff); ascii85.write(red); ascii85.write(green); ascii85.write(blue); } } } ascii85.close(); /* * Write ASCII85 end-of-data marker. */ writeLine(mWriter, "~>"); writeLine(mWriter, "Q"); } /** * Save state, protecting color, linestyle, transform of output. * This state can be restored later with restoreState(). */ public void saveState() { if (mOutputType == POSTSCRIPT_GEOMETRY) writeLine(mWriter, "q"); else if (mOutputType == PDF) writeLine(mPDFGeometryWriter, "q"); else if (mOutputType == SVG) writeLine(mWriter, "<g>"); } /** * Restore state saved with saveState(). * @return true if saved state was successfully restored. * Only PostScript format can be successfully restored, caller * will have to reset values for other formats. */ public boolean restoreState() { boolean retval; if (mOutputType == POSTSCRIPT_GEOMETRY) { writeLine(mWriter, "Q"); retval = true; } else if (mOutputType == PDF) { writeLine(mPDFGeometryWriter, "Q"); retval = true; } else { if (mOutputType == SVG) writeLine(mWriter, "</g>"); /* * Can't restore state when drawing to an image or SVG file. Caller * must set everything to correct values again. */ retval = false; } return(retval); } /** * Writes trailing and buffered information, then closes output file. */ public void closeOutputFormat() throws IOException, MapyrusException { if (mOutputType == POSTSCRIPT_GEOMETRY || mOutputType == POSTSCRIPT_IMAGE) { if (mOutputType == POSTSCRIPT_IMAGE) { /* * Write image file containing page. */ writePostScriptImage(mImage, mPageWidth / 2, mPageHeight / 2, mPageWidth, mPageHeight, 0); } /* * Finish off PostScript file. */ if (mFormatName.equals("ps")) { /* * showpage is not included in Encapsulated PostScript files. */ writeLine(mWriter, "showpage"); } writeLine(mWriter, "%%Trailer"); /* * Included list of fonts we used in this file but did * not include in the header. */ writeLine(mWriter, "%%DocumentNeededResources:"); Iterator it = mNeededFontResources.iterator(); while (it.hasNext()) { String fontName = (String)(it.next()); if (!mSuppliedFontResources.contains(fontName)) writeLine(mWriter, "%%+ font " + fontName); } writeLine(mWriter, "%%EOF"); if (mIsStandardOutput) mWriter.flush(); else mWriter.close(); if (mWriter.checkError()) { throw new MapyrusException(mFilename + ": " + MapyrusMessages.get(MapyrusMessages.ERROR_PS)); } /* * If updating file then replace existing file with completed * temporary file now. */ if (mTempFile != null) { if ((!new File(mFilename).delete()) || (!mTempFile.renameTo(new File(mFilename)))) { mTempFile.delete(); throw new MapyrusException(MapyrusMessages.get(MapyrusMessages.READ_ONLY) + ": " + mFilename); } } } else if (mOutputType == PDF) { /* * Now that we have the complete geometry, we can write it to the PDF file. */ mPDFGeometryWriter.flush(); String geometry = mPDFGeometryStringWriter.toString(); int nChars = writeLine(mWriter, "5 0 obj"); nChars += writeLine(mWriter, "<< /Length " + geometry.length() + " >>"); nChars += writeLine(mWriter, "stream"); nChars += writeLine(mWriter, geometry); nChars += writeLine(mWriter, "endstream"); nChars += writeLine(mWriter, "endobj"); Integer offset = (Integer)mPDFFileOffsets.get(mPDFFileOffsets.size() - 1); mPDFFileOffsets.add(new Integer(offset.intValue() + nChars)); nChars = writeLine(mWriter, "6 0 obj"); nChars += writeLine(mWriter, "[/PDF]"); nChars += writeLine(mWriter, "endobj"); Iterator it = mPDFImageObjects.iterator(); while (it.hasNext()) { nChars += writeLine(mWriter, "%" + it.next().toString()); } /* * Write cross reference table giving file offset of each * object in PDF file. */ writeLine(mWriter, "xref"); writeLine(mWriter, "0 " + (mPDFFileOffsets.size() + 1)); writeLine(mWriter, "0000000000 65535 f"); it = mPDFFileOffsets.iterator(); while (it.hasNext()) { String fileOffset = it.next().toString(); int padding = 10 - fileOffset.length(); StringBuffer sb = new StringBuffer(); while (padding-- > 0) sb.append('0'); sb.append(fileOffset); sb.append(" 00000 n"); writeLine(mWriter, sb.toString()); } writeLine(mWriter, "trailer"); writeLine(mWriter, "<< /Size " + (mPDFFileOffsets.size() + 1) + " /Root 1 0 R >>"); /* * Write file offset of start of cross reference table. */ writeLine(mWriter, "startxref"); offset = (Integer)mPDFFileOffsets.get(mPDFFileOffsets.size() - 1); writeLine(mWriter, Integer.toString(offset.intValue() + nChars)); writeLine(mWriter, "%%EOF"); if (mIsStandardOutput) mWriter.flush(); else mWriter.close(); if (mWriter.checkError()) { throw new MapyrusException(mFilename + ": " + MapyrusMessages.get(MapyrusMessages.ERROR_PS)); } } else if (mOutputType == SVG) { writeLine(mWriter, "</g>"); writeLine(mWriter, "</svg>"); if (mIsStandardOutput) mWriter.flush(); else mWriter.close(); if (mWriter.checkError()) { throw new MapyrusException(mFilename + ": " + MapyrusMessages.get(MapyrusMessages.ERROR_SVG)); } } else if (mOutputType == IMAGE_FILE) { /* * If updating file then overwrite it now with new image. */ if (mIsUpdatingFile) mOutputStream = new FileOutputStream(mFilename); /* * Write image buffer to file. */ ImageIOWrapper.write(mImage, mFormatName, mOutputStream); if (mIsStandardOutput) mOutputStream.flush(); else mOutputStream.close(); } else if (mOutputType == SCREEN_WINDOW) { /* * Show image we have created in a window. * Then wait for user to close the window. */ String title = Constants.PROGRAM_NAME + ": " + mFilename; MapyrusFrame frame = new MapyrusFrame(title, mImage); frame.waitForClose(); } mImage = null; mGraphics2D = null; if (mOutputType != INTERNAL_IMAGE) { /* * If we are piping output to another program then wait for * that program to finish. Then check that it succeeded. */ if (mIsPipedOutput) { int retval = 0; try { retval = mOutputProcess.waitFor(); } catch (InterruptedException e) { throw new MapyrusException(mFilename + ": " + e.getMessage()); } if (retval != 0) { throw new MapyrusException(MapyrusMessages.get(MapyrusMessages.PROCESS_ERROR) + ": " + retval + ": " + mFilename); } } } if (mImageMapWriter != null) { mImageMapWriter.close(); } } /** * Set font for labelling in output format. * @param fontName is name of font as defined in java.awt.Font class. * @param fontSize is size for labelling in millimetres. * @param fontRotation is rotation angle for font, in degrees, * measured counter-clockwise. * @param outlineWidth if non-zero, labels will drawn as character outlines * with this width. */ public void setFontAttribute(String fontName, double fontSize, double fontRotation, double outlineWidth) throws IOException, MapyrusException { if (mOutputType == POSTSCRIPT_GEOMETRY) { if (mEncodeAsISOLatin1.contains(fontName)) { /* * Re-encode font from StandardEncoding to ISOLatin1Encoding * before it is used. */ writeLine(mWriter, isoLatinEncode(fontName)); mEncodeAsISOLatin1.remove(fontName); } /* * Set font and size for labelling. */ writeLine(mWriter, "/" + fontName + " " + fontSize + " " + fontRotation + " " + outlineWidth + " font"); mNeededFontResources.add(fontName); } else { /* * Split font name into font and style. */ int style = Font.PLAIN; if (fontName.endsWith("-Bold")) { style = Font.BOLD; fontName = fontName.substring(0, fontName.length() - 5); } else if (fontName.endsWith("-Italic")) { style = Font.ITALIC; fontName = fontName.substring(0, fontName.length() - 7); } else if (fontName.endsWith("-BoldItalic")) { style = Font.BOLD|Font.ITALIC; fontName = fontName.substring(0, fontName.length() - 11); } /* * Continually opening and deriving fonts is probably expensive. * Check that new font is actually different to current font * before defining it. */ Font currentFont = mGraphics2D.getFont(); float newSize = (float)fontSize; float currentSize = currentFont.getSize2D(); String currentFontName = currentFont.getName(); if (newSize != currentSize || style != currentFont.getStyle() || (!fontName.equals(currentFontName)) || fontRotation != mFontRotation) { /* * We need a base font that is not rotated for calculating * string widths for justifying text. * Get base font from cache, or create it if we don't find it there. */ mBaseFont = mFontCache.get(fontName, style, newSize, 0); if (mBaseFont == null) { /* * If this is a font for which user provided a TTF file then * use that, else expect the operating system to be able to * open the font. */ TrueTypeFont ttf = (TrueTypeFont)mTTFFonts.get(fontName); if (ttf != null) mBaseFont = ttf.getFont().deriveFont(style, newSize); else mBaseFont = new Font(fontName, style, (int)newSize).deriveFont(newSize); mFontCache.put(fontName, style, newSize, 0, mBaseFont); } /* * The real font used for labelling must be mirrored in Y axis * (to reverse the transform we use on Graphics2D objects) and * rotated to the angle the user wants. * * Look it up in cache too. */ Font font = mFontCache.get(fontName, style, -newSize, fontRotation); if (font == null) { AffineTransform fontTransform; fontTransform = AffineTransform.getRotateInstance(fontRotation); fontTransform.scale(1, -1); font = mBaseFont.deriveFont(fontTransform); mFontCache.put(fontName, style, -newSize, fontRotation, font); } mGraphics2D.setFont(font); } } /* * Font rotation and outlining not easily held in a Graphics2D * object so keep track of it's current value ourselves. */ mFontRotation = fontRotation; mFontOutlineWidth = outlineWidth; } /** * Set label justification in output format. * @param justify is label justification value, combination of JUSTIFY_* bit flags. */ public void setJustifyAttribute(int justify) { /* * Calculate fraction of string height and width to move text to get required * justification. */ if ((justify & JUSTIFY_LEFT) != 0) mJustificationShiftX = 0.0; else if ((justify & JUSTIFY_CENTER) != 0) mJustificationShiftX = -0.5; else mJustificationShiftX = -1.0; if ((justify & JUSTIFY_BOTTOM) != 0) mJustificationShiftY = 0.0; else if ((justify & JUSTIFY_MIDDLE) != 0) mJustificationShiftY = -0.5; else mJustificationShiftY = -1.0; if (mOutputType == POSTSCRIPT_GEOMETRY) { /* * Define dictionary entries for justification settings for PostScript * procedure to use for aligning text correctly itself. */ writeLine(mWriter, mJustificationShiftX + " " + mJustificationShiftY + " ju"); } } /** * Set color in output format. * @param color is color to draw in. */ public void setColorAttribute(Color color) { if (mOutputType == POSTSCRIPT_GEOMETRY || mOutputType == PDF) { float c[] = color.getRGBColorComponents(null); PrintWriter pw; if (mOutputType == PDF) pw = mPDFGeometryWriter; else pw = mWriter; StringBuffer sb = new StringBuffer(); sb.append(mCoordinateDecimal.format(c[0])); sb.append(' '); sb.append(mCoordinateDecimal.format(c[1])); sb.append(' '); sb.append(mCoordinateDecimal.format(c[2])); writeLine(pw, sb.toString() + " RG"); if (mOutputType == PDF) writeLine(pw, sb.toString() + " rg"); } else { mGraphics2D.setColor(color); } } /** * Set linestyle in output format. * @param linestyle is Java2D line width, cap and join style, dash pattern. */ public void setLinestyleAttribute(BasicStroke linestyle) { if (mOutputType == POSTSCRIPT_GEOMETRY || mOutputType == PDF) { PrintWriter pw; if (mOutputType == PDF) pw = mPDFGeometryWriter; else pw = mWriter; /* * Convert BasicStroke end cap and line join values to PostScript. */ int cap = linestyle.getEndCap(); if (cap == BasicStroke.CAP_BUTT) cap = 0; else if (cap == BasicStroke.CAP_ROUND) cap = 1; else /* SQUARE */ cap = 2; int join = linestyle.getLineJoin(); if (join == BasicStroke.JOIN_MITER) join = 0; else if (join == BasicStroke.JOIN_ROUND) join = 1; else /* BEVEL */ join = 2; writeLine(pw, mCoordinateDecimal.format(linestyle.getLineWidth()) + " w " + cap + " J " + join + " j " + mCoordinateDecimal.format(linestyle.getMiterLimit()) + " M"); /* * If there a dash pattern then set that too. */ float dashes[] = linestyle.getDashArray(); if (dashes != null) { StringBuffer s = new StringBuffer("["); for (int i = 0; i < dashes.length; i++) { if (i > 0) s.append(" "); s.append(mCoordinateDecimal.format(dashes[i])); } s.append("] "); s.append(linestyle.getDashPhase()); s.append(" d"); writeLine(pw, s.toString()); } else { /* * Remove any dashed line previously defined. */ writeLine(pw, "[] 0 d"); } } else { mGraphics2D.setStroke(linestyle); } } /** * Set clip path for output format. * @param clipPaths are polygons to clip against, or null if * there are no clip polygons. */ public void setClipAttribute(ArrayList clipPaths) { if (mOutputType != POSTSCRIPT_GEOMETRY && mOutputType != PDF) { mGraphics2D.setClip(null); mIsClipPathActive = (clipPaths != null && clipPaths.size() > 0); if (mIsClipPathActive) { if (mOutputType == SVG) { mClipPathCounter++; writeLine(mWriter, "<clipPath id=\"clip" + mClipPathCounter + "\">"); } for (int i = 0; i < clipPaths.size(); i++) { GeometricPath clipPath = (GeometricPath)(clipPaths.get(i)); if (mOutputType == SVG) { writeLine(mWriter, "<path d=\""); writeShape(clipPath.getShape(), mOutputType, mWriter, null); writeLine(mWriter, "\"/>"); } else { mGraphics2D.clip(clipPath.getShape()); } } if (mOutputType == SVG) writeLine(mWriter, "</clipPath>"); } } } /* * Walk through path, converting it to output format. */ private void writeShape(Shape shape, int outputType, PrintWriter pw, String scriptCommands) { PathIterator pi; if (outputType == IMAGEMAP) { pi = shape.getPathIterator(null, mResolution); } else { pi = shape.getPathIterator(null); } float coords[] = new float[6]; float lastX = 0.0f, lastY = 0.0f; float x = 0.0f, y = 0.0f; float distSquared; float resolutionSquared = (float)(mResolution * mResolution); int segmentType = PathIterator.SEG_CLOSE; boolean skippedLastSegment = false; String imageMapString = null; while (!pi.isDone()) { segmentType = pi.currentSegment(coords); switch (segmentType) { case PathIterator.SEG_MOVETO: lastX = coords[0]; lastY = coords[1]; if (outputType == SVG) { writeLine(pw, "M " + mCoordinateDecimal.format(lastX) + " " + mCoordinateDecimal.format(mPageHeight - lastY)); } else if (outputType == IMAGEMAP) { if (imageMapString != null) mImageMapWriter.println(imageMapString); mImageMapWriter.println("<area shape=\"polygon\" coords=\"" + Math.round(lastX / mResolution) + "," + Math.round((mPageHeight - lastY) / mResolution)); imageMapString = "\" " + scriptCommands + " >"; } else { writeLine(pw, mCoordinateDecimal.format(lastX) + " " + mCoordinateDecimal.format(lastY) + " m"); } skippedLastSegment = false; break; case PathIterator.SEG_LINETO: x = coords[0]; y = coords[1]; distSquared = (lastX - x) * (lastX - x) + (lastY - y) * (lastY - y); if (distSquared >= resolutionSquared) { if (outputType == SVG) { String sx = mCoordinateDecimal.format(x); String sy = mCoordinateDecimal.format(mPageHeight - y); /* * Use shortcut path types for horizontal * and vertical line segments. */ if (x == lastX) writeLine(pw, "V " + sy); else if (y == lastY) writeLine(pw, "H " + sx); else writeLine(pw, "L " + sx + " " + sy); } else if (outputType == IMAGEMAP) { mImageMapWriter.println("," + Math.round(x / mResolution) + "," + Math.round((mPageHeight - y) / mResolution)); } else { writeLine(pw, mCoordinateDecimal.format(x) + " " + mCoordinateDecimal.format(y) + " l"); } lastX = x; lastY = y; skippedLastSegment = false; } else { /* * Skip segments that are less than one unit of resolution in length. */ skippedLastSegment = true; } break; case PathIterator.SEG_CLOSE: if (skippedLastSegment) { if (outputType == SVG) { writeLine(pw, "L " + mCoordinateDecimal.format(x) + " " + mCoordinateDecimal.format(mPageHeight - y)); } else if (outputType == IMAGEMAP) { if (imageMapString != null) { mImageMapWriter.println("," + Math.round(x / mResolution) + "," + Math.round((mPageHeight - y) / mResolution)); } } else { writeLine(pw, mCoordinateDecimal.format(x) + " " + mCoordinateDecimal.format(y) + " l"); } } if (outputType == SVG) { writeLine(pw, "z"); } else if (outputType == IMAGEMAP) { if (imageMapString != null) { mImageMapWriter.println(imageMapString); imageMapString = null; } } else { writeLine(pw, "h"); } skippedLastSegment = false; break; case PathIterator.SEG_CUBICTO: if (outputType == SVG) { writeLine(pw, "C " + mCoordinateDecimal.format(coords[0]) + " " + mCoordinateDecimal.format(mPageHeight - coords[1]) + " " + mCoordinateDecimal.format(coords[2]) + " " + mCoordinateDecimal.format(mPageHeight - coords[3]) + " " + mCoordinateDecimal.format(coords[4]) + " " + mCoordinateDecimal.format(mPageHeight - coords[5])); } else { writeLine(pw, mCoordinateDecimal.format(coords[0]) + " " + mCoordinateDecimal.format(coords[1]) + " " + mCoordinateDecimal.format(coords[2]) + " " + mCoordinateDecimal.format(coords[3]) + " " + mCoordinateDecimal.format(coords[4]) + " " + mCoordinateDecimal.format(coords[5]) + " " + "c"); } lastX = coords[4]; lastY = coords[5]; skippedLastSegment = false; break; } pi.next(); } if (skippedLastSegment) { /* * Always include last point in lines and polygons, * never skip it. */ if (outputType == SVG) { writeLine(pw, "L " + mCoordinateDecimal.format(x) + " " + mCoordinateDecimal.format(mPageHeight - y)); } else if (outputType == IMAGEMAP) { if (imageMapString != null) { mImageMapWriter.println("," + Math.round(x / mResolution) + "," + Math.round((mPageHeight - y) / mResolution)); } } else { writeLine(pw, mCoordinateDecimal.format(x) + " " + mCoordinateDecimal.format(y) + " l"); } } /* * Complete any imagemap being created. */ if (outputType == IMAGEMAP && imageMapString != null) { mImageMapWriter.println(imageMapString); } } /** * Determines single color used in an image. * @param image image to check. * @return single non-transparent color used in an image, or null if * image has many colors. */ private Color getSingleImageColor(BufferedImage image) { Color singleColor = Color.BLACK; boolean foundDifferentColors = false; boolean foundFirstColor = false; int imageWidth = image.getWidth(); int imageHeight = image.getHeight(); /* * Check if all pixels are the same color, or transparent. */ int y = 0; while (y < imageHeight && (!foundDifferentColors)) { int x = 0; while (x < imageWidth && (!foundDifferentColors)) { int pixel = image.getRGB(x, y); if ((pixel & 0xff000000) != 0) { /* * Pixel is not transparent. */ if (!foundFirstColor) { foundFirstColor = true; singleColor = new Color(pixel & 0xffffff); } else { foundDifferentColors = (pixel != singleColor.getRGB()); } } x++; } y++; } if (foundDifferentColors) singleColor = null; return(singleColor); } /** * Draw icon at points on page. * @param pointList is list of Point2D objects at which to draw icon. * @param icon image to draw. * @param size is size of icon in millimeters, or zero for screen size. * @param rotation rotation angle for icon. * @param scaling scale factor for icon. */ public void drawIcon(ArrayList pointList, BufferedImage image, double size, double rotation, double scaling) throws IOException, MapyrusException { int pixelWidth = image.getWidth(); int pixelHeight = image.getHeight(); Point2D pt; int i; double x, y, mmWidth, mmHeight; /* * If size not given then make icon about as large as it would appear * on the screen in an image viewer, with one image pixel in one screen * pixel. */ if (size <= 0.0) { size = Math.max(pixelWidth, pixelHeight) * (Constants.MM_PER_INCH / Constants.getScreenResolution()); } size *= scaling; /* * Calculate width and height for non-square images. */ if (pixelWidth > pixelHeight) { mmWidth = size; mmHeight = size * ((double)pixelHeight / pixelWidth); } else { mmHeight = size; mmWidth = size * ((double)pixelWidth / pixelHeight); } if (mOutputType == POSTSCRIPT_GEOMETRY) { /* * Draw icon at each position in list. */ for (i = 0; i < pointList.size(); i++) { pt = (Point2D)(pointList.get(i)); x = pt.getX(); y = pt.getY(); /* * Skip points that are outside page. */ if (x + mmWidth >= 0 && x - mmWidth <= mPageWidth && y + mmHeight >= 0.0 && y - mmHeight <= mPageHeight) { writePostScriptImage(image, x, y, mmWidth, mmHeight, rotation); } } } else if (mOutputType != SVG) { for (i = 0; i < pointList.size(); i++) { pt = (Point2D)(pointList.get(i)); x = pt.getX(); y = pt.getY(); AffineTransform affine = AffineTransform.getTranslateInstance(x, y); /* * Scale transformation so that units are in pixels. */ double mmPerPixel = Constants.MM_PER_INCH / Constants.getScreenResolution(); affine.scale(mmPerPixel, mmPerPixel * -1); /* * Rotate clockwise around point (x, y). */ affine.rotate(-rotation); /* * Scale image to requested size. */ double xScale = (mmWidth / mmPerPixel) / pixelWidth; double yScale = (mmHeight / mmPerPixel) / pixelHeight; affine.scale(xScale, yScale); /* * Shift origin so that middle of image is at point (x, y). */ affine.translate(-pixelWidth / 2.0, -pixelHeight / 2.0); try { /* * Sun JVM throws NullPointerException if image is * too big to fit in memory. */ mGraphics2D.drawImage(image, affine, null); } catch (NullPointerException e) { throw new OutOfMemoryError("Failed loading icon."); } } } } /** * Draw geo-referenced image on page. * @param image image to display. * @param x X coordinate of bottom left corner of image. * @param y Y coordinate of bottom left corner of image. * @param width width of image in millimetres. * @param height height of image in millimetres. */ public void drawGeoImage(BufferedImage image, double x, double y, double width, double height) throws MapyrusException, IOException { if (mOutputType == POSTSCRIPT_GEOMETRY) { writePostScriptImage(image, x + width / 2, y + height / 2, width, height, 0); } else { /* * Position image on page, inverting it to appear right way up * and scaling it to requested size. */ AffineTransform affine = AffineTransform.getTranslateInstance(x, y + height); affine.scale(1, -1); affine.scale(width / image.getWidth(), height / image.getHeight()); mGraphics2D.drawImage(image, affine, null); } } /** * Draw EPS file at points on page. * @param pointList is list of Point2D objects at which to draw EPS file. * @param EPS filename. * @param size size for EPS file on page in millimetres. * @param rotation rotation angle for EPS file. * @param scaling scale factor for EPS file. */ public void drawEPS(ArrayList pointList, String filename, double size, double rotation, double scaling) throws IOException, MapyrusException { PostScriptFile psfile = new PostScriptFile(filename); Rectangle boundingBox = psfile.getBoundingBox(); int pointWidth = (int)boundingBox.getWidth(); int pointHeight = (int)boundingBox.getHeight(); Point2D pt; int i; double x, y; /* * If size not given then make EPS about as large as defined in the EPS file. */ if (size <= 0.0) { size = Math.max(pointWidth, pointHeight) * (Constants.MM_PER_INCH / Constants.POINTS_PER_INCH); } size *= scaling; if (mOutputType == POSTSCRIPT_GEOMETRY) { /* * Include EPS file at each position in list. */ for (i = 0; i < pointList.size(); i++) { pt = (Point2D)(pointList.get(i)); x = pt.getX(); y = pt.getY(); /* * Skip points that are outside page. */ if (x + size >= 0 && x - size <= mPageWidth && y + size >= 0.0 && y - size <= mPageHeight) { writeLine(mWriter, "save"); writeLine(mWriter, x + " " + y + " translate"); writeLine(mWriter, rotation + " radtodeg rotate"); /* * EPS file is centred at each point. * Shift position left and down half it's size * so that it is displayed centered. */ writeLine(mWriter, -(size / 2) + " " + -(size / 2) + " translate"); double scale = size / Math.max(pointWidth, pointHeight); writeLine(mWriter, scale + " dup scale"); /* * Shift EPS file so that lower-left corner of EPS file is in * lower left corner of our box on the page. */ writeLine(mWriter, -boundingBox.getMinX() + " " + -boundingBox.getMinY() + " translate"); /* * Set graphics attributes to initial values, as described * on page 728 of PostScript Language Reference Manual. */ writeLine(mWriter, "/showpage {} def"); writeLine(mWriter, "0 setgray 0 setlinecap 1 setlinewidth"); writeLine(mWriter, "0 setlinejoin 10 setmiterlimit [] 0 setdash newpath"); writeLine(mWriter, "%%BeginDocument: (" + filename + ")"); BufferedReader reader = null; try { reader = new FileOrURL(filename).getReader(); String line; while ((line = reader.readLine()) != null) { writeLine(mWriter, line); } writeLine(mWriter, "%%EndDocument"); writeLine(mWriter, "restore"); } finally { /* * Ensure EPS file is always closed. */ if (reader != null) reader.close(); } } } } else { /* * We cannot show EPS files when drawing to an image file so show a * transparent grey box where the EPS file would appear. */ GeneralPath path = new GeneralPath(); Color currentColor = mGraphics2D.getColor(); mGraphics2D.setColor(new Color(127, 127, 127, 127)); for (i = 0; i < pointList.size(); i++) { pt = (Point2D)(pointList.get(i)); x = pt.getX(); y = pt.getY(); double xDist = Math.cos(rotation) * size / 2; double yDist = Math.sin(rotation) * size / 2; Point2D currentPoint; path.reset(); path.moveTo((float)(x - xDist + yDist), (float)(y - yDist - xDist)); currentPoint = path.getCurrentPoint(); path.lineTo((float)(currentPoint.getX() - yDist - yDist), (float)(currentPoint.getY() + xDist + xDist)); currentPoint = path.getCurrentPoint(); path.lineTo((float)(currentPoint.getX() + xDist + xDist), (float)(currentPoint.getY() + yDist + yDist)); currentPoint = path.getCurrentPoint(); path.lineTo((float)(currentPoint.getX() + yDist + yDist), (float)(currentPoint.getY() - xDist - xDist)); path.closePath(); fill(path); } mGraphics2D.setColor(currentColor); } } /** * Draw currently defined path to output page. */ public void stroke(Shape shape) { if (mOutputType == POSTSCRIPT_GEOMETRY || mOutputType == SVG || mOutputType == PDF) { if (shape.intersects(0.0, 0.0, mPageWidth, mPageHeight)) { if (mOutputType == SVG) { writeLine(mWriter, "<path d=\""); writeShape(shape, mOutputType, mWriter, null); writeLine(mWriter, "\""); Color color = mGraphics2D.getColor(); BasicStroke stroke = (BasicStroke)mGraphics2D.getStroke(); float width = stroke.getLineWidth(); int endCap = stroke.getEndCap(); int lineJoin = stroke.getLineJoin(); float []dashArray = stroke.getDashArray(); float dashPhase = stroke.getDashPhase(); String capString, joinString; if (endCap == BasicStroke.CAP_BUTT) capString = "butt"; else if (endCap == BasicStroke.CAP_SQUARE) capString = "square"; else capString = "round"; if (lineJoin == BasicStroke.JOIN_BEVEL) joinString = "bevel"; else if (lineJoin == BasicStroke.JOIN_MITER) joinString = "miter"; else joinString = "round"; if (mIsClipPathActive) { writeLine(mWriter, " clip-path=\"url(#clip" + mClipPathCounter + ")\""); } writeLine(mWriter, " style=\"stroke:" + ColorDatabase.toHexString(color) + ";stroke-width:" + width + ";stroke-linecap:" + capString + ";stroke-linejoin:" + joinString); if (dashArray != null) { StringBuffer dashes = new StringBuffer(";stroke-dasharray:"); for (int i = 0 ; i < dashArray.length; i++) { if (i > 0) dashes.append(","); dashes.append(mCoordinateDecimal.format(dashArray[i])); } writeLine(mWriter, dashes.toString()); writeLine(mWriter, ";stroke-dashoffset:" + dashPhase); } int alpha = color.getAlpha(); if (alpha != 255) { writeLine(mWriter, ";stroke-opacity:" + (alpha / 255.0f)); } writeLine(mWriter, ";fill:none\"/>"); } else { PrintWriter pw; if (mOutputType == PDF) pw = mPDFGeometryWriter; else pw = mWriter; writeShape(shape, mOutputType, pw, null); writeLine(pw, "S"); } } } else { /* * Draw path into image. */ mGraphics2D.draw(shape); } } /** * Fill currently defined path on output page. * @param shape shape to fill on page. * run when this shape is clicked. */ public void fill(Shape shape) { if (mOutputType == POSTSCRIPT_GEOMETRY || mOutputType == SVG || mOutputType == PDF) { if (shape.intersects(0.0, 0.0, mPageWidth, mPageHeight)) { if (mOutputType == SVG) { writeLine(mWriter, "<path d=\""); writeShape(shape, mOutputType, mWriter, null); writeLine(mWriter, "\""); Color color = mGraphics2D.getColor(); int alpha = color.getAlpha(); if (mIsClipPathActive) { writeLine(mWriter, " clip-path=\"url(#clip" + mClipPathCounter + ")\""); } StringBuffer sb = new StringBuffer(" style=\"fill:"); sb.append(ColorDatabase.toHexString(color)); if (alpha != 255) { sb.append(";fill-opacity:" + (alpha / 255.0f)); } sb.append(";stroke:none\"/>"); writeLine(mWriter, sb.toString()); } else { PrintWriter pw; if (mOutputType == PDF) pw = mPDFGeometryWriter; else pw = mWriter; writeShape(shape, mOutputType, pw, null); writeLine(pw, "f"); } } } else { /* * Fill path in image. */ mGraphics2D.fill(shape); } } /** * Set script commands for path on output page. * @param shape shape to fill on page. * @param scriptCommands script language commands to * run when this shape is clicked. */ public void setEventScript(Shape shape, String scriptCommands) { if (mImageMapWriter != null) { /* * Write shape to image map together with script commands. */ writeShape(shape, IMAGEMAP, mWriter, scriptCommands); } else if (mOutputType == SVG) { /* * Embed script commands in SVG file. */ writeLine(mWriter, "<path d=\""); writeShape(shape, mOutputType, mWriter, scriptCommands); writeLine(mWriter, "\""); writeLine(mWriter, scriptCommands); writeLine(mWriter, "/>"); } } /** * Fill currently defined path with gradient fill pattern. * @param shape current path to be filled. * @param isVerticalGradient true if vertical color gradient to be used, * false for horizontal. * @param c1 color for left or bottom of path. * @param c2 color for right or top of path. */ public void gradientFill(Shape shape, boolean isVerticalGradient, Color c1, Color c2) { if (mOutputType == SVG) { if (shape.intersects(0.0, 0.0, mPageWidth, mPageHeight)) { String uniqueId = "gradient" + mGradientCounter++; writeLine(mWriter, "<defs>"); writeLine(mWriter, "<linearGradient id=\"" + uniqueId + "\""); /* * SVG supports only horizontal gradients (default) or vertical * gradients. */ if (isVerticalGradient) writeLine(mWriter, "x1=\"0%\" y1=\"100%\" x2=\"0%\" y2=\"0%\""); writeLine(mWriter, ">"); writeLine(mWriter, "<stop offset=\"0%\" stop-color=\"" + ColorDatabase.toHexString(c1) + "\"/>"); writeLine(mWriter, "<stop offset=\"100%\" stop-color=\"" + ColorDatabase.toHexString(c2) + "\"/>"); writeLine(mWriter, "</linearGradient>"); writeLine(mWriter, "</defs>"); writeLine(mWriter, "<path d=\""); writeShape(shape, mOutputType, mWriter, null); writeLine(mWriter, "\""); if (mIsClipPathActive) { writeLine(mWriter, " clip-path=\"url(#clip" + mClipPathCounter + ")\""); } writeLine(mWriter, " fill=\"url(#" + uniqueId + ")\" stroke=\"none\"/>"); } } } /** * Set clip region to inside of currently defined path on output page. */ public void clip(Shape shape) { if (mOutputType == POSTSCRIPT_GEOMETRY || mOutputType == PDF) { PrintWriter pw; if (mOutputType == PDF) pw = mPDFGeometryWriter; else pw = mWriter; /* * Set clip path now, then it stays in effect until previous * state is restored. */ if (shape.intersects(0.0, 0.0, mPageWidth, mPageHeight)) { writeShape(shape, mOutputType, pw, null); } else { /* * Clip region is outside page. Clip to simple rectangle * outside page instead so that nothing is shown. */ writeShape(new Rectangle2D.Float(-1.0f, -1.0f, 0.1f, 0.1f), mOutputType, pw, null); } writeLine(pw, "W n"); } } /** * Convert a string to PostScript format, escaping special characters and * write it to PostScript file. * @param s is string to convert and write. */ private void writePostScriptString(String s) { char c; StringBuffer buffer = new StringBuffer("("); for (int i = 0; i < s.length(); i++) { /* * Wrap strings that get too long. */ if (buffer.length() > 72) { buffer.append('\\'); writeLine(mWriter, buffer.toString()); buffer.setLength(0); } /* * Convert backslashes to '\\' and other special characters to octal code. */ c = s.charAt(i); if (c == '\\') { buffer.append("\\\\"); } else if (c == '(' || c == ')' || c == '%' || c < ' ' || c > 'z') { int extendedChar = c; int b1 = extendedChar / (8 * 8); extendedChar -= b1 * (8 * 8); int b2 = extendedChar / 8; extendedChar -= b2 * 8; int b3 = extendedChar; buffer.append('\\'); buffer.append(b1); buffer.append(b2); buffer.append(b3); } else { buffer.append(c); } } buffer.append(")"); writeLine(mWriter, buffer.toString()); } /** * Draw label positioned at (or along) currently defined path. * @param pointList is list of Point2D objects at which to draw label. * @param label is string to draw on path. */ public void label(ArrayList pointList, String label) { Point2D pt, startPt; double x, y; String nextLine; StringTokenizer st; int lineNumber; AffineTransform affine; FontRenderContext frc = null; Stroke originalStroke = null; if (mOutputType != POSTSCRIPT_GEOMETRY) { frc = mGraphics2D.getFontRenderContext(); if (mFontOutlineWidth > 0) { /* * Save existing linestyle and create new one for drawing outlines of each letter. */ originalStroke = mGraphics2D.getStroke(); BasicStroke outlineStroke = new BasicStroke((float)mFontOutlineWidth, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 2.0f); mGraphics2D.setStroke(outlineStroke); } } /* * Draw label at each position in list. */ for (int i = 0; i < pointList.size(); i++) { pt = (Point2D)(pointList.get(i)); x = pt.getX(); y = pt.getY(); /* * Draw each line of label below the one above. */ st = new StringTokenizer(label, Constants.LINE_SEPARATOR); lineNumber = 0; while (st.hasMoreTokens()) { nextLine = st.nextToken(); if (mOutputType == POSTSCRIPT_GEOMETRY) { writeLine(mWriter, mCoordinateDecimal.format(x) + " " + mCoordinateDecimal.format(y) + " m"); /* * Pass counter and line to PostScript procedure for * drawing each line of the label. */ writeLine(mWriter, Integer.toString(lineNumber)); writePostScriptString(nextLine); writeLine(mWriter, "t"); } else if (mOutputType == SVG) { double yInc = 0; if (lineNumber > 0) { Rectangle2D bounds = mBaseFont.getStringBounds(nextLine, frc); yInc = bounds.getHeight() * lineNumber; } String anchor; if (mJustificationShiftX == -1) anchor = "end"; else if (mJustificationShiftX == 0) anchor = "start"; else anchor = "middle"; Color color = mGraphics2D.getColor(); int alpha = color.getAlpha(); Font font = mGraphics2D.getFont(); StringBuffer extras = new StringBuffer(); if (font.isBold()) extras.append(" font-weight=\"bold\" "); if (font.isItalic()) extras.append(" font-style=\"italic\" "); if (mFontOutlineWidth > 0) { extras.append(" stroke=\""); extras.append(ColorDatabase.toHexString(color)); extras.append("\" stroke-width=\""); extras.append(mFontOutlineWidth); extras.append("\" "); if (alpha != 255) { extras.append(" stroke-opacity=\""); extras.append(alpha / 255.0f); extras.append("\" "); } } else { extras.append(" fill=\""); extras.append(ColorDatabase.toHexString(color)); extras.append("\" "); if (alpha != 255) { extras.append(" fill-opacity=\""); extras.append(alpha / 255.0f); extras.append("\" "); } } if (mIsClipPathActive) { extras.append(" clip-path=\"url(#clip"); extras.append(mClipPathCounter); extras.append(")\" "); } double px, py; if (mFontRotation != 0) { /* * Rotate text around origin point. * Rotation is negative sense because Y axis * decreases downwards. */ writeLine(mWriter, "<g transform=\"translate(" + mCoordinateDecimal.format(x) + ", " + mCoordinateDecimal.format(mPageHeight - y) + ") rotate(" + mCoordinateDecimal.format(Math.toDegrees(-mFontRotation)) + ")\">"); px = py = 0; } else { px = x; py = mPageHeight - (y - yInc); } /* * Shift text to correct vertical alignment. */ py -= mJustificationShiftY * font.getSize2D(); writeLine(mWriter, "<text x=\"" + mCoordinateDecimal.format(px) + "\" y=\"" + mCoordinateDecimal.format(py) + "\" text-anchor=\"" + anchor + "\""); String fontName = font.getName(); /* * Change default Java font names to something sensible. */ if (fontName.equalsIgnoreCase("sansserif") || fontName.equalsIgnoreCase("dialog")) { fontName = "Courier"; } writeLine(mWriter, " font-family=\"" + fontName + "\" " + "font-size=\"" + font.getSize2D() + "\" " + extras.toString()); /* * Make text string XML safe. */ nextLine = nextLine.replaceAll("&", "&amp;"); nextLine = nextLine.replaceAll("<", "&lt;"); nextLine = nextLine.replaceAll(">", "&gt;"); nextLine = nextLine.replaceAll("\"", "&quot;"); writeLine(mWriter, ">" + nextLine + "</text>"); if (mFontRotation != 0) writeLine(mWriter, "</g>"); } else { /* * Reposition label from original point so it has correct justification. */ if (mJustificationShiftX != 0.0 || mJustificationShiftY != 0.0 || lineNumber > 0) { Rectangle2D bounds = mBaseFont.getStringBounds(nextLine, frc); affine = AffineTransform.getTranslateInstance(x, y); affine.rotate(mFontRotation); startPt = new Point2D.Double(bounds.getWidth() * mJustificationShiftX, bounds.getHeight() * (mJustificationShiftY - lineNumber)); affine.transform(startPt, startPt); } else { startPt = pt; } float fx = (float)startPt.getX(); float fy = (float)startPt.getY(); if (mFontOutlineWidth > 0) { /* * Draw only outline of letters in label as lines. */ GlyphVector glyphs = mGraphics2D.getFont().createGlyphVector(frc, nextLine); Shape outline = glyphs.getOutline(fx, fy); mGraphics2D.draw(outline); } else { /* * Draw plain label. */ mGraphics2D.drawString(nextLine, fx, fy); } } lineNumber++; } } if (originalStroke != null) { /* * Restore line style. */ mGraphics2D.setStroke(originalStroke); } } }
src/org/mapyrus/OutputFormat.java
/* * This file is part of Mapyrus, software for plotting maps. * Copyright (C) 2003, 2004, 2005 Simon Chenery. * * Mapyrus is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Mapyrus is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Mapyrus; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* * @(#) $Id$ */ package org.mapyrus; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.Shape; import java.awt.Stroke; import java.awt.font.FontRenderContext; import java.awt.font.GlyphVector; import java.awt.geom.AffineTransform; import java.awt.geom.GeneralPath; import java.awt.geom.PathIterator; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintStream; import java.io.PrintWriter; import java.io.StringReader; import java.io.StringWriter; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.StringTokenizer; import java.util.zip.GZIPOutputStream; import org.mapyrus.font.AdobeFontMetricsManager; import org.mapyrus.font.PostScriptFont; import org.mapyrus.font.StringDimension; import org.mapyrus.font.TrueTypeFont; import org.mapyrus.image.ImageIOWrapper; import org.mapyrus.io.ASCII85Writer; import org.mapyrus.io.WildcardFile; import org.mapyrus.ps.PostScriptFile; /** * Abstraction of a graphics format. Provides methods to create new * output files and then draw to them, independent of the graphics * format. */ public class OutputFormat { /* * Type of output currently being generated. */ private static final int INTERNAL_IMAGE = 1; private static final int IMAGE_FILE = 2; /* * Output to window on screen. */ private static final int SCREEN_WINDOW = 3; /* * PostScript output can be created as either moveto-lineto-stroke * commands to draw shapes on page or as an single image covering * the whole page containing all drawn shapes. */ private static final int POSTSCRIPT_GEOMETRY = 4; private static final int POSTSCRIPT_IMAGE = 5; /* * Portable Documnet Format output. */ private static final int PDF = 6; /* * Scalable Vector Graphics (SVG) output. */ private static final int SVG = 7; /* * HTML image map being created in combination with an image. */ private static final int IMAGEMAP = 8; /* * Type of justification for labels on page, as used * in a word processor and in HTML tags. */ public static final int JUSTIFY_LEFT = 1; public static final int JUSTIFY_CENTER = 2; public static final int JUSTIFY_RIGHT = 4; public static final int JUSTIFY_TOP = 8; public static final int JUSTIFY_MIDDLE = 16; public static final int JUSTIFY_BOTTOM = 32; /* * File or image that drawing commands are * writing to. */ private int mOutputType; private String mFormatName; private BufferedImage mImage; private String mFilename; private PrintWriter mWriter; private OutputStream mOutputStream; private Graphics2D mGraphics2D; private boolean mIsPipedOutput; private boolean mIsStandardOutput; private boolean mIsUpdatingFile; private Process mOutputProcess; private File mTempFile; private PrintWriter mImageMapWriter; /* * Frequently used fonts. */ private FontCache mFontCache; /* * List of font definitions included in this PostScript file and list of fonts * used in this file but not defined. */ private HashSet mSuppliedFontResources; private HashSet mNeededFontResources; /* * Fonts which are to be re-encoded to ISOLatin1 in PostScript file. * This is normally done so that extended symbols (such as degree symbol) * can be used. */ private HashSet mEncodeAsISOLatin1; /* * Adobe Font Metrics files containing character width information for all fonts. */ private AdobeFontMetricsManager mAdobeFontMetrics; private ArrayList mAfmFiles; /* * List of TrueType fonts to load using Java Font.createFont() method. */ private HashMap mTTFFonts; /* * Page dimensions and resolution. */ private double mPageWidth; private double mPageHeight; private double mResolution; /* * Justification for labels as fraction of string height and width * to move string in X and Y direction to achieve correct justification. */ private double mJustificationShiftX; private double mJustificationShiftY; /* * Rotation of current font in radians, with 0 horizontal, * measured counter-clockwise. */ private double mFontRotation; /* * If non-zero, gives linewidth to use for drawing outlines of * each character of labels. */ private double mFontOutlineWidth; private Font mBaseFont; /* * Mask containing protected areas of the page. */ private PageMask mPageMask; /* * Counts clip paths and gradient fills set for SVG output * so each clip path and gradient can be given a unique id. */ private int mClipPathCounter; private boolean mIsClipPathActive; private int mGradientCounter; /* * File offset of each object in PDF file and buffers containing * all geometry and images to be included in PDF file. */ private ArrayList mPDFFileOffsets; private StringWriter mPDFGeometryStringWriter; private PrintWriter mPDFGeometryWriter; private ArrayList mPDFImageObjects; /* * Format for writing coordinate values. */ private DecimalFormat mCoordinateDecimal = new DecimalFormat("#.###", Constants.US_DECIMAL_FORMAT_SYMBOLS); /** * Write PostScript file header, including document structuring conventions (DSC). * @param width width of page in mm. * @param height height of page in mm. * @param resolution resolution of page in DPI. * @param turnPage flag true when page is to be rotated 90 degrees. * @param fontList list of PostScript fonts to include in header. * @param backgroundColor background color for page, or null if no background. */ private void writePostScriptHeader(double width, double height, int resolution, boolean turnPage, ArrayList fontList, Color backgroundColor) throws IOException, MapyrusException { long widthInPoints = Math.round(width / Constants.MM_PER_INCH * Constants.POINTS_PER_INCH); long heightInPoints = Math.round(height / Constants.MM_PER_INCH * Constants.POINTS_PER_INCH); StringBuffer sb = new StringBuffer("%!PS-Adobe-3.0"); if (mFormatName.equals("eps") || mFormatName.equals("epsimage")) sb.append(" EPSF-3.0"); writeLine(mWriter, sb.toString()); if (turnPage) writeLine(mWriter, "%%BoundingBox: 0 0 " + heightInPoints + " " + widthInPoints); else writeLine(mWriter, "%%BoundingBox: 0 0 " + widthInPoints + " " + heightInPoints); if ((!mFormatName.equals("eps")) && (!mFormatName.equals("epsimage"))) writeLine(mWriter, "%%Pages: 1"); writeLine(mWriter, "%%DocumentData: Clean7Bit"); writeLine(mWriter, "%%LanguageLevel: 2"); writeLine(mWriter, "%%Creator: (" + Constants.PROGRAM_NAME + " " + Constants.getVersion() + ")"); writeLine(mWriter, "%%OperatorMessage: (Mapyrus Output...)"); Date now = new Date(); writeLine(mWriter, "%%CreationDate: (" + now.toString() + ")"); String username = System.getProperty("user.name"); if (username != null) writeLine(mWriter, "%%For: (" + username + ")"); /* * List fonts included in this PostScript file. */ writeLine(mWriter, "%%DocumentRequiredResources: (atend)"); if (fontList.size() > 0) { sb = new StringBuffer("%%DocumentSuppliedResources: font"); Iterator it = fontList.iterator(); while (it.hasNext()) { PostScriptFont psFont = (PostScriptFont)(it.next()); sb.append(" ").append(psFont.getName()); mSuppliedFontResources.add(psFont.getName()); } writeLine(mWriter, sb.toString()); } writeLine(mWriter, "%%EndComments"); writeLine(mWriter, ""); writeLine(mWriter, "% Resolution " + resolution + " DPI"); /* * Inline font definitions. */ writeLine(mWriter, "%%BeginSetup"); Iterator it = fontList.iterator(); while (it.hasNext()) { PostScriptFont psFont = (PostScriptFont)(it.next()); writeLine(mWriter, "%%BeginResource: font " + psFont.getName()); String fontDefinition = psFont.getFontDefinition(); writeLine(mWriter, fontDefinition); writeLine(mWriter, "%%EndResource"); } writeLine(mWriter, "%%EndSetup"); /* * Set color and linestyle to reasonable default values. * Taken from 'initgraphics' operator example in PostScript Language * Reference Manual. */ writeLine(mWriter, "1 setlinewidth 0 setlinecap 0 setlinejoin"); writeLine(mWriter, "[] 0 setdash 0 setgray 10 setmiterlimit"); if (turnPage) { /* * Turn page 90 degrees so that a landscape orientation page appears * on a portrait page. */ writeLine(mWriter, "% Turn page 90 degrees."); writeLine(mWriter, "90 rotate 0 " + heightInPoints + " neg translate"); } /* * Prevent anything being displayed outside bounding box we've just defined. */ writeLine(mWriter, "0 0 " + widthInPoints + " " + heightInPoints + " rectclip"); /* * Set background color for page. */ writeLine(mWriter, "/RG { setrgbcolor } bind def"); if (backgroundColor != null) { float c[] = backgroundColor.getRGBColorComponents(null); writeLine(mWriter, "gsave"); writeLine(mWriter, mCoordinateDecimal.format(c[0]) + " " + mCoordinateDecimal.format(c[1]) + " " + mCoordinateDecimal.format(c[2]) + " RG"); writeLine(mWriter, "0 0 " + widthInPoints + " " + heightInPoints + " rectfill"); writeLine(mWriter, "grestore"); } /* * Define shorter names for most commonly used operations. * Bind all operators names to improve performance (see 3.11 of * PostScript Language Reference Manual). */ writeLine(mWriter, "/m { moveto } bind def /l { lineto } bind def"); writeLine(mWriter, "/c { curveto } bind def /h { closepath } bind def"); writeLine(mWriter, "/S { stroke } bind def /f { fill } bind def"); writeLine(mWriter, "/ju { /fjy exch def /fjx exch def } bind def"); /* * Define font and dictionary entries for font size and justification. * Don't bind these as font loading operators may be overridden in interpreter. */ writeLine(mWriter, "/font {"); writeLine(mWriter, "/foutline exch def"); writeLine(mWriter, "/frot exch radtodeg def"); writeLine(mWriter, "/fsize exch def findfont fsize scalefont setfont } def"); writeLine(mWriter, "/radtodeg { 180 mul 3.1415629 div } bind def"); /* * Draw text string, after setting correct position, rotation, * justifying it horizontally and vertically for current font size * and shifting it down a number of lines if it is part of a multi-line * string. * * Line number (starting at 0) and string to show are passed to this procedure. */ writeLine(mWriter, "/t { gsave currentpoint translate frot rotate"); writeLine(mWriter, "dup stringwidth pop fjx mul"); writeLine(mWriter, "3 -1 roll neg fjy add fsize mul"); writeLine(mWriter, "rmoveto foutline 0 gt"); writeLine(mWriter, "{false charpath foutline w 0 j 0 J 2 M stroke} {show} ifelse"); writeLine(mWriter, "grestore newpath } bind def"); writeLine(mWriter, "/w { setlinewidth } bind def"); writeLine(mWriter, "/J { setlinecap } bind def"); writeLine(mWriter, "/j { setlinejoin } bind def"); writeLine(mWriter, "/M { setmiterlimit } bind def"); writeLine(mWriter, "/d { setdash } bind def"); /* * Use new dictionary in saved state so that variables we define * do not overwrite variables in parent state. */ writeLine(mWriter, "/gs { gsave 4 dict begin } bind def"); writeLine(mWriter, "/gr { end grestore } bind def"); writeLine(mWriter, ""); } /** * Write PDF file header. * @param width width of page in mm. * @param height height of page in mm. * @param resolution resolution of page in DPI. * @param turnPage flag true when page is to be rotated 90 degrees. * @param fontList list of PostScript fonts to include in header. * @param backgroundColor background color for page, or null if no background. */ private void writePDFHeader(double width, double height, int resolution, boolean turnPage, ArrayList fontList, Color backgroundColor) throws IOException, MapyrusException { long widthInPoints = Math.round(width / Constants.MM_PER_INCH * Constants.POINTS_PER_INCH); long heightInPoints = Math.round(height / Constants.MM_PER_INCH * Constants.POINTS_PER_INCH); mPDFFileOffsets = new ArrayList(); int nChars = writeLine(mWriter, "%PDF-1.4"); mPDFFileOffsets.add(new Integer(nChars)); nChars += writeLine(mWriter, "1 0 obj"); nChars += writeLine(mWriter, "<<"); nChars += writeLine(mWriter, "/Type /Catalog"); nChars += writeLine(mWriter, "/Outlines 2 0 R"); nChars += writeLine(mWriter, "/Pages 3 0 R"); nChars += writeLine(mWriter, ">>"); nChars += writeLine(mWriter, "endobj"); mPDFFileOffsets.add(new Integer(nChars)); nChars += writeLine(mWriter, "2 0 obj"); nChars += writeLine(mWriter, "<<"); nChars += writeLine(mWriter, "/Type /Outlines"); nChars += writeLine(mWriter, "/Count 0"); nChars += writeLine(mWriter, ">>"); nChars += writeLine(mWriter, "endobj"); mWriter.flush(); mPDFFileOffsets.add(new Integer(nChars)); nChars += writeLine(mWriter, "3 0 obj"); nChars += writeLine(mWriter, "<<"); nChars += writeLine(mWriter, "/Type /Pages"); nChars += writeLine(mWriter, "/Kids [4 0 R]"); nChars += writeLine(mWriter, "/Count 1"); nChars += writeLine(mWriter, ">>"); nChars += writeLine(mWriter, "endobj"); mPDFFileOffsets.add(new Integer(nChars)); nChars += writeLine(mWriter, "4 0 obj"); nChars += writeLine(mWriter, "<<"); nChars += writeLine(mWriter, "/Type /Page"); String mediaBox; if (turnPage) mediaBox = "/MediaBox [0 0 " + heightInPoints + " " + widthInPoints + "]"; else mediaBox = "/MediaBox [0 0 " + widthInPoints + " " + heightInPoints + "]"; nChars += writeLine(mWriter, mediaBox); nChars += writeLine(mWriter, "/Contents 5 0 R"); nChars += writeLine(mWriter, "/Resources 6 0 R"); nChars += writeLine(mWriter, ">>"); nChars += writeLine(mWriter, "endobj"); mPDFFileOffsets.add(new Integer(nChars)); mPDFImageObjects = new ArrayList(); mPDFGeometryStringWriter = new StringWriter(); mPDFGeometryWriter = new PrintWriter(mPDFGeometryStringWriter); if (turnPage) { /* * Turn page 90 degrees so that a landscape orientation page appears * on a portrait page. */ writeLine(mPDFGeometryWriter, "0 1 -1 0 0 0 cm"); writeLine(mPDFGeometryWriter, "1 0 0 1 0 " + (-heightInPoints) + " cm"); } if (backgroundColor != null) { /* * Write object to set page background. */ float components[] = backgroundColor.getColorComponents(null); writeLine(mPDFGeometryWriter, "q"); writeLine(mPDFGeometryWriter, "0 0 " + widthInPoints + " " + heightInPoints + " re"); for (int i = 0; i < components.length; i++) writeLine(mPDFGeometryWriter, mCoordinateDecimal.format(components[i])); writeLine(mPDFGeometryWriter, "rg f Q"); } /* * Set scale so that we can give all coordinate positions in millimetres. */ double scale = Constants.POINTS_PER_INCH / Constants.MM_PER_INCH; writeLine(mPDFGeometryWriter, scale + " 0 0 " + scale + " 0 0 cm"); } /* * Set scale in PostScript file so that we can give all coordinate * positions in millimetres. */ private void writePostScriptScaling() { /* * Set plotting units to millimetres. */ writeLine(mWriter, "% Set scaling so that (x, y) coordinates are given in millimetres"); writeLine(mWriter, Constants.POINTS_PER_INCH + " " + Constants.MM_PER_INCH + " div dup scale"); } /** * Write SVG file header, starting with XML waffle. * @param width width of page in mm. * @param height height of page in mm. * @param backgroundColor background color for page, or null if no background. */ private void writeSVGHeader(double width, double height, Color backgroundColor) { writeLine(mWriter, "<?xml version=\"1.0\" encoding=\"ISO-8859-1\" standalone=\"no\"?>"); Date now = new Date(); writeLine(mWriter, "<!-- Created by " + Constants.PROGRAM_NAME + " " + Constants.getVersion() + " on " + now.toString() + " -->"); double pxPerMM = Constants.getScreenResolution() / Constants.MM_PER_INCH; writeLine(mWriter, "<svg width=\"" + mCoordinateDecimal.format(width * pxPerMM) + "\""); writeLine(mWriter, " height=\"" + mCoordinateDecimal.format(height * pxPerMM) + "\""); writeLine(mWriter, " version=\"1.1\""); writeLine(mWriter, " overflow=\"hidden\""); writeLine(mWriter, " xml:space=\"preserve\""); writeLine(mWriter, " xmlns=\"http://www.w3.org/2000/svg\">"); if (backgroundColor != null) { writeLine(mWriter, "<rect x=\"0\" y=\"0\" width=\"100%\""); writeLine(mWriter, " height=\"100%\" stroke=\"none\""); writeLine(mWriter, " fill=\"" + ColorDatabase.toHexString(backgroundColor) + "\" fill-opacity=\"1\"/>"); } /* * Set scaling so that units can be given in millimetres. * Set reasonable default values for rarely used settings that are * not given each time a shape is displayed. */ writeLine(mWriter, "<g transform=\"scale(" + pxPerMM + ")\""); writeLine(mWriter, " style=\"fill-rule:nonzero;fill-opacity:1;stroke-opacity:1;stroke-dasharray:none;\""); writeLine(mWriter, " clip-rule=\"nonzero\">"); } /** * Sets correct rendering hints and transformation * for buffered image we will plot to. * @param resolution resolution for page in DPI. * @param backgroundColor background color for page, or null if no background. * @param lineAliasing flag true if lines should be drawn with anti-aliasing. * @param labelAliasing flag true if labels should be drawn with anti-aliasing. */ private void setupBufferedImage(double resolution, Color backgroundColor, boolean lineAntiAliasing, boolean labelAntiAliasing) { double scale; scale = resolution / Constants.MM_PER_INCH; /* * Set background of entire image to desired color. */ if (backgroundColor != null) { Color originalColor = mGraphics2D.getColor(); mGraphics2D.setColor(backgroundColor); mGraphics2D.fillRect(0, 0, mImage.getWidth(), mImage.getHeight()); mGraphics2D.setColor(originalColor); } /* * Set transform with origin in lower-left corner and * Y axis increasing upwards. */ mGraphics2D.translate(0, mImage.getHeight()); mGraphics2D.scale(scale, -scale); /* * Set anti-aliasing for labels and lines if the user wants it. */ if (lineAntiAliasing) { mGraphics2D.addRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)); } else { mGraphics2D.addRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF)); } if (labelAntiAliasing) { mGraphics2D.addRenderingHints(new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON)); } else { mGraphics2D.addRenderingHints(new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF)); } } /** * Indicates whether an image format is supported or not. * @param formatName * @return true if creation of images in given format is supported. */ private boolean isSupportedImageFormat(String formatName) { boolean found = false; String knownFormats[] = ImageIOWrapper.getWriterFormatNames(); for (int i = 0; i < knownFormats.length && found == false; i++) { if (formatName.equalsIgnoreCase(knownFormats[i])) { found = true; } } return(found); } /** * Return PostScript commands to re-encode a font in ISOLatin1 encoding. * @param fontName name of font to re-encode. * @return string containing PostScript commands to re-encode font. */ private String isoLatinEncode(String fontName) { /* * Re-encoding commands taken from section 5.6.1 of Adobe PostScript * Language Reference Manual (2nd Edition). */ return("/" + fontName + " findfont" + Constants.LINE_SEPARATOR + "dup length dict begin" + Constants.LINE_SEPARATOR + "{1 index /FID ne {def} {pop pop} ifelse} forall" + Constants.LINE_SEPARATOR + "/Encoding ISOLatin1Encoding def" + Constants.LINE_SEPARATOR + "currentdict" + Constants.LINE_SEPARATOR + "end" + Constants.LINE_SEPARATOR + "/" + fontName + " exch definefont pop"); } private void setOutput(String filename, double width, double height, String extras, PrintStream stdoutStream) throws IOException, MapyrusException { /* * Parse list of additional options given by caller. */ ArrayList fontList = new ArrayList(); mEncodeAsISOLatin1 = new HashSet(); mTTFFonts = new HashMap(); mAfmFiles = new ArrayList(); mIsUpdatingFile = false; int resolution; boolean turnPage = false; Color backgroundColor = null; boolean labelAntiAliasing = true; boolean lineAntiAliasing = false; boolean compressOutput = false; Rectangle2D existingBoundingBox = null; if (mOutputType == POSTSCRIPT_GEOMETRY) resolution = 300; else resolution = Constants.getScreenResolution(); /* * Reading all font metrics information takes some time. * Wait until we really need it before loading it. */ mAdobeFontMetrics = null; StringTokenizer st = new StringTokenizer(extras); while (st.hasMoreTokens()) { String token = st.nextToken(); if (token.startsWith("pfafiles=")) { /* * Build list of font filenames user wants * to include in this PostScript file. */ StringTokenizer st2 = new StringTokenizer(token.substring(9), ","); while (st2.hasMoreTokens()) { String pfaFilename = st2.nextToken(); if (pfaFilename.length() > 0) { /* * Accept wildcards in filenames. */ WildcardFile wildcard = new WildcardFile(pfaFilename); Iterator it = wildcard.getMatchingFiles().iterator(); while (it.hasNext()) fontList.add(new PostScriptFont((String)it.next())); } } } if (token.startsWith("afmfiles=")) { StringTokenizer st2 = new StringTokenizer(token.substring(9), ","); while (st2.hasMoreTokens()) { String afmFilename = st2.nextToken(); if (afmFilename.length() > 0) { /* * Accept wildcards in filenames. */ WildcardFile wildcard = new WildcardFile(afmFilename); Iterator it = wildcard.getMatchingFiles().iterator(); while (it.hasNext()) { mAfmFiles.add(it.next()); } } } } else if (token.startsWith("isolatinfonts=")) { /* * Build list of fonts to encode in ISOLatin1. */ StringTokenizer st2 = new StringTokenizer(token.substring(14), ","); while (st2.hasMoreTokens()) { String fontName = st2.nextToken(); if (fontName.length() > 0) mEncodeAsISOLatin1.add(fontName); } } else if (token.startsWith("resolution=")) { String r = token.substring(11); try { resolution = Integer.parseInt(r); } catch (NumberFormatException e) { throw new MapyrusException(MapyrusMessages.get(MapyrusMessages.INVALID_PAGE_RESOLUTION) + ": " + r); } if (resolution < 1) { throw new MapyrusException(MapyrusMessages.get(MapyrusMessages.INVALID_PAGE_RESOLUTION) + ": " + r); } } else if (token.startsWith("ttffiles=")) { /* * Build list of TrueType font filenames user wants * to open with Java methods. */ StringTokenizer st2 = new StringTokenizer(token.substring(9), ","); while (st2.hasMoreTokens()) { String ttfFilename = st2.nextToken(); /* * Accept wildcards in filenames. */ if (ttfFilename.length() > 0) { WildcardFile wildcard = new WildcardFile(ttfFilename); Iterator it = wildcard.getMatchingFiles().iterator(); while (it.hasNext()) { String s = (String)it.next(); TrueTypeFont ttf = new TrueTypeFont(s); String fontName = ttf.getName(); mTTFFonts.put(fontName, ttf); mTTFFonts.put(fontName.toLowerCase(), ttf); mTTFFonts.put(fontName.toUpperCase(), ttf); } } } } else if (token.startsWith("turnpage=")) { String flag = token.substring(9); turnPage = flag.equalsIgnoreCase("true"); } else if (token.startsWith("labelantialiasing=")) { String flag = token.substring(18); labelAntiAliasing = flag.equalsIgnoreCase("true"); } else if (token.startsWith("lineantialiasing=")) { String flag = token.substring(17); lineAntiAliasing = flag.equalsIgnoreCase("true"); } else if (token.startsWith("update=") && mOutputType != SVG && mOutputType != PDF) { String flag = token.substring(7); mIsUpdatingFile = flag.equalsIgnoreCase("true"); } else if (token.startsWith("compress=")) { String flag = token.substring(9); compressOutput = flag.equalsIgnoreCase("true"); } else if (token.startsWith("imagemap=") && mOutputType == IMAGE_FILE) { mImageMapWriter = new PrintWriter(new FileWriter(token.substring(9))); } else if (token.startsWith("background=")) { String colorName = token.substring(11); backgroundColor = ColorDatabase.getColor(colorName, 255); if (backgroundColor == null) { throw new MapyrusException(MapyrusMessages.get(MapyrusMessages.COLOR_NOT_FOUND) + ": " + colorName); } } } if ((mOutputType == POSTSCRIPT_GEOMETRY || mOutputType == POSTSCRIPT_IMAGE || mOutputType == PDF || mOutputType == IMAGE_FILE || mOutputType == SVG) && (!mIsUpdatingFile)) { /* * Should we pipe the output to another program * instead of writing a file? */ mIsPipedOutput = filename.startsWith("|"); /* * Are we writing to standard output instead of to a file? */ mIsStandardOutput = filename.equals("-"); if (mIsPipedOutput) { String pipeCommand = filename.substring(1).trim(); String []cmdArray; if (Constants.getOSName().indexOf("WIN") >= 0) cmdArray = new String[]{pipeCommand}; else cmdArray = new String[]{"sh", "-c", pipeCommand}; mOutputProcess = Runtime.getRuntime().exec(cmdArray); mOutputStream = mOutputProcess.getOutputStream(); } else { if (mIsStandardOutput) mOutputStream = stdoutStream; else mOutputStream = new FileOutputStream(filename); } /* * Compress output too if the user wants it. */ if (compressOutput) mOutputStream = new GZIPOutputStream(mOutputStream); } File f = new File(filename); if (mIsUpdatingFile) { if (!f.canWrite()) { throw new IOException(MapyrusMessages.get(MapyrusMessages.READ_ONLY) + ": " + filename); } } /* * Setup file we are writing to. */ if (mOutputType == POSTSCRIPT_GEOMETRY || mOutputType == POSTSCRIPT_IMAGE || mOutputType == PDF) { if (mIsUpdatingFile) { PostScriptFile ps = new PostScriptFile(filename); if (ps.getNumberOfPages() > 1) { throw new MapyrusException(MapyrusMessages.get(MapyrusMessages.NOT_PS_FILE) + ": " + filename); } /* * Use size of existing PostScript file as size for new page. */ existingBoundingBox = ps.getBoundingBox(); width = existingBoundingBox.getMaxX() / Constants.POINTS_PER_INCH * Constants.MM_PER_INCH; height = existingBoundingBox.getMaxY() / Constants.POINTS_PER_INCH * Constants.MM_PER_INCH; /* * Start writing to a temporary file in same directory. We'll replace the * original file at the end when the file is successfully completed. */ mTempFile = File.createTempFile(Constants.PROGRAM_NAME, null, new File(filename).getAbsoluteFile().getParentFile()); mOutputStream = new FileOutputStream(mTempFile); } mWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(mOutputStream))); mSuppliedFontResources = new HashSet(); if (mOutputType == PDF) writePDFHeader(width, height, resolution, turnPage, fontList, backgroundColor); else writePostScriptHeader(width, height, resolution, turnPage, fontList, backgroundColor); mNeededFontResources = new HashSet(); if (mIsUpdatingFile) { /* * Append contents of existing file as an included document * to the new file we are creating. */ writeLine(mWriter, "save"); writeLine(mWriter, "/showpage {} def"); writeLine(mWriter, "%%BeginDocument: " + filename); BufferedReader r = null; try { r = new BufferedReader(new FileReader(filename)); String line; while ((line = r.readLine()) != null) { writeLine(mWriter, line); } } finally { try { if (r != null) r.close(); } catch (IOException e) { } } writeLine(mWriter, "%%EndDocument"); writeLine(mWriter, "restore"); } if (mOutputType != PDF) writePostScriptScaling(); } else if (mOutputType == SVG) { mWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(mOutputStream))); writeSVGHeader(width, height, backgroundColor); /* * Create a graphics context we can use for saving current graphics * state whilst drawing. */ BufferedImage anyImage = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB); mGraphics2D = (Graphics2D)anyImage.getGraphics(); } if (mOutputType != POSTSCRIPT_GEOMETRY && mOutputType != SVG && mOutputType != PDF) { /* * Create image to draw into. */ if (mOutputType == IMAGE_FILE || mOutputType == SCREEN_WINDOW || mOutputType == POSTSCRIPT_IMAGE) { if (mIsUpdatingFile && mOutputType == IMAGE_FILE) { /* * Read existing image for editing. * Set page width and height to size of existing image. */ mImage = ImageIOWrapper.read(f, Color.BLACK); if (mImage == null) { throw new MapyrusException(MapyrusMessages.get(MapyrusMessages.INVALID_FORMAT) + ": " + filename); } width = mImage.getWidth() / (resolution / Constants.MM_PER_INCH); height = mImage.getHeight() / (resolution / Constants.MM_PER_INCH); } else { /* * Create a BufferedImage to draw into. We'll save it to a file * when user has finished drawing to it. */ int widthInPixels = (int)Math.round(width / Constants.MM_PER_INCH * resolution); int heightInPixels = (int)Math.round(height / Constants.MM_PER_INCH * resolution); int imageType; /* * Create images with transparency for all formats except * JPEG and PPM (which do not support it). */ if (mFormatName.equals("jpg") || mFormatName.equals("jpeg") || mFormatName.equals("ppm")) imageType = BufferedImage.TYPE_3BYTE_BGR; else imageType = BufferedImage.TYPE_INT_ARGB; mImage = new BufferedImage(widthInPixels, heightInPixels, imageType); } } else if (mOutputType == INTERNAL_IMAGE) { /* * Calculate width of page, based on image and resolution given * by user. */ width = mImage.getWidth() / (resolution / Constants.MM_PER_INCH); height = mImage.getHeight() / (resolution / Constants.MM_PER_INCH); } mGraphics2D = (Graphics2D)(mImage.getGraphics()); setupBufferedImage(resolution, backgroundColor, lineAntiAliasing, labelAntiAliasing); } if (mImageMapWriter != null) { /* * Create image map. */ mImageMapWriter.println("<!-- HTML Imagemap created by Mapyrus for image " + filename + " -->"); mImageMapWriter.println("<!-- Surround contents of this file with <map name=\"foo\"> ... </map> and -->"); mImageMapWriter.println("<!-- combine it with the image using HTML like <img src=\"" + filename + "\" usemap=\"#foo\"> -->"); } mFilename = filename; mPageWidth = width; mPageHeight = height; mResolution = Constants.MM_PER_INCH / resolution; mFontCache = new FontCache(); mJustificationShiftX = mJustificationShiftY = 0.0; mFontOutlineWidth = 0.0; /* * Set impossible current font rotation so first font * accessed will be loaded. */ mFontRotation = Double.MAX_VALUE; /* * Do not allocate page mask until needed to save memory. */ mPageMask = null; } /** * Creates new graphics file, ready for drawing to. * @param filename name of image file output will be saved to. * If filename begins with '|' character then output is piped as * input to that command. * @param format is the graphics format to use. * @param width is the page width (in mm). * @param height is the page height (in mm). * @param extras contains extra settings for this output. * @param stdoutStream standard output stream for program. */ public OutputFormat(String filename, String format, double width, double height, String extras, PrintStream stdoutStream) throws IOException, MapyrusException { mFormatName = format.toLowerCase(); /* * Check that Java can write this image format to a file. */ if (mFormatName.equals("ps") || mFormatName.equals("postscript") || mFormatName.equals("application/postscript")) { mFormatName = "ps"; mOutputType = POSTSCRIPT_GEOMETRY; } else if (mFormatName.equals("eps")) { mOutputType = POSTSCRIPT_GEOMETRY; } else if (mFormatName.equals("epsimage")) { mOutputType = POSTSCRIPT_IMAGE; } else if (mFormatName.equals("pdf") || mFormatName.equals("application/pdf")) { mOutputType = PDF; } else if (mFormatName.equals("svg") || mFormatName.equals("image/svg+xml")) { mFormatName = "svg"; mOutputType = SVG; } else if (mFormatName.equals("screen")) { mOutputType = SCREEN_WINDOW; } else { if (mFormatName.equals("image/x-portable-pixmap")) mFormatName = "ppm"; else if (mFormatName.startsWith("image/")) mFormatName = mFormatName.substring(6); if (!isSupportedImageFormat(mFormatName)) { throw new MapyrusException(MapyrusMessages.get(MapyrusMessages.INVALID_FORMAT) + ": " + format); } mOutputType = IMAGE_FILE; } setOutput(filename, width, height, extras, stdoutStream); } /** * Sets image for drawing into. * @param image is buffered image to draw into. * @param extras contains extra settings for this output. */ public OutputFormat(BufferedImage image, String extras) throws IOException, MapyrusException { mOutputType = INTERNAL_IMAGE; mImage = image; mFormatName = "png"; PrintStream dummyStdout = new PrintStream(new ByteArrayOutputStream()); setOutput("", 0, 0, extras, dummyStdout); } /** * Return page width. * @return width in millimetres. */ public double getPageWidth() { return(mPageWidth); } /** * Return page height. * @return height in millimetres. */ public double getPageHeight() { return(mPageHeight); } /** * Return file format of page. * @return file format of page in lowercase. */ public String getPageFormat() { return(mFormatName); } /** * Return resolution of page as a distance measurement. * @return distance in millimetres between centres of adjacent pixels. */ public double getResolution() { return(mResolution); } /** * Returns height and width of a string, drawn to current page. * @param s string to calculate width for. * @param fontName name of font to calculate dimensions for. * @param fontSize size of characters in millimetres. * @return height and width of string in millimetres. */ public StringDimension getStringDimension(String s, String fontName, double fontSize) throws IOException, MapyrusException { StringDimension retval = new StringDimension(); BufferedReader stringReader = new BufferedReader(new StringReader(s)); double width = 0, height = 0; String token; double tokenWidth; /* * Break multi-line strings into separate lines so we * can find the width of the longest line. */ while ((token = stringReader.readLine()) != null) { if (mOutputType == POSTSCRIPT_GEOMETRY) { /* * Load Font Metrics information only when it is needed. */ if (mAdobeFontMetrics == null) mAdobeFontMetrics = new AdobeFontMetricsManager(mAfmFiles, mEncodeAsISOLatin1); double pointSize = fontSize / Constants.MM_PER_INCH * Constants.POINTS_PER_INCH; tokenWidth = mAdobeFontMetrics.getStringWidth(fontName, pointSize, token); tokenWidth = tokenWidth / Constants.POINTS_PER_INCH * Constants.MM_PER_INCH; if (tokenWidth > width) width = tokenWidth; height += fontSize; } else { /* * Use Java2D calculation for bounding box of string displayed with * horizontal font. */ FontRenderContext frc = mGraphics2D.getFontRenderContext(); Rectangle2D bounds = mBaseFont.getStringBounds(token, frc); tokenWidth = bounds.getWidth(); if (tokenWidth > width) width = tokenWidth; height += bounds.getHeight(); } } retval.setSize(width, height); return(retval); } /** * Return mask for this page. * @return page mask. */ public PageMask getPageMask() { if (mPageMask == null) { mPageMask = new PageMask((int)Math.round(mPageWidth), (int)Math.round(mPageHeight)); } return(mPageMask); } /* * Write a line to PostScript, PDF or SVG file. * @return number of characters written to file. */ private int writeLine(PrintWriter writer, String line) { writer.write(line); writer.write("\r\n"); return(line.length() + 2); } /** * Write image to PostScript file. * @param image image to write. * @param x center position on page for image. * @param y center position on page for image. * @param width width of image in millimetres. * @param height height of image in millimetres. * @param rotation rotation angle for image. */ private void writePostScriptImage(BufferedImage image, double x, double y, double width, double height, double rotation) throws IOException, MapyrusException { int pixelWidth, pixelHeight; int step; pixelWidth = image.getWidth(); pixelHeight = image.getHeight(); /* * Calculate reduction in image size so that it is * an appropriate size for the resolution of the page. */ if (pixelWidth <= 16 || pixelHeight <= 16) { step = 1; } else { double bestPixelWidth = width / mResolution; double bestPixelHeight = height / mResolution; /* * Keep reducing image 1/2, 1/3, 1/4, ... until it reaches the * resolution of the page. Use that reduction for image. */ step = 1; while (pixelHeight / (step + 1) > bestPixelHeight && pixelWidth / (step + 1) > bestPixelWidth) { step++; } } int reducedPixelWidth = (pixelWidth + step - 1) / step; int reducedPixelHeight = (pixelHeight + step - 1) / step; /* * Check if image is a single color. * Draw single color images with transparent background * using PostScript 'imagemask' operator. * Draw other images as RGB images using 'image' operator. */ Color singleColor = getSingleImageColor(image); /* * Write PostScript image directionary entry to draw image. * Taken from Adobe PostScript Language Reference Manual * (2nd Edition), p. 234. */ writeLine(mWriter, "gs"); writeLine(mWriter, "/DeviceRGB setcolorspace"); writeLine(mWriter, x + " " + y + " translate"); writeLine(mWriter, rotation + " radtodeg rotate"); writeLine(mWriter, width + " " + height + " scale"); /* * Image is centred at each point. * Shift image left and down half it's size so that it is displayed centred. */ writeLine(mWriter, "-0.5 -0.5 translate"); /* * Set color for drawing single color images. */ if (singleColor != null) { float []c = singleColor.getColorComponents(null); writeLine(mWriter, mCoordinateDecimal.format(c[0]) + " " + mCoordinateDecimal.format(c[1]) + " " + mCoordinateDecimal.format(c[2]) + " RG"); } writeLine(mWriter, "% original image size " + pixelWidth + "x" + pixelHeight + " with reduction factor " + step); writeLine(mWriter, "<<"); writeLine(mWriter, "/ImageType 1"); writeLine(mWriter, "/Width " + reducedPixelWidth); writeLine(mWriter, "/Height " + reducedPixelHeight); if (singleColor != null) { writeLine(mWriter, "/BitsPerComponent 1"); writeLine(mWriter, "/Decode [0 1]"); } else { writeLine(mWriter, "/BitsPerComponent 8"); writeLine(mWriter, "/Decode [0 1 0 1 0 1]"); } writeLine(mWriter, "/ImageMatrix [" + reducedPixelWidth + " 0 0 " + -reducedPixelHeight + " 0 " + reducedPixelHeight + "]"); writeLine(mWriter, "/DataSource currentfile /ASCII85Decode filter"); writeLine(mWriter, ">>"); if (singleColor != null) writeLine(mWriter, "imagemask"); else writeLine(mWriter, "image"); /* * Write ASCII85 encoded string containing all pixel values. */ ASCII85Writer ascii85 = new ASCII85Writer(mWriter); int byteValue = 0; int bitCounter = 0; for (int row = 0; row < pixelHeight; row += step) { for (int col = 0; col < pixelWidth; col += step) { int pixel = image.getRGB(col, row); if (singleColor != null) { /* * Pixel is set in PostScript image if it is transparent. */ int nextBit = ((pixel >> 24) == 0) ? 1 : 0; /* * Store next pixel value as a single bit in a byte. * If we've completed a byte or reached the end of a row * then write byte out and begin next byte. */ nextBit <<= (7 - bitCounter); byteValue |= nextBit; bitCounter++; if (bitCounter == 8 || (col + step >= pixelWidth)) { ascii85.write(byteValue); byteValue = bitCounter = 0; } } else { /* * Ignore transparency, we want only red, green, blue components * of pixel. */ int blue = (pixel & 0xff); int green = ((pixel >> 8) & 0xff); int red = ((pixel >> 16) & 0xff); ascii85.write(red); ascii85.write(green); ascii85.write(blue); } } } ascii85.close(); /* * Write ASCII85 end-of-data marker. */ writeLine(mWriter, "~>"); writeLine(mWriter, "gr"); } /** * Save state, protecting color, linestyle, transform of output. * This state can be restored later with restoreState(). */ public void saveState() { if (mOutputType == POSTSCRIPT_GEOMETRY) { writeLine(mWriter, "gs"); } else if (mOutputType == SVG) { writeLine(mWriter, "<g>"); } } /** * Restore state saved with saveState(). * @return true if saved state was successfully restored. * Only PostScript format can be successfully restored, caller * will have to reset values for other formats. */ public boolean restoreState() { boolean retval; if (mOutputType == POSTSCRIPT_GEOMETRY) { writeLine(mWriter, "gr"); retval = true; } else { if (mOutputType == SVG) writeLine(mWriter, "</g>"); /* * Can't restore state when drawing to an image or SVG file. Caller * must set everything to correct values again. */ retval = false; } return(retval); } /** * Writes trailing and buffered information, then closes output file. */ public void closeOutputFormat() throws IOException, MapyrusException { if (mOutputType == POSTSCRIPT_GEOMETRY || mOutputType == POSTSCRIPT_IMAGE) { if (mOutputType == POSTSCRIPT_IMAGE) { /* * Write image file containing page. */ writePostScriptImage(mImage, mPageWidth / 2, mPageHeight / 2, mPageWidth, mPageHeight, 0); } /* * Finish off PostScript file. */ if (mFormatName.equals("ps")) { /* * showpage is not included in Encapsulated PostScript files. */ writeLine(mWriter, "showpage"); } writeLine(mWriter, "%%Trailer"); /* * Included list of fonts we used in this file but did * not include in the header. */ writeLine(mWriter, "%%DocumentNeededResources:"); Iterator it = mNeededFontResources.iterator(); while (it.hasNext()) { String fontName = (String)(it.next()); if (!mSuppliedFontResources.contains(fontName)) writeLine(mWriter, "%%+ font " + fontName); } writeLine(mWriter, "%%EOF"); if (mIsStandardOutput) mWriter.flush(); else mWriter.close(); if (mWriter.checkError()) { throw new MapyrusException(mFilename + ": " + MapyrusMessages.get(MapyrusMessages.ERROR_PS)); } /* * If updating file then replace existing file with completed * temporary file now. */ if (mTempFile != null) { if ((!new File(mFilename).delete()) || (!mTempFile.renameTo(new File(mFilename)))) { mTempFile.delete(); throw new MapyrusException(MapyrusMessages.get(MapyrusMessages.READ_ONLY) + ": " + mFilename); } } } else if (mOutputType == PDF) { /* * Now that we have the complete geometry, we can write it to the PDF file. */ mPDFGeometryWriter.flush(); String geometry = mPDFGeometryStringWriter.toString(); int nChars = writeLine(mWriter, "5 0 obj"); nChars += writeLine(mWriter, "<< /Length " + geometry.length() + " >>"); nChars += writeLine(mWriter, "stream"); nChars += writeLine(mWriter, geometry); nChars += writeLine(mWriter, "endstream"); nChars += writeLine(mWriter, "endobj"); Integer offset = (Integer)mPDFFileOffsets.get(mPDFFileOffsets.size() - 1); mPDFFileOffsets.add(new Integer(offset.intValue() + nChars)); nChars = writeLine(mWriter, "6 0 obj"); nChars += writeLine(mWriter, "[/PDF]"); nChars += writeLine(mWriter, "endobj"); Iterator it = mPDFImageObjects.iterator(); while (it.hasNext()) { nChars += writeLine(mWriter, "%" + it.next().toString()); } /* * Write cross reference table giving file offset of each * object in PDF file. */ writeLine(mWriter, "xref"); writeLine(mWriter, "0 " + (mPDFFileOffsets.size() + 1)); writeLine(mWriter, "0000000000 65535 f"); it = mPDFFileOffsets.iterator(); while (it.hasNext()) { String fileOffset = it.next().toString(); int padding = 10 - fileOffset.length(); StringBuffer sb = new StringBuffer(); while (padding-- > 0) sb.append('0'); sb.append(fileOffset); sb.append(" 00000 n"); writeLine(mWriter, sb.toString()); } writeLine(mWriter, "trailer"); writeLine(mWriter, "<< /Size " + (mPDFFileOffsets.size() + 1) + " /Root 1 0 R >>"); /* * Write file offset of start of cross reference table. */ writeLine(mWriter, "startxref"); offset = (Integer)mPDFFileOffsets.get(mPDFFileOffsets.size() - 1); writeLine(mWriter, Integer.toString(offset.intValue() + nChars)); writeLine(mWriter, "%%EOF"); if (mIsStandardOutput) mWriter.flush(); else mWriter.close(); if (mWriter.checkError()) { throw new MapyrusException(mFilename + ": " + MapyrusMessages.get(MapyrusMessages.ERROR_PS)); } } else if (mOutputType == SVG) { writeLine(mWriter, "</g>"); writeLine(mWriter, "</svg>"); if (mIsStandardOutput) mWriter.flush(); else mWriter.close(); if (mWriter.checkError()) { throw new MapyrusException(mFilename + ": " + MapyrusMessages.get(MapyrusMessages.ERROR_SVG)); } } else if (mOutputType == IMAGE_FILE) { /* * If updating file then overwrite it now with new image. */ if (mIsUpdatingFile) mOutputStream = new FileOutputStream(mFilename); /* * Write image buffer to file. */ ImageIOWrapper.write(mImage, mFormatName, mOutputStream); if (mIsStandardOutput) mOutputStream.flush(); else mOutputStream.close(); } else if (mOutputType == SCREEN_WINDOW) { /* * Show image we have created in a window. * Then wait for user to close the window. */ String title = Constants.PROGRAM_NAME + ": " + mFilename; MapyrusFrame frame = new MapyrusFrame(title, mImage); frame.waitForClose(); } mImage = null; mGraphics2D = null; if (mOutputType != INTERNAL_IMAGE) { /* * If we are piping output to another program then wait for * that program to finish. Then check that it succeeded. */ if (mIsPipedOutput) { int retval = 0; try { retval = mOutputProcess.waitFor(); } catch (InterruptedException e) { throw new MapyrusException(mFilename + ": " + e.getMessage()); } if (retval != 0) { throw new MapyrusException(MapyrusMessages.get(MapyrusMessages.PROCESS_ERROR) + ": " + retval + ": " + mFilename); } } } if (mImageMapWriter != null) { mImageMapWriter.close(); } } /** * Set font for labelling in output format. * @param fontName is name of font as defined in java.awt.Font class. * @param fontSize is size for labelling in millimetres. * @param fontRotation is rotation angle for font, in degrees, * measured counter-clockwise. * @param outlineWidth if non-zero, labels will drawn as character outlines * with this width. */ public void setFontAttribute(String fontName, double fontSize, double fontRotation, double outlineWidth) throws IOException, MapyrusException { if (mOutputType == POSTSCRIPT_GEOMETRY) { if (mEncodeAsISOLatin1.contains(fontName)) { /* * Re-encode font from StandardEncoding to ISOLatin1Encoding * before it is used. */ writeLine(mWriter, isoLatinEncode(fontName)); mEncodeAsISOLatin1.remove(fontName); } /* * Set font and size for labelling. */ writeLine(mWriter, "/" + fontName + " " + fontSize + " " + fontRotation + " " + outlineWidth + " font"); mNeededFontResources.add(fontName); } else { /* * Split font name into font and style. */ int style = Font.PLAIN; if (fontName.endsWith("-Bold")) { style = Font.BOLD; fontName = fontName.substring(0, fontName.length() - 5); } else if (fontName.endsWith("-Italic")) { style = Font.ITALIC; fontName = fontName.substring(0, fontName.length() - 7); } else if (fontName.endsWith("-BoldItalic")) { style = Font.BOLD|Font.ITALIC; fontName = fontName.substring(0, fontName.length() - 11); } /* * Continually opening and deriving fonts is probably expensive. * Check that new font is actually different to current font * before defining it. */ Font currentFont = mGraphics2D.getFont(); float newSize = (float)fontSize; float currentSize = currentFont.getSize2D(); String currentFontName = currentFont.getName(); if (newSize != currentSize || style != currentFont.getStyle() || (!fontName.equals(currentFontName)) || fontRotation != mFontRotation) { /* * We need a base font that is not rotated for calculating * string widths for justifying text. * Get base font from cache, or create it if we don't find it there. */ mBaseFont = mFontCache.get(fontName, style, newSize, 0); if (mBaseFont == null) { /* * If this is a font for which user provided a TTF file then * use that, else expect the operating system to be able to * open the font. */ TrueTypeFont ttf = (TrueTypeFont)mTTFFonts.get(fontName); if (ttf != null) mBaseFont = ttf.getFont().deriveFont(style, newSize); else mBaseFont = new Font(fontName, style, (int)newSize).deriveFont(newSize); mFontCache.put(fontName, style, newSize, 0, mBaseFont); } /* * The real font used for labelling must be mirrored in Y axis * (to reverse the transform we use on Graphics2D objects) and * rotated to the angle the user wants. * * Look it up in cache too. */ Font font = mFontCache.get(fontName, style, -newSize, fontRotation); if (font == null) { AffineTransform fontTransform; fontTransform = AffineTransform.getRotateInstance(fontRotation); fontTransform.scale(1, -1); font = mBaseFont.deriveFont(fontTransform); mFontCache.put(fontName, style, -newSize, fontRotation, font); } mGraphics2D.setFont(font); } } /* * Font rotation and outlining not easily held in a Graphics2D * object so keep track of it's current value ourselves. */ mFontRotation = fontRotation; mFontOutlineWidth = outlineWidth; } /** * Set label justification in output format. * @param justify is label justification value, combination of JUSTIFY_* bit flags. */ public void setJustifyAttribute(int justify) { /* * Calculate fraction of string height and width to move text to get required * justification. */ if ((justify & JUSTIFY_LEFT) != 0) mJustificationShiftX = 0.0; else if ((justify & JUSTIFY_CENTER) != 0) mJustificationShiftX = -0.5; else mJustificationShiftX = -1.0; if ((justify & JUSTIFY_BOTTOM) != 0) mJustificationShiftY = 0.0; else if ((justify & JUSTIFY_MIDDLE) != 0) mJustificationShiftY = -0.5; else mJustificationShiftY = -1.0; if (mOutputType == POSTSCRIPT_GEOMETRY) { /* * Define dictionary entries for justification settings for PostScript * procedure to use for aligning text correctly itself. */ writeLine(mWriter, mJustificationShiftX + " " + mJustificationShiftY + " ju"); } } /** * Set color in output format. * @param color is color to draw in. */ public void setColorAttribute(Color color) { if (mOutputType == POSTSCRIPT_GEOMETRY || mOutputType == PDF) { float c[] = color.getRGBColorComponents(null); PrintWriter pw; if (mOutputType == PDF) pw = mPDFGeometryWriter; else pw = mWriter; StringBuffer sb = new StringBuffer(); sb.append(mCoordinateDecimal.format(c[0])); sb.append(' '); sb.append(mCoordinateDecimal.format(c[1])); sb.append(' '); sb.append(mCoordinateDecimal.format(c[2])); writeLine(pw, sb.toString() + " RG"); if (mOutputType == PDF) writeLine(pw, sb.toString() + " rg"); } else { mGraphics2D.setColor(color); } } /** * Set linestyle in output format. * @param linestyle is Java2D line width, cap and join style, dash pattern. */ public void setLinestyleAttribute(BasicStroke linestyle) { if (mOutputType == POSTSCRIPT_GEOMETRY || mOutputType == PDF) { PrintWriter pw; if (mOutputType == PDF) pw = mPDFGeometryWriter; else pw = mWriter; /* * Convert BasicStroke end cap and line join values to PostScript. */ int cap = linestyle.getEndCap(); if (cap == BasicStroke.CAP_BUTT) cap = 0; else if (cap == BasicStroke.CAP_ROUND) cap = 1; else /* SQUARE */ cap = 2; int join = linestyle.getLineJoin(); if (join == BasicStroke.JOIN_MITER) join = 0; else if (join == BasicStroke.JOIN_ROUND) join = 1; else /* BEVEL */ join = 2; writeLine(pw, mCoordinateDecimal.format(linestyle.getLineWidth()) + " w " + cap + " J " + join + " j " + mCoordinateDecimal.format(linestyle.getMiterLimit()) + " M"); /* * If there a dash pattern then set that too. */ float dashes[] = linestyle.getDashArray(); if (dashes != null) { StringBuffer s = new StringBuffer("["); for (int i = 0; i < dashes.length; i++) { if (i > 0) s.append(" "); s.append(mCoordinateDecimal.format(dashes[i])); } s.append("] "); s.append(linestyle.getDashPhase()); s.append(" d"); writeLine(pw, s.toString()); } else { /* * Remove any dashed line previously defined. */ writeLine(pw, "[] 0 d"); } } else { mGraphics2D.setStroke(linestyle); } } /** * Set clip path for output format. * @param clipPaths are polygons to clip against, or null if * there are no clip polygons. */ public void setClipAttribute(ArrayList clipPaths) { if (mOutputType != POSTSCRIPT_GEOMETRY && mOutputType != PDF) { mGraphics2D.setClip(null); mIsClipPathActive = (clipPaths != null && clipPaths.size() > 0); if (mIsClipPathActive) { if (mOutputType == SVG) { mClipPathCounter++; writeLine(mWriter, "<clipPath id=\"clip" + mClipPathCounter + "\">"); } for (int i = 0; i < clipPaths.size(); i++) { GeometricPath clipPath = (GeometricPath)(clipPaths.get(i)); if (mOutputType == SVG) { writeLine(mWriter, "<path d=\""); writeShape(clipPath.getShape(), mOutputType, mWriter, null); writeLine(mWriter, "\"/>"); } else { mGraphics2D.clip(clipPath.getShape()); } } if (mOutputType == SVG) writeLine(mWriter, "</clipPath>"); } } } /* * Walk through path, converting it to output format. */ private void writeShape(Shape shape, int outputType, PrintWriter pw, String scriptCommands) { PathIterator pi; if (outputType == IMAGEMAP) { pi = shape.getPathIterator(null, mResolution); } else { pi = shape.getPathIterator(null); } float coords[] = new float[6]; float lastX = 0.0f, lastY = 0.0f; float x = 0.0f, y = 0.0f; float distSquared; float resolutionSquared = (float)(mResolution * mResolution); int segmentType = PathIterator.SEG_CLOSE; boolean skippedLastSegment = false; String imageMapString = null; while (!pi.isDone()) { segmentType = pi.currentSegment(coords); switch (segmentType) { case PathIterator.SEG_MOVETO: lastX = coords[0]; lastY = coords[1]; if (outputType == SVG) { writeLine(pw, "M " + mCoordinateDecimal.format(lastX) + " " + mCoordinateDecimal.format(mPageHeight - lastY)); } else if (outputType == IMAGEMAP) { if (imageMapString != null) mImageMapWriter.println(imageMapString); mImageMapWriter.println("<area shape=\"polygon\" coords=\"" + Math.round(lastX / mResolution) + "," + Math.round((mPageHeight - lastY) / mResolution)); imageMapString = "\" " + scriptCommands + " >"; } else { writeLine(pw, mCoordinateDecimal.format(lastX) + " " + mCoordinateDecimal.format(lastY) + " m"); } skippedLastSegment = false; break; case PathIterator.SEG_LINETO: x = coords[0]; y = coords[1]; distSquared = (lastX - x) * (lastX - x) + (lastY - y) * (lastY - y); if (distSquared >= resolutionSquared) { if (outputType == SVG) { String sx = mCoordinateDecimal.format(x); String sy = mCoordinateDecimal.format(mPageHeight - y); /* * Use shortcut path types for horizontal * and vertical line segments. */ if (x == lastX) writeLine(pw, "V " + sy); else if (y == lastY) writeLine(pw, "H " + sx); else writeLine(pw, "L " + sx + " " + sy); } else if (outputType == IMAGEMAP) { mImageMapWriter.println("," + Math.round(x / mResolution) + "," + Math.round((mPageHeight - y) / mResolution)); } else { writeLine(pw, mCoordinateDecimal.format(x) + " " + mCoordinateDecimal.format(y) + " l"); } lastX = x; lastY = y; skippedLastSegment = false; } else { /* * Skip segments that are less than one unit of resolution in length. */ skippedLastSegment = true; } break; case PathIterator.SEG_CLOSE: if (skippedLastSegment) { if (outputType == SVG) { writeLine(pw, "L " + mCoordinateDecimal.format(x) + " " + mCoordinateDecimal.format(mPageHeight - y)); } else if (outputType == IMAGEMAP) { if (imageMapString != null) { mImageMapWriter.println("," + Math.round(x / mResolution) + "," + Math.round((mPageHeight - y) / mResolution)); } } else { writeLine(pw, mCoordinateDecimal.format(x) + " " + mCoordinateDecimal.format(y) + " l"); } } if (outputType == SVG) { writeLine(pw, "z"); } else if (outputType == IMAGEMAP) { if (imageMapString != null) { mImageMapWriter.println(imageMapString); imageMapString = null; } } else { writeLine(pw, "h"); } skippedLastSegment = false; break; case PathIterator.SEG_CUBICTO: if (outputType == SVG) { writeLine(pw, "C " + mCoordinateDecimal.format(coords[0]) + " " + mCoordinateDecimal.format(mPageHeight - coords[1]) + " " + mCoordinateDecimal.format(coords[2]) + " " + mCoordinateDecimal.format(mPageHeight - coords[3]) + " " + mCoordinateDecimal.format(coords[4]) + " " + mCoordinateDecimal.format(mPageHeight - coords[5])); } else { writeLine(pw, mCoordinateDecimal.format(coords[0]) + " " + mCoordinateDecimal.format(coords[1]) + " " + mCoordinateDecimal.format(coords[2]) + " " + mCoordinateDecimal.format(coords[3]) + " " + mCoordinateDecimal.format(coords[4]) + " " + mCoordinateDecimal.format(coords[5]) + " " + "c"); } lastX = coords[4]; lastY = coords[5]; skippedLastSegment = false; break; } pi.next(); } if (skippedLastSegment) { /* * Always include last point in lines and polygons, * never skip it. */ if (outputType == SVG) { writeLine(pw, "L " + mCoordinateDecimal.format(x) + " " + mCoordinateDecimal.format(mPageHeight - y)); } else if (outputType == IMAGEMAP) { if (imageMapString != null) { mImageMapWriter.println("," + Math.round(x / mResolution) + "," + Math.round((mPageHeight - y) / mResolution)); } } else { writeLine(pw, mCoordinateDecimal.format(x) + " " + mCoordinateDecimal.format(y) + " l"); } } /* * Complete any imagemap being created. */ if (outputType == IMAGEMAP && imageMapString != null) { mImageMapWriter.println(imageMapString); } } /** * Determines single color used in an image. * @param image image to check. * @return single non-transparent color used in an image, or null if * image has many colors. */ private Color getSingleImageColor(BufferedImage image) { Color singleColor = Color.BLACK; boolean foundDifferentColors = false; boolean foundFirstColor = false; int imageWidth = image.getWidth(); int imageHeight = image.getHeight(); /* * Check if all pixels are the same color, or transparent. */ int y = 0; while (y < imageHeight && (!foundDifferentColors)) { int x = 0; while (x < imageWidth && (!foundDifferentColors)) { int pixel = image.getRGB(x, y); if ((pixel & 0xff000000) != 0) { /* * Pixel is not transparent. */ if (!foundFirstColor) { foundFirstColor = true; singleColor = new Color(pixel & 0xffffff); } else { foundDifferentColors = (pixel != singleColor.getRGB()); } } x++; } y++; } if (foundDifferentColors) singleColor = null; return(singleColor); } /** * Draw icon at points on page. * @param pointList is list of Point2D objects at which to draw icon. * @param icon image to draw. * @param size is size of icon in millimeters, or zero for screen size. * @param rotation rotation angle for icon. * @param scaling scale factor for icon. */ public void drawIcon(ArrayList pointList, BufferedImage image, double size, double rotation, double scaling) throws IOException, MapyrusException { int pixelWidth = image.getWidth(); int pixelHeight = image.getHeight(); Point2D pt; int i; double x, y, mmWidth, mmHeight; /* * If size not given then make icon about as large as it would appear * on the screen in an image viewer, with one image pixel in one screen * pixel. */ if (size <= 0.0) { size = Math.max(pixelWidth, pixelHeight) * (Constants.MM_PER_INCH / Constants.getScreenResolution()); } size *= scaling; /* * Calculate width and height for non-square images. */ if (pixelWidth > pixelHeight) { mmWidth = size; mmHeight = size * ((double)pixelHeight / pixelWidth); } else { mmHeight = size; mmWidth = size * ((double)pixelWidth / pixelHeight); } if (mOutputType == POSTSCRIPT_GEOMETRY) { /* * Draw icon at each position in list. */ for (i = 0; i < pointList.size(); i++) { pt = (Point2D)(pointList.get(i)); x = pt.getX(); y = pt.getY(); /* * Skip points that are outside page. */ if (x + mmWidth >= 0 && x - mmWidth <= mPageWidth && y + mmHeight >= 0.0 && y - mmHeight <= mPageHeight) { writePostScriptImage(image, x, y, mmWidth, mmHeight, rotation); } } } else if (mOutputType != SVG) { for (i = 0; i < pointList.size(); i++) { pt = (Point2D)(pointList.get(i)); x = pt.getX(); y = pt.getY(); AffineTransform affine = AffineTransform.getTranslateInstance(x, y); /* * Scale transformation so that units are in pixels. */ double mmPerPixel = Constants.MM_PER_INCH / Constants.getScreenResolution(); affine.scale(mmPerPixel, mmPerPixel * -1); /* * Rotate clockwise around point (x, y). */ affine.rotate(-rotation); /* * Scale image to requested size. */ double xScale = (mmWidth / mmPerPixel) / pixelWidth; double yScale = (mmHeight / mmPerPixel) / pixelHeight; affine.scale(xScale, yScale); /* * Shift origin so that middle of image is at point (x, y). */ affine.translate(-pixelWidth / 2.0, -pixelHeight / 2.0); try { /* * Sun JVM throws NullPointerException if image is * too big to fit in memory. */ mGraphics2D.drawImage(image, affine, null); } catch (NullPointerException e) { throw new OutOfMemoryError("Failed loading icon."); } } } } /** * Draw geo-referenced image on page. * @param image image to display. * @param x X coordinate of bottom left corner of image. * @param y Y coordinate of bottom left corner of image. * @param width width of image in millimetres. * @param height height of image in millimetres. */ public void drawGeoImage(BufferedImage image, double x, double y, double width, double height) throws MapyrusException, IOException { if (mOutputType == POSTSCRIPT_GEOMETRY) { writePostScriptImage(image, x + width / 2, y + height / 2, width, height, 0); } else { /* * Position image on page, inverting it to appear right way up * and scaling it to requested size. */ AffineTransform affine = AffineTransform.getTranslateInstance(x, y + height); affine.scale(1, -1); affine.scale(width / image.getWidth(), height / image.getHeight()); mGraphics2D.drawImage(image, affine, null); } } /** * Draw EPS file at points on page. * @param pointList is list of Point2D objects at which to draw EPS file. * @param EPS filename. * @param size size for EPS file on page in millimetres. * @param rotation rotation angle for EPS file. * @param scaling scale factor for EPS file. */ public void drawEPS(ArrayList pointList, String filename, double size, double rotation, double scaling) throws IOException, MapyrusException { PostScriptFile psfile = new PostScriptFile(filename); Rectangle boundingBox = psfile.getBoundingBox(); int pointWidth = (int)boundingBox.getWidth(); int pointHeight = (int)boundingBox.getHeight(); Point2D pt; int i; double x, y; /* * If size not given then make EPS about as large as defined in the EPS file. */ if (size <= 0.0) { size = Math.max(pointWidth, pointHeight) * (Constants.MM_PER_INCH / Constants.POINTS_PER_INCH); } size *= scaling; if (mOutputType == POSTSCRIPT_GEOMETRY) { /* * Include EPS file at each position in list. */ for (i = 0; i < pointList.size(); i++) { pt = (Point2D)(pointList.get(i)); x = pt.getX(); y = pt.getY(); /* * Skip points that are outside page. */ if (x + size >= 0 && x - size <= mPageWidth && y + size >= 0.0 && y - size <= mPageHeight) { writeLine(mWriter, "save"); writeLine(mWriter, x + " " + y + " translate"); writeLine(mWriter, rotation + " radtodeg rotate"); /* * EPS file is centred at each point. * Shift position left and down half it's size * so that it is displayed centered. */ writeLine(mWriter, -(size / 2) + " " + -(size / 2) + " translate"); double scale = size / Math.max(pointWidth, pointHeight); writeLine(mWriter, scale + " dup scale"); /* * Shift EPS file so that lower-left corner of EPS file is in * lower left corner of our box on the page. */ writeLine(mWriter, -boundingBox.getMinX() + " " + -boundingBox.getMinY() + " translate"); /* * Set graphics attributes to initial values, as described * on page 728 of PostScript Language Reference Manual. */ writeLine(mWriter, "/showpage {} def"); writeLine(mWriter, "0 setgray 0 setlinecap 1 setlinewidth"); writeLine(mWriter, "0 setlinejoin 10 setmiterlimit [] 0 setdash newpath"); writeLine(mWriter, "%%BeginDocument: (" + filename + ")"); BufferedReader reader = null; try { reader = new FileOrURL(filename).getReader(); String line; while ((line = reader.readLine()) != null) { writeLine(mWriter, line); } writeLine(mWriter, "%%EndDocument"); writeLine(mWriter, "restore"); } finally { /* * Ensure EPS file is always closed. */ if (reader != null) reader.close(); } } } } else { /* * We cannot show EPS files when drawing to an image file so show a * transparent grey box where the EPS file would appear. */ GeneralPath path = new GeneralPath(); Color currentColor = mGraphics2D.getColor(); mGraphics2D.setColor(new Color(127, 127, 127, 127)); for (i = 0; i < pointList.size(); i++) { pt = (Point2D)(pointList.get(i)); x = pt.getX(); y = pt.getY(); double xDist = Math.cos(rotation) * size / 2; double yDist = Math.sin(rotation) * size / 2; Point2D currentPoint; path.reset(); path.moveTo((float)(x - xDist + yDist), (float)(y - yDist - xDist)); currentPoint = path.getCurrentPoint(); path.lineTo((float)(currentPoint.getX() - yDist - yDist), (float)(currentPoint.getY() + xDist + xDist)); currentPoint = path.getCurrentPoint(); path.lineTo((float)(currentPoint.getX() + xDist + xDist), (float)(currentPoint.getY() + yDist + yDist)); currentPoint = path.getCurrentPoint(); path.lineTo((float)(currentPoint.getX() + yDist + yDist), (float)(currentPoint.getY() - xDist - xDist)); path.closePath(); fill(path); } mGraphics2D.setColor(currentColor); } } /** * Draw currently defined path to output page. */ public void stroke(Shape shape) { if (mOutputType == POSTSCRIPT_GEOMETRY || mOutputType == SVG || mOutputType == PDF) { if (shape.intersects(0.0, 0.0, mPageWidth, mPageHeight)) { if (mOutputType == SVG) { writeLine(mWriter, "<path d=\""); writeShape(shape, mOutputType, mWriter, null); writeLine(mWriter, "\""); Color color = mGraphics2D.getColor(); BasicStroke stroke = (BasicStroke)mGraphics2D.getStroke(); float width = stroke.getLineWidth(); int endCap = stroke.getEndCap(); int lineJoin = stroke.getLineJoin(); float []dashArray = stroke.getDashArray(); float dashPhase = stroke.getDashPhase(); String capString, joinString; if (endCap == BasicStroke.CAP_BUTT) capString = "butt"; else if (endCap == BasicStroke.CAP_SQUARE) capString = "square"; else capString = "round"; if (lineJoin == BasicStroke.JOIN_BEVEL) joinString = "bevel"; else if (lineJoin == BasicStroke.JOIN_MITER) joinString = "miter"; else joinString = "round"; if (mIsClipPathActive) { writeLine(mWriter, " clip-path=\"url(#clip" + mClipPathCounter + ")\""); } writeLine(mWriter, " style=\"stroke:" + ColorDatabase.toHexString(color) + ";stroke-width:" + width + ";stroke-linecap:" + capString + ";stroke-linejoin:" + joinString); if (dashArray != null) { StringBuffer dashes = new StringBuffer(";stroke-dasharray:"); for (int i = 0 ; i < dashArray.length; i++) { if (i > 0) dashes.append(","); dashes.append(mCoordinateDecimal.format(dashArray[i])); } writeLine(mWriter, dashes.toString()); writeLine(mWriter, ";stroke-dashoffset:" + dashPhase); } int alpha = color.getAlpha(); if (alpha != 255) { writeLine(mWriter, ";stroke-opacity:" + (alpha / 255.0f)); } writeLine(mWriter, ";fill:none\"/>"); } else { PrintWriter pw; if (mOutputType == PDF) pw = mPDFGeometryWriter; else pw = mWriter; writeShape(shape, mOutputType, pw, null); writeLine(pw, "S"); } } } else { /* * Draw path into image. */ mGraphics2D.draw(shape); } } /** * Fill currently defined path on output page. * @param shape shape to fill on page. * run when this shape is clicked. */ public void fill(Shape shape) { if (mOutputType == POSTSCRIPT_GEOMETRY || mOutputType == SVG || mOutputType == PDF) { if (shape.intersects(0.0, 0.0, mPageWidth, mPageHeight)) { if (mOutputType == SVG) { writeLine(mWriter, "<path d=\""); writeShape(shape, mOutputType, mWriter, null); writeLine(mWriter, "\""); Color color = mGraphics2D.getColor(); int alpha = color.getAlpha(); if (mIsClipPathActive) { writeLine(mWriter, " clip-path=\"url(#clip" + mClipPathCounter + ")\""); } StringBuffer sb = new StringBuffer(" style=\"fill:"); sb.append(ColorDatabase.toHexString(color)); if (alpha != 255) { sb.append(";fill-opacity:" + (alpha / 255.0f)); } sb.append(";stroke:none\"/>"); writeLine(mWriter, sb.toString()); } else { PrintWriter pw; if (mOutputType == PDF) pw = mPDFGeometryWriter; else pw = mWriter; writeShape(shape, mOutputType, pw, null); writeLine(pw, "f"); } } } else { /* * Fill path in image. */ mGraphics2D.fill(shape); } } /** * Set script commands for path on output page. * @param shape shape to fill on page. * @param scriptCommands script language commands to * run when this shape is clicked. */ public void setEventScript(Shape shape, String scriptCommands) { if (mImageMapWriter != null) { /* * Write shape to image map together with script commands. */ writeShape(shape, IMAGEMAP, mWriter, scriptCommands); } else if (mOutputType == SVG) { /* * Embed script commands in SVG file. */ writeLine(mWriter, "<path d=\""); writeShape(shape, mOutputType, mWriter, scriptCommands); writeLine(mWriter, "\""); writeLine(mWriter, scriptCommands); writeLine(mWriter, "/>"); } } /** * Fill currently defined path with gradient fill pattern. * @param shape current path to be filled. * @param isVerticalGradient true if vertical color gradient to be used, * false for horizontal. * @param c1 color for left or bottom of path. * @param c2 color for right or top of path. */ public void gradientFill(Shape shape, boolean isVerticalGradient, Color c1, Color c2) { if (mOutputType == SVG) { if (shape.intersects(0.0, 0.0, mPageWidth, mPageHeight)) { String uniqueId = "gradient" + mGradientCounter++; writeLine(mWriter, "<defs>"); writeLine(mWriter, "<linearGradient id=\"" + uniqueId + "\""); /* * SVG supports only horizontal gradients (default) or vertical * gradients. */ if (isVerticalGradient) writeLine(mWriter, "x1=\"0%\" y1=\"100%\" x2=\"0%\" y2=\"0%\""); writeLine(mWriter, ">"); writeLine(mWriter, "<stop offset=\"0%\" stop-color=\"" + ColorDatabase.toHexString(c1) + "\"/>"); writeLine(mWriter, "<stop offset=\"100%\" stop-color=\"" + ColorDatabase.toHexString(c2) + "\"/>"); writeLine(mWriter, "</linearGradient>"); writeLine(mWriter, "</defs>"); writeLine(mWriter, "<path d=\""); writeShape(shape, mOutputType, mWriter, null); writeLine(mWriter, "\""); if (mIsClipPathActive) { writeLine(mWriter, " clip-path=\"url(#clip" + mClipPathCounter + ")\""); } writeLine(mWriter, " fill=\"url(#" + uniqueId + ")\" stroke=\"none\"/>"); } } } /** * Set clip region to inside of currently defined path on output page. */ public void clip(Shape shape) { if (mOutputType == POSTSCRIPT_GEOMETRY || mOutputType == PDF) { PrintWriter pw; if (mOutputType == PDF) pw = mPDFGeometryWriter; else pw = mWriter; /* * Set clip path now, then it stays in effect until previous * state is restored. */ if (shape.intersects(0.0, 0.0, mPageWidth, mPageHeight)) { writeShape(shape, mOutputType, pw, null); } else { /* * Clip region is outside page. Clip to simple rectangle * outside page instead so that nothing is shown. */ writeShape(new Rectangle2D.Float(-1.0f, -1.0f, 0.1f, 0.1f), mOutputType, pw, null); } writeLine(pw, "clip newpath"); } } /** * Convert a string to PostScript format, escaping special characters and * write it to PostScript file. * @param s is string to convert and write. */ private void writePostScriptString(String s) { char c; StringBuffer buffer = new StringBuffer("("); for (int i = 0; i < s.length(); i++) { /* * Wrap strings that get too long. */ if (buffer.length() > 72) { buffer.append('\\'); writeLine(mWriter, buffer.toString()); buffer.setLength(0); } /* * Convert backslashes to '\\' and other special characters to octal code. */ c = s.charAt(i); if (c == '\\') { buffer.append("\\\\"); } else if (c == '(' || c == ')' || c == '%' || c < ' ' || c > 'z') { int extendedChar = c; int b1 = extendedChar / (8 * 8); extendedChar -= b1 * (8 * 8); int b2 = extendedChar / 8; extendedChar -= b2 * 8; int b3 = extendedChar; buffer.append('\\'); buffer.append(b1); buffer.append(b2); buffer.append(b3); } else { buffer.append(c); } } buffer.append(")"); writeLine(mWriter, buffer.toString()); } /** * Draw label positioned at (or along) currently defined path. * @param pointList is list of Point2D objects at which to draw label. * @param label is string to draw on path. */ public void label(ArrayList pointList, String label) { Point2D pt, startPt; double x, y; String nextLine; StringTokenizer st; int lineNumber; AffineTransform affine; FontRenderContext frc = null; Stroke originalStroke = null; if (mOutputType != POSTSCRIPT_GEOMETRY) { frc = mGraphics2D.getFontRenderContext(); if (mFontOutlineWidth > 0) { /* * Save existing linestyle and create new one for drawing outlines of each letter. */ originalStroke = mGraphics2D.getStroke(); BasicStroke outlineStroke = new BasicStroke((float)mFontOutlineWidth, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 2.0f); mGraphics2D.setStroke(outlineStroke); } } /* * Draw label at each position in list. */ for (int i = 0; i < pointList.size(); i++) { pt = (Point2D)(pointList.get(i)); x = pt.getX(); y = pt.getY(); /* * Draw each line of label below the one above. */ st = new StringTokenizer(label, Constants.LINE_SEPARATOR); lineNumber = 0; while (st.hasMoreTokens()) { nextLine = st.nextToken(); if (mOutputType == POSTSCRIPT_GEOMETRY) { writeLine(mWriter, mCoordinateDecimal.format(x) + " " + mCoordinateDecimal.format(y) + " m"); /* * Pass counter and line to PostScript procedure for * drawing each line of the label. */ writeLine(mWriter, Integer.toString(lineNumber)); writePostScriptString(nextLine); writeLine(mWriter, "t"); } else if (mOutputType == SVG) { double yInc = 0; if (lineNumber > 0) { Rectangle2D bounds = mBaseFont.getStringBounds(nextLine, frc); yInc = bounds.getHeight() * lineNumber; } String anchor; if (mJustificationShiftX == -1) anchor = "end"; else if (mJustificationShiftX == 0) anchor = "start"; else anchor = "middle"; Color color = mGraphics2D.getColor(); int alpha = color.getAlpha(); Font font = mGraphics2D.getFont(); StringBuffer extras = new StringBuffer(); if (font.isBold()) extras.append(" font-weight=\"bold\" "); if (font.isItalic()) extras.append(" font-style=\"italic\" "); if (mFontOutlineWidth > 0) { extras.append(" stroke=\""); extras.append(ColorDatabase.toHexString(color)); extras.append("\" stroke-width=\""); extras.append(mFontOutlineWidth); extras.append("\" "); if (alpha != 255) { extras.append(" stroke-opacity=\""); extras.append(alpha / 255.0f); extras.append("\" "); } } else { extras.append(" fill=\""); extras.append(ColorDatabase.toHexString(color)); extras.append("\" "); if (alpha != 255) { extras.append(" fill-opacity=\""); extras.append(alpha / 255.0f); extras.append("\" "); } } if (mIsClipPathActive) { extras.append(" clip-path=\"url(#clip"); extras.append(mClipPathCounter); extras.append(")\" "); } double px, py; if (mFontRotation != 0) { /* * Rotate text around origin point. * Rotation is negative sense because Y axis * decreases downwards. */ writeLine(mWriter, "<g transform=\"translate(" + mCoordinateDecimal.format(x) + ", " + mCoordinateDecimal.format(mPageHeight - y) + ") rotate(" + mCoordinateDecimal.format(Math.toDegrees(-mFontRotation)) + ")\">"); px = py = 0; } else { px = x; py = mPageHeight - (y - yInc); } /* * Shift text to correct vertical alignment. */ py -= mJustificationShiftY * font.getSize2D(); writeLine(mWriter, "<text x=\"" + mCoordinateDecimal.format(px) + "\" y=\"" + mCoordinateDecimal.format(py) + "\" text-anchor=\"" + anchor + "\""); String fontName = font.getName(); /* * Change default Java font names to something sensible. */ if (fontName.equalsIgnoreCase("sansserif") || fontName.equalsIgnoreCase("dialog")) { fontName = "Courier"; } writeLine(mWriter, " font-family=\"" + fontName + "\" " + "font-size=\"" + font.getSize2D() + "\" " + extras.toString()); /* * Make text string XML safe. */ nextLine = nextLine.replaceAll("&", "&amp;"); nextLine = nextLine.replaceAll("<", "&lt;"); nextLine = nextLine.replaceAll(">", "&gt;"); nextLine = nextLine.replaceAll("\"", "&quot;"); writeLine(mWriter, ">" + nextLine + "</text>"); if (mFontRotation != 0) writeLine(mWriter, "</g>"); } else { /* * Reposition label from original point so it has correct justification. */ if (mJustificationShiftX != 0.0 || mJustificationShiftY != 0.0 || lineNumber > 0) { Rectangle2D bounds = mBaseFont.getStringBounds(nextLine, frc); affine = AffineTransform.getTranslateInstance(x, y); affine.rotate(mFontRotation); startPt = new Point2D.Double(bounds.getWidth() * mJustificationShiftX, bounds.getHeight() * (mJustificationShiftY - lineNumber)); affine.transform(startPt, startPt); } else { startPt = pt; } float fx = (float)startPt.getX(); float fy = (float)startPt.getY(); if (mFontOutlineWidth > 0) { /* * Draw only outline of letters in label as lines. */ GlyphVector glyphs = mGraphics2D.getFont().createGlyphVector(frc, nextLine); Shape outline = glyphs.getOutline(fx, fy); mGraphics2D.draw(outline); } else { /* * Draw plain label. */ mGraphics2D.drawString(nextLine, fx, fy); } } lineNumber++; } } if (originalStroke != null) { /* * Restore line style. */ mGraphics2D.setStroke(originalStroke); } } }
Change clipping to work for PDF output too.
src/org/mapyrus/OutputFormat.java
Change clipping to work for PDF output too.
Java
lgpl-2.1
e793891f2d66db08edebfb6d143d38825157c027
0
SensorsINI/jaer,SensorsINI/jaer,SensorsINI/jaer,SensorsINI/jaer,SensorsINI/jaer,SensorsINI/jaer,SensorsINI/jaer,SensorsINI/jaer
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package net.sf.jaer.graphics; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.io.File; import java.io.IOException; import java.util.logging.Logger; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.KeyStroke; import net.sf.jaer.aemonitor.AEPacketRaw; import net.sf.jaer.eventio.AEFileInputStreamInterface; /** * Base class for AEPlayers for playing back AER data files that implements some * parts of the interface. * * @author tobi * * This is part of jAER * <a href="http://jaerproject.net/">jaerproject.net</a>, licensed under the * LGPL (<a * href="http://en.wikipedia.org/wiki/GNU_Lesser_General_Public_License">http://en.wikipedia.org/wiki/GNU_Lesser_General_Public_License</a>. */ public abstract class AbstractAEPlayer { protected AEViewer viewer = null; protected static Logger log = Logger.getLogger("AbstractAEPlayer"); /** * The AE file input stream. */ protected AEFileInputStreamInterface aeFileInputStream = null; /** * The input file. */ protected File inputFile = null; public final PausePlayAction pausePlayAction = new PausePlayAction(); public final PlayAction playAction = new PlayAction(); public final PlayBackwardsAction playBackwardsAction = new PlayBackwardsAction(); public final PauseAction pauseAction = new PauseAction(); public final RewindAction rewindAction = new RewindAction(); public final FasterAction fasterAction = new FasterAction(); public final SlowerAction slowerAction = new SlowerAction(); public final ReverseAction reverseAction = new ReverseAction(); public final StepForwardAction stepForwardAction = new StepForwardAction(); public final StepBackwardAction stepBackwardAction = new StepBackwardAction(); // public final SyncPlaybackAction syncPlaybackAction = new SyncPlaybackAction(); public final MarkInAction markInAction = new MarkInAction(); public final MarkOutAction markOutAction = new MarkOutAction(); public final ClearMarksAction clearMarksAction = new ClearMarksAction(); /** * PropertyChangeEvent. */ public static final String EVENT_PLAYBACKMODE = "playbackMode", EVENT_TIMESLICE_US = "timesliceUs", EVENT_PACKETSIZEEVENTS = "packetSizeEvents", EVENT_PLAYBACKDIRECTION = "playbackDirection", EVENT_PAUSED = "paused", EVENT_RESUMED = "resumed", EVENT_STOPPED = "stopped", EVENT_FILEOPEN = "fileopen", EVENT_REPEAT = "repeat"; // TODO not used yet in code /** * Creates new instance of AbstractAEPlayer and adds the viewer (if not * null) to the list of listeners. * * @param viewer must be instance of AEViewer. */ public AbstractAEPlayer(AEViewer viewer) { this.viewer = viewer; if (viewer != null) { support.addPropertyChangeListener(viewer); // TODO do we always want to add viewer to the listeners, or should it be up to the viewer to decide? } } // /**Returns the proper AbstractAEPlayer: either <code>this</code> or the delegated-to JAERViewer.SyncPlayer. // * // * @return the local player, unless we are part of a synchronized playback gruop. // */ // public AbstractAEPlayer getAePlayer (){ // if ( viewer == null || viewer.getJaerViewer() == null || !viewer.getJaerViewer().isSyncEnabled() || viewer.getJaerViewer().getViewers().size() == 1 ){ // return viewer.aePlayer; // } // // return viewer.getJaerViewer().getSyncPlayer(); // } // // /** Returns true if we delegate our player responsibilities to the JAERViewer.SyncPlayer player. // * // * @return true if delegated. // */ // public boolean isDelegated (){ // if ( viewer == null || viewer.getJaerViewer() == null || !viewer.getJaerViewer().isSyncEnabled() || viewer.getJaerViewer().getViewers().size() == 1 ){ // return false; // } else{ // return true; // } // } // // /** Returns this. */ // public AbstractAEPlayer getLocalPlayer(){ // return this; // } // // /** Returns the JAERViewer.SyncPlayer; throws null reference exception if viewer is null. // * // * @return // */ // public AbstractAEPlayer getGlobalPlayer(){ // return viewer.getJaerViewer().getSyncPlayer(); // } protected PropertyChangeSupport support = new PropertyChangeSupport(this); /** * Fires the following change events: (see EVENT_ public static final * Strings) * <ul> * <li> timesliceUs - when timeslice changes. * <li> packetSizeEvents - when packet size changes. * <li> playbackMode - when {@link #playbackMode} changes. * <li> playbackDirection - when {@link #playbackDirection} changes. * <li> paused - when paused. * <li> resumed - when resumed. * <li> stopped - when playback is stopped. * </ul> */ public PropertyChangeSupport getSupport() { return support; } /** * Adds a listener for property changes * * @param listener the listener * @see #getSupport() */ public void addPropertyChangeListener(PropertyChangeListener listener) { this.support.addPropertyChangeListener(listener); } /** * Removes a listener * * @param listener the listener * @see #getSupport() */ public void removePropertyChangeListener(PropertyChangeListener listener) { this.support.removePropertyChangeListener(listener); } /** * Flog for all pause/resume state. */ volatile protected boolean paused = false; // multiple threads will access /** * Whether playback repeats after mark out or EOF is reached */ volatile protected boolean repeat = viewer.prefs.getBoolean("AbstractAEPlayer.repeat", true); // multiple threads will access public abstract void setFractionalPosition(float fracPos); abstract public void setDoSingleStepEnabled(boolean b); abstract public void doSingleStep(); /** * Returns the associated viewer. * * @return the viewer */ public AEViewer getViewer() { return viewer; } /** * Use this method to set the viewer if it has changed since construction. * * @param viewer the viewer to set */ public void setViewer(AEViewer viewer) { this.viewer = viewer; } public enum PlaybackMode { FixedTimeSlice, FixedPacketSize, RealTime } public enum PlaybackDirection { Forward, Backward } protected PlaybackMode playbackMode = PlaybackMode.FixedTimeSlice; protected PlaybackDirection playbackDirection = PlaybackDirection.Forward; protected int timesliceUs = 20000; protected int packetSizeEvents = 256; protected int jogPacketCount = 30; protected int jogPacketsLeft = 0; protected boolean jogOccuring = false; abstract public void openAEInputFileDialog(); abstract public AEPacketRaw getNextPacket(AbstractAEPlayer player); abstract public AEPacketRaw getNextPacket(); /** * Speeds up the playback so that more time or more events are displayed per * slice. * */ public void speedUp() { if (isFlexTimeEnabled()) { setPacketSizeEvents(getPacketSizeEvents() * 2); } else { long newTimeSlice = (long) getTimesliceUs() * 2; if (newTimeSlice > (long) Integer.MAX_VALUE) { newTimeSlice = Integer.MAX_VALUE; // clip to avoid negative slices sizes for slices > 2G us } setTimesliceUs((int) newTimeSlice); } log.info("new time and event slice durations are " + getTimesliceUs() + " us and " + getPacketSizeEvents() + "events"); } /** * Slows down the playback so that less time or fewer events are displayed * per slice. * */ public void slowDown() { if (isFlexTimeEnabled()) { setPacketSizeEvents(getPacketSizeEvents() / 2); if (getPacketSizeEvents() == 0) { setPacketSizeEvents(1); } } else { setTimesliceUs(getTimesliceUs() / 2); if (getTimesliceUs() == 0) { log.info("tried to reduce timeslice below 1us, clipped to 1us"); setTimesliceUs(1); } } if (Math.abs(getPacketSizeEvents()) < 1) { setPacketSizeEvents((int) Math.signum(getPacketSizeEvents())); } if (Math.abs(getTimesliceUs()) < 1) { setTimesliceUs((int) Math.signum(getTimesliceUs())); } log.info("new time and event slice durations are " + getTimesliceUs() + " us and " + getPacketSizeEvents() + "events"); } public void jogForwards() { jogOccuring = true; jogPacketsLeft += jogPacketCount; } public void jogBackwards() { jogOccuring = true; jogPacketsLeft -= jogPacketCount; } public void cancelJog() { jogOccuring = false; jogPacketsLeft = 0; } /** * Should adjust the playback timeslice interval to approach real time * playback. */ abstract public void adjustTimesliceForRealtimePlayback(); public boolean isRealtimePlaybackEnabled() { return playbackMode == PlaybackMode.RealTime; } public PlaybackMode getPlaybackMode() { return playbackMode; } /** * Changes playback mode and fires PropertyChange EVENT_PLAYBACKMODE * * @param playbackMode */ public void setPlaybackMode(PlaybackMode playbackMode) { PlaybackMode old = this.playbackMode; this.playbackMode = playbackMode; support.firePropertyChange(EVENT_PLAYBACKMODE, old, playbackMode); } public AEFileInputStreamInterface getAEInputStream() { return aeFileInputStream; } abstract public int getTime(); abstract public boolean isChoosingFile(); public boolean isPlayingForwards() { return getTimesliceUs() > 0; } abstract public void clearMarks(); abstract public long setMarkIn(); abstract public long setMarkOut(); public void pause() { setPaused(true); } public void resume() { setPaused(false); } abstract public void rewind(); /** * Returns state of playback paused. * * @return true if the playback is paused. */ public boolean isPaused() { return paused; } /** * Pauses/unpauses playback. Fires property change "paused" or "resumed". * * @param yes true to pause, false to resume. */ public void setPaused(boolean yes) { boolean old = paused; paused = yes; support.firePropertyChange(paused ? EVENT_PAUSED : EVENT_RESUMED, old, paused); if (yes) { pausePlayAction.setPlayAction(); } else { pausePlayAction.setPauseAction(); } } /** * Returns state of repeat. * * @return true if the playback is repeated. */ public boolean isRepeat() { return repeat; } /** * repeats/unrepeats playback. Fires property change "repeatOn" or * "repeatOff". * * @param yes true to repeat, false to stop after playback. */ public void setRepeat(boolean yes) { boolean old = this.repeat; this.repeat = yes; support.firePropertyChange(EVENT_REPEAT, old, this.repeat); viewer.prefs.putBoolean("AbstractAEPlayer.repeat", this.repeat); } abstract public void setTime(int time); /** * Opens an input stream and starts playing it. * * @param file the file to play. * @param progressMonitor to monitor progress and allow canceling it * @throws IOException if there is some problem opening file. * @throws java.lang.InterruptedException if a long-running open operation * is interrupted */ abstract public void startPlayback(File file) throws IOException, InterruptedException; /** * Should close the input stream. */ abstract public void stopPlayback(); /** * Toggles the direction of playback */ public void toggleDirection() { setPacketSizeEvents(getPacketSizeEvents() * -1); setTimesliceUs(getTimesliceUs() * -1); if (getPlaybackDirection() == PlaybackDirection.Forward) { setPlaybackDirection(PlaybackDirection.Backward); } else { setPlaybackDirection(PlaybackDirection.Forward); } } /** * Sets the playback direction * * @param forwards true for forwards, false for backwards */ public void setDirectionForwards(boolean forwards) { int sign = forwards ? 1 : -1; setPacketSizeEvents(sign * Math.abs(getPacketSizeEvents())); setTimesliceUs(sign * Math.abs(getTimesliceUs())); } public int getPacketSizeEvents() { return packetSizeEvents; } public void setPacketSizeEvents(int packetSizeEvents) { int old = this.packetSizeEvents; this.packetSizeEvents = packetSizeEvents; support.firePropertyChange(EVENT_PACKETSIZEEVENTS, old, packetSizeEvents); } public boolean isFlexTimeEnabled() { return playbackMode == PlaybackMode.FixedPacketSize; } public void setFlexTimeEnabled() { setPlaybackMode(PlaybackMode.FixedPacketSize); } public void setFixedTimesliceEnabled() { setPlaybackMode(PlaybackMode.FixedTimeSlice); } public boolean isRealtimeEnabled() { return playbackMode == PlaybackMode.RealTime; } public void setRealtimeEnabled() { setPlaybackMode(PlaybackMode.RealTime); } public void setTimesliceUs(int samplePeriodUs) { int old = this.timesliceUs; this.timesliceUs = samplePeriodUs; support.firePropertyChange(EVENT_TIMESLICE_US, old, timesliceUs); } /** * Toggles between fixed packet size and fixed time slice. If mode is * RealTime, has no effect. * */ void toggleFlexTime() { if (playbackMode == PlaybackMode.FixedPacketSize) { setFixedTimesliceEnabled(); } else if (playbackMode == PlaybackMode.FixedTimeSlice) { setFlexTimeEnabled(); } else { log.warning("cannot toggle flex time since we are in RealTime playback mode now"); } } public int getTimesliceUs() { return timesliceUs; } public PlaybackDirection getPlaybackDirection() { return playbackDirection; } public void setPlaybackDirection(PlaybackDirection direction) { PlaybackDirection old = playbackDirection; this.playbackDirection = direction; support.firePropertyChange(EVENT_PLAYBACKDIRECTION, old, this.playbackDirection); } abstract public class MyAction extends AbstractAction { protected final String path = "/net/sf/jaer/graphics/icons/"; public MyAction() { super(); } public MyAction(String name, String icon) { putValue(Action.NAME, name); putValue(Action.SMALL_ICON, new javax.swing.ImageIcon(getClass().getResource(path + icon + ".gif"))); putValue("hideActionText", "true"); putValue(Action.SHORT_DESCRIPTION, name); } } final public class PausePlayAction extends MyAction { final String pauseIcon = "Pause16", playIcon = "Play16"; public PausePlayAction() { super("Pause", "Pause16"); } public void actionPerformed(ActionEvent e) { if (isPaused()) { setPaused(false); setPauseAction(); } else { setPaused(true); setPlayAction(); } } protected void setPauseAction() { putValue(Action.NAME, "Pause"); setIcon(pauseIcon); putValue(Action.SHORT_DESCRIPTION, "Pause"); } protected void setPlayAction() { putValue(Action.NAME, "Play"); setIcon(playIcon); putValue(Action.SHORT_DESCRIPTION, "Play"); } private void setIcon(String icon) { putValue(Action.SMALL_ICON, new javax.swing.ImageIcon(getClass().getResource(path + icon + ".gif"))); } } final public class ClearMarksAction extends MyAction { public ClearMarksAction() { super("Clear Marks", "ClearMarks16"); } public void actionPerformed(ActionEvent e) { clearMarks(); putValue(Action.SELECTED_KEY, true); putValue(Action.SHORT_DESCRIPTION, "Clears IN and OUT markers"); } } final public class MarkInAction extends MyAction { public MarkInAction() { super("Mark IN", "MarkIn16"); } public void actionPerformed(ActionEvent e) { setMarkIn(); putValue(Action.SELECTED_KEY, true); putValue(Action.SHORT_DESCRIPTION, "Marks IN marker"); } } final public class MarkOutAction extends MyAction { public MarkOutAction() { super("Mark OUT", "MarkOut16"); } public void actionPerformed(ActionEvent e) { setMarkOut(); putValue(Action.SELECTED_KEY, true); putValue(Action.SHORT_DESCRIPTION, "Sets OUT marker"); } } final public class PlayAction extends MyAction { public PlayAction() { super("Play", "Play16"); } public void actionPerformed(ActionEvent e) { setPlaybackDirection(PlaybackDirection.Forward); setPaused(false); putValue(Action.SELECTED_KEY, true); } } final public class PauseAction extends MyAction { public PauseAction() { super("Pause", "Pause16"); putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0)); } public void actionPerformed(ActionEvent e) { setPaused(true); putValue(Action.SELECTED_KEY, true); } } final public class RewindAction extends MyAction { public RewindAction() { super("Rewind", "Rewind16"); putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_R, 0)); } public void actionPerformed(ActionEvent e) { rewind(); putValue(Action.SELECTED_KEY, true); } } final public class ReverseAction extends MyAction { public ReverseAction() { super("Reverse", "Reverse16"); putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_B, 0)); } public void actionPerformed(ActionEvent e) { toggleDirection(); putValue(Action.SELECTED_KEY, true); } } final public class PlayBackwardsAction extends MyAction { public PlayBackwardsAction() { super("Play Backwards", "PlayBackwards16"); } public void actionPerformed(ActionEvent e) { setPlaybackDirection(PlaybackDirection.Backward); setPaused(false); putValue(Action.SELECTED_KEY, true); } } final public class FasterAction extends MyAction { public FasterAction() { super("Play faster", "Faster16"); putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_F, 0)); } public void actionPerformed(ActionEvent e) { speedUp(); putValue(Action.SELECTED_KEY, true); } } final public class SlowerAction extends MyAction { public SlowerAction() { super("Play slower", "Slower16"); putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_S, 0)); } public void actionPerformed(ActionEvent e) { slowDown(); putValue(Action.SELECTED_KEY, true); } } final public class StepForwardAction extends MyAction { public StepForwardAction() { super("Step forward", "StepForward16"); putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_PERIOD, 0)); } public void actionPerformed(ActionEvent e) { setPlaybackDirection(PlaybackDirection.Forward); doSingleStep(); if (viewer != null) { viewer.interruptViewloop(); } putValue(Action.SELECTED_KEY, true); } } final public class StepBackwardAction extends MyAction { public StepBackwardAction() { super("Step backward", "StepBack16"); putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_COMMA, 0)); } public void actionPerformed(ActionEvent e) { setPlaybackDirection(PlaybackDirection.Backward); doSingleStep(); if (viewer != null) { viewer.interruptViewloop(); } putValue(Action.SELECTED_KEY, true); } } // final public class SyncPlaybackAction extends AbstractAction{ // public SyncPlaybackAction (){ // super("Synchronized playback"); // } // // public void actionPerformed (ActionEvent e){ // log.info(e.toString()); // // if ( getViewer() == null ){ // return; // } // getViewer().getJaerViewer().getToggleSyncEnabledAction().actionPerformed(e); // } // } @Override public String toString() { return String.format("AEPlayer paused=%s repeat=%s playBackDirection=%s playBackMode=%s timesliceUs=%d packetSizeEvents=%d ", paused, repeat, playbackDirection, playbackMode, timesliceUs, packetSizeEvents); } /** * @return the jogPacketCount */ public int getJogPacketCount() { return jogPacketCount; } /** * @param jogPacketCount the jogPacketCount to set */ public void setJogPacketCount(int jogPacketCount) { this.jogPacketCount = jogPacketCount; } }
src/net/sf/jaer/graphics/AbstractAEPlayer.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package net.sf.jaer.graphics; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.io.File; import java.io.IOException; import java.util.logging.Logger; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.KeyStroke; import net.sf.jaer.aemonitor.AEPacketRaw; import net.sf.jaer.eventio.AEFileInputStreamInterface; /** * Base class for AEPlayers for playing back AER data files that implements some * parts of the interface. * * @author tobi * * This is part of jAER * <a href="http://jaerproject.net/">jaerproject.net</a>, licensed under the * LGPL (<a * href="http://en.wikipedia.org/wiki/GNU_Lesser_General_Public_License">http://en.wikipedia.org/wiki/GNU_Lesser_General_Public_License</a>. */ public abstract class AbstractAEPlayer { protected AEViewer viewer = null; protected static Logger log = Logger.getLogger("AbstractAEPlayer"); /** * The AE file input stream. */ protected AEFileInputStreamInterface aeFileInputStream = null; /** * The input file. */ protected File inputFile = null; public final PausePlayAction pausePlayAction = new PausePlayAction(); public final PlayAction playAction = new PlayAction(); public final PlayBackwardsAction playBackwardsAction = new PlayBackwardsAction(); public final PauseAction pauseAction = new PauseAction(); public final RewindAction rewindAction = new RewindAction(); public final FasterAction fasterAction = new FasterAction(); public final SlowerAction slowerAction = new SlowerAction(); public final ReverseAction reverseAction = new ReverseAction(); public final StepForwardAction stepForwardAction = new StepForwardAction(); public final StepBackwardAction stepBackwardAction = new StepBackwardAction(); // public final SyncPlaybackAction syncPlaybackAction = new SyncPlaybackAction(); public final MarkInAction markInAction = new MarkInAction(); public final MarkOutAction markOutAction = new MarkOutAction(); public final ClearMarksAction clearMarksAction = new ClearMarksAction(); /** * PropertyChangeEvent. */ public static final String EVENT_PLAYBACKMODE = "playbackMode", EVENT_TIMESLICE_US = "timesliceUs", EVENT_PACKETSIZEEVENTS = "packetSizeEvents", EVENT_PLAYBACKDIRECTION = "playbackDirection", EVENT_PAUSED = "paused", EVENT_RESUMED = "resumed", EVENT_STOPPED = "stopped", EVENT_FILEOPEN = "fileopen", EVENT_REPEAT = "repeat"; // TODO not used yet in code /** * Creates new instance of AbstractAEPlayer and adds the viewer (if not * null) to the list of listeners. * * @param viewer must be instance of AEViewer. */ public AbstractAEPlayer(AEViewer viewer) { this.viewer = viewer; if (viewer != null) { support.addPropertyChangeListener(viewer); // TODO do we always want to add viewer to the listeners, or should it be up to the viewer to decide? } } // /**Returns the proper AbstractAEPlayer: either <code>this</code> or the delegated-to JAERViewer.SyncPlayer. // * // * @return the local player, unless we are part of a synchronized playback gruop. // */ // public AbstractAEPlayer getAePlayer (){ // if ( viewer == null || viewer.getJaerViewer() == null || !viewer.getJaerViewer().isSyncEnabled() || viewer.getJaerViewer().getViewers().size() == 1 ){ // return viewer.aePlayer; // } // // return viewer.getJaerViewer().getSyncPlayer(); // } // // /** Returns true if we delegate our player responsibilities to the JAERViewer.SyncPlayer player. // * // * @return true if delegated. // */ // public boolean isDelegated (){ // if ( viewer == null || viewer.getJaerViewer() == null || !viewer.getJaerViewer().isSyncEnabled() || viewer.getJaerViewer().getViewers().size() == 1 ){ // return false; // } else{ // return true; // } // } // // /** Returns this. */ // public AbstractAEPlayer getLocalPlayer(){ // return this; // } // // /** Returns the JAERViewer.SyncPlayer; throws null reference exception if viewer is null. // * // * @return // */ // public AbstractAEPlayer getGlobalPlayer(){ // return viewer.getJaerViewer().getSyncPlayer(); // } protected PropertyChangeSupport support = new PropertyChangeSupport(this); /** * Fires the following change events: (see EVENT_ public static final * Strings) * <ul> * <li> timesliceUs - when timeslice changes. * <li> packetSizeEvents - when packet size changes. * <li> playbackMode - when {@link #playbackMode} changes. * <li> playbackDirection - when {@link #playbackDirection} changes. * <li> paused - when paused. * <li> resumed - when resumed. * <li> stopped - when playback is stopped. * </ul> */ public PropertyChangeSupport getSupport() { return support; } /** * Adds a listener for property changes * * @param listener the listener * @see #getSupport() */ public void addPropertyChangeListener(PropertyChangeListener listener) { this.support.addPropertyChangeListener(listener); } /** * Removes a listener * * @param listener the listener * @see #getSupport() */ public void removePropertyChangeListener(PropertyChangeListener listener) { this.support.removePropertyChangeListener(listener); } /** * Flog for all pause/resume state. */ volatile protected boolean paused = false; // multiple threads will access /** * Whether playback repeats after mark out or EOF is reached */ volatile protected boolean repeat = viewer.prefs.getBoolean("AbstractAEPlayer.repeat", true); // multiple threads will access public abstract void setFractionalPosition(float fracPos); abstract public void setDoSingleStepEnabled(boolean b); abstract public void doSingleStep(); /** * Returns the associated viewer. * * @return the viewer */ public AEViewer getViewer() { return viewer; } /** * Use this method to set the viewer if it has changed since construction. * * @param viewer the viewer to set */ public void setViewer(AEViewer viewer) { this.viewer = viewer; } public enum PlaybackMode { FixedTimeSlice, FixedPacketSize, RealTime } public enum PlaybackDirection { Forward, Backward } protected PlaybackMode playbackMode = PlaybackMode.FixedTimeSlice; protected PlaybackDirection playbackDirection = PlaybackDirection.Forward; protected int timesliceUs = 20000; protected int packetSizeEvents = 256; protected int jogPacketCount = 30; protected int jogPacketsLeft = 0; protected boolean jogOccuring = false; abstract public void openAEInputFileDialog(); abstract public AEPacketRaw getNextPacket(AbstractAEPlayer player); abstract public AEPacketRaw getNextPacket(); /** * Speeds up the playback so that more time or more events are displayed per * slice. * */ public void speedUp() { if (isFlexTimeEnabled()) { setPacketSizeEvents(getPacketSizeEvents() * 2); } else { long newTimeSlice = (long) getTimesliceUs() * 2; if (newTimeSlice > (long) Integer.MAX_VALUE) { newTimeSlice = Integer.MAX_VALUE; // clip to avoid negative slices sizes for slices > 2G us } setTimesliceUs((int) newTimeSlice); } log.info("new time and event slice durations are "+getTimesliceUs()+" us and "+getPacketSizeEvents()+"events"); } /** * Slows down the playback so that less time or fewer events are displayed * per slice. * */ public void slowDown() { if (isFlexTimeEnabled()) { setPacketSizeEvents(getPacketSizeEvents() / 2); if (getPacketSizeEvents() == 0) { setPacketSizeEvents(1); } } else { setTimesliceUs(getTimesliceUs() / 2); if (getTimesliceUs() == 0) { log.info("tried to reduce timeslice below 1us, clipped to 1us"); setTimesliceUs(1); } } if (Math.abs(getPacketSizeEvents()) < 1) { setPacketSizeEvents((int) Math.signum(getPacketSizeEvents())); } if (Math.abs(getTimesliceUs()) < 1) { setTimesliceUs((int) Math.signum(getTimesliceUs())); } log.info("new time and event slice durations are "+getTimesliceUs()+" us and "+getPacketSizeEvents()+"events"); } public void jogForwards() { jogOccuring = true; jogPacketsLeft += jogPacketCount; } public void jogBackwards() { jogOccuring = true; jogPacketsLeft -= jogPacketCount; } public void cancelJog(){ jogOccuring=false; jogPacketsLeft=0; } /** * Should adjust the playback timeslice interval to approach real time * playback. */ abstract public void adjustTimesliceForRealtimePlayback(); public boolean isRealtimePlaybackEnabled() { return playbackMode == PlaybackMode.RealTime; } public PlaybackMode getPlaybackMode() { return playbackMode; } /** * Changes playback mode and fires PropertyChange EVENT_PLAYBACKMODE * * @param playbackMode */ public void setPlaybackMode(PlaybackMode playbackMode) { PlaybackMode old = this.playbackMode; this.playbackMode = playbackMode; support.firePropertyChange(EVENT_PLAYBACKMODE, old, playbackMode); } public AEFileInputStreamInterface getAEInputStream() { return aeFileInputStream; } abstract public int getTime(); abstract public boolean isChoosingFile(); public boolean isPlayingForwards() { return getTimesliceUs() > 0; } abstract public void clearMarks(); abstract public long setMarkIn(); abstract public long setMarkOut(); public void pause() { setPaused(true); } public void resume() { setPaused(false); } abstract public void rewind(); /** * Returns state of playback paused. * * @return true if the playback is paused. */ public boolean isPaused() { return paused; } /** * Pauses/unpauses playback. Fires property change "paused" or "resumed". * * @param yes true to pause, false to resume. */ public void setPaused(boolean yes) { boolean old = paused; paused = yes; support.firePropertyChange(paused ? EVENT_PAUSED : EVENT_RESUMED, old, paused); if (yes) { pausePlayAction.setPlayAction(); } else { pausePlayAction.setPauseAction(); } } /** * Returns state of repeat. * * @return true if the playback is repeated. */ public boolean isRepeat() { return repeat; } /** * repeats/unrepeats playback. Fires property change "repeatOn" or * "repeatOff". * * @param yes true to repeat, false to stop after playback. */ public void setRepeat(boolean yes) { boolean old = this.repeat; this.repeat = yes; support.firePropertyChange(EVENT_REPEAT, old, this.repeat); viewer.prefs.putBoolean("AbstractAEPlayer.repeat", this.repeat); } abstract public void setTime(int time); /** * Opens an input stream and starts playing it. * * @param file the file to play. * @param progressMonitor to monitor progress and allow canceling it * @throws IOException if there is some problem opening file. * @throws java.lang.InterruptedException if a long-running open operation * is interrupted */ abstract public void startPlayback(File file) throws IOException, InterruptedException; /** * Should close the input stream. */ abstract public void stopPlayback(); /** * Toggles the direction of playback */ public void toggleDirection() { setPacketSizeEvents(getPacketSizeEvents() * -1); setTimesliceUs(getTimesliceUs() * -1); } /** * Sets the playback direction * * @param forwards true for forwards, false for backwards */ public void setDirectionForwards(boolean forwards) { int sign = forwards ? 1 : -1; setPacketSizeEvents(sign * Math.abs(getPacketSizeEvents())); setTimesliceUs(sign * Math.abs(getTimesliceUs())); } public int getPacketSizeEvents() { return packetSizeEvents; } public void setPacketSizeEvents(int packetSizeEvents) { int old = this.packetSizeEvents; this.packetSizeEvents = packetSizeEvents; support.firePropertyChange(EVENT_PACKETSIZEEVENTS, old, packetSizeEvents); } public boolean isFlexTimeEnabled() { return playbackMode == PlaybackMode.FixedPacketSize; } public void setFlexTimeEnabled() { setPlaybackMode(PlaybackMode.FixedPacketSize); } public void setFixedTimesliceEnabled() { setPlaybackMode(PlaybackMode.FixedTimeSlice); } public boolean isRealtimeEnabled() { return playbackMode == PlaybackMode.RealTime; } public void setRealtimeEnabled() { setPlaybackMode(PlaybackMode.RealTime); } public void setTimesliceUs(int samplePeriodUs) { int old = this.timesliceUs; this.timesliceUs = samplePeriodUs; support.firePropertyChange(EVENT_TIMESLICE_US, old, timesliceUs); } /** * Toggles between fixed packet size and fixed time slice. If mode is * RealTime, has no effect. * */ void toggleFlexTime() { if (playbackMode == PlaybackMode.FixedPacketSize) { setFixedTimesliceEnabled(); } else if (playbackMode == PlaybackMode.FixedTimeSlice) { setFlexTimeEnabled(); } else { log.warning("cannot toggle flex time since we are in RealTime playback mode now"); } } public int getTimesliceUs() { return timesliceUs; } public PlaybackDirection getPlaybackDirection() { return playbackDirection; } public void setPlaybackDirection(PlaybackDirection direction) { PlaybackDirection old = playbackDirection; if (direction != this.playbackDirection) { toggleDirection(); } this.playbackDirection = direction; support.firePropertyChange(EVENT_PLAYBACKDIRECTION, old, this.playbackDirection); } abstract public class MyAction extends AbstractAction { protected final String path = "/net/sf/jaer/graphics/icons/"; public MyAction() { super(); } public MyAction(String name, String icon) { putValue(Action.NAME, name); putValue(Action.SMALL_ICON, new javax.swing.ImageIcon(getClass().getResource(path + icon + ".gif"))); putValue("hideActionText", "true"); putValue(Action.SHORT_DESCRIPTION, name); } } final public class PausePlayAction extends MyAction { final String pauseIcon = "Pause16", playIcon = "Play16"; public PausePlayAction() { super("Pause", "Pause16"); } public void actionPerformed(ActionEvent e) { if (isPaused()) { setPaused(false); setPauseAction(); } else { setPaused(true); setPlayAction(); } } protected void setPauseAction() { putValue(Action.NAME, "Pause"); setIcon(pauseIcon); putValue(Action.SHORT_DESCRIPTION, "Pause"); } protected void setPlayAction() { putValue(Action.NAME, "Play"); setIcon(playIcon); putValue(Action.SHORT_DESCRIPTION, "Play"); } private void setIcon(String icon) { putValue(Action.SMALL_ICON, new javax.swing.ImageIcon(getClass().getResource(path + icon + ".gif"))); } } final public class ClearMarksAction extends MyAction { public ClearMarksAction() { super("Clear Marks", "ClearMarks16"); } public void actionPerformed(ActionEvent e) { clearMarks(); putValue(Action.SELECTED_KEY, true); putValue(Action.SHORT_DESCRIPTION, "Clears IN and OUT markers"); } } final public class MarkInAction extends MyAction { public MarkInAction() { super("Mark IN", "MarkIn16"); } public void actionPerformed(ActionEvent e) { setMarkIn(); putValue(Action.SELECTED_KEY, true); putValue(Action.SHORT_DESCRIPTION, "Marks IN marker"); } } final public class MarkOutAction extends MyAction { public MarkOutAction() { super("Mark OUT", "MarkOut16"); } public void actionPerformed(ActionEvent e) { setMarkOut(); putValue(Action.SELECTED_KEY, true); putValue(Action.SHORT_DESCRIPTION, "Sets OUT marker"); } } final public class PlayAction extends MyAction { public PlayAction() { super("Play", "Play16"); } public void actionPerformed(ActionEvent e) { setPlaybackDirection(PlaybackDirection.Forward); setPaused(false); putValue(Action.SELECTED_KEY, true); } } final public class PauseAction extends MyAction { public PauseAction() { super("Pause", "Pause16"); putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0)); } public void actionPerformed(ActionEvent e) { setPaused(true); putValue(Action.SELECTED_KEY, true); } } final public class RewindAction extends MyAction { public RewindAction() { super("Rewind", "Rewind16"); putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_R, 0)); } public void actionPerformed(ActionEvent e) { rewind(); putValue(Action.SELECTED_KEY, true); } } final public class ReverseAction extends MyAction { public ReverseAction() { super("Reverse", "Reverse16"); putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_B, 0)); } public void actionPerformed(ActionEvent e) { toggleDirection(); putValue(Action.SELECTED_KEY, true); } } final public class PlayBackwardsAction extends MyAction { public PlayBackwardsAction() { super("Play Backwards", "PlayBackwards16"); } public void actionPerformed(ActionEvent e) { setPlaybackDirection(PlaybackDirection.Backward); setPaused(false); putValue(Action.SELECTED_KEY, true); } } final public class FasterAction extends MyAction { public FasterAction() { super("Play faster", "Faster16"); putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_F, 0)); } public void actionPerformed(ActionEvent e) { speedUp(); putValue(Action.SELECTED_KEY, true); } } final public class SlowerAction extends MyAction { public SlowerAction() { super("Play slower", "Slower16"); putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_S, 0)); } public void actionPerformed(ActionEvent e) { slowDown(); putValue(Action.SELECTED_KEY, true); } } final public class StepForwardAction extends MyAction { public StepForwardAction() { super("Step forward", "StepForward16"); putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_PERIOD, 0)); } public void actionPerformed(ActionEvent e) { setPlaybackDirection(PlaybackDirection.Forward); doSingleStep(); if (viewer != null) { viewer.interruptViewloop(); } putValue(Action.SELECTED_KEY, true); } } final public class StepBackwardAction extends MyAction { public StepBackwardAction() { super("Step backward", "StepBack16"); putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_COMMA, 0)); } public void actionPerformed(ActionEvent e) { setPlaybackDirection(PlaybackDirection.Backward); doSingleStep(); if (viewer != null) { viewer.interruptViewloop(); } putValue(Action.SELECTED_KEY, true); } } // final public class SyncPlaybackAction extends AbstractAction{ // public SyncPlaybackAction (){ // super("Synchronized playback"); // } // // public void actionPerformed (ActionEvent e){ // log.info(e.toString()); // // if ( getViewer() == null ){ // return; // } // getViewer().getJaerViewer().getToggleSyncEnabledAction().actionPerformed(e); // } // } @Override public String toString() { return String.format("AEPlayer paused=%s repeat=%s playBackDirection=%s playBackMode=%s timesliceUs=%d packetSizeEvents=%d ", paused, repeat, playbackDirection, playbackMode, timesliceUs, packetSizeEvents); } /** * @return the jogPacketCount */ public int getJogPacketCount() { return jogPacketCount; } /** * @param jogPacketCount the jogPacketCount to set */ public void setJogPacketCount(int jogPacketCount) { this.jogPacketCount = jogPacketCount; } }
reformat
src/net/sf/jaer/graphics/AbstractAEPlayer.java
reformat
Java
lgpl-2.1
991cea8d62dbd5fffc0f0c6de055ef1e8531cd97
0
ggiudetti/opencms-core,serrapos/opencms-core,MenZil/opencms-core,mediaworx/opencms-core,alkacon/opencms-core,sbonoc/opencms-core,MenZil/opencms-core,gallardo/opencms-core,it-tavis/opencms-core,alkacon/opencms-core,MenZil/opencms-core,it-tavis/opencms-core,ggiudetti/opencms-core,victos/opencms-core,it-tavis/opencms-core,serrapos/opencms-core,sbonoc/opencms-core,victos/opencms-core,sbonoc/opencms-core,alkacon/opencms-core,MenZil/opencms-core,serrapos/opencms-core,ggiudetti/opencms-core,alkacon/opencms-core,gallardo/opencms-core,it-tavis/opencms-core,sbonoc/opencms-core,gallardo/opencms-core,ggiudetti/opencms-core,victos/opencms-core,serrapos/opencms-core,serrapos/opencms-core,serrapos/opencms-core,serrapos/opencms-core,victos/opencms-core,gallardo/opencms-core,mediaworx/opencms-core,mediaworx/opencms-core,mediaworx/opencms-core
/* * File : $Source: /alkacon/cvs/opencms/src/com/opencms/workplace/Attic/CmsTaskContentDetail.java,v $ * Date : $Date: 2000/03/16 21:05:35 $ * Version: $Revision: 1.11 $ * * Copyright (C) 2000 The OpenCms Group * * This File is part of OpenCms - * the Open Source Content Mananagement System * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * For further information about OpenCms, please see the * OpenCms Website: http://www.opencms.com * * You should have received a copy of the GNU General Public License * long with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package com.opencms.workplace; import com.opencms.file.*; import com.opencms.core.*; import com.opencms.util.*; import com.opencms.template.*; import java.util.*; import javax.servlet.http.*; /** * Template class for displaying OpenCms workplace task content detail screens. * <P> * * @author Andreas Schouten * @version $Revision: 1.11 $ $Date: 2000/03/16 21:05:35 $ * @see com.opencms.workplace.CmsXmlWpTemplateFile */ public class CmsTaskContentDetail extends CmsWorkplaceDefault implements I_CmsConstants, I_CmsWpConstants { /** * Constant for generating user javascriptlist */ private final static String C_ALL_ROLES = "___all"; /** * Indicates if the results of this class are cacheable. * * @param cms A_CmsObject Object for accessing system resources * @param templateFile Filename of the template file * @param elementName Element name of this template in our parent template. * @param parameters Hashtable with all template class parameters. * @param templateSelector template section that should be processed. * @return <EM>true</EM> if cacheable, <EM>false</EM> otherwise. */ public boolean isCacheable(A_CmsObject cms, String templateFile, String elementName, Hashtable parameters, String templateSelector) { return false; } /** * Gets the content of a defined section in a given template file and its subtemplates * with the given parameters. * * @see getContent(A_CmsObject cms, String templateFile, String elementName, Hashtable parameters) * @param cms A_CmsObject Object for accessing system resources. * @param templateFile Filename of the template file. * @param elementName Element name of this template in our parent template. * @param parameters Hashtable with all template class parameters. * @param templateSelector template section that should be processed. */ public byte[] getContent(A_CmsObject cms, String templateFile, String elementName, Hashtable parameters, String templateSelector) throws CmsException { if(C_DEBUG && A_OpenCms.isLogging()) { A_OpenCms.log(C_OPENCMS_DEBUG, this.getClassName() + "getting content of element " + ((elementName==null)?"<root>":elementName)); A_OpenCms.log(C_OPENCMS_DEBUG, this.getClassName() + "template file is: " + templateFile); A_OpenCms.log(C_OPENCMS_DEBUG, this.getClassName() + "selected template section is: " + ((templateSelector==null)?"<default>":templateSelector)); } A_CmsRequestContext context = cms.getRequestContext(); CmsXmlWpTemplateFile xmlTemplateDocument = (CmsXmlWpTemplateFile) getOwnTemplateFile(cms, templateFile, elementName, parameters, templateSelector); A_CmsTask task; int taskid = -1; HttpSession session= ((HttpServletRequest)cms.getRequestContext().getRequest().getOriginalRequest()).getSession(true); try { Integer sessionTaskid = (Integer)session.getValue("taskid"); if(sessionTaskid != null) { taskid = sessionTaskid.intValue(); } try { taskid = Integer.parseInt((String)parameters.get("taskid")); } catch(Exception exc) { // no new taskid use the one from session } session.putValue("taskid", new Integer(taskid)); parameters.put("taskid", taskid + ""); task = cms.readTask(taskid); if("acceptok".equals((String)parameters.get("action"))){ // accept the task CmsTaskAction.accept(cms, taskid); } else if("accept".equals((String)parameters.get("action"))){ // show dialog templateSelector = "accept"; } else if("take".equals((String)parameters.get("action"))){ // show dialog templateSelector = "take"; } else if("takeok".equals((String)parameters.get("action"))){ // take the task CmsTaskAction.take(cms, taskid); } else if("forwardok".equals((String)parameters.get("action"))){ // forward the task CmsTaskAction.forward(cms, taskid, (String)parameters.get("USER"), (String)parameters.get("TEAM")); } else if("due".equals((String)parameters.get("action"))){ // show dialog templateSelector = "due"; } else if("dueok".equals((String)parameters.get("action"))){ // change the due-date of the task CmsTaskAction.due(cms, taskid, (String)parameters.get("DATE")); } else if("priorityok".equals((String)parameters.get("action"))){ // change the priority of the task CmsTaskAction.priority(cms, taskid, (String)parameters.get("PRIORITY")); } else if("reaktok".equals((String)parameters.get("action"))){ // reaktivate the task CmsTaskAction.reakt(cms, taskid, (String)parameters.get("USER"), (String)parameters.get("TEAM"), (String)parameters.get("TASK"), (String)parameters.get("DESCRIPTION"), (String)parameters.get("DATE"), (String)parameters.get("PRIORITY"), (String)parameters.get("MSG_ACCEPTATION"), (String)parameters.get("MSG_ALL"), (String)parameters.get("MSG_COMPLETION"), (String)parameters.get("MSG_DELIVERY")); } else if("okok".equals((String)parameters.get("action"))){ // ok the task CmsTaskAction.end(cms, taskid); } else if("ok".equals((String)parameters.get("action"))) { // show dialog templateSelector = "ok"; } else if("comment".equals((String)parameters.get("action"))) { // add comment String comment = (String)parameters.get("DESCRIPTION"); if( (comment != null) && (comment.length() != 0)) { cms.writeTaskLog(taskid, comment, C_TASKLOGTYPE_COMMENT); } } else if("messageok".equals((String)parameters.get("action"))) { // add message CmsTaskAction.message(cms, taskid, (String)parameters.get("DESCRIPTION")); } else if("queryok".equals((String)parameters.get("action"))) { // add message CmsTaskAction.query(cms, taskid, (String)parameters.get("DESCRIPTION")); } // update the task-data // it maybe had been changed task = cms.readTask(taskid); } catch (Exception exc) { throw new CmsException(CmsException.C_UNKNOWN_EXCEPTION, exc); } A_CmsUser owner = null; String ownerName = ""; try { owner = cms.readOwner(task); ownerName = owner.getName(); } catch(Exception exc) { // ignore the exception } A_CmsUser editor = null; String editorName = ""; try { editor = cms.readAgent(task); editorName = editor.getName(); } catch(Exception exc) { // ignore the exception } A_CmsGroup role = null; String roleName = ""; try { role = cms.readGroup(task); roleName = role.getName(); } catch(Exception exc) { // ignore the exception } String priority; String projectname = "?"; String style; String button1; String button2; String button3; String button4; String button5; String button6; long startTime; long timeout; GregorianCalendar cal = new GregorianCalendar(); cal.setTime(new Date(System.currentTimeMillis())); cal.set(Calendar.HOUR,0); cal.set(Calendar.MINUTE,0); cal.set(Calendar.SECOND,0); cal.set(Calendar.MILLISECOND,0); GregorianCalendar newcal = new GregorianCalendar(cal.get(Calendar.YEAR),cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH),0,0,0); long now = newcal.getTime().getTime(); try { projectname = cms.readTask(task.getRoot()).getName(); } catch(Exception exc) { // no root?! } priority = xmlTemplateDocument.getProcessedXmlDataValue("priority" + task.getPriority(), this); startTime = task.getStartTime().getTime(); timeout = task.getTimeOut().getTime(); String due = ""; try { due = Utils.getNiceShortDate(timeout); } catch(Exception exc) { // ignore the exception } String from = ""; try { from = Utils.getNiceShortDate(startTime); } catch(Exception exc) { // ignore the exception } xmlTemplateDocument.setXmlData("taskid", task.getId() + ""); boolean isOwner = context.currentUser().equals(owner); boolean isEditor = context.currentUser().equals(editor); boolean isInRole = false; try { isInRole = cms.userInGroup(context.currentUser().getName(), roleName); } catch(Exception exc) { // ignore the exception } // choose the right style and buttons if(task.getState() == C_TASK_STATE_ENDED) { if(isOwner) { // this is the owner of the task button1 = getButton(xmlTemplateDocument, "button_message", false); button2 = getButton(xmlTemplateDocument, "button_accept", false); button3 = getButton(xmlTemplateDocument, "button_due", false); button4 = getButton(xmlTemplateDocument, "button_priority", false); button5 = getButton(xmlTemplateDocument, "button_comment", false); button6 = getButton(xmlTemplateDocument, "button_reakt", true); } else if(isEditor) { // this user is the editor for this task button1 = getButton(xmlTemplateDocument, "button_query", false); button2 = getButton(xmlTemplateDocument, "button_forward", false); button3 = getButton(xmlTemplateDocument, "button_due", false); button4 = getButton(xmlTemplateDocument, "button_priority", false); button5 = getButton(xmlTemplateDocument, "button_comment", false); button6 = getButton(xmlTemplateDocument, "button_reakt", false); } else if(isInRole) { // this user is in the role for this task button1 = getButton(xmlTemplateDocument, "button_query", false); button2 = getButton(xmlTemplateDocument, "button_take", false); button3 = getButton(xmlTemplateDocument, "button_due", false); button4 = getButton(xmlTemplateDocument, "button_priority", false); button5 = getButton(xmlTemplateDocument, "button_comment", false); button6 = getButton(xmlTemplateDocument, "button_reakt", false); } else { // all other users button1 = getButton(xmlTemplateDocument, "button_query", false); button2 = getButton(xmlTemplateDocument, "button_take", false); button3 = getButton(xmlTemplateDocument, "button_due", false); button4 = getButton(xmlTemplateDocument, "button_priority", false); button5 = getButton(xmlTemplateDocument, "button_comment", false); button6 = getButton(xmlTemplateDocument, "button_reakt", false); } if(timeout < now ) { style = xmlTemplateDocument.getProcessedXmlDataValue("style_ok", this); } else { style = xmlTemplateDocument.getProcessedXmlDataValue("style_ok", this); } } else if(task.getPercentage() == 0) { if(isOwner && isEditor) { // this is a task from me and for me button1 = getButton(xmlTemplateDocument, "button_query", true); button2 = getButton(xmlTemplateDocument, "button_accept", true); button3 = getButton(xmlTemplateDocument, "button_due", true); button4 = getButton(xmlTemplateDocument, "button_priority", true); button5 = getButton(xmlTemplateDocument, "button_comment", true); button6 = getButton(xmlTemplateDocument, "button_ok", false); } else if(isOwner) { // this is the owner of the task button1 = getButton(xmlTemplateDocument, "button_message", true); button2 = getButton(xmlTemplateDocument, "button_forward", true); button3 = getButton(xmlTemplateDocument, "button_due", true); button4 = getButton(xmlTemplateDocument, "button_priority", true); button5 = getButton(xmlTemplateDocument, "button_comment", true); button6 = getButton(xmlTemplateDocument, "button_ok", false); } else if(isEditor) { // this user is the editor for this task button1 = getButton(xmlTemplateDocument, "button_query", true); button2 = getButton(xmlTemplateDocument, "button_accept", true); button3 = getButton(xmlTemplateDocument, "button_due", false); button4 = getButton(xmlTemplateDocument, "button_priority", false); button5 = getButton(xmlTemplateDocument, "button_comment", true); button6 = getButton(xmlTemplateDocument, "button_ok", false); } else if(isInRole) { // this user is in the role for this task button1 = getButton(xmlTemplateDocument, "button_query", false); button2 = getButton(xmlTemplateDocument, "button_take", true); button3 = getButton(xmlTemplateDocument, "button_due", false); button4 = getButton(xmlTemplateDocument, "button_priority", false); button5 = getButton(xmlTemplateDocument, "button_comment", false); button6 = getButton(xmlTemplateDocument, "button_ok", false); } else { // all other users button1 = getButton(xmlTemplateDocument, "button_query", false); button2 = getButton(xmlTemplateDocument, "button_take", false); button3 = getButton(xmlTemplateDocument, "button_due", false); button4 = getButton(xmlTemplateDocument, "button_priority", false); button5 = getButton(xmlTemplateDocument, "button_comment", false); button6 = getButton(xmlTemplateDocument, "button_ok", false); } if(timeout < now ) { style = xmlTemplateDocument.getProcessedXmlDataValue("style_alert", this); } else { style = xmlTemplateDocument.getProcessedXmlDataValue("style_new", this); } } else { if(isOwner && isEditor) { // this is a task from me and for me button1 = getButton(xmlTemplateDocument, "button_query", true); button2 = getButton(xmlTemplateDocument, "button_forward", true); button3 = getButton(xmlTemplateDocument, "button_due", true); button4 = getButton(xmlTemplateDocument, "button_priority", true); button5 = getButton(xmlTemplateDocument, "button_comment", true); button6 = getButton(xmlTemplateDocument, "button_ok", true); } else if(isOwner) { // this is the owner of the task button1 = getButton(xmlTemplateDocument, "button_message", true); button2 = getButton(xmlTemplateDocument, "button_forward", true); button3 = getButton(xmlTemplateDocument, "button_due", true); button4 = getButton(xmlTemplateDocument, "button_priority", true); button5 = getButton(xmlTemplateDocument, "button_comment", true); button6 = getButton(xmlTemplateDocument, "button_ok", false); } else if(isEditor) { // this user is the editor for this task button1 = getButton(xmlTemplateDocument, "button_query", true); button2 = getButton(xmlTemplateDocument, "button_forward", true); button3 = getButton(xmlTemplateDocument, "button_due", false); button4 = getButton(xmlTemplateDocument, "button_priority", false); button5 = getButton(xmlTemplateDocument, "button_comment", true); button6 = getButton(xmlTemplateDocument, "button_ok", true); } else if(isInRole) { // this user is in the role for this task button1 = getButton(xmlTemplateDocument, "button_query", false); button2 = getButton(xmlTemplateDocument, "button_take", true); button3 = getButton(xmlTemplateDocument, "button_due", false); button4 = getButton(xmlTemplateDocument, "button_priority", false); button5 = getButton(xmlTemplateDocument, "button_comment", false); button6 = getButton(xmlTemplateDocument, "button_ok", false); } else { // all other users button1 = getButton(xmlTemplateDocument, "button_query", false); button2 = getButton(xmlTemplateDocument, "button_take", false); button3 = getButton(xmlTemplateDocument, "button_due", false); button4 = getButton(xmlTemplateDocument, "button_priority", false); button5 = getButton(xmlTemplateDocument, "button_comment", false); button6 = getButton(xmlTemplateDocument, "button_ok", false); } if(timeout < now ) { style = xmlTemplateDocument.getProcessedXmlDataValue("style_alert", this); } else { style = xmlTemplateDocument.getProcessedXmlDataValue("style_activ", this); } } // get the processed list. xmlTemplateDocument.setXmlData("style", style); xmlTemplateDocument.setXmlData("priority", priority); xmlTemplateDocument.setXmlData("task", task.getName()); xmlTemplateDocument.setXmlData("foruser", Utils.getFullName(editor)); xmlTemplateDocument.setXmlData("forrole", roleName); xmlTemplateDocument.setXmlData("actuator", Utils.getFullName(owner)); xmlTemplateDocument.setXmlData("due", due); xmlTemplateDocument.setXmlData("from", from); xmlTemplateDocument.setXmlData("project", projectname); // now setting the buttons xmlTemplateDocument.setXmlData("button1", button1); xmlTemplateDocument.setXmlData("button2", button2); xmlTemplateDocument.setXmlData("button3", button3); xmlTemplateDocument.setXmlData("button4", button4); xmlTemplateDocument.setXmlData("button5", button5); xmlTemplateDocument.setXmlData("button6", button6); // Now load the template file and start the processing return startProcessing(cms, xmlTemplateDocument, elementName, parameters, templateSelector); } /** * This private helper method generates a string-representation of a button. * @param xmlTemplateDocument The xml-document in which the buttons are defined. * @param name The name of the button to generate. * @param enabled True, if the button is enabled, else false. * @return the string-representation of the button. * @exception Throws CmsException, if something goes wrong. */ private String getButton(CmsXmlWpTemplateFile xmlTemplateDocument, String name, boolean enabled) throws CmsException { if(enabled) { // the button is enabled xmlTemplateDocument.setXmlData("disabled", ""); } else { // the button is disabled xmlTemplateDocument.setXmlData("disabled", "disabled"); } // return the generated button return xmlTemplateDocument.getProcessedXmlDataValue(name, this); } }
src/com/opencms/workplace/CmsTaskContentDetail.java
/* * File : $Source: /alkacon/cvs/opencms/src/com/opencms/workplace/Attic/CmsTaskContentDetail.java,v $ * Date : $Date: 2000/03/15 14:32:15 $ * Version: $Revision: 1.10 $ * * Copyright (C) 2000 The OpenCms Group * * This File is part of OpenCms - * the Open Source Content Mananagement System * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * For further information about OpenCms, please see the * OpenCms Website: http://www.opencms.com * * You should have received a copy of the GNU General Public License * long with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package com.opencms.workplace; import com.opencms.file.*; import com.opencms.core.*; import com.opencms.util.*; import com.opencms.template.*; import java.util.*; import javax.servlet.http.*; /** * Template class for displaying OpenCms workplace task content detail screens. * <P> * * @author Andreas Schouten * @version $Revision: 1.10 $ $Date: 2000/03/15 14:32:15 $ * @see com.opencms.workplace.CmsXmlWpTemplateFile */ public class CmsTaskContentDetail extends CmsWorkplaceDefault implements I_CmsConstants, I_CmsWpConstants { /** * Constant for generating user javascriptlist */ private final static String C_ALL_ROLES = "___all"; /** * Indicates if the results of this class are cacheable. * * @param cms A_CmsObject Object for accessing system resources * @param templateFile Filename of the template file * @param elementName Element name of this template in our parent template. * @param parameters Hashtable with all template class parameters. * @param templateSelector template section that should be processed. * @return <EM>true</EM> if cacheable, <EM>false</EM> otherwise. */ public boolean isCacheable(A_CmsObject cms, String templateFile, String elementName, Hashtable parameters, String templateSelector) { return false; } /** * Gets the content of a defined section in a given template file and its subtemplates * with the given parameters. * * @see getContent(A_CmsObject cms, String templateFile, String elementName, Hashtable parameters) * @param cms A_CmsObject Object for accessing system resources. * @param templateFile Filename of the template file. * @param elementName Element name of this template in our parent template. * @param parameters Hashtable with all template class parameters. * @param templateSelector template section that should be processed. */ public byte[] getContent(A_CmsObject cms, String templateFile, String elementName, Hashtable parameters, String templateSelector) throws CmsException { if(C_DEBUG && A_OpenCms.isLogging()) { A_OpenCms.log(C_OPENCMS_DEBUG, this.getClassName() + "getting content of element " + ((elementName==null)?"<root>":elementName)); A_OpenCms.log(C_OPENCMS_DEBUG, this.getClassName() + "template file is: " + templateFile); A_OpenCms.log(C_OPENCMS_DEBUG, this.getClassName() + "selected template section is: " + ((templateSelector==null)?"<default>":templateSelector)); } A_CmsRequestContext context = cms.getRequestContext(); CmsXmlWpTemplateFile xmlTemplateDocument = (CmsXmlWpTemplateFile) getOwnTemplateFile(cms, templateFile, elementName, parameters, templateSelector); A_CmsTask task; int taskid = -1; HttpSession session= ((HttpServletRequest)cms.getRequestContext().getRequest().getOriginalRequest()).getSession(true); try { Integer sessionTaskid = (Integer)session.getValue("taskid"); if(sessionTaskid != null) { taskid = sessionTaskid.intValue(); } try { taskid = Integer.parseInt((String)parameters.get("taskid")); } catch(Exception exc) { // no new taskid use the one from session } session.putValue("taskid", new Integer(taskid)); parameters.put("taskid", taskid + ""); task = cms.readTask(taskid); if("acceptok".equals((String)parameters.get("action"))){ // accept the task CmsTaskAction.accept(cms, taskid); } else if("accept".equals((String)parameters.get("action"))){ // show dialog templateSelector = "accept"; } else if("take".equals((String)parameters.get("action"))){ // show dialog templateSelector = "take"; } else if("takeok".equals((String)parameters.get("action"))){ // take the task CmsTaskAction.take(cms, taskid); } else if("forwardok".equals((String)parameters.get("action"))){ // forward the task CmsTaskAction.forward(cms, taskid, (String)parameters.get("USER"), (String)parameters.get("TEAM")); } else if("due".equals((String)parameters.get("action"))){ // show dialog templateSelector = "due"; } else if("dueok".equals((String)parameters.get("action"))){ // change the due-date of the task CmsTaskAction.due(cms, taskid, (String)parameters.get("DATE")); } else if("priorityok".equals((String)parameters.get("action"))){ // change the priority of the task CmsTaskAction.priority(cms, taskid, (String)parameters.get("PRIORITY")); } else if("reaktok".equals((String)parameters.get("action"))){ // reaktivate the task CmsTaskAction.reakt(cms, taskid, (String)parameters.get("USER"), (String)parameters.get("TEAM"), (String)parameters.get("TASK"), (String)parameters.get("DESCRIPTION"), (String)parameters.get("DATE"), (String)parameters.get("PRIORITY"), (String)parameters.get("MSG_ACCEPTATION"), (String)parameters.get("MSG_ALL"), (String)parameters.get("MSG_COMPLETION"), (String)parameters.get("MSG_DELIVERY")); } else if("okok".equals((String)parameters.get("action"))){ // ok the task CmsTaskAction.end(cms, taskid); } else if("ok".equals((String)parameters.get("action"))) { // show dialog templateSelector = "ok"; } else if("comment".equals((String)parameters.get("action"))) { // add comment String comment = (String)parameters.get("DESCRIPTION"); if( (comment != null) && (comment.length() != 0)) { cms.writeTaskLog(taskid, comment, C_TASKLOGTYPE_COMMENT); } } else if("messageok".equals((String)parameters.get("action"))) { // add message CmsTaskAction.message(cms, taskid, (String)parameters.get("DESCRIPTION")); } else if("queryok".equals((String)parameters.get("action"))) { // add message CmsTaskAction.query(cms, taskid, (String)parameters.get("DESCRIPTION")); } // update the task-data // it maybe had been changed task = cms.readTask(taskid); } catch (Exception exc) { throw new CmsException(CmsException.C_UNKNOWN_EXCEPTION, exc); } A_CmsUser owner = null; String ownerName = ""; try { owner = cms.readOwner(task); ownerName = owner.getName(); } catch(Exception exc) { // ignore the exception } A_CmsUser editor = null; String editorName = ""; try { editor = cms.readAgent(task); editorName = editor.getName(); } catch(Exception exc) { // ignore the exception } A_CmsGroup role = null; String roleName = ""; try { role = cms.readGroup(task); roleName = role.getName(); } catch(Exception exc) { // ignore the exception } String priority; String projectname = "?"; String style; String button1; String button2; String button3; String button4; String button5; String button6; long startTime; long timeout; GregorianCalendar cal = new GregorianCalendar(); cal.setTime(new Date(System.currentTimeMillis())); cal.set(Calendar.HOUR,0); cal.set(Calendar.MINUTE,0); cal.set(Calendar.SECOND,0); cal.set(Calendar.MILLISECOND,0); GregorianCalendar newcal = new GregorianCalendar(cal.get(Calendar.YEAR),cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH),0,0,0); long now = newcal.getTime().getTime(); try { projectname = cms.readTask(task.getRoot()).getName(); } catch(Exception exc) { // no root?! } priority = xmlTemplateDocument.getProcessedXmlDataValue("priority" + task.getPriority(), this); startTime = task.getStartTime().getTime(); timeout = task.getTimeOut().getTime(); String due = ""; try { due = Utils.getNiceShortDate(timeout); } catch(Exception exc) { // ignore the exception } String from = ""; try { from = Utils.getNiceShortDate(startTime); } catch(Exception exc) { // ignore the exception } xmlTemplateDocument.setXmlData("taskid", task.getId() + ""); boolean isOwner = context.currentUser().equals(owner); boolean isEditor = context.currentUser().equals(editor); boolean isInRole = false; try { isInRole = cms.userInGroup(context.currentUser().getName(), roleName); } catch(Exception exc) { // ignore the exception } // choose the right style and buttons if(task.getState() == C_TASK_STATE_ENDED) { if(isOwner) { // this is the owner of the task button1 = getButton(xmlTemplateDocument, "button_message", false); button2 = getButton(xmlTemplateDocument, "button_accept", false); button3 = getButton(xmlTemplateDocument, "button_due", false); button4 = getButton(xmlTemplateDocument, "button_priority", false); button5 = getButton(xmlTemplateDocument, "button_comment", false); button6 = getButton(xmlTemplateDocument, "button_reakt", true); } else if(isEditor) { // this user is the editor for this task button1 = getButton(xmlTemplateDocument, "button_query", false); button2 = getButton(xmlTemplateDocument, "button_forward", false); button3 = getButton(xmlTemplateDocument, "button_due", false); button4 = getButton(xmlTemplateDocument, "button_priority", false); button5 = getButton(xmlTemplateDocument, "button_comment", false); button6 = getButton(xmlTemplateDocument, "button_reakt", false); } else if(isInRole) { // this user is in the role for this task button1 = getButton(xmlTemplateDocument, "button_query", false); button2 = getButton(xmlTemplateDocument, "button_take", false); button3 = getButton(xmlTemplateDocument, "button_due", false); button4 = getButton(xmlTemplateDocument, "button_priority", false); button5 = getButton(xmlTemplateDocument, "button_comment", false); button6 = getButton(xmlTemplateDocument, "button_reakt", false); } else { // all other users button1 = getButton(xmlTemplateDocument, "button_query", false); button2 = getButton(xmlTemplateDocument, "button_take", false); button3 = getButton(xmlTemplateDocument, "button_due", false); button4 = getButton(xmlTemplateDocument, "button_priority", false); button5 = getButton(xmlTemplateDocument, "button_comment", false); button6 = getButton(xmlTemplateDocument, "button_reakt", false); } if(timeout < now ) { style = xmlTemplateDocument.getProcessedXmlDataValue("style_ok", this); } else { style = xmlTemplateDocument.getProcessedXmlDataValue("style_ok", this); } } else if(task.getPercentage() == 0) { if(isOwner) { // this is the owner of the task button1 = getButton(xmlTemplateDocument, "button_message", true); button2 = getButton(xmlTemplateDocument, "button_forward", true); button3 = getButton(xmlTemplateDocument, "button_due", true); button4 = getButton(xmlTemplateDocument, "button_priority", true); button5 = getButton(xmlTemplateDocument, "button_comment", true); button6 = getButton(xmlTemplateDocument, "button_ok", false); } else if(isEditor) { // this user is the editor for this task button1 = getButton(xmlTemplateDocument, "button_query", true); button2 = getButton(xmlTemplateDocument, "button_accept", true); button3 = getButton(xmlTemplateDocument, "button_due", false); button4 = getButton(xmlTemplateDocument, "button_priority", false); button5 = getButton(xmlTemplateDocument, "button_comment", true); button6 = getButton(xmlTemplateDocument, "button_ok", false); } else if(isInRole) { // this user is in the role for this task button1 = getButton(xmlTemplateDocument, "button_query", false); button2 = getButton(xmlTemplateDocument, "button_take", true); button3 = getButton(xmlTemplateDocument, "button_due", false); button4 = getButton(xmlTemplateDocument, "button_priority", false); button5 = getButton(xmlTemplateDocument, "button_comment", false); button6 = getButton(xmlTemplateDocument, "button_ok", false); } else { // all other users button1 = getButton(xmlTemplateDocument, "button_query", false); button2 = getButton(xmlTemplateDocument, "button_take", false); button3 = getButton(xmlTemplateDocument, "button_due", false); button4 = getButton(xmlTemplateDocument, "button_priority", false); button5 = getButton(xmlTemplateDocument, "button_comment", false); button6 = getButton(xmlTemplateDocument, "button_ok", false); } if(timeout < now ) { style = xmlTemplateDocument.getProcessedXmlDataValue("style_alert", this); } else { style = xmlTemplateDocument.getProcessedXmlDataValue("style_new", this); } } else { if(isOwner) { // this is the owner of the task button1 = getButton(xmlTemplateDocument, "button_message", true); button2 = getButton(xmlTemplateDocument, "button_forward", true); button3 = getButton(xmlTemplateDocument, "button_due", true); button4 = getButton(xmlTemplateDocument, "button_priority", true); button5 = getButton(xmlTemplateDocument, "button_comment", true); button6 = getButton(xmlTemplateDocument, "button_ok", false); } else if(isEditor) { // this user is the editor for this task button1 = getButton(xmlTemplateDocument, "button_query", true); button2 = getButton(xmlTemplateDocument, "button_forward", true); button3 = getButton(xmlTemplateDocument, "button_due", false); button4 = getButton(xmlTemplateDocument, "button_priority", false); button5 = getButton(xmlTemplateDocument, "button_comment", true); button6 = getButton(xmlTemplateDocument, "button_ok", true); } else if(isInRole) { // this user is in the role for this task button1 = getButton(xmlTemplateDocument, "button_query", false); button2 = getButton(xmlTemplateDocument, "button_take", true); button3 = getButton(xmlTemplateDocument, "button_due", false); button4 = getButton(xmlTemplateDocument, "button_priority", false); button5 = getButton(xmlTemplateDocument, "button_comment", false); button6 = getButton(xmlTemplateDocument, "button_ok", false); } else { // all other users button1 = getButton(xmlTemplateDocument, "button_query", false); button2 = getButton(xmlTemplateDocument, "button_take", false); button3 = getButton(xmlTemplateDocument, "button_due", false); button4 = getButton(xmlTemplateDocument, "button_priority", false); button5 = getButton(xmlTemplateDocument, "button_comment", false); button6 = getButton(xmlTemplateDocument, "button_ok", false); } if(timeout < now ) { style = xmlTemplateDocument.getProcessedXmlDataValue("style_alert", this); } else { style = xmlTemplateDocument.getProcessedXmlDataValue("style_activ", this); } } // get the processed list. xmlTemplateDocument.setXmlData("style", style); xmlTemplateDocument.setXmlData("priority", priority); xmlTemplateDocument.setXmlData("task", task.getName()); xmlTemplateDocument.setXmlData("foruser", Utils.getFullName(editor)); xmlTemplateDocument.setXmlData("forrole", roleName); xmlTemplateDocument.setXmlData("actuator", Utils.getFullName(owner)); xmlTemplateDocument.setXmlData("due", due); xmlTemplateDocument.setXmlData("from", from); xmlTemplateDocument.setXmlData("project", projectname); // now setting the buttons xmlTemplateDocument.setXmlData("button1", button1); xmlTemplateDocument.setXmlData("button2", button2); xmlTemplateDocument.setXmlData("button3", button3); xmlTemplateDocument.setXmlData("button4", button4); xmlTemplateDocument.setXmlData("button5", button5); xmlTemplateDocument.setXmlData("button6", button6); // Now load the template file and start the processing return startProcessing(cms, xmlTemplateDocument, elementName, parameters, templateSelector); } /** * This private helper method generates a string-representation of a button. * @param xmlTemplateDocument The xml-document in which the buttons are defined. * @param name The name of the button to generate. * @param enabled True, if the button is enabled, else false. * @return the string-representation of the button. * @exception Throws CmsException, if something goes wrong. */ private String getButton(CmsXmlWpTemplateFile xmlTemplateDocument, String name, boolean enabled) throws CmsException { if(enabled) { // the button is enabled xmlTemplateDocument.setXmlData("disabled", ""); } else { // the button is disabled xmlTemplateDocument.setXmlData("disabled", "disabled"); } // return the generated button return xmlTemplateDocument.getProcessedXmlDataValue(name, this); } }
Now a user can create a task for himself.
src/com/opencms/workplace/CmsTaskContentDetail.java
Now a user can create a task for himself.
Java
lgpl-2.1
793d80c793f67720babcfa8a46267ba4c2c33161
0
SensorsINI/jaer,viktorbahr/jaer,viktorbahr/jaer,viktorbahr/jaer,SensorsINI/jaer,viktorbahr/jaer,SensorsINI/jaer,SensorsINI/jaer,SensorsINI/jaer,viktorbahr/jaer,viktorbahr/jaer,SensorsINI/jaer,SensorsINI/jaer,SensorsINI/jaer,viktorbahr/jaer
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.ine.telluride.cochlea; import ch.unizh.ini.caviar.chip.AEChip; import ch.unizh.ini.caviar.event.EventPacket; import ch.unizh.ini.caviar.eventprocessing.EventFilter2D; import ch.unizh.ini.caviar.graphics.FrameAnnotater; import com.sun.opengl.util.GLUT; import java.awt.Graphics2D; import javax.media.opengl.GL; import javax.media.opengl.GLAutoDrawable; import javax.media.opengl.glu.GLU; /** * Extracts pitch from AE cochlea spike output. * * @author ahs (Andrew Schwartz, MIT) */ public class MSO extends EventFilter2D implements FrameAnnotater { private static final int NUM_CHANS=32; private int binWidth=getPrefs().getInt("MSO.binWidth", 100); {setPropertyTooltip("binWidth", "Bin width for ITD hisotgram");} private int numBins=getPrefs().getInt("MSO.numBins", 15); {setPropertyTooltip("numBins", "Total number of bins, centered about 0");} private float[] ITDBuffer=null; private int[] ITDBins=null; private int[] ITDBinEdges=null; private boolean[] includeChannelInITD = new boolean[NUM_CHANS]; private int[][] delays=null; private ANFSpikeBuffer anf=null; private int chan, ii, jj, bin, count; private int spikeCount = 0; private int bufferSize = 0; private int newBufferSize = 0; private int[][][] spikeBuffer = null; private boolean[][] bufferFull; private int glBins = numBins; //temp: private int[][] bufferIndex = null; @Override public String getDescription() { return "Computes ITD of incoming binaural signal"; } public MSO(AEChip chip) { super(chip); resetFilter(); for(chan=0; chan<NUM_CHANS; chan++) { includeChannelInITD[chan]=true; } } @Override synchronized public EventPacket<?> filterPacket(EventPacket<?> in) { if(!isFilterEnabled()) { return in; } if(!checkSpikeBuffer()){ throw new RuntimeException("Can't find prior ANFSpikeBuffer in filter chain"); } if(in==null) { return in; } for(Object o : in) { spikeCount++; if (spikeCount==100) { computeITD(); spikeCount = 0; } } return in; } public void computeITD() { newBufferSize = anf.getBufferSize(); if (newBufferSize != bufferSize) { System.out.println("Buffer size changed! Allocating new memory for buffers"); bufferSize = newBufferSize; allocateSpikeBuffer(); } bufferFull = anf.getBufferFull(); spikeBuffer = anf.getBuffer(); initializeITDBuffer(); //compute delays in buffers for(chan=0; chan<NUM_CHANS; chan++) { if(includeChannelInITD[chan] && bufferFull[0][chan] && bufferFull[1][chan]) { //compute delays in this channel for(ii=0; ii<bufferSize; ii++) { for(jj=0; jj<bufferSize; jj++) { delays[ii][jj]=spikeBuffer[0][chan][ii]-spikeBuffer[1][chan][jj]; } } //bin delays for(bin=0; bin<numBins; bin++) { count=0; for(ii=0; ii<bufferSize; ii++) { for(jj=0; jj<bufferSize; jj++) { if(delays[ii][jj]>=ITDBinEdges[bin]&&delays[ii][jj]<=ITDBinEdges[bin+1]) { count++; } } } ITDBuffer[bin]+=count; } } // if (IncludeChannelInITD) } //for (chan=0; chan<NUM_CHANS; chan++) return; } public float[] getITD() { return ITDBuffer; } @Override public Object getFilterState() { return null; } @Override public void resetFilter() { binWidth = getPrefs().getInt("MSO.binWidth",100); numBins = getPrefs().getInt("MSO.numBins", 15); allocateITDBuffer(); allocateSpikeBuffer(); } @Override public void initFilter() { binWidth = getPrefs().getInt("MSO.binWidth",100); numBins = getPrefs().getInt("MSO.numBins", 15); allocateITDBuffer(); allocateSpikeBuffer(); } public int getBufferSize() { return bufferSize; } public void setBufferSize(int bufferSize) { this.bufferSize=bufferSize; getPrefs().putInt("MSO.bufferSize", bufferSize); allocateSpikeBuffer(); } public int getBinWidth() { return binWidth; } public void setBinWidth(int binWidth) { this.binWidth=binWidth; getPrefs().putInt("MSO.binWidth", binWidth); allocateITDBuffer(); } public int getNumBins() { return numBins; } public void setNumBins(int numBins) { this.numBins=numBins; getPrefs().putInt("MSO.numBins", numBins); allocateITDBuffer(); } private boolean checkSpikeBuffer() { if(anf==null) { anf=(ANFSpikeBuffer) chip.getFilterChain().findFilter(ANFSpikeBuffer.class); bufferSize = anf.getBufferSize(); allocateSpikeBuffer(); return anf!=null; } else { return true; } } private void allocateSpikeBuffer() { System.out.println("Allocatin spike buffer"); spikeBuffer= new int[2][NUM_CHANS][bufferSize]; bufferFull = new boolean[2][NUM_CHANS]; delays=new int[bufferSize][bufferSize]; } private void allocateITDBuffer() { System.out.println("Allocatin ITD buffer"); ITDBuffer=new float[numBins]; ITDBinEdges=new int[numBins+1]; ITDBins=new int[numBins]; initializeITDBuffer(); } private void initializeITDBuffer() { //set ITD buffer values for(ii=0; ii<numBins; ii++) { ITDBinEdges[ii]=(-numBins*binWidth)/2+ii*binWidth; ITDBins[ii]=(-(numBins-1)*binWidth)/2+ii*binWidth; ITDBuffer[ii]=0; } ITDBinEdges[numBins]=-ITDBinEdges[0]; } public void annotate(float[][][] frame) { } public void annotate(Graphics2D g) { } private GLU glu=new GLU(); ; public void annotate(GLAutoDrawable drawable) { if(!isFilterEnabled()) { return; // if(isRelaxed) return; } if (glBins!=numBins) { System.out.println("glBins differs from numBins! Reallocating..."); allocateITDBuffer(); glBins = numBins; } if (ITDBuffer!=null) { GL gl=drawable.getGL(); gl.glPushMatrix(); gl.glBegin(gl.GL_LINE_STRIP); gl.glColor3d(0, 1, 1); for (bin=0;bin<numBins;bin++) { gl.glVertex3f(bin,ITDBuffer[bin]/(NUM_CHANS),0); } gl.glEnd( ); for (bin=0;bin<numBins;bin+=3) { gl.glRasterPos2i(bin,-1); chip.getCanvas().getGlut().glutBitmapString(GLUT.BITMAP_HELVETICA_12, ""+ITDBins[bin]); } gl.glPopMatrix(); } } }
src/org/ine/telluride/cochlea/MSO.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.ine.telluride.cochlea; import ch.unizh.ini.caviar.chip.AEChip; import ch.unizh.ini.caviar.event.EventPacket; import ch.unizh.ini.caviar.eventprocessing.EventFilter2D; import ch.unizh.ini.caviar.graphics.FrameAnnotater; import com.sun.opengl.util.GLUT; import java.awt.Graphics2D; import javax.media.opengl.GL; import javax.media.opengl.GLAutoDrawable; import javax.media.opengl.glu.GLU; /** * Extracts pitch from AE cochlea spike output. * * @author ahs (Andrew Schwartz, MIT) */ public class MSO extends EventFilter2D implements FrameAnnotater { private static final int NUM_CHANS=32; private int binWidth=getPrefs().getInt("MSO.binWidth", 100); {setPropertyTooltip("binWidth", "Bin width for ITD hisotgram");} private int numBins=getPrefs().getInt("MSO.numBins", 15); {setPropertyTooltip("numBins", "Total number of bins, centered about 0");} private float[] ITDBuffer=null; private int[] ITDBins=null; private int[] ITDBinEdges=null; private boolean[] includeChannelInITD = new boolean[NUM_CHANS]; private int[][] delays=null; private ANFSpikeBuffer anf=null; private int chan, ii, jj, bin, count; private int spikeCount = 0; private int bufferSize = 0; private int newBufferSize = 0; private int[][][] spikeBuffer = null; private boolean[][] bufferFull; private int glBins = 0; //temp: private int[][] bufferIndex = null; @Override public String getDescription() { return "Computes ITD of incoming binaural signal"; } public MSO(AEChip chip) { super(chip); resetFilter(); for(chan=0; chan<NUM_CHANS; chan++) { includeChannelInITD[chan]=true; } } @Override synchronized public EventPacket<?> filterPacket(EventPacket<?> in) { if(!isFilterEnabled()) { return in; } if(!checkSpikeBuffer()){ throw new RuntimeException("Can't find prior ANFSpikeBuffer in filter chain"); } if(in==null) { return in; } for(Object o : in) { spikeCount++; if (spikeCount==100) { computeITD(); spikeCount = 0; } } return in; } public void computeITD() { newBufferSize = anf.getBufferSize(); if (newBufferSize != bufferSize) { System.out.println("Buffer size changed! Allocating new memory for buffers"); bufferSize = newBufferSize; allocateSpikeBuffer(); } bufferFull = anf.getBufferFull(); spikeBuffer = anf.getBuffer(); initializeITDBuffer(); //compute delays in buffers for(chan=0; chan<NUM_CHANS; chan++) { if(includeChannelInITD[chan] && bufferFull[0][chan] && bufferFull[1][chan]) { //compute delays in this channel for(ii=0; ii<bufferSize; ii++) { for(jj=0; jj<bufferSize; jj++) { delays[ii][jj]=spikeBuffer[0][chan][ii]-spikeBuffer[1][chan][jj]; } } //bin delays for(bin=0; bin<numBins; bin++) { count=0; for(ii=0; ii<bufferSize; ii++) { for(jj=0; jj<bufferSize; jj++) { if(delays[ii][jj]>=ITDBinEdges[bin]&&delays[ii][jj]<=ITDBinEdges[bin+1]) { count++; } } } ITDBuffer[bin]+=count; } } // if (IncludeChannelInITD) } //for (chan=0; chan<NUM_CHANS; chan++) return; } public float[] getITD() { return ITDBuffer; } @Override public Object getFilterState() { return null; } @Override public void resetFilter() { binWidth = getPrefs().getInt("MSO.binWidth",100); numBins = getPrefs().getInt("MSO.numBins", 15); allocateITDBuffer(); allocateSpikeBuffer(); } @Override public void initFilter() { binWidth = getPrefs().getInt("MSO.binWidth",100); numBins = getPrefs().getInt("MSO.numBins", 15); allocateITDBuffer(); allocateSpikeBuffer(); } public int getBufferSize() { return bufferSize; } public void setBufferSize(int bufferSize) { this.bufferSize=bufferSize; getPrefs().putInt("MSO.bufferSize", bufferSize); allocateSpikeBuffer(); } public int getBinWidth() { return binWidth; } public void setBinWidth(int binWidth) { this.binWidth=binWidth; getPrefs().putInt("MSO.binWidth", binWidth); allocateITDBuffer(); } public int getNumBins() { return numBins; } public void setNumBins(int numBins) { this.numBins=numBins; getPrefs().putInt("MSO.numBins", numBins); glBins = numBins; } private boolean checkSpikeBuffer() { if(anf==null) { anf=(ANFSpikeBuffer) chip.getFilterChain().findFilter(ANFSpikeBuffer.class); bufferSize = anf.getBufferSize(); allocateSpikeBuffer(); return anf!=null; } else { return true; } } private void allocateSpikeBuffer() { spikeBuffer= new int[2][NUM_CHANS][bufferSize]; bufferFull = new boolean[2][NUM_CHANS]; delays=new int[bufferSize][bufferSize]; } private void allocateITDBuffer() { ITDBuffer=new float[numBins]; ITDBinEdges=new int[numBins+1]; ITDBins=new int[numBins]; initializeITDBuffer(); } private void initializeITDBuffer() { //set ITD buffer values for(ii=0; ii<numBins; ii++) { ITDBinEdges[ii]=(-numBins*binWidth)/2+ii*binWidth; ITDBins[ii]=(-(numBins-1)*binWidth)/2+ii*binWidth; ITDBuffer[ii]=0; } ITDBinEdges[numBins]=-ITDBinEdges[0]; } public void annotate(float[][][] frame) { } public void annotate(Graphics2D g) { } private GLU glu=new GLU(); ; public void annotate(GLAutoDrawable drawable) { if(!isFilterEnabled()) { return; // if(isRelaxed) return; } if (ITDBuffer!=null && glBins==numBins) { GL gl=drawable.getGL(); gl.glPushMatrix(); gl.glBegin(gl.GL_LINE_STRIP); gl.glColor3d(0, 1, 1); for (bin=0;bin<numBins;bin++) { gl.glVertex3f(bin,ITDBuffer[bin]/(NUM_CHANS),0); } gl.glEnd( ); int font=GLUT.BITMAP_HELVETICA_12; chip.getCanvas().getGlut().glutBitmapString(font, "Test string"); gl.glPopMatrix(); } // show state of Goalie (arm shows its own state) // gl.glColor3d(1, 1, 1); // gl.glPushMatrix(); // gl.glRasterPos3f(1, 1, 0); // annotate the cluster with the arm state, e.g. relaxed or learning // String stats=String.format("%s rateFilter=%.2f speechinessFilter=%.2f isSomeoneThere=%s responseFraction=%.1f", // overallState.toString(),rateModulationFilter.getValue(),speechinessFilter.getValue(),isSomeoneThere(),getResponseFraction()); // chip.getCanvas().getGlut().glutBitmapString(font, stats); // gl.glPopMatrix(); } }
Graphical display of ITD. Must address changing ANF buffer size causes out of bounds exception. git-svn-id: e3d3b427d532171a6bd7557d8a4952a393b554a2@753 b7f4320f-462c-0410-a916-d9f35bb82d52
src/org/ine/telluride/cochlea/MSO.java
Graphical display of ITD. Must address changing ANF buffer size causes out of bounds exception.
Java
apache-2.0
2f9407b876a9e2a91c368777ab2aad88af3db2dd
0
JavaSaBr/jME3-SpaceShift-Editor
package com.ss.editor; import static com.jme3x.jfx.injfx.JmeToJFXIntegrator.bind; import static com.jme3x.jfx.injfx.processor.FrameTransferSceneProcessor.TransferMode.ON_CHANGES; import static com.ss.editor.config.DefaultSettingsProvider.Defaults.PREF_DEFAULT_OPEN_GL; import static com.ss.editor.config.DefaultSettingsProvider.Defaults.PREF_DEFAULT_STOP_RENDER_ON_LOST_FOCUS; import static com.ss.editor.config.DefaultSettingsProvider.Preferences.*; import static com.ss.rlib.util.ObjectUtils.notNull; import static com.ss.rlib.util.Utils.run; import static java.nio.file.Files.createDirectories; import static java.nio.file.Files.newOutputStream; import com.jme3.renderer.Renderer; import com.jme3.system.JmeContext; import com.jme3.util.LWJGLBufferAllocator; import com.jme3x.jfx.injfx.JmeToJFXApplication; import com.jme3x.jfx.injfx.processor.FrameTransferSceneProcessor; import com.ss.editor.analytics.google.GAEvent; import com.ss.editor.analytics.google.GAnalytics; import com.ss.editor.annotation.FromAnyThread; import com.ss.editor.annotation.FxThread; import com.ss.editor.annotation.JmeThread; import com.ss.editor.config.CommandLineConfig; import com.ss.editor.config.Config; import com.ss.editor.config.EditorConfig; import com.ss.editor.executor.impl.JmeThreadExecutor; import com.ss.editor.file.converter.FileConverterRegistry; import com.ss.editor.manager.*; import com.ss.editor.plugin.api.settings.SettingsProviderRegistry; import com.ss.editor.task.CheckNewVersionTask; import com.ss.editor.ui.builder.EditorFxSceneBuilder; import com.ss.editor.ui.component.asset.tree.AssetTreeContextMenuFillerRegistry; import com.ss.editor.ui.component.creator.FileCreatorRegistry; import com.ss.editor.ui.component.editor.EditorRegistry; import com.ss.editor.ui.component.log.LogView; import com.ss.editor.ui.control.property.builder.PropertyBuilderRegistry; import com.ss.editor.ui.control.tree.node.factory.TreeNodeFactoryRegistry; import com.ss.editor.ui.css.CssRegistry; import com.ss.editor.ui.dialog.ConfirmDialog; import com.ss.editor.ui.preview.FilePreviewFactoryRegistry; import com.ss.editor.ui.scene.EditorFxScene; import com.ss.editor.util.EditorUtil; import com.ss.editor.util.OpenGLVersion; import com.ss.editor.util.svg.SvgImageLoaderFactory; import com.ss.rlib.logging.Logger; import com.ss.rlib.logging.LoggerLevel; import com.ss.rlib.logging.LoggerManager; import com.ss.rlib.logging.impl.FolderFileListener; import com.ss.rlib.manager.InitializeManager; import com.ss.rlib.util.ArrayUtils; import com.ss.rlib.util.array.Array; import com.ss.rlib.util.array.ArrayFactory; import com.ss.rlib.util.array.ConcurrentArray; import javafx.application.Application; import javafx.application.Platform; import javafx.beans.value.ChangeListener; import javafx.collections.ObservableList; import javafx.scene.control.ComboBoxBase; import javafx.scene.image.Image; import javafx.stage.Stage; import javafx.stage.StageStyle; import javafx.stage.Window; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.lwjgl.system.Configuration; import javax.imageio.ImageIO; import java.io.IOException; import java.io.PrintStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Collection; import java.util.logging.Level; /** * The starter of the JavaFX application. * * @author JavaSaBr */ public class JfxApplication extends Application { @NotNull private static final Logger LOGGER = LoggerManager.getLogger(JfxApplication.class); @Nullable private static JfxApplication instance; /** * It's an internal method. * * @see EditorUtil */ @Deprecated @FromAnyThread public static @NotNull JfxApplication getInstance() { return notNull(instance); } /** * Main. * * @param args the args * @throws IOException the io exception */ public static void main(final String[] args) { configureLogger(); // need to disable to work on macos Configuration.GLFW_CHECK_THREAD0.set(false); // use jemalloc Configuration.MEMORY_ALLOCATOR.set("jemalloc"); // JavaFX System.setProperty("prism.lcdtext", "false"); System.setProperty("prism.text", "t2k"); System.setProperty("javafx.animation.fullspeed", "false"); final EditorConfig editorConfig = EditorConfig.getInstance(); final OpenGLVersion openGLVersion = editorConfig.getEnum(PREF_OPEN_GL, PREF_DEFAULT_OPEN_GL); // set a render if it isn't override if(System.getProperty("jfx.background.render") == null) { System.setProperty("jfx.background.render", openGLVersion.getRender()); } System.setProperty(LWJGLBufferAllocator.PROPERTY_CONCURRENT_BUFFER_ALLOCATOR, "true"); // some settings for the render of JavaFX System.setProperty("prism.printrendergraph", "false"); System.setProperty("javafx.pulseLogger", "false"); //System.setProperty("prism.cacheshapes", "true"); //System.setProperty("prism.scrollcacheopt", "true"); //System.setProperty("prism.allowhidpi", "true"); //System.setProperty("prism.order", "sw"); //System.setProperty("prism.showdirty", "true"); //System.setProperty("prism.showoverdraw", "true"); //System.setProperty("prism.debug", "true"); //System.setProperty("prism.verbose", "true"); CommandLineConfig.args(args); JmeToJFXApplication application; try { application = JmeApplication.prepareToStart(); } catch (final Throwable e) { printError(e); System.exit(-1); return; } InitializeManager.register(ClasspathManager.class); InitializeManager.register(ResourceManager.class); InitializeManager.register(JavaFxImageManager.class); InitializeManager.register(FileIconManager.class); InitializeManager.register(WorkspaceManager.class); InitializeManager.register(PluginManager.class); InitializeManager.register(RemoteControlManager.class); InitializeManager.initialize(); new EditorThread(new ThreadGroup("LWJGL"), () -> startJmeApplication(application), "LWJGL Render").start(); } @FxThread private static void configureLogger() { // disable the standard logger if (Config.DEV_DEBUG) { java.util.logging.Logger.getLogger("").setLevel(Level.WARNING); } // configure our logger LoggerLevel.DEBUG.setEnabled(Config.DEV_DEBUG); LoggerLevel.INFO.setEnabled(true); LoggerLevel.ERROR.setEnabled(true); LoggerLevel.WARNING.setEnabled(true); final Path logFolder = Config.getFolderForLog(); if (!Files.exists(logFolder)) { run(() -> createDirectories(logFolder)); } if (!LoggerLevel.DEBUG.isEnabled()) { LoggerManager.addListener(new FolderFileListener(logFolder)); } } /** * Start the new jME application. * * @param application the new jME application. */ @JmeThread private static void startJmeApplication(@NotNull final JmeToJFXApplication application) { final InitializationManager initializationManager = InitializationManager.getInstance(); initializationManager.onBeforeCreateJmeContext(); application.start(); final JmeContext context = application.getContext(); final Renderer renderer = context.getRenderer(); if (renderer == null) { final EditorConfig editorConfig = EditorConfig.getInstance(); editorConfig.set(PREF_OPEN_GL, OpenGLVersion.GL_20); editorConfig.save(); } } /** * Create a new focus listener. * * @return the new focus listener. */ @FxThread private static @NotNull ChangeListener<Boolean> makeFocusedListener() { return (observable, oldValue, newValue) -> { final JmeApplication jmeApplication = JmeApplication.getInstance(); final Stage stage = EditorUtil.getFxStage(); if (newValue || stage.isFocused()) { jmeApplication.setPaused(false); return; } final EditorConfig editorConfig = EditorConfig.getInstance(); if (!editorConfig.getBoolean(PREF_STOP_RENDER_ON_LOST_FOCUS, PREF_DEFAULT_STOP_RENDER_ON_LOST_FOCUS)) { jmeApplication.setPaused(false); return; } final JfxApplication application = JfxApplication.getInstance(); final Window window = ArrayUtils.getInReadLock(application.openedWindows, windows -> windows.search(Window::isFocused)); jmeApplication.setPaused(window == null); }; } /** * Start. */ @FromAnyThread public static void start() { launch(); } @FromAnyThread private static void printError(@NotNull final Throwable throwable) { throwable.printStackTrace(); final String userHome = System.getProperty("user.home"); final String fileName = "jmonkeybuilder-error.log"; try (final PrintStream out = new PrintStream(newOutputStream(Paths.get(userHome, fileName)))) { throwable.printStackTrace(out); } catch (final IOException e) { e.printStackTrace(); } } /** * The list of opened windows. */ @NotNull private final ConcurrentArray<Window> openedWindows; /** * The JavaFX scene. */ @Nullable private volatile EditorFxScene scene; /** * The scene processor. */ @Nullable private volatile FrameTransferSceneProcessor sceneProcessor; /** * The stage. */ @Nullable private Stage stage; public JfxApplication() { EditorUtil.setJfxApplication(this); this.openedWindows = ArrayFactory.newConcurrentStampedLockArray(Window.class); } /** * Request focus of this window. */ public void requestFocus() { notNull(stage).requestFocus(); } /** * Add the new opened window. * * @param window the new opened window. */ @FxThread public void addWindow(@NotNull final Window window) { window.focusedProperty().addListener(makeFocusedListener()); ArrayUtils.runInWriteLock(openedWindows, window, Collection::add); } /** * Remove the opened window. * * @param window the opened window. */ @FxThread public void removeWindow(@NotNull final Window window) { ArrayUtils.runInWriteLock(openedWindows, window, Array::slowRemove); } /** * Gets the last opened window. * * @return the last opened window. */ @FxThread public @NotNull Window getLastWindow() { return notNull(ArrayUtils.getInReadLock(openedWindows, Array::last)); } @Override @FxThread public void start(final Stage stage) throws Exception { JfxApplication.instance = this; this.stage = stage; addWindow(stage); try { // initialize javaFX events in javaFX thread. ArrayFactory.asArray(ComboBoxBase.ON_SHOWN); final ResourceManager resourceManager = ResourceManager.getInstance(); resourceManager.reload(); final InitializationManager initializationManager = InitializationManager.getInstance(); initializationManager.onBeforeCreateJavaFxContext(); final PluginManager pluginManager = PluginManager.getInstance(); pluginManager.handlePlugins(editorPlugin -> editorPlugin.register(CssRegistry.getInstance())); LogView.getInstance(); SvgImageLoaderFactory.install(); ImageIO.read(getClass().getResourceAsStream("/ui/icons/test/test.jpg")); final ObservableList<Image> icons = stage.getIcons(); icons.add(new Image("/ui/icons/app/256x256.png")); icons.add(new Image("/ui/icons/app/128x128.png")); icons.add(new Image("/ui/icons/app/96x96.png")); icons.add(new Image("/ui/icons/app/64x64.png")); icons.add(new Image("/ui/icons/app/48x48.png")); icons.add(new Image("/ui/icons/app/32x32.png")); icons.add(new Image("/ui/icons/app/24x24.png")); icons.add(new Image("/ui/icons/app/16x16.png")); final EditorConfig config = EditorConfig.getInstance(); stage.initStyle(StageStyle.DECORATED); stage.setMinHeight(600); stage.setMinWidth(800); stage.setWidth(config.getScreenWidth()); stage.setHeight(config.getScreenHeight()); stage.setMaximized(config.isMaximized()); stage.setTitle(Config.TITLE); stage.show(); if (!stage.isMaximized()) { stage.centerOnScreen(); } stage.widthProperty().addListener((observable, oldValue, newValue) -> { if (stage.isMaximized()) return; config.setScreenWidth(newValue.intValue()); }); stage.heightProperty().addListener((observable, oldValue, newValue) -> { if (stage.isMaximized()) return; config.setScreenHeight(newValue.intValue()); }); stage.maximizedProperty() .addListener((observable, oldValue, newValue) -> config.setMaximized(newValue)); buildScene(); } catch (final Throwable e) { LOGGER.error(this, e); throw e; } } @Override @FxThread public void stop() throws Exception { super.stop(); onExit(); } /** * On exit. */ @FxThread protected void onExit() { GAnalytics.forceSendEvent(GAEvent.Category.APPLICATION, GAEvent.Action.APPLICATION_CLOSED, GAEvent.Label.THE_EDITOR_APP_WAS_CLOSED); final EditorConfig config = EditorConfig.getInstance(); config.save(); final JmeThreadExecutor executor = JmeThreadExecutor.getInstance(); executor.addToExecute(() -> { final JmeApplication jmeApplication = JmeApplication.getInstance(); jmeApplication.destroy(); }); GAnalytics.waitForSend(); } /** * Build the scene. */ @FxThread private void buildScene() { this.scene = EditorFxSceneBuilder.build(notNull(stage)); final InitializationManager initializationManager = InitializationManager.getInstance(); initializationManager.onAfterCreateJavaFxContext(); final PluginManager pluginManager = PluginManager.getInstance(); pluginManager.handlePlugins(editorPlugin -> { editorPlugin.register(FileCreatorRegistry.getInstance()); editorPlugin.register(EditorRegistry.getInstance()); editorPlugin.register(FileIconManager.getInstance()); editorPlugin.register(FileConverterRegistry.getInstance()); editorPlugin.register(AssetTreeContextMenuFillerRegistry.getInstance()); editorPlugin.register(TreeNodeFactoryRegistry.getInstance()); editorPlugin.register(PropertyBuilderRegistry.getInstance()); editorPlugin.register(FilePreviewFactoryRegistry.getInstance()); editorPlugin.register(SettingsProviderRegistry.getInstance()); }); final EditorFxScene scene = getScene(); final JmeApplication jmeApplication = JmeApplication.getInstance(); final JmeThreadExecutor executor = JmeThreadExecutor.getInstance(); executor.addToExecute(() -> createSceneProcessor(scene, jmeApplication)); JmeFilePreviewManager.getInstance(); GAnalytics.forceSendEvent(GAEvent.Category.APPLICATION, GAEvent.Action.APPLICATION_LAUNCHED, GAEvent.Label.THE_EDITOR_APP_WAS_LAUNCHED); final ExecutorManager executorManager = ExecutorManager.getInstance(); executorManager.addBackgroundTask(new CheckNewVersionTask()); final EditorConfig editorConfig = EditorConfig.getInstance(); if (editorConfig.isAnalyticsQuestion()) { return; } editorConfig.set(PREF_ANALYTICS_GOOGLE, false); editorConfig.save(); Platform.runLater(() -> { final Stage stage = notNull(getStage()); final ConfirmDialog confirmDialog = new ConfirmDialog(result -> { editorConfig.setAnalyticsQuestion(true); editorConfig.set(PREF_ANALYTICS_GOOGLE, Boolean.TRUE.equals(result)); editorConfig.save(); }, Messages.ANALYTICS_CONFIRM_DIALOG_MESSAGE); confirmDialog.show(stage); }); } @FxThread private void createSceneProcessor(@NotNull final EditorFxScene scene, @NotNull final JmeApplication jmeApplication) { final FrameTransferSceneProcessor sceneProcessor = bind(jmeApplication, scene.getCanvas(), jmeApplication.getViewPort()); sceneProcessor.setEnabled(false); sceneProcessor.setTransferMode(ON_CHANGES); this.sceneProcessor = sceneProcessor; final Stage stage = notNull(getStage()); stage.focusedProperty().addListener(makeFocusedListener()); Platform.runLater(scene::notifyFinishBuild); } /** * Get the current JavaFX scene. * * @return the JavaFX scene. */ @FromAnyThread public @NotNull EditorFxScene getScene() { return notNull(scene, "Scene can't be null."); } /** * Get the current stage of JavaFX. * * @return the current stage. */ @FromAnyThread public @NotNull Stage getStage() { return notNull(stage); } /** * Get the current scene processor of this application. * * @return the scene processor. */ @FromAnyThread public @NotNull FrameTransferSceneProcessor getSceneProcessor() { return notNull(sceneProcessor, "Scene processor can't be null."); } }
src/main/java/com/ss/editor/JfxApplication.java
package com.ss.editor; import static com.jme3x.jfx.injfx.JmeToJFXIntegrator.bind; import static com.jme3x.jfx.injfx.processor.FrameTransferSceneProcessor.TransferMode.ON_CHANGES; import static com.ss.editor.config.DefaultSettingsProvider.Defaults.PREF_DEFAULT_OPEN_GL; import static com.ss.editor.config.DefaultSettingsProvider.Defaults.PREF_DEFAULT_STOP_RENDER_ON_LOST_FOCUS; import static com.ss.editor.config.DefaultSettingsProvider.Preferences.*; import static com.ss.rlib.util.ObjectUtils.notNull; import static com.ss.rlib.util.Utils.run; import static java.nio.file.Files.createDirectories; import static java.nio.file.Files.newOutputStream; import com.jme3.renderer.Renderer; import com.jme3.system.JmeContext; import com.jme3.util.LWJGLBufferAllocator; import com.jme3x.jfx.injfx.JmeToJFXApplication; import com.jme3x.jfx.injfx.processor.FrameTransferSceneProcessor; import com.ss.editor.analytics.google.GAEvent; import com.ss.editor.analytics.google.GAnalytics; import com.ss.editor.annotation.FromAnyThread; import com.ss.editor.annotation.FxThread; import com.ss.editor.annotation.JmeThread; import com.ss.editor.config.CommandLineConfig; import com.ss.editor.config.Config; import com.ss.editor.config.EditorConfig; import com.ss.editor.executor.impl.JmeThreadExecutor; import com.ss.editor.file.converter.FileConverterRegistry; import com.ss.editor.manager.*; import com.ss.editor.plugin.api.settings.SettingsProviderRegistry; import com.ss.editor.task.CheckNewVersionTask; import com.ss.editor.ui.builder.EditorFxSceneBuilder; import com.ss.editor.ui.component.asset.tree.AssetTreeContextMenuFillerRegistry; import com.ss.editor.ui.component.creator.FileCreatorRegistry; import com.ss.editor.ui.component.editor.EditorRegistry; import com.ss.editor.ui.component.log.LogView; import com.ss.editor.ui.control.property.builder.PropertyBuilderRegistry; import com.ss.editor.ui.control.tree.node.factory.TreeNodeFactoryRegistry; import com.ss.editor.ui.css.CssRegistry; import com.ss.editor.ui.dialog.ConfirmDialog; import com.ss.editor.ui.preview.FilePreviewFactoryRegistry; import com.ss.editor.ui.scene.EditorFxScene; import com.ss.editor.util.EditorUtil; import com.ss.editor.util.OpenGLVersion; import com.ss.editor.util.svg.SvgImageLoaderFactory; import com.ss.rlib.logging.Logger; import com.ss.rlib.logging.LoggerLevel; import com.ss.rlib.logging.LoggerManager; import com.ss.rlib.logging.impl.FolderFileListener; import com.ss.rlib.manager.InitializeManager; import com.ss.rlib.util.ArrayUtils; import com.ss.rlib.util.array.Array; import com.ss.rlib.util.array.ArrayFactory; import com.ss.rlib.util.array.ConcurrentArray; import javafx.application.Application; import javafx.application.Platform; import javafx.beans.value.ChangeListener; import javafx.collections.ObservableList; import javafx.scene.control.ComboBoxBase; import javafx.scene.image.Image; import javafx.stage.Stage; import javafx.stage.StageStyle; import javafx.stage.Window; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.lwjgl.system.Configuration; import javax.imageio.ImageIO; import java.io.IOException; import java.io.PrintStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Collection; import java.util.logging.Level; /** * The starter of the JavaFX application. * * @author JavaSaBr */ public class JfxApplication extends Application { @NotNull private static final Logger LOGGER = LoggerManager.getLogger(JfxApplication.class); @Nullable private static JfxApplication instance; /** * It's an internal method. * * @see EditorUtil */ @Deprecated @FromAnyThread public static @NotNull JfxApplication getInstance() { return notNull(instance); } /** * Main. * * @param args the args * @throws IOException the io exception */ public static void main(final String[] args) { configureLogger(); // need to disable to work on macos Configuration.GLFW_CHECK_THREAD0.set(false); // use jemalloc Configuration.MEMORY_ALLOCATOR.set("jemalloc"); // JavaFX System.setProperty("prism.lcdtext", "false"); System.setProperty("prism.text", "t2k"); System.setProperty("javafx.animation.fullspeed", "false"); final EditorConfig editorConfig = EditorConfig.getInstance(); final OpenGLVersion openGLVersion = editorConfig.getEnum(PREF_OPEN_GL, PREF_DEFAULT_OPEN_GL); // set a render if it isn't override if(System.getProperty("jfx.background.render") == null) { System.setProperty("jfx.background.render", openGLVersion.getRender()); } System.setProperty(LWJGLBufferAllocator.PROPERTY_CONCURRENT_BUFFER_ALLOCATOR, "true"); // some settings for the render of JavaFX System.setProperty("prism.printrendergraph", "false"); System.setProperty("javafx.pulseLogger", "false"); //System.setProperty("prism.cacheshapes", "true"); //System.setProperty("prism.scrollcacheopt", "true"); //System.setProperty("prism.allowhidpi", "true"); //System.setProperty("prism.order", "sw"); //System.setProperty("prism.showdirty", "true"); //System.setProperty("prism.showoverdraw", "true"); //System.setProperty("prism.debug", "true"); //System.setProperty("prism.verbose", "true"); CommandLineConfig.args(args); JmeToJFXApplication application; try { application = JmeApplication.prepareToStart(); } catch (final Throwable e) { printError(e); System.exit(-1); return; } InitializeManager.register(ClasspathManager.class); InitializeManager.register(ResourceManager.class); InitializeManager.register(JavaFxImageManager.class); InitializeManager.register(FileIconManager.class); InitializeManager.register(WorkspaceManager.class); InitializeManager.register(PluginManager.class); InitializeManager.register(RemoteControlManager.class); InitializeManager.initialize(); new EditorThread(new ThreadGroup("LWJGL"), () -> startJmeApplication(application), "LWJGL Render").start(); } @FxThread private static void configureLogger() { // disable the standard logger java.util.logging.Logger.getLogger("").setLevel(Level.WARNING); // configure our logger LoggerLevel.DEBUG.setEnabled(Config.DEV_DEBUG); LoggerLevel.INFO.setEnabled(true); LoggerLevel.ERROR.setEnabled(true); LoggerLevel.WARNING.setEnabled(true); final Path logFolder = Config.getFolderForLog(); if (!Files.exists(logFolder)) { run(() -> createDirectories(logFolder)); } if (!LoggerLevel.DEBUG.isEnabled()) { LoggerManager.addListener(new FolderFileListener(logFolder)); } } /** * Start the new jME application. * * @param application the new jME application. */ @JmeThread private static void startJmeApplication(@NotNull final JmeToJFXApplication application) { final InitializationManager initializationManager = InitializationManager.getInstance(); initializationManager.onBeforeCreateJmeContext(); application.start(); final JmeContext context = application.getContext(); final Renderer renderer = context.getRenderer(); if (renderer == null) { final EditorConfig editorConfig = EditorConfig.getInstance(); editorConfig.set(PREF_OPEN_GL, OpenGLVersion.GL_20); editorConfig.save(); } } /** * Create a new focus listener. * * @return the new focus listener. */ @FxThread private static @NotNull ChangeListener<Boolean> makeFocusedListener() { return (observable, oldValue, newValue) -> { final JmeApplication jmeApplication = JmeApplication.getInstance(); final Stage stage = EditorUtil.getFxStage(); if (newValue || stage.isFocused()) { jmeApplication.setPaused(false); return; } final EditorConfig editorConfig = EditorConfig.getInstance(); if (!editorConfig.getBoolean(PREF_STOP_RENDER_ON_LOST_FOCUS, PREF_DEFAULT_STOP_RENDER_ON_LOST_FOCUS)) { jmeApplication.setPaused(false); return; } final JfxApplication application = JfxApplication.getInstance(); final Window window = ArrayUtils.getInReadLock(application.openedWindows, windows -> windows.search(Window::isFocused)); jmeApplication.setPaused(window == null); }; } /** * Start. */ @FromAnyThread public static void start() { launch(); } @FromAnyThread private static void printError(@NotNull final Throwable throwable) { throwable.printStackTrace(); final String userHome = System.getProperty("user.home"); final String fileName = "jmonkeybuilder-error.log"; try (final PrintStream out = new PrintStream(newOutputStream(Paths.get(userHome, fileName)))) { throwable.printStackTrace(out); } catch (final IOException e) { e.printStackTrace(); } } /** * The list of opened windows. */ @NotNull private final ConcurrentArray<Window> openedWindows; /** * The JavaFX scene. */ @Nullable private volatile EditorFxScene scene; /** * The scene processor. */ @Nullable private volatile FrameTransferSceneProcessor sceneProcessor; /** * The stage. */ @Nullable private Stage stage; public JfxApplication() { EditorUtil.setJfxApplication(this); this.openedWindows = ArrayFactory.newConcurrentStampedLockArray(Window.class); } /** * Request focus of this window. */ public void requestFocus() { notNull(stage).requestFocus(); } /** * Add the new opened window. * * @param window the new opened window. */ @FxThread public void addWindow(@NotNull final Window window) { window.focusedProperty().addListener(makeFocusedListener()); ArrayUtils.runInWriteLock(openedWindows, window, Collection::add); } /** * Remove the opened window. * * @param window the opened window. */ @FxThread public void removeWindow(@NotNull final Window window) { ArrayUtils.runInWriteLock(openedWindows, window, Array::slowRemove); } /** * Gets the last opened window. * * @return the last opened window. */ @FxThread public @NotNull Window getLastWindow() { return notNull(ArrayUtils.getInReadLock(openedWindows, Array::last)); } @Override @FxThread public void start(final Stage stage) throws Exception { JfxApplication.instance = this; this.stage = stage; addWindow(stage); try { // initialize javaFX events in javaFX thread. ArrayFactory.asArray(ComboBoxBase.ON_SHOWN); final ResourceManager resourceManager = ResourceManager.getInstance(); resourceManager.reload(); final InitializationManager initializationManager = InitializationManager.getInstance(); initializationManager.onBeforeCreateJavaFxContext(); final PluginManager pluginManager = PluginManager.getInstance(); pluginManager.handlePlugins(editorPlugin -> editorPlugin.register(CssRegistry.getInstance())); LogView.getInstance(); SvgImageLoaderFactory.install(); ImageIO.read(getClass().getResourceAsStream("/ui/icons/test/test.jpg")); final ObservableList<Image> icons = stage.getIcons(); icons.add(new Image("/ui/icons/app/256x256.png")); icons.add(new Image("/ui/icons/app/128x128.png")); icons.add(new Image("/ui/icons/app/96x96.png")); icons.add(new Image("/ui/icons/app/64x64.png")); icons.add(new Image("/ui/icons/app/48x48.png")); icons.add(new Image("/ui/icons/app/32x32.png")); icons.add(new Image("/ui/icons/app/24x24.png")); icons.add(new Image("/ui/icons/app/16x16.png")); final EditorConfig config = EditorConfig.getInstance(); stage.initStyle(StageStyle.DECORATED); stage.setMinHeight(600); stage.setMinWidth(800); stage.setWidth(config.getScreenWidth()); stage.setHeight(config.getScreenHeight()); stage.setMaximized(config.isMaximized()); stage.setTitle(Config.TITLE); stage.show(); if (!stage.isMaximized()) { stage.centerOnScreen(); } stage.widthProperty().addListener((observable, oldValue, newValue) -> { if (stage.isMaximized()) return; config.setScreenWidth(newValue.intValue()); }); stage.heightProperty().addListener((observable, oldValue, newValue) -> { if (stage.isMaximized()) return; config.setScreenHeight(newValue.intValue()); }); stage.maximizedProperty() .addListener((observable, oldValue, newValue) -> config.setMaximized(newValue)); buildScene(); } catch (final Throwable e) { LOGGER.error(this, e); throw e; } } @Override @FxThread public void stop() throws Exception { super.stop(); onExit(); } /** * On exit. */ @FxThread protected void onExit() { GAnalytics.forceSendEvent(GAEvent.Category.APPLICATION, GAEvent.Action.APPLICATION_CLOSED, GAEvent.Label.THE_EDITOR_APP_WAS_CLOSED); final EditorConfig config = EditorConfig.getInstance(); config.save(); final JmeThreadExecutor executor = JmeThreadExecutor.getInstance(); executor.addToExecute(() -> { final JmeApplication jmeApplication = JmeApplication.getInstance(); jmeApplication.destroy(); }); GAnalytics.waitForSend(); } /** * Build the scene. */ @FxThread private void buildScene() { this.scene = EditorFxSceneBuilder.build(notNull(stage)); final InitializationManager initializationManager = InitializationManager.getInstance(); initializationManager.onAfterCreateJavaFxContext(); final PluginManager pluginManager = PluginManager.getInstance(); pluginManager.handlePlugins(editorPlugin -> { editorPlugin.register(FileCreatorRegistry.getInstance()); editorPlugin.register(EditorRegistry.getInstance()); editorPlugin.register(FileIconManager.getInstance()); editorPlugin.register(FileConverterRegistry.getInstance()); editorPlugin.register(AssetTreeContextMenuFillerRegistry.getInstance()); editorPlugin.register(TreeNodeFactoryRegistry.getInstance()); editorPlugin.register(PropertyBuilderRegistry.getInstance()); editorPlugin.register(FilePreviewFactoryRegistry.getInstance()); editorPlugin.register(SettingsProviderRegistry.getInstance()); }); final EditorFxScene scene = getScene(); final JmeApplication jmeApplication = JmeApplication.getInstance(); final JmeThreadExecutor executor = JmeThreadExecutor.getInstance(); executor.addToExecute(() -> createSceneProcessor(scene, jmeApplication)); JmeFilePreviewManager.getInstance(); GAnalytics.forceSendEvent(GAEvent.Category.APPLICATION, GAEvent.Action.APPLICATION_LAUNCHED, GAEvent.Label.THE_EDITOR_APP_WAS_LAUNCHED); final ExecutorManager executorManager = ExecutorManager.getInstance(); executorManager.addBackgroundTask(new CheckNewVersionTask()); final EditorConfig editorConfig = EditorConfig.getInstance(); if (editorConfig.isAnalyticsQuestion()) { return; } editorConfig.set(PREF_ANALYTICS_GOOGLE, false); editorConfig.save(); Platform.runLater(() -> { final Stage stage = notNull(getStage()); final ConfirmDialog confirmDialog = new ConfirmDialog(result -> { editorConfig.setAnalyticsQuestion(true); editorConfig.set(PREF_ANALYTICS_GOOGLE, Boolean.TRUE.equals(result)); editorConfig.save(); }, Messages.ANALYTICS_CONFIRM_DIALOG_MESSAGE); confirmDialog.show(stage); }); } @FxThread private void createSceneProcessor(@NotNull final EditorFxScene scene, @NotNull final JmeApplication jmeApplication) { final FrameTransferSceneProcessor sceneProcessor = bind(jmeApplication, scene.getCanvas(), jmeApplication.getViewPort()); sceneProcessor.setEnabled(false); sceneProcessor.setTransferMode(ON_CHANGES); this.sceneProcessor = sceneProcessor; final Stage stage = notNull(getStage()); stage.focusedProperty().addListener(makeFocusedListener()); Platform.runLater(scene::notifyFinishBuild); } /** * Get the current JavaFX scene. * * @return the JavaFX scene. */ @FromAnyThread public @NotNull EditorFxScene getScene() { return notNull(scene, "Scene can't be null."); } /** * Get the current stage of JavaFX. * * @return the current stage. */ @FromAnyThread public @NotNull Stage getStage() { return notNull(stage); } /** * Get the current scene processor of this application. * * @return the scene processor. */ @FromAnyThread public @NotNull FrameTransferSceneProcessor getSceneProcessor() { return notNull(sceneProcessor, "Scene processor can't be null."); } }
logger.
src/main/java/com/ss/editor/JfxApplication.java
logger.
Java
apache-2.0
92685ab4a8330651c7703a41d9809950a045bfc2
0
chriscm2006/ChrisLogger
package com.chriscm.clog; import android.util.Log; import java.util.HashMap; import static com.chriscm.clog.Utils.*; /** * Created by chrismcmeeking on 3/8/16. * * A static class API that can be used rather than creating your own logger instances. */ public class CLog { static String DEFAULT_LOG_TAG = null; static boolean RELEASE_MODE = true; static boolean DEBUG_MODE = false; /** * The logger must be initialized before any use. This allows for customizing behavior * between release and debug modes, without actually changing your build configuration. * Making for easier testing, and forcing release mode if you wish. * @param defaultTag The flag that will be used when in release mode for all loggers. * @param debugMode True if you're in debug mode. Just use BuildConfig.DEBUG. */ public static void initialize(final String defaultTag, final boolean debugMode) { RELEASE_MODE = !debugMode; DEBUG_MODE = debugMode; DEFAULT_LOG_TAG = defaultTag; String mode = debugMode ? "debug" : "release"; Log.i(defaultTag, "CLog initialized and in " + mode + " mode."); } static HashMap<Class <?>, Logger> mLoggers = new HashMap<>(); static Logger mDefaultLogger = new Logger(); /** * Convenience method, log to verbose log level. If escalated, will log to info. * @param message The message to be logged. */ public static void v(final String message) { println(message, Logger.LogLevel.VERBOSE); } /** * Convenience method, log to debug level. If escalated, will log to info. * @param message The message to be logged. */ public static void d(final String message) { println(message, Logger.LogLevel.DEBUG); } /** * Convenience method, log to info level. Doesn't escalate. * @param message The message to be logged. */ public static void i(final String message) { println(message, Logger.LogLevel.INFO); } /** * Convenience method, log to warning log level. Doesn't escalate. * @param message The message to be logged. */ public static void w(final String message) { println(message, Logger.LogLevel.WARN); } /** * Convenience method, log to error log level. Doesn't escalate. * @param message The message to be logged. */ public static void e(final String message) { println(message, Logger.LogLevel.ERROR); } /** * Convenience method, log to assert log level. Doesn't escalate. * @param message The message to be logged. */ public static void wtf(final String message) { println(message, Logger.LogLevel.ASSERT); } /** * Prints the given message to the given log level. The input level may not be the * same as the output level. Messages below the info level can be escalated up to * the info log level. * @param message The message to be logged. * @param logLevel The target log level. */ public static void println(final String message, final Logger.LogLevel logLevel) { try { String className = getFirstStackTraceElementNotInPackage().getClassName(); getLogger(Class.forName(className)).println(logLevel, message); } catch (Exception stackTraceElementNotFound) { mDefaultLogger.println(logLevel, message); } } /** * Get the logger for a class object. Not all Logger instance methods have a * static convenience method. So this is required for some actions. * @param clazz The class you want the logger for. * @return The logger associated with that class. */ public static Logger getLogger(Class <?> clazz) { if (!mLoggers.containsKey(clazz)) { mLoggers.put(clazz, new Logger()); } return mLoggers.get(clazz); } /** * Sets the include function names tag for all active loggers. * Also sets the static default value so any future constructed * loggers will have the same value for this tag. * @param value Set to true to include the function name in log tags */ public static void setIncludeFunctionNames(final boolean value) { for (Logger logger : mLoggers.values()) { logger.setTagIncludeFunctionName(value); } Logger.DEFAULT_INCLUDE_FUNCTION_NAME = value; } /** * Sets the include line number tag for all active loggers. * Also sets the static default value so any future constructed * loggers will have the same value for this tag. * @param value Set to true to include line numbers in log tags. */ public static void setIncludeLineNumber(final boolean value) { for (Logger logger : mLoggers.values()) { logger.setTagIncludeLineNumber(value); } Logger.DEFAULT_INCLUDE_LINE_NUMBER = value; } }
clog/src/main/java/com/chriscm/clog/CLog.java
package com.chriscm.clog; import java.util.HashMap; import static com.chriscm.clog.Utils.*; /** * Created by chrismcmeeking on 3/8/16. * * A static class API that can be used rather than creating your own logger instances. */ public class CLog { static String DEFAULT_LOG_TAG = null; static boolean RELEASE_MODE = true; static boolean DEBUG_MODE = false; /** * The logger must be initialized before any use. This allows for customizing behavior * between release and debug modes, without actually changing your build configuration. * Making for easier testing, and forcing release mode if you wish. * @param defaultTag The flag that will be used when in release mode for all loggers. * @param debugMode True if you're in debug mode. Just use BuildConfig.DEBUG. */ public static void initialize(final String defaultTag, final boolean debugMode) { RELEASE_MODE = !debugMode; DEBUG_MODE = debugMode; DEFAULT_LOG_TAG = defaultTag; } static HashMap<Class <?>, Logger> mLoggers = new HashMap<>(); static Logger mDefaultLogger = new Logger(); /** * Convenience method, log to verbose log level. If escalated, will log to info. * @param message The message to be logged. */ public static void v(final String message) { println(message, Logger.LogLevel.VERBOSE); } /** * Convenience method, log to debug level. If escalated, will log to info. * @param message The message to be logged. */ public static void d(final String message) { println(message, Logger.LogLevel.DEBUG); } /** * Convenience method, log to info level. Doesn't escalate. * @param message The message to be logged. */ public static void i(final String message) { println(message, Logger.LogLevel.INFO); } /** * Convenience method, log to warning log level. Doesn't escalate. * @param message The message to be logged. */ public static void w(final String message) { println(message, Logger.LogLevel.WARN); } /** * Convenience method, log to error log level. Doesn't escalate. * @param message The message to be logged. */ public static void e(final String message) { println(message, Logger.LogLevel.ERROR); } /** * Convenience method, log to assert log level. Doesn't escalate. * @param message The message to be logged. */ public static void wtf(final String message) { println(message, Logger.LogLevel.ASSERT); } /** * Prints the given message to the given log level. The input level may not be the * same as the output level. Messages below the info level can be escalated up to * the info log level. * @param message The message to be logged. * @param logLevel The target log level. */ public static void println(final String message, final Logger.LogLevel logLevel) { try { String className = getFirstStackTraceElementNotInPackage().getClassName(); getLogger(Class.forName(className)).println(logLevel, message); } catch (Exception stackTraceElementNotFound) { mDefaultLogger.println(logLevel, message); } } /** * Get the logger for a class object. Not all Logger instance methods have a * static convenience method. So this is required for some actions. * @param clazz The class you want the logger for. * @return The logger associated with that class. */ public static Logger getLogger(Class <?> clazz) { if (!mLoggers.containsKey(clazz)) { mLoggers.put(clazz, new Logger()); } return mLoggers.get(clazz); } /** * Sets the include function names tag for all active loggers. * Also sets the static default value so any future constructed * loggers will have the same value for this tag. * @param value Set to true to include the function name in log tags */ public static void setIncludeFunctionNames(final boolean value) { for (Logger logger : mLoggers.values()) { logger.setTagIncludeFunctionName(value); } Logger.DEFAULT_INCLUDE_FUNCTION_NAME = value; } /** * Sets the include line number tag for all active loggers. * Also sets the static default value so any future constructed * loggers will have the same value for this tag. * @param value Set to true to include line numbers in log tags. */ public static void setIncludeLineNumber(final boolean value) { for (Logger logger : mLoggers.values()) { logger.setTagIncludeLineNumber(value); } Logger.DEFAULT_INCLUDE_LINE_NUMBER = value; } }
Added a simple log message so we now how clog is initialized.
clog/src/main/java/com/chriscm/clog/CLog.java
Added a simple log message so we now how clog is initialized.
Java
apache-2.0
60a6f640ee1b94a080255fa8ee7996e5ed63f775
0
speedment/speedment,speedment/speedment
/** * * Copyright (c) 2006-2017, Speedment, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); You may not * use this file except in compliance with the License. You may obtain a copy of * the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.speedment.runtime.core.internal.db.postgresql; import com.speedment.runtime.config.Column; import com.speedment.runtime.core.db.JavaTypeMap; import com.speedment.runtime.core.db.metadata.ColumnMetaData; import com.speedment.runtime.core.internal.db.AbstractDbmsMetadataHandler; import java.sql.Blob; import java.sql.SQLException; import java.sql.Timestamp; import java.util.Optional; /** * Created by fdirlikl on 11/13/2015. * * @author Fatih Dirlikli * @author Emil Forslund */ public final class PostgresqlDbmsMetadataHandler extends AbstractDbmsMetadataHandler { @Override protected JavaTypeMap newJavaTypeMap() { final JavaTypeMap javaTypeMap = super.newJavaTypeMap(); javaTypeMap.put("bytea", Blob.class); // https://www.postgresql.org/docs/9.2/static/infoschema-datatypes.html javaTypeMap.put("cardinal_number", Integer.class); javaTypeMap.put("character_data", String.class); javaTypeMap.put("sql_identifier", String.class); javaTypeMap.put("time_stamp", Timestamp.class); javaTypeMap.put("yes_or_no", String.class); javaTypeMap.put("json", String.class); javaTypeMap.put("jsonb", String.class); javaTypeMap.addRule((sqlTypeMapping, md) -> { // Map a BIT(1) to boolean if ("BIT".equalsIgnoreCase(md.getTypeName()) && md.getColumnSize() == 1) { return Optional.of(Boolean.class); } else return Optional.empty(); }); javaTypeMap.addRule((sqlTypeMapping, md) -> { if ("year".equalsIgnoreCase(md.getTypeName()) && md.getDataType() == 2001) { return Optional.of(Integer.class); } else return Optional.empty(); }); return javaTypeMap; } @Override protected void setAutoIncrement(Column column, ColumnMetaData md) throws SQLException { super.setAutoIncrement(column, md); final String defaultValue = md.getColumnDef(); if (defaultValue != null && defaultValue.startsWith("nextval(")) { column.mutator().setAutoIncrement(true); } } }
runtime-parent/runtime-core/src/main/java/com/speedment/runtime/core/internal/db/postgresql/PostgresqlDbmsMetadataHandler.java
/** * * Copyright (c) 2006-2017, Speedment, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); You may not * use this file except in compliance with the License. You may obtain a copy of * the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.speedment.runtime.core.internal.db.postgresql; import com.speedment.runtime.config.Column; import com.speedment.runtime.core.db.JavaTypeMap; import com.speedment.runtime.core.db.metadata.ColumnMetaData; import com.speedment.runtime.core.internal.db.AbstractDbmsMetadataHandler; import java.sql.Blob; import java.sql.SQLException; import java.sql.Timestamp; import java.util.Optional; /** * Created by fdirlikl on 11/13/2015. * * @author Fatih Dirlikli * @author Emil Forslund */ public final class PostgresqlDbmsMetadataHandler extends AbstractDbmsMetadataHandler { @Override protected JavaTypeMap newJavaTypeMap() { final JavaTypeMap javaTypeMap = super.newJavaTypeMap(); javaTypeMap.put("bytea", Blob.class); // https://www.postgresql.org/docs/9.2/static/infoschema-datatypes.html javaTypeMap.put("cardinal_number", Integer.class); javaTypeMap.put("character_data", String.class); javaTypeMap.put("sql_identifier", String.class); javaTypeMap.put("time_stamp", Timestamp.class); javaTypeMap.put("yes_or_no", String.class); javaTypeMap.put("JSON", String.class); javaTypeMap.addRule((sqlTypeMapping, md) -> { // Map a BIT(1) to boolean if ("BIT".equalsIgnoreCase(md.getTypeName()) && md.getColumnSize() == 1) { return Optional.of(Boolean.class); } else return Optional.empty(); }); javaTypeMap.addRule((sqlTypeMapping, md) -> { if ("year".equalsIgnoreCase(md.getTypeName()) && md.getDataType() == 2001) { return Optional.of(Integer.class); } else return Optional.empty(); }); return javaTypeMap; } @Override protected void setAutoIncrement(Column column, ColumnMetaData md) throws SQLException { super.setAutoIncrement(column, md); final String defaultValue = md.getColumnDef(); if (defaultValue != null && defaultValue.startsWith("nextval(")) { column.mutator().setAutoIncrement(true); } } }
postgres: Make PostgreSQL recognize JSON and JSONB types, Fix #532
runtime-parent/runtime-core/src/main/java/com/speedment/runtime/core/internal/db/postgresql/PostgresqlDbmsMetadataHandler.java
postgres: Make PostgreSQL recognize JSON and JSONB types, Fix #532
Java
apache-2.0
8d65a94ef46e44f4b46db1cc477efc377c8be4d5
0
opencb/opencga,opencb/opencga,opencb/opencga,j-coll/opencga,j-coll/opencga,j-coll/opencga,opencb/opencga,opencb/opencga,j-coll/opencga,opencb/opencga,j-coll/opencga,j-coll/opencga
/* * Copyright 2015-2017 OpenCB * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.opencb.opencga.storage.core.variant.search; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectReader; import com.fasterxml.jackson.databind.ObjectWriter; import htsjdk.variant.vcf.VCFConstants; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.StringUtils; import org.opencb.biodata.models.variant.StudyEntry; import org.opencb.biodata.models.variant.Variant; import org.opencb.biodata.models.variant.annotation.ConsequenceTypeMappings; import org.opencb.biodata.models.variant.avro.*; import org.opencb.biodata.models.variant.stats.VariantStats; import org.opencb.commons.datastore.core.ComplexTypeConverter; import org.opencb.commons.utils.CollectionUtils; import org.opencb.commons.utils.ListUtils; import org.opencb.opencga.core.common.ArrayUtils; import org.opencb.opencga.storage.core.variant.adaptors.VariantField; import org.opencb.opencga.storage.core.variant.annotation.converters.VariantTraitAssociationToEvidenceEntryConverter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.*; import static org.opencb.opencga.storage.core.variant.adaptors.VariantField.AdditionalAttributes.GROUP_NAME; import static org.opencb.opencga.storage.core.variant.adaptors.VariantField.AdditionalAttributes.RELEASE; /** * Created by imedina on 14/11/16. */ public class VariantSearchToVariantConverter implements ComplexTypeConverter<Variant, VariantSearchModel> { public static final double MISSING_VALUE = -100.0; private static final String LIST_SEP = "___"; private static final String FIELD_SEP = " -- "; private Logger logger = LoggerFactory.getLogger(VariantSearchToVariantConverter.class); private final VariantTraitAssociationToEvidenceEntryConverter evidenceEntryConverter; private Set<VariantField> includeFields; public VariantSearchToVariantConverter() { evidenceEntryConverter = new VariantTraitAssociationToEvidenceEntryConverter(); } public VariantSearchToVariantConverter(Set<VariantField> includeFields) { this(); this.includeFields = includeFields; } /** * Conversion: from storage type to data model. * * @param variantSearchModel Storage type object * @return Data model object */ @Override public Variant convertToDataModelType(VariantSearchModel variantSearchModel) { // set chromosome, start, end, ref, alt from ID Variant variant = new Variant(variantSearchModel.getId()); // set ID, chromosome, start, end, ref, alt, type variant.setId(variantSearchModel.getVariantId()); // set variant type if (StringUtils.isNotEmpty(variantSearchModel.getType())) { variant.setType(VariantType.valueOf(variantSearchModel.getType())); } // Study management Map<String, StudyEntry> studyEntryMap = new HashMap<>(); if (variantSearchModel.getStudies() != null && CollectionUtils.isNotEmpty(variantSearchModel.getStudies())) { List<StudyEntry> studies = new ArrayList<>(); variantSearchModel.getStudies().forEach(studyId -> { StudyEntry entry = new StudyEntry(studyId); studies.add(entry); studyEntryMap.put(studyId, entry); }); variant.setStudies(studies); } // Genotypes and sample data and format if (MapUtils.isNotEmpty(variantSearchModel.getSampleFormat())) { for (String studyId: studyEntryMap.keySet()) { String stringToList; String suffix = VariantSearchUtils.FIELD_SEPARATOR + studyId + VariantSearchUtils.FIELD_SEPARATOR; StudyEntry studyEntry = studyEntryMap.get(studyId); // Format stringToList = variantSearchModel.getSampleFormat().get("sampleFormat" + suffix + "format"); if (StringUtils.isNotEmpty(stringToList)) { studyEntry.setFormat(Arrays.asList(StringUtils.splitByWholeSeparatorPreserveAllTokens(stringToList, LIST_SEP))); } // Sample Data management stringToList = variantSearchModel.getSampleFormat().get("sampleFormat" + suffix + "sampleName"); if (StringUtils.isNotEmpty(stringToList)) { String[] sampleNames = StringUtils.splitByWholeSeparatorPreserveAllTokens(stringToList, LIST_SEP); List<List<String>> sampleData = new ArrayList<>(); Map<String, Integer> samplePosition = new HashMap<>(); int pos = 0; for (String sampleName: sampleNames) { suffix = VariantSearchUtils.FIELD_SEPARATOR + studyId + VariantSearchUtils.FIELD_SEPARATOR + sampleName; stringToList = variantSearchModel.getSampleFormat().get("sampleFormat" + suffix); if (StringUtils.isNotEmpty(stringToList)) { sampleData.add(Arrays.asList(StringUtils.splitByWholeSeparatorPreserveAllTokens(stringToList, LIST_SEP))); samplePosition.put(sampleName, pos++); } // else { // logger.error("Error converting samplesFormat, sample '{}' is missing or empty, value: '{}'", // sampleName, stringToList); // } } if (ListUtils.isNotEmpty(sampleData)) { studyEntry.setSamplesData(sampleData); studyEntry.setSamplesPosition(samplePosition); } } } } // File info management if (MapUtils.isNotEmpty(variantSearchModel.getFileInfo())) { ObjectReader reader = new ObjectMapper().reader(HashMap.class); for (String key: variantSearchModel.getFileInfo().keySet()) { // key consists of 'fileInfo' + "__" + studyId + "__" + fileId String[] fields = StringUtils.splitByWholeSeparator(key, VariantSearchUtils.FIELD_SEPARATOR); FileEntry fileEntry = new FileEntry(fields[2], null, new HashMap<>()); try { // We obtain the original call Map<String, String> fileInfoAttributes = reader.readValue(variantSearchModel.getFileInfo().get(key)); if (MapUtils.isNotEmpty(fileInfoAttributes)) { fileEntry.setCall(fileInfoAttributes.get("fileCall")); fileInfoAttributes.remove("fileCall"); fileEntry.setAttributes(fileInfoAttributes); } } catch (IOException e) { logger.error("Error converting fileInfo from variant search model: {}", e.getMessage()); } finally { variant.getStudy(fields[1]).getFiles().add(fileEntry); } } } // Stats management if (MapUtils.isNotEmpty(variantSearchModel.getStats())) { for (String key: variantSearchModel.getStats().keySet()) { // key consists of 'stats' + "__" + studyId + "__" + cohort String[] fields = StringUtils.splitByWholeSeparator(key, VariantSearchUtils.FIELD_SEPARATOR); if (studyEntryMap.containsKey(fields[1])) { VariantStats variantStats = new VariantStats(); variantStats.setRefAlleleFreq(1 - variantSearchModel.getStats().get(key)); variantStats.setAltAlleleFreq(variantSearchModel.getStats().get(key)); variantStats.setMaf(Math.min(variantSearchModel.getStats().get(key), 1 - variantSearchModel.getStats().get(key))); studyEntryMap.get(fields[1]).setStats(fields[2], variantStats); } } } // process annotation variant.setAnnotation(getVariantAnnotation(variantSearchModel, variant)); return variant; } public VariantAnnotation getVariantAnnotation(VariantSearchModel variantSearchModel, Variant variant) { if (includeFields != null && !includeFields.contains(VariantField.ANNOTATION)) { return null; } VariantAnnotation variantAnnotation = new VariantAnnotation(); variantAnnotation.setChromosome(variant.getChromosome()); variantAnnotation.setStart(variant.getStart()); variantAnnotation.setEnd(variant.getEnd()); variantAnnotation.setAlternate(variant.getAlternate()); variantAnnotation.setReference(variant.getReference()); // Set 'release' if it was not missing if (variantSearchModel.getRelease() > 0) { Map<String, String> attribute = new HashMap<>(); attribute.put(RELEASE.key(), String.valueOf(variantSearchModel.getRelease())); variantAnnotation.setAdditionalAttributes(new HashMap<>()); variantAnnotation.getAdditionalAttributes().put(GROUP_NAME.key(), new AdditionalAttribute(attribute)); } // Xrefs List<Xref> xrefs = new ArrayList<>(); if (ListUtils.isNotEmpty(variantSearchModel.getXrefs())) { for (String xref: variantSearchModel.getXrefs()) { if (xref == null) { continue; } if (xref.startsWith("rs")) { xrefs.add(new Xref(xref, "dbSNP")); continue; } if (xref.startsWith("ENSG")) { xrefs.add(new Xref(xref, "ensemblGene")); continue; } if (xref.startsWith("ENST")) { xrefs.add(new Xref(xref, "ensemblTranscript")); } } } variantAnnotation.setXrefs(xrefs); // Init the consequence type map with protein variant annotation // and set displayConsequenceType, hgvs, cytobands and repeats from 'other' field Map<String, ConsequenceType> consequenceTypeMap = new HashMap<>(); variantAnnotation.setHgvs(new ArrayList<>()); variantAnnotation.setCytoband(new ArrayList<>()); variantAnnotation.setRepeat(new ArrayList<>()); for (String other : variantSearchModel.getOther()) { // Sanity check if (StringUtils.isEmpty(other)) { continue; } String[] fields = StringUtils.splitByWholeSeparatorPreserveAllTokens(other, FIELD_SEP); switch (fields[0]) { case "DCT": variantAnnotation.setDisplayConsequenceType(fields[1]); break; case "HGVS": variantAnnotation.getHgvs().add(fields[1]); break; case "CB": Cytoband cytoband = Cytoband.newBuilder() .setChromosome(variant.getChromosome()) .setName(fields[1]) .setStain(fields[2]) .setStart(Integer.parseInt(fields[3])).setEnd(Integer.parseInt(fields[4])) .build(); variantAnnotation.getCytoband().add(cytoband); break; case "RP": Repeat repeat = Repeat.newBuilder() .setId(fields[1]) .setSource(fields[2]) .setChromosome(variant.getChromosome()) .setStart(Integer.parseInt(fields[5])) .setEnd(Integer.parseInt(fields[6])) .setCopyNumber(parseFloat(fields[3], null)) .setPercentageMatch(parseFloat(fields[4], null)) .setPeriod(null) .setConsensusSize(null) .setScore(null) .setSequence(null) .build(); variantAnnotation.getRepeat().add(repeat); break; case "TRANS": // Create consequence type from transcript info: // 1 2 3 4 5 6 // transcriptId -- biotype -- annotationFlags -- cdnaPosition -- cdsPosition -- codon // 7 8 9 10 11 // -- uniprotAccession -- uniprotAccession -- uniprotVariantId -- position -- aaChange // 12 13 14 15 // siftScore -- siftDescr -- poliphenScore -- poliphenDescr ConsequenceType consequenceType = new ConsequenceType(); if (fields.length > 2) { consequenceType.setEnsemblTranscriptId(fields[1]); consequenceType.setBiotype(fields[2]); } if (fields.length > 3) { if (fields[3].length() > 0) { consequenceType.setTranscriptAnnotationFlags(Arrays.asList(fields[3].split(","))); } } if (fields.length > 4) { consequenceType.setCdnaPosition(Integer.parseInt(fields[4])); consequenceType.setCdsPosition(Integer.parseInt(fields[5])); if (fields.length > 6) { // Sometimes, codon (i.e., split at 5) is null, check it! consequenceType.setCodon(fields[6]); } } if (fields.length > 7) { // Create, init and add protein variant annotation to the consequence type ProteinVariantAnnotation protVarAnnotation = new ProteinVariantAnnotation(); // Uniprot info protVarAnnotation.setUniprotAccession(fields[7]); protVarAnnotation.setUniprotName(fields[8]); protVarAnnotation.setUniprotVariantId(fields[9]); if (StringUtils.isNotEmpty(fields[10])) { try { protVarAnnotation.setPosition(Integer.parseInt(fields[10])); } catch (NumberFormatException e) { logger.warn("Parsing position: " + e.getMessage()); } } if (StringUtils.isNotEmpty(fields[11]) && fields[11].contains("/")) { String[] refAlt = fields[11].split("/"); protVarAnnotation.setReference(refAlt[0]); protVarAnnotation.setAlternate(refAlt[1]); } // Sift score List<Score> scores = new ArrayList<>(2); if (fields.length > 12 && (StringUtils.isNotEmpty(fields[12]) || StringUtils.isNotEmpty(fields[13]))) { Score score = new Score(); score.setSource("sift"); if (StringUtils.isNotEmpty(fields[12])) { score.setScore(parseDouble(fields[12], null, "Exception parsing Sift score")); } score.setDescription(fields[13]); scores.add(score); } // Polyphen score if (fields.length > 14 && (StringUtils.isNotEmpty(fields[14]) || StringUtils.isNotEmpty(fields[15]))) { Score score = new Score(); score.setSource("polyphen"); if (StringUtils.isNotEmpty(fields[14])) { score.setScore(parseDouble(fields[14], null, "Exception parsing Polyphen score")); } score.setDescription(fields[15]); scores.add(score); } protVarAnnotation.setSubstitutionScores(scores); // Finally, set protein variant annotation in consequence type consequenceType.setProteinVariantAnnotation(protVarAnnotation); } // The key is the ENST id consequenceTypeMap.put(fields[1], consequenceType); break; default: logger.warn("Unknown key in 'other' array in Solr: " + fields[0]); } } // consequence types String geneName = null; String ensGene = null; if (ListUtils.isNotEmpty(variantSearchModel.getGenes())) { for (String name : variantSearchModel.getGenes()) { if (!name.startsWith("ENS")) { geneName = name; } else if (name.startsWith("ENSG")) { ensGene = name; } else if (name.startsWith("ENST")) { ConsequenceType consequenceType = consequenceTypeMap.getOrDefault(name, null); if (consequenceType == null) { consequenceType = new ConsequenceType(); consequenceType.setEnsemblTranscriptId(name); consequenceTypeMap.put(name, consequenceType); logger.warn("No information found in Solr field 'other' for transcript '{}'", name); // throw new InternalError("Transcript '" + name + "' missing in schema field name 'other'"); } consequenceType.setGeneName(geneName); consequenceType.setEnsemblGeneId(ensGene); } } } // prepare protein substitution scores: sift and polyphen List<Score> scores; // ProteinVariantAnnotation proteinAnnotation = new ProteinVariantAnnotation(); // if (!ArrayUtils.equals(variantSearchModel.getSift(), MISSING_VALUE) // || !ArrayUtils.equals(variantSearchModel.getPolyphen(), MISSING_VALUE)) { // scores = new ArrayList<>(); // if (!ArrayUtils.equals(variantSearchModel.getSift(), MISSING_VALUE)) { // scores.add(new Score(variantSearchModel.getSift(), "sift", variantSearchModel.getSiftDesc())); // } // if (!ArrayUtils.equals(variantSearchModel.getPolyphen(), MISSING_VALUE)) { // scores.add(new Score(variantSearchModel.getPolyphen(), "polyphen", variantSearchModel.getPolyphenDesc())); // } // proteinAnnotation.setSubstitutionScores(scores); // } // and finally, update the SO acc. for each conseq. type and setProteinVariantAnnotation if SO accession is 1583 Set<Integer> geneRelatedSoTerms = new HashSet<>(); if (variantSearchModel.getGeneToSoAcc() != null) { for (String geneToSoAcc : variantSearchModel.getGeneToSoAcc()) { String[] fields = geneToSoAcc.split("_"); if (consequenceTypeMap.containsKey(fields[0])) { int soAcc = Integer.parseInt(fields[1]); geneRelatedSoTerms.add(soAcc); // we memorise the SO term for next block SequenceOntologyTerm sequenceOntologyTerm = new SequenceOntologyTerm(); sequenceOntologyTerm.setAccession("SO:" + String.format("%07d", soAcc)); sequenceOntologyTerm.setName(ConsequenceTypeMappings.accessionToTerm.get(soAcc)); if (consequenceTypeMap.get(fields[0]).getSequenceOntologyTerms() == null) { consequenceTypeMap.get(fields[0]).setSequenceOntologyTerms(new ArrayList<>()); } consequenceTypeMap.get(fields[0]).getSequenceOntologyTerms().add(sequenceOntologyTerm); // // only set protein for that conseq. type if annotated protein and SO acc is 1583 (missense_variant) // if (soAcc == 1583) { // consequenceTypeMap.get(fields[0]).setProteinVariantAnnotation(proteinAnnotation); // } } } } // We convert the Map into an array ArrayList<ConsequenceType> consequenceTypes = new ArrayList<>(consequenceTypeMap.values()); // Add non-gene related SO terms if (variantSearchModel.getSoAcc() != null) { for (Integer soAcc : variantSearchModel.getSoAcc()) { // let's process all non-gene related terms such as regulatory_region_variant or intergenic_variant if (!geneRelatedSoTerms.contains(soAcc)) { SequenceOntologyTerm sequenceOntologyTerm = new SequenceOntologyTerm(); sequenceOntologyTerm.setAccession("SO:" + String.format("%07d", soAcc)); sequenceOntologyTerm.setName(ConsequenceTypeMappings.accessionToTerm.get(soAcc)); ConsequenceType consequenceType = new ConsequenceType(); consequenceType.setEnsemblGeneId(""); consequenceType.setGeneName(""); consequenceType.setEnsemblTranscriptId(""); consequenceType.setSequenceOntologyTerms(Collections.singletonList(sequenceOntologyTerm)); consequenceTypes.add(consequenceType); } } } // and update the variant annotation with the consequence types variantAnnotation.setConsequenceTypes(consequenceTypes); // set populations List<PopulationFrequency> populationFrequencies = new ArrayList<>(); if (variantSearchModel.getPopFreq() != null && variantSearchModel.getPopFreq().size() > 0) { for (String key : variantSearchModel.getPopFreq().keySet()) { PopulationFrequency populationFrequency = new PopulationFrequency(); String[] fields = StringUtils.splitByWholeSeparator(key, VariantSearchUtils.FIELD_SEPARATOR); populationFrequency.setStudy(fields[1]); populationFrequency.setPopulation(fields[2]); populationFrequency.setRefAlleleFreq(1 - variantSearchModel.getPopFreq().get(key)); populationFrequency.setAltAlleleFreq(variantSearchModel.getPopFreq().get(key)); populationFrequencies.add(populationFrequency); } } variantAnnotation.setPopulationFrequencies(populationFrequencies); // Set conservations scores scores = new ArrayList<>(); if (!ArrayUtils.equals(variantSearchModel.getPhylop(), MISSING_VALUE)) { scores.add(new Score(variantSearchModel.getPhylop(), "phylop", "")); } if (!ArrayUtils.equals(variantSearchModel.getPhastCons(), MISSING_VALUE)) { scores.add(new Score(variantSearchModel.getPhastCons(), "phastCons", "")); } if (!ArrayUtils.equals(variantSearchModel.getGerp(), MISSING_VALUE)) { scores.add(new Score(variantSearchModel.getGerp(), "gerp", "")); } variantAnnotation.setConservation(scores); // Set CADD scores scores = new ArrayList<>(); if (!ArrayUtils.equals(variantSearchModel.getCaddRaw(), MISSING_VALUE)) { scores.add(new Score(variantSearchModel.getCaddRaw(), "cadd_raw", "")); } if (!ArrayUtils.equals(variantSearchModel.getCaddScaled(), MISSING_VALUE)) { scores.add(new Score(variantSearchModel.getCaddScaled(), "cadd_scaled", "")); } variantAnnotation.setFunctionalScore(scores); // set HPO, ClinVar and Cosmic if (variantSearchModel.getTraits() != null) { Map<String, ClinVar> clinVarMap = new HashMap<>(); List<ClinVar> clinVarList = new ArrayList<>(); List<Cosmic> cosmicList = new ArrayList<>(); List<GeneTraitAssociation> geneTraitAssociationList = new ArrayList<>(); for (String trait : variantSearchModel.getTraits()) { String[] fields = StringUtils.splitByWholeSeparatorPreserveAllTokens(trait, FIELD_SEP); switch (fields[0]) { case "HP": // Gene trait: HP -- hpo -- id -- name GeneTraitAssociation geneTraitAssociation = new GeneTraitAssociation(); geneTraitAssociation.setHpo(fields[1]); geneTraitAssociation.setId(fields[2]); geneTraitAssociation.setName(fields[3]); geneTraitAssociationList.add(geneTraitAssociation); break; case "CV": // Variant trait: CV -- accession -- trait if (!clinVarMap.containsKey(fields[1])) { String clinicalSignificance = ""; if (fields.length > 3 && fields[3].length() > 3) { clinicalSignificance = fields[3].substring(3); } ClinVar clinVar = new ClinVar(fields[1], clinicalSignificance, new ArrayList<>(), new ArrayList<>(), ""); clinVarMap.put(fields[1], clinVar); clinVarList.add(clinVar); } clinVarMap.get(fields[1]).getTraits().add(fields[2]); break; case "CM": // Variant trait: CM -- mutation id -- primary histology -- histology subtype Cosmic cosmic = new Cosmic(); cosmic.setMutationId(fields[1]); cosmic.setPrimaryHistology(fields[2]); cosmic.setHistologySubtype(fields[3]); cosmicList.add(cosmic); break; case "KW": case "PD": // These are taken from consequence type non-indexed field break; default: { logger.warn("Unknown trait type: " + fields[0] + ", it should be HPO, ClinVar or Cosmic"); break; } } } // TODO to be removed in next versions VariantTraitAssociation variantTraitAssociation = new VariantTraitAssociation(); // This fills the old data model: variantTraitAssociation if (CollectionUtils.isNotEmpty(clinVarList)) { variantTraitAssociation.setClinvar(clinVarList); } if (CollectionUtils.isNotEmpty(cosmicList)) { variantTraitAssociation.setCosmic(cosmicList); } variantAnnotation.setVariantTraitAssociation(variantTraitAssociation); // This fills the new data model: traitAssociation List<EvidenceEntry> evidenceEntries = new ArrayList<>(); // Clinvar -> traitAssociation for (ClinVar clinvar: clinVarList) { evidenceEntries.add(evidenceEntryConverter.fromClinVar(clinvar)); } // Cosmic -> traitAssociation for (Cosmic cosmic: cosmicList) { evidenceEntries.add(evidenceEntryConverter.fromCosmic(cosmic)); } variantAnnotation.setTraitAssociation(evidenceEntries); // Set the gene disease annotation if (CollectionUtils.isNotEmpty(geneTraitAssociationList)) { variantAnnotation.setGeneTraitAssociation(geneTraitAssociationList); } } return variantAnnotation; } /** * Conversion: from data model to storage type. * * @param variant Data model object * @return Storage type object */ @Override public VariantSearchModel convertToStorageType(Variant variant) { VariantSearchModel variantSearchModel = new VariantSearchModel(); // Set general Variant attributes: id, dbSNP, chromosome, start, end, type variantSearchModel.setId(variant.toString()); // Internal unique ID e.g. 3:1000:AT:- variantSearchModel.setVariantId(variant.getId()); variantSearchModel.setChromosome(variant.getChromosome()); variantSearchModel.setStart(variant.getStart()); variantSearchModel.setEnd(variant.getEnd()); variantSearchModel.setType(variant.getType().toString()); // This field contains all possible IDs: id, dbSNP, names, genes, transcripts, protein, clinvar, hpo, ... // This will help when searching by variant id. This is added at the end of the method after collecting all IDs Set<String> xrefs = new HashSet<>(); xrefs.add(variantSearchModel.getId()); xrefs.add(variantSearchModel.getVariantId()); if (variant.getNames() != null && !variant.getNames().isEmpty()) { variant.getNames().forEach(name -> { if (name != null) { xrefs.add(name); } }); } // convert Study related information if (CollectionUtils.isNotEmpty(variant.getStudies())) { ObjectWriter writer = new ObjectMapper().writer(); for (StudyEntry studyEntry : variant.getStudies()) { String studyId = studyIdToSearchModel(studyEntry.getStudyId()); variantSearchModel.getStudies().add(studyId); // We store the cohort stats with the format stats_STUDY_COHORT = value, e.g. stats_1kg_phase3_ALL=0.02 if (studyEntry.getStats() != null && studyEntry.getStats().size() > 0) { Map<String, VariantStats> studyStats = studyEntry.getStats(); for (String key : studyStats.keySet()) { variantSearchModel.getStats().put("stats" + VariantSearchUtils.FIELD_SEPARATOR + studyId + VariantSearchUtils.FIELD_SEPARATOR + key, studyStats.get(key).getAltAlleleFreq()); } } // samples, genotypes and format fields conversion if (MapUtils.isNotEmpty(studyEntry.getSamplesPosition()) && ListUtils.isNotEmpty(studyEntry.getOrderedSamplesName())) { List<String> sampleNames = studyEntry.getOrderedSamplesName(); // sanity check, the number od sample names and sample data must be the same if (ListUtils.isNotEmpty(studyEntry.getSamplesData()) && sampleNames.size() == studyEntry.getSamplesData().size()) { String suffix = VariantSearchUtils.FIELD_SEPARATOR + studyId + VariantSearchUtils.FIELD_SEPARATOR; // Save sample formats in a map (after, to JSON string), including sample names and GT variantSearchModel.getSampleFormat().put("sampleFormat" + suffix + "sampleName", StringUtils.join(sampleNames, LIST_SEP)); // find the index position of DP in the FORMAT int dpIndexPos = -1; if (ListUtils.isNotEmpty(studyEntry.getFormat())) { variantSearchModel.getSampleFormat().put("sampleFormat" + suffix + "format", StringUtils.join(studyEntry.getFormat(), LIST_SEP)); // find the index position of DP in the FORMAT for (int i = 0; i < studyEntry.getFormat().size(); i++) { if ("DP".equalsIgnoreCase(studyEntry.getFormat().get(i))) { dpIndexPos = i; break; } } } for (int i = 0; i < sampleNames.size(); i++) { suffix = VariantSearchUtils.FIELD_SEPARATOR + studyId + VariantSearchUtils.FIELD_SEPARATOR + sampleNames.get(i); // Save genotype (gt) and depth (dp) where study and sample name as key variantSearchModel.getGt().put("gt" + suffix, studyEntry.getSampleData(i).get(0)); if (dpIndexPos != -1) { String dpValue = studyEntry.getSampleData(i).get(dpIndexPos); // Skip if empty if (!StringUtils.isEmpty(dpValue) && !dpValue.equals(VCFConstants.EMPTY_INFO_FIELD)) { try { variantSearchModel.getDp().put("dp" + suffix, Integer.valueOf(dpValue)); } catch (NumberFormatException e) { logger.error("Problem converting from variant to variant search when getting DP" + " value from sample {}: {}", sampleNames.get(i), e.getMessage()); } } } // Save formats for each sample (after, to JSON string) if (ListUtils.isNotEmpty(studyEntry.getSamplesData().get(i))) { variantSearchModel.getSampleFormat().put("sampleFormat" + suffix, StringUtils.join(studyEntry.getSamplesData().get(i), LIST_SEP)); } } } else { logger.error("Mismatch sizes: please, check your sample names, sample data and format array"); } } // QUAL, FILTER and file info fields management if (ListUtils.isNotEmpty(studyEntry.getFiles())) { for (FileEntry fileEntry: studyEntry.getFiles()) { // Call is stored in Solr fileInfo with key "fileCall" Map<String, String> fileInfoMap = new LinkedHashMap<>(); if (StringUtils.isNotEmpty(fileEntry.getCall())) { fileInfoMap.put("fileCall", fileEntry.getCall()); } // Info fields are stored in Solr fileInfo if (MapUtils.isNotEmpty(fileEntry.getAttributes())) { fileInfoMap.putAll(fileEntry.getAttributes()); // In addition, store QUAL and FILTER separately String qual = fileEntry.getAttributes().get(StudyEntry.QUAL); if (StringUtils.isNotEmpty(qual)) { variantSearchModel.getQual().put("qual" + VariantSearchUtils.FIELD_SEPARATOR + studyId + VariantSearchUtils.FIELD_SEPARATOR + fileEntry.getFileId(), Float.parseFloat(qual)); } String filter = fileEntry.getAttributes().get(StudyEntry.FILTER); if (StringUtils.isNotEmpty(filter)) { variantSearchModel.getFilter().put("filter" + VariantSearchUtils.FIELD_SEPARATOR + studyId + VariantSearchUtils.FIELD_SEPARATOR + fileEntry.getFileId(), filter); } } if (MapUtils.isNotEmpty(fileInfoMap)) { try { variantSearchModel.getFileInfo().put("fileInfo" + VariantSearchUtils.FIELD_SEPARATOR + studyId + VariantSearchUtils.FIELD_SEPARATOR + fileEntry.getFileId(), writer.writeValueAsString(fileInfoMap)); } catch (JsonProcessingException e) { logger.info("Error converting fileInfo for study {} and file {}", studyId, fileEntry.getFileId()); } } } } } } // We init all annotation numeric values to MISSING_VALUE, this fixes two different scenarios: // 1. No Variant Annotation has been found, probably because it is a SV longer than 100bp. // 2. There are some conservation or CADD scores missing variantSearchModel.setSift(MISSING_VALUE); variantSearchModel.setPolyphen(MISSING_VALUE); variantSearchModel.setPhastCons(MISSING_VALUE); variantSearchModel.setPhylop(MISSING_VALUE); variantSearchModel.setGerp(MISSING_VALUE); variantSearchModel.setCaddRaw(MISSING_VALUE); variantSearchModel.setCaddScaled(MISSING_VALUE); // Process Variant Annotation VariantAnnotation variantAnnotation = variant.getAnnotation(); if (variantAnnotation != null) { // This object will store all info and descriptions for full-text search Set<String> traits = new HashSet<>(); // Set release field int release = -1; // default value if missing is -1 if (variantAnnotation.getAdditionalAttributes() != null && variantAnnotation.getAdditionalAttributes().get(GROUP_NAME.key()) != null) { String releaseStr = variantAnnotation.getAdditionalAttributes().get(GROUP_NAME.key()).getAttribute().get(RELEASE.key()); // example: release = "2,3,4" if (StringUtils.isNotEmpty(releaseStr)) { releaseStr = releaseStr.split(",")[0]; if (StringUtils.isNumeric(releaseStr)) { release = Integer.parseInt(releaseStr); } } } variantSearchModel.setRelease(release); // Add cytoband names if (variantAnnotation.getCytoband() != null) { for (Cytoband cytoband : variantAnnotation.getCytoband()) { xrefs.add(cytoband.getChromosome() + cytoband.getName()); } } // Add all XRefs coming from the variant annotation if (variantAnnotation.getXrefs() != null && !variantAnnotation.getXrefs().isEmpty()) { variantAnnotation.getXrefs().forEach(xref -> { if (xref != null) { xrefs.add(xref.getId()); } }); } // Add all HGVS coming from the variant annotation if (ListUtils.isNotEmpty(variantAnnotation.getHgvs())) { xrefs.addAll(variantAnnotation.getHgvs()); } // Set Genes and Consequence Types and create Other list to insert transcript info (biotype, protein, ariant annotation,...) List<ConsequenceType> consequenceTypes = variantAnnotation.getConsequenceTypes(); List<String> other = new ArrayList<>(); if (consequenceTypes != null) { // This MUST be a LinkedHashMap to keep the order of the elements! Map<String, Set<String>> genes = new LinkedHashMap<>(); Set<Integer> soAccessions = new LinkedHashSet<>(); Set<String> geneToSOAccessions = new LinkedHashSet<>(); Set<String> biotypes = new LinkedHashSet<>(); for (ConsequenceType conseqType : consequenceTypes) { StringBuilder trans = new StringBuilder(); // Set genes and biotypes if exist if (StringUtils.isNotEmpty(conseqType.getGeneName())) { // One gene can contain several transcripts and therefore several Consequence Types if (!genes.containsKey(conseqType.getGeneName())) { genes.put(conseqType.getGeneName(), new LinkedHashSet<>()); } // DO NOT change the order of the following code genes.get(conseqType.getGeneName()).add(conseqType.getGeneName()); genes.get(conseqType.getGeneName()).add(conseqType.getEnsemblGeneId()); genes.get(conseqType.getGeneName()).add(conseqType.getEnsemblTranscriptId()); if (StringUtils.isNotEmpty(conseqType.getEnsemblTranscriptId())) { trans.append("TRANS").append(FIELD_SEP).append(conseqType.getEnsemblTranscriptId()); trans.append(FIELD_SEP).append(StringUtils.isEmpty(conseqType.getBiotype()) ? "" : conseqType.getBiotype()); trans.append(FIELD_SEP); if (ListUtils.isNotEmpty(conseqType.getTranscriptAnnotationFlags())) { trans.append(StringUtils.join(conseqType.getTranscriptAnnotationFlags(), ",")); } } xrefs.add(conseqType.getGeneName()); xrefs.add(conseqType.getEnsemblGeneId()); xrefs.add(conseqType.getEnsemblTranscriptId()); if (StringUtils.isNotEmpty(conseqType.getBiotype())) { biotypes.add(conseqType.getBiotype()); // Add the combination of Gene and Biotype, this will prevent variants to be returned when they overlap // two different genes where the overlapping gene has the wanted Biotype. geneToSOAccessions.add(conseqType.getGeneName() + "_" + conseqType.getBiotype()); geneToSOAccessions.add(conseqType.getEnsemblGeneId() + "_" + conseqType.getBiotype()); geneToSOAccessions.add(conseqType.getEnsemblTranscriptId() + "_" + conseqType.getBiotype()); } } // Remove 'SO:' prefix to Store SO Accessions as integers and also store the gene - SO acc relation for (SequenceOntologyTerm sequenceOntologyTerm : conseqType.getSequenceOntologyTerms()) { int soIdInt = Integer.parseInt(sequenceOntologyTerm.getAccession().substring(3)); soAccessions.add(soIdInt); if (StringUtils.isNotEmpty(conseqType.getGeneName())) { geneToSOAccessions.add(conseqType.getGeneName() + "_" + soIdInt); geneToSOAccessions.add(conseqType.getEnsemblGeneId() + "_" + soIdInt); geneToSOAccessions.add(conseqType.getEnsemblTranscriptId() + "_" + soIdInt); if (StringUtils.isNotEmpty(conseqType.getBiotype())) { geneToSOAccessions.add(conseqType.getGeneName() + "_" + conseqType.getBiotype() + "_" + soIdInt); geneToSOAccessions.add(conseqType.getEnsemblGeneId() + "_" + conseqType.getBiotype() + "_" + soIdInt); geneToSOAccessions.add(conseqType.getEnsemblTranscriptId() + "_" + conseqType.getBiotype() + "_" + soIdInt); // This is useful when no gene or transcript is passed, for example we want 'LoF' in real 'protein_coding' geneToSOAccessions.add(conseqType.getBiotype() + "_" + soIdInt); } // Add a combination with the transcript flag if (conseqType.getTranscriptAnnotationFlags() != null) { for (String transcriptFlag : conseqType.getTranscriptAnnotationFlags()) { if (transcriptFlag.equalsIgnoreCase("basic") || transcriptFlag.equalsIgnoreCase("CCDS")) { geneToSOAccessions.add(conseqType.getGeneName() + "_" + soIdInt + "_" + transcriptFlag); geneToSOAccessions.add(conseqType.getEnsemblGeneId() + "_" + soIdInt + "_" + transcriptFlag); geneToSOAccessions.add(conseqType.getEnsemblTranscriptId() + "_" + soIdInt + "_" + transcriptFlag); // This is useful when no gene or transcript is used, for example 'LoF' in 'basic' transcripts geneToSOAccessions.add(soIdInt + "_" + transcriptFlag); } } } } } // if (StringUtils.isNotEmpty(conseqType.getCodon()) || (conseqType.getCdnaPosition() != null && conseqType.getCdnaPosition() > 0) || (conseqType.getCdsPosition() != null && conseqType.getCdsPosition() > 0)) { if (trans.length() == 0) { // Sanity check logger.warn("Codon information without Ensembl transcript ID"); } else { trans.append(FIELD_SEP) .append(conseqType.getCdnaPosition() == null ? 0 : conseqType.getCdnaPosition()) .append(FIELD_SEP) .append(conseqType.getCdsPosition() == null ? 0 : conseqType.getCdsPosition()) .append(FIELD_SEP) .append(StringUtils.isNotEmpty(conseqType.getCodon()) ? conseqType.getCodon() : ""); } } if (conseqType.getProteinVariantAnnotation() != null) { ProteinVariantAnnotation protVarAnnotation = conseqType.getProteinVariantAnnotation(); // Add UniProt accession, name and ID to xrefs trans.append(FIELD_SEP); if (StringUtils.isNotEmpty(protVarAnnotation.getUniprotAccession())) { trans.append(protVarAnnotation.getUniprotAccession()); xrefs.add(protVarAnnotation.getUniprotAccession()); } trans.append(FIELD_SEP); if (StringUtils.isNotEmpty(protVarAnnotation.getUniprotName())) { trans.append(protVarAnnotation.getUniprotName()); xrefs.add(protVarAnnotation.getUniprotName()); } trans.append(FIELD_SEP); if (StringUtils.isNotEmpty(protVarAnnotation.getUniprotVariantId())) { trans.append(protVarAnnotation.getUniprotVariantId()); xrefs.add(protVarAnnotation.getUniprotVariantId()); } trans.append(FIELD_SEP).append(protVarAnnotation.getPosition() == null ? 0 : protVarAnnotation.getPosition()); trans.append(FIELD_SEP); if (StringUtils.isNotEmpty(protVarAnnotation.getReference()) && StringUtils.isNotEmpty(protVarAnnotation.getAlternate())) { trans.append(protVarAnnotation.getReference()).append("/") .append(protVarAnnotation.getAlternate()); } // Create transcript info and add it into the other list Score sift = getScore(protVarAnnotation.getSubstitutionScores(), "sift"); Score polyph = getScore(protVarAnnotation.getSubstitutionScores(), "polyphen"); trans.append(FIELD_SEP); if (sift != null) { trans.append(sift.getScore()).append(FIELD_SEP).append(sift.getDescription()); } else { trans.append(FIELD_SEP); } trans.append(FIELD_SEP); if (polyph != null) { trans.append(polyph.getScore()).append(FIELD_SEP).append(polyph.getDescription()); } else { trans.append(FIELD_SEP); } // Add keywords to and Features to traits if (protVarAnnotation.getKeywords() != null) { for (String keyword : protVarAnnotation.getKeywords()) { traits.add("KW" + FIELD_SEP + protVarAnnotation.getUniprotAccession() + FIELD_SEP + keyword); } } // Add protein domains if (protVarAnnotation.getFeatures() != null) { for (ProteinFeature proteinFeature : protVarAnnotation.getFeatures()) { if (StringUtils.isNotEmpty(proteinFeature.getId())) { // We store them in xrefs and traits, the number of these IDs is very small xrefs.add(proteinFeature.getId()); traits.add("PD" + FIELD_SEP + proteinFeature.getId() + FIELD_SEP + proteinFeature.getDescription()); } } } } if (StringUtils.isNotEmpty(conseqType.getEnsemblTranscriptId()) && trans.length() > 0) { other.add(trans.toString()); } } // We store the accumulated data genes.forEach((s, strings) -> variantSearchModel.getGenes().addAll(strings)); variantSearchModel.setSoAcc(new ArrayList<>(soAccessions)); variantSearchModel.setGeneToSoAcc(new ArrayList<>(geneToSOAccessions)); variantSearchModel.setBiotypes(new ArrayList<>(biotypes)); // We now process Sift and Polyphen setProteinScores(consequenceTypes, variantSearchModel); } // Set Populations frequencies Map<String, Float> populationFrequencies = new HashMap<>(); if (variantAnnotation.getPopulationFrequencies() != null) { for (PopulationFrequency populationFrequency : variantAnnotation.getPopulationFrequencies()) { populationFrequencies.put("popFreq" + VariantSearchUtils.FIELD_SEPARATOR + populationFrequency.getStudy() + VariantSearchUtils.FIELD_SEPARATOR + populationFrequency.getPopulation(), populationFrequency.getAltAlleleFreq()); } } // Add 0.0 for mot commonly used populations, this will allow to skip a NON EXIST query and improve performance populationFrequencies.putIfAbsent("popFreq" + VariantSearchUtils.FIELD_SEPARATOR + "1kG_phase3__ALL", 0.0f); populationFrequencies.putIfAbsent("popFreq" + VariantSearchUtils.FIELD_SEPARATOR + "GNOMAD_EXOMES__ALL", 0.0f); populationFrequencies.putIfAbsent("popFreq" + VariantSearchUtils.FIELD_SEPARATOR + "GNOMAD_GENOMES__ALL", 0.0f); // Set population frequencies into the model variantSearchModel.setPopFreq(populationFrequencies); // Set Conservation scores if (variantAnnotation.getConservation() != null) { for (Score score : variantAnnotation.getConservation()) { switch (score.getSource()) { case "phastCons": variantSearchModel.setPhastCons(score.getScore()); break; case "phylop": variantSearchModel.setPhylop(score.getScore()); break; case "gerp": variantSearchModel.setGerp(score.getScore()); break; default: logger.warn("Unknown 'conservation' source: score.getSource() = " + score.getSource()); break; } } } // Set CADD if (variantAnnotation.getFunctionalScore() != null) { for (Score score : variantAnnotation.getFunctionalScore()) { switch (score.getSource()) { case "cadd_raw": case "caddRaw": variantSearchModel.setCaddRaw(score.getScore()); break; case "cadd_scaled": case "caddScaled": variantSearchModel.setCaddScaled(score.getScore()); break; default: logger.warn("Unknown 'functional score' source: score.getSource() = " + score.getSource()); break; } } } // Set variant traits: ClinVar, Cosmic, HPO, ... if (variantAnnotation.getVariantTraitAssociation() != null) { if (variantAnnotation.getVariantTraitAssociation().getClinvar() != null) { variantAnnotation.getVariantTraitAssociation().getClinvar() .forEach(cv -> { xrefs.add(cv.getAccession()); cv.getTraits().forEach(cvt -> traits.add("CV" + FIELD_SEP + cv.getAccession() + FIELD_SEP + cvt + FIELD_SEP + "cs:" + cv.getClinicalSignificance())); }); } if (variantAnnotation.getVariantTraitAssociation().getCosmic() != null) { variantAnnotation.getVariantTraitAssociation().getCosmic() .forEach(cosmic -> { xrefs.add(cosmic.getMutationId()); traits.add("CM" + FIELD_SEP + cosmic.getMutationId() + FIELD_SEP + cosmic.getPrimaryHistology() + FIELD_SEP + cosmic.getHistologySubtype()); }); } } if (variantAnnotation.getGeneTraitAssociation() != null && CollectionUtils.isNotEmpty(variantAnnotation.getGeneTraitAssociation())) { for (GeneTraitAssociation geneTraitAssociation : variantAnnotation.getGeneTraitAssociation()) { switch (geneTraitAssociation.getSource().toLowerCase()) { case "hpo": traits.add("HP" + FIELD_SEP + geneTraitAssociation.getHpo() + FIELD_SEP + geneTraitAssociation.getId() + " -- " + geneTraitAssociation.getName()); break; // case "disgenet": // traits.add("DG -- " + geneTraitAssociation.getId() + " -- " + geneTraitAssociation.getName()); // break; default: break; } } } variantSearchModel.setTraits(new ArrayList<>(traits)); // Now we fill other field if (StringUtils.isNotEmpty(variantAnnotation.getDisplayConsequenceType())) { other.add("DCT" + FIELD_SEP + variantAnnotation.getDisplayConsequenceType()); } if (variantAnnotation.getHgvs() != null) { for (String hgvs : variantAnnotation.getHgvs()) { other.add("HGVS" + FIELD_SEP + hgvs); } } if (variantAnnotation.getCytoband() != null) { for (Cytoband cytoband : variantAnnotation.getCytoband()) { other.add("CB" + FIELD_SEP + cytoband.getName() + FIELD_SEP + cytoband.getStain() + FIELD_SEP + cytoband.getStart() + FIELD_SEP + cytoband.getEnd()); } } if (variantAnnotation.getRepeat() != null) { for (Repeat repeat : variantAnnotation.getRepeat()) { other.add("RP" + FIELD_SEP + repeat.getId() + FIELD_SEP + repeat.getSource() + FIELD_SEP + repeat.getCopyNumber() + FIELD_SEP + repeat.getPercentageMatch() + FIELD_SEP + repeat.getStart() + FIELD_SEP + repeat.getEnd()); } } variantSearchModel.setOther(other); } variantSearchModel.setXrefs(new ArrayList<>(xrefs)); return variantSearchModel; } public static String studyIdToSearchModel(String studyId) { return studyId.substring(studyId.lastIndexOf(':') + 1); } public List<VariantSearchModel> convertListToStorageType(List<Variant> variants) { List<VariantSearchModel> variantSearchModelList = new ArrayList<>(variants.size()); for (Variant variant : variants) { VariantSearchModel variantSearchModel = convertToStorageType(variant); if (variantSearchModel.getId() != null) { variantSearchModelList.add(variantSearchModel); } } return variantSearchModelList; } /** * Retrieve the protein substitution scores and descriptions from a consequence * type annotation: sift or polyphen, and update the variant search model. * * @param consequenceTypes List of consequence type target * @param variantSearchModel Variant search model to update */ private void setProteinScores(List<ConsequenceType> consequenceTypes, VariantSearchModel variantSearchModel) { double sift = 10; String siftDesc = ""; double polyphen = MISSING_VALUE; String polyphenDesc = ""; if (consequenceTypes != null) { for (ConsequenceType consequenceType : consequenceTypes) { if (consequenceType.getProteinVariantAnnotation() != null && consequenceType.getProteinVariantAnnotation().getSubstitutionScores() != null) { for (Score score : consequenceType.getProteinVariantAnnotation().getSubstitutionScores()) { String source = score.getSource(); if (("sift").equals(source)) { if (score.getScore() < sift) { sift = score.getScore(); siftDesc = score.getDescription(); } } else if (("polyphen").equals(source)) { if (score.getScore() > polyphen) { polyphen = score.getScore(); polyphenDesc = score.getDescription(); } } } } } } // If sift not exist we set it to -100.0 if (ArrayUtils.equals(sift, 10)) { sift = MISSING_VALUE; } // set scores variantSearchModel.setSift(sift); variantSearchModel.setPolyphen(polyphen); // set descriptions variantSearchModel.setSiftDesc(siftDesc); variantSearchModel.setPolyphenDesc(polyphenDesc); } private Score getScore(List<Score> scores, String source) { if (ListUtils.isNotEmpty(scores) && StringUtils.isNotEmpty(source)) { for (Score score: scores) { if (source.equals(score.getSource())) { return score; } } } return null; } private Double parseDouble(String value, Double defaultValue) { return parseDouble(value, defaultValue, null); } private Double parseDouble(String value, Double defaultValue, String message) { try { return Double.parseDouble(value); } catch (NumberFormatException e) { if (message != null) { logger.warn(message + ". Value: '" + value + "'"); } return defaultValue; } } private Float parseFloat(String value, Float defaultValue) { return parseFloat(value, defaultValue, null); } private Float parseFloat(String value, Float defaultValue, String message) { try { return Float.parseFloat(value); } catch (NumberFormatException e) { if (message != null) { logger.warn(message + ". Value: '" + value + "'"); } return defaultValue; } } }
opencga-storage/opencga-storage-core/src/main/java/org/opencb/opencga/storage/core/variant/search/VariantSearchToVariantConverter.java
/* * Copyright 2015-2017 OpenCB * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.opencb.opencga.storage.core.variant.search; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectReader; import com.fasterxml.jackson.databind.ObjectWriter; import htsjdk.variant.vcf.VCFConstants; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.StringUtils; import org.opencb.biodata.models.variant.StudyEntry; import org.opencb.biodata.models.variant.Variant; import org.opencb.biodata.models.variant.annotation.ConsequenceTypeMappings; import org.opencb.biodata.models.variant.avro.*; import org.opencb.biodata.models.variant.stats.VariantStats; import org.opencb.commons.datastore.core.ComplexTypeConverter; import org.opencb.commons.utils.CollectionUtils; import org.opencb.commons.utils.ListUtils; import org.opencb.opencga.core.common.ArrayUtils; import org.opencb.opencga.storage.core.variant.adaptors.VariantField; import org.opencb.opencga.storage.core.variant.annotation.converters.VariantTraitAssociationToEvidenceEntryConverter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.*; import static org.opencb.opencga.storage.core.variant.adaptors.VariantField.AdditionalAttributes.GROUP_NAME; import static org.opencb.opencga.storage.core.variant.adaptors.VariantField.AdditionalAttributes.RELEASE; /** * Created by imedina on 14/11/16. */ public class VariantSearchToVariantConverter implements ComplexTypeConverter<Variant, VariantSearchModel> { public static final double MISSING_VALUE = -100.0; private static final String LIST_SEP = "___"; private static final String FIELD_SEP = " -- "; private Logger logger = LoggerFactory.getLogger(VariantSearchToVariantConverter.class); private final VariantTraitAssociationToEvidenceEntryConverter evidenceEntryConverter; private Set<VariantField> includeFields; public VariantSearchToVariantConverter() { evidenceEntryConverter = new VariantTraitAssociationToEvidenceEntryConverter(); } public VariantSearchToVariantConverter(Set<VariantField> includeFields) { this(); this.includeFields = includeFields; } /** * Conversion: from storage type to data model. * * @param variantSearchModel Storage type object * @return Data model object */ @Override public Variant convertToDataModelType(VariantSearchModel variantSearchModel) { // set chromosome, start, end, ref, alt from ID Variant variant = new Variant(variantSearchModel.getId()); // set ID, chromosome, start, end, ref, alt, type variant.setId(variantSearchModel.getVariantId()); // set variant type if (StringUtils.isNotEmpty(variantSearchModel.getType())) { variant.setType(VariantType.valueOf(variantSearchModel.getType())); } // Study management Map<String, StudyEntry> studyEntryMap = new HashMap<>(); if (variantSearchModel.getStudies() != null && CollectionUtils.isNotEmpty(variantSearchModel.getStudies())) { List<StudyEntry> studies = new ArrayList<>(); variantSearchModel.getStudies().forEach(studyId -> { StudyEntry entry = new StudyEntry(studyId); studies.add(entry); studyEntryMap.put(studyId, entry); }); variant.setStudies(studies); } // Genotypes and sample data and format if (MapUtils.isNotEmpty(variantSearchModel.getSampleFormat())) { for (String studyId: studyEntryMap.keySet()) { String stringToList; String suffix = VariantSearchUtils.FIELD_SEPARATOR + studyId + VariantSearchUtils.FIELD_SEPARATOR; StudyEntry studyEntry = studyEntryMap.get(studyId); // Format stringToList = variantSearchModel.getSampleFormat().get("sampleFormat" + suffix + "format"); if (StringUtils.isNotEmpty(stringToList)) { studyEntry.setFormat(Arrays.asList(StringUtils.splitByWholeSeparatorPreserveAllTokens(stringToList, LIST_SEP))); } // Sample Data management stringToList = variantSearchModel.getSampleFormat().get("sampleFormat" + suffix + "sampleName"); if (StringUtils.isNotEmpty(stringToList)) { String[] sampleNames = StringUtils.splitByWholeSeparatorPreserveAllTokens(stringToList, LIST_SEP); List<List<String>> sampleData = new ArrayList<>(); Map<String, Integer> samplePosition = new HashMap<>(); int pos = 0; for (String sampleName: sampleNames) { suffix = VariantSearchUtils.FIELD_SEPARATOR + studyId + VariantSearchUtils.FIELD_SEPARATOR + sampleName; stringToList = variantSearchModel.getSampleFormat().get("sampleFormat" + suffix); if (StringUtils.isNotEmpty(stringToList)) { sampleData.add(Arrays.asList(StringUtils.splitByWholeSeparatorPreserveAllTokens(stringToList, LIST_SEP))); samplePosition.put(sampleName, pos++); } // else { // logger.error("Error converting samplesFormat, sample '{}' is missing or empty, value: '{}'", // sampleName, stringToList); // } } if (ListUtils.isNotEmpty(sampleData)) { studyEntry.setSamplesData(sampleData); studyEntry.setSamplesPosition(samplePosition); } } } } // File info management if (MapUtils.isNotEmpty(variantSearchModel.getFileInfo())) { ObjectReader reader = new ObjectMapper().reader(HashMap.class); for (String key: variantSearchModel.getFileInfo().keySet()) { // key consists of 'fileInfo' + "__" + studyId + "__" + fileId String[] fields = StringUtils.splitByWholeSeparator(key, VariantSearchUtils.FIELD_SEPARATOR); FileEntry fileEntry = new FileEntry(fields[2], null, new HashMap<>()); try { // We obtain the original call Map<String, String> fileInfoAttributes = reader.readValue(variantSearchModel.getFileInfo().get(key)); if (MapUtils.isNotEmpty(fileInfoAttributes)) { fileEntry.setCall(fileInfoAttributes.get("fileCall")); fileInfoAttributes.remove("fileCall"); fileEntry.setAttributes(fileInfoAttributes); } } catch (IOException e) { logger.error("Error converting fileInfo from variant search model: {}", e.getMessage()); } finally { variant.getStudy(fields[1]).getFiles().add(fileEntry); } } } // Stats management if (MapUtils.isNotEmpty(variantSearchModel.getStats())) { for (String key: variantSearchModel.getStats().keySet()) { // key consists of 'stats' + "__" + studyId + "__" + cohort String[] fields = StringUtils.splitByWholeSeparator(key, VariantSearchUtils.FIELD_SEPARATOR); if (studyEntryMap.containsKey(fields[1])) { VariantStats variantStats = new VariantStats(); variantStats.setRefAlleleFreq(1 - variantSearchModel.getStats().get(key)); variantStats.setAltAlleleFreq(variantSearchModel.getStats().get(key)); variantStats.setMaf(Math.min(variantSearchModel.getStats().get(key), 1 - variantSearchModel.getStats().get(key))); studyEntryMap.get(fields[1]).setStats(fields[2], variantStats); } } } // process annotation variant.setAnnotation(getVariantAnnotation(variantSearchModel, variant)); return variant; } public VariantAnnotation getVariantAnnotation(VariantSearchModel variantSearchModel, Variant variant) { if (includeFields != null && !includeFields.contains(VariantField.ANNOTATION)) { return null; } VariantAnnotation variantAnnotation = new VariantAnnotation(); variantAnnotation.setChromosome(variant.getChromosome()); variantAnnotation.setStart(variant.getStart()); variantAnnotation.setEnd(variant.getEnd()); variantAnnotation.setAlternate(variant.getAlternate()); variantAnnotation.setReference(variant.getReference()); // Set 'release' if it was not missing if (variantSearchModel.getRelease() > 0) { Map<String, String> attribute = new HashMap<>(); attribute.put(RELEASE.key(), String.valueOf(variantSearchModel.getRelease())); variantAnnotation.setAdditionalAttributes(new HashMap<>()); variantAnnotation.getAdditionalAttributes().put(GROUP_NAME.key(), new AdditionalAttribute(attribute)); } // Xrefs List<Xref> xrefs = new ArrayList<>(); if (ListUtils.isNotEmpty(variantSearchModel.getXrefs())) { for (String xref: variantSearchModel.getXrefs()) { if (xref == null) { continue; } if (xref.startsWith("rs")) { xrefs.add(new Xref(xref, "dbSNP")); continue; } if (xref.startsWith("ENSG")) { xrefs.add(new Xref(xref, "ensemblGene")); continue; } if (xref.startsWith("ENST")) { xrefs.add(new Xref(xref, "ensemblTranscript")); } } } variantAnnotation.setXrefs(xrefs); // Init the consequence type map with protein variant annotation // and set displayConsequenceType, hgvs, cytobands and repeats from 'other' field Map<String, ConsequenceType> consequenceTypeMap = new HashMap<>(); variantAnnotation.setHgvs(new ArrayList<>()); variantAnnotation.setCytoband(new ArrayList<>()); variantAnnotation.setRepeat(new ArrayList<>()); for (String other : variantSearchModel.getOther()) { // Sanity check if (StringUtils.isEmpty(other)) { continue; } String[] fields = StringUtils.splitByWholeSeparatorPreserveAllTokens(other, FIELD_SEP); switch (fields[0]) { case "DCT": variantAnnotation.setDisplayConsequenceType(fields[1]); break; case "HGVS": variantAnnotation.getHgvs().add(fields[1]); break; case "CB": Cytoband cytoband = Cytoband.newBuilder() .setChromosome(variant.getChromosome()) .setName(fields[1]) .setStain(fields[2]) .setStart(Integer.parseInt(fields[3])).setEnd(Integer.parseInt(fields[4])) .build(); variantAnnotation.getCytoband().add(cytoband); break; case "RP": Repeat repeat = Repeat.newBuilder() .setId(fields[1]) .setSource(fields[2]) .setChromosome(variant.getChromosome()) .setStart(Integer.parseInt(fields[5])) .setEnd(Integer.parseInt(fields[6])) .setCopyNumber(parseFloat(fields[3], null)) .setPercentageMatch(parseFloat(fields[4], null)) .setPeriod(null) .setConsensusSize(null) .setScore(null) .setSequence(null) .build(); variantAnnotation.getRepeat().add(repeat); break; case "TRANS": // Create consequence type from transcript info: // 1 2 3 4 5 6 // transcriptId -- biotype -- annotationFlags -- cdnaPosition -- cdsPosition -- codon // 7 8 9 10 11 // -- uniprotAccession -- uniprotAccession -- uniprotVariantId -- position -- aaChange // 12 13 14 15 // siftScore -- siftDescr -- poliphenScore -- poliphenDescr ConsequenceType consequenceType = new ConsequenceType(); if (fields.length > 2) { consequenceType.setEnsemblTranscriptId(fields[1]); consequenceType.setBiotype(fields[2]); } if (fields.length > 3) { if (fields[3].length() > 0) { consequenceType.setTranscriptAnnotationFlags(Arrays.asList(fields[3].split(","))); } } if (fields.length > 4) { consequenceType.setCdnaPosition(Integer.parseInt(fields[4])); consequenceType.setCdsPosition(Integer.parseInt(fields[5])); if (fields.length > 6) { // Sometimes, codon (i.e., split at 5) is null, check it! consequenceType.setCodon(fields[6]); } } if (fields.length > 7) { // Create, init and add protein variant annotation to the consequence type ProteinVariantAnnotation protVarAnnotation = new ProteinVariantAnnotation(); // Uniprot info protVarAnnotation.setUniprotAccession(fields[7]); protVarAnnotation.setUniprotName(fields[8]); protVarAnnotation.setUniprotVariantId(fields[9]); if (StringUtils.isNotEmpty(fields[10])) { try { protVarAnnotation.setPosition(Integer.parseInt(fields[10])); } catch (NumberFormatException e) { logger.warn("Parsing position: " + e.getMessage()); } } if (StringUtils.isNotEmpty(fields[11]) && fields[11].contains("/")) { String[] refAlt = fields[11].split("/"); protVarAnnotation.setReference(refAlt[0]); protVarAnnotation.setAlternate(refAlt[1]); } // Sift score List<Score> scores = new ArrayList<>(2); if (fields.length > 12 && (StringUtils.isNotEmpty(fields[12]) || StringUtils.isNotEmpty(fields[13]))) { Score score = new Score(); score.setSource("sift"); if (StringUtils.isNotEmpty(fields[12])) { score.setScore(parseDouble(fields[12], null, "Exception parsing Sift score")); } score.setDescription(fields[13]); scores.add(score); } // Polyphen score if (fields.length > 14 && (StringUtils.isNotEmpty(fields[14]) || StringUtils.isNotEmpty(fields[15]))) { Score score = new Score(); score.setSource("polyphen"); if (StringUtils.isNotEmpty(fields[14])) { score.setScore(parseDouble(fields[14], null, "Exception parsing Polyphen score")); } score.setDescription(fields[15]); scores.add(score); } protVarAnnotation.setSubstitutionScores(scores); // Finally, set protein variant annotation in consequence type consequenceType.setProteinVariantAnnotation(protVarAnnotation); } // The key is the ENST id consequenceTypeMap.put(fields[1], consequenceType); break; default: logger.warn("Unknown key in 'other' array in Solr: " + fields[0]); } } // consequence types String geneName = null; String ensGene = null; if (ListUtils.isNotEmpty(variantSearchModel.getGenes())) { for (String name : variantSearchModel.getGenes()) { if (!name.startsWith("ENS")) { geneName = name; } else if (name.startsWith("ENSG")) { ensGene = name; } else if (name.startsWith("ENST")) { ConsequenceType consequenceType = consequenceTypeMap.getOrDefault(name, null); if (consequenceType == null) { consequenceType = new ConsequenceType(); consequenceType.setEnsemblTranscriptId(name); consequenceTypeMap.put(name, consequenceType); logger.warn("No information found in Solr field 'other' for transcript '{}'", name); // throw new InternalError("Transcript '" + name + "' missing in schema field name 'other'"); } consequenceType.setGeneName(geneName); consequenceType.setEnsemblGeneId(ensGene); } } } // prepare protein substitution scores: sift and polyphen List<Score> scores; // ProteinVariantAnnotation proteinAnnotation = new ProteinVariantAnnotation(); // if (!ArrayUtils.equals(variantSearchModel.getSift(), MISSING_VALUE) // || !ArrayUtils.equals(variantSearchModel.getPolyphen(), MISSING_VALUE)) { // scores = new ArrayList<>(); // if (!ArrayUtils.equals(variantSearchModel.getSift(), MISSING_VALUE)) { // scores.add(new Score(variantSearchModel.getSift(), "sift", variantSearchModel.getSiftDesc())); // } // if (!ArrayUtils.equals(variantSearchModel.getPolyphen(), MISSING_VALUE)) { // scores.add(new Score(variantSearchModel.getPolyphen(), "polyphen", variantSearchModel.getPolyphenDesc())); // } // proteinAnnotation.setSubstitutionScores(scores); // } // and finally, update the SO acc. for each conseq. type and setProteinVariantAnnotation if SO accession is 1583 Set<Integer> geneRelatedSoTerms = new HashSet<>(); if (variantSearchModel.getGeneToSoAcc() != null) { for (String geneToSoAcc : variantSearchModel.getGeneToSoAcc()) { String[] fields = geneToSoAcc.split("_"); if (consequenceTypeMap.containsKey(fields[0])) { int soAcc = Integer.parseInt(fields[1]); geneRelatedSoTerms.add(soAcc); // we memorise the SO term for next block SequenceOntologyTerm sequenceOntologyTerm = new SequenceOntologyTerm(); sequenceOntologyTerm.setAccession("SO:" + String.format("%07d", soAcc)); sequenceOntologyTerm.setName(ConsequenceTypeMappings.accessionToTerm.get(soAcc)); if (consequenceTypeMap.get(fields[0]).getSequenceOntologyTerms() == null) { consequenceTypeMap.get(fields[0]).setSequenceOntologyTerms(new ArrayList<>()); } consequenceTypeMap.get(fields[0]).getSequenceOntologyTerms().add(sequenceOntologyTerm); // // only set protein for that conseq. type if annotated protein and SO acc is 1583 (missense_variant) // if (soAcc == 1583) { // consequenceTypeMap.get(fields[0]).setProteinVariantAnnotation(proteinAnnotation); // } } } } // We convert the Map into an array ArrayList<ConsequenceType> consequenceTypes = new ArrayList<>(consequenceTypeMap.values()); // Add non-gene related SO terms if (variantSearchModel.getSoAcc() != null) { for (Integer soAcc : variantSearchModel.getSoAcc()) { // let's process all non-gene related terms such as regulatory_region_variant or intergenic_variant if (!geneRelatedSoTerms.contains(soAcc)) { SequenceOntologyTerm sequenceOntologyTerm = new SequenceOntologyTerm(); sequenceOntologyTerm.setAccession("SO:" + String.format("%07d", soAcc)); sequenceOntologyTerm.setName(ConsequenceTypeMappings.accessionToTerm.get(soAcc)); ConsequenceType consequenceType = new ConsequenceType(); consequenceType.setEnsemblGeneId(""); consequenceType.setGeneName(""); consequenceType.setEnsemblTranscriptId(""); consequenceType.setSequenceOntologyTerms(Collections.singletonList(sequenceOntologyTerm)); consequenceTypes.add(consequenceType); } } } // and update the variant annotation with the consequence types variantAnnotation.setConsequenceTypes(consequenceTypes); // set populations List<PopulationFrequency> populationFrequencies = new ArrayList<>(); if (variantSearchModel.getPopFreq() != null && variantSearchModel.getPopFreq().size() > 0) { for (String key : variantSearchModel.getPopFreq().keySet()) { PopulationFrequency populationFrequency = new PopulationFrequency(); String[] fields = StringUtils.splitByWholeSeparator(key, VariantSearchUtils.FIELD_SEPARATOR); populationFrequency.setStudy(fields[1]); populationFrequency.setPopulation(fields[2]); populationFrequency.setRefAlleleFreq(1 - variantSearchModel.getPopFreq().get(key)); populationFrequency.setAltAlleleFreq(variantSearchModel.getPopFreq().get(key)); populationFrequencies.add(populationFrequency); } } variantAnnotation.setPopulationFrequencies(populationFrequencies); // Set conservations scores scores = new ArrayList<>(); if (!ArrayUtils.equals(variantSearchModel.getPhylop(), MISSING_VALUE)) { scores.add(new Score(variantSearchModel.getPhylop(), "phylop", "")); } if (!ArrayUtils.equals(variantSearchModel.getPhastCons(), MISSING_VALUE)) { scores.add(new Score(variantSearchModel.getPhastCons(), "phastCons", "")); } if (!ArrayUtils.equals(variantSearchModel.getGerp(), MISSING_VALUE)) { scores.add(new Score(variantSearchModel.getGerp(), "gerp", "")); } variantAnnotation.setConservation(scores); // Set CADD scores scores = new ArrayList<>(); if (!ArrayUtils.equals(variantSearchModel.getCaddRaw(), MISSING_VALUE)) { scores.add(new Score(variantSearchModel.getCaddRaw(), "cadd_raw", "")); } if (!ArrayUtils.equals(variantSearchModel.getCaddScaled(), MISSING_VALUE)) { scores.add(new Score(variantSearchModel.getCaddScaled(), "cadd_scaled", "")); } variantAnnotation.setFunctionalScore(scores); // set HPO, ClinVar and Cosmic if (variantSearchModel.getTraits() != null) { Map<String, ClinVar> clinVarMap = new HashMap<>(); List<ClinVar> clinVarList = new ArrayList<>(); List<Cosmic> cosmicList = new ArrayList<>(); List<GeneTraitAssociation> geneTraitAssociationList = new ArrayList<>(); for (String trait : variantSearchModel.getTraits()) { String[] fields = StringUtils.splitByWholeSeparatorPreserveAllTokens(trait, FIELD_SEP); switch (fields[0]) { case "HP": // Gene trait: HP -- hpo -- id -- name GeneTraitAssociation geneTraitAssociation = new GeneTraitAssociation(); geneTraitAssociation.setHpo(fields[1]); geneTraitAssociation.setId(fields[2]); geneTraitAssociation.setName(fields[3]); geneTraitAssociationList.add(geneTraitAssociation); break; case "CV": // Variant trait: CV -- accession -- trait if (!clinVarMap.containsKey(fields[1])) { String clinicalSignificance = ""; if (fields.length > 3 && fields[3].length() > 3) { clinicalSignificance = fields[3].substring(3); } ClinVar clinVar = new ClinVar(fields[1], clinicalSignificance, new ArrayList<>(), new ArrayList<>(), ""); clinVarMap.put(fields[1], clinVar); clinVarList.add(clinVar); } clinVarMap.get(fields[1]).getTraits().add(fields[2]); break; case "CM": // Variant trait: CM -- mutation id -- primary histology -- histology subtype Cosmic cosmic = new Cosmic(); cosmic.setMutationId(fields[1]); cosmic.setPrimaryHistology(fields[2]); cosmic.setHistologySubtype(fields[3]); cosmicList.add(cosmic); break; case "KW": case "PD": // These are taken from consequence type non-indexed field break; default: { logger.warn("Unknown trait type: " + fields[0] + ", it should be HPO, ClinVar or Cosmic"); break; } } } // TODO to be removed in next versions VariantTraitAssociation variantTraitAssociation = new VariantTraitAssociation(); // This fills the old data model: variantTraitAssociation if (CollectionUtils.isNotEmpty(clinVarList)) { variantTraitAssociation.setClinvar(clinVarList); } if (CollectionUtils.isNotEmpty(cosmicList)) { variantTraitAssociation.setCosmic(cosmicList); } variantAnnotation.setVariantTraitAssociation(variantTraitAssociation); // This fills the new data model: traitAssociation List<EvidenceEntry> evidenceEntries = new ArrayList<>(); // Clinvar -> traitAssociation for (ClinVar clinvar: clinVarList) { evidenceEntries.add(evidenceEntryConverter.fromClinVar(clinvar)); } // Cosmic -> traitAssociation for (Cosmic cosmic: cosmicList) { evidenceEntries.add(evidenceEntryConverter.fromCosmic(cosmic)); } variantAnnotation.setTraitAssociation(evidenceEntries); // Set the gene disease annotation if (CollectionUtils.isNotEmpty(geneTraitAssociationList)) { variantAnnotation.setGeneTraitAssociation(geneTraitAssociationList); } } return variantAnnotation; } /** * Conversion: from data model to storage type. * * @param variant Data model object * @return Storage type object */ @Override public VariantSearchModel convertToStorageType(Variant variant) { VariantSearchModel variantSearchModel = new VariantSearchModel(); // Set general Variant attributes: id, dbSNP, chromosome, start, end, type variantSearchModel.setId(variant.toString()); // Internal unique ID e.g. 3:1000:AT:- variantSearchModel.setVariantId(variant.getId()); variantSearchModel.setChromosome(variant.getChromosome()); variantSearchModel.setStart(variant.getStart()); variantSearchModel.setEnd(variant.getEnd()); variantSearchModel.setType(variant.getType().toString()); // This field contains all possible IDs: id, dbSNP, names, genes, transcripts, protein, clinvar, hpo, ... // This will help when searching by variant id. This is added at the end of the method after collecting all IDs Set<String> xrefs = new HashSet<>(); xrefs.add(variantSearchModel.getId()); xrefs.add(variantSearchModel.getVariantId()); if (variant.getNames() != null && !variant.getNames().isEmpty()) { variant.getNames().forEach(name -> { if (name != null) { xrefs.add(name); } }); } // convert Study related information if (CollectionUtils.isNotEmpty(variant.getStudies())) { ObjectWriter writer = new ObjectMapper().writer(); for (StudyEntry studyEntry : variant.getStudies()) { String studyId = studyIdToSearchModel(studyEntry.getStudyId()); variantSearchModel.getStudies().add(studyId); // We store the cohort stats with the format stats_STUDY_COHORT = value, e.g. stats_1kg_phase3_ALL=0.02 if (studyEntry.getStats() != null && studyEntry.getStats().size() > 0) { Map<String, VariantStats> studyStats = studyEntry.getStats(); for (String key : studyStats.keySet()) { variantSearchModel.getStats().put("stats" + VariantSearchUtils.FIELD_SEPARATOR + studyId + VariantSearchUtils.FIELD_SEPARATOR + key, studyStats.get(key).getAltAlleleFreq()); } } // samples, genotypes and format fields conversion if (MapUtils.isNotEmpty(studyEntry.getSamplesPosition()) && ListUtils.isNotEmpty(studyEntry.getOrderedSamplesName())) { List<String> sampleNames = studyEntry.getOrderedSamplesName(); // sanity check, the number od sample names and sample data must be the same if (ListUtils.isNotEmpty(studyEntry.getSamplesData()) && sampleNames.size() == studyEntry.getSamplesData().size()) { String suffix = VariantSearchUtils.FIELD_SEPARATOR + studyId + VariantSearchUtils.FIELD_SEPARATOR; // Save sample formats in a map (after, to JSON string), including sample names and GT variantSearchModel.getSampleFormat().put("sampleFormat" + suffix + "sampleName", StringUtils.join(sampleNames, LIST_SEP)); // find the index position of DP in the FORMAT int dpIndexPos = -1; if (ListUtils.isNotEmpty(studyEntry.getFormat())) { variantSearchModel.getSampleFormat().put("sampleFormat" + suffix + "format", StringUtils.join(studyEntry.getFormat(), LIST_SEP)); // find the index position of DP in the FORMAT for (int i = 0; i < studyEntry.getFormat().size(); i++) { if ("DP".equalsIgnoreCase(studyEntry.getFormat().get(i))) { dpIndexPos = i; break; } } } for (int i = 0; i < sampleNames.size(); i++) { suffix = VariantSearchUtils.FIELD_SEPARATOR + studyId + VariantSearchUtils.FIELD_SEPARATOR + sampleNames.get(i); // Save genotype (gt) and depth (dp) where study and sample name as key variantSearchModel.getGt().put("gt" + suffix, studyEntry.getSampleData(i).get(0)); if (dpIndexPos != -1) { String dpValue = studyEntry.getSampleData(i).get(dpIndexPos); // Skip if empty if (!StringUtils.isEmpty(dpValue) && !dpValue.equals(VCFConstants.EMPTY_INFO_FIELD)) { try { variantSearchModel.getDp().put("dp" + suffix, Integer.valueOf(dpValue)); } catch (NumberFormatException e) { logger.error("Problem converting from variant to variant search when getting DP" + " value from sample {}: {}", sampleNames.get(i), e.getMessage()); } } } // Save formats for each sample (after, to JSON string) if (ListUtils.isNotEmpty(studyEntry.getSamplesData().get(i))) { variantSearchModel.getSampleFormat().put("sampleFormat" + suffix, StringUtils.join(studyEntry.getSamplesData().get(i), LIST_SEP)); } } } else { logger.error("Mismatch sizes: please, check your sample names, sample data and format array"); } } // QUAL, FILTER and file info fields management if (ListUtils.isNotEmpty(studyEntry.getFiles())) { for (FileEntry fileEntry: studyEntry.getFiles()) { // Call is stored in Solr fileInfo with key "fileCall" Map<String, String> fileInfoMap = new LinkedHashMap<>(); if (StringUtils.isNotEmpty(fileEntry.getCall())) { fileInfoMap.put("fileCall", fileEntry.getCall()); } // Info fields are stored in Solr fileInfo if (MapUtils.isNotEmpty(fileEntry.getAttributes())) { fileInfoMap.putAll(fileEntry.getAttributes()); // In addition, store QUAL and FILTER separately String qual = fileEntry.getAttributes().get(StudyEntry.QUAL); if (StringUtils.isNotEmpty(qual)) { variantSearchModel.getQual().put("qual" + VariantSearchUtils.FIELD_SEPARATOR + studyId + VariantSearchUtils.FIELD_SEPARATOR + fileEntry.getFileId(), Float.parseFloat(qual)); } String filter = fileEntry.getAttributes().get(StudyEntry.FILTER); if (StringUtils.isNotEmpty(filter)) { variantSearchModel.getFilter().put("filter" + VariantSearchUtils.FIELD_SEPARATOR + studyId + VariantSearchUtils.FIELD_SEPARATOR + fileEntry.getFileId(), filter); } } if (MapUtils.isNotEmpty(fileInfoMap)) { try { variantSearchModel.getFileInfo().put("fileInfo" + VariantSearchUtils.FIELD_SEPARATOR + studyId + VariantSearchUtils.FIELD_SEPARATOR + fileEntry.getFileId(), writer.writeValueAsString(fileInfoMap)); } catch (JsonProcessingException e) { logger.info("Error converting fileInfo for study {} and file {}", studyId, fileEntry.getFileId()); } } } } } } // We init all annotation numeric values to MISSING_VALUE, this fixes two different scenarios: // 1. No Variant Annotation has been found, probably because it is a SV longer than 100bp. // 2. There are some conservation or CADD scores missing variantSearchModel.setSift(MISSING_VALUE); variantSearchModel.setPolyphen(MISSING_VALUE); variantSearchModel.setPhastCons(MISSING_VALUE); variantSearchModel.setPhylop(MISSING_VALUE); variantSearchModel.setGerp(MISSING_VALUE); variantSearchModel.setCaddRaw(MISSING_VALUE); variantSearchModel.setCaddScaled(MISSING_VALUE); // Process Variant Annotation VariantAnnotation variantAnnotation = variant.getAnnotation(); if (variantAnnotation != null) { // This object will store all info and descriptions for full-text search Set<String> traits = new HashSet<>(); // Set release field int release = -1; // default value if missing is -1 if (variantAnnotation.getAdditionalAttributes() != null && variantAnnotation.getAdditionalAttributes().get(GROUP_NAME.key()) != null) { String releaseStr = variantAnnotation.getAdditionalAttributes().get(GROUP_NAME.key()).getAttribute().get(RELEASE.key()); // example: release = "2,3,4" if (StringUtils.isNotEmpty(releaseStr)) { releaseStr = releaseStr.split(",")[0]; if (StringUtils.isNumeric(releaseStr)) { release = Integer.parseInt(releaseStr); } } } variantSearchModel.setRelease(release); // Add cytoband names if (variantAnnotation.getCytoband() != null) { for (Cytoband cytoband : variantAnnotation.getCytoband()) { xrefs.add(cytoband.getChromosome() + cytoband.getName()); } } // Add all XRefs coming from the variant annotation if (variantAnnotation.getXrefs() != null && !variantAnnotation.getXrefs().isEmpty()) { variantAnnotation.getXrefs().forEach(xref -> { if (xref != null) { xrefs.add(xref.getId()); } }); } // Add all HGVS coming from the variant annotation if (ListUtils.isNotEmpty(variantAnnotation.getHgvs())) { xrefs.addAll(variantAnnotation.getHgvs()); } // Set Genes and Consequence Types and create Other list to insert transcript info (biotype, protein, ariant annotation,...) List<ConsequenceType> consequenceTypes = variantAnnotation.getConsequenceTypes(); List<String> other = new ArrayList<>(); if (consequenceTypes != null) { // This MUST be a LinkedHashMap to keep the order of the elements! Map<String, Set<String>> genes = new LinkedHashMap<>(); Set<Integer> soAccessions = new LinkedHashSet<>(); Set<String> geneToSOAccessions = new LinkedHashSet<>(); Set<String> biotypes = new LinkedHashSet<>(); for (ConsequenceType conseqType : consequenceTypes) { StringBuilder trans = new StringBuilder(); // Set genes and biotypes if exist if (StringUtils.isNotEmpty(conseqType.getGeneName())) { // One gene can contain several transcripts and therefore several Consequence Types if (!genes.containsKey(conseqType.getGeneName())) { genes.put(conseqType.getGeneName(), new LinkedHashSet<>()); } // DO NOT change the order of the following code genes.get(conseqType.getGeneName()).add(conseqType.getGeneName()); genes.get(conseqType.getGeneName()).add(conseqType.getEnsemblGeneId()); genes.get(conseqType.getGeneName()).add(conseqType.getEnsemblTranscriptId()); if (StringUtils.isNotEmpty(conseqType.getEnsemblTranscriptId())) { trans.append("TRANS").append(FIELD_SEP).append(conseqType.getEnsemblTranscriptId()); trans.append(FIELD_SEP).append(StringUtils.isEmpty(conseqType.getBiotype()) ? "" : conseqType.getBiotype()); trans.append(FIELD_SEP); if (ListUtils.isNotEmpty(conseqType.getTranscriptAnnotationFlags())) { trans.append(StringUtils.join(conseqType.getTranscriptAnnotationFlags(), ",")); } } xrefs.add(conseqType.getGeneName()); xrefs.add(conseqType.getEnsemblGeneId()); xrefs.add(conseqType.getEnsemblTranscriptId()); if (StringUtils.isNotEmpty(conseqType.getBiotype())) { biotypes.add(conseqType.getBiotype()); // Add the combination of Gene and Biotype, this will prevent variants to be returned when they overlap // two different genes where the overlapping gene has the wanted Biotype. geneToSOAccessions.add(conseqType.getGeneName() + "_" + conseqType.getBiotype()); geneToSOAccessions.add(conseqType.getEnsemblGeneId() + "_" + conseqType.getBiotype()); geneToSOAccessions.add(conseqType.getEnsemblTranscriptId() + "_" + conseqType.getBiotype()); } } // Remove 'SO:' prefix to Store SO Accessions as integers and also store the gene - SO acc relation for (SequenceOntologyTerm sequenceOntologyTerm : conseqType.getSequenceOntologyTerms()) { int soIdInt = Integer.parseInt(sequenceOntologyTerm.getAccession().substring(3)); soAccessions.add(soIdInt); if (StringUtils.isNotEmpty(conseqType.getGeneName())) { geneToSOAccessions.add(conseqType.getGeneName() + "_" + soIdInt); geneToSOAccessions.add(conseqType.getEnsemblGeneId() + "_" + soIdInt); geneToSOAccessions.add(conseqType.getEnsemblTranscriptId() + "_" + soIdInt); if (StringUtils.isNotEmpty(conseqType.getBiotype())) { geneToSOAccessions.add(conseqType.getGeneName() + "_" + conseqType.getBiotype() + "_" + soIdInt); geneToSOAccessions.add(conseqType.getEnsemblGeneId() + "_" + conseqType.getBiotype() + "_" + soIdInt); geneToSOAccessions.add(conseqType.getEnsemblTranscriptId() + "_" + conseqType.getBiotype() + "_" + soIdInt); // This is useful when no gene or transcript is passed, for example we want 'LoF' in real 'protein_coding' geneToSOAccessions.add(conseqType.getBiotype() + "_" + soIdInt); } // Add a combination with the transcript flag if (conseqType.getTranscriptAnnotationFlags() != null) { for (String transcriptFlag : conseqType.getTranscriptAnnotationFlags()) { if (transcriptFlag.equalsIgnoreCase("basic") || transcriptFlag.equalsIgnoreCase("CCDS")) { geneToSOAccessions.add(conseqType.getGeneName() + "_" + soIdInt + "_" + transcriptFlag); geneToSOAccessions.add(conseqType.getEnsemblGeneId() + "_" + soIdInt + "_" + transcriptFlag); geneToSOAccessions.add(conseqType.getEnsemblTranscriptId() + "_" + soIdInt + "_" + transcriptFlag); } // This is useful when no gene or transcript is used, for example we want 'LoF' in 'basic' transcripts geneToSOAccessions.add(soIdInt + "_" + transcriptFlag); } } } } // if (StringUtils.isNotEmpty(conseqType.getCodon()) || (conseqType.getCdnaPosition() != null && conseqType.getCdnaPosition() > 0) || (conseqType.getCdsPosition() != null && conseqType.getCdsPosition() > 0)) { if (trans.length() == 0) { // Sanity check logger.warn("Codon information without Ensembl transcript ID"); } else { trans.append(FIELD_SEP) .append(conseqType.getCdnaPosition() == null ? 0 : conseqType.getCdnaPosition()) .append(FIELD_SEP) .append(conseqType.getCdsPosition() == null ? 0 : conseqType.getCdsPosition()) .append(FIELD_SEP) .append(StringUtils.isNotEmpty(conseqType.getCodon()) ? conseqType.getCodon() : ""); } } if (conseqType.getProteinVariantAnnotation() != null) { ProteinVariantAnnotation protVarAnnotation = conseqType.getProteinVariantAnnotation(); // Add UniProt accession, name and ID to xrefs trans.append(FIELD_SEP); if (StringUtils.isNotEmpty(protVarAnnotation.getUniprotAccession())) { trans.append(protVarAnnotation.getUniprotAccession()); xrefs.add(protVarAnnotation.getUniprotAccession()); } trans.append(FIELD_SEP); if (StringUtils.isNotEmpty(protVarAnnotation.getUniprotName())) { trans.append(protVarAnnotation.getUniprotName()); xrefs.add(protVarAnnotation.getUniprotName()); } trans.append(FIELD_SEP); if (StringUtils.isNotEmpty(protVarAnnotation.getUniprotVariantId())) { trans.append(protVarAnnotation.getUniprotVariantId()); xrefs.add(protVarAnnotation.getUniprotVariantId()); } trans.append(FIELD_SEP).append(protVarAnnotation.getPosition() == null ? 0 : protVarAnnotation.getPosition()); trans.append(FIELD_SEP); if (StringUtils.isNotEmpty(protVarAnnotation.getReference()) && StringUtils.isNotEmpty(protVarAnnotation.getAlternate())) { trans.append(protVarAnnotation.getReference()).append("/") .append(protVarAnnotation.getAlternate()); } // Create transcript info and add it into the other list Score sift = getScore(protVarAnnotation.getSubstitutionScores(), "sift"); Score polyph = getScore(protVarAnnotation.getSubstitutionScores(), "polyphen"); trans.append(FIELD_SEP); if (sift != null) { trans.append(sift.getScore()).append(FIELD_SEP).append(sift.getDescription()); } else { trans.append(FIELD_SEP); } trans.append(FIELD_SEP); if (polyph != null) { trans.append(polyph.getScore()).append(FIELD_SEP).append(polyph.getDescription()); } else { trans.append(FIELD_SEP); } // Add keywords to and Features to traits if (protVarAnnotation.getKeywords() != null) { for (String keyword : protVarAnnotation.getKeywords()) { traits.add("KW" + FIELD_SEP + protVarAnnotation.getUniprotAccession() + FIELD_SEP + keyword); } } // Add protein domains if (protVarAnnotation.getFeatures() != null) { for (ProteinFeature proteinFeature : protVarAnnotation.getFeatures()) { if (StringUtils.isNotEmpty(proteinFeature.getId())) { // We store them in xrefs and traits, the number of these IDs is very small xrefs.add(proteinFeature.getId()); traits.add("PD" + FIELD_SEP + proteinFeature.getId() + FIELD_SEP + proteinFeature.getDescription()); } } } } if (StringUtils.isNotEmpty(conseqType.getEnsemblTranscriptId()) && trans.length() > 0) { other.add(trans.toString()); } } // We store the accumulated data genes.forEach((s, strings) -> variantSearchModel.getGenes().addAll(strings)); variantSearchModel.setSoAcc(new ArrayList<>(soAccessions)); variantSearchModel.setGeneToSoAcc(new ArrayList<>(geneToSOAccessions)); variantSearchModel.setBiotypes(new ArrayList<>(biotypes)); // We now process Sift and Polyphen setProteinScores(consequenceTypes, variantSearchModel); } // Set Populations frequencies if (variantAnnotation.getPopulationFrequencies() != null) { Map<String, Float> populationFrequencies = new HashMap<>(); for (PopulationFrequency populationFrequency : variantAnnotation.getPopulationFrequencies()) { populationFrequencies.put("popFreq" + VariantSearchUtils.FIELD_SEPARATOR + populationFrequency.getStudy() + VariantSearchUtils.FIELD_SEPARATOR + populationFrequency.getPopulation(), populationFrequency.getAltAlleleFreq()); } // Add 0.0 frequency for common populations, this will allow to skip a NON EXIST query and improve performance populationFrequencies.putIfAbsent("popFreq" + VariantSearchUtils.FIELD_SEPARATOR + "1kG_phase3__ALL", 0.0f); populationFrequencies.putIfAbsent("popFreq" + VariantSearchUtils.FIELD_SEPARATOR + "GNOMAD_EXOMES__ALL", 0.0f); populationFrequencies.putIfAbsent("popFreq" + VariantSearchUtils.FIELD_SEPARATOR + "GNOMAD_GENOMES__ALL", 0.0f); populationFrequencies.putIfAbsent("popFreq" + VariantSearchUtils.FIELD_SEPARATOR + "ESP6500__ALL", 0.0f); populationFrequencies.putIfAbsent("popFreq" + VariantSearchUtils.FIELD_SEPARATOR + "UK10K__ALL", 0.0f); populationFrequencies.putIfAbsent("popFreq" + VariantSearchUtils.FIELD_SEPARATOR + "GONL__ALL", 0.0f); if (!populationFrequencies.isEmpty()) { variantSearchModel.setPopFreq(populationFrequencies); } } // Set Conservation scores if (variantAnnotation.getConservation() != null) { for (Score score : variantAnnotation.getConservation()) { switch (score.getSource()) { case "phastCons": variantSearchModel.setPhastCons(score.getScore()); break; case "phylop": variantSearchModel.setPhylop(score.getScore()); break; case "gerp": variantSearchModel.setGerp(score.getScore()); break; default: logger.warn("Unknown 'conservation' source: score.getSource() = " + score.getSource()); break; } } } // Set CADD if (variantAnnotation.getFunctionalScore() != null) { for (Score score : variantAnnotation.getFunctionalScore()) { switch (score.getSource()) { case "cadd_raw": case "caddRaw": variantSearchModel.setCaddRaw(score.getScore()); break; case "cadd_scaled": case "caddScaled": variantSearchModel.setCaddScaled(score.getScore()); break; default: logger.warn("Unknown 'functional score' source: score.getSource() = " + score.getSource()); break; } } } // Set variant traits: ClinVar, Cosmic, HPO, ... if (variantAnnotation.getVariantTraitAssociation() != null) { if (variantAnnotation.getVariantTraitAssociation().getClinvar() != null) { variantAnnotation.getVariantTraitAssociation().getClinvar() .forEach(cv -> { xrefs.add(cv.getAccession()); cv.getTraits().forEach(cvt -> traits.add("CV" + FIELD_SEP + cv.getAccession() + FIELD_SEP + cvt + FIELD_SEP + "cs:" + cv.getClinicalSignificance())); }); } if (variantAnnotation.getVariantTraitAssociation().getCosmic() != null) { variantAnnotation.getVariantTraitAssociation().getCosmic() .forEach(cosmic -> { xrefs.add(cosmic.getMutationId()); traits.add("CM" + FIELD_SEP + cosmic.getMutationId() + FIELD_SEP + cosmic.getPrimaryHistology() + FIELD_SEP + cosmic.getHistologySubtype()); }); } } if (variantAnnotation.getGeneTraitAssociation() != null && CollectionUtils.isNotEmpty(variantAnnotation.getGeneTraitAssociation())) { for (GeneTraitAssociation geneTraitAssociation : variantAnnotation.getGeneTraitAssociation()) { switch (geneTraitAssociation.getSource().toLowerCase()) { case "hpo": traits.add("HP" + FIELD_SEP + geneTraitAssociation.getHpo() + FIELD_SEP + geneTraitAssociation.getId() + " -- " + geneTraitAssociation.getName()); break; // case "disgenet": // traits.add("DG -- " + geneTraitAssociation.getId() + " -- " + geneTraitAssociation.getName()); // break; default: break; } } } variantSearchModel.setTraits(new ArrayList<>(traits)); // Now we fill other field if (StringUtils.isNotEmpty(variantAnnotation.getDisplayConsequenceType())) { other.add("DCT" + FIELD_SEP + variantAnnotation.getDisplayConsequenceType()); } if (variantAnnotation.getHgvs() != null) { for (String hgvs : variantAnnotation.getHgvs()) { other.add("HGVS" + FIELD_SEP + hgvs); } } if (variantAnnotation.getCytoband() != null) { for (Cytoband cytoband : variantAnnotation.getCytoband()) { other.add("CB" + FIELD_SEP + cytoband.getName() + FIELD_SEP + cytoband.getStain() + FIELD_SEP + cytoband.getStart() + FIELD_SEP + cytoband.getEnd()); } } if (variantAnnotation.getRepeat() != null) { for (Repeat repeat : variantAnnotation.getRepeat()) { other.add("RP" + FIELD_SEP + repeat.getId() + FIELD_SEP + repeat.getSource() + FIELD_SEP + repeat.getCopyNumber() + FIELD_SEP + repeat.getPercentageMatch() + FIELD_SEP + repeat.getStart() + FIELD_SEP + repeat.getEnd()); } } variantSearchModel.setOther(other); } variantSearchModel.setXrefs(new ArrayList<>(xrefs)); return variantSearchModel; } public static String studyIdToSearchModel(String studyId) { return studyId.substring(studyId.lastIndexOf(':') + 1); } public List<VariantSearchModel> convertListToStorageType(List<Variant> variants) { List<VariantSearchModel> variantSearchModelList = new ArrayList<>(variants.size()); for (Variant variant : variants) { VariantSearchModel variantSearchModel = convertToStorageType(variant); if (variantSearchModel.getId() != null) { variantSearchModelList.add(variantSearchModel); } } return variantSearchModelList; } /** * Retrieve the protein substitution scores and descriptions from a consequence * type annotation: sift or polyphen, and update the variant search model. * * @param consequenceTypes List of consequence type target * @param variantSearchModel Variant search model to update */ private void setProteinScores(List<ConsequenceType> consequenceTypes, VariantSearchModel variantSearchModel) { double sift = 10; String siftDesc = ""; double polyphen = MISSING_VALUE; String polyphenDesc = ""; if (consequenceTypes != null) { for (ConsequenceType consequenceType : consequenceTypes) { if (consequenceType.getProteinVariantAnnotation() != null && consequenceType.getProteinVariantAnnotation().getSubstitutionScores() != null) { for (Score score : consequenceType.getProteinVariantAnnotation().getSubstitutionScores()) { String source = score.getSource(); if (("sift").equals(source)) { if (score.getScore() < sift) { sift = score.getScore(); siftDesc = score.getDescription(); } } else if (("polyphen").equals(source)) { if (score.getScore() > polyphen) { polyphen = score.getScore(); polyphenDesc = score.getDescription(); } } } } } } // If sift not exist we set it to -100.0 if (ArrayUtils.equals(sift, 10)) { sift = MISSING_VALUE; } // set scores variantSearchModel.setSift(sift); variantSearchModel.setPolyphen(polyphen); // set descriptions variantSearchModel.setSiftDesc(siftDesc); variantSearchModel.setPolyphenDesc(polyphenDesc); } private Score getScore(List<Score> scores, String source) { if (ListUtils.isNotEmpty(scores) && StringUtils.isNotEmpty(source)) { for (Score score: scores) { if (source.equals(score.getSource())) { return score; } } } return null; } private Double parseDouble(String value, Double defaultValue) { return parseDouble(value, defaultValue, null); } private Double parseDouble(String value, Double defaultValue, String message) { try { return Double.parseDouble(value); } catch (NumberFormatException e) { if (message != null) { logger.warn(message + ". Value: '" + value + "'"); } return defaultValue; } } private Float parseFloat(String value, Float defaultValue) { return parseFloat(value, defaultValue, null); } private Float parseFloat(String value, Float defaultValue, String message) { try { return Float.parseFloat(value); } catch (NumberFormatException e) { if (message != null) { logger.warn(message + ". Value: '" + value + "'"); } return defaultValue; } } }
storage: remove non basic or CCDS transcirpt flags in all cases. Remove ESP6500, UK10K and GONL default values
opencga-storage/opencga-storage-core/src/main/java/org/opencb/opencga/storage/core/variant/search/VariantSearchToVariantConverter.java
storage: remove non basic or CCDS transcirpt flags in all cases. Remove ESP6500, UK10K and GONL default values
Java
apache-2.0
2ea42fe7cc13c8355c068458d665f0a6e2385aa0
0
wso2/analytics-apim,ksdperera/analytics-apim,maheshakya/analytics-apim,lakmali/analytics-apim-1,ksdperera/analytics-apim,lakmali/analytics-apim-1,rajeev3001/analytics-apim,maheshakya/analytics-apim,ksdperera/analytics-apim,maheshakya/analytics-apim,wso2/analytics-apim,rajeev3001/analytics-apim,maheshakya/analytics-apim,maheshakya/analytics-apim,ChamNDeSilva/analytics-apim,ksdperera/analytics-apim,lakmali/analytics-apim-1,lakmali/analytics-apim-1,wso2/analytics-apim,ksdperera/analytics-apim,ChamNDeSilva/analytics-apim,ChamNDeSilva/analytics-apim,rajeev3001/analytics-apim,ChamNDeSilva/analytics-apim,rajeev3001/analytics-apim,ChamNDeSilva/analytics-apim,lakmali/analytics-apim-1,rajeev3001/analytics-apim
/* * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.analytics.apim.integration.tests.apim.analytics; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.wso2.carbon.event.simulator.stub.types.EventDto; public class AbnormalResponseAndBackendTimeTestCase extends APIMAnalyticsBaseTestCase { private static final Log log = LogFactory.getLog(AbnormalResponseAndBackendTimeTestCase.class); private final String STREAM_NAME = "org.wso2.apimgt.statistics.response"; private final String STREAM_VERSION = "1.1.0"; private final String TEST_RESOURCE_PATH = "abnormalResponseAndBackendTime"; private final String ABNORMAL_RESPONSE_TIME_PUBLISHER_FILE = "logger_abnormalResponseTime.xml"; private final String ABNORMAL_BACKEND_TIME_PUBLISHER_FILE = "logger_abnormalBackendTime.xml"; private final String SPARK_SCRIPT = "APIMAnalytics-ResponseStatGenerator"; private final String RESPONSE_PERCENTILE_TABLE = "ORG_WSO2_ANALYTICS_APIM_RESPONSEPERCENTILE"; private final String EXECUTION_PLAN_NAME = "APIMAnalytics-AbnormalResponseAndBackendTimeDetection"; private final int MAX_TRIES = 20; @BeforeClass(alwaysRun = true) public void setup() throws Exception { super.init(); if (isTableExist(-1234, STREAM_NAME.replace('.', '_'))) { deleteData(-1234, STREAM_NAME.replace('.', '_')); } if (isTableExist(-1234, RESPONSE_PERCENTILE_TABLE)) { deleteData(-1234, RESPONSE_PERCENTILE_TABLE); } // deploy the publisher xml files deployPublisher(TEST_RESOURCE_PATH, ABNORMAL_BACKEND_TIME_PUBLISHER_FILE); deployPublisher(TEST_RESOURCE_PATH, ABNORMAL_RESPONSE_TIME_PUBLISHER_FILE); editActiveExecutionPlan(getActiveExecutionPlan(EXECUTION_PLAN_NAME),EXECUTION_PLAN_NAME); } @AfterClass(alwaysRun = true) public void cleanup() throws Exception { if (isTableExist(-1234, STREAM_NAME.replace('.', '_'))) { deleteData(-1234, STREAM_NAME.replace('.', '_')); } if (isTableExist(-1234, RESPONSE_PERCENTILE_TABLE)) { deleteData(-1234, RESPONSE_PERCENTILE_TABLE); } // undeploy the publishers undeployPublisher(ABNORMAL_BACKEND_TIME_PUBLISHER_FILE); undeployPublisher(ABNORMAL_RESPONSE_TIME_PUBLISHER_FILE); } @Test(groups = "wso2.analytics.apim", description = "Tests if the Spark script is deployed") public void testResponseStatGeneratorSparkScriptDeployment() throws Exception { Assert.assertTrue(isSparkScriptExists(SPARK_SCRIPT), "org_wso2_analytics_apim_response_stat_generator spark script is not deployed!"); } @Test(groups = "wso2.analytics.apim", description = "Test if the Simulation data has been published" , dependsOnMethods = "testResponseStatGeneratorSparkScriptDeployment") public void testResponseSimulationDataSent() throws Exception { //publish events pubishEventsFromCSV(TEST_RESOURCE_PATH, "sim.csv", getStreamId(STREAM_NAME, STREAM_VERSION), 100); pubishEventsFromCSV(TEST_RESOURCE_PATH, "sim.csv", getStreamId(STREAM_NAME, STREAM_VERSION), 100); int i = 0; long currentResponseEventCount = 0; boolean eventsPublished = false; while (i < MAX_TRIES) { Thread.sleep(5000); currentResponseEventCount = getRecordCount(-1234, STREAM_NAME.replace('.', '_')); eventsPublished = currentResponseEventCount >= 11; if (eventsPublished) { break; } i++; } Assert.assertTrue(eventsPublished, "Simulation events did not get published, expected entry count:11 but found: "+currentResponseEventCount+ "!"); } @Test(groups = "wso2.analytics.apim", description = "Test org_wso2_analytics_apim_response_stat_generator Spark Script execution" , dependsOnMethods = "testResponseSimulationDataSent") public void testResponseStatGeneratorSparkScriptExecution() throws Exception { //run the script executeSparkScript(SPARK_SCRIPT); int i = 0; boolean scriptExecuted = false; long percentileTableCount = 0; while (i < MAX_TRIES) { Thread.sleep(10000); percentileTableCount = getRecordCount(-1234, RESPONSE_PERCENTILE_TABLE); scriptExecuted = (percentileTableCount >= 1); if (scriptExecuted) { break; } i++; } Assert.assertTrue(scriptExecuted, "Spark script did not execute as expected, expected entry count:1 but found: "+percentileTableCount+ "!"); } @Test(groups = "wso2.analytics.apim", description = "Test Abnormal ResponseTime Alert", dependsOnMethods = "testResponseStatGeneratorSparkScriptExecution") public void testAbnormalResponseTimeAlert() throws Exception { logViewerClient.clearLogs(); EventDto eventDto = new EventDto(); eventDto.setEventStreamId(getStreamId(STREAM_NAME, STREAM_VERSION)); eventDto.setAttributeValues( new String[]{"external", "s8SWbnmzQEgzMIsol7AHt9cjhEsa", "/calc/1.0", "CalculatorAPI:v1.0", "CalculatorAPI", "/add?x=12&y=3", "/add", "GET", "1.0", "1", "220", "7", "5", "admin@carbon.super", "1456894602386", "carbon.super", "192.168.66.1", "admin@carbon.super", "DefaultApplication", "1", "False", "0", "https-8243", "200"} ); publishEvent(eventDto); publishEvent(eventDto); boolean abnormalResponseTimeAlertTriggered = isAlertReceived(0, "Unique ID: logger_abnormalResponseTime", 5, 1000); Assert.assertTrue(abnormalResponseTimeAlertTriggered, "Abnormal ResponseTime Alert event not received!"); } @Test(groups = "wso2.analytics.apim", description = "Test Abnormal BackendTime Alert", dependsOnMethods = "testResponseStatGeneratorSparkScriptExecution") public void testAbnormalBackendTimeAlert() throws Exception { logViewerClient.clearLogs(); EventDto eventDto = new EventDto(); eventDto.setEventStreamId(getStreamId(STREAM_NAME, STREAM_VERSION)); eventDto.setAttributeValues( new String[]{"external", "s8SWbnmzQEgzMIsol7AHt9cjhEsa", "/calc/1.0", "CalculatorAPI:v1.0", "CalculatorAPI", "/add?x=12&y=3", "/add", "GET", "1.0", "1", "12", "7", "165", "admin@carbon.super", "1456894602386", "carbon.super", "192.168.66.1", "admin@carbon.super", "DefaultApplication", "1", "False", "0", "https-8243", "200"} ); publishEvent(eventDto); publishEvent(eventDto); boolean abnormalBackendTimeAlertTriggered = isAlertReceived(0, "Unique ID: logger_abnormalBackendTime", 5, 1000); Assert.assertTrue(abnormalBackendTimeAlertTriggered, "Abnormal BackendTime Alert event not received!"); } }
product/integration/tests-integration/src/test/java/org/wso2/analytics/apim/integration/tests/apim/analytics/AbnormalResponseAndBackendTimeTestCase.java
/* * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.analytics.apim.integration.tests.apim.analytics; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.wso2.carbon.event.simulator.stub.types.EventDto; public class AbnormalResponseAndBackendTimeTestCase extends APIMAnalyticsBaseTestCase { private static final Log log = LogFactory.getLog(AbnormalResponseAndBackendTimeTestCase.class); private final String STREAM_NAME = "org.wso2.apimgt.statistics.response"; private final String STREAM_VERSION = "1.1.0"; private final String TEST_RESOURCE_PATH = "abnormalResponseAndBackendTime"; private final String ABNORMAL_RESPONSE_TIME_PUBLISHER_FILE = "logger_abnormalResponseTime.xml"; private final String ABNORMAL_BACKEND_TIME_PUBLISHER_FILE = "logger_abnormalBackendTime.xml"; private final String SPARK_SCRIPT = "APIMAnalytics-ResponseStatGenerator"; private final String RESPONSE_PERCENTILE_TABLE = "ORG_WSO2_ANALYTICS_APIM_RESPONSEPERCENTILE"; private final String EXECUTION_PLAN_NAME = "APIMAnalytics-AbnormalResponseAndBackendTimeDetection"; private final int MAX_TRIES = 20; @BeforeClass(alwaysRun = true) public void setup() throws Exception { super.init(); if (isTableExist(-1234, STREAM_NAME.replace('.', '_'))) { deleteData(-1234, STREAM_NAME.replace('.', '_')); } if (isTableExist(-1234, RESPONSE_PERCENTILE_TABLE)) { deleteData(-1234, RESPONSE_PERCENTILE_TABLE); } // deploy the publisher xml files deployPublisher(TEST_RESOURCE_PATH, ABNORMAL_BACKEND_TIME_PUBLISHER_FILE); deployPublisher(TEST_RESOURCE_PATH, ABNORMAL_RESPONSE_TIME_PUBLISHER_FILE); editActiveExecutionPlan(getActiveExecutionPlan(EXECUTION_PLAN_NAME),EXECUTION_PLAN_NAME); } @AfterClass(alwaysRun = true) public void cleanup() throws Exception { if (isTableExist(-1234, STREAM_NAME.replace('.', '_'))) { deleteData(-1234, STREAM_NAME.replace('.', '_')); } if (isTableExist(-1234, RESPONSE_PERCENTILE_TABLE)) { deleteData(-1234, RESPONSE_PERCENTILE_TABLE); } // undeploy the publishers undeployPublisher(ABNORMAL_BACKEND_TIME_PUBLISHER_FILE); undeployPublisher(ABNORMAL_RESPONSE_TIME_PUBLISHER_FILE); } @Test(groups = "wso2.analytics.apim", description = "Tests if the Spark script is deployed") public void testResponseStatGeneratorSparkScriptDeployment() throws Exception { Assert.assertTrue(isSparkScriptExists(SPARK_SCRIPT), "org_wso2_analytics_apim_response_stat_generator spark script is not deployed!"); } @Test(groups = "wso2.analytics.apim", description = "Test if the Simulation data has been published" , dependsOnMethods = "testResponseStatGeneratorSparkScriptDeployment") public void testResponseSimulationDataSent() throws Exception { //publish events pubishEventsFromCSV(TEST_RESOURCE_PATH, "sim.csv", getStreamId(STREAM_NAME, STREAM_VERSION), 100); pubishEventsFromCSV(TEST_RESOURCE_PATH, "sim.csv", getStreamId(STREAM_NAME, STREAM_VERSION), 100); int i = 0; long currentResponseEventCount = 0; boolean eventsPublished = false; while (i < MAX_TRIES) { Thread.sleep(5000); currentResponseEventCount = getRecordCount(-1234, STREAM_NAME.replace('.', '_')); eventsPublished = currentResponseEventCount >= 11; if (eventsPublished) { break; } i++; } Assert.assertTrue(eventsPublished, "Simulation events did not get published, expected entry count:11 but found: "+currentResponseEventCount+ "!"); } @Test(groups = "wso2.analytics.apim", description = "Test org_wso2_analytics_apim_response_stat_generator Spark Script execution" , dependsOnMethods = "testResponseSimulationDataSent") public void testResponseStatGeneratorSparkScriptExecution() throws Exception { //run the script executeSparkScript(SPARK_SCRIPT); int i = 0; boolean scriptExecuted = false; long percentileTableCount = 0; while (i < MAX_TRIES) { Thread.sleep(10000); percentileTableCount = getRecordCount(-1234, RESPONSE_PERCENTILE_TABLE); scriptExecuted = (percentileTableCount >= 1); if (scriptExecuted) { break; } i++; } Assert.assertTrue(scriptExecuted, "Spark script did not execute as expected, expected entry count:5 but found: "+percentileTableCount+ "!"); } @Test(groups = "wso2.analytics.apim", description = "Test Abnormal ResponseTime Alert", dependsOnMethods = "testResponseStatGeneratorSparkScriptExecution") public void testAbnormalResponseTimeAlert() throws Exception { logViewerClient.clearLogs(); EventDto eventDto = new EventDto(); eventDto.setEventStreamId(getStreamId(STREAM_NAME, STREAM_VERSION)); eventDto.setAttributeValues( new String[]{"external", "s8SWbnmzQEgzMIsol7AHt9cjhEsa", "/calc/1.0", "CalculatorAPI:v1.0", "CalculatorAPI", "/add?x=12&y=3", "/add", "GET", "1.0", "1", "220", "7", "5", "admin@carbon.super", "1456894602386", "carbon.super", "192.168.66.1", "admin@carbon.super", "DefaultApplication", "1", "False", "0", "https-8243", "200"} ); publishEvent(eventDto); publishEvent(eventDto); boolean abnormalResponseTimeAlertTriggered = isAlertReceived(0, "Unique ID: logger_abnormalResponseTime", 5, 1000); Assert.assertTrue(abnormalResponseTimeAlertTriggered, "Abnormal ResponseTime Alert event not received!"); } @Test(groups = "wso2.analytics.apim", description = "Test Abnormal BackendTime Alert", dependsOnMethods = "testResponseStatGeneratorSparkScriptExecution") public void testAbnormalBackendTimeAlert() throws Exception { logViewerClient.clearLogs(); EventDto eventDto = new EventDto(); eventDto.setEventStreamId(getStreamId(STREAM_NAME, STREAM_VERSION)); eventDto.setAttributeValues( new String[]{"external", "s8SWbnmzQEgzMIsol7AHt9cjhEsa", "/calc/1.0", "CalculatorAPI:v1.0", "CalculatorAPI", "/add?x=12&y=3", "/add", "GET", "1.0", "1", "12", "7", "165", "admin@carbon.super", "1456894602386", "carbon.super", "192.168.66.1", "admin@carbon.super", "DefaultApplication", "1", "False", "0", "https-8243", "200"} ); publishEvent(eventDto); publishEvent(eventDto); boolean abnormalBackendTimeAlertTriggered = isAlertReceived(0, "Unique ID: logger_abnormalBackendTime", 5, 1000); Assert.assertTrue(abnormalBackendTimeAlertTriggered, "Abnormal BackendTime Alert event not received!"); } }
Fixing assert message of testResponseStatGeneratorSparkScriptExecution
product/integration/tests-integration/src/test/java/org/wso2/analytics/apim/integration/tests/apim/analytics/AbnormalResponseAndBackendTimeTestCase.java
Fixing assert message of testResponseStatGeneratorSparkScriptExecution
Java
apache-2.0
1aca99eab14e0f6632a2b13d06db68b25d92e1b3
0
jaamsim/jaamsim,jaamsim/jaamsim,jaamsim/jaamsim,jaamsim/jaamsim
/* * JaamSim Discrete Event Simulation * Copyright (C) 2012 Ausenco Engineering Canada Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package com.jaamsim.render; //import com.jaamsim.math.*; import java.awt.Font; import java.awt.Frame; import java.awt.Image; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.awt.image.BufferedImage; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.nio.IntBuffer; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.EnumMap; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Queue; import java.util.concurrent.atomic.AtomicBoolean; import javax.media.opengl.DebugGL2; import javax.media.opengl.GL; import javax.media.opengl.GL2GL3; import javax.media.opengl.GLAutoDrawable; import javax.media.opengl.GLCapabilities; import javax.media.opengl.GLContext; import javax.media.opengl.GLEventListener; import javax.media.opengl.GLException; import javax.media.opengl.GLProfile; import com.jaamsim.DisplayModels.DisplayModel; import com.jaamsim.MeshFiles.MeshData; import com.jaamsim.font.OverlayString; import com.jaamsim.font.TessFont; import com.jaamsim.math.AABB; import com.jaamsim.math.Color4d; import com.jaamsim.math.ConvexHull; import com.jaamsim.math.Ray; import com.jaamsim.math.Vec4d; import com.jaamsim.render.util.ExceptionLogger; import com.jogamp.newt.event.WindowEvent; import com.jogamp.newt.event.WindowListener; import com.jogamp.newt.event.WindowUpdateEvent; import com.jogamp.newt.opengl.GLWindow; import com.sandwell.JavaSimulation.ColourInput; /** * The central renderer for JaamSim Renderer, Contains references to all context * specific data (like shader caches) * * @author Matt.Chudleigh * */ public class Renderer { public enum ShaderHandle { MESH, FONT, HULL, OVERLAY_FONT, OVERLAY_FLAT, DEBUG } static private Object idLock = new Object(); static private int _nextID = 1; /** * Get a system wide unique ID * @return */ public static int getAssetID() { synchronized(idLock) { return _nextID++; } } private static boolean RENDER_DEBUG_INFO = false; private static boolean USE_DEBUG_GL = true; private EnumMap<ShaderHandle, Shader> _shaders; // Display _display = null; // Screen _screen = null; private GLContext _sharedContext = null; Map<Integer, Integer> _sharedVaoMap = new HashMap<Integer, Integer>(); GLWindow _dummyWindow; private GLCapabilities _caps = null; private TexCache _texCache = new TexCache(this); // An initalization time flag specifying if the 'safest' graphical techniques should be used private boolean _safeGraphics; private final Thread _renderThread; private final Object _rendererLock = new Object(); private final Map<MeshProtoKey, MeshProto> _protoCache; private final Map<TessFontKey, TessFont> _fontCache; private final Map<ConvexHullKey, HullProto> _hullCache; private final HashMap<Integer, RenderWindow> _openWindows; private final Queue<RenderMessage> _renderMessages = new ArrayDeque<RenderMessage>(); private final AtomicBoolean _displayNeeded = new AtomicBoolean(true); private final AtomicBoolean _initialized = new AtomicBoolean(false); private final AtomicBoolean _shutdown = new AtomicBoolean(false); private final AtomicBoolean _fatalError = new AtomicBoolean(false); private String _errorString; // This is the string that caused the fatal error private StackTraceElement[] _fatalStackTrace; // the stack trace from the fatal error private final ExceptionLogger _exceptionLogger; private TessFontKey _defaultFontKey = new TessFontKey(Font.SANS_SERIF, Font.PLAIN); private TessFontKey _defaultBoldFontKey = new TessFontKey(Font.SANS_SERIF, Font.BOLD); private final Object _sceneLock = new Object(); private ArrayList<RenderProxy> _proxyScene = new ArrayList<RenderProxy>(); private boolean _allowDelayedTextures; private double _sceneTimeMS; private double _loopTimeMS; private long _usedVRAM = 0; // This may not be the best way to cache this //private GL2GL3 _currentGL = null; private GLContext _drawContext = null; // A cache of the current scene, needed by the individual windows to render private ArrayList<Renderable> _currentScene = new ArrayList<Renderable>(); private ArrayList<OverlayRenderable> _currentOverlay = null; public Renderer(boolean safeGraphics) throws RenderException { _safeGraphics = safeGraphics; _protoCache = new HashMap<MeshProtoKey, MeshProto>(); _fontCache = new HashMap<TessFontKey, TessFont>(); _hullCache = new HashMap<ConvexHullKey, HullProto>(); _exceptionLogger = new ExceptionLogger(); _openWindows = new HashMap<Integer, RenderWindow>(); _renderThread = new Thread(new Runnable() { @Override public void run() { mainRenderLoop(); } }, "RenderThread"); _renderThread.start(); } private void mainRenderLoop() { //long startNanos = System.nanoTime(); try { // GLProfile.initSingleton(); GLProfile glp = GLProfile.get(GLProfile.GL2GL3); _caps = new GLCapabilities(glp); _caps.setSampleBuffers(true); _caps.setNumSamples(4); _caps.setDepthBits(24); // Create a dummy window _dummyWindow = GLWindow.create(_caps); _dummyWindow.setSize(128, 128); _dummyWindow.setPosition(-2000, -2000); // This is unfortunately necessary due to JOGL's (newt's?) involved // startup code // I can not find a way to make a context valid without a visible window _dummyWindow.setVisible(true); _sharedContext = _dummyWindow.getContext(); assert (_sharedContext != null); _dummyWindow.setVisible(false); // long endNanos = System.nanoTime(); // long ms = (endNanos - startNanos) /1000000L; // System.out.println("Creating shared context at:" + ms + "ms"); initSharedContext(); // Notify the main thread we're done synchronized (_initialized) { _initialized.set(true); _initialized.notifyAll(); } } catch (Exception e) { _fatalError.set(true); _errorString = e.getLocalizedMessage(); _fatalStackTrace = e.getStackTrace(); System.out.println("Renderer encountered a fatal error:"); e.printStackTrace(); } finally { if (_sharedContext != null && _sharedContext.isCurrent()) _sharedContext.release(); } // endNanos = System.nanoTime(); // ms = (endNanos - startNanos) /1000000L; // System.out.println("Started renderer loop after:" + ms + "ms"); long lastLoopEnd = System.nanoTime(); while (!_shutdown.get()) { try { // If a fatal error was encountered, clean up the renderer if (_fatalError.get()) { // We should clean up everything we can, then die try { for (Entry<Integer, RenderWindow> entry : _openWindows.entrySet()){ entry.getValue().getGLWindowRef().destroy(); entry.getValue().getAWTFrameRef().dispose(); } } catch(Exception e) {} // Ignore any exceptions, this is just a best effort cleanup try { _dummyWindow.destroy(); _sharedContext.destroy(); _dummyWindow = null; _sharedContext = null; _openWindows.clear(); _currentScene = null; _currentOverlay = null; _caps = null; _fontCache.clear(); _protoCache.clear(); _hullCache.clear(); _shaders.clear(); } catch (Exception e) { } break; // Exiting the loop will end the thread } // Run all render messages RenderMessage message; do { // Only lock the queue while reading messages, release it while // processing them message = null; synchronized (_renderMessages) { if (!_renderMessages.isEmpty()) { message = _renderMessages.remove(); } } if (message != null) { try { handleMessage(message); } catch (Throwable t) { // Log this error but continue processing logException(t); } } } while (!_renderMessages.isEmpty()); if (_displayNeeded.get()) { _displayNeeded.set(false); updateRenderableScene(); // Defensive copy the window list (in case a window is closed while we render) HashMap<Integer, RenderWindow> winds; synchronized (_openWindows) { winds = new HashMap<Integer, RenderWindow>(_openWindows); } for (RenderWindow wind : winds.values()) { try { GLContext context = wind.getGLWindowRef().getContext(); if (context != null && context.isCreated() && !_shutdown.get()) { wind.getGLWindowRef().display(); } } catch (Throwable t) { // Log it, but move on to the other windows logException(t); } } } long loopEnd = System.nanoTime(); _loopTimeMS = (loopEnd - lastLoopEnd) / 1000000; lastLoopEnd = loopEnd; try { synchronized (_displayNeeded) { if (!_displayNeeded.get()) { _displayNeeded.wait(); } } } catch (InterruptedException e) { // Let's loop anyway... } } catch (Throwable t) { // Any other unexpected exceptions... logException(t); } } } /** * Returns the shader object for this handle, should only be called from the render thread (during a render) * @param h * @return */ public Shader getShader(ShaderHandle h) { return _shaders.get(h); } /** * Returns the MeshProto for the supplied key, should only be called from the render thread (during a render) * @param key * @return */ public MeshProto getProto(MeshProtoKey key) { MeshProto proto = _protoCache.get(key); if (proto == null) { // This prototype needs to be lazily loaded loadMeshProtoImp(key); } return _protoCache.get(key); } public TessFont getTessFont(TessFontKey key) { if (!_fontCache.containsKey(key)) { loadTessFontImp(key); // Try lazy initialization for now } return _fontCache.get(key); } public HullProto getHullProto(ConvexHullKey key) { HullProto hp = _hullCache.get(key); if (hp == null) { loadHullImp(key); } return _hullCache.get(key); } public void setScene(ArrayList<RenderProxy> scene) { synchronized (_sceneLock) { _proxyScene = scene; } } public void queueRedraw() { _displayNeeded.set(true); synchronized(_displayNeeded) { _displayNeeded.notifyAll(); } } private void addRenderMessage(RenderMessage msg) { _renderMessages.add(msg); queueRedraw(); } public void setCameraInfoForWindow(int windowID, CameraInfo info) { synchronized (_renderMessages) { addRenderMessage(new SetCameraMessage(windowID, info)); } } private void setCameraInfoImp(SetCameraMessage mes) { synchronized (_openWindows) { RenderWindow w = _openWindows.get(mes.windowID); if (w != null) { w.getCameraRef().setInfo(mes.cameraInfo); } } } /** * Call this from any thread to shutdown the Renderer, will return * immediately but the renderer will shutdown after the next redraw */ public void shutdown() { _shutdown.set(true); } public GL2GL3 getGL() { return _drawContext.getGL().getGL2GL3(); } /** * Get a list of all the IDs of currently open windows * @return */ public ArrayList<Integer> getOpenWindowIDs() { synchronized(_openWindows) { ArrayList<Integer> ret = new ArrayList<Integer>(); for (int id : _openWindows.keySet()) { ret.add(id); } return ret; } } public String getWindowName(int windowID) { synchronized(_openWindows) { RenderWindow win = _openWindows.get(windowID); if (win == null) { return null; } return win.getName(); } } public Frame getAWTFrame(int windowID) { synchronized(_openWindows) { RenderWindow win = _openWindows.get(windowID); if (win == null) { return null; } return win.getAWTFrameRef(); } } public void focusWindow(int windowID) { synchronized(_openWindows) { RenderWindow win = _openWindows.get(windowID); if (win == null) { return; } win.getAWTFrameRef().setExtendedState(Frame.NORMAL); win.getAWTFrameRef().toFront(); } } /** * Construct a new window (a NEWT window specifically) * * @param width * @param height * @return */ private void createWindowImp(CreateWindowMessage message) { RenderGLListener listener = new RenderGLListener(); // Set the listeners windowID before creating the window to ensure it never gets a callback before the // ID is valid message.listener.setWindowID(message.windowID); RenderWindow window = new RenderWindow(message.x, message.y, message.width, message.height, message.title, message.name, _sharedContext, _caps, listener, message.icon, message.windowID, message.viewID, message.listener); listener.setWindow(window); synchronized (_openWindows) { _openWindows.put(message.windowID, window); } GLWindowListener wl = new GLWindowListener(window.getWindowID()); window.getGLWindowRef().addWindowListener(wl); window.getAWTFrameRef().addComponentListener(wl); window.getGLWindowRef().addMouseListener(new MouseHandler(window, message.listener)); window.getAWTFrameRef().setVisible(true); } public int createWindow(int x, int y, int width, int height, int viewID, String title, String name, Image icon, WindowInteractionListener listener) { synchronized (_renderMessages) { int windowID = getAssetID(); addRenderMessage(new CreateWindowMessage(x, y, width, height, title, name, windowID, viewID, icon, listener)); return windowID; } } public void setWindowDebugInfo(int windowID, String debugString, ArrayList<Long> debugIDs) { synchronized(_openWindows) { RenderWindow w = _openWindows.get(windowID); if (w != null) { w.setDebugString(debugString); w.setDebugIDs(debugIDs); } } } public int getNumOpenWindows() { synchronized(_openWindows) { return _openWindows.size(); } } public void closeWindow(int windowID) { synchronized (_renderMessages) { addRenderMessage(new CloseWindowMessage(windowID)); } } private void closeWindowImp(CloseWindowMessage msg) { RenderWindow window; synchronized(_openWindows) { window = _openWindows.get(msg.windowID); if (window == null) { return; } } windowCleanup(msg.windowID); window.getGLWindowRef().destroy(); window.getAWTFrameRef().dispose(); } private String readSource(String file) { URL res = Renderer.class.getResource(file); StringBuilder source = new StringBuilder(); BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(res.openStream())); while (true) { String line = reader.readLine(); if (line == null) break; source.append(line).append("\n"); } reader.close(); reader = null; } catch (IOException e) {} return source.toString(); } private void createShader(ShaderHandle sh, String vert, String frag, GL2GL3 gl) { String vertsrc = readSource(vert); String fragsrc = readSource(frag); Shader s = new Shader(vertsrc, fragsrc, gl); if (s.isGood()) { _shaders.put(sh, s); return; } String failure = s.getFailureLog(); throw new RenderException("Shader failed: " + sh.toString() + " " + failure); } /** * Create and compile all the shaders */ private void initShaders(GL2GL3 gl) throws RenderException { _shaders = new EnumMap<ShaderHandle, Shader>(ShaderHandle.class); String vert, frag; vert = "/resources/shaders/flat.vert"; frag = "/resources/shaders/flat.frag"; createShader(ShaderHandle.MESH, vert, frag, gl); vert = "/resources/shaders/font.vert"; frag = "/resources/shaders/font.frag"; createShader(ShaderHandle.FONT, vert, frag, gl); vert = "/resources/shaders/hull.vert"; frag = "/resources/shaders/hull.frag"; createShader(ShaderHandle.HULL, vert, frag, gl); vert = "/resources/shaders/overlay-font.vert"; frag = "/resources/shaders/overlay-font.frag"; createShader(ShaderHandle.OVERLAY_FONT, vert, frag, gl); vert = "/resources/shaders/overlay-flat.vert"; frag = "/resources/shaders/overlay-flat.frag"; createShader(ShaderHandle.OVERLAY_FLAT, vert, frag, gl); vert = "/resources/shaders/debug.vert"; frag = "/resources/shaders/debug.frag"; createShader(ShaderHandle.DEBUG, vert, frag, gl); } /** * Basic message dispatch * * @param message */ private void handleMessage(RenderMessage message) { assert (Thread.currentThread() == _renderThread); if (message instanceof CreateWindowMessage) { createWindowImp((CreateWindowMessage) message); return; } if (message instanceof SetCameraMessage) { setCameraInfoImp((SetCameraMessage) message); return; } if (message instanceof OffScreenMessage) { offScreenImp((OffScreenMessage) message); return; } if (message instanceof CloseWindowMessage) { closeWindowImp((CloseWindowMessage) message); return; } if (message instanceof CreateOffscreenTargetMessage) { populateOffscreenTarget(((CreateOffscreenTargetMessage)message).target); } if (message instanceof FreeOffscreenTargetMessage) { freeOffscreenTargetImp(((FreeOffscreenTargetMessage)message).target); } } private void initSharedContext() { assert (Thread.currentThread() == _renderThread); assert (_drawContext == null); int res = _sharedContext.makeCurrent(); assert (res == GLContext.CONTEXT_CURRENT); if (USE_DEBUG_GL) { _sharedContext.setGL(new DebugGL2(_sharedContext.getGL().getGL2())); } GL2GL3 gl = _sharedContext.getGL().getGL2GL3(); initShaders(gl); // Sub system specific intitializations DebugUtils.init(this, gl); Polygon.init(this, gl); MeshProto.init(this, gl); _texCache.init(gl); // Load the bad mesh proto MeshData badData = MeshDataCache.getBadMesh(); MeshProto badProto = new MeshProto(badData, _safeGraphics, !_safeGraphics); _protoCache.put(MeshDataCache.BAD_MESH_KEY, badProto); badProto.loadGPUAssets(gl, this); _sharedContext.release(); } private void loadMeshProtoImp(final MeshProtoKey key) { //long startNanos = System.nanoTime(); assert (Thread.currentThread() == _renderThread); if (_protoCache.get(key) != null) { return; // This mesh has already been loaded } if (_drawContext != null) { _drawContext.release(); } int res = _sharedContext.makeCurrent(); assert (res == GLContext.CONTEXT_CURRENT); GL2GL3 gl = _sharedContext.getGL().getGL2GL3(); MeshData data = MeshDataCache.getMeshData(key); MeshProto proto = new MeshProto(data, _safeGraphics, !_safeGraphics); assert (proto != null); proto.loadGPUAssets(gl, this); if (!proto.isLoadedGPU()) { // This did not load cleanly, clear it out and use the default bad mesh asset proto.freeResources(gl); System.out.printf("Could not load GPU assset: %s\n", key.getURL().toString()); proto = _protoCache.get(MeshDataCache.BAD_MESH_KEY); } _protoCache.put(key, proto); _sharedContext.release(); if (_drawContext != null) { _drawContext.makeCurrent(); } // long endNanos = System.nanoTime(); // long ms = (endNanos - startNanos) /1000000L; // System.out.println("LoadMeshProtoImp time:" + ms + "ms"); } private void loadTessFontImp(TessFontKey key) { if (_fontCache.get(key) != null) { return; // This font has already been loaded } TessFont tf = new TessFont(key); _fontCache.put(key, tf); } private void loadHullImp(ConvexHullKey key) { // Find the mesh proto assert (Thread.currentThread() == _renderThread); MeshProto proto = _protoCache.get(key.getMeshKey()); if (proto == null) { //TODO: log error, or load mesh return; // This mesh has not been loaded.... } ConvexHull hull = proto.getHull(); assert(hull != null); HullProto hp = new HullProto(hull); if (_drawContext != null) { _drawContext.release(); } int res = _sharedContext.makeCurrent(); assert (res == GLContext.CONTEXT_CURRENT); GL2GL3 gl = _sharedContext.getGL().getGL2GL3(); hp.loadGPUAssets(gl, this); assert (hp.isLoadedGPU()); _hullCache.put(key, hp); _sharedContext.release(); if (_drawContext != null) { _drawContext.makeCurrent(); } } // Recreate the internal scene based on external input private void updateRenderableScene() { synchronized (_sceneLock) { long sceneStart = System.nanoTime(); _currentScene = new ArrayList<Renderable>(); _currentOverlay = new ArrayList<OverlayRenderable>(); for (RenderProxy proxy : _proxyScene) { proxy.collectRenderables(this, _currentScene); proxy.collectOverlayRenderables(this, _currentOverlay); } long sceneTime = System.nanoTime() - sceneStart; _sceneTimeMS = sceneTime / 1000000.0; } } public static class PickResult { public double dist; public long pickingID; public PickResult(double dist, long pickingID) { this.dist = dist; this.pickingID = pickingID; } } /** * Cast the provided ray into the current scene and return the list of bounds collisions * @param ray * @return */ public List<PickResult> pick(Ray pickRay, int viewID, boolean precise) { // Do not update the scene while a pick is underway ArrayList<PickResult> ret = new ArrayList<PickResult>(); if (_currentScene == null) { return ret; } synchronized (_sceneLock) { for (Renderable r : _currentScene) { double rayDist = r.getCollisionDist(pickRay, precise); if (rayDist >= 0.0) { // Also check that this is visible double centerDist = pickRay.getDistAlongRay(r.getBoundsRef().getCenter()); if (r.renderForView(viewID, centerDist)) { ret.add(new PickResult(rayDist, r.getPickingID())); } } } return ret; } } public static class WindowMouseInfo { public int x, y; public int width, height; public int viewableX, viewableY; public boolean mouseInWindow; public CameraInfo cameraInfo; } /** * Get Window specific information about the mouse. This is very useful for picking on the App side * @param windowID * @return */ public WindowMouseInfo getMouseInfo(int windowID) { synchronized(_openWindows) { RenderWindow w = _openWindows.get(windowID); if (w == null) { return null; // Not a valid window ID, or the window has closed } WindowMouseInfo info = new WindowMouseInfo(); info.x = w.getMouseX(); info.y = w.getMouseY(); info.width = w.getViewableWidth(); info.height = w.getViewableHeight(); info.viewableX = w.getViewableX(); info.viewableY = w.getViewableY(); info.mouseInWindow = w.isMouseInWindow(); info.cameraInfo = w.getCameraRef().getInfo(); return info; } } public CameraInfo getCameraInfo(int windowID) { synchronized(_openWindows) { RenderWindow w = _openWindows.get(windowID); if (w == null) { return null; // Not a valid window ID, or the window has closed } return w.getCameraRef().getInfo(); } } // Common cleanup code for window closing. Applies to both user closed and programatically closed windows private void windowCleanup(int windowID) { RenderWindow w; synchronized(_openWindows) { w = _openWindows.get(windowID); if (w == null) { return; } _openWindows.remove(windowID); } w.getAWTFrameRef().setVisible(false); // Fire the window closing callback w.getWindowListener().windowClosing(); } private class GLWindowListener implements WindowListener, ComponentListener { private int _windowID; public GLWindowListener(int id) { _windowID = id; } private WindowInteractionListener getListener() { synchronized(_openWindows) { RenderWindow w = _openWindows.get(_windowID); if (w == null) { return null; // Not a valid window ID, or the window has closed } return w.getWindowListener(); } } @Override public void windowDestroyNotify(WindowEvent we) { windowCleanup(_windowID); } @Override public void windowDestroyed(WindowEvent arg0) { } @Override public void windowGainedFocus(WindowEvent arg0) { WindowInteractionListener listener = getListener(); if (listener != null) { listener.windowGainedFocus(); } } @Override public void windowLostFocus(WindowEvent arg0) { } @Override public void windowMoved(WindowEvent arg0) { } @Override public void windowRepaint(WindowUpdateEvent arg0) { } @Override public void windowResized(WindowEvent arg0) { } private void updateWindowSizeAndPos() { RenderWindow w; synchronized(_openWindows) { w = _openWindows.get(_windowID); if (w == null) { return; } } w.getWindowListener().windowMoved(w.getWindowX(), w.getWindowY(), w.getWindowWidth(), w.getWindowHeight()); } @Override public void componentHidden(ComponentEvent arg0) { } @Override public void componentMoved(ComponentEvent arg0) { updateWindowSizeAndPos(); } @Override public void componentResized(ComponentEvent arg0) { updateWindowSizeAndPos(); } @Override public void componentShown(ComponentEvent arg0) { } } private class RenderGLListener implements GLEventListener { private RenderWindow _window; private long _lastFrameNanos = 0; public void setWindow(RenderWindow win) { _window = win; } @Override public void init(GLAutoDrawable drawable) { synchronized (_rendererLock) { // Per window initialization if (USE_DEBUG_GL) { drawable.setGL(new DebugGL2(drawable.getGL().getGL2())); } GL2GL3 gl = drawable.getGL().getGL2GL3(); // Some of this is probably redundant, but here goes gl.glClearColor(1.0f, 1.0f, 1.0f, 1.0f); gl.glEnable(GL.GL_DEPTH_TEST); gl.glClearDepth(1.0); gl.glDepthFunc(GL2GL3.GL_LEQUAL); gl.glEnable(GL2GL3.GL_CULL_FACE); gl.glCullFace(GL2GL3.GL_BACK); gl.glEnable(GL.GL_MULTISAMPLE); gl.glBlendEquationSeparate(GL2GL3.GL_FUNC_ADD, GL2GL3.GL_MAX); gl.glBlendFuncSeparate(GL2GL3.GL_SRC_ALPHA, GL2GL3.GL_ONE_MINUS_SRC_ALPHA, GL2GL3.GL_ONE, GL2GL3.GL_ONE); } } @Override public void dispose(GLAutoDrawable drawable) { synchronized (_rendererLock) { GL2GL3 gl = drawable.getGL().getGL2GL3(); Map<Integer, Integer> vaoMap = _window.getVAOMap(); int[] vaos = new int[vaoMap.size()]; int index = 0; for (int vao : vaoMap.values()) { vaos[index++] = vao; } if (vaos.length > 0) { gl.glDeleteVertexArrays(vaos.length, vaos, 0); } } } @Override public void display(GLAutoDrawable drawable) { // Only display from the render thread, this can be called from the EDT for first window draw... if (Thread.currentThread() != _renderThread) { queueRedraw(); return; } synchronized (_rendererLock) { Camera cam = _window.getCameraRef(); // The ray of the current mouse position (or null if the mouse is not hovering over the window) Ray pickRay = RenderUtils.getPickRay(getMouseInfo(_window.getWindowID())); PerfInfo pi = new PerfInfo(); long startNanos = System.nanoTime(); _allowDelayedTextures = true; renderScene(drawable.getContext(), _window.getVAOMap(), _currentScene, _currentOverlay, cam, _window.getViewableWidth(), _window.getViewableHeight(), pickRay, _window.getViewID(), pi); GL2GL3 gl = drawable.getContext().getGL().getGL2GL3(); // Just to clean up the code below if (RENDER_DEBUG_INFO) { // Draw a window specific performance counter gl.glDisable(GL2GL3.GL_DEPTH_TEST); _drawContext = drawable.getContext(); StringBuilder perf = new StringBuilder("Objects Culled: ").append(pi.objectsCulled); perf.append(" VRAM: ").append(_usedVRAM/(1024.0*1024.0)).append("MB"); perf.append(" Frame time (ms) :").append(_lastFrameNanos / 1000000.0); perf.append(" SceneTime: ").append(_sceneTimeMS); perf.append(" Loop Time: ").append(_loopTimeMS); TessFont defFont = getTessFont(_defaultBoldFontKey); OverlayString os = new OverlayString(defFont, perf.toString(), ColourInput.BLACK, 10, 10, 15, false, false, DisplayModel.ALWAYS); os.render(_window.getVAOMap(), Renderer.this, _window.getViewableWidth(), _window.getViewableHeight()); // Also draw this window's debug string os = new OverlayString(defFont, _window.getDebugString(), ColourInput.BLACK, 10, 10, 30, false, false, DisplayModel.ALWAYS); os.render(_window.getVAOMap(), Renderer.this, _window.getViewableWidth(), _window.getViewableHeight()); _drawContext = null; gl.glEnable(GL2GL3.GL_DEPTH_TEST); } gl.glFinish(); long endNanos = System.nanoTime(); _lastFrameNanos = endNanos - startNanos; } } @Override public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) { //_window.resized(width, height); Camera cam = _window.getCameraRef(); cam.setAspectRatio((double) width / (double) height); } } /** * Abstract base type for internal renderer messages */ private static class RenderMessage { @SuppressWarnings("unused") public long queueTime = System.nanoTime(); } private static class CreateWindowMessage extends RenderMessage { public int x, y; public int width, height; public String title, name; public WindowInteractionListener listener; public int windowID, viewID; public Image icon; public CreateWindowMessage(int x, int y, int width, int height, String title, String name, int windowID, int viewID, Image icon, WindowInteractionListener listener) { this.x = x; this.y = y; this.width = width; this.height = height; this.title = title; this.name = name; this.listener = listener; this.windowID = windowID; this.viewID = viewID; this.icon = icon; } } private static class SetCameraMessage extends RenderMessage { public int windowID; public CameraInfo cameraInfo; public SetCameraMessage(int windowID, CameraInfo cameraInfo) { this.windowID = windowID; this.cameraInfo = cameraInfo; } } private static class OffScreenMessage extends RenderMessage { public ArrayList<RenderProxy> scene; public int viewID; public Camera cam; public int width, height; public Future<BufferedImage> result; public OffscreenTarget target; OffScreenMessage(ArrayList<RenderProxy> s, int vID, Camera c, int w, int h, Future<BufferedImage> r, OffscreenTarget t) { scene = s; viewID = vID; cam = c; width = w; height = h; result = r; target = t; } } private static class CloseWindowMessage extends RenderMessage { public int windowID; public CloseWindowMessage(int id) { windowID = id; } } private static class CreateOffscreenTargetMessage extends RenderMessage { public OffscreenTarget target; } private static class FreeOffscreenTargetMessage extends RenderMessage { public OffscreenTarget target; } public TexCache getTexCache() { return _texCache; } public boolean debugDrawHulls() { return false; } public boolean debugDrawAABBs() { return false; } public boolean debugDrawArmatures() { return false; } public boolean isInitialized() { return _initialized.get() && !_fatalError.get(); } public boolean hasFatalError() { return _fatalError.get(); } public String getErrorString() { return _errorString; } public StackTraceElement[] getFatalStackTrace() { return _fatalStackTrace; } public TessFontKey getDefaultFont() { return _defaultFontKey; } public boolean allowDelayedTextures() { return _allowDelayedTextures; } private void logException(Throwable t) { _exceptionLogger.logException(t); // For now print a synopsis for all exceptions thrown printExceptionLog(); t.printStackTrace(); } private void printExceptionLog() { System.out.println("Exceptions from Renderer: "); _exceptionLogger.printExceptionLog(); System.out.println(""); } /** * Queue up an off screen rendering * @param scene * @param cam * @param width * @param height * @return */ public Future<BufferedImage> renderOffscreen(ArrayList<RenderProxy> scene, int viewID, CameraInfo camInfo, int width, int height, Runnable runWhenDone, OffscreenTarget target) { Future<BufferedImage> result = new Future<BufferedImage>(runWhenDone); Camera cam = new Camera(camInfo, (double)width/(double)height); synchronized (_renderMessages) { addRenderMessage(new OffScreenMessage(scene, viewID, cam, width, height, result, target)); } synchronized (_displayNeeded) { _displayNeeded.notifyAll(); } return result; } public OffscreenTarget createOffscreenTarget(int width, int height) { OffscreenTarget ret = new OffscreenTarget(width, height); synchronized (_renderMessages) { CreateOffscreenTargetMessage msg = new CreateOffscreenTargetMessage(); msg.target = ret; addRenderMessage(msg); } return ret; } public void freeOffscreenTarget(OffscreenTarget target) { synchronized (_renderMessages) { FreeOffscreenTargetMessage msg = new FreeOffscreenTargetMessage(); msg.target = target; addRenderMessage(msg); } } /** * Create the resources for an OffscreenTarget */ private void populateOffscreenTarget(OffscreenTarget target) { int width = target.getWidth(); int height = target.getHeight(); _sharedContext.makeCurrent(); GL2GL3 gl = _sharedContext.getGL().getGL2GL3(); // Just to clean up the code below // Create a new frame buffer for this draw operation int[] temp = new int[2]; gl.glGenFramebuffers(2, temp, 0); int drawFBO = temp[0]; int blitFBO = temp[1]; gl.glGenTextures(2, temp, 0); int drawTex = temp[0]; int blitTex = temp[1]; gl.glGenRenderbuffers(1, temp, 0); int depthBuf = temp[0]; gl.glBindTexture(GL2GL3.GL_TEXTURE_2D_MULTISAMPLE, drawTex); gl.glTexImage2DMultisample(GL2GL3.GL_TEXTURE_2D_MULTISAMPLE, 4, GL2GL3.GL_RGBA8, width, height, true); gl.glBindRenderbuffer(GL2GL3.GL_RENDERBUFFER, depthBuf); gl.glRenderbufferStorageMultisample(GL2GL3.GL_RENDERBUFFER, 4, GL2GL3.GL_DEPTH_COMPONENT, width, height); gl.glBindFramebuffer(GL2GL3.GL_FRAMEBUFFER, drawFBO); gl.glFramebufferTexture2D(GL2GL3.GL_FRAMEBUFFER, GL2GL3.GL_COLOR_ATTACHMENT0, GL2GL3.GL_TEXTURE_2D_MULTISAMPLE, drawTex, 0); gl.glFramebufferRenderbuffer(GL2GL3.GL_FRAMEBUFFER, GL2GL3.GL_DEPTH_ATTACHMENT, GL2GL3.GL_RENDERBUFFER, depthBuf); int fbStatus = gl.glCheckFramebufferStatus(GL2GL3.GL_FRAMEBUFFER); assert(fbStatus == GL2GL3.GL_FRAMEBUFFER_COMPLETE); gl.glBindTexture(GL2GL3.GL_TEXTURE_2D, blitTex); gl.glTexImage2D(GL2GL3.GL_TEXTURE_2D, 0, GL2GL3.GL_RGBA8, width, height, 0, GL2GL3.GL_RGBA, GL2GL3.GL_BYTE, null); gl.glBindFramebuffer(GL2GL3.GL_FRAMEBUFFER, blitFBO); gl.glFramebufferTexture2D(GL2GL3.GL_FRAMEBUFFER, GL2GL3.GL_COLOR_ATTACHMENT0, GL2GL3.GL_TEXTURE_2D, blitTex, 0); gl.glBindFramebuffer(GL2GL3.GL_FRAMEBUFFER, 0); target.load(drawFBO, drawTex, depthBuf, blitFBO, blitTex); _sharedContext.release(); } private void freeOffscreenTargetImp(OffscreenTarget target) { _sharedContext.makeCurrent(); GL2GL3 gl = _sharedContext.getGL().getGL2GL3(); // Just to clean up the code below int[] temp = new int[2]; temp[0] = target.getDrawFBO(); temp[1] = target.getBlitFBO(); gl.glDeleteFramebuffers(2, temp, 0); temp[0] = target.getDrawTex(); temp[1] = target.getBlitTex(); gl.glDeleteTextures(2, temp, 0); temp[0] = target.getDepthBuffer(); gl.glDeleteRenderbuffers(1, temp, 0); target.free(); _sharedContext.release(); } private void offScreenImp(OffScreenMessage message) { try { boolean isTempTarget; OffscreenTarget target; if (message.target == null) { isTempTarget = true; target = new OffscreenTarget(message.width, message.height); populateOffscreenTarget(target); } else { isTempTarget = false; target = message.target; assert(target.getWidth() == message.width); assert(target.getHeight() == message.height); } int width = message.width; int height = message.height; assert(target.isLoaded()); _sharedContext.makeCurrent(); GL2GL3 gl = _sharedContext.getGL().getGL2GL3(); // Just to clean up the code below // Collect the renderables ArrayList<Renderable> renderables = new ArrayList<Renderable>(); ArrayList<OverlayRenderable> overlay = new ArrayList<OverlayRenderable>(); for (RenderProxy p : message.scene) { p.collectRenderables(this, renderables); p.collectOverlayRenderables(this, overlay); } gl.glBindFramebuffer(GL2GL3.GL_DRAW_FRAMEBUFFER, target.getDrawFBO()); gl.glClearColor(0, 0, 0, 0); gl.glViewport(0, 0, width, height); gl.glEnable(GL2GL3.GL_DEPTH_TEST); gl.glDepthFunc(GL2GL3.GL_LEQUAL); _allowDelayedTextures = false; PerfInfo perfInfo = new PerfInfo(); // Okay, now actually render this thing... renderScene(_sharedContext, _sharedVaoMap, renderables, overlay, message.cam, width, height, null, message.viewID, perfInfo); gl.glFinish(); gl.glBindFramebuffer(GL2GL3.GL_DRAW_FRAMEBUFFER, target.getBlitFBO()); gl.glBindFramebuffer(GL2GL3.GL_READ_FRAMEBUFFER, target.getDrawFBO()); gl.glBlitFramebuffer(0, 0, width, height, 0, 0, width, height, GL2GL3.GL_COLOR_BUFFER_BIT, GL2GL3.GL_NEAREST); gl.glBindTexture(GL2GL3.GL_TEXTURE_2D, target.getBlitTex()); IntBuffer pixels = target.getPixelBuffer(); gl.glGetTexImage(GL2GL3.GL_TEXTURE_2D, 0, GL2GL3.GL_BGRA, GL2GL3.GL_UNSIGNED_INT_8_8_8_8_REV, pixels); gl.glBindTexture(GL2GL3.GL_TEXTURE_2D, 0); BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); for (int h = 0; h < height; ++h) { // Set this one scan line at a time, in the opposite order as java is y down img.setRGB(0, h, width, 1, pixels.array(), (height - 1 - h) * width, width); } message.result.setComplete(img); // Clean up gl.glBindFramebuffer(GL2GL3.GL_READ_FRAMEBUFFER, 0); gl.glBindFramebuffer(GL2GL3.GL_DRAW_FRAMEBUFFER, 0); if (isTempTarget) { freeOffscreenTargetImp(target); } } catch (GLException ex){ message.result.setFailed(ex.getMessage()); } finally { if (_sharedContext.isCurrent()) _sharedContext.release(); } } /** * Returns true if the current thread is this renderer's render thread * @return */ public boolean isRenderThread() { return (Thread.currentThread() == _renderThread); } private static class PerfInfo { public int objectsCulled = 0; } private static class TransSortable implements Comparable<TransSortable> { public Renderable r; public double dist; @Override public int compareTo(TransSortable o) { // Sort such that largest distance sorts to front of list // by reversing argument order in compare. return Double.compare(o.dist, this.dist); } } public void renderScene(GLContext context, Map<Integer, Integer> vaoMap, List<Renderable> scene, List<OverlayRenderable> overlay, Camera cam, int width, int height, Ray pickRay, int viewID, PerfInfo perfInfo) { final Vec4d viewDir = new Vec4d(0.0d, 0.0d, 0.0d, 1.0d); cam.getViewDir(viewDir); final Vec4d temp = new Vec4d(0.0d, 0.0d, 0.0d, 1.0d); assert (_drawContext == null); _drawContext = context; GL2GL3 gl = _drawContext.getGL().getGL2GL3(); // Just to clean up the code below gl.glClear(GL2GL3.GL_COLOR_BUFFER_BIT | GL2GL3.GL_DEPTH_BUFFER_BIT); // The 'height' of a pixel 1 unit from the viewer double unitPixelHeight = 2 * Math.tan(cam.getFOV()/2.0) / height; ArrayList<TransSortable> transparents = new ArrayList<TransSortable>(); if (scene == null) return; for (Renderable r : scene) { AABB bounds = r.getBoundsRef(); double dist = cam.distToBounds(bounds); if (!r.renderForView(viewID, dist)) { continue; } if (!cam.collides(bounds)) { ++perfInfo.objectsCulled; continue; } double apparentSize = 2 * bounds.getRadius().mag3() / Math.abs(dist); if (apparentSize < unitPixelHeight) { // This object is too small to draw ++perfInfo.objectsCulled; continue; } if (r.hasTransparent()) { // Defer rendering of transparent objects TransSortable ts = new TransSortable(); ts.r = r; temp.set4(r.getBoundsRef().getCenter()); temp.sub3(cam.getTransformRef().getTransRef()); ts.dist = temp.dot3(viewDir); transparents.add(ts); } r.render(vaoMap, this, cam, pickRay); } gl.glEnable(GL2GL3.GL_BLEND); gl.glDepthMask(false); Collections.sort(transparents); for (TransSortable ts : transparents) { AABB bounds = ts.r.getBoundsRef(); if (!cam.collides(bounds)) { ++perfInfo.objectsCulled; continue; } ts.r.renderTransparent(vaoMap, this, cam, pickRay); } gl.glDisable(GL2GL3.GL_BLEND); gl.glDepthMask(true); // Debug render AABBs if (debugDrawAABBs()) { Color4d yellow = new Color4d(1, 1, 0, 1.0d); Color4d red = new Color4d(1, 0, 0, 1.0d); for (Renderable r : scene) { Color4d aabbColor = yellow; if (pickRay != null && r.getBoundsRef().collisionDist(pickRay) > 0) { aabbColor = red; } DebugUtils.renderAABB(vaoMap, this, r.getBoundsRef(), aabbColor, cam); } } // for renderables // Now draw the overlay gl.glDisable(GL2GL3.GL_DEPTH_TEST); if (overlay != null) { for (OverlayRenderable r : overlay) { if (!r.renderForView(viewID)) { continue; } r.render(vaoMap, this, width, height); } } gl.glEnable(GL2GL3.GL_DEPTH_TEST); gl.glBindVertexArray(0); _drawContext = null; } public void usingVRAM(long bytes) { _usedVRAM += bytes; } }
src/main/java/com/jaamsim/render/Renderer.java
/* * JaamSim Discrete Event Simulation * Copyright (C) 2012 Ausenco Engineering Canada Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package com.jaamsim.render; //import com.jaamsim.math.*; import java.awt.Font; import java.awt.Frame; import java.awt.Image; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.awt.image.BufferedImage; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.nio.IntBuffer; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.EnumMap; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Queue; import java.util.concurrent.atomic.AtomicBoolean; import javax.media.opengl.DebugGL2; import javax.media.opengl.GL; import javax.media.opengl.GL2GL3; import javax.media.opengl.GLAutoDrawable; import javax.media.opengl.GLCapabilities; import javax.media.opengl.GLContext; import javax.media.opengl.GLEventListener; import javax.media.opengl.GLException; import javax.media.opengl.GLProfile; import com.jaamsim.DisplayModels.DisplayModel; import com.jaamsim.MeshFiles.MeshData; import com.jaamsim.font.OverlayString; import com.jaamsim.font.TessFont; import com.jaamsim.math.AABB; import com.jaamsim.math.Color4d; import com.jaamsim.math.ConvexHull; import com.jaamsim.math.Ray; import com.jaamsim.math.Vec4d; import com.jaamsim.render.util.ExceptionLogger; import com.jogamp.newt.event.WindowEvent; import com.jogamp.newt.event.WindowListener; import com.jogamp.newt.event.WindowUpdateEvent; import com.jogamp.newt.opengl.GLWindow; import com.sandwell.JavaSimulation.ColourInput; /** * The central renderer for JaamSim Renderer, Contains references to all context * specific data (like shader caches) * * @author Matt.Chudleigh * */ public class Renderer { public enum ShaderHandle { MESH, FONT, HULL, OVERLAY_FONT, OVERLAY_FLAT, DEBUG } static private Object idLock = new Object(); static private int _nextID = 1; /** * Get a system wide unique ID * @return */ public static int getAssetID() { synchronized(idLock) { return _nextID++; } } private static boolean RENDER_DEBUG_INFO = false; private static boolean USE_DEBUG_GL = true; private EnumMap<ShaderHandle, Shader> _shaders; // Display _display = null; // Screen _screen = null; private GLContext _sharedContext = null; Map<Integer, Integer> _sharedVaoMap = new HashMap<Integer, Integer>(); GLWindow _dummyWindow; private GLCapabilities _caps = null; private TexCache _texCache = new TexCache(this); // An initalization time flag specifying if the 'safest' graphical techniques should be used private boolean _safeGraphics; private final Thread _renderThread; private final Object _rendererLock = new Object(); private final Map<MeshProtoKey, MeshProto> _protoCache; private final Map<TessFontKey, TessFont> _fontCache; private final Map<ConvexHullKey, HullProto> _hullCache; private final HashMap<Integer, RenderWindow> _openWindows; private final Queue<RenderMessage> _renderMessages = new ArrayDeque<RenderMessage>(); private final AtomicBoolean _displayNeeded = new AtomicBoolean(true); private final AtomicBoolean _initialized = new AtomicBoolean(false); private final AtomicBoolean _shutdown = new AtomicBoolean(false); private final AtomicBoolean _fatalError = new AtomicBoolean(false); private String _errorString; // This is the string that caused the fatal error private StackTraceElement[] _fatalStackTrace; // the stack trace from the fatal error private final ExceptionLogger _exceptionLogger; private TessFontKey _defaultFontKey = new TessFontKey(Font.SANS_SERIF, Font.PLAIN); private TessFontKey _defaultBoldFontKey = new TessFontKey(Font.SANS_SERIF, Font.BOLD); private final Object _sceneLock = new Object(); private ArrayList<RenderProxy> _proxyScene = new ArrayList<RenderProxy>(); private boolean _allowDelayedTextures; private double _sceneTimeMS; private double _loopTimeMS; private long _usedVRAM = 0; // This may not be the best way to cache this //private GL2GL3 _currentGL = null; private GLContext _drawContext = null; // A cache of the current scene, needed by the individual windows to render private ArrayList<Renderable> _currentScene = new ArrayList<Renderable>(); private ArrayList<OverlayRenderable> _currentOverlay = null; public Renderer(boolean safeGraphics) throws RenderException { _safeGraphics = safeGraphics; _protoCache = new HashMap<MeshProtoKey, MeshProto>(); _fontCache = new HashMap<TessFontKey, TessFont>(); _hullCache = new HashMap<ConvexHullKey, HullProto>(); _exceptionLogger = new ExceptionLogger(); _openWindows = new HashMap<Integer, RenderWindow>(); _renderThread = new Thread(new Runnable() { @Override public void run() { mainRenderLoop(); } }, "RenderThread"); _renderThread.start(); } private void mainRenderLoop() { //long startNanos = System.nanoTime(); try { // GLProfile.initSingleton(); GLProfile glp = GLProfile.get(GLProfile.GL2GL3); _caps = new GLCapabilities(glp); _caps.setSampleBuffers(true); _caps.setNumSamples(4); _caps.setDepthBits(24); // Create a dummy window _dummyWindow = GLWindow.create(_caps); _dummyWindow.setSize(128, 128); _dummyWindow.setPosition(-2000, -2000); // This is unfortunately necessary due to JOGL's (newt's?) involved // startup code // I can not find a way to make a context valid without a visible window _dummyWindow.setVisible(true); _sharedContext = _dummyWindow.getContext(); assert (_sharedContext != null); _dummyWindow.setVisible(false); // long endNanos = System.nanoTime(); // long ms = (endNanos - startNanos) /1000000L; // System.out.println("Creating shared context at:" + ms + "ms"); initSharedContext(); // Notify the main thread we're done synchronized (_initialized) { _initialized.set(true); _initialized.notifyAll(); } } catch (Exception e) { _fatalError.set(true); _errorString = e.getLocalizedMessage(); _fatalStackTrace = e.getStackTrace(); System.out.println("Renderer encountered a fatal error:"); e.printStackTrace(); } finally { if (_sharedContext != null && _sharedContext.isCurrent()) _sharedContext.release(); } // endNanos = System.nanoTime(); // ms = (endNanos - startNanos) /1000000L; // System.out.println("Started renderer loop after:" + ms + "ms"); long lastLoopEnd = System.nanoTime(); while (!_shutdown.get()) { try { // If a fatal error was encountered, clean up the renderer if (_fatalError.get()) { // We should clean up everything we can, then die try { for (Entry<Integer, RenderWindow> entry : _openWindows.entrySet()){ entry.getValue().getGLWindowRef().destroy(); entry.getValue().getAWTFrameRef().dispose(); } } catch(Exception e) {} // Ignore any exceptions, this is just a best effort cleanup try { _dummyWindow.destroy(); _sharedContext.destroy(); _dummyWindow = null; _sharedContext = null; _openWindows.clear(); _currentScene = null; _currentOverlay = null; _caps = null; _fontCache.clear(); _protoCache.clear(); _hullCache.clear(); _shaders.clear(); } catch (Exception e) { } break; // Exiting the loop will end the thread } // Run all render messages RenderMessage message; do { // Only lock the queue while reading messages, release it while // processing them message = null; synchronized (_renderMessages) { if (!_renderMessages.isEmpty()) { message = _renderMessages.remove(); } } if (message != null) { try { handleMessage(message); } catch (Throwable t) { // Log this error but continue processing logException(t); } } } while (!_renderMessages.isEmpty()); if (_displayNeeded.get()) { _displayNeeded.set(false); updateRenderableScene(); // Defensive copy the window list (in case a window is closed while we render) HashMap<Integer, RenderWindow> winds; synchronized (_openWindows) { winds = new HashMap<Integer, RenderWindow>(_openWindows); } for (RenderWindow wind : winds.values()) { try { GLContext context = wind.getGLWindowRef().getContext(); if (context != null && context.isCreated() && !_shutdown.get()) { wind.getGLWindowRef().display(); } } catch (Throwable t) { // Log it, but move on to the other windows logException(t); } } } long loopEnd = System.nanoTime(); _loopTimeMS = (loopEnd - lastLoopEnd) / 1000000; lastLoopEnd = loopEnd; try { synchronized (_displayNeeded) { if (!_displayNeeded.get()) { _displayNeeded.wait(); } } } catch (InterruptedException e) { // Let's loop anyway... } } catch (Throwable t) { // Any other unexpected exceptions... logException(t); } } } /** * Returns the shader object for this handle, should only be called from the render thread (during a render) * @param h * @return */ public Shader getShader(ShaderHandle h) { return _shaders.get(h); } /** * Returns the MeshProto for the supplied key, should only be called from the render thread (during a render) * @param key * @return */ public MeshProto getProto(MeshProtoKey key) { MeshProto proto = _protoCache.get(key); if (proto == null) { // This prototype needs to be lazily loaded loadMeshProtoImp(key); } return _protoCache.get(key); } public TessFont getTessFont(TessFontKey key) { if (!_fontCache.containsKey(key)) { loadTessFontImp(key); // Try lazy initialization for now } return _fontCache.get(key); } public HullProto getHullProto(ConvexHullKey key) { HullProto hp = _hullCache.get(key); if (hp == null) { loadHullImp(key); } return _hullCache.get(key); } public void setScene(ArrayList<RenderProxy> scene) { synchronized (_sceneLock) { _proxyScene = scene; } } public void queueRedraw() { _displayNeeded.set(true); synchronized(_displayNeeded) { _displayNeeded.notifyAll(); } } private void addRenderMessage(RenderMessage msg) { _renderMessages.add(msg); queueRedraw(); } public void setCameraInfoForWindow(int windowID, CameraInfo info) { synchronized (_renderMessages) { addRenderMessage(new SetCameraMessage(windowID, info)); } } private void setCameraInfoImp(SetCameraMessage mes) { synchronized (_openWindows) { RenderWindow w = _openWindows.get(mes.windowID); if (w != null) { w.getCameraRef().setInfo(mes.cameraInfo); } } } /** * Call this from any thread to shutdown the Renderer, will return * immediately but the renderer will shutdown after the next redraw */ public void shutdown() { _shutdown.set(true); } public GL2GL3 getGL() { return _drawContext.getGL().getGL2GL3(); } /** * Get a list of all the IDs of currently open windows * @return */ public ArrayList<Integer> getOpenWindowIDs() { synchronized(_openWindows) { ArrayList<Integer> ret = new ArrayList<Integer>(); for (int id : _openWindows.keySet()) { ret.add(id); } return ret; } } public String getWindowName(int windowID) { synchronized(_openWindows) { RenderWindow win = _openWindows.get(windowID); if (win == null) { return null; } return win.getName(); } } public Frame getAWTFrame(int windowID) { synchronized(_openWindows) { RenderWindow win = _openWindows.get(windowID); if (win == null) { return null; } return win.getAWTFrameRef(); } } public void focusWindow(int windowID) { synchronized(_openWindows) { RenderWindow win = _openWindows.get(windowID); if (win == null) { return; } win.getAWTFrameRef().setExtendedState(Frame.NORMAL); win.getAWTFrameRef().toFront(); } } /** * Construct a new window (a NEWT window specifically) * * @param width * @param height * @return */ private void createWindowImp(CreateWindowMessage message) { RenderGLListener listener = new RenderGLListener(); // Set the listeners windowID before creating the window to ensure it never gets a callback before the // ID is valid message.listener.setWindowID(message.windowID); RenderWindow window = new RenderWindow(message.x, message.y, message.width, message.height, message.title, message.name, _sharedContext, _caps, listener, message.icon, message.windowID, message.viewID, message.listener); listener.setWindow(window); synchronized (_openWindows) { _openWindows.put(message.windowID, window); } GLWindowListener wl = new GLWindowListener(window.getWindowID()); window.getGLWindowRef().addWindowListener(wl); window.getAWTFrameRef().addComponentListener(wl); window.getGLWindowRef().addMouseListener(new MouseHandler(window, message.listener)); window.getAWTFrameRef().setVisible(true); } public int createWindow(int x, int y, int width, int height, int viewID, String title, String name, Image icon, WindowInteractionListener listener) { synchronized (_renderMessages) { int windowID = getAssetID(); addRenderMessage(new CreateWindowMessage(x, y, width, height, title, name, windowID, viewID, icon, listener)); return windowID; } } public void setWindowDebugInfo(int windowID, String debugString, ArrayList<Long> debugIDs) { synchronized(_openWindows) { RenderWindow w = _openWindows.get(windowID); if (w != null) { w.setDebugString(debugString); w.setDebugIDs(debugIDs); } } } public int getNumOpenWindows() { synchronized(_openWindows) { return _openWindows.size(); } } public void closeWindow(int windowID) { synchronized (_renderMessages) { addRenderMessage(new CloseWindowMessage(windowID)); } } private void closeWindowImp(CloseWindowMessage msg) { RenderWindow window; synchronized(_openWindows) { window = _openWindows.get(msg.windowID); if (window == null) { return; } } windowCleanup(msg.windowID); window.getGLWindowRef().destroy(); window.getAWTFrameRef().dispose(); } private String readSource(String file) { URL res = Renderer.class.getResource(file); StringBuilder source = new StringBuilder(); BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(res.openStream())); while (true) { String line = reader.readLine(); if (line == null) break; source.append(line).append("\n"); } reader.close(); reader = null; } catch (IOException e) {} return source.toString(); } private void createShader(ShaderHandle sh, String vert, String frag, GL2GL3 gl) { String vertsrc = readSource(vert); String fragsrc = readSource(frag); Shader s = new Shader(vertsrc, fragsrc, gl); if (s.isGood()) { _shaders.put(sh, s); return; } String failure = s.getFailureLog(); throw new RenderException("Shader failed: " + sh.toString() + " " + failure); } /** * Create and compile all the shaders */ private void initShaders(GL2GL3 gl) throws RenderException { _shaders = new EnumMap<ShaderHandle, Shader>(ShaderHandle.class); String vert, frag; vert = "/resources/shaders/flat.vert"; frag = "/resources/shaders/flat.frag"; createShader(ShaderHandle.MESH, vert, frag, gl); vert = "/resources/shaders/font.vert"; frag = "/resources/shaders/font.frag"; createShader(ShaderHandle.FONT, vert, frag, gl); vert = "/resources/shaders/hull.vert"; frag = "/resources/shaders/hull.frag"; createShader(ShaderHandle.HULL, vert, frag, gl); vert = "/resources/shaders/overlay-font.vert"; frag = "/resources/shaders/overlay-font.frag"; createShader(ShaderHandle.OVERLAY_FONT, vert, frag, gl); vert = "/resources/shaders/overlay-flat.vert"; frag = "/resources/shaders/overlay-flat.frag"; createShader(ShaderHandle.OVERLAY_FLAT, vert, frag, gl); vert = "/resources/shaders/debug.vert"; frag = "/resources/shaders/debug.frag"; createShader(ShaderHandle.DEBUG, vert, frag, gl); } /** * Basic message dispatch * * @param message */ private void handleMessage(RenderMessage message) { assert (Thread.currentThread() == _renderThread); if (message instanceof CreateWindowMessage) { createWindowImp((CreateWindowMessage) message); return; } if (message instanceof SetCameraMessage) { setCameraInfoImp((SetCameraMessage) message); return; } if (message instanceof OffScreenMessage) { offScreenImp((OffScreenMessage) message); return; } if (message instanceof CloseWindowMessage) { closeWindowImp((CloseWindowMessage) message); return; } if (message instanceof CreateOffscreenTargetMessage) { populateOffscreenTarget(((CreateOffscreenTargetMessage)message).target); } if (message instanceof FreeOffscreenTargetMessage) { freeOffscreenTargetImp(((FreeOffscreenTargetMessage)message).target); } } private void initSharedContext() { assert (Thread.currentThread() == _renderThread); assert (_drawContext == null); int res = _sharedContext.makeCurrent(); assert (res == GLContext.CONTEXT_CURRENT); if (USE_DEBUG_GL) { _sharedContext.setGL(new DebugGL2(_sharedContext.getGL().getGL2())); } GL2GL3 gl = _sharedContext.getGL().getGL2GL3(); initShaders(gl); // Sub system specific intitializations DebugUtils.init(this, gl); Polygon.init(this, gl); MeshProto.init(this, gl); _texCache.init(gl); // Load the bad mesh proto MeshData badData = MeshDataCache.getBadMesh(); MeshProto badProto = new MeshProto(badData, _safeGraphics, !_safeGraphics); _protoCache.put(MeshDataCache.BAD_MESH_KEY, badProto); badProto.loadGPUAssets(gl, this); _sharedContext.release(); } private void loadMeshProtoImp(final MeshProtoKey key) { //long startNanos = System.nanoTime(); assert (Thread.currentThread() == _renderThread); if (_protoCache.get(key) != null) { return; // This mesh has already been loaded } if (_drawContext != null) { _drawContext.release(); } int res = _sharedContext.makeCurrent(); assert (res == GLContext.CONTEXT_CURRENT); GL2GL3 gl = _sharedContext.getGL().getGL2GL3(); MeshData data = MeshDataCache.getMeshData(key); MeshProto proto = new MeshProto(data, _safeGraphics, !_safeGraphics); assert (proto != null); proto.loadGPUAssets(gl, this); if (!proto.isLoadedGPU()) { // This did not load cleanly, clear it out and use the default bad mesh asset proto.freeResources(gl); System.out.printf("Could not load GPU assset: %s\n", key.getURL().toString()); proto = _protoCache.get(MeshDataCache.BAD_MESH_KEY); } _protoCache.put(key, proto); _sharedContext.release(); if (_drawContext != null) { _drawContext.makeCurrent(); } // long endNanos = System.nanoTime(); // long ms = (endNanos - startNanos) /1000000L; // System.out.println("LoadMeshProtoImp time:" + ms + "ms"); } private void loadTessFontImp(TessFontKey key) { if (_fontCache.get(key) != null) { return; // This font has already been loaded } TessFont tf = new TessFont(key); _fontCache.put(key, tf); } private void loadHullImp(ConvexHullKey key) { // Find the mesh proto assert (Thread.currentThread() == _renderThread); MeshProto proto = _protoCache.get(key.getMeshKey()); if (proto == null) { //TODO: log error, or load mesh return; // This mesh has not been loaded.... } ConvexHull hull = proto.getHull(); assert(hull != null); HullProto hp = new HullProto(hull); if (_drawContext != null) { _drawContext.release(); } int res = _sharedContext.makeCurrent(); assert (res == GLContext.CONTEXT_CURRENT); GL2GL3 gl = _sharedContext.getGL().getGL2GL3(); hp.loadGPUAssets(gl, this); assert (hp.isLoadedGPU()); _hullCache.put(key, hp); _sharedContext.release(); if (_drawContext != null) { _drawContext.makeCurrent(); } } // Recreate the internal scene based on external input private void updateRenderableScene() { synchronized (_sceneLock) { long sceneStart = System.nanoTime(); _currentScene = new ArrayList<Renderable>(); _currentOverlay = new ArrayList<OverlayRenderable>(); for (RenderProxy proxy : _proxyScene) { proxy.collectRenderables(this, _currentScene); proxy.collectOverlayRenderables(this, _currentOverlay); } long sceneTime = System.nanoTime() - sceneStart; _sceneTimeMS = sceneTime / 1000000.0; } } public static class PickResult { public double dist; public long pickingID; public PickResult(double dist, long pickingID) { this.dist = dist; this.pickingID = pickingID; } } /** * Cast the provided ray into the current scene and return the list of bounds collisions * @param ray * @return */ public List<PickResult> pick(Ray pickRay, int viewID, boolean precise) { // Do not update the scene while a pick is underway ArrayList<PickResult> ret = new ArrayList<PickResult>(); if (_currentScene == null) { return ret; } synchronized (_sceneLock) { for (Renderable r : _currentScene) { double rayDist = r.getCollisionDist(pickRay, precise); if (rayDist >= 0.0) { // Also check that this is visible double centerDist = pickRay.getDistAlongRay(r.getBoundsRef().getCenter()); if (r.renderForView(viewID, centerDist)) { ret.add(new PickResult(rayDist, r.getPickingID())); } } } return ret; } } public static class WindowMouseInfo { public int x, y; public int width, height; public int viewableX, viewableY; public boolean mouseInWindow; public CameraInfo cameraInfo; } /** * Get Window specific information about the mouse. This is very useful for picking on the App side * @param windowID * @return */ public WindowMouseInfo getMouseInfo(int windowID) { synchronized(_openWindows) { RenderWindow w = _openWindows.get(windowID); if (w == null) { return null; // Not a valid window ID, or the window has closed } WindowMouseInfo info = new WindowMouseInfo(); info.x = w.getMouseX(); info.y = w.getMouseY(); info.width = w.getViewableWidth(); info.height = w.getViewableHeight(); info.viewableX = w.getViewableX(); info.viewableY = w.getViewableY(); info.mouseInWindow = w.isMouseInWindow(); info.cameraInfo = w.getCameraRef().getInfo(); return info; } } public CameraInfo getCameraInfo(int windowID) { synchronized(_openWindows) { RenderWindow w = _openWindows.get(windowID); if (w == null) { return null; // Not a valid window ID, or the window has closed } return w.getCameraRef().getInfo(); } } // Common cleanup code for window closing. Applies to both user closed and programatically closed windows private void windowCleanup(int windowID) { RenderWindow w; synchronized(_openWindows) { w = _openWindows.get(windowID); if (w == null) { return; } _openWindows.remove(windowID); } w.getAWTFrameRef().setVisible(false); // Fire the window closing callback w.getWindowListener().windowClosing(); } private class GLWindowListener implements WindowListener, ComponentListener { private int _windowID; public GLWindowListener(int id) { _windowID = id; } private WindowInteractionListener getListener() { synchronized(_openWindows) { RenderWindow w = _openWindows.get(_windowID); if (w == null) { return null; // Not a valid window ID, or the window has closed } return w.getWindowListener(); } } @Override public void windowDestroyNotify(WindowEvent we) { windowCleanup(_windowID); } @Override public void windowDestroyed(WindowEvent arg0) { } @Override public void windowGainedFocus(WindowEvent arg0) { WindowInteractionListener listener = getListener(); if (listener != null) { listener.windowGainedFocus(); } } @Override public void windowLostFocus(WindowEvent arg0) { } @Override public void windowMoved(WindowEvent arg0) { } @Override public void windowRepaint(WindowUpdateEvent arg0) { } @Override public void windowResized(WindowEvent arg0) { } private void updateWindowSizeAndPos() { RenderWindow w; synchronized(_openWindows) { w = _openWindows.get(_windowID); if (w == null) { return; } } w.getWindowListener().windowMoved(w.getWindowX(), w.getWindowY(), w.getWindowWidth(), w.getWindowHeight()); } @Override public void componentHidden(ComponentEvent arg0) { } @Override public void componentMoved(ComponentEvent arg0) { updateWindowSizeAndPos(); } @Override public void componentResized(ComponentEvent arg0) { updateWindowSizeAndPos(); } @Override public void componentShown(ComponentEvent arg0) { } } private class RenderGLListener implements GLEventListener { private RenderWindow _window; private long _lastFrameNanos = 0; public void setWindow(RenderWindow win) { _window = win; } @Override public void init(GLAutoDrawable drawable) { synchronized (_rendererLock) { // Per window initialization if (USE_DEBUG_GL) { drawable.setGL(new DebugGL2(drawable.getGL().getGL2())); } GL2GL3 gl = drawable.getGL().getGL2GL3(); // Some of this is probably redundant, but here goes gl.glClearColor(1.0f, 1.0f, 1.0f, 1.0f); gl.glEnable(GL.GL_DEPTH_TEST); gl.glClearDepth(1.0); gl.glDepthFunc(GL2GL3.GL_LEQUAL); gl.glEnable(GL2GL3.GL_CULL_FACE); gl.glCullFace(GL2GL3.GL_BACK); gl.glEnable(GL.GL_MULTISAMPLE); gl.glBlendEquationSeparate(GL2GL3.GL_FUNC_ADD, GL2GL3.GL_MAX); gl.glBlendFuncSeparate(GL2GL3.GL_SRC_ALPHA, GL2GL3.GL_ONE_MINUS_SRC_ALPHA, GL2GL3.GL_ONE, GL2GL3.GL_ONE); } } @Override public void dispose(GLAutoDrawable drawable) { synchronized (_rendererLock) { GL2GL3 gl = drawable.getGL().getGL2GL3(); Map<Integer, Integer> vaoMap = _window.getVAOMap(); int[] vaos = new int[vaoMap.size()]; int index = 0; for (int vao : vaoMap.values()) { vaos[index++] = vao; } if (vaos.length > 0) { gl.glDeleteVertexArrays(vaos.length, vaos, 0); } } } @Override public void display(GLAutoDrawable drawable) { // Only display from the render thread, this can be called from the EDT for first window draw... if (Thread.currentThread() != _renderThread) { queueRedraw(); return; } synchronized (_rendererLock) { Camera cam = _window.getCameraRef(); // The ray of the current mouse position (or null if the mouse is not hovering over the window) Ray pickRay = RenderUtils.getPickRay(getMouseInfo(_window.getWindowID())); PerfInfo pi = new PerfInfo(); long startNanos = System.nanoTime(); _allowDelayedTextures = true; renderScene(drawable.getContext(), _window.getVAOMap(), _currentScene, _currentOverlay, cam, _window.getViewableWidth(), _window.getViewableHeight(), pickRay, _window.getViewID(), pi); if (RENDER_DEBUG_INFO) { // Draw a window specific performance counter _drawContext = drawable.getContext(); StringBuilder perf = new StringBuilder("Objects Culled: ").append(pi.objectsCulled); perf.append(" VRAM: ").append(_usedVRAM/(1024.0*1024.0)).append("MB"); perf.append(" Frame time (ms) :").append(_lastFrameNanos / 1000000.0); perf.append(" SceneTime: ").append(_sceneTimeMS); perf.append(" Loop Time: ").append(_loopTimeMS); TessFont defFont = getTessFont(_defaultBoldFontKey); OverlayString os = new OverlayString(defFont, perf.toString(), ColourInput.BLACK, 10, 10, 15, false, false, DisplayModel.ALWAYS); os.render(_window.getVAOMap(), Renderer.this, _window.getViewableWidth(), _window.getViewableHeight()); // Also draw this window's debug string os = new OverlayString(defFont, _window.getDebugString(), ColourInput.BLACK, 10, 10, 30, false, false, DisplayModel.ALWAYS); os.render(_window.getVAOMap(), Renderer.this, _window.getViewableWidth(), _window.getViewableHeight()); _drawContext = null; } GL2GL3 gl = drawable.getContext().getGL().getGL2GL3(); // Just to clean up the code below gl.glFinish(); long endNanos = System.nanoTime(); _lastFrameNanos = endNanos - startNanos; } } @Override public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) { //_window.resized(width, height); Camera cam = _window.getCameraRef(); cam.setAspectRatio((double) width / (double) height); } } /** * Abstract base type for internal renderer messages */ private static class RenderMessage { @SuppressWarnings("unused") public long queueTime = System.nanoTime(); } private static class CreateWindowMessage extends RenderMessage { public int x, y; public int width, height; public String title, name; public WindowInteractionListener listener; public int windowID, viewID; public Image icon; public CreateWindowMessage(int x, int y, int width, int height, String title, String name, int windowID, int viewID, Image icon, WindowInteractionListener listener) { this.x = x; this.y = y; this.width = width; this.height = height; this.title = title; this.name = name; this.listener = listener; this.windowID = windowID; this.viewID = viewID; this.icon = icon; } } private static class SetCameraMessage extends RenderMessage { public int windowID; public CameraInfo cameraInfo; public SetCameraMessage(int windowID, CameraInfo cameraInfo) { this.windowID = windowID; this.cameraInfo = cameraInfo; } } private static class OffScreenMessage extends RenderMessage { public ArrayList<RenderProxy> scene; public int viewID; public Camera cam; public int width, height; public Future<BufferedImage> result; public OffscreenTarget target; OffScreenMessage(ArrayList<RenderProxy> s, int vID, Camera c, int w, int h, Future<BufferedImage> r, OffscreenTarget t) { scene = s; viewID = vID; cam = c; width = w; height = h; result = r; target = t; } } private static class CloseWindowMessage extends RenderMessage { public int windowID; public CloseWindowMessage(int id) { windowID = id; } } private static class CreateOffscreenTargetMessage extends RenderMessage { public OffscreenTarget target; } private static class FreeOffscreenTargetMessage extends RenderMessage { public OffscreenTarget target; } public TexCache getTexCache() { return _texCache; } public boolean debugDrawHulls() { return false; } public boolean debugDrawAABBs() { return false; } public boolean debugDrawArmatures() { return false; } public boolean isInitialized() { return _initialized.get() && !_fatalError.get(); } public boolean hasFatalError() { return _fatalError.get(); } public String getErrorString() { return _errorString; } public StackTraceElement[] getFatalStackTrace() { return _fatalStackTrace; } public TessFontKey getDefaultFont() { return _defaultFontKey; } public boolean allowDelayedTextures() { return _allowDelayedTextures; } private void logException(Throwable t) { _exceptionLogger.logException(t); // For now print a synopsis for all exceptions thrown printExceptionLog(); t.printStackTrace(); } private void printExceptionLog() { System.out.println("Exceptions from Renderer: "); _exceptionLogger.printExceptionLog(); System.out.println(""); } /** * Queue up an off screen rendering * @param scene * @param cam * @param width * @param height * @return */ public Future<BufferedImage> renderOffscreen(ArrayList<RenderProxy> scene, int viewID, CameraInfo camInfo, int width, int height, Runnable runWhenDone, OffscreenTarget target) { Future<BufferedImage> result = new Future<BufferedImage>(runWhenDone); Camera cam = new Camera(camInfo, (double)width/(double)height); synchronized (_renderMessages) { addRenderMessage(new OffScreenMessage(scene, viewID, cam, width, height, result, target)); } synchronized (_displayNeeded) { _displayNeeded.notifyAll(); } return result; } public OffscreenTarget createOffscreenTarget(int width, int height) { OffscreenTarget ret = new OffscreenTarget(width, height); synchronized (_renderMessages) { CreateOffscreenTargetMessage msg = new CreateOffscreenTargetMessage(); msg.target = ret; addRenderMessage(msg); } return ret; } public void freeOffscreenTarget(OffscreenTarget target) { synchronized (_renderMessages) { FreeOffscreenTargetMessage msg = new FreeOffscreenTargetMessage(); msg.target = target; addRenderMessage(msg); } } /** * Create the resources for an OffscreenTarget */ private void populateOffscreenTarget(OffscreenTarget target) { int width = target.getWidth(); int height = target.getHeight(); _sharedContext.makeCurrent(); GL2GL3 gl = _sharedContext.getGL().getGL2GL3(); // Just to clean up the code below // Create a new frame buffer for this draw operation int[] temp = new int[2]; gl.glGenFramebuffers(2, temp, 0); int drawFBO = temp[0]; int blitFBO = temp[1]; gl.glGenTextures(2, temp, 0); int drawTex = temp[0]; int blitTex = temp[1]; gl.glGenRenderbuffers(1, temp, 0); int depthBuf = temp[0]; gl.glBindTexture(GL2GL3.GL_TEXTURE_2D_MULTISAMPLE, drawTex); gl.glTexImage2DMultisample(GL2GL3.GL_TEXTURE_2D_MULTISAMPLE, 4, GL2GL3.GL_RGBA8, width, height, true); gl.glBindRenderbuffer(GL2GL3.GL_RENDERBUFFER, depthBuf); gl.glRenderbufferStorageMultisample(GL2GL3.GL_RENDERBUFFER, 4, GL2GL3.GL_DEPTH_COMPONENT, width, height); gl.glBindFramebuffer(GL2GL3.GL_FRAMEBUFFER, drawFBO); gl.glFramebufferTexture2D(GL2GL3.GL_FRAMEBUFFER, GL2GL3.GL_COLOR_ATTACHMENT0, GL2GL3.GL_TEXTURE_2D_MULTISAMPLE, drawTex, 0); gl.glFramebufferRenderbuffer(GL2GL3.GL_FRAMEBUFFER, GL2GL3.GL_DEPTH_ATTACHMENT, GL2GL3.GL_RENDERBUFFER, depthBuf); int fbStatus = gl.glCheckFramebufferStatus(GL2GL3.GL_FRAMEBUFFER); assert(fbStatus == GL2GL3.GL_FRAMEBUFFER_COMPLETE); gl.glBindTexture(GL2GL3.GL_TEXTURE_2D, blitTex); gl.glTexImage2D(GL2GL3.GL_TEXTURE_2D, 0, GL2GL3.GL_RGBA8, width, height, 0, GL2GL3.GL_RGBA, GL2GL3.GL_BYTE, null); gl.glBindFramebuffer(GL2GL3.GL_FRAMEBUFFER, blitFBO); gl.glFramebufferTexture2D(GL2GL3.GL_FRAMEBUFFER, GL2GL3.GL_COLOR_ATTACHMENT0, GL2GL3.GL_TEXTURE_2D, blitTex, 0); gl.glBindFramebuffer(GL2GL3.GL_FRAMEBUFFER, 0); target.load(drawFBO, drawTex, depthBuf, blitFBO, blitTex); _sharedContext.release(); } private void freeOffscreenTargetImp(OffscreenTarget target) { _sharedContext.makeCurrent(); GL2GL3 gl = _sharedContext.getGL().getGL2GL3(); // Just to clean up the code below int[] temp = new int[2]; temp[0] = target.getDrawFBO(); temp[1] = target.getBlitFBO(); gl.glDeleteFramebuffers(2, temp, 0); temp[0] = target.getDrawTex(); temp[1] = target.getBlitTex(); gl.glDeleteTextures(2, temp, 0); temp[0] = target.getDepthBuffer(); gl.glDeleteRenderbuffers(1, temp, 0); target.free(); _sharedContext.release(); } private void offScreenImp(OffScreenMessage message) { try { boolean isTempTarget; OffscreenTarget target; if (message.target == null) { isTempTarget = true; target = new OffscreenTarget(message.width, message.height); populateOffscreenTarget(target); } else { isTempTarget = false; target = message.target; assert(target.getWidth() == message.width); assert(target.getHeight() == message.height); } int width = message.width; int height = message.height; assert(target.isLoaded()); _sharedContext.makeCurrent(); GL2GL3 gl = _sharedContext.getGL().getGL2GL3(); // Just to clean up the code below // Collect the renderables ArrayList<Renderable> renderables = new ArrayList<Renderable>(); ArrayList<OverlayRenderable> overlay = new ArrayList<OverlayRenderable>(); for (RenderProxy p : message.scene) { p.collectRenderables(this, renderables); p.collectOverlayRenderables(this, overlay); } gl.glBindFramebuffer(GL2GL3.GL_DRAW_FRAMEBUFFER, target.getDrawFBO()); gl.glClearColor(0, 0, 0, 0); gl.glViewport(0, 0, width, height); gl.glEnable(GL2GL3.GL_DEPTH_TEST); gl.glDepthFunc(GL2GL3.GL_LEQUAL); _allowDelayedTextures = false; PerfInfo perfInfo = new PerfInfo(); // Okay, now actually render this thing... renderScene(_sharedContext, _sharedVaoMap, renderables, overlay, message.cam, width, height, null, message.viewID, perfInfo); gl.glFinish(); gl.glBindFramebuffer(GL2GL3.GL_DRAW_FRAMEBUFFER, target.getBlitFBO()); gl.glBindFramebuffer(GL2GL3.GL_READ_FRAMEBUFFER, target.getDrawFBO()); gl.glBlitFramebuffer(0, 0, width, height, 0, 0, width, height, GL2GL3.GL_COLOR_BUFFER_BIT, GL2GL3.GL_NEAREST); gl.glBindTexture(GL2GL3.GL_TEXTURE_2D, target.getBlitTex()); IntBuffer pixels = target.getPixelBuffer(); gl.glGetTexImage(GL2GL3.GL_TEXTURE_2D, 0, GL2GL3.GL_BGRA, GL2GL3.GL_UNSIGNED_INT_8_8_8_8_REV, pixels); gl.glBindTexture(GL2GL3.GL_TEXTURE_2D, 0); BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); for (int h = 0; h < height; ++h) { // Set this one scan line at a time, in the opposite order as java is y down img.setRGB(0, h, width, 1, pixels.array(), (height - 1 - h) * width, width); } message.result.setComplete(img); // Clean up gl.glBindFramebuffer(GL2GL3.GL_READ_FRAMEBUFFER, 0); gl.glBindFramebuffer(GL2GL3.GL_DRAW_FRAMEBUFFER, 0); if (isTempTarget) { freeOffscreenTargetImp(target); } } catch (GLException ex){ message.result.setFailed(ex.getMessage()); } finally { if (_sharedContext.isCurrent()) _sharedContext.release(); } } /** * Returns true if the current thread is this renderer's render thread * @return */ public boolean isRenderThread() { return (Thread.currentThread() == _renderThread); } private static class PerfInfo { public int objectsCulled = 0; } private static class TransSortable implements Comparable<TransSortable> { public Renderable r; public double dist; @Override public int compareTo(TransSortable o) { // Sort such that largest distance sorts to front of list // by reversing argument order in compare. return Double.compare(o.dist, this.dist); } } public void renderScene(GLContext context, Map<Integer, Integer> vaoMap, List<Renderable> scene, List<OverlayRenderable> overlay, Camera cam, int width, int height, Ray pickRay, int viewID, PerfInfo perfInfo) { final Vec4d viewDir = new Vec4d(0.0d, 0.0d, 0.0d, 1.0d); cam.getViewDir(viewDir); final Vec4d temp = new Vec4d(0.0d, 0.0d, 0.0d, 1.0d); assert (_drawContext == null); _drawContext = context; GL2GL3 gl = _drawContext.getGL().getGL2GL3(); // Just to clean up the code below gl.glClear(GL2GL3.GL_COLOR_BUFFER_BIT | GL2GL3.GL_DEPTH_BUFFER_BIT); // The 'height' of a pixel 1 unit from the viewer double unitPixelHeight = 2 * Math.tan(cam.getFOV()/2.0) / height; ArrayList<TransSortable> transparents = new ArrayList<TransSortable>(); if (scene == null) return; for (Renderable r : scene) { AABB bounds = r.getBoundsRef(); double dist = cam.distToBounds(bounds); if (!r.renderForView(viewID, dist)) { continue; } if (!cam.collides(bounds)) { ++perfInfo.objectsCulled; continue; } double apparentSize = 2 * bounds.getRadius().mag3() / Math.abs(dist); if (apparentSize < unitPixelHeight) { // This object is too small to draw ++perfInfo.objectsCulled; continue; } if (r.hasTransparent()) { // Defer rendering of transparent objects TransSortable ts = new TransSortable(); ts.r = r; temp.set4(r.getBoundsRef().getCenter()); temp.sub3(cam.getTransformRef().getTransRef()); ts.dist = temp.dot3(viewDir); transparents.add(ts); } r.render(vaoMap, this, cam, pickRay); } gl.glEnable(GL2GL3.GL_BLEND); gl.glDepthMask(false); Collections.sort(transparents); for (TransSortable ts : transparents) { AABB bounds = ts.r.getBoundsRef(); if (!cam.collides(bounds)) { ++perfInfo.objectsCulled; continue; } ts.r.renderTransparent(vaoMap, this, cam, pickRay); } gl.glDisable(GL2GL3.GL_BLEND); gl.glDepthMask(true); // Debug render AABBs if (debugDrawAABBs()) { Color4d yellow = new Color4d(1, 1, 0, 1.0d); Color4d red = new Color4d(1, 0, 0, 1.0d); for (Renderable r : scene) { Color4d aabbColor = yellow; if (pickRay != null && r.getBoundsRef().collisionDist(pickRay) > 0) { aabbColor = red; } DebugUtils.renderAABB(vaoMap, this, r.getBoundsRef(), aabbColor, cam); } } // for renderables // Now draw the overlay gl.glDisable(GL2GL3.GL_DEPTH_TEST); if (overlay != null) { for (OverlayRenderable r : overlay) { if (!r.renderForView(viewID)) { continue; } r.render(vaoMap, this, width, height); } } gl.glEnable(GL2GL3.GL_DEPTH_TEST); gl.glBindVertexArray(0); _drawContext = null; } public void usingVRAM(long bytes) { _usedVRAM += bytes; } }
JS: Fix debug string depth test bug This won't be found in the wild, but recent changes to overlay depth testing broke the debug string. Signed-off-by: Matt Chudleigh <0ca390ed93f516590d05286882efa52bb3b35616@ausenco.com> Signed-off-by: Harvey Harrison <eadbd6b462bf3c97df0300a934c12bc2e5d1fe51@ausenco.com>
src/main/java/com/jaamsim/render/Renderer.java
JS: Fix debug string depth test bug
Java
apache-2.0
a365f770c6e8aa22630a2570a417c2c9e65e1a12
0
eFaps/eFaps-Kernel
/* * Copyright 2003 - 2019 The eFaps Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.efaps.eql.builder; import java.util.Collection; import org.efaps.admin.datamodel.Status; import org.efaps.ci.CIAttribute; import org.efaps.ci.CIStatus; import org.efaps.db.Instance; import org.efaps.eql2.IWhereElement; import org.efaps.eql2.bldr.AbstractWhereBuilder; import org.efaps.util.cache.CacheReloadException; public class Where extends AbstractWhereBuilder<Where> { @Override protected Where getThis() { return this; } public Where in(final Collection<Instance> _instances) { in(_instances.stream().map(inst -> inst.getId()).toArray(Long[]::new)); return getThis(); } public Where attribute(final CIAttribute _ciAttr) { final IWhereElement element = getCurrentElement(); element.setAttribute(_ciAttr.name); return getThis(); } public Where eq(final Instance _instance) { return eq(_instance.getId()); } public Where eq(final Status _status) { return eq(_status.getId()); } public Where eq(final CIStatus _ciStatus) throws CacheReloadException { return eq(Status.find(_ciStatus)); } /** * Stmt. * * @return the prints the stmt */ @Override public Print select() { return (Print) super.select(); } }
src/main/java/org/efaps/eql/builder/Where.java
/* * Copyright 2003 - 2019 The eFaps Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.efaps.eql.builder; import java.util.Collection; import org.efaps.ci.CIAttribute; import org.efaps.db.Instance; import org.efaps.eql2.IWhereElement; import org.efaps.eql2.bldr.AbstractWhereBuilder; public class Where extends AbstractWhereBuilder<Where> { @Override protected Where getThis() { return this; } public Where in(final Collection<Instance> _instances) { in(_instances.stream().map(inst -> inst.getId()).toArray(Long[]::new)); return getThis(); } public Where attribute(final CIAttribute _ciAttr) { final IWhereElement element = getCurrentElement(); element.setAttribute(_ciAttr.name); return getThis(); } public Where eq(final Instance _instance) { return eq(_instance.getId()); } /** * Stmt. * * @return the prints the stmt */ @Override public Print select() { return (Print) super.select(); } }
Additional eq options for eql where
src/main/java/org/efaps/eql/builder/Where.java
Additional eq options for eql where
Java
apache-2.0
f5668607373d6cbc2224a86491d78edf515fb90c
0
google/closure-templates,google/closure-templates,yext/closure-templates,yext/closure-templates,google/closure-templates,google/closure-templates,google/closure-templates,yext/closure-templates,yext/closure-templates
/* * Copyright 2015 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.template.soy.incrementaldomsrc; import static com.google.common.base.Preconditions.checkState; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.INCREMENTAL_DOM; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.INCREMENTAL_DOM_APPLY_ATTRS; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.INCREMENTAL_DOM_APPLY_STATICS; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.INCREMENTAL_DOM_ATTR; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.INCREMENTAL_DOM_CLOSE; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.INCREMENTAL_DOM_ENTER; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.INCREMENTAL_DOM_EXIT; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.INCREMENTAL_DOM_LIB; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.INCREMENTAL_DOM_MAYBE_SKIP; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.INCREMENTAL_DOM_OPEN; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.INCREMENTAL_DOM_OPEN_SSR; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.INCREMENTAL_DOM_PARAM_NAME; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.INCREMENTAL_DOM_POP_KEY; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.INCREMENTAL_DOM_POP_MANUAL_KEY; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.INCREMENTAL_DOM_PUSH_KEY; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.INCREMENTAL_DOM_PUSH_MANUAL_KEY; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.INCREMENTAL_DOM_TEXT; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.INCREMENTAL_DOM_TODEFAULT; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.INCREMENTAL_DOM_TONULL; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.INCREMENTAL_DOM_VERIFY_LOGONLY; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.SOY_IDOM; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.SOY_IDOM_CALL_DYNAMIC_ATTRIBUTES; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.SOY_IDOM_CALL_DYNAMIC_CSS; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.SOY_IDOM_CALL_DYNAMIC_HTML; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.SOY_IDOM_CALL_DYNAMIC_JS; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.SOY_IDOM_CALL_DYNAMIC_TEXT; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.SOY_IDOM_MAKE_ATTRIBUTES; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.SOY_IDOM_MAKE_HTML; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.SOY_IDOM_PRINT; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.SOY_IDOM_PRINT_DYNAMIC_ATTR; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.SOY_IDOM_TYPE_ATTRIBUTE; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.SOY_IDOM_TYPE_HTML; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.SOY_IDOM_VISIT_HTML_COMMENT; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.STATE_PREFIX; import static com.google.template.soy.jssrc.dsl.Expression.EMPTY_OBJECT_LITERAL; import static com.google.template.soy.jssrc.dsl.Expression.LITERAL_EMPTY_STRING; import static com.google.template.soy.jssrc.dsl.Expression.id; import static com.google.template.soy.jssrc.dsl.Expression.stringLiteral; import static com.google.template.soy.jssrc.dsl.Statement.returnValue; import static com.google.template.soy.jssrc.internal.JsRuntime.GOOG_STRING_UNESCAPE_ENTITIES; import static com.google.template.soy.jssrc.internal.JsRuntime.SOY_ESCAPE_HTML; import com.google.common.base.Ascii; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.template.soy.base.internal.SanitizedContentKind; import com.google.template.soy.data.SanitizedContent; import com.google.template.soy.data.SanitizedContentOperator; import com.google.template.soy.error.ErrorReporter; import com.google.template.soy.exprtree.FunctionNode; import com.google.template.soy.incrementaldomsrc.GenIncrementalDomExprsVisitor.GenIncrementalDomExprsVisitorFactory; import com.google.template.soy.jssrc.SoyJsSrcOptions; import com.google.template.soy.jssrc.dsl.ClassExpression; import com.google.template.soy.jssrc.dsl.ClassExpression.MethodDeclaration; import com.google.template.soy.jssrc.dsl.CodeChunk; import com.google.template.soy.jssrc.dsl.CodeChunkUtils; import com.google.template.soy.jssrc.dsl.Expression; import com.google.template.soy.jssrc.dsl.GoogRequire; import com.google.template.soy.jssrc.dsl.JsDoc; import com.google.template.soy.jssrc.dsl.Statement; import com.google.template.soy.jssrc.dsl.VariableDeclaration; import com.google.template.soy.jssrc.internal.CanInitOutputVarVisitor; import com.google.template.soy.jssrc.internal.GenCallCodeUtils; import com.google.template.soy.jssrc.internal.GenJsCodeVisitor; import com.google.template.soy.jssrc.internal.GenJsCodeVisitorAssistantForMsgs; import com.google.template.soy.jssrc.internal.GenJsExprsVisitor; import com.google.template.soy.jssrc.internal.IsComputableAsJsExprsVisitor; import com.google.template.soy.jssrc.internal.JavaScriptValueFactoryImpl; import com.google.template.soy.jssrc.internal.JsCodeBuilder; import com.google.template.soy.jssrc.internal.JsRuntime; import com.google.template.soy.jssrc.internal.JsType; import com.google.template.soy.jssrc.internal.TemplateAliases; import com.google.template.soy.jssrc.internal.TranslateExprNodeVisitor; import com.google.template.soy.jssrc.internal.TranslationContext; import com.google.template.soy.passes.ShouldEnsureDataIsDefinedVisitor; import com.google.template.soy.shared.internal.BuiltinFunction; import com.google.template.soy.soytree.CallNode; import com.google.template.soy.soytree.CallParamContentNode; import com.google.template.soy.soytree.CallParamNode; import com.google.template.soy.soytree.HtmlAttributeNode; import com.google.template.soy.soytree.HtmlAttributeValueNode; import com.google.template.soy.soytree.HtmlCloseTagNode; import com.google.template.soy.soytree.HtmlCommentNode; import com.google.template.soy.soytree.HtmlContext; import com.google.template.soy.soytree.HtmlOpenTagNode; import com.google.template.soy.soytree.IfNode; import com.google.template.soy.soytree.KeyNode; import com.google.template.soy.soytree.LetContentNode; import com.google.template.soy.soytree.MsgFallbackGroupNode; import com.google.template.soy.soytree.MsgHtmlTagNode; import com.google.template.soy.soytree.MsgPlaceholderNode; import com.google.template.soy.soytree.PrintNode; import com.google.template.soy.soytree.RawTextNode; import com.google.template.soy.soytree.SkipNode; import com.google.template.soy.soytree.SoyNode; import com.google.template.soy.soytree.SoyNode.ParentSoyNode; import com.google.template.soy.soytree.SoyNode.RenderUnitNode; import com.google.template.soy.soytree.SoyTreeUtils; import com.google.template.soy.soytree.TagName; import com.google.template.soy.soytree.TemplateDelegateNode; import com.google.template.soy.soytree.TemplateElementNode; import com.google.template.soy.soytree.TemplateNode; import com.google.template.soy.soytree.VeLogNode; import com.google.template.soy.soytree.defn.TemplateHeaderVarDefn; import com.google.template.soy.soytree.defn.TemplateParam; import com.google.template.soy.soytree.defn.TemplateStateVar; import com.google.template.soy.types.SoyType; import com.google.template.soy.types.SoyTypeRegistry; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; /** * Generates a series of JavaScript control statements and function calls for rendering one or more * templates as HTML. This heavily leverages {@link GenJsCodeVisitor}, adding logic to print the * function calls and changing how statements are combined. */ public final class GenIncrementalDomCodeVisitor extends GenJsCodeVisitor { private static final String NAMESPACE_EXTENSION = ".incrementaldom"; private static final ImmutableList<HtmlContext> STRINGLIKE_KINDS = ImmutableList.of( HtmlContext.URI, HtmlContext.TEXT, HtmlContext.HTML_ATTRIBUTE_NAME, HtmlContext.HTML_NORMAL_ATTR_VALUE); private static class Holder<T> { T elementValue; T callValue; public Holder(T value, T callValue) { this.elementValue = value; this.callValue = callValue; } } /** * Class that contains the state generated from visiting the beginning of a velogging statement. * This allows one to generate code such as * * <pre> * var velog_1 = foobar; * if (velog_1) { * idom = idom.toNullRenderer(); * } * idom.enter(new Metadata(...)); * ... * if (velog_1) { * idom = idom.toDefaultRenderer(); * } * </pre> */ static class VeLogStateHolder { Expression logOnlyConditional; // Holds the variable reference to velog_1 Statement enterStatement; // Contains the idom.enter(...) statement public VeLogStateHolder(Expression logOnlyConditional, Statement enterStatement) { this.logOnlyConditional = logOnlyConditional; this.enterStatement = enterStatement; } } // Tracks the counter to use for a tag's generated key: // - When encountering an open tag without a manual key, the counter at the top of the stack is // incremented. // - When encountering an open tag with a manual key, a new counter is pushed onto the stack. // - When encountering a close tag that corresponds to an open tag with a manual key, the // topmost counter is then popped from the stack. private ArrayDeque<Holder<Integer>> keyCounterStack; // Counter for static variables that are declared at the global scope. private int staticsCounter = 0; private String alias = ""; GenIncrementalDomCodeVisitor( SoyJsSrcOptions jsSrcOptions, JavaScriptValueFactoryImpl javaScriptValueFactory, IncrementalDomDelTemplateNamer incrementalDomDelTemplateNamer, IncrementalDomGenCallCodeUtils genCallCodeUtils, IsComputableAsIncrementalDomExprsVisitor isComputableAsJsExprsVisitor, CanInitOutputVarVisitor canInitOutputVarVisitor, GenIncrementalDomExprsVisitorFactory genIncrementalDomExprsVisitorFactory, SoyTypeRegistry typeRegistry) { super( jsSrcOptions, javaScriptValueFactory, incrementalDomDelTemplateNamer, genCallCodeUtils, isComputableAsJsExprsVisitor, canInitOutputVarVisitor, genIncrementalDomExprsVisitorFactory, typeRegistry); } @Override protected JsCodeBuilder createCodeBuilder() { return new IncrementalDomCodeBuilder(); } @Override protected IncrementalDomCodeBuilder createChildJsCodeBuilder() { return new IncrementalDomCodeBuilder(getJsCodeBuilder()); } @Override protected IncrementalDomCodeBuilder getJsCodeBuilder() { return (IncrementalDomCodeBuilder) super.getJsCodeBuilder(); } @Override protected JsType getJsTypeForParamForDeclaration(SoyType paramType) { return JsType.forIncrementalDomState(paramType); } @Override protected JsType getJsTypeForParamTypeCheck(SoyType paramType) { return JsType.forIncrementalDom(paramType); } @Override protected void visit(SoyNode node) { try { super.visit(node); } catch (RuntimeException e) { throw new Error("error from : " + node.getKind() + " @ " + node.getSourceLocation(), e); } } /** * Changes module namespaces, adding an extension of '.incrementaldom' to allow it to co-exist * with templates generated by jssrc. */ @Override protected String getGoogModuleNamespace(String soyNamespace) { return soyNamespace + NAMESPACE_EXTENSION; } @Override protected String getTemplateReturnType(TemplateNode node) { if (isTextContent(node.getContentKind())) { return super.getTemplateReturnType(node); } // This template does not return any content but rather contains Incremental DOM // instructions. return "void"; } @Override protected void visitTemplateNode(TemplateNode node) { keyCounterStack = new ArrayDeque<>(); keyCounterStack.push(new Holder<>(0, 0)); staticsCounter = 0; SanitizedContentKind kind = node.getContentKind(); getJsCodeBuilder().setContentKind(kind); if (node instanceof TemplateDelegateNode) { alias = node.getPartialTemplateName().substring(1); } else { alias = templateAliases.get(node.getTemplateName()); } super.visitTemplateNode(node); if (kind == SanitizedContentKind.HTML || kind == SanitizedContentKind.ATTRIBUTES) { Expression type; if (kind == SanitizedContentKind.HTML) { type = SOY_IDOM_TYPE_HTML; } else { type = SOY_IDOM_TYPE_ATTRIBUTE; } getJsCodeBuilder().append(Statement.assign(id(alias).dotAccess("contentKind"), type)); } if (node instanceof TemplateElementNode) { TemplateElementNode element = (TemplateElementNode) node; String elementName = this.getSoyElementClassName(); String elementAccessor = elementName + "Interface"; getJsCodeBuilder().appendLine(); getJsCodeBuilder().append(generateAccessorInterface(elementAccessor, element)); getJsCodeBuilder().append(generateExportsForSoyElement(elementAccessor)); getJsCodeBuilder().append(generateClassForSoyElement(elementName, elementAccessor, element)); getJsCodeBuilder().append(generateExportsForSoyElement(elementName)); } } @Override protected JsDoc generateFunctionJsDoc(TemplateNode node, String alias) { JsDoc.Builder jsDocBuilder = JsDoc.builder(); SanitizedContentKind kind = node.getContentKind(); if (kind == SanitizedContentKind.HTML || kind == SanitizedContentKind.ATTRIBUTES) { jsDocBuilder.addGoogRequire(INCREMENTAL_DOM_LIB); jsDocBuilder.addParam( INCREMENTAL_DOM_PARAM_NAME, "!incrementaldomlib.IncrementalDomRenderer"); } // This is true if there are any calls with data="all" (which implicitly add optional parameters // from those template) or if all parameters are optional (but there are some parameters). boolean noRequiredParams = new ShouldEnsureDataIsDefinedVisitor().exec(node); if (node.getParams().isEmpty()) { // If there are indirect parameters, allow an arbitrary object. // Either way, allow null, since the caller may not pass parameters. jsDocBuilder.addParam("opt_data", noRequiredParams ? "?Object<string, *>=" : "null="); } else if (noRequiredParams) { // All parameters are optional or only owned by an indirect callee; caller doesn't need to // pass an object. jsDocBuilder.addParam("opt_data", "?" + alias + ".Params="); } else { jsDocBuilder.addParam("opt_data", "!" + alias + ".Params"); } jsDocBuilder.addGoogRequire(GoogRequire.createTypeRequire("goog.soy")); jsDocBuilder.addParam("opt_ijData", "?goog.soy.IjData="); String returnType = getTemplateReturnType(node); jsDocBuilder.addParameterizedAnnotation("return", returnType); // TODO(b/11787791): make the checkTypes suppression more fine grained. jsDocBuilder.addParameterizedAnnotation("suppress", "checkTypes"); return jsDocBuilder.build(); } @Override protected Statement generateFunctionBody(TemplateNode node, String alias) { ImmutableList.Builder<Statement> bodyStatements = ImmutableList.builder(); // Generate statement to ensure data is defined, if necessary. if (new ShouldEnsureDataIsDefinedVisitor().exec(node)) { bodyStatements.add( Statement.assign( JsRuntime.OPT_DATA, JsRuntime.OPT_DATA.or( EMPTY_OBJECT_LITERAL, templateTranslationContext.codeGenerator()))); } bodyStatements.add( node instanceof TemplateElementNode ? this.generateFunctionBodyForSoyElement(node) : this.generateIncrementalDomRenderCalls(node, alias)); return Statement.of(bodyStatements.build()); } /** Generates idom#elementOpen, idom#elementClose, etc. function calls for the given node. */ private Statement generateIncrementalDomRenderCalls(TemplateNode node, String alias) { IncrementalDomCodeBuilder jsCodeBuilder = getJsCodeBuilder(); boolean isTextTemplate = isTextContent(node.getContentKind()); Statement typeChecks = genParamTypeChecks(node, alias); ImmutableList.Builder<Statement> stateReassignmentBuilder = ImmutableList.builder(); if (node instanceof TemplateElementNode) { TemplateElementNode soyElement = (TemplateElementNode) node; for (TemplateHeaderVarDefn headerVar : Lists.newArrayList(soyElement.getStateVars())) { if (SoyTreeUtils.isConstantExpr(headerVar.defaultValue())) { continue; } stateReassignmentBuilder.add( Statement.assign( Expression.THIS.dotAccess(STATE_PREFIX + headerVar.name()), translateExpr(headerVar.defaultValue()))); } } List<Statement> reassignments = stateReassignmentBuilder.build(); Statement stateReassignments = Statement.of(reassignments); if (!reassignments.isEmpty()) { stateReassignments = Statement.ifStatement( Expression.THIS.dotAccess("shouldSyncState").call(), stateReassignments) .build(); } // Note: we do not try to combine this into a single return statement if the content is // computable as a JsExpr. A JavaScript compiler, such as Closure Compiler, is able to perform // the transformation. if (isTextTemplate) { // We do our own initialization below, so mark it as such. jsCodeBuilder.pushOutputVar("output").setOutputVarInited(); } Statement body = visitChildrenReturningCodeChunk(node); if (isTextTemplate) { VariableDeclaration declare = VariableDeclaration.builder("output").setRhs(LITERAL_EMPTY_STRING).build(); jsCodeBuilder.popOutputVar(); body = Statement.of(declare, body, returnValue(sanitize(declare.ref(), node.getContentKind()))); } return Statement.of(typeChecks, stateReassignments, body); } /** * Generates main template function body for Soy elements. Specifically, generates code to create * a new instance of the element class and invoke its #render method. */ private Statement generateFunctionBodyForSoyElement(TemplateNode node) { String soyElementClassName = this.getSoyElementClassName(); Expression firstElementKey = // Since Soy element roots cannot have manual keys (see go/soy-element-keyed-roots), // this will always be the first element key. JsRuntime.XID.call(Expression.stringLiteral(node.getTemplateName() + "-0")); return SOY_IDOM .dotAccess("$$handleSoyElement") .call( INCREMENTAL_DOM, id(soyElementClassName), firstElementKey, JsRuntime.OPT_DATA, JsRuntime.OPT_IJ_DATA) .asStatement(); } /** * Visits the children of a ParentSoyNode. This function is overridden to not do all of the work * that {@link GenJsCodeVisitor} does. */ @Override protected void visitChildren(ParentSoyNode<?> node) { for (SoyNode child : node.getChildren()) { visit(child); } } /** Generates class expression for the given template node, provided it is a Soy element. */ private VariableDeclaration generateClassForSoyElement( String soyElementClassName, String soyElementAccessorName, TemplateElementNode node) { String paramsType = node.getParams().isEmpty() ? "null" : "!" + alias + ".Params"; ImmutableList.Builder<MethodDeclaration> stateMethods = ImmutableList.builder(); for (TemplateStateVar stateVar : node.getStateVars()) { stateMethods.addAll( this.generateStateMethodsForSoyElementClass(soyElementClassName, stateVar)); } ImmutableList.Builder<MethodDeclaration> parameterMethods = ImmutableList.builder(); for (TemplateParam param : node.getParams()) { parameterMethods.add( this.generateGetParamMethodForSoyElementClass( param, /* isAbstract= */ false, /* isInjected= */ false)); } ImmutableList.Builder<MethodDeclaration> injectedParameterMethods = ImmutableList.builder(); for (TemplateParam injectedParam : node.getInjectedParams()) { injectedParameterMethods.add( this.generateGetParamMethodForSoyElementClass( injectedParam, /* isAbstract= */ false, /* isInjected= */ true)); } ImmutableList.Builder<Statement> stateVarInitializations = ImmutableList.builder(); for (TemplateStateVar stateVar : node.getStateVars()) { JsType jsType = JsType.forIncrementalDomState(stateVar.type()); JsDoc stateVarJsdoc = JsDoc.builder().addParameterizedAnnotation("private", jsType.typeExpr()).build(); Expression rhsValue; if (SoyTreeUtils.isConstantExpr(stateVar.defaultValue())) { rhsValue = translateExpr(stateVar.defaultValue()); } else { rhsValue = Expression.LITERAL_UNDEFINED.castAs("?"); } stateVarInitializations.add( Statement.assign( Expression.THIS.dotAccess(STATE_PREFIX + stateVar.name()), rhsValue, stateVarJsdoc)); } // Build constructor method. Statement ctorBody = Statement.of( id("super").call(JsRuntime.OPT_DATA, JsRuntime.OPT_IJ_DATA).asStatement(), Statement.of(stateVarInitializations.build())); MethodDeclaration constructorMethod = MethodDeclaration.create( "constructor", JsDoc.builder() .addParam("opt_data", paramsType) .addGoogRequire(GoogRequire.createTypeRequire("goog.soy")) .addParam("opt_ijData", "!goog.soy.IjData=") .build(), ctorBody); // Build `renderInternal` method. MethodDeclaration renderInternalMethod = MethodDeclaration.create( "renderInternal", JsDoc.builder() .addParam(INCREMENTAL_DOM_PARAM_NAME, "!incrementaldomlib.IncrementalDomRenderer") .addParam("opt_data", paramsType) .addAnnotation("protected") .addAnnotation("override") .addParameterizedAnnotation("suppress", "checkTypes") .build(), Statement.of( // Various parts of the js codegen expects these parameters to be in the local // scope. VariableDeclaration.builder("opt_ijData") .setRhs(Expression.THIS.dotAccess("ijData")) .build(), generateIncrementalDomRenderCalls(node, alias), Statement.returnValue(Expression.LITERAL_FALSE))); ClassExpression soyElementClass = ClassExpression.create( SOY_IDOM.dotAccess("$SoyElement"), ImmutableList.<MethodDeclaration>builder() .add(constructorMethod, renderInternalMethod) .addAll(stateMethods.build()) .addAll(parameterMethods.build()) .addAll(injectedParameterMethods.build()) .build()); String elementAccessor = soyElementClassName + "Interface"; VariableDeclaration classExpression = VariableDeclaration.builder(soyElementClassName) .setJsDoc( JsDoc.builder() .addAnnotation( "extends", "{soyIdom.$SoyElement<" + paramsType + ",!" + elementAccessor + ">}") .addParameterizedAnnotation("implements", soyElementAccessorName) .build()) .setRhs(soyElementClass) .build(); return classExpression; } /** Generates class expression for the given template node, provided it is a Soy element. */ private VariableDeclaration generateAccessorInterface( String className, TemplateElementNode node) { ImmutableList.Builder<MethodDeclaration> parameterMethods = ImmutableList.builder(); for (TemplateParam param : node.getParams()) { parameterMethods.add( this.generateGetParamMethodForSoyElementClass( param, /* isAbstract= */ true, /* isInjected= */ false)); } ImmutableList.Builder<MethodDeclaration> injectedParameterMethods = ImmutableList.builder(); for (TemplateParam injectedParam : node.getInjectedParams()) { injectedParameterMethods.add( this.generateGetParamMethodForSoyElementClass( injectedParam, /* isAbstract= */ true, /* isInjected= */ true)); } ClassExpression soyElementClass = ClassExpression.create( ImmutableList.<MethodDeclaration>builder() .addAll(parameterMethods.build()) .addAll(injectedParameterMethods.build()) .build()); VariableDeclaration classExpression = VariableDeclaration.builder(className) .setJsDoc(JsDoc.builder().addAnnotation("interface").build()) .setRhs(soyElementClass) .build(); return classExpression; } private Statement generateExportsForSoyElement(String soyElementClassName) { return Statement.assign( // Idom only supports goog.module generation. JsRuntime.EXPORTS.dotAccess( // Drop the leading '$' from soyElementClassName. soyElementClassName.substring(1)), id(soyElementClassName)); } /** * Generates `getFoo` (index 0) and `setFoo` (index 1) methods for a given `foo` state variable. */ private ImmutableList<MethodDeclaration> generateStateMethodsForSoyElementClass( String soyElementClassName, TemplateStateVar stateVar) { JsType jsType = JsType.forIncrementalDomState(stateVar.type()); String stateAccessorSuffix = Ascii.toUpperCase(stateVar.name().substring(0, 1)) + stateVar.name().substring(1); Expression stateValue = id("this").dotAccess(STATE_PREFIX + stateVar.name()); MethodDeclaration getStateMethod = MethodDeclaration.create( "get" + stateAccessorSuffix, JsDoc.builder().addParameterizedAnnotation("return", jsType.typeExpr()).build(), Statement.returnValue(stateValue)); jsType = JsType.forIncrementalDomState(stateVar.type()); ImmutableList.Builder<Statement> setStateMethodStatements = ImmutableList.builder(); Optional<Expression> typeAssertion = jsType.getSoyTypeAssertion( id(stateVar.name()), stateVar.name(), templateTranslationContext.codeGenerator()); if (typeAssertion.isPresent()) { setStateMethodStatements.add(typeAssertion.get().asStatement()); } setStateMethodStatements.add( stateValue.assign(id(stateVar.name())).asStatement(), Statement.returnValue(id("this"))); MethodDeclaration setStateMethod = MethodDeclaration.create( "set" + stateAccessorSuffix, JsDoc.builder() .addParam(stateVar.name(), jsType.typeExpr()) .addParameterizedAnnotation("return", "!" + soyElementClassName) .build(), Statement.of(setStateMethodStatements.build())); return ImmutableList.of(getStateMethod, setStateMethod); } /** Generates `get[X]` for a given parameter value. */ private MethodDeclaration generateGetParamMethodForSoyElementClass( TemplateParam param, boolean isAbstract, boolean isInjected) { JsType jsType = JsType.forIncrementalDomState(param.type()); String accessorSuffix = Ascii.toUpperCase(param.name().substring(0, 1)) + param.name().substring(1); if (isAbstract) { return MethodDeclaration.create( "get" + accessorSuffix, JsDoc.builder() .addAnnotation("abstract") // Injected params are marked as optional, see: .addParameterizedAnnotation("return", jsType.typeExpr()) .build(), Statement.of(ImmutableList.of())); } Expression value = id("this").dotAccess(isInjected ? "ijData" : "data").dotAccess(param.name()); if (param.hasDefault()) { value = templateTranslationContext .codeGenerator() .declarationBuilder() .setRhs(value) .build() .ref(); value = value.withInitialStatement( genParamDefault( param, value, alias, getJsTypeForParamTypeCheck(param.type()), /* declareStatic= */ false)); } // Injected params are marked as optional to account for unused templates, see: // We can assert the presence of the injected param if it being called. Optional<Expression> typeAssertion = isInjected ? jsType.getSoyTypeAssertion( value, param.name(), templateTranslationContext.codeGenerator()) : Optional.empty(); MethodDeclaration getParamMethod = MethodDeclaration.create( "get" + accessorSuffix, JsDoc.builder().addAnnotation("override").addAnnotation("public").build(), Statement.returnValue(typeAssertion.orElse(value))); return getParamMethod; } /** Constructs template class name, e.g. converts template `ns.foo` => `$FooElement`. */ private String getSoyElementClassName() { Preconditions.checkState( alias.startsWith("$"), "Alias should start with '$', or template class name may be malformed."); return "$" // `alias` has '$' as the 0th char, so capitalize the 1st char. + Ascii.toUpperCase(alias.charAt(1)) /// ...and concat the rest of the alias. + alias.substring(2) + "Element"; } /** * Generates the content of a {@code let} or {@code param} statement. For HTML and attribute * let/param statements, the generated instructions inside the node are wrapped in a function * which will be optionally passed to another template and invoked in the correct location. All * other kinds of let statements are generated as a simple variable. */ private void visitLetParamContentNode(RenderUnitNode node, String generatedVarName) { // The html transform step, performed by HtmlContextVisitor, ensures that // we always have a content kind specified. checkState(node.getContentKind() != null); IncrementalDomCodeBuilder jsCodeBuilder = getJsCodeBuilder(); SanitizedContentKind prevContentKind = jsCodeBuilder.getContentKind(); jsCodeBuilder.setContentKind(node.getContentKind()); CodeChunk definition; VariableDeclaration.Builder builder = VariableDeclaration.builder(generatedVarName); SanitizedContentKind kind = node.getContentKind(); if (kind == SanitizedContentKind.HTML || kind == SanitizedContentKind.ATTRIBUTES) { Expression constructor; if (kind == SanitizedContentKind.HTML) { constructor = SOY_IDOM_MAKE_HTML; } else { constructor = SOY_IDOM_MAKE_ATTRIBUTES; } JsDoc jsdoc = JsDoc.builder() .addParam(INCREMENTAL_DOM_PARAM_NAME, "incrementaldomlib.IncrementalDomRenderer") .build(); definition = builder .setRhs( constructor.call( Expression.arrowFunction(jsdoc, visitChildrenReturningCodeChunk(node)))) .build(); } else { // We do our own initialization, so mark it as such. String outputVarName = generatedVarName + "_output"; jsCodeBuilder.pushOutputVar(outputVarName).setOutputVarInited(); // TODO(b/246994962): Skip this definition for SanitizedContentKind.TEXT. definition = Statement.of( VariableDeclaration.builder(outputVarName).setRhs(LITERAL_EMPTY_STRING).build(), visitChildrenReturningCodeChunk(node), builder .setRhs( kind == SanitizedContentKind.TEXT ? id(outputVarName) : JsRuntime.sanitizedContentOrdainerFunctionForInternalBlocks( node.getContentKind()) .call(id(outputVarName))) .build()); jsCodeBuilder.popOutputVar(); } jsCodeBuilder.setContentKind(prevContentKind); jsCodeBuilder.append(definition); } /** * Generates the content of a {@code let} statement. For HTML and attribute let statements, the * generated instructions inside the node are wrapped in a function which will be optionally * passed to another template and invoked in the correct location. All other kinds of let/param * statements are generated as a simple variable. */ @Override protected void visitLetContentNode(LetContentNode node) { String generatedVarName = node.getUniqueVarName(); visitLetParamContentNode(node, generatedVarName); templateTranslationContext .soyToJsVariableMappings() .put(node.getVarName(), id(generatedVarName)); } @Override protected void visitCallParamContentNode(CallParamContentNode node) { String generatedVarName = "param" + node.getId(); visitLetParamContentNode(node, generatedVarName); } @Override protected void visitCallNode(CallNode node) { // If this node has any CallParamContentNode children those contents are not computable as JS // expressions, visit them to generate code to define their respective 'param<n>' variables. for (CallParamNode child : node.getChildren()) { if (child instanceof CallParamContentNode && !isComputableAsJsExprsVisitor.exec(child)) { visit(child); } } Expression call; Optional<SanitizedContentKind> kind = templateRegistry.getCallContentKind(node); Expression callee = genCallCodeUtils.genCallee(node, templateAliases, getExprTranslator()); Expression objToPass = genCallCodeUtils.genObjToPass( node, templateAliases, templateTranslationContext, errorReporter, getExprTranslator()); boolean shouldPushKey = false; if (STRINGLIKE_KINDS.contains(node.getHtmlContext()) && (!kind.isPresent() || kind.get() == SanitizedContentKind.ATTRIBUTES || kind.get() == SanitizedContentKind.HTML)) { call = SOY_IDOM_CALL_DYNAMIC_TEXT.call(callee, objToPass, JsRuntime.OPT_IJ_DATA); } else if (kind.isPresent() && (kind.get() == SanitizedContentKind.HTML || kind.get() == SanitizedContentKind.ATTRIBUTES)) { // This is executed in the case of HTML/ATTR -> HTML/ATTR. All other ambiguous cases are // passed through to runtime functions. call = callee.call(INCREMENTAL_DOM, objToPass, JsRuntime.OPT_IJ_DATA); shouldPushKey = true; } else { // This is executed in the case of TEXT Context -> Text Template call = callee.call(objToPass, JsRuntime.OPT_IJ_DATA); } if (STRINGLIKE_KINDS.contains(node.getHtmlContext())) { call = GenCallCodeUtils.applyEscapingDirectives(call, node); getJsCodeBuilder().addChunkToOutputVar(call); } else { switch (node.getHtmlContext()) { case HTML_TAG: if (!kind.isPresent() || kind.get() != SanitizedContentKind.ATTRIBUTES) { call = SOY_IDOM_CALL_DYNAMIC_ATTRIBUTES.call( INCREMENTAL_DOM, callee, objToPass, JsRuntime.OPT_IJ_DATA); } break; case CSS: call = SOY_IDOM_CALL_DYNAMIC_CSS.call( INCREMENTAL_DOM, callee, objToPass, JsRuntime.OPT_IJ_DATA); break; case JS: call = SOY_IDOM_CALL_DYNAMIC_JS.call( INCREMENTAL_DOM, callee, objToPass, JsRuntime.OPT_IJ_DATA); break; default: if (!kind.isPresent() || kind.get() != SanitizedContentKind.HTML) { call = SOY_IDOM_CALL_DYNAMIC_HTML.call( INCREMENTAL_DOM, callee, objToPass, JsRuntime.OPT_IJ_DATA); shouldPushKey = true; } break; } TemplateNode template = node.getNearestAncestor(TemplateNode.class); String keyVariable = "_keyVariable" + staticsCounter++; if (shouldPushKey) { if (node.getKeyExpr() != null) { getJsCodeBuilder() .append(INCREMENTAL_DOM_PUSH_MANUAL_KEY.call(translateExpr(node.getKeyExpr()))); } else { getJsCodeBuilder() .append( VariableDeclaration.builder(keyVariable) .setRhs(INCREMENTAL_DOM_PUSH_KEY.call(incrementKeyForCall(template))) .build()); } } // TODO: In reality, the CALL_X functions are really just IDOM versions of the related // escaping directives. Consider doing a replace instead of not using escaping directives // at all. getJsCodeBuilder().append(call); if (shouldPushKey) { if (node.getKeyExpr() != null) { getJsCodeBuilder().append(INCREMENTAL_DOM_POP_MANUAL_KEY.call()); } else { getJsCodeBuilder().append(INCREMENTAL_DOM_POP_KEY.call(Expression.id(keyVariable))); } } } } /** * Generates calls in HTML/Attributes content as non-JsExprs, since Incremental DOM instructions * are needed and not a JavaScript expression. */ @Override protected void visitIfNode(IfNode node) { IncrementalDomCodeBuilder jsCodeBuilder = getJsCodeBuilder(); SanitizedContentKind currentContentKind = jsCodeBuilder.getContentKind(); if (!isTextContent(currentContentKind)) { super.generateNonExpressionIfNode(node); } else { super.visitIfNode(node); } } /** * Determines if a given type of content represents text or some sort of HTML. * * @param contentKind The kind of content to check. * @return True if the content represents text, false otherwise. */ private boolean isTextContent(SanitizedContentKind contentKind) { return contentKind != SanitizedContentKind.HTML && contentKind != SanitizedContentKind.ATTRIBUTES; } @Override protected TranslateExprNodeVisitor getExprTranslator() { return new IncrementalDomTranslateExprNodeVisitor( javaScriptValueFactory, templateTranslationContext, errorReporter); } @Override protected void visitHtmlCommentNode(HtmlCommentNode node) { String id = "html_comment_" + node.getId(); getJsCodeBuilder() .append(VariableDeclaration.builder(id).setRhs(Expression.LITERAL_EMPTY_STRING).build()); getJsCodeBuilder().pushOutputVar(id).setOutputVarInited(); SanitizedContentKind prev = getJsCodeBuilder().getContentKind(); getJsCodeBuilder().setContentKind(SanitizedContentKind.TEXT); for (int i = 0; i < node.numChildren(); i++) { visit(node.getChild(i)); } getJsCodeBuilder().append(SOY_IDOM_VISIT_HTML_COMMENT.call(INCREMENTAL_DOM, id(id))); getJsCodeBuilder().popOutputVar(); getJsCodeBuilder().setContentKind(prev); } /** * Visits the {@link HtmlAttributeNode}. The attribute nodes will typically be children of the * corresponding {@link HtmlOpenTagNode} or in a let/param of kind attributes, e.g. * * <pre> * {let $attrs kind="attributes"} * attr="value" * {/let} * </pre> * * This method prints the attribute declaration calls. For example, given * * <pre> * &lt;div {if $condition}attr="value"{/if}&gt; * </pre> * * it would print the call to {@code incrementalDom.attr}, resulting in: * * <pre> * if (condition) { * IncrementalDom.attr(attr, "value"); * } * </pre> */ @Override protected void visitHtmlAttributeNode(HtmlAttributeNode node) { IncrementalDomCodeBuilder jsCodeBuilder = getJsCodeBuilder(); if (node.hasValue()) { // Attribute keys can only be print statements or constants. As such, the first child // should be the key and the second the value. checkState(isComputableAsJsExprsVisitor.exec(node.getChild(0))); jsCodeBuilder.append( INCREMENTAL_DOM_ATTR.call( // Attributes can only be print nodes or constants genJsExprsVisitor.exec(node.getChild(0)).get(0), CodeChunkUtils.concatChunksForceString(getAttributeValues(node)))); } else { visitChildren(node); // Prints raw text or attributes node. } } @Override protected void visitHtmlAttributeValueNode(HtmlAttributeValueNode node) { // ignore quotes since idom doesn't care about them, so we just iterate the children. visitChildren(node); } private List<Expression> getAttributeValues(HtmlAttributeNode node) { if (!node.hasValue()) { // No attribute value, e.g. "<button disabled></button>". Need to put an empty string so that // the runtime knows to create an attribute. return ImmutableList.of(LITERAL_EMPTY_STRING); } ParentSoyNode<?> value = (ParentSoyNode<?>) node.getChild(1); String outputVar = "html_attribute_" + node.getId(); boolean needsToBeCoerced = false; // There may be HTML nodes in the children that can get coerced to a string. In this case, // the appending path needs to be executed. for (Object n : value.getChildren()) { if (n instanceof CallNode) { Optional<SanitizedContentKind> kind = templateRegistry.getCallContentKind((CallNode) n); needsToBeCoerced = !kind.isPresent() || kind.get() == SanitizedContentKind.HTML || kind.get() == SanitizedContentKind.ATTRIBUTES; } } if (!isComputableAsJsExprsVisitor.execOnChildren(value) || needsToBeCoerced) { getJsCodeBuilder().pushOutputVar(outputVar).setOutputVarInited(); SanitizedContentKind prev = getJsCodeBuilder().getContentKind(); getJsCodeBuilder().setContentKind(SanitizedContentKind.TEXT); IncrementalDomCodeBuilder jsCodeBuilder = getJsCodeBuilder(); jsCodeBuilder.append( VariableDeclaration.builder(outputVar).setRhs(Expression.LITERAL_EMPTY_STRING).build()); visit(value); getJsCodeBuilder().popOutputVar(); getJsCodeBuilder().setContentKind(prev); return ImmutableList.of(id(outputVar)); } return genJsExprsVisitor.exec(value); } /** * Returns a unique key for the template. This has the side-effect of incrementing the current * keyCounter at the top of the stack. */ private Expression incrementKeyForTemplate(TemplateNode template) { Holder<Integer> keyCounter = keyCounterStack.peek(); return JsRuntime.XID.call( Expression.stringLiteral(template.getTemplateName() + "-" + keyCounter.elementValue++)); } /** * Returns a unique key for the template. This has the side-effect of incrementing the current * keyCounter at the top of the stack. This is for calls to disambugate between HTML nodes and * calls. */ private Expression incrementKeyForCall(TemplateNode template) { Holder<Integer> keyCounter = keyCounterStack.peek(); return JsRuntime.XID.call( Expression.stringLiteral(template.getTemplateName() + "-call-" + keyCounter.callValue++)); } /** * Removes static children from {@code node} and returns them in a map of key to value. For * attribute nodes that are known to be static, we can improve performance by adding them to the * statics array(http://google.github.io/incremental-dom/#statics-array). */ private ImmutableMap<String, Expression> getStaticAttributes(HtmlOpenTagNode node) { List<HtmlAttributeNode> nodesToRemove = new ArrayList<>(); ImmutableMap.Builder<String, Expression> builder = ImmutableMap.builder(); // The 0th index is actually the tag itself, so we don't need to iterate over it. for (int i = 1; i < node.numChildren(); i++) { if (node.getChild(i) instanceof HtmlAttributeNode) { HtmlAttributeNode attrNode = (HtmlAttributeNode) node.getChild(i); String attributeKey = attrNode.getStaticKey(); Expression value = getStaticContent(attrNode); if (attributeKey != null && value != null) { nodesToRemove.add(attrNode); builder.put(attributeKey, value); } } } for (HtmlAttributeNode child : nodesToRemove) { node.removeChild(child); } return builder.build(); } /** * Extract static content from attributes, or return null if value is dynamic. Static content is * either an attribute value that is nonexistent or a combination of raw text and xid/css calls. */ private Expression getStaticContent(HtmlAttributeNode node) { if (!node.hasValue()) { return Expression.stringLiteral(""); } // This case is some control flow like a switch, if, or for loop. if (!(node.getChild(1) instanceof HtmlAttributeValueNode)) { return null; } HtmlAttributeValueNode attrValue = (HtmlAttributeValueNode) node.getChild(1); if (attrValue.numChildren() == 0) { return Expression.stringLiteral(""); } // If any children are not raw text or constant xid/css calls, return null for (int i = 0; i < attrValue.numChildren(); i++) { if (attrValue.getChild(i) instanceof RawTextNode) { continue; } else if (attrValue.getChild(i) instanceof PrintNode) { PrintNode n = (PrintNode) attrValue.getChild(i); if (n.getExpr().getRoot() instanceof FunctionNode) { FunctionNode fnNode = (FunctionNode) n.getExpr().getRoot(); if (fnNode.getSoyFunction() != BuiltinFunction.XID && fnNode.getSoyFunction() != BuiltinFunction.CSS) { return null; // Function call was not xid or css } } else { // Child is variable expression ie {$foo} or {$foo + $bar} return null; } } else { // Child was control flow. return null; } } return CodeChunkUtils.concatChunksForceString(getAttributeValues(node)); } private Expression getOpenSSRCall(HtmlOpenTagNode node, SkipNode skip) { List<Expression> args = new ArrayList<>(); args.add(getTagNameCodeChunk(node.getTagName())); KeyNode keyNode = node.getKeyNode(); if (keyNode == null) { args.add(JsRuntime.XID.call(Expression.stringLiteral(skip.getSkipId()))); } else { // Key difference between getOpen and getOpenSSR args.add(translateExpr(node.getKeyNode().getExpr())); } if (node.isElementRoot()) { args.add(JsRuntime.OPT_DATA); } return INCREMENTAL_DOM_OPEN_SSR.call(args); } private Expression getOpenCall(HtmlOpenTagNode node) { TemplateNode template = node.getNearestAncestor(TemplateNode.class); List<Expression> args = new ArrayList<>(); args.add(getTagNameCodeChunk(node.getTagName())); KeyNode keyNode = node.getKeyNode(); Expression key = Expression.LITERAL_UNDEFINED; if (keyNode == null) { key = incrementKeyForTemplate(template); } else { keyCounterStack.push(new Holder<>(0, 0)); } args.add(key); return INCREMENTAL_DOM_OPEN.call(args); } private Optional<Expression> getApplyStaticAttributes(HtmlOpenTagNode node) { Map<String, Expression> staticAttributes = getStaticAttributes(node); ImmutableList.Builder<Expression> staticsBuilder = ImmutableList.builder(); for (Map.Entry<String, Expression> entry : staticAttributes.entrySet()) { staticsBuilder.add(Expression.stringLiteral(entry.getKey())); staticsBuilder.add(entry.getValue()); } // Instead of inlining the array, place the variable declaration in the global scope // and lazily initialize it in the template. if (!staticAttributes.isEmpty()) { String id = "_statics_" + staticsCounter++; Expression idExpr = id(alias + id); Expression lazyAssignment = // Generator can be null because we know this evaluates to an or // ie alias_statics_1 || alias_statics_1 = [] idExpr.or( idExpr.assign(Expression.arrayLiteral(staticsBuilder.build())), /* codeGenerator= */ null); staticVarDeclarations.add(VariableDeclaration.builder(alias + id).build()); return Optional.of(INCREMENTAL_DOM_APPLY_STATICS.call(lazyAssignment)); } return Optional.empty(); } private Expression getApplyAttrs(HtmlOpenTagNode node) { for (int i = 1; i < node.numChildren(); i++) { visit(node.getChild(i)); } return INCREMENTAL_DOM_APPLY_ATTRS.call(); } /** * Visits an {@link HtmlOpenTagNode} and emits appropriate attr/staticAttr calls and maybe a self * close tag. * * <pre> * &lt;div attr="value" attr2="{$someVar}"&gt;...&lt;/div&gt; * </pre> * * generates * * <pre> * open('div'); * attr('attr', 'value'); * attr('attr2', someVar); * applyAttrs() * ... * * close() * </pre> */ @Override protected void visitHtmlOpenTagNode(HtmlOpenTagNode node) { IncrementalDomCodeBuilder jsCodeBuilder = getJsCodeBuilder(); if (!node.isSkipRoot()) { if (node.getKeyNode() != null) { // Push key BEFORE emitting `elementOpen`. Later, for `elementOpen` calls of keyed elements, // we do not specify any key. Expression key = translateExpr(node.getKeyNode().getExpr()); getJsCodeBuilder().append(INCREMENTAL_DOM_PUSH_MANUAL_KEY.call(key)); } Expression openTagExpr = getOpenCall(node); if (node.isElementRoot()) { // Append code to stash the template object in this node. jsCodeBuilder.append( Statement.ifStatement( INCREMENTAL_DOM_MAYBE_SKIP.call(INCREMENTAL_DOM, openTagExpr), Statement.returnValue(Expression.LITERAL_TRUE)) .build()); } else { jsCodeBuilder.append(openTagExpr.asStatement()); } } jsCodeBuilder.append(getAttributeAndCloseCalls(node)); } private Statement getAttributeAndCloseCalls(HtmlOpenTagNode node) { List<Statement> statements = new ArrayList<>(); Optional<Expression> maybeApplyStatics = getApplyStaticAttributes(node); if (maybeApplyStatics.isPresent()) { statements.add(maybeApplyStatics.get().asStatement()); } statements.add(getApplyAttrs(node).asStatement()); // Whether or not it is valid for this tag to be self closing has already been validated by the // HtmlContextVisitor. So we just need to output the close instructions if the node is self // closing or definitely void. if (node.isSelfClosing() || node.getTagName().isDefinitelyVoid()) { statements.add(INCREMENTAL_DOM_CLOSE.call().asStatement()); } return Statement.of(statements); } /** * Visits an {@link HtmlCloseTagNode}, which occurs when an HTML tag is closed. For example: * * <pre> * &lt;/div&gt; * </pre> * * generates * * <pre> * incrementalDom.close('div'); * </pre> */ @Override protected void visitHtmlCloseTagNode(HtmlCloseTagNode node) { // This case occurs in the case where we encounter the end of a keyed element. If the open tag // mapped to this close tag contains a key node, pop the keyCounterStack to return // to the state before entering the keyed node. if (node.getTaggedPairs().size() == 1) { HtmlOpenTagNode openTag = (HtmlOpenTagNode) node.getTaggedPairs().get(0); if (openTag.getKeyNode() != null && !(openTag.getParent() instanceof SkipNode)) { keyCounterStack.pop(); getJsCodeBuilder().append(INCREMENTAL_DOM_POP_MANUAL_KEY.call()); } } if (!node.getTagName().isDefinitelyVoid()) { getJsCodeBuilder().append(INCREMENTAL_DOM_CLOSE.call().asStatement()); } } /** * Visits a {@link RawTextNode}, which occurs either as a child of any BlockNode or the 'child' of * an HTML tag. Note that in the soy tree, tags and their logical HTML children do not have a * parent-child relationship, but are rather siblings. For example: * * <pre> * &lt;div&gt;Hello world&lt;/div&gt; * </pre> * * The text "Hello world" translates to * * <pre> * incrementalDom.text('Hello world'); * </pre> */ @Override protected void visitRawTextNode(RawTextNode node) { Expression textArg = stringLiteral(node.getRawText()); JsCodeBuilder jsCodeBuilder = getJsCodeBuilder(); switch (node.getHtmlContext()) { case JS: case CSS: case HTML_RCDATA: case HTML_PCDATA: // Note - we don't use generateTextCall since this text can never be null. jsCodeBuilder.append(INCREMENTAL_DOM_TEXT.call(textArg)); break; case HTML_TAG: jsCodeBuilder.append(INCREMENTAL_DOM_ATTR.call(textArg, stringLiteral(""))); break; default: jsCodeBuilder.addChunkToOutputVar(textArg); break; } } /** * Visit an {@link PrintNode}, with special cases for a variable being printed within an attribute * declaration or as HTML content. * * <p>For attributes, if the variable is of kind attributes, it is invoked. Any other kind of * variable is an error. * * <p>For HTML, if the variable is of kind HTML, it is invoked. Any other kind of variable gets * wrapped in a call to {@code incrementalDom.text}, resulting in a Text node. */ @Override protected void visitPrintNode(PrintNode node) { List<Expression> chunks = genJsExprsVisitor.exec(node); switch (node.getHtmlContext()) { case HTML_TAG: getJsCodeBuilder() .append( SOY_IDOM_PRINT_DYNAMIC_ATTR.call( INCREMENTAL_DOM, CodeChunkUtils.concatChunks(chunks))); break; case JS: // fall through case CSS: // fall through case HTML_PCDATA: if (node.numChildren() > 0 && node.getChild(node.numChildren() - 1).getPrintDirective() instanceof SanitizedContentOperator && ((SanitizedContentOperator) node.getChild(node.numChildren() - 1).getPrintDirective()) .getContentKind() == SanitizedContent.ContentKind.HTML) { getJsCodeBuilder() .append( SOY_IDOM_PRINT.call( INCREMENTAL_DOM, CodeChunkUtils.concatChunks(chunks), Expression.LITERAL_TRUE)); } else { getJsCodeBuilder() .append(SOY_IDOM_PRINT.call(INCREMENTAL_DOM, CodeChunkUtils.concatChunks(chunks))); } break; case HTML_RCDATA: getJsCodeBuilder() .append( INCREMENTAL_DOM_TEXT.call(id("String").call(CodeChunkUtils.concatChunks(chunks)))); break; default: super.visitPrintNode(node); break; } } @Override protected void visitSkipNode(SkipNode node) { IncrementalDomCodeBuilder jsCodeBuilder = getJsCodeBuilder(); HtmlOpenTagNode openTag = (HtmlOpenTagNode) node.getChild(0); Expression openTagExpr = getOpenSSRCall(openTag, node); Statement childStatements = visitChildrenReturningCodeChunk(node); jsCodeBuilder.append(Statement.ifStatement(openTagExpr, Statement.of(childStatements)).build()); } @Override protected void visitVeLogNode(VeLogNode node) { VeLogStateHolder state = openVeLogNode(node); getJsCodeBuilder().append(state.enterStatement); visitChildren(node); getJsCodeBuilder().append(exitVeLogNode(node, state.logOnlyConditional)); } VeLogStateHolder openVeLogNode(VeLogNode node) { Expression isLogOnly = Expression.LITERAL_FALSE; VariableDeclaration isLogOnlyVar = null; Expression isLogOnlyReference = null; if (node.getLogonlyExpression() != null) { String idName = "velog_" + staticsCounter++; isLogOnlyReference = id(idName); isLogOnly = getExprTranslator().exec(node.getLogonlyExpression()); isLogOnlyVar = VariableDeclaration.builder(idName).setRhs(isLogOnly).build(); getJsCodeBuilder() .append( Statement.of( isLogOnlyVar, Statement.ifStatement( INCREMENTAL_DOM_VERIFY_LOGONLY.call(isLogOnlyVar.ref()), Statement.assign(INCREMENTAL_DOM, INCREMENTAL_DOM_TONULL.call())) .build())); } Expression veData = getExprTranslator().exec(node.getVeDataExpression()); return new VeLogStateHolder( isLogOnlyReference, INCREMENTAL_DOM_ENTER.call(veData, isLogOnly).asStatement()); } Statement exitVeLogNode(VeLogNode node, Expression isLogOnly) { Statement exit = INCREMENTAL_DOM_EXIT.call().asStatement(); if (isLogOnly != null) { return Statement.of( exit, Statement.ifStatement( isLogOnly, Statement.assign(INCREMENTAL_DOM, INCREMENTAL_DOM_TODEFAULT.call())) .build()); } return exit; } @Override protected void visitMsgFallbackGroupNode(MsgFallbackGroupNode node) { Expression msgExpression; switch (node.getHtmlContext()) { case HTML_PCDATA: String id = "_msg_" + alias + "_" + staticsCounter++; VariableDeclaration staticDecl = VariableDeclaration.builder(id) .setRhs(Expression.objectLiteral(ImmutableMap.of())) .build(); staticVarDeclarations.add(staticDecl); CodeChunk chunk = new AssistantForHtmlMsgs( /* master= */ this, jsSrcOptions, genCallCodeUtils, isComputableAsJsExprsVisitor, templateAliases, genJsExprsVisitor, templateTranslationContext, errorReporter, id) .generateMsgGroupCode(node); getJsCodeBuilder().append(chunk); break; // Messages in attribute values are plain text. However, since the translated content // includes entities (because other Soy backends treat these messages as HTML source), we // must unescape the translations before passing them to the idom APIs. case HTML_NORMAL_ATTR_VALUE: msgExpression = new AssistantForAttributeMsgs( /* master= */ this, jsSrcOptions, genCallCodeUtils, isComputableAsJsExprsVisitor, templateAliases, genJsExprsVisitor, templateTranslationContext, errorReporter) .generateMsgGroupVariable(node); getJsCodeBuilder().addChunkToOutputVar(GOOG_STRING_UNESCAPE_ENTITIES.call(msgExpression)); break; case HTML_RCDATA: msgExpression = getAssistantForMsgs().generateMsgGroupVariable(node); getJsCodeBuilder().append(INCREMENTAL_DOM_TEXT.call(id("String").call(msgExpression))); break; default: msgExpression = getAssistantForMsgs().generateMsgGroupVariable(node); getJsCodeBuilder().addChunkToOutputVar(msgExpression); break; } } @Override protected void visitMsgHtmlTagNode(MsgHtmlTagNode node) { visitChildren(node); } private Expression getTagNameCodeChunk(TagName tagName) { // No need to check if is computable as js expr because tag names can only be // print nodes and constants. return genJsExprsVisitor.exec(tagName.getNode()).get(0); } /** * Handles <code>{msg}</code> commands in attribute context for idom. The literal text in the * translated message must be unescaped after translation, because we pass the text directly to * DOM text APIs, whereas translators write HTML with entities. Therefore, we must first escape * all interpolated placeholders (which can only be TEXT values). * * <p>In non-idom, this happens in the contextual auto-escaper. */ private static final class AssistantForAttributeMsgs extends GenJsCodeVisitorAssistantForMsgs { AssistantForAttributeMsgs( GenIncrementalDomCodeVisitor master, SoyJsSrcOptions jsSrcOptions, GenCallCodeUtils genCallCodeUtils, IsComputableAsJsExprsVisitor isComputableAsJsExprsVisitor, TemplateAliases functionAliases, GenJsExprsVisitor genJsExprsVisitor, TranslationContext translationContext, ErrorReporter errorReporter) { super( master, jsSrcOptions, genCallCodeUtils, isComputableAsJsExprsVisitor, functionAliases, genJsExprsVisitor, translationContext, errorReporter); } @Override protected Expression genGoogMsgPlaceholder(MsgPlaceholderNode msgPhNode) { Expression toEscape = super.genGoogMsgPlaceholder(msgPhNode); return SOY_ESCAPE_HTML.call(toEscape); } } }
java/src/com/google/template/soy/incrementaldomsrc/GenIncrementalDomCodeVisitor.java
/* * Copyright 2015 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.template.soy.incrementaldomsrc; import static com.google.common.base.Preconditions.checkState; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.INCREMENTAL_DOM; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.INCREMENTAL_DOM_APPLY_ATTRS; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.INCREMENTAL_DOM_APPLY_STATICS; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.INCREMENTAL_DOM_ATTR; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.INCREMENTAL_DOM_CLOSE; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.INCREMENTAL_DOM_ENTER; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.INCREMENTAL_DOM_EXIT; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.INCREMENTAL_DOM_LIB; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.INCREMENTAL_DOM_MAYBE_SKIP; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.INCREMENTAL_DOM_OPEN; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.INCREMENTAL_DOM_OPEN_SSR; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.INCREMENTAL_DOM_PARAM_NAME; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.INCREMENTAL_DOM_POP_KEY; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.INCREMENTAL_DOM_POP_MANUAL_KEY; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.INCREMENTAL_DOM_PUSH_KEY; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.INCREMENTAL_DOM_PUSH_MANUAL_KEY; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.INCREMENTAL_DOM_TEXT; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.INCREMENTAL_DOM_TODEFAULT; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.INCREMENTAL_DOM_TONULL; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.INCREMENTAL_DOM_VERIFY_LOGONLY; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.SOY_IDOM; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.SOY_IDOM_CALL_DYNAMIC_ATTRIBUTES; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.SOY_IDOM_CALL_DYNAMIC_CSS; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.SOY_IDOM_CALL_DYNAMIC_HTML; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.SOY_IDOM_CALL_DYNAMIC_JS; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.SOY_IDOM_CALL_DYNAMIC_TEXT; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.SOY_IDOM_MAKE_ATTRIBUTES; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.SOY_IDOM_MAKE_HTML; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.SOY_IDOM_PRINT; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.SOY_IDOM_PRINT_DYNAMIC_ATTR; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.SOY_IDOM_TYPE_ATTRIBUTE; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.SOY_IDOM_TYPE_HTML; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.SOY_IDOM_VISIT_HTML_COMMENT; import static com.google.template.soy.incrementaldomsrc.IncrementalDomRuntime.STATE_PREFIX; import static com.google.template.soy.jssrc.dsl.Expression.EMPTY_OBJECT_LITERAL; import static com.google.template.soy.jssrc.dsl.Expression.LITERAL_EMPTY_STRING; import static com.google.template.soy.jssrc.dsl.Expression.id; import static com.google.template.soy.jssrc.dsl.Expression.stringLiteral; import static com.google.template.soy.jssrc.dsl.Statement.returnValue; import static com.google.template.soy.jssrc.internal.JsRuntime.GOOG_STRING_UNESCAPE_ENTITIES; import static com.google.template.soy.jssrc.internal.JsRuntime.SOY_ESCAPE_HTML; import com.google.common.base.Ascii; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.template.soy.base.internal.SanitizedContentKind; import com.google.template.soy.data.SanitizedContent; import com.google.template.soy.data.SanitizedContentOperator; import com.google.template.soy.error.ErrorReporter; import com.google.template.soy.exprtree.FunctionNode; import com.google.template.soy.incrementaldomsrc.GenIncrementalDomExprsVisitor.GenIncrementalDomExprsVisitorFactory; import com.google.template.soy.jssrc.SoyJsSrcOptions; import com.google.template.soy.jssrc.dsl.ClassExpression; import com.google.template.soy.jssrc.dsl.ClassExpression.MethodDeclaration; import com.google.template.soy.jssrc.dsl.CodeChunk; import com.google.template.soy.jssrc.dsl.CodeChunkUtils; import com.google.template.soy.jssrc.dsl.Expression; import com.google.template.soy.jssrc.dsl.GoogRequire; import com.google.template.soy.jssrc.dsl.JsDoc; import com.google.template.soy.jssrc.dsl.Statement; import com.google.template.soy.jssrc.dsl.VariableDeclaration; import com.google.template.soy.jssrc.internal.CanInitOutputVarVisitor; import com.google.template.soy.jssrc.internal.GenCallCodeUtils; import com.google.template.soy.jssrc.internal.GenJsCodeVisitor; import com.google.template.soy.jssrc.internal.GenJsCodeVisitorAssistantForMsgs; import com.google.template.soy.jssrc.internal.GenJsExprsVisitor; import com.google.template.soy.jssrc.internal.IsComputableAsJsExprsVisitor; import com.google.template.soy.jssrc.internal.JavaScriptValueFactoryImpl; import com.google.template.soy.jssrc.internal.JsCodeBuilder; import com.google.template.soy.jssrc.internal.JsRuntime; import com.google.template.soy.jssrc.internal.JsType; import com.google.template.soy.jssrc.internal.TemplateAliases; import com.google.template.soy.jssrc.internal.TranslateExprNodeVisitor; import com.google.template.soy.jssrc.internal.TranslationContext; import com.google.template.soy.passes.ShouldEnsureDataIsDefinedVisitor; import com.google.template.soy.shared.internal.BuiltinFunction; import com.google.template.soy.soytree.CallNode; import com.google.template.soy.soytree.CallParamContentNode; import com.google.template.soy.soytree.CallParamNode; import com.google.template.soy.soytree.HtmlAttributeNode; import com.google.template.soy.soytree.HtmlAttributeValueNode; import com.google.template.soy.soytree.HtmlCloseTagNode; import com.google.template.soy.soytree.HtmlCommentNode; import com.google.template.soy.soytree.HtmlContext; import com.google.template.soy.soytree.HtmlOpenTagNode; import com.google.template.soy.soytree.IfNode; import com.google.template.soy.soytree.KeyNode; import com.google.template.soy.soytree.LetContentNode; import com.google.template.soy.soytree.MsgFallbackGroupNode; import com.google.template.soy.soytree.MsgHtmlTagNode; import com.google.template.soy.soytree.MsgPlaceholderNode; import com.google.template.soy.soytree.PrintNode; import com.google.template.soy.soytree.RawTextNode; import com.google.template.soy.soytree.SkipNode; import com.google.template.soy.soytree.SoyNode; import com.google.template.soy.soytree.SoyNode.ParentSoyNode; import com.google.template.soy.soytree.SoyNode.RenderUnitNode; import com.google.template.soy.soytree.SoyTreeUtils; import com.google.template.soy.soytree.TagName; import com.google.template.soy.soytree.TemplateDelegateNode; import com.google.template.soy.soytree.TemplateElementNode; import com.google.template.soy.soytree.TemplateNode; import com.google.template.soy.soytree.VeLogNode; import com.google.template.soy.soytree.defn.TemplateHeaderVarDefn; import com.google.template.soy.soytree.defn.TemplateParam; import com.google.template.soy.soytree.defn.TemplateStateVar; import com.google.template.soy.types.SoyType; import com.google.template.soy.types.SoyTypeRegistry; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; /** * Generates a series of JavaScript control statements and function calls for rendering one or more * templates as HTML. This heavily leverages {@link GenJsCodeVisitor}, adding logic to print the * function calls and changing how statements are combined. */ public final class GenIncrementalDomCodeVisitor extends GenJsCodeVisitor { private static final String NAMESPACE_EXTENSION = ".incrementaldom"; private static final ImmutableList<HtmlContext> STRINGLIKE_KINDS = ImmutableList.of( HtmlContext.URI, HtmlContext.TEXT, HtmlContext.HTML_ATTRIBUTE_NAME, HtmlContext.HTML_NORMAL_ATTR_VALUE); private static class Holder<T> { T value; public Holder(T value) { this.value = value; } } /** * Class that contains the state generated from visiting the beginning of a velogging statement. * This allows one to generate code such as * * <pre> * var velog_1 = foobar; * if (velog_1) { * idom = idom.toNullRenderer(); * } * idom.enter(new Metadata(...)); * ... * if (velog_1) { * idom = idom.toDefaultRenderer(); * } * </pre> */ static class VeLogStateHolder { Expression logOnlyConditional; // Holds the variable reference to velog_1 Statement enterStatement; // Contains the idom.enter(...) statement public VeLogStateHolder(Expression logOnlyConditional, Statement enterStatement) { this.logOnlyConditional = logOnlyConditional; this.enterStatement = enterStatement; } } // Tracks the counter to use for a tag's generated key: // - When encountering an open tag without a manual key, the counter at the top of the stack is // incremented. // - When encountering an open tag with a manual key, a new counter is pushed onto the stack. // - When encountering a close tag that corresponds to an open tag with a manual key, the // topmost counter is then popped from the stack. private ArrayDeque<Holder<Integer>> keyCounterStack; // Counter for static variables that are declared at the global scope. private int staticsCounter = 0; private String alias = ""; GenIncrementalDomCodeVisitor( SoyJsSrcOptions jsSrcOptions, JavaScriptValueFactoryImpl javaScriptValueFactory, IncrementalDomDelTemplateNamer incrementalDomDelTemplateNamer, IncrementalDomGenCallCodeUtils genCallCodeUtils, IsComputableAsIncrementalDomExprsVisitor isComputableAsJsExprsVisitor, CanInitOutputVarVisitor canInitOutputVarVisitor, GenIncrementalDomExprsVisitorFactory genIncrementalDomExprsVisitorFactory, SoyTypeRegistry typeRegistry) { super( jsSrcOptions, javaScriptValueFactory, incrementalDomDelTemplateNamer, genCallCodeUtils, isComputableAsJsExprsVisitor, canInitOutputVarVisitor, genIncrementalDomExprsVisitorFactory, typeRegistry); } @Override protected JsCodeBuilder createCodeBuilder() { return new IncrementalDomCodeBuilder(); } @Override protected IncrementalDomCodeBuilder createChildJsCodeBuilder() { return new IncrementalDomCodeBuilder(getJsCodeBuilder()); } @Override protected IncrementalDomCodeBuilder getJsCodeBuilder() { return (IncrementalDomCodeBuilder) super.getJsCodeBuilder(); } @Override protected JsType getJsTypeForParamForDeclaration(SoyType paramType) { return JsType.forIncrementalDomState(paramType); } @Override protected JsType getJsTypeForParamTypeCheck(SoyType paramType) { return JsType.forIncrementalDom(paramType); } @Override protected void visit(SoyNode node) { try { super.visit(node); } catch (RuntimeException e) { throw new Error("error from : " + node.getKind() + " @ " + node.getSourceLocation(), e); } } /** * Changes module namespaces, adding an extension of '.incrementaldom' to allow it to co-exist * with templates generated by jssrc. */ @Override protected String getGoogModuleNamespace(String soyNamespace) { return soyNamespace + NAMESPACE_EXTENSION; } @Override protected String getTemplateReturnType(TemplateNode node) { if (isTextContent(node.getContentKind())) { return super.getTemplateReturnType(node); } // This template does not return any content but rather contains Incremental DOM // instructions. return "void"; } @Override protected void visitTemplateNode(TemplateNode node) { keyCounterStack = new ArrayDeque<>(); keyCounterStack.push(new Holder<>(0)); staticsCounter = 0; SanitizedContentKind kind = node.getContentKind(); getJsCodeBuilder().setContentKind(kind); if (node instanceof TemplateDelegateNode) { alias = node.getPartialTemplateName().substring(1); } else { alias = templateAliases.get(node.getTemplateName()); } super.visitTemplateNode(node); if (kind == SanitizedContentKind.HTML || kind == SanitizedContentKind.ATTRIBUTES) { Expression type; if (kind == SanitizedContentKind.HTML) { type = SOY_IDOM_TYPE_HTML; } else { type = SOY_IDOM_TYPE_ATTRIBUTE; } getJsCodeBuilder().append(Statement.assign(id(alias).dotAccess("contentKind"), type)); } if (node instanceof TemplateElementNode) { TemplateElementNode element = (TemplateElementNode) node; String elementName = this.getSoyElementClassName(); String elementAccessor = elementName + "Interface"; getJsCodeBuilder().appendLine(); getJsCodeBuilder().append(generateAccessorInterface(elementAccessor, element)); getJsCodeBuilder().append(generateExportsForSoyElement(elementAccessor)); getJsCodeBuilder().append(generateClassForSoyElement(elementName, elementAccessor, element)); getJsCodeBuilder().append(generateExportsForSoyElement(elementName)); } } @Override protected JsDoc generateFunctionJsDoc(TemplateNode node, String alias) { JsDoc.Builder jsDocBuilder = JsDoc.builder(); SanitizedContentKind kind = node.getContentKind(); if (kind == SanitizedContentKind.HTML || kind == SanitizedContentKind.ATTRIBUTES) { jsDocBuilder.addGoogRequire(INCREMENTAL_DOM_LIB); jsDocBuilder.addParam( INCREMENTAL_DOM_PARAM_NAME, "!incrementaldomlib.IncrementalDomRenderer"); } // This is true if there are any calls with data="all" (which implicitly add optional parameters // from those template) or if all parameters are optional (but there are some parameters). boolean noRequiredParams = new ShouldEnsureDataIsDefinedVisitor().exec(node); if (node.getParams().isEmpty()) { // If there are indirect parameters, allow an arbitrary object. // Either way, allow null, since the caller may not pass parameters. jsDocBuilder.addParam("opt_data", noRequiredParams ? "?Object<string, *>=" : "null="); } else if (noRequiredParams) { // All parameters are optional or only owned by an indirect callee; caller doesn't need to // pass an object. jsDocBuilder.addParam("opt_data", "?" + alias + ".Params="); } else { jsDocBuilder.addParam("opt_data", "!" + alias + ".Params"); } jsDocBuilder.addGoogRequire(GoogRequire.createTypeRequire("goog.soy")); jsDocBuilder.addParam("opt_ijData", "?goog.soy.IjData="); String returnType = getTemplateReturnType(node); jsDocBuilder.addParameterizedAnnotation("return", returnType); // TODO(b/11787791): make the checkTypes suppression more fine grained. jsDocBuilder.addParameterizedAnnotation("suppress", "checkTypes"); return jsDocBuilder.build(); } @Override protected Statement generateFunctionBody(TemplateNode node, String alias) { ImmutableList.Builder<Statement> bodyStatements = ImmutableList.builder(); // Generate statement to ensure data is defined, if necessary. if (new ShouldEnsureDataIsDefinedVisitor().exec(node)) { bodyStatements.add( Statement.assign( JsRuntime.OPT_DATA, JsRuntime.OPT_DATA.or( EMPTY_OBJECT_LITERAL, templateTranslationContext.codeGenerator()))); } bodyStatements.add( node instanceof TemplateElementNode ? this.generateFunctionBodyForSoyElement(node) : this.generateIncrementalDomRenderCalls(node, alias)); return Statement.of(bodyStatements.build()); } /** Generates idom#elementOpen, idom#elementClose, etc. function calls for the given node. */ private Statement generateIncrementalDomRenderCalls(TemplateNode node, String alias) { IncrementalDomCodeBuilder jsCodeBuilder = getJsCodeBuilder(); boolean isTextTemplate = isTextContent(node.getContentKind()); Statement typeChecks = genParamTypeChecks(node, alias); ImmutableList.Builder<Statement> stateReassignmentBuilder = ImmutableList.builder(); if (node instanceof TemplateElementNode) { TemplateElementNode soyElement = (TemplateElementNode) node; for (TemplateHeaderVarDefn headerVar : Lists.newArrayList(soyElement.getStateVars())) { if (SoyTreeUtils.isConstantExpr(headerVar.defaultValue())) { continue; } stateReassignmentBuilder.add( Statement.assign( Expression.THIS.dotAccess(STATE_PREFIX + headerVar.name()), translateExpr(headerVar.defaultValue()))); } } List<Statement> reassignments = stateReassignmentBuilder.build(); Statement stateReassignments = Statement.of(reassignments); if (!reassignments.isEmpty()) { stateReassignments = Statement.ifStatement( Expression.THIS.dotAccess("shouldSyncState").call(), stateReassignments) .build(); } // Note: we do not try to combine this into a single return statement if the content is // computable as a JsExpr. A JavaScript compiler, such as Closure Compiler, is able to perform // the transformation. if (isTextTemplate) { // We do our own initialization below, so mark it as such. jsCodeBuilder.pushOutputVar("output").setOutputVarInited(); } Statement body = visitChildrenReturningCodeChunk(node); if (isTextTemplate) { VariableDeclaration declare = VariableDeclaration.builder("output").setRhs(LITERAL_EMPTY_STRING).build(); jsCodeBuilder.popOutputVar(); body = Statement.of(declare, body, returnValue(sanitize(declare.ref(), node.getContentKind()))); } return Statement.of(typeChecks, stateReassignments, body); } /** * Generates main template function body for Soy elements. Specifically, generates code to create * a new instance of the element class and invoke its #render method. */ private Statement generateFunctionBodyForSoyElement(TemplateNode node) { String soyElementClassName = this.getSoyElementClassName(); Expression firstElementKey = // Since Soy element roots cannot have manual keys (see go/soy-element-keyed-roots), // this will always be the first element key. JsRuntime.XID.call(Expression.stringLiteral(node.getTemplateName() + "-0")); return SOY_IDOM .dotAccess("$$handleSoyElement") .call( INCREMENTAL_DOM, id(soyElementClassName), firstElementKey, JsRuntime.OPT_DATA, JsRuntime.OPT_IJ_DATA) .asStatement(); } /** * Visits the children of a ParentSoyNode. This function is overridden to not do all of the work * that {@link GenJsCodeVisitor} does. */ @Override protected void visitChildren(ParentSoyNode<?> node) { for (SoyNode child : node.getChildren()) { visit(child); } } /** Generates class expression for the given template node, provided it is a Soy element. */ private VariableDeclaration generateClassForSoyElement( String soyElementClassName, String soyElementAccessorName, TemplateElementNode node) { String paramsType = node.getParams().isEmpty() ? "null" : "!" + alias + ".Params"; ImmutableList.Builder<MethodDeclaration> stateMethods = ImmutableList.builder(); for (TemplateStateVar stateVar : node.getStateVars()) { stateMethods.addAll( this.generateStateMethodsForSoyElementClass(soyElementClassName, stateVar)); } ImmutableList.Builder<MethodDeclaration> parameterMethods = ImmutableList.builder(); for (TemplateParam param : node.getParams()) { parameterMethods.add( this.generateGetParamMethodForSoyElementClass( param, /* isAbstract= */ false, /* isInjected= */ false)); } ImmutableList.Builder<MethodDeclaration> injectedParameterMethods = ImmutableList.builder(); for (TemplateParam injectedParam : node.getInjectedParams()) { injectedParameterMethods.add( this.generateGetParamMethodForSoyElementClass( injectedParam, /* isAbstract= */ false, /* isInjected= */ true)); } ImmutableList.Builder<Statement> stateVarInitializations = ImmutableList.builder(); for (TemplateStateVar stateVar : node.getStateVars()) { JsType jsType = JsType.forIncrementalDomState(stateVar.type()); JsDoc stateVarJsdoc = JsDoc.builder().addParameterizedAnnotation("private", jsType.typeExpr()).build(); Expression rhsValue; if (SoyTreeUtils.isConstantExpr(stateVar.defaultValue())) { rhsValue = translateExpr(stateVar.defaultValue()); } else { rhsValue = Expression.LITERAL_UNDEFINED.castAs("?"); } stateVarInitializations.add( Statement.assign( Expression.THIS.dotAccess(STATE_PREFIX + stateVar.name()), rhsValue, stateVarJsdoc)); } // Build constructor method. Statement ctorBody = Statement.of( id("super").call(JsRuntime.OPT_DATA, JsRuntime.OPT_IJ_DATA).asStatement(), Statement.of(stateVarInitializations.build())); MethodDeclaration constructorMethod = MethodDeclaration.create( "constructor", JsDoc.builder() .addParam("opt_data", paramsType) .addGoogRequire(GoogRequire.createTypeRequire("goog.soy")) .addParam("opt_ijData", "!goog.soy.IjData=") .build(), ctorBody); // Build `renderInternal` method. MethodDeclaration renderInternalMethod = MethodDeclaration.create( "renderInternal", JsDoc.builder() .addParam(INCREMENTAL_DOM_PARAM_NAME, "!incrementaldomlib.IncrementalDomRenderer") .addParam("opt_data", paramsType) .addAnnotation("protected") .addAnnotation("override") .addParameterizedAnnotation("suppress", "checkTypes") .build(), Statement.of( // Various parts of the js codegen expects these parameters to be in the local // scope. VariableDeclaration.builder("opt_ijData") .setRhs(Expression.THIS.dotAccess("ijData")) .build(), generateIncrementalDomRenderCalls(node, alias), Statement.returnValue(Expression.LITERAL_FALSE))); ClassExpression soyElementClass = ClassExpression.create( SOY_IDOM.dotAccess("$SoyElement"), ImmutableList.<MethodDeclaration>builder() .add(constructorMethod, renderInternalMethod) .addAll(stateMethods.build()) .addAll(parameterMethods.build()) .addAll(injectedParameterMethods.build()) .build()); String elementAccessor = soyElementClassName + "Interface"; VariableDeclaration classExpression = VariableDeclaration.builder(soyElementClassName) .setJsDoc( JsDoc.builder() .addAnnotation( "extends", "{soyIdom.$SoyElement<" + paramsType + ",!" + elementAccessor + ">}") .addParameterizedAnnotation("implements", soyElementAccessorName) .build()) .setRhs(soyElementClass) .build(); return classExpression; } /** Generates class expression for the given template node, provided it is a Soy element. */ private VariableDeclaration generateAccessorInterface( String className, TemplateElementNode node) { ImmutableList.Builder<MethodDeclaration> parameterMethods = ImmutableList.builder(); for (TemplateParam param : node.getParams()) { parameterMethods.add( this.generateGetParamMethodForSoyElementClass( param, /* isAbstract= */ true, /* isInjected= */ false)); } ImmutableList.Builder<MethodDeclaration> injectedParameterMethods = ImmutableList.builder(); for (TemplateParam injectedParam : node.getInjectedParams()) { injectedParameterMethods.add( this.generateGetParamMethodForSoyElementClass( injectedParam, /* isAbstract= */ true, /* isInjected= */ true)); } ClassExpression soyElementClass = ClassExpression.create( ImmutableList.<MethodDeclaration>builder() .addAll(parameterMethods.build()) .addAll(injectedParameterMethods.build()) .build()); VariableDeclaration classExpression = VariableDeclaration.builder(className) .setJsDoc(JsDoc.builder().addAnnotation("interface").build()) .setRhs(soyElementClass) .build(); return classExpression; } private Statement generateExportsForSoyElement(String soyElementClassName) { return Statement.assign( // Idom only supports goog.module generation. JsRuntime.EXPORTS.dotAccess( // Drop the leading '$' from soyElementClassName. soyElementClassName.substring(1)), id(soyElementClassName)); } /** * Generates `getFoo` (index 0) and `setFoo` (index 1) methods for a given `foo` state variable. */ private ImmutableList<MethodDeclaration> generateStateMethodsForSoyElementClass( String soyElementClassName, TemplateStateVar stateVar) { JsType jsType = JsType.forIncrementalDomState(stateVar.type()); String stateAccessorSuffix = Ascii.toUpperCase(stateVar.name().substring(0, 1)) + stateVar.name().substring(1); Expression stateValue = id("this").dotAccess(STATE_PREFIX + stateVar.name()); MethodDeclaration getStateMethod = MethodDeclaration.create( "get" + stateAccessorSuffix, JsDoc.builder().addParameterizedAnnotation("return", jsType.typeExpr()).build(), Statement.returnValue(stateValue)); jsType = JsType.forIncrementalDomState(stateVar.type()); ImmutableList.Builder<Statement> setStateMethodStatements = ImmutableList.builder(); Optional<Expression> typeAssertion = jsType.getSoyTypeAssertion( id(stateVar.name()), stateVar.name(), templateTranslationContext.codeGenerator()); if (typeAssertion.isPresent()) { setStateMethodStatements.add(typeAssertion.get().asStatement()); } setStateMethodStatements.add( stateValue.assign(id(stateVar.name())).asStatement(), Statement.returnValue(id("this"))); MethodDeclaration setStateMethod = MethodDeclaration.create( "set" + stateAccessorSuffix, JsDoc.builder() .addParam(stateVar.name(), jsType.typeExpr()) .addParameterizedAnnotation("return", "!" + soyElementClassName) .build(), Statement.of(setStateMethodStatements.build())); return ImmutableList.of(getStateMethod, setStateMethod); } /** Generates `get[X]` for a given parameter value. */ private MethodDeclaration generateGetParamMethodForSoyElementClass( TemplateParam param, boolean isAbstract, boolean isInjected) { JsType jsType = JsType.forIncrementalDomState(param.type()); String accessorSuffix = Ascii.toUpperCase(param.name().substring(0, 1)) + param.name().substring(1); if (isAbstract) { return MethodDeclaration.create( "get" + accessorSuffix, JsDoc.builder() .addAnnotation("abstract") // Injected params are marked as optional, see: .addParameterizedAnnotation("return", jsType.typeExpr()) .build(), Statement.of(ImmutableList.of())); } Expression value = id("this").dotAccess(isInjected ? "ijData" : "data").dotAccess(param.name()); if (param.hasDefault()) { value = templateTranslationContext .codeGenerator() .declarationBuilder() .setRhs(value) .build() .ref(); value = value.withInitialStatement( genParamDefault( param, value, alias, getJsTypeForParamTypeCheck(param.type()), /* declareStatic= */ false)); } // Injected params are marked as optional to account for unused templates, see: // We can assert the presence of the injected param if it being called. Optional<Expression> typeAssertion = isInjected ? jsType.getSoyTypeAssertion( value, param.name(), templateTranslationContext.codeGenerator()) : Optional.empty(); MethodDeclaration getParamMethod = MethodDeclaration.create( "get" + accessorSuffix, JsDoc.builder().addAnnotation("override").addAnnotation("public").build(), Statement.returnValue(typeAssertion.orElse(value))); return getParamMethod; } /** Constructs template class name, e.g. converts template `ns.foo` => `$FooElement`. */ private String getSoyElementClassName() { Preconditions.checkState( alias.startsWith("$"), "Alias should start with '$', or template class name may be malformed."); return "$" // `alias` has '$' as the 0th char, so capitalize the 1st char. + Ascii.toUpperCase(alias.charAt(1)) /// ...and concat the rest of the alias. + alias.substring(2) + "Element"; } /** * Generates the content of a {@code let} or {@code param} statement. For HTML and attribute * let/param statements, the generated instructions inside the node are wrapped in a function * which will be optionally passed to another template and invoked in the correct location. All * other kinds of let statements are generated as a simple variable. */ private void visitLetParamContentNode(RenderUnitNode node, String generatedVarName) { // The html transform step, performed by HtmlContextVisitor, ensures that // we always have a content kind specified. checkState(node.getContentKind() != null); IncrementalDomCodeBuilder jsCodeBuilder = getJsCodeBuilder(); SanitizedContentKind prevContentKind = jsCodeBuilder.getContentKind(); jsCodeBuilder.setContentKind(node.getContentKind()); CodeChunk definition; VariableDeclaration.Builder builder = VariableDeclaration.builder(generatedVarName); SanitizedContentKind kind = node.getContentKind(); if (kind == SanitizedContentKind.HTML || kind == SanitizedContentKind.ATTRIBUTES) { Expression constructor; if (kind == SanitizedContentKind.HTML) { constructor = SOY_IDOM_MAKE_HTML; } else { constructor = SOY_IDOM_MAKE_ATTRIBUTES; } JsDoc jsdoc = JsDoc.builder() .addParam(INCREMENTAL_DOM_PARAM_NAME, "incrementaldomlib.IncrementalDomRenderer") .build(); definition = builder .setRhs( constructor.call( Expression.arrowFunction(jsdoc, visitChildrenReturningCodeChunk(node)))) .build(); } else { // We do our own initialization, so mark it as such. String outputVarName = generatedVarName + "_output"; jsCodeBuilder.pushOutputVar(outputVarName).setOutputVarInited(); // TODO(b/246994962): Skip this definition for SanitizedContentKind.TEXT. definition = Statement.of( VariableDeclaration.builder(outputVarName).setRhs(LITERAL_EMPTY_STRING).build(), visitChildrenReturningCodeChunk(node), builder .setRhs( kind == SanitizedContentKind.TEXT ? id(outputVarName) : JsRuntime.sanitizedContentOrdainerFunctionForInternalBlocks( node.getContentKind()) .call(id(outputVarName))) .build()); jsCodeBuilder.popOutputVar(); } jsCodeBuilder.setContentKind(prevContentKind); jsCodeBuilder.append(definition); } /** * Generates the content of a {@code let} statement. For HTML and attribute let statements, the * generated instructions inside the node are wrapped in a function which will be optionally * passed to another template and invoked in the correct location. All other kinds of let/param * statements are generated as a simple variable. */ @Override protected void visitLetContentNode(LetContentNode node) { String generatedVarName = node.getUniqueVarName(); visitLetParamContentNode(node, generatedVarName); templateTranslationContext .soyToJsVariableMappings() .put(node.getVarName(), id(generatedVarName)); } @Override protected void visitCallParamContentNode(CallParamContentNode node) { String generatedVarName = "param" + node.getId(); visitLetParamContentNode(node, generatedVarName); } @Override protected void visitCallNode(CallNode node) { // If this node has any CallParamContentNode children those contents are not computable as JS // expressions, visit them to generate code to define their respective 'param<n>' variables. for (CallParamNode child : node.getChildren()) { if (child instanceof CallParamContentNode && !isComputableAsJsExprsVisitor.exec(child)) { visit(child); } } Expression call; Optional<SanitizedContentKind> kind = templateRegistry.getCallContentKind(node); Expression callee = genCallCodeUtils.genCallee(node, templateAliases, getExprTranslator()); Expression objToPass = genCallCodeUtils.genObjToPass( node, templateAliases, templateTranslationContext, errorReporter, getExprTranslator()); boolean shouldPushKey = false; if (STRINGLIKE_KINDS.contains(node.getHtmlContext()) && (!kind.isPresent() || kind.get() == SanitizedContentKind.ATTRIBUTES || kind.get() == SanitizedContentKind.HTML)) { call = SOY_IDOM_CALL_DYNAMIC_TEXT.call(callee, objToPass, JsRuntime.OPT_IJ_DATA); } else if (kind.isPresent() && (kind.get() == SanitizedContentKind.HTML || kind.get() == SanitizedContentKind.ATTRIBUTES)) { // This is executed in the case of HTML/ATTR -> HTML/ATTR. All other ambiguous cases are // passed through to runtime functions. call = callee.call(INCREMENTAL_DOM, objToPass, JsRuntime.OPT_IJ_DATA); shouldPushKey = true; } else { // This is executed in the case of TEXT Context -> Text Template call = callee.call(objToPass, JsRuntime.OPT_IJ_DATA); } if (STRINGLIKE_KINDS.contains(node.getHtmlContext())) { call = GenCallCodeUtils.applyEscapingDirectives(call, node); getJsCodeBuilder().addChunkToOutputVar(call); } else { switch (node.getHtmlContext()) { case HTML_TAG: if (!kind.isPresent() || kind.get() != SanitizedContentKind.ATTRIBUTES) { call = SOY_IDOM_CALL_DYNAMIC_ATTRIBUTES.call( INCREMENTAL_DOM, callee, objToPass, JsRuntime.OPT_IJ_DATA); } break; case CSS: call = SOY_IDOM_CALL_DYNAMIC_CSS.call( INCREMENTAL_DOM, callee, objToPass, JsRuntime.OPT_IJ_DATA); break; case JS: call = SOY_IDOM_CALL_DYNAMIC_JS.call( INCREMENTAL_DOM, callee, objToPass, JsRuntime.OPT_IJ_DATA); break; default: if (!kind.isPresent() || kind.get() != SanitizedContentKind.HTML) { call = SOY_IDOM_CALL_DYNAMIC_HTML.call( INCREMENTAL_DOM, callee, objToPass, JsRuntime.OPT_IJ_DATA); shouldPushKey = true; } break; } TemplateNode template = node.getNearestAncestor(TemplateNode.class); String keyVariable = "_keyVariable" + staticsCounter++; if (shouldPushKey) { if (node.getKeyExpr() != null) { getJsCodeBuilder() .append(INCREMENTAL_DOM_PUSH_MANUAL_KEY.call(translateExpr(node.getKeyExpr()))); } else { getJsCodeBuilder() .append( VariableDeclaration.builder(keyVariable) .setRhs(INCREMENTAL_DOM_PUSH_KEY.call(incrementKeyForTemplate(template))) .build()); } } // TODO: In reality, the CALL_X functions are really just IDOM versions of the related // escaping directives. Consider doing a replace instead of not using escaping directives // at all. getJsCodeBuilder().append(call); if (shouldPushKey) { if (node.getKeyExpr() != null) { getJsCodeBuilder().append(INCREMENTAL_DOM_POP_MANUAL_KEY.call()); } else { getJsCodeBuilder().append(INCREMENTAL_DOM_POP_KEY.call(Expression.id(keyVariable))); } } } } /** * Generates calls in HTML/Attributes content as non-JsExprs, since Incremental DOM instructions * are needed and not a JavaScript expression. */ @Override protected void visitIfNode(IfNode node) { IncrementalDomCodeBuilder jsCodeBuilder = getJsCodeBuilder(); SanitizedContentKind currentContentKind = jsCodeBuilder.getContentKind(); if (!isTextContent(currentContentKind)) { super.generateNonExpressionIfNode(node); } else { super.visitIfNode(node); } } /** * Determines if a given type of content represents text or some sort of HTML. * * @param contentKind The kind of content to check. * @return True if the content represents text, false otherwise. */ private boolean isTextContent(SanitizedContentKind contentKind) { return contentKind != SanitizedContentKind.HTML && contentKind != SanitizedContentKind.ATTRIBUTES; } @Override protected TranslateExprNodeVisitor getExprTranslator() { return new IncrementalDomTranslateExprNodeVisitor( javaScriptValueFactory, templateTranslationContext, errorReporter); } @Override protected void visitHtmlCommentNode(HtmlCommentNode node) { String id = "html_comment_" + node.getId(); getJsCodeBuilder() .append(VariableDeclaration.builder(id).setRhs(Expression.LITERAL_EMPTY_STRING).build()); getJsCodeBuilder().pushOutputVar(id).setOutputVarInited(); SanitizedContentKind prev = getJsCodeBuilder().getContentKind(); getJsCodeBuilder().setContentKind(SanitizedContentKind.TEXT); for (int i = 0; i < node.numChildren(); i++) { visit(node.getChild(i)); } getJsCodeBuilder().append(SOY_IDOM_VISIT_HTML_COMMENT.call(INCREMENTAL_DOM, id(id))); getJsCodeBuilder().popOutputVar(); getJsCodeBuilder().setContentKind(prev); } /** * Visits the {@link HtmlAttributeNode}. The attribute nodes will typically be children of the * corresponding {@link HtmlOpenTagNode} or in a let/param of kind attributes, e.g. * * <pre> * {let $attrs kind="attributes"} * attr="value" * {/let} * </pre> * * This method prints the attribute declaration calls. For example, given * * <pre> * &lt;div {if $condition}attr="value"{/if}&gt; * </pre> * * it would print the call to {@code incrementalDom.attr}, resulting in: * * <pre> * if (condition) { * IncrementalDom.attr(attr, "value"); * } * </pre> */ @Override protected void visitHtmlAttributeNode(HtmlAttributeNode node) { IncrementalDomCodeBuilder jsCodeBuilder = getJsCodeBuilder(); if (node.hasValue()) { // Attribute keys can only be print statements or constants. As such, the first child // should be the key and the second the value. checkState(isComputableAsJsExprsVisitor.exec(node.getChild(0))); jsCodeBuilder.append( INCREMENTAL_DOM_ATTR.call( // Attributes can only be print nodes or constants genJsExprsVisitor.exec(node.getChild(0)).get(0), CodeChunkUtils.concatChunksForceString(getAttributeValues(node)))); } else { visitChildren(node); // Prints raw text or attributes node. } } @Override protected void visitHtmlAttributeValueNode(HtmlAttributeValueNode node) { // ignore quotes since idom doesn't care about them, so we just iterate the children. visitChildren(node); } private List<Expression> getAttributeValues(HtmlAttributeNode node) { if (!node.hasValue()) { // No attribute value, e.g. "<button disabled></button>". Need to put an empty string so that // the runtime knows to create an attribute. return ImmutableList.of(LITERAL_EMPTY_STRING); } ParentSoyNode<?> value = (ParentSoyNode<?>) node.getChild(1); String outputVar = "html_attribute_" + node.getId(); boolean needsToBeCoerced = false; // There may be HTML nodes in the children that can get coerced to a string. In this case, // the appending path needs to be executed. for (Object n : value.getChildren()) { if (n instanceof CallNode) { Optional<SanitizedContentKind> kind = templateRegistry.getCallContentKind((CallNode) n); needsToBeCoerced = !kind.isPresent() || kind.get() == SanitizedContentKind.HTML || kind.get() == SanitizedContentKind.ATTRIBUTES; } } if (!isComputableAsJsExprsVisitor.execOnChildren(value) || needsToBeCoerced) { getJsCodeBuilder().pushOutputVar(outputVar).setOutputVarInited(); SanitizedContentKind prev = getJsCodeBuilder().getContentKind(); getJsCodeBuilder().setContentKind(SanitizedContentKind.TEXT); IncrementalDomCodeBuilder jsCodeBuilder = getJsCodeBuilder(); jsCodeBuilder.append( VariableDeclaration.builder(outputVar).setRhs(Expression.LITERAL_EMPTY_STRING).build()); visit(value); getJsCodeBuilder().popOutputVar(); getJsCodeBuilder().setContentKind(prev); return ImmutableList.of(id(outputVar)); } return genJsExprsVisitor.exec(value); } /** * Returns a unique key for the template. This has the side-effect of incrementing the current * keyCounter at the top of the stack. */ private Expression incrementKeyForTemplate(TemplateNode template) { Holder<Integer> keyCounter = keyCounterStack.peek(); return JsRuntime.XID.call( Expression.stringLiteral(template.getTemplateName() + "-" + keyCounter.value++)); } /** * Removes static children from {@code node} and returns them in a map of key to value. For * attribute nodes that are known to be static, we can improve performance by adding them to the * statics array(http://google.github.io/incremental-dom/#statics-array). */ private ImmutableMap<String, Expression> getStaticAttributes(HtmlOpenTagNode node) { List<HtmlAttributeNode> nodesToRemove = new ArrayList<>(); ImmutableMap.Builder<String, Expression> builder = ImmutableMap.builder(); // The 0th index is actually the tag itself, so we don't need to iterate over it. for (int i = 1; i < node.numChildren(); i++) { if (node.getChild(i) instanceof HtmlAttributeNode) { HtmlAttributeNode attrNode = (HtmlAttributeNode) node.getChild(i); String attributeKey = attrNode.getStaticKey(); Expression value = getStaticContent(attrNode); if (attributeKey != null && value != null) { nodesToRemove.add(attrNode); builder.put(attributeKey, value); } } } for (HtmlAttributeNode child : nodesToRemove) { node.removeChild(child); } return builder.build(); } /** * Extract static content from attributes, or return null if value is dynamic. Static content is * either an attribute value that is nonexistent or a combination of raw text and xid/css calls. */ private Expression getStaticContent(HtmlAttributeNode node) { if (!node.hasValue()) { return Expression.stringLiteral(""); } // This case is some control flow like a switch, if, or for loop. if (!(node.getChild(1) instanceof HtmlAttributeValueNode)) { return null; } HtmlAttributeValueNode attrValue = (HtmlAttributeValueNode) node.getChild(1); if (attrValue.numChildren() == 0) { return Expression.stringLiteral(""); } // If any children are not raw text or constant xid/css calls, return null for (int i = 0; i < attrValue.numChildren(); i++) { if (attrValue.getChild(i) instanceof RawTextNode) { continue; } else if (attrValue.getChild(i) instanceof PrintNode) { PrintNode n = (PrintNode) attrValue.getChild(i); if (n.getExpr().getRoot() instanceof FunctionNode) { FunctionNode fnNode = (FunctionNode) n.getExpr().getRoot(); if (fnNode.getSoyFunction() != BuiltinFunction.XID && fnNode.getSoyFunction() != BuiltinFunction.CSS) { return null; // Function call was not xid or css } } else { // Child is variable expression ie {$foo} or {$foo + $bar} return null; } } else { // Child was control flow. return null; } } return CodeChunkUtils.concatChunksForceString(getAttributeValues(node)); } private Expression getOpenSSRCall(HtmlOpenTagNode node, SkipNode skip) { List<Expression> args = new ArrayList<>(); args.add(getTagNameCodeChunk(node.getTagName())); KeyNode keyNode = node.getKeyNode(); if (keyNode == null) { args.add(JsRuntime.XID.call(Expression.stringLiteral(skip.getSkipId()))); } else { // Key difference between getOpen and getOpenSSR args.add(translateExpr(node.getKeyNode().getExpr())); } if (node.isElementRoot()) { args.add(JsRuntime.OPT_DATA); } return INCREMENTAL_DOM_OPEN_SSR.call(args); } private Expression getOpenCall(HtmlOpenTagNode node) { TemplateNode template = node.getNearestAncestor(TemplateNode.class); List<Expression> args = new ArrayList<>(); args.add(getTagNameCodeChunk(node.getTagName())); KeyNode keyNode = node.getKeyNode(); Expression key = Expression.LITERAL_UNDEFINED; if (keyNode == null) { key = incrementKeyForTemplate(template); } else { keyCounterStack.push(new Holder<>(0)); } args.add(key); return INCREMENTAL_DOM_OPEN.call(args); } private Optional<Expression> getApplyStaticAttributes(HtmlOpenTagNode node) { Map<String, Expression> staticAttributes = getStaticAttributes(node); ImmutableList.Builder<Expression> staticsBuilder = ImmutableList.builder(); for (Map.Entry<String, Expression> entry : staticAttributes.entrySet()) { staticsBuilder.add(Expression.stringLiteral(entry.getKey())); staticsBuilder.add(entry.getValue()); } // Instead of inlining the array, place the variable declaration in the global scope // and lazily initialize it in the template. if (!staticAttributes.isEmpty()) { String id = "_statics_" + staticsCounter++; Expression idExpr = id(alias + id); Expression lazyAssignment = // Generator can be null because we know this evaluates to an or // ie alias_statics_1 || alias_statics_1 = [] idExpr.or( idExpr.assign(Expression.arrayLiteral(staticsBuilder.build())), /* codeGenerator= */ null); staticVarDeclarations.add(VariableDeclaration.builder(alias + id).build()); return Optional.of(INCREMENTAL_DOM_APPLY_STATICS.call(lazyAssignment)); } return Optional.empty(); } private Expression getApplyAttrs(HtmlOpenTagNode node) { for (int i = 1; i < node.numChildren(); i++) { visit(node.getChild(i)); } return INCREMENTAL_DOM_APPLY_ATTRS.call(); } /** * Visits an {@link HtmlOpenTagNode} and emits appropriate attr/staticAttr calls and maybe a self * close tag. * * <pre> * &lt;div attr="value" attr2="{$someVar}"&gt;...&lt;/div&gt; * </pre> * * generates * * <pre> * open('div'); * attr('attr', 'value'); * attr('attr2', someVar); * applyAttrs() * ... * * close() * </pre> */ @Override protected void visitHtmlOpenTagNode(HtmlOpenTagNode node) { IncrementalDomCodeBuilder jsCodeBuilder = getJsCodeBuilder(); if (!node.isSkipRoot()) { if (node.getKeyNode() != null) { // Push key BEFORE emitting `elementOpen`. Later, for `elementOpen` calls of keyed elements, // we do not specify any key. Expression key = translateExpr(node.getKeyNode().getExpr()); getJsCodeBuilder().append(INCREMENTAL_DOM_PUSH_MANUAL_KEY.call(key)); } Expression openTagExpr = getOpenCall(node); if (node.isElementRoot()) { // Append code to stash the template object in this node. jsCodeBuilder.append( Statement.ifStatement( INCREMENTAL_DOM_MAYBE_SKIP.call(INCREMENTAL_DOM, openTagExpr), Statement.returnValue(Expression.LITERAL_TRUE)) .build()); } else { jsCodeBuilder.append(openTagExpr.asStatement()); } } jsCodeBuilder.append(getAttributeAndCloseCalls(node)); } private Statement getAttributeAndCloseCalls(HtmlOpenTagNode node) { List<Statement> statements = new ArrayList<>(); Optional<Expression> maybeApplyStatics = getApplyStaticAttributes(node); if (maybeApplyStatics.isPresent()) { statements.add(maybeApplyStatics.get().asStatement()); } statements.add(getApplyAttrs(node).asStatement()); // Whether or not it is valid for this tag to be self closing has already been validated by the // HtmlContextVisitor. So we just need to output the close instructions if the node is self // closing or definitely void. if (node.isSelfClosing() || node.getTagName().isDefinitelyVoid()) { statements.add(INCREMENTAL_DOM_CLOSE.call().asStatement()); } return Statement.of(statements); } /** * Visits an {@link HtmlCloseTagNode}, which occurs when an HTML tag is closed. For example: * * <pre> * &lt;/div&gt; * </pre> * * generates * * <pre> * incrementalDom.close('div'); * </pre> */ @Override protected void visitHtmlCloseTagNode(HtmlCloseTagNode node) { // This case occurs in the case where we encounter the end of a keyed element. If the open tag // mapped to this close tag contains a key node, pop the keyCounterStack to return // to the state before entering the keyed node. if (node.getTaggedPairs().size() == 1) { HtmlOpenTagNode openTag = (HtmlOpenTagNode) node.getTaggedPairs().get(0); if (openTag.getKeyNode() != null && !(openTag.getParent() instanceof SkipNode)) { keyCounterStack.pop(); getJsCodeBuilder().append(INCREMENTAL_DOM_POP_MANUAL_KEY.call()); } } if (!node.getTagName().isDefinitelyVoid()) { getJsCodeBuilder().append(INCREMENTAL_DOM_CLOSE.call().asStatement()); } } /** * Visits a {@link RawTextNode}, which occurs either as a child of any BlockNode or the 'child' of * an HTML tag. Note that in the soy tree, tags and their logical HTML children do not have a * parent-child relationship, but are rather siblings. For example: * * <pre> * &lt;div&gt;Hello world&lt;/div&gt; * </pre> * * The text "Hello world" translates to * * <pre> * incrementalDom.text('Hello world'); * </pre> */ @Override protected void visitRawTextNode(RawTextNode node) { Expression textArg = stringLiteral(node.getRawText()); JsCodeBuilder jsCodeBuilder = getJsCodeBuilder(); switch (node.getHtmlContext()) { case JS: case CSS: case HTML_RCDATA: case HTML_PCDATA: // Note - we don't use generateTextCall since this text can never be null. jsCodeBuilder.append(INCREMENTAL_DOM_TEXT.call(textArg)); break; case HTML_TAG: jsCodeBuilder.append(INCREMENTAL_DOM_ATTR.call(textArg, stringLiteral(""))); break; default: jsCodeBuilder.addChunkToOutputVar(textArg); break; } } /** * Visit an {@link PrintNode}, with special cases for a variable being printed within an attribute * declaration or as HTML content. * * <p>For attributes, if the variable is of kind attributes, it is invoked. Any other kind of * variable is an error. * * <p>For HTML, if the variable is of kind HTML, it is invoked. Any other kind of variable gets * wrapped in a call to {@code incrementalDom.text}, resulting in a Text node. */ @Override protected void visitPrintNode(PrintNode node) { List<Expression> chunks = genJsExprsVisitor.exec(node); switch (node.getHtmlContext()) { case HTML_TAG: getJsCodeBuilder() .append( SOY_IDOM_PRINT_DYNAMIC_ATTR.call( INCREMENTAL_DOM, CodeChunkUtils.concatChunks(chunks))); break; case JS: // fall through case CSS: // fall through case HTML_PCDATA: if (node.numChildren() > 0 && node.getChild(node.numChildren() - 1).getPrintDirective() instanceof SanitizedContentOperator && ((SanitizedContentOperator) node.getChild(node.numChildren() - 1).getPrintDirective()) .getContentKind() == SanitizedContent.ContentKind.HTML) { getJsCodeBuilder() .append( SOY_IDOM_PRINT.call( INCREMENTAL_DOM, CodeChunkUtils.concatChunks(chunks), Expression.LITERAL_TRUE)); } else { getJsCodeBuilder() .append(SOY_IDOM_PRINT.call(INCREMENTAL_DOM, CodeChunkUtils.concatChunks(chunks))); } break; case HTML_RCDATA: getJsCodeBuilder() .append( INCREMENTAL_DOM_TEXT.call(id("String").call(CodeChunkUtils.concatChunks(chunks)))); break; default: super.visitPrintNode(node); break; } } @Override protected void visitSkipNode(SkipNode node) { IncrementalDomCodeBuilder jsCodeBuilder = getJsCodeBuilder(); HtmlOpenTagNode openTag = (HtmlOpenTagNode) node.getChild(0); Expression openTagExpr = getOpenSSRCall(openTag, node); Statement childStatements = visitChildrenReturningCodeChunk(node); jsCodeBuilder.append(Statement.ifStatement(openTagExpr, Statement.of(childStatements)).build()); } @Override protected void visitVeLogNode(VeLogNode node) { VeLogStateHolder state = openVeLogNode(node); getJsCodeBuilder().append(state.enterStatement); visitChildren(node); getJsCodeBuilder().append(exitVeLogNode(node, state.logOnlyConditional)); } VeLogStateHolder openVeLogNode(VeLogNode node) { Expression isLogOnly = Expression.LITERAL_FALSE; VariableDeclaration isLogOnlyVar = null; Expression isLogOnlyReference = null; if (node.getLogonlyExpression() != null) { String idName = "velog_" + staticsCounter++; isLogOnlyReference = id(idName); isLogOnly = getExprTranslator().exec(node.getLogonlyExpression()); isLogOnlyVar = VariableDeclaration.builder(idName).setRhs(isLogOnly).build(); getJsCodeBuilder() .append( Statement.of( isLogOnlyVar, Statement.ifStatement( INCREMENTAL_DOM_VERIFY_LOGONLY.call(isLogOnlyVar.ref()), Statement.assign(INCREMENTAL_DOM, INCREMENTAL_DOM_TONULL.call())) .build())); } Expression veData = getExprTranslator().exec(node.getVeDataExpression()); return new VeLogStateHolder( isLogOnlyReference, INCREMENTAL_DOM_ENTER.call(veData, isLogOnly).asStatement()); } Statement exitVeLogNode(VeLogNode node, Expression isLogOnly) { Statement exit = INCREMENTAL_DOM_EXIT.call().asStatement(); if (isLogOnly != null) { return Statement.of( exit, Statement.ifStatement( isLogOnly, Statement.assign(INCREMENTAL_DOM, INCREMENTAL_DOM_TODEFAULT.call())) .build()); } return exit; } @Override protected void visitMsgFallbackGroupNode(MsgFallbackGroupNode node) { Expression msgExpression; switch (node.getHtmlContext()) { case HTML_PCDATA: String id = "_msg_" + alias + "_" + staticsCounter++; VariableDeclaration staticDecl = VariableDeclaration.builder(id) .setRhs(Expression.objectLiteral(ImmutableMap.of())) .build(); staticVarDeclarations.add(staticDecl); CodeChunk chunk = new AssistantForHtmlMsgs( /* master= */ this, jsSrcOptions, genCallCodeUtils, isComputableAsJsExprsVisitor, templateAliases, genJsExprsVisitor, templateTranslationContext, errorReporter, id) .generateMsgGroupCode(node); getJsCodeBuilder().append(chunk); break; // Messages in attribute values are plain text. However, since the translated content // includes entities (because other Soy backends treat these messages as HTML source), we // must unescape the translations before passing them to the idom APIs. case HTML_NORMAL_ATTR_VALUE: msgExpression = new AssistantForAttributeMsgs( /* master= */ this, jsSrcOptions, genCallCodeUtils, isComputableAsJsExprsVisitor, templateAliases, genJsExprsVisitor, templateTranslationContext, errorReporter) .generateMsgGroupVariable(node); getJsCodeBuilder().addChunkToOutputVar(GOOG_STRING_UNESCAPE_ENTITIES.call(msgExpression)); break; case HTML_RCDATA: msgExpression = getAssistantForMsgs().generateMsgGroupVariable(node); getJsCodeBuilder().append(INCREMENTAL_DOM_TEXT.call(id("String").call(msgExpression))); break; default: msgExpression = getAssistantForMsgs().generateMsgGroupVariable(node); getJsCodeBuilder().addChunkToOutputVar(msgExpression); break; } } @Override protected void visitMsgHtmlTagNode(MsgHtmlTagNode node) { visitChildren(node); } private Expression getTagNameCodeChunk(TagName tagName) { // No need to check if is computable as js expr because tag names can only be // print nodes and constants. return genJsExprsVisitor.exec(tagName.getNode()).get(0); } /** * Handles <code>{msg}</code> commands in attribute context for idom. The literal text in the * translated message must be unescaped after translation, because we pass the text directly to * DOM text APIs, whereas translators write HTML with entities. Therefore, we must first escape * all interpolated placeholders (which can only be TEXT values). * * <p>In non-idom, this happens in the contextual auto-escaper. */ private static final class AssistantForAttributeMsgs extends GenJsCodeVisitorAssistantForMsgs { AssistantForAttributeMsgs( GenIncrementalDomCodeVisitor master, SoyJsSrcOptions jsSrcOptions, GenCallCodeUtils genCallCodeUtils, IsComputableAsJsExprsVisitor isComputableAsJsExprsVisitor, TemplateAliases functionAliases, GenJsExprsVisitor genJsExprsVisitor, TranslationContext translationContext, ErrorReporter errorReporter) { super( master, jsSrcOptions, genCallCodeUtils, isComputableAsJsExprsVisitor, functionAliases, genJsExprsVisitor, translationContext, errorReporter); } @Override protected Expression genGoogMsgPlaceholder(MsgPlaceholderNode msgPhNode) { Expression toEscape = super.genGoogMsgPlaceholder(msgPhNode); return SOY_ESCAPE_HTML.call(toEscape); } } }
Separate the call keys from the element keys, in preparation for emitting keys at ssr time in jbcsrc. GITHUB_BREAKING_CHANGES=n/a ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=282003693
java/src/com/google/template/soy/incrementaldomsrc/GenIncrementalDomCodeVisitor.java
Separate the call keys from the element keys, in preparation for emitting keys at ssr time in jbcsrc.
Java
apache-2.0
416bfe5c08886215a324f06169059bbf8ed27cb3
0
yc507/Android-Universal-Image-Loader,lxhxhlw/Android-Universal-Image-Loader,tanyixiu/Android-Universal-Image-Loader,bobierbo/Android-Universal-Image-Loader,kabouzeid/Android-Universal-Image-Loader,Bibeknam/Android-Universal-Image-Loader,xiaochilun/Android-Universal-Image-Loader,lenmoyouziJiangjun/Android-Universal-Image-Loader,xiangwei/Android-Universal-Image-Loader,jiashie/Android-Universal-Image-Loader,bestwpw/Android-Universal-Image-Loader,mengdd/Android-Universal-Image-Loader,HossainKhademian/AndroidUniversalImageLoader,lzy-h2o2/Android-Universal-Image-Loader,CJstar/Android-Universal-Image-Loader,kbajpai/Android-Universal-Image-Loader,gaojinhua/Android-Universal-Image-Loader,ChanJLee/Android-Universal-Image-Loader,inexistence/Android-Universal-Image-Loader,sahilk2579/Android-Universal-Image-Loader,VideoTec/Android-Universal-Image-Loader,triplezhao/Android-Universal-Image-Loader,yangguoyu92/Android-Universal-Image-Loader,zhaog/Android-Universal-Image-Loader,crazysniper/Android-Universal-Image-Loader,Peter32/Android-Universal-Image-Loader,jianxiansining/Android-Universal-Image-Loader,Genesis6/Android-Universal-Image-Loader,wanjingyan001/Android-Universal-Image-Loader,masken2/Android-Universal-Image-Loader,Jackear/Android-Universal-Image-Loader,xu509/Android-Universal-Image-Loader,JerryloveEmily/Android-Universal-Image-Loader,huanting/Android-Universal-Image-Loader,westlakestudent/Android-Universal-Image-Loader,fhchina/Android-Universal-Image-Loader,n4android/Android-Universal-Image-Loader,hzjsftw/hanzjProject,ligi/Android-Universal-Image-Loader,panggirl/Android-Universal-Image-Loader,jokerNi/Android-Universal-Image-Loader,kys9261/Android-Universal-Image-Loader,3sidedcube/Android-Universal-Image-Loader,yihr/Android-Universal-Image-Loader,aLoyalStudent/Android-Universal-Image-Loader,brianzzzzz/Android-Universal-Image-Loader,huangsongyan/Android-Universal-Image-Loader,motian/Android-Universal-Image-Loader,jjfreeze/Android-Universal-Image-Loader,yyhat/Android-Universal-Image-Loader,hzysoft/Android-Universal-Image-Loader,johnjohndoe/Android-Universal-Image-Loader,wenscript/Android-Universal-Image-Loader,xiepengfei/Android-Universal-Image-Loader,guoxiaojun001/Android-Universal-Image-Loader,yi291047383/Android-Universal-Image-Loader,maduhu/Android-Universal-Image-Loader,MoskalenkoViktor/Android-Universal-Image-Loader,OnlyWangyn/Android-Universal-Image-Loader,tuolin2013/universal_image_loader_lib,pobuing/Android-Universal-Image-Loader,wy315700/Android-Universal-Image-Loader,vvandvv/Android-Universal-Image-Loader,freeman0211/Android-Universal-Image-Loader,jinmiao/Android-Universal-Image-Loader,TomIsYourName/Android-Universal-Image-Loader,guoGavin/Android-Universal-Image-Loader,xiaob/Android-Universal-Image-Loader,Jackie880823/Android-Universal-Image-Loader,hotarzhang/Android-Universal-Image-Loader,LeonardoPhysh/Android-Universal-Image-Loader,5A59/Android-Universal-Image-Loader,liuguangli/Android-Universal-Image-Loader,cpetzel/Android-Universal-Image-Loader,lvxb/Android-Universal-Image-Loader,RadiateWSG/Android-Universal-Image-Loader,cjpx00008/Android-Universal-Image-Loader,junenn/Android-Universal-Image-Loader,kanjiandahai/Android-Universal-Image-Loader,hareshsandeep/Android-Universal-Image-Loader,mpoozd/Android-Universal-Image-Loader,shizhongyu/Android-Universal-Image-Loader,AdrianHsu/Android-Universal-Image-Loader,xiuweikang/Android-Universal-Image-Loader,jinmiao0601/Android-Universal-Image-Loader,simple88/Android-Universal-Image-Loader,Wei-JJ/Android-Image,appdevzhang/Android-Universal-Image-Loader,JunyiZhou/Android-Universal-Image-Loader,zhaokidd/Android-Universal-Image-Loader,hxy0107/Android-Universal-Image-Loader,ppk5457/Android-Universal-Image-Loader,wangqi504635/Android-Universal-Image-Loader,yinzhiliang/Android-Universal-Image-Loader,teffy/Android-Universal-Image-Loader,jp1017/Android-Universal-Image-Loader,Meowzm/Android-Universal-Image-Loader,weizhiwei/Android-Universal-Image-Loader,yutail/Android-Universal-Image-Loader,tonycheng93/Android-Universal-Image-Loader,Morddeka/Android-Universal-Image-Loader,DeathPluto/Android-Universal-Image-Loader,SyllaJay/Android-Universal-Image-Loader,nguyendinhduc/Android-Universal-Image-Loader,tanweijiu/Android-Universal-Image-Loader,vivekkiran/Android-Universal-Image-Loader,EricInCD/Android-Universal-Image-Loader,finch0219/Android-Universal-Image-Loader,ForNowForever/Android-Universal-Image-Loader,yushiwo/Android-Universal-Image-Loader,lolevsky/Android-Universal-Image-Loader,hejunbinlan/Android-Universal-Image-Loader,Topface/Android-Universal-Image-Loader,captainJeck/Android-Universal-Image-Loader,lq-ever/Android-Universal-Image-Loader,leixinstar/Android-Universal-Image-Loader,wanelo/android-imageloader,yummy222/Android-Universal-Image-Loader,ZhaoYukai/Android-Universal-Image-Loader,wiStar/Android-Universal-Image-Loader,qingsong-xu/Android-Universal-Image-Loader,nostra13/Android-Universal-Image-Loader,askk/Android-Universal-Image-Loader,wyxacc/Android-Universal-Image-Loader,krumman/Android-Universal-Image-Loader,ijidan/Android-Universal-Image-Loader,dat0106/Android-Universal-Image-Loader,jjzhoujun/Android-Universal-Image-Loader,Rachel-Ding/Android-Universal-Image-Loader,maitho/Android-Universal-Image-Loader,charlialiang/Android-Universal-Image-Loader,yummykwok/Android-Universal-Image-Loader,zhangtianqiu/imagLoader,weikipeng/Android-Universal-Image-Loader,pchauhan/Android-Universal-Image-Loader,ManagerOrganization/Android-Universal-Image-Loader,8tory/Android-Universal-Image-Loader,RomzesRover/Android-Universal-Image-Loader,maolala/Android-Universal-Image-Loader,yuzhiboi/Android-Universal-Image-Loader,zlonglove/Android-Universal-Image-Loader-,Jokeby/Android-Universal-Image-Loader,MayurAmipara/Android-Universal-Image-Loader,lemoclone/Android-Universal-Image-Loader,Ringares/Android-Universal-Image-Loader,lixinxinlove/Android-Universal-Image-Loader,jxauchengchao/Android-Universal-Image-Loader,zjutzhaodj/Android-Universal-Image-Loader,TY-tianyu/Android-Universal-Image-Loader,imoblife/Android-Universal-Image-Loader,sixgodIT/Android-Universal-Image-Loader,libo2007/Android-Universal-Image-Loader,lovecc0923/Android-Universal-Image-Loader,lostghoul/Android-Universal-Image-Loader,FinalLevel/Android-Universal-Image-Loader,Faner007/Android-Universal-Image-Loader,wmg494005678/Android-Universal-Image-Loader,bellycard/Android-Universal-Image-Loader,ranjith068/Android-Universal-Image-Loader,java02014/Android-Universal-Image-Loader,chwnFlyPig/Android-Universal-Image-Loader,hgl888/Android-Universal-Image-Loader,jjjjjjjjj99999/Android-Universal-Image-Loader,309746069/Android-Universal-Image-Loader,zhupengGitHub/Android-Universal-Image-Loader,jekey/Android-Universal-Image-Loader,moziqi/Android-Universal-Image-Loader,yangshangwei/Android-Universal-Image-Loader,kingdawin/Android-Universal-Image-Loader,LittleRobotRoad/Android-Universal-Image-Loader,Fastrun/Android-Universal-Image-Loader,StevenWT/Android-Universal-Image-Loader,huihui4045/Android-Universal-Image-Loader,yigeyidian/Android-Universal-Image-Loader,akhilesh0707/Android-Universal-Image-Loader,lypdemo/Android-Universal-Image-Loader,littlefisher112291/Android-Universal-Image-Loader,tandingbo/Android-Universal-Image-Loader
package com.nostra13.universalimageloader.imageloader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.Field; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import android.app.Activity; import android.graphics.Bitmap; import android.util.Log; import android.view.ViewGroup.LayoutParams; import android.widget.ImageView; import com.nostra13.universalimageloader.R; import com.nostra13.universalimageloader.utils.FileUtils; /** * Singletone for image loading and displaying at {@link ImageView ImageViews}<br /> * <b>NOTE:</b> {@link #init(ImageLoaderConfiguration)} method must be called before any other method. * * @author Sergey Tarasevich (nostra13[at]gmail[dot]com) */ public class ImageLoader { private static final String TAG = ImageLoader.class.getSimpleName(); private static final String ERROR_NOT_INIT = "ImageLoader must be init with configuration before using"; private static final String ERROR_INIT_CONFIG_WITH_NULL = "ImageLoader configuration can not be initialized with null"; private static final int IMAGE_TAG_KEY = R.id.tag_image_loader; private ImageLoaderConfiguration configuration; private ExecutorService imageLoadingExecutor; private ImageLoadingListener emptyListener; private volatile static ImageLoader instance; /** Returns singletone class instance */ public static ImageLoader getInstance() { if (instance == null) { synchronized (ImageLoader.class) { if (instance == null) { instance = new ImageLoader(); } } } return instance; } private ImageLoader() { } /** * Initializes ImageLoader's singletone instance with configuration. Method shoiuld be called <b>once</b> (each * following call will have no effect)<br /> * * @param configuration * {@linkplain ImageLoaderConfiguration ImageLoader configuration} * @throws IllegalArgumentException * if <b>configuration</b> parameter is null */ public synchronized void init(ImageLoaderConfiguration configuration) { if (configuration == null) { throw new IllegalArgumentException(ERROR_INIT_CONFIG_WITH_NULL); } if (this.configuration == null) { this.configuration = configuration; imageLoadingExecutor = Executors.newFixedThreadPool(configuration.threadPoolSize); emptyListener = new EmptyListener(); } } /** * Adds display image task to execution pool. Image will be set to ImageView when it's turn. <br/> * Default {@linkplain DisplayImageOptions display image options} from {@linkplain ImageLoaderConfiguration * configuration} will be used.<br /> * <b>NOTE:</b> {@link #init(ImageLoaderConfiguration)} method must be called before this method call * * @param url * Image URL (i.e. "http://site.com/image.png", "file:///mnt/sdcard/image.png") * @param imageView * {@link ImageView} which should display image * @throws RuntimeException * if {@link #init(ImageLoaderConfiguration)} method wasn't called before */ public void displayImage(String url, ImageView imageView) { displayImage(url, imageView, null, null); } /** * Adds display image task to execution pool. Image will be set to ImageView when it's turn.<br /> * <b>NOTE:</b> {@link #init(ImageLoaderConfiguration)} method must be called before this method call * * @param url * Image URL (i.e. "http://site.com/image.png", "file:///mnt/sdcard/image.png") * @param imageView * {@link ImageView} which should display image * @param options * {@linkplain DisplayImageOptions Display image options} for image displaying. If <b>null</b> - default * display image options * {@linkplain ImageLoaderConfiguration.Builder#defaultDisplayImageOptions(DisplayImageOptions) from * configuration} will be used. * @throws RuntimeException * if {@link #init(ImageLoaderConfiguration)} method wasn't called before */ public void displayImage(String url, ImageView imageView, DisplayImageOptions options) { displayImage(url, imageView, options, null); } /** * Adds display image task to execution pool. Image will be set to ImageView when it's turn.<br /> * Default {@linkplain DisplayImageOptions display image options} from {@linkplain ImageLoaderConfiguration * configuration} will be used.<br /> * <b>NOTE:</b> {@link #init(ImageLoaderConfiguration)} method must be called before this method call * * @param url * Image URL (i.e. "http://site.com/image.png", "file:///mnt/sdcard/image.png") * @param imageView * {@link ImageView} which should display image * @param listener * {@linkplain ImageLoadingListener Listener} for image loading process. Listener fires events only if * there is no image for loading in memory cache. If there is image for loading in memory cache then * image is displayed at ImageView but listener does not fire any event. Listener fires events on UI * thread. * @throws RuntimeException * if {@link #init(ImageLoaderConfiguration)} method wasn't called before */ public void displayImage(String url, ImageView imageView, ImageLoadingListener listener) { displayImage(url, imageView, null, listener); } /** * Adds display image task to execution pool. Image will be set to ImageView when it's turn.<br /> * <b>NOTE:</b> {@link #init(ImageLoaderConfiguration)} method must be called before this method call * * @param url * Image URL (i.e. "http://site.com/image.png", "file:///mnt/sdcard/image.png") * @param imageView * {@link ImageView} which should display image * @param options * {@linkplain DisplayImageOptions Display image options} for image displaying. If <b>null</b> - default * display image options * {@linkplain ImageLoaderConfiguration.Builder#defaultDisplayImageOptions(DisplayImageOptions) from * configuration} will be used. * @param listener * {@linkplain ImageLoadingListener Listener} for image loading process. Listener fires events only if * there is no image for loading in memory cache. If there is image for loading in memory cache then * image is displayed at ImageView but listener does not fire any event. Listener fires events on UI * thread. * @throws RuntimeException * if {@link #init(ImageLoaderConfiguration)} method wasn't called before */ public void displayImage(String url, ImageView imageView, DisplayImageOptions options, ImageLoadingListener listener) { if (configuration == null) { throw new RuntimeException(ERROR_NOT_INIT); } if (url == null || url.length() == 0 || imageView == null) { return; } if (listener == null) { listener = emptyListener; } if (options == null) { options = configuration.defaultDisplayImageOptions; } // Set specific tag to ImageView. This tag will be used to prevent load image from other URL into this ImageView. imageView.setTag(IMAGE_TAG_KEY, url); Bitmap bmp = configuration.memoryCache.get(url); if (bmp != null && !bmp.isRecycled()) { imageView.setImageBitmap(bmp); } else { listener.onLoadingStarted(); if (imageLoadingExecutor.isShutdown()) { imageLoadingExecutor = Executors.newFixedThreadPool(configuration.threadPoolSize); } ImageLoadingInfo imageLoadingInfo = new ImageLoadingInfo(url, imageView, options, listener); imageLoadingExecutor.submit(new DisplayImageTask(imageLoadingInfo)); if (options.isShowStubImage()) { imageView.setImageResource(options.getStubImage()); } else { imageView.setImageBitmap(null); } } } /** Stops all running display image tasks, discards all other scheduled tasks */ public void stop() { if (imageLoadingExecutor != null) { imageLoadingExecutor.shutdown(); } } /** * Clear memory cache.<br /> * Do nothing if {@link #init(ImageLoaderConfiguration)} method wasn't called before. */ public void clearMemoryCache() { if (configuration != null) { configuration.memoryCache.clear(); } } /** * Clear disc cache.<br /> * Do nothing if {@link #init(ImageLoaderConfiguration)} method wasn't called before. */ public void clearDiscCache() { if (configuration != null) { configuration.discCache.clear(); } } /** Information about display image task */ private final class ImageLoadingInfo { private final String url; private final ImageView imageView; private final DisplayImageOptions options; private final ImageLoadingListener listener; public ImageLoadingInfo(String url, ImageView imageView, DisplayImageOptions options, ImageLoadingListener listener) { this.url = url; this.imageView = imageView; this.options = options; this.listener = listener; } /** Whether current URL matches to URL from ImageView tag */ boolean isConsistent() { return url.equals(imageView.getTag(IMAGE_TAG_KEY)); } } /** * Presents display image task. Used to load image from Internet or file system, decode it to {@link Bitmap}, and * display it in {@link ImageView} through {@link DisplayBitmapTask}. */ private class DisplayImageTask implements Runnable { private final ImageLoadingInfo imageLoadingInfo; public DisplayImageTask(ImageLoadingInfo imageLoadingInfo) { this.imageLoadingInfo = imageLoadingInfo; } @Override public void run() { if (!imageLoadingInfo.isConsistent()) { return; } // Load bitmap ImageSize targetImageSize = getImageSizeScaleTo(imageLoadingInfo.imageView); Bitmap bmp = getBitmap(imageLoadingInfo.url, targetImageSize, imageLoadingInfo.options.isCacheOnDisc()); if (bmp == null) { imageLoadingInfo.listener.onLoadingFailed(); return; } if (!imageLoadingInfo.isConsistent()) { return; } // Cache bitmap in memory if (imageLoadingInfo.options.isCacheInMemory()) { configuration.memoryCache.put(imageLoadingInfo.url, bmp); } // Display image in {@link ImageView} on UI thread DisplayBitmapTask displayBitmapTask = new DisplayBitmapTask(imageLoadingInfo, bmp); Activity activity = (Activity) imageLoadingInfo.imageView.getContext(); activity.runOnUiThread(displayBitmapTask); } /** * Defines image size for loading at memory (for memory economy) by {@link ImageView} parameters.<br /> * Size computing algorithm:<br /> * 1) Get <b>maxWidth</b> and <b>maxHeight</b>. If both of them are not set then go to step #2.<br /> * 2) Get <b>layout_width</b> and <b>layout_height</b>. If both of them haven't exact value then go to step * #3.</br> 3) Get device screen dimensions. */ private ImageSize getImageSizeScaleTo(ImageView imageView) { int width = -1; int height = -1; // Check maxWidth and maxHeight parameters try { Field maxWidthField = ImageView.class.getDeclaredField("mMaxWidth"); Field maxHeightField = ImageView.class.getDeclaredField("mMaxHeight"); maxWidthField.setAccessible(true); maxHeightField.setAccessible(true); int maxWidth = (Integer) maxWidthField.get(imageView); int maxHeight = (Integer) maxHeightField.get(imageView); if (maxWidth >= 0 && maxWidth < Integer.MAX_VALUE) { width = maxWidth; } if (maxHeight >= 0 && maxHeight < Integer.MAX_VALUE) { height = maxHeight; } } catch (Exception e) { Log.e(TAG, e.getMessage(), e); } if (width < 0 && height < 0) { // Get layout width and height parameters LayoutParams params = imageView.getLayoutParams(); width = params.width; height = params.height; } // Get device screen dimensions if (width < 0 && height < 0) { width = configuration.maxImageWidthForMemoryCache; height = configuration.maxImageHeightForMemoryCache; } return new ImageSize(width, height); } private Bitmap getBitmap(String imageUrl, ImageSize targetImageSize, boolean cacheImageOnDisc) { File f = configuration.discCache.getFile(imageUrl); // Try to load image from disc cache try { if (f.exists()) { Bitmap b = ImageDecoder.decodeFile(f.toURL(), targetImageSize); if (b != null) { return b; } } } catch (IOException e) { // There is no image in disc cache. Do nothing } // Load image from Web Bitmap bitmap = null; try { URL imageUrlForDecoding = null; if (cacheImageOnDisc) { saveImageOnDisc(imageUrl, f); imageUrlForDecoding = f.toURL(); } else { imageUrlForDecoding = new URL(imageUrl); } bitmap = ImageDecoder.decodeFile(imageUrlForDecoding, targetImageSize); } catch (Exception ex) { Log.e(TAG, String.format("Exception while loading bitmap from URL=%s : %s", imageUrl, ex.getMessage()), ex); if (f.exists()) { f.delete(); } } return bitmap; } private void saveImageOnDisc(String imageUrl, File targetFile) throws MalformedURLException, IOException { HttpURLConnection conn = (HttpURLConnection) new URL(imageUrl).openConnection(); conn.setConnectTimeout(configuration.httpConnectTimeout); conn.setReadTimeout(configuration.httpReadTimeout); InputStream is = conn.getInputStream(); try { OutputStream os = new FileOutputStream(targetFile); try { FileUtils.copyStream(is, os); } finally { os.close(); } } finally { is.close(); } } } /** Used to display bitmap in {@link ImageView}. Must be called on UI thread. */ private class DisplayBitmapTask implements Runnable { private final Bitmap bitmap; private final ImageLoadingInfo imageLoadingInfo; public DisplayBitmapTask(ImageLoadingInfo imageLoadingInfo, Bitmap bitmap) { this.bitmap = bitmap; this.imageLoadingInfo = imageLoadingInfo; } public void run() { if (imageLoadingInfo.isConsistent()) { imageLoadingInfo.imageView.setImageBitmap(bitmap); imageLoadingInfo.listener.onLoadingComplete(); } } } private class EmptyListener implements ImageLoadingListener { @Override public void onLoadingStarted() { } @Override public void onLoadingFailed() { } @Override public void onLoadingComplete() { } } }
UniversalImageLoader/src/com/nostra13/universalimageloader/imageloader/ImageLoader.java
package com.nostra13.universalimageloader.imageloader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.Field; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import android.app.Activity; import android.graphics.Bitmap; import android.util.Log; import android.view.ViewGroup.LayoutParams; import android.widget.ImageView; import com.nostra13.universalimageloader.R; import com.nostra13.universalimageloader.utils.FileUtils; /** * Singletone for image loading and displaying at {@link ImageView ImageViews}<br /> * <b>NOTE:</b> {@link #init(ImageLoaderConfiguration)} method must be called before any other method. * * @author Sergey Tarasevich (nostra13[at]gmail[dot]com) */ public class ImageLoader { private static final String TAG = ImageLoader.class.getSimpleName(); private static final String ERROR_NOT_INIT = "ImageLoader must be init with configuration before using"; private static final String ERROR_INIT_CONFIG_WITH_NULL = "ImageLoader configuration can not be initialized with null"; private static final int IMAGE_TAG_KEY = R.id.tag_image_loader; private ImageLoaderConfiguration configuration; private ExecutorService imageLoadingExecutor; private ImageLoadingListener emptyListener; private volatile static ImageLoader instance; /** Returns singletone class instance */ public static ImageLoader getInstance() { if (instance == null) { synchronized (ImageLoader.class) { if (instance == null) { instance = new ImageLoader(); } } } return instance; } private ImageLoader() { } /** * Initializes ImageLoader's singletone instance with configuration. Method shoiuld be called <b>once</b> (each * following call will have no effect)<br /> * * @param configuration * {@linkplain ImageLoaderConfiguration ImageLoader configuration} * @throws IllegalArgumentException * if <b>configuration</b> parameter is null */ public synchronized void init(ImageLoaderConfiguration configuration) { if (configuration == null) { throw new IllegalArgumentException(ERROR_INIT_CONFIG_WITH_NULL); } if (this.configuration == null) { this.configuration = configuration; imageLoadingExecutor = Executors.newFixedThreadPool(configuration.threadPoolSize); emptyListener = new EmptyImageLoadingListener(); } } /** * Adds display image task to execution pool. Image will be set to ImageView when it's turn. <br/> * Default {@linkplain DisplayImageOptions display image options} from {@linkplain ImageLoaderConfiguration * configuration} will be used.<br /> * <b>NOTE:</b> {@link #init(ImageLoaderConfiguration)} method must be called before this method call * * @param url * Image URL (i.e. "http://site.com/image.png", "file:///mnt/sdcard/image.png") * @param imageView * {@link ImageView} which should display image * @throws RuntimeException * if {@link #init(ImageLoaderConfiguration)} method wasn't called before */ public void displayImage(String url, ImageView imageView) { displayImage(url, imageView, null, null); } /** * Adds display image task to execution pool. Image will be set to ImageView when it's turn.<br /> * <b>NOTE:</b> {@link #init(ImageLoaderConfiguration)} method must be called before this method call * * @param url * Image URL (i.e. "http://site.com/image.png", "file:///mnt/sdcard/image.png") * @param imageView * {@link ImageView} which should display image * @param options * {@linkplain DisplayImageOptions Display image options} for image displaying. If <b>null</b> - default * display image options * {@linkplain ImageLoaderConfiguration.Builder#defaultDisplayImageOptions(DisplayImageOptions) from * configuration} will be used. * @throws RuntimeException * if {@link #init(ImageLoaderConfiguration)} method wasn't called before */ public void displayImage(String url, ImageView imageView, DisplayImageOptions options) { displayImage(url, imageView, options, null); } /** * Adds display image task to execution pool. Image will be set to ImageView when it's turn.<br /> * Default {@linkplain DisplayImageOptions display image options} from {@linkplain ImageLoaderConfiguration * configuration} will be used.<br /> * <b>NOTE:</b> {@link #init(ImageLoaderConfiguration)} method must be called before this method call * * @param url * Image URL (i.e. "http://site.com/image.png", "file:///mnt/sdcard/image.png") * @param imageView * {@link ImageView} which should display image * @param listener * {@linkplain ImageLoadingListener Listener} for image loading process. Listener fires events only if * there is no image for loading in memory cache. If there is image for loading in memory cache then * image is displayed at ImageView but listener does not fire any event. Listener fires events on UI * thread. * @throws RuntimeException * if {@link #init(ImageLoaderConfiguration)} method wasn't called before */ public void displayImage(String url, ImageView imageView, ImageLoadingListener listener) { displayImage(url, imageView, null, listener); } /** * Adds display image task to execution pool. Image will be set to ImageView when it's turn.<br /> * <b>NOTE:</b> {@link #init(ImageLoaderConfiguration)} method must be called before this method call * * @param url * Image URL (i.e. "http://site.com/image.png", "file:///mnt/sdcard/image.png") * @param imageView * {@link ImageView} which should display image * @param options * {@linkplain DisplayImageOptions Display image options} for image displaying. If <b>null</b> - default * display image options * {@linkplain ImageLoaderConfiguration.Builder#defaultDisplayImageOptions(DisplayImageOptions) from * configuration} will be used. * @param listener * {@linkplain ImageLoadingListener Listener} for image loading process. Listener fires events only if * there is no image for loading in memory cache. If there is image for loading in memory cache then * image is displayed at ImageView but listener does not fire any event. Listener fires events on UI * thread. * @throws RuntimeException * if {@link #init(ImageLoaderConfiguration)} method wasn't called before */ public void displayImage(String url, ImageView imageView, DisplayImageOptions options, ImageLoadingListener listener) { if (configuration == null) { throw new RuntimeException(ERROR_NOT_INIT); } if (url == null || url.length() == 0 || imageView == null) { return; } if (listener == null) { listener = emptyListener; } if (options == null) { options = configuration.defaultDisplayImageOptions; } // Set specific tag to ImageView. This tag will be used to prevent load image from other URL into this ImageView. imageView.setTag(IMAGE_TAG_KEY, url); Bitmap bmp = configuration.memoryCache.get(url); if (bmp != null && !bmp.isRecycled()) { imageView.setImageBitmap(bmp); } else { listener.onLoadingStarted(); if (imageLoadingExecutor.isShutdown()) { imageLoadingExecutor = Executors.newFixedThreadPool(configuration.threadPoolSize); } ImageLoadingInfo imageLoadingInfo = new ImageLoadingInfo(url, imageView, options, listener); imageLoadingExecutor.submit(new DisplayImageTask(imageLoadingInfo)); if (options.isShowStubImage()) { imageView.setImageResource(options.getStubImage()); } else { imageView.setImageBitmap(null); } } } /** Stops all running display image tasks, discards all other scheduled tasks */ public void stop() { if (imageLoadingExecutor != null) { imageLoadingExecutor.shutdown(); } } /** * Clear memory cache.<br /> * Do nothing if {@link #init(ImageLoaderConfiguration)} method wasn't called before. */ public void clearMemoryCache() { if (configuration != null) { configuration.memoryCache.clear(); } } /** * Clear disc cache.<br /> * Do nothing if {@link #init(ImageLoaderConfiguration)} method wasn't called before. */ public void clearDiscCache() { if (configuration != null) { configuration.discCache.clear(); } } /** Information about display image task */ private final class ImageLoadingInfo { private final String url; private final ImageView imageView; private final DisplayImageOptions options; private final ImageLoadingListener listener; public ImageLoadingInfo(String url, ImageView imageView, DisplayImageOptions options, ImageLoadingListener listener) { this.url = url; this.imageView = imageView; this.options = options; this.listener = listener; } /** Whether current URL matches to URL from ImageView tag */ boolean isConsistent() { return url.equals(imageView.getTag(IMAGE_TAG_KEY)); } } /** * Presents display image task. Used to load image from Internet or file system, decode it to {@link Bitmap}, and * display it in {@link ImageView} through {@link DisplayBitmapTask}. */ private class DisplayImageTask implements Runnable { private final ImageLoadingInfo imageLoadingInfo; public DisplayImageTask(ImageLoadingInfo imageLoadingInfo) { this.imageLoadingInfo = imageLoadingInfo; } @Override public void run() { if (!imageLoadingInfo.isConsistent()) { return; } // Load bitmap ImageSize targetImageSize = getImageSizeScaleTo(imageLoadingInfo.imageView); Bitmap bmp = getBitmap(imageLoadingInfo.url, targetImageSize, imageLoadingInfo.options.isCacheOnDisc()); if (bmp == null) { imageLoadingInfo.listener.onLoadingFailed(); return; } if (!imageLoadingInfo.isConsistent()) { return; } // Cache bitmap in memory if (imageLoadingInfo.options.isCacheInMemory()) { configuration.memoryCache.put(imageLoadingInfo.url, bmp); } // Display image in {@link ImageView} on UI thread DisplayBitmapTask displayBitmapTask = new DisplayBitmapTask(imageLoadingInfo, bmp); Activity activity = (Activity) imageLoadingInfo.imageView.getContext(); activity.runOnUiThread(displayBitmapTask); } /** * Defines image size for loading at memory (for memory economy) by {@link ImageView} parameters.<br /> * Size computing algorithm:<br /> * 1) Get <b>maxWidth</b> and <b>maxHeight</b>. If both of them are not set then go to step #2.<br /> * 2) Get <b>layout_width</b> and <b>layout_height</b>. If both of them haven't exact value then go to step * #3.</br> 3) Get device screen dimensions. */ private ImageSize getImageSizeScaleTo(ImageView imageView) { int width = -1; int height = -1; // Check maxWidth and maxHeight parameters try { Field maxWidthField = ImageView.class.getDeclaredField("mMaxWidth"); Field maxHeightField = ImageView.class.getDeclaredField("mMaxHeight"); maxWidthField.setAccessible(true); maxHeightField.setAccessible(true); int maxWidth = (Integer) maxWidthField.get(imageView); int maxHeight = (Integer) maxHeightField.get(imageView); if (maxWidth >= 0 && maxWidth < Integer.MAX_VALUE) { width = maxWidth; } if (maxHeight >= 0 && maxHeight < Integer.MAX_VALUE) { height = maxHeight; } } catch (Exception e) { Log.e(TAG, e.getMessage(), e); } if (width < 0 && height < 0) { // Get layout width and height parameters LayoutParams params = imageView.getLayoutParams(); width = params.width; height = params.height; } // Get device screen dimensions if (width < 0 && height < 0) { width = configuration.maxImageWidthForMemoryCache; height = configuration.maxImageHeightForMemoryCache; } return new ImageSize(width, height); } private Bitmap getBitmap(String imageUrl, ImageSize targetImageSize, boolean cacheImageOnDisc) { File f = configuration.discCache.getFile(imageUrl); // Try to load image from disc cache try { if (f.exists()) { Bitmap b = ImageDecoder.decodeFile(f.toURL(), targetImageSize); if (b != null) { return b; } } } catch (IOException e) { // There is no image in disc cache. Do nothing } // Load image from Web Bitmap bitmap = null; try { URL imageUrlForDecoding = null; if (cacheImageOnDisc) { saveImageOnDisc(imageUrl, f); imageUrlForDecoding = f.toURL(); } else { imageUrlForDecoding = new URL(imageUrl); } bitmap = ImageDecoder.decodeFile(imageUrlForDecoding, targetImageSize); } catch (Exception ex) { Log.e(TAG, String.format("Exception while loading bitmap from URL=%s : %s", imageUrl, ex.getMessage()), ex); if (f.exists()) { f.delete(); } } return bitmap; } private void saveImageOnDisc(String imageUrl, File targetFile) throws MalformedURLException, IOException { HttpURLConnection conn = (HttpURLConnection) new URL(imageUrl).openConnection(); conn.setConnectTimeout(configuration.httpConnectTimeout); conn.setReadTimeout(configuration.httpReadTimeout); InputStream is = conn.getInputStream(); try { OutputStream os = new FileOutputStream(targetFile); try { FileUtils.copyStream(is, os); } finally { os.close(); } } finally { is.close(); } } } /** Used to display bitmap in {@link ImageView}. Must be called on UI thread. */ private class DisplayBitmapTask implements Runnable { private final Bitmap bitmap; private final ImageLoadingInfo imageLoadingInfo; public DisplayBitmapTask(ImageLoadingInfo imageLoadingInfo, Bitmap bitmap) { this.bitmap = bitmap; this.imageLoadingInfo = imageLoadingInfo; } public void run() { if (imageLoadingInfo.isConsistent()) { imageLoadingInfo.imageView.setImageBitmap(bitmap); imageLoadingInfo.listener.onLoadingComplete(); } } } private class EmptyImageLoadingListener implements ImageLoadingListener { @Override public void onLoadingStarted() { } @Override public void onLoadingFailed() { } @Override public void onLoadingComplete() { } } }
Rename EmptyListener -> EmptyImageLoadingListener
UniversalImageLoader/src/com/nostra13/universalimageloader/imageloader/ImageLoader.java
Rename EmptyListener -> EmptyImageLoadingListener
Java
apache-2.0
2a026cbb9af0f2fbaee01ddf97c208f786e3211f
0
vvv1559/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,retomerz/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,asedunov/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,da1z/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,suncycheng/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,ibinti/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,ibinti/intellij-community,retomerz/intellij-community,apixandru/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,fitermay/intellij-community,FHannes/intellij-community,semonte/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,fitermay/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,apixandru/intellij-community,signed/intellij-community,FHannes/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,semonte/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,asedunov/intellij-community,ibinti/intellij-community,allotria/intellij-community,hurricup/intellij-community,FHannes/intellij-community,retomerz/intellij-community,FHannes/intellij-community,signed/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,xfournet/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,allotria/intellij-community,fitermay/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,FHannes/intellij-community,retomerz/intellij-community,fitermay/intellij-community,fitermay/intellij-community,hurricup/intellij-community,fitermay/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,allotria/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,allotria/intellij-community,da1z/intellij-community,hurricup/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,fitermay/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,signed/intellij-community,xfournet/intellij-community,da1z/intellij-community,asedunov/intellij-community,signed/intellij-community,allotria/intellij-community,da1z/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,FHannes/intellij-community,asedunov/intellij-community,xfournet/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,signed/intellij-community,FHannes/intellij-community,asedunov/intellij-community,semonte/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,signed/intellij-community,xfournet/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,allotria/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,retomerz/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,semonte/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,apixandru/intellij-community,signed/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,da1z/intellij-community,signed/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,signed/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,allotria/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,da1z/intellij-community,retomerz/intellij-community,allotria/intellij-community,FHannes/intellij-community,FHannes/intellij-community,apixandru/intellij-community,semonte/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,retomerz/intellij-community,hurricup/intellij-community,hurricup/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,youdonghai/intellij-community,da1z/intellij-community,FHannes/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,fitermay/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,fitermay/intellij-community
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.wm.impl.content; import com.intellij.ide.DataManager; import com.intellij.ide.IdeEventQueue; import com.intellij.ide.actions.CloseAction; import com.intellij.ide.actions.ShowContentAction; import com.intellij.ide.util.PropertiesComponent; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.actionSystem.impl.ActionManagerImpl; import com.intellij.openapi.actionSystem.impl.MenuItemPresentationFactory; import com.intellij.openapi.project.DumbAwareAction; import com.intellij.openapi.ui.popup.JBPopupFactory; import com.intellij.openapi.ui.popup.ListPopup; import com.intellij.openapi.util.*; import com.intellij.openapi.wm.IdeFrame; import com.intellij.openapi.wm.ToolWindowContentUiType; import com.intellij.openapi.wm.impl.ToolWindowImpl; import com.intellij.ui.PopupHandler; import com.intellij.ui.awt.RelativeRectangle; import com.intellij.ui.content.*; import com.intellij.ui.content.tabs.PinToolwindowTabAction; import com.intellij.ui.content.tabs.TabbedContentAction; import com.intellij.ui.switcher.SwitchProvider; import com.intellij.ui.switcher.SwitchTarget; import com.intellij.util.Alarm; import com.intellij.util.ContentUtilEx; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.ui.UIUtil; import com.intellij.util.ui.update.ComparableObject; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.border.EmptyBorder; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionAdapter; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.List; public class ToolWindowContentUi extends JPanel implements ContentUI, PropertyChangeListener, DataProvider, SwitchProvider { public static final String POPUP_PLACE = "ToolwindowPopup"; // when client property is put in toolwindow component, hides toolwindow label public static final String HIDE_ID_LABEL = "HideIdLabel"; ContentManager myManager; final JPanel myContent = new JPanel(new BorderLayout()); ToolWindowImpl myWindow; TabbedContentAction.CloseAllAction myCloseAllAction; TabbedContentAction.MyNextTabAction myNextTabAction; TabbedContentAction.MyPreviousTabAction myPreviousTabAction; ShowContentAction myShowContent; ContentLayout myTabsLayout = new TabContentLayout(this); ContentLayout myComboLayout = new ComboContentLayout(this); private ToolWindowContentUiType myType = ToolWindowContentUiType.TABBED; private boolean myShouldNotShowPopup; public ToolWindowContentUi(ToolWindowImpl window) { myWindow = window; myContent.setOpaque(false); myContent.setFocusable(false); setOpaque(false); myShowContent = new ShowContentAction(myWindow, myContent); setBorder(new EmptyBorder(0, 0, 0, 2)); } public void setType(@NotNull ToolWindowContentUiType type) { if (myType != type) { if (myType != null) { getCurrentLayout().reset(); } myType = type; getCurrentLayout().init(); rebuild(); } } private ContentLayout getCurrentLayout() { assert myManager != null; return myType == ToolWindowContentUiType.TABBED ? myTabsLayout : myComboLayout; } public JComponent getComponent() { return myContent; } public boolean isCycleRoot() { return true; } public JComponent getTabComponent() { return this; } public void setManager(@NotNull final ContentManager manager) { if (myManager != null) { getCurrentLayout().reset(); } myManager = manager; getCurrentLayout().init(); myManager.addContentManagerListener(new ContentManagerListener() { public void contentAdded(final ContentManagerEvent event) { getCurrentLayout().contentAdded(event); event.getContent().addPropertyChangeListener(ToolWindowContentUi.this); rebuild(); } public void contentRemoved(final ContentManagerEvent event) { event.getContent().removePropertyChangeListener(ToolWindowContentUi.this); getCurrentLayout().contentRemoved(event); ensureSelectedContentVisible(); rebuild(); } public void contentRemoveQuery(final ContentManagerEvent event) { } public void selectionChanged(final ContentManagerEvent event) { ensureSelectedContentVisible(); update(); myContent.revalidate(); myContent.repaint(); } }); initMouseListeners(this, this); rebuild(); myCloseAllAction = new TabbedContentAction.CloseAllAction(myManager); myNextTabAction = new TabbedContentAction.MyNextTabAction(myManager); myPreviousTabAction = new TabbedContentAction.MyPreviousTabAction(myManager); } private void ensureSelectedContentVisible() { final Content selected = myManager.getSelectedContent(); if (selected == null) { myContent.removeAll(); return; } if (myContent.getComponentCount() == 1) { final Component visible = myContent.getComponent(0); if (visible == selected.getComponent()) return; } myContent.removeAll(); myContent.add(selected.getComponent(), BorderLayout.CENTER); myContent.revalidate(); myContent.repaint(); } private void rebuild() { getCurrentLayout().rebuild(); getCurrentLayout().update(); revalidate(); repaint(); if (myManager.getContentCount() == 0 && myWindow.isToHideOnEmptyContent()) { myWindow.hide(null); } } public void doLayout() { getCurrentLayout().layout(); } protected void paintComponent(final Graphics g) { super.paintComponent(g); getCurrentLayout().paintComponent(g); } protected void paintChildren(final Graphics g) { super.paintChildren(g); getCurrentLayout().paintChildren(g); } public Dimension getMinimumSize() { Insets insets = getInsets(); return new Dimension(insets.left + insets.right + getCurrentLayout().getMinimumWidth(), super.getMinimumSize().height); } public Dimension getPreferredSize() { Dimension size = super.getPreferredSize(); size.height = 0; for (int i = 0; i < getComponentCount(); i++) { final Component each = getComponent(i); size.height = Math.max(each.getPreferredSize().height, size.height); } return size; } public void propertyChange(final PropertyChangeEvent evt) { update(); } private void update() { getCurrentLayout().update(); revalidate(); repaint(); } public boolean isSingleSelection() { return true; } public boolean isToSelectAddedContent() { return false; } public boolean canBeEmptySelection() { return false; } public void beforeDispose() { } public boolean canChangeSelectionTo(@NotNull Content content, boolean implicit) { return true; } @NotNull @Override public String getCloseActionName() { return getCurrentLayout().getCloseActionName(); } @NotNull @Override public String getCloseAllButThisActionName() { return getCurrentLayout().getCloseAllButThisActionName(); } @NotNull @Override public String getPreviousContentActionName() { return getCurrentLayout().getPreviousContentActionName(); } @NotNull @Override public String getNextContentActionName() { return getCurrentLayout().getNextContentActionName(); } public static void initMouseListeners(final JComponent c, final ToolWindowContentUi ui) { if (c.getClientProperty(ui) != null) return; final Point[] myLastPoint = new Point[1]; c.addMouseMotionListener(new MouseMotionAdapter() { public void mouseDragged(final MouseEvent e) { if (myLastPoint[0] == null) return; final Window window = SwingUtilities.windowForComponent(c); if (window instanceof IdeFrame) return; final Point windowLocation = window.getLocationOnScreen(); PointerInfo info = MouseInfo.getPointerInfo(); if (info == null) return; final Point newPoint = info.getLocation(); Point p = myLastPoint[0]; windowLocation.translate(newPoint.x - p.x, newPoint.y - p.y); window.setLocation(windowLocation); myLastPoint[0] = newPoint; } }); c.addMouseListener(new MouseAdapter() { public void mousePressed(final MouseEvent e) { PointerInfo info = MouseInfo.getPointerInfo(); myLastPoint[0] = info != null ? info.getLocation() : e.getLocationOnScreen(); if (!e.isPopupTrigger()) { if (!UIUtil.isCloseClick(e)) { ui.myWindow.fireActivated(); } } } @Override public void mouseReleased(MouseEvent e) { if (!e.isPopupTrigger()) { if (UIUtil.isCloseClick(e, MouseEvent.MOUSE_RELEASED)) { ui.processHide(e); } } } }); c.addMouseListener(new PopupHandler() { public void invokePopup(final Component comp, final int x, final int y) { final Content content = c instanceof BaseLabel ? ((BaseLabel)c).getContent() : null; ui.showContextMenu(comp, x, y, ui.myWindow.getPopupGroup(), content); } }); c.putClientProperty(ui, Boolean.TRUE); } private void initActionGroup(DefaultActionGroup group, final Content content) { if (content == null) { return; } group.addSeparator(); group.add(new TabbedContentAction.CloseAction(content)); group.add(myCloseAllAction); group.add(new TabbedContentAction.CloseAllButThisAction(content)); group.addSeparator(); if (content.isPinnable()) { group.add(PinToolwindowTabAction.getPinAction()); group.addSeparator(); } group.add(myNextTabAction); group.add(myPreviousTabAction); group.add(myShowContent); if (content instanceof TabbedContent && ((TabbedContent)content).getTabs().size() > 1) { group.addAction(createSplitTabsAction((TabbedContent)content)); } if (Boolean.TRUE == content.getUserData(Content.TABBED_CONTENT_KEY)) { final String groupName = content.getUserData(Content.TAB_GROUP_NAME_KEY); if (groupName != null) { group.addAction(createMergeTabsAction(myManager, groupName)); } } group.addSeparator(); } public void showContextMenu(Component comp, int x, int y, ActionGroup toolWindowGroup, @Nullable Content selectedContent) { if (selectedContent == null && toolWindowGroup == null) { return; } DefaultActionGroup group = new DefaultActionGroup(); if (selectedContent != null) { initActionGroup(group, selectedContent); } if (toolWindowGroup != null) { group.addAll(toolWindowGroup); } final ActionPopupMenu popupMenu = ((ActionManagerImpl)ActionManager.getInstance()).createActionPopupMenu(POPUP_PLACE, group, new MenuItemPresentationFactory(true)); popupMenu.getComponent().show(comp, x, y); } private static AnAction createSplitTabsAction(final TabbedContent content) { return new DumbAwareAction("Split '" + content.getTitlePrefix() + "' group") { @Override public void actionPerformed(AnActionEvent e) { content.split(); } }; } private static AnAction createMergeTabsAction(final ContentManager manager, final String tabPrefix) { return new DumbAwareAction("Merge tabs to '" + tabPrefix + "' group") { @Override public void actionPerformed(AnActionEvent e) { final Content selectedContent = manager.getSelectedContent(); final List<Pair<String, JComponent>> tabs = new ArrayList<Pair<String, JComponent>>(); int selectedTab = -1; List<Content> mergedContent = ContainerUtil.newArrayList(); for (Content content : manager.getContents()) { if (tabPrefix.equals(content.getUserData(Content.TAB_GROUP_NAME_KEY))) { final String label = content.getTabName().substring(tabPrefix.length() + 2); final JComponent component = content.getComponent(); if (content == selectedContent) { selectedTab = tabs.size(); } tabs.add(Pair.create(label, component)); manager.removeContent(content, false); content.setComponent(null); mergedContent.add(content); } } PropertiesComponent.getInstance().unsetValue(TabbedContent.SPLIT_PROPERTY_PREFIX + tabPrefix); for (int i = 0; i < tabs.size(); i++) { final Pair<String, JComponent> tab = tabs.get(i); ContentUtilEx.addTabbedContent(manager, tab.second, tabPrefix, tab.first, i == selectedTab); } mergedContent.forEach(Disposer::dispose); } }; } private void processHide(final MouseEvent e) { IdeEventQueue.getInstance().blockNextEvents(e); final Component c = e.getComponent(); if (c instanceof BaseLabel) { final BaseLabel tab = (BaseLabel)c; if (tab.getContent() != null) { if (myManager.canCloseContents() && tab.getContent().isCloseable()) { myManager.removeContent(tab.getContent(), true, true, true); } else { if (myManager.getContentCount() == 1) { hideWindow(e); } } } else { hideWindow(e); } } else { hideWindow(e); } } private void hideWindow(final MouseEvent e) { if (e.isControlDown()) { myWindow.fireHiddenSide(); } else { myWindow.fireHidden(); } } @Nullable public Object getData(@NonNls String dataId) { if (PlatformDataKeys.TOOL_WINDOW.is(dataId)) return myWindow; if (CloseAction.CloseTarget.KEY.is(dataId)) { return computeCloseTarget(); } if (SwitchProvider.KEY.is(dataId) && myType == ToolWindowContentUiType.TABBED) { return this; } return null; } private CloseAction.CloseTarget computeCloseTarget() { if (myManager.canCloseContents()) { Content selected = myManager.getSelectedContent(); if (selected != null && selected.isCloseable()) { return new CloseContentTarget(selected); } } return new HideToolwindowTarget(); } private class HideToolwindowTarget implements CloseAction.CloseTarget { public void close() { myWindow.fireHidden(); } } private class CloseContentTarget implements CloseAction.CloseTarget { private Content myContent; private CloseContentTarget(Content content) { myContent = content; } public void close() { myManager.removeContent(myContent, true, true, true); } } public void dispose() { } boolean isCurrent(ContentLayout layout) { return getCurrentLayout() == layout; } public void toggleContentPopup() { if (myShouldNotShowPopup) { myShouldNotShowPopup = false; return; } final Ref<AnAction> selected = Ref.create(); final Ref<AnAction> selectedTab = Ref.create(); final Content[] contents = myManager.getContents(); final Content selectedContent = myManager.getSelectedContent(); final AnAction[] actions = new AnAction[contents.length]; for (int i = 0; i < actions.length; i++) { final Content content = contents[i]; if (content instanceof TabbedContent) { final TabbedContent tabbedContent = (TabbedContent)content; final List<Pair<String, JComponent>> tabs = ((TabbedContent)content).getTabs(); final AnAction[] tabActions = new AnAction[tabs.size()]; for (int j = 0; j < tabActions.length; j++) { final int index = j; tabActions[j] = new DumbAwareAction(tabs.get(index).first) { @Override public void actionPerformed(@NotNull AnActionEvent e) { myManager.setSelectedContent(tabbedContent); tabbedContent.selectContent(index); } }; } final DefaultActionGroup group = new DefaultActionGroup(tabActions); group.getTemplatePresentation().setText(((TabbedContent)content).getTitlePrefix()); group.setPopup(true); actions[i] = group; if (content == selectedContent) { selected.set(group); final int selectedIndex = ContentUtilEx.getSelectedTab(tabbedContent); if (selectedIndex != -1) { selectedTab.set(tabActions[selectedIndex]); } } } else { actions[i] = new DumbAwareAction() { { getTemplatePresentation().setText(content.getTabName(), false); } @Override public void actionPerformed(@NotNull AnActionEvent e) { myManager.setSelectedContent(content, true, true); } }; if (content == selectedContent) { selected.set(actions[i]); } } } final ListPopup popup = JBPopupFactory.getInstance().createActionGroupPopup(null, new DefaultActionGroup(actions), DataManager.getInstance() .getDataContext(myManager.getComponent()), false, true, true, null, -1, new Condition<AnAction>() { @Override public boolean value(AnAction action) { return action == selected.get() || action == selectedTab.get(); } }); getCurrentLayout().showContentPopup(popup); if (selectedContent instanceof TabbedContent) { new Alarm(Alarm.ThreadToUse.SWING_THREAD, popup).addRequest(new Runnable() { public void run() { popup.handleSelect(true); } }, 30); } } public List<SwitchTarget> getTargets(boolean onlyVisible, boolean originalProvider) { List<SwitchTarget> result = new ArrayList<SwitchTarget>(); if (myType == ToolWindowContentUiType.TABBED) { for (int i = 0; i < myManager.getContentCount(); i++) { result.add(new ContentSwitchTarget(myManager.getContent(i))); } } return result; } public SwitchTarget getCurrentTarget() { return new ContentSwitchTarget(myManager.getSelectedContent()); } private class ContentSwitchTarget extends ComparableObject.Impl implements SwitchTarget { private Content myContent; private ContentSwitchTarget(Content content) { myContent = content; } public ActionCallback switchTo(boolean requestFocus) { return myManager.setSelectedContentCB(myContent, requestFocus); } public boolean isVisible() { return true; } public RelativeRectangle getRectangle() { return myTabsLayout.getRectangleFor(myContent); } public Component getComponent() { return myManager.getComponent(); } @Override public String toString() { return myContent.getDisplayName(); } @NotNull @Override public Object[] getEqualityObjects() { return new Object[] {myContent}; } } }
platform/platform-impl/src/com/intellij/openapi/wm/impl/content/ToolWindowContentUi.java
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.wm.impl.content; import com.intellij.ide.DataManager; import com.intellij.ide.IdeEventQueue; import com.intellij.ide.actions.CloseAction; import com.intellij.ide.actions.ShowContentAction; import com.intellij.ide.util.PropertiesComponent; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.actionSystem.impl.ActionManagerImpl; import com.intellij.openapi.actionSystem.impl.MenuItemPresentationFactory; import com.intellij.openapi.project.DumbAwareAction; import com.intellij.openapi.ui.popup.JBPopupFactory; import com.intellij.openapi.ui.popup.ListPopup; import com.intellij.openapi.util.*; import com.intellij.openapi.wm.IdeFrame; import com.intellij.openapi.wm.ToolWindowContentUiType; import com.intellij.openapi.wm.impl.ToolWindowImpl; import com.intellij.ui.PopupHandler; import com.intellij.ui.awt.RelativeRectangle; import com.intellij.ui.content.*; import com.intellij.ui.content.tabs.PinToolwindowTabAction; import com.intellij.ui.content.tabs.TabbedContentAction; import com.intellij.ui.switcher.SwitchProvider; import com.intellij.ui.switcher.SwitchTarget; import com.intellij.util.Alarm; import com.intellij.util.ContentUtilEx; import com.intellij.util.ui.UIUtil; import com.intellij.util.ui.update.ComparableObject; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.border.EmptyBorder; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionAdapter; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.List; public class ToolWindowContentUi extends JPanel implements ContentUI, PropertyChangeListener, DataProvider, SwitchProvider { public static final String POPUP_PLACE = "ToolwindowPopup"; // when client property is put in toolwindow component, hides toolwindow label public static final String HIDE_ID_LABEL = "HideIdLabel"; ContentManager myManager; final JPanel myContent = new JPanel(new BorderLayout()); ToolWindowImpl myWindow; TabbedContentAction.CloseAllAction myCloseAllAction; TabbedContentAction.MyNextTabAction myNextTabAction; TabbedContentAction.MyPreviousTabAction myPreviousTabAction; ShowContentAction myShowContent; ContentLayout myTabsLayout = new TabContentLayout(this); ContentLayout myComboLayout = new ComboContentLayout(this); private ToolWindowContentUiType myType = ToolWindowContentUiType.TABBED; private boolean myShouldNotShowPopup; public ToolWindowContentUi(ToolWindowImpl window) { myWindow = window; myContent.setOpaque(false); myContent.setFocusable(false); setOpaque(false); myShowContent = new ShowContentAction(myWindow, myContent); setBorder(new EmptyBorder(0, 0, 0, 2)); } public void setType(@NotNull ToolWindowContentUiType type) { if (myType != type) { if (myType != null) { getCurrentLayout().reset(); } myType = type; getCurrentLayout().init(); rebuild(); } } private ContentLayout getCurrentLayout() { assert myManager != null; return myType == ToolWindowContentUiType.TABBED ? myTabsLayout : myComboLayout; } public JComponent getComponent() { return myContent; } public boolean isCycleRoot() { return true; } public JComponent getTabComponent() { return this; } public void setManager(@NotNull final ContentManager manager) { if (myManager != null) { getCurrentLayout().reset(); } myManager = manager; getCurrentLayout().init(); myManager.addContentManagerListener(new ContentManagerListener() { public void contentAdded(final ContentManagerEvent event) { getCurrentLayout().contentAdded(event); event.getContent().addPropertyChangeListener(ToolWindowContentUi.this); rebuild(); } public void contentRemoved(final ContentManagerEvent event) { event.getContent().removePropertyChangeListener(ToolWindowContentUi.this); getCurrentLayout().contentRemoved(event); ensureSelectedContentVisible(); rebuild(); } public void contentRemoveQuery(final ContentManagerEvent event) { } public void selectionChanged(final ContentManagerEvent event) { ensureSelectedContentVisible(); update(); myContent.revalidate(); myContent.repaint(); } }); initMouseListeners(this, this); rebuild(); myCloseAllAction = new TabbedContentAction.CloseAllAction(myManager); myNextTabAction = new TabbedContentAction.MyNextTabAction(myManager); myPreviousTabAction = new TabbedContentAction.MyPreviousTabAction(myManager); } private void ensureSelectedContentVisible() { final Content selected = myManager.getSelectedContent(); if (selected == null) { myContent.removeAll(); return; } if (myContent.getComponentCount() == 1) { final Component visible = myContent.getComponent(0); if (visible == selected.getComponent()) return; } myContent.removeAll(); myContent.add(selected.getComponent(), BorderLayout.CENTER); myContent.revalidate(); myContent.repaint(); } private void rebuild() { getCurrentLayout().rebuild(); getCurrentLayout().update(); revalidate(); repaint(); if (myManager.getContentCount() == 0 && myWindow.isToHideOnEmptyContent()) { myWindow.hide(null); } } public void doLayout() { getCurrentLayout().layout(); } protected void paintComponent(final Graphics g) { super.paintComponent(g); getCurrentLayout().paintComponent(g); } protected void paintChildren(final Graphics g) { super.paintChildren(g); getCurrentLayout().paintChildren(g); } public Dimension getMinimumSize() { Insets insets = getInsets(); return new Dimension(insets.left + insets.right + getCurrentLayout().getMinimumWidth(), super.getMinimumSize().height); } public Dimension getPreferredSize() { Dimension size = super.getPreferredSize(); size.height = 0; for (int i = 0; i < getComponentCount(); i++) { final Component each = getComponent(i); size.height = Math.max(each.getPreferredSize().height, size.height); } return size; } public void propertyChange(final PropertyChangeEvent evt) { update(); } private void update() { getCurrentLayout().update(); revalidate(); repaint(); } public boolean isSingleSelection() { return true; } public boolean isToSelectAddedContent() { return false; } public boolean canBeEmptySelection() { return false; } public void beforeDispose() { } public boolean canChangeSelectionTo(@NotNull Content content, boolean implicit) { return true; } @NotNull @Override public String getCloseActionName() { return getCurrentLayout().getCloseActionName(); } @NotNull @Override public String getCloseAllButThisActionName() { return getCurrentLayout().getCloseAllButThisActionName(); } @NotNull @Override public String getPreviousContentActionName() { return getCurrentLayout().getPreviousContentActionName(); } @NotNull @Override public String getNextContentActionName() { return getCurrentLayout().getNextContentActionName(); } public static void initMouseListeners(final JComponent c, final ToolWindowContentUi ui) { if (c.getClientProperty(ui) != null) return; final Point[] myLastPoint = new Point[1]; c.addMouseMotionListener(new MouseMotionAdapter() { public void mouseDragged(final MouseEvent e) { if (myLastPoint[0] == null) return; final Window window = SwingUtilities.windowForComponent(c); if (window instanceof IdeFrame) return; final Point windowLocation = window.getLocationOnScreen(); PointerInfo info = MouseInfo.getPointerInfo(); if (info == null) return; final Point newPoint = info.getLocation(); Point p = myLastPoint[0]; windowLocation.translate(newPoint.x - p.x, newPoint.y - p.y); window.setLocation(windowLocation); myLastPoint[0] = newPoint; } }); c.addMouseListener(new MouseAdapter() { public void mousePressed(final MouseEvent e) { PointerInfo info = MouseInfo.getPointerInfo(); myLastPoint[0] = info != null ? info.getLocation() : e.getLocationOnScreen(); if (!e.isPopupTrigger()) { if (!UIUtil.isCloseClick(e)) { ui.myWindow.fireActivated(); } } } @Override public void mouseReleased(MouseEvent e) { if (!e.isPopupTrigger()) { if (UIUtil.isCloseClick(e, MouseEvent.MOUSE_RELEASED)) { ui.processHide(e); } } } }); c.addMouseListener(new PopupHandler() { public void invokePopup(final Component comp, final int x, final int y) { final Content content = c instanceof BaseLabel ? ((BaseLabel)c).getContent() : null; ui.showContextMenu(comp, x, y, ui.myWindow.getPopupGroup(), content); } }); c.putClientProperty(ui, Boolean.TRUE); } private void initActionGroup(DefaultActionGroup group, final Content content) { if (content == null) { return; } group.addSeparator(); group.add(new TabbedContentAction.CloseAction(content)); group.add(myCloseAllAction); group.add(new TabbedContentAction.CloseAllButThisAction(content)); group.addSeparator(); if (content.isPinnable()) { group.add(PinToolwindowTabAction.getPinAction()); group.addSeparator(); } group.add(myNextTabAction); group.add(myPreviousTabAction); group.add(myShowContent); if (content instanceof TabbedContent && ((TabbedContent)content).getTabs().size() > 1) { group.addAction(createSplitTabsAction((TabbedContent)content)); } if (Boolean.TRUE == content.getUserData(Content.TABBED_CONTENT_KEY)) { final String groupName = content.getUserData(Content.TAB_GROUP_NAME_KEY); if (groupName != null) { group.addAction(createMergeTabsAction(myManager, groupName)); } } group.addSeparator(); } public void showContextMenu(Component comp, int x, int y, ActionGroup toolWindowGroup, @Nullable Content selectedContent) { if (selectedContent == null && toolWindowGroup == null) { return; } DefaultActionGroup group = new DefaultActionGroup(); if (selectedContent != null) { initActionGroup(group, selectedContent); } if (toolWindowGroup != null) { group.addAll(toolWindowGroup); } final ActionPopupMenu popupMenu = ((ActionManagerImpl)ActionManager.getInstance()).createActionPopupMenu(POPUP_PLACE, group, new MenuItemPresentationFactory(true)); popupMenu.getComponent().show(comp, x, y); } private static AnAction createSplitTabsAction(final TabbedContent content) { return new DumbAwareAction("Split '" + content.getTitlePrefix() + "' group") { @Override public void actionPerformed(AnActionEvent e) { content.split(); } }; } private static AnAction createMergeTabsAction(final ContentManager manager, final String tabPrefix) { return new DumbAwareAction("Merge tabs to '" + tabPrefix + "' group") { @Override public void actionPerformed(AnActionEvent e) { final Content selectedContent = manager.getSelectedContent(); final List<Pair<String, JComponent>> tabs = new ArrayList<Pair<String, JComponent>>(); int selectedTab = -1; for (Content content : manager.getContents()) { if (tabPrefix.equals(content.getUserData(Content.TAB_GROUP_NAME_KEY))) { final String label = content.getTabName().substring(tabPrefix.length() + 2); final JComponent component = content.getComponent(); if (content == selectedContent) { selectedTab = tabs.size(); } tabs.add(Pair.create(label, component)); manager.removeContent(content, false); content.setComponent(null); Disposer.dispose(content); } } PropertiesComponent.getInstance().unsetValue(TabbedContent.SPLIT_PROPERTY_PREFIX + tabPrefix); for (int i = 0; i < tabs.size(); i++) { final Pair<String, JComponent> tab = tabs.get(i); ContentUtilEx.addTabbedContent(manager, tab.second, tabPrefix, tab.first, i == selectedTab); } } }; } private void processHide(final MouseEvent e) { IdeEventQueue.getInstance().blockNextEvents(e); final Component c = e.getComponent(); if (c instanceof BaseLabel) { final BaseLabel tab = (BaseLabel)c; if (tab.getContent() != null) { if (myManager.canCloseContents() && tab.getContent().isCloseable()) { myManager.removeContent(tab.getContent(), true, true, true); } else { if (myManager.getContentCount() == 1) { hideWindow(e); } } } else { hideWindow(e); } } else { hideWindow(e); } } private void hideWindow(final MouseEvent e) { if (e.isControlDown()) { myWindow.fireHiddenSide(); } else { myWindow.fireHidden(); } } @Nullable public Object getData(@NonNls String dataId) { if (PlatformDataKeys.TOOL_WINDOW.is(dataId)) return myWindow; if (CloseAction.CloseTarget.KEY.is(dataId)) { return computeCloseTarget(); } if (SwitchProvider.KEY.is(dataId) && myType == ToolWindowContentUiType.TABBED) { return this; } return null; } private CloseAction.CloseTarget computeCloseTarget() { if (myManager.canCloseContents()) { Content selected = myManager.getSelectedContent(); if (selected != null && selected.isCloseable()) { return new CloseContentTarget(selected); } } return new HideToolwindowTarget(); } private class HideToolwindowTarget implements CloseAction.CloseTarget { public void close() { myWindow.fireHidden(); } } private class CloseContentTarget implements CloseAction.CloseTarget { private Content myContent; private CloseContentTarget(Content content) { myContent = content; } public void close() { myManager.removeContent(myContent, true, true, true); } } public void dispose() { } boolean isCurrent(ContentLayout layout) { return getCurrentLayout() == layout; } public void toggleContentPopup() { if (myShouldNotShowPopup) { myShouldNotShowPopup = false; return; } final Ref<AnAction> selected = Ref.create(); final Ref<AnAction> selectedTab = Ref.create(); final Content[] contents = myManager.getContents(); final Content selectedContent = myManager.getSelectedContent(); final AnAction[] actions = new AnAction[contents.length]; for (int i = 0; i < actions.length; i++) { final Content content = contents[i]; if (content instanceof TabbedContent) { final TabbedContent tabbedContent = (TabbedContent)content; final List<Pair<String, JComponent>> tabs = ((TabbedContent)content).getTabs(); final AnAction[] tabActions = new AnAction[tabs.size()]; for (int j = 0; j < tabActions.length; j++) { final int index = j; tabActions[j] = new DumbAwareAction(tabs.get(index).first) { @Override public void actionPerformed(@NotNull AnActionEvent e) { myManager.setSelectedContent(tabbedContent); tabbedContent.selectContent(index); } }; } final DefaultActionGroup group = new DefaultActionGroup(tabActions); group.getTemplatePresentation().setText(((TabbedContent)content).getTitlePrefix()); group.setPopup(true); actions[i] = group; if (content == selectedContent) { selected.set(group); final int selectedIndex = ContentUtilEx.getSelectedTab(tabbedContent); if (selectedIndex != -1) { selectedTab.set(tabActions[selectedIndex]); } } } else { actions[i] = new DumbAwareAction() { { getTemplatePresentation().setText(content.getTabName(), false); } @Override public void actionPerformed(@NotNull AnActionEvent e) { myManager.setSelectedContent(content, true, true); } }; if (content == selectedContent) { selected.set(actions[i]); } } } final ListPopup popup = JBPopupFactory.getInstance().createActionGroupPopup(null, new DefaultActionGroup(actions), DataManager.getInstance() .getDataContext(myManager.getComponent()), false, true, true, null, -1, new Condition<AnAction>() { @Override public boolean value(AnAction action) { return action == selected.get() || action == selectedTab.get(); } }); getCurrentLayout().showContentPopup(popup); if (selectedContent instanceof TabbedContent) { new Alarm(Alarm.ThreadToUse.SWING_THREAD, popup).addRequest(new Runnable() { public void run() { popup.handleSelect(true); } }, 30); } } public List<SwitchTarget> getTargets(boolean onlyVisible, boolean originalProvider) { List<SwitchTarget> result = new ArrayList<SwitchTarget>(); if (myType == ToolWindowContentUiType.TABBED) { for (int i = 0; i < myManager.getContentCount(); i++) { result.add(new ContentSwitchTarget(myManager.getContent(i))); } } return result; } public SwitchTarget getCurrentTarget() { return new ContentSwitchTarget(myManager.getSelectedContent()); } private class ContentSwitchTarget extends ComparableObject.Impl implements SwitchTarget { private Content myContent; private ContentSwitchTarget(Content content) { myContent = content; } public ActionCallback switchTo(boolean requestFocus) { return myManager.setSelectedContentCB(myContent, requestFocus); } public boolean isVisible() { return true; } public RelativeRectangle getRectangle() { return myTabsLayout.getRectangleFor(myContent); } public Component getComponent() { return myManager.getComponent(); } @Override public String toString() { return myContent.getDisplayName(); } @NotNull @Override public Object[] getEqualityObjects() { return new Object[] {myContent}; } } }
[tabs] merge action disposes old contents after creating new ones
platform/platform-impl/src/com/intellij/openapi/wm/impl/content/ToolWindowContentUi.java
[tabs] merge action disposes old contents after creating new ones
Java
apache-2.0
52019f24c517c3e89ea2f79d79a4a404b77b2ef5
0
aadamowski/fi.java.net,aadamowski/fi.java.net
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright (c) 2011 Oracle and/or its affiliates. All rights reserved. * * Oracle licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sun.xml.fastinfoset.util; import com.sun.xml.fastinfoset.CommonResourceBundle; public class ContiguousCharArrayArray extends ValueArray { public static final int INITIAL_CHARACTER_SIZE = 512; public static final int MAXIMUM_CHARACTER_SIZE = Integer.MAX_VALUE; protected int _maximumCharacterSize; public int[] _offset; public int[] _length; public char[] _array; public int _arrayIndex; public int _readOnlyArrayIndex; private String[] _cachedStrings; public int _cachedIndex; private ContiguousCharArrayArray _readOnlyArray; public ContiguousCharArrayArray(int initialCapacity, int maximumCapacity, int initialCharacterSize, int maximumCharacterSize) { _offset = new int[initialCapacity]; _length = new int[initialCapacity]; _array = new char[initialCharacterSize]; _maximumCapacity = maximumCapacity; _maximumCharacterSize = maximumCharacterSize; } public ContiguousCharArrayArray() { this(DEFAULT_CAPACITY, MAXIMUM_CAPACITY, INITIAL_CHARACTER_SIZE, MAXIMUM_CHARACTER_SIZE); } public final void clear() { _arrayIndex = _readOnlyArrayIndex; _size = _readOnlyArraySize; if (_cachedStrings != null) { for (int i = _readOnlyArraySize; i < _cachedStrings.length; i++) { _cachedStrings[i] = null; } } } public final int getArrayIndex() { return _arrayIndex; } public final void setReadOnlyArray(ValueArray readOnlyArray, boolean clear) { if (!(readOnlyArray instanceof ContiguousCharArrayArray)) { throw new IllegalArgumentException(CommonResourceBundle.getInstance().getString("message.illegalClass", new Object[]{readOnlyArray})); } setReadOnlyArray((ContiguousCharArrayArray)readOnlyArray, clear); } public final void setReadOnlyArray(ContiguousCharArrayArray readOnlyArray, boolean clear) { if (readOnlyArray != null) { _readOnlyArray = readOnlyArray; _readOnlyArraySize = readOnlyArray.getSize(); _readOnlyArrayIndex = readOnlyArray.getArrayIndex(); if (clear) { clear(); } _array = getCompleteCharArray(); _offset = getCompleteOffsetArray(); _length = getCompleteLengthArray(); _size = _readOnlyArraySize; _arrayIndex = _readOnlyArrayIndex; } } public final char[] getCompleteCharArray() { if (_readOnlyArray == null) { return _array; } else { final char[] ra = _readOnlyArray.getCompleteCharArray(); final char[] a = new char[_readOnlyArrayIndex + _array.length]; System.arraycopy(ra, 0, a, 0, _readOnlyArrayIndex); return a; } } public final int[] getCompleteOffsetArray() { if (_readOnlyArray == null) { return _offset; } else { final int[] ra = _readOnlyArray.getCompleteOffsetArray(); final int[] a = new int[_readOnlyArraySize + _offset.length]; System.arraycopy(ra, 0, a, 0, _readOnlyArraySize); return a; } } public final int[] getCompleteLengthArray() { if (_readOnlyArray == null) { return _length; } else { final int[] ra = _readOnlyArray.getCompleteLengthArray(); final int[] a = new int[_readOnlyArraySize + _length.length]; System.arraycopy(ra, 0, a, 0, _readOnlyArraySize); return a; } } public final String getString(int i) { if (_cachedStrings != null && i < _cachedStrings.length) { final String s = _cachedStrings[i]; return (s != null) ? s : (_cachedStrings[i] = new String(_array, _offset[i], _length[i])); } final String[] newCachedStrings = new String[_offset.length]; if (_cachedStrings != null && i >= _cachedStrings.length) { System.arraycopy(_cachedStrings, 0, newCachedStrings, 0, _cachedStrings.length); } _cachedStrings = newCachedStrings; return _cachedStrings[i] = new String(_array, _offset[i], _length[i]); } public final void ensureSize(int l) { if (_arrayIndex + l >= _array.length) { resizeArray(_arrayIndex + l); } } public final void add(int l) { if (_size == _offset.length) { resize(); } _cachedIndex = _size; _offset[_size] = _arrayIndex; _length[_size++] = l; _arrayIndex += l; } public final int add(char[] c, int l) { if (_size == _offset.length) { resize(); } final int oldArrayIndex = _arrayIndex; final int arrayIndex = oldArrayIndex + l; _cachedIndex = _size; _offset[_size] = oldArrayIndex; _length[_size++] = l; if (arrayIndex >= _array.length) { resizeArray(arrayIndex); } System.arraycopy(c, 0, _array, oldArrayIndex, l); _arrayIndex = arrayIndex; return oldArrayIndex; } protected final void resize() { if (_size == _maximumCapacity) { throw new ValueArrayResourceException(CommonResourceBundle.getInstance().getString("message.arrayMaxCapacity")); } int newSize = _size * 3 / 2 + 1; if (newSize > _maximumCapacity) { newSize = _maximumCapacity; } final int[] offset = new int[newSize]; System.arraycopy(_offset, 0, offset, 0, _size); _offset = offset; final int[] length = new int[newSize]; System.arraycopy(_length, 0, length, 0, _size); _length = length; } protected final void resizeArray(int requestedSize) { if (_arrayIndex == _maximumCharacterSize) { throw new ValueArrayResourceException(CommonResourceBundle.getInstance().getString("message.maxNumberOfCharacters")); } int newSize = requestedSize * 3 / 2 + 1; if (newSize > _maximumCharacterSize) { newSize = _maximumCharacterSize; } final char[] array = new char[newSize]; System.arraycopy(_array, 0, array, 0, _arrayIndex); _array = array; } }
code/fastinfoset/src/main/java/com/sun/xml/fastinfoset/util/ContiguousCharArrayArray.java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright (c) 2011 Oracle and/or its affiliates. All rights reserved. * * Oracle licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sun.xml.fastinfoset.util; import com.sun.xml.fastinfoset.CommonResourceBundle; public class ContiguousCharArrayArray extends ValueArray { public static final int INITIAL_CHARACTER_SIZE = 512; public static final int MAXIMUM_CHARACTER_SIZE = Integer.MAX_VALUE; protected int _maximumCharacterSize; public int[] _offset; public int[] _length; public char[] _array; public int _arrayIndex; public int _readOnlyArrayIndex; private String[] _cachedStrings; public int _cachedIndex; private ContiguousCharArrayArray _readOnlyArray; public ContiguousCharArrayArray(int initialCapacity, int maximumCapacity, int initialCharacterSize, int maximumCharacterSize) { _offset = new int[initialCapacity]; _length = new int[initialCapacity]; _array = new char[initialCharacterSize]; _maximumCapacity = maximumCapacity; _maximumCharacterSize = maximumCharacterSize; } public ContiguousCharArrayArray() { this(DEFAULT_CAPACITY, MAXIMUM_CAPACITY, INITIAL_CHARACTER_SIZE, MAXIMUM_CHARACTER_SIZE); } public final void clear() { _arrayIndex = _readOnlyArrayIndex; _size = _readOnlyArraySize; if (_cachedStrings != null) { for (int i = _readOnlyArraySize; i < _cachedStrings.length; i++) { _cachedStrings[i] = null; } } } public final int getArrayIndex() { return _arrayIndex; } public final void setReadOnlyArray(ValueArray readOnlyArray, boolean clear) { if (!(readOnlyArray instanceof ContiguousCharArrayArray)) { throw new IllegalArgumentException(CommonResourceBundle.getInstance().getString("message.illegalClass", new Object[]{readOnlyArray})); } setReadOnlyArray((ContiguousCharArrayArray)readOnlyArray, clear); } public final void setReadOnlyArray(ContiguousCharArrayArray readOnlyArray, boolean clear) { if (readOnlyArray != null) { _readOnlyArray = readOnlyArray; _readOnlyArraySize = readOnlyArray.getSize(); _readOnlyArrayIndex = readOnlyArray.getArrayIndex(); if (clear) { clear(); } _array = getCompleteCharArray(); _offset = getCompleteOffsetArray(); _length = getCompleteLengthArray(); _size = _readOnlyArraySize; } } public final char[] getCompleteCharArray() { if (_readOnlyArray == null) { return _array; } else { final char[] ra = _readOnlyArray.getCompleteCharArray(); final char[] a = new char[_readOnlyArrayIndex + _array.length]; System.arraycopy(ra, 0, a, 0, _readOnlyArrayIndex); return a; } } public final int[] getCompleteOffsetArray() { if (_readOnlyArray == null) { return _offset; } else { final int[] ra = _readOnlyArray.getCompleteOffsetArray(); final int[] a = new int[_readOnlyArraySize + _offset.length]; System.arraycopy(ra, 0, a, 0, _readOnlyArraySize); return a; } } public final int[] getCompleteLengthArray() { if (_readOnlyArray == null) { return _length; } else { final int[] ra = _readOnlyArray.getCompleteLengthArray(); final int[] a = new int[_readOnlyArraySize + _length.length]; System.arraycopy(ra, 0, a, 0, _readOnlyArraySize); return a; } } public final String getString(int i) { if (_cachedStrings != null && i < _cachedStrings.length) { final String s = _cachedStrings[i]; return (s != null) ? s : (_cachedStrings[i] = new String(_array, _offset[i], _length[i])); } final String[] newCachedStrings = new String[_offset.length]; if (_cachedStrings != null && i >= _cachedStrings.length) { System.arraycopy(_cachedStrings, 0, newCachedStrings, 0, _cachedStrings.length); } _cachedStrings = newCachedStrings; return _cachedStrings[i] = new String(_array, _offset[i], _length[i]); } public final void ensureSize(int l) { if (_arrayIndex + l >= _array.length) { resizeArray(_arrayIndex + l); } } public final void add(int l) { if (_size == _offset.length) { resize(); } _cachedIndex = _size; _offset[_size] = _arrayIndex; _length[_size++] = l; _arrayIndex += l; } public final int add(char[] c, int l) { if (_size == _offset.length) { resize(); } final int oldArrayIndex = _arrayIndex; final int arrayIndex = oldArrayIndex + l; _cachedIndex = _size; _offset[_size] = oldArrayIndex; _length[_size++] = l; if (arrayIndex >= _array.length) { resizeArray(arrayIndex); } System.arraycopy(c, 0, _array, oldArrayIndex, l); _arrayIndex = arrayIndex; return oldArrayIndex; } protected final void resize() { if (_size == _maximumCapacity) { throw new ValueArrayResourceException(CommonResourceBundle.getInstance().getString("message.arrayMaxCapacity")); } int newSize = _size * 3 / 2 + 1; if (newSize > _maximumCapacity) { newSize = _maximumCapacity; } final int[] offset = new int[newSize]; System.arraycopy(_offset, 0, offset, 0, _size); _offset = offset; final int[] length = new int[newSize]; System.arraycopy(_length, 0, length, 0, _size); _length = length; } protected final void resizeArray(int requestedSize) { if (_arrayIndex == _maximumCharacterSize) { throw new ValueArrayResourceException(CommonResourceBundle.getInstance().getString("message.maxNumberOfCharacters")); } int newSize = requestedSize * 3 / 2 + 1; if (newSize > _maximumCharacterSize) { newSize = _maximumCharacterSize; } final char[] array = new char[newSize]; System.arraycopy(_array, 0, array, 0, _arrayIndex); _array = array; } }
fix issue #35 http://java.net/jira/browse/FI-35 "Round trip failure with external vocab"
code/fastinfoset/src/main/java/com/sun/xml/fastinfoset/util/ContiguousCharArrayArray.java
fix issue #35 http://java.net/jira/browse/FI-35 "Round trip failure with external vocab"
Java
apache-2.0
bf61da3591224c1ecfebe83f50fb489841ba2a18
0
Unicon/cas-addons
package net.unicon.cas.addons.web.flow; import net.unicon.cas.addons.serviceregistry.RegisteredServiceWithAttributes; import org.jasig.cas.authentication.principal.Service; import org.jasig.cas.services.RegisteredService; import org.jasig.cas.services.ServicesManager; import org.jasig.cas.services.UnauthorizedServiceException; import org.jasig.cas.web.support.WebUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.webflow.action.AbstractAction; import org.springframework.webflow.execution.Event; import org.springframework.webflow.execution.RequestContext; import org.springframework.webflow.test.MockRequestContext; import javax.validation.constraints.NotNull; /** * Performs a basic check if an authentication request for a provided service is authorized to proceed * based on the registered services registry configuration (or lack thereof). * <p/> * Adds an additional support for a custom <i>unauthorizedUrl</i> attribute in case of a registered service is * not enabled. * * @author Dmitriy Kopylenko * @author Unicon, inc. * @since 1.0.2 */ public final class ServiceAuthorizationCheckWithCustomView extends AbstractAction { @NotNull private final ServicesManager servicesManager; private final Logger logger = LoggerFactory.getLogger(this.getClass()); public ServiceAuthorizationCheckWithCustomView(final ServicesManager servicesManager) { this.servicesManager = servicesManager; } @Override protected Event doExecute(final RequestContext context) throws Exception { final Service service = WebUtils.getService(context); //No service == plain /login request. Return success indicating transition to the login form if (service == null) { return success(); } final RegisteredService registeredService = this.servicesManager.findServiceBy(service); if (registeredService == null) { logger.warn("Unauthorized Service Access for Service: [ {} ] - service is not defined in the service registry.", service.getId()); throw new UnauthorizedServiceException(); } else if (!registeredService.isEnabled()) { logger.warn("Unauthorized Service Access for Service: [ {} ] - service is not enabled in the service registry.", service.getId()); if (registeredService instanceof RegisteredServiceWithAttributes) { String unauthorizedUrl = (String) RegisteredServiceWithAttributes.class.cast(registeredService).getExtraAttributes().get("unauthorizedUrl"); if (unauthorizedUrl != null) { context.getRequestScope().put("unauthorizedUrl", unauthorizedUrl); return no(); } } throw new UnauthorizedServiceException(); } return success(); } }
src/main/java/net/unicon/cas/addons/web/flow/ServiceAuthorizationCheckWithCustomView.java
package net.unicon.cas.addons.web.flow; import net.unicon.cas.addons.serviceregistry.RegisteredServiceWithAttributes; import org.jasig.cas.authentication.principal.Service; import org.jasig.cas.services.RegisteredService; import org.jasig.cas.services.ServicesManager; import org.jasig.cas.services.UnauthorizedServiceException; import org.jasig.cas.web.support.WebUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.webflow.action.AbstractAction; import org.springframework.webflow.execution.Event; import org.springframework.webflow.execution.RequestContext; import org.springframework.webflow.test.MockRequestContext; import javax.validation.constraints.NotNull; /** * Performs a basic check if an authentication request for a provided service is authorized to proceed * based on the registered services registry configuration (or lack thereof). * * Adds an additional support for a custom <i>unauthorizedUrl</i> attribute in case of a registered service is * not enabled. * * @author Dmitriy Kopylenko * @author Unicon, inc. * @since 1.0.2 */ public final class ServiceAuthorizationCheckWithCustomView extends AbstractAction { @NotNull private final ServicesManager servicesManager; private final Logger logger = LoggerFactory.getLogger(this.getClass()); public ServiceAuthorizationCheckWithCustomView(final ServicesManager servicesManager) { this.servicesManager = servicesManager; } @Override protected Event doExecute(final RequestContext context) throws Exception { final Service service = WebUtils.getService(context); //No service == plain /login request. Return success indicating transition to the login form if (service == null) { return success(); } final RegisteredService registeredService = this.servicesManager.findServiceBy(service); if (registeredService == null) { logger.warn("Unauthorized Service Access for Service: [ {} ] - service is not defined in the service registry.", service.getId()); throw new UnauthorizedServiceException(); } else if (!registeredService.isEnabled()) { logger.warn("Unauthorized Service Access for Service: [ {} ] - service is not enabled in the service registry.", service.getId()); if (registeredService instanceof RegisteredServiceWithAttributes) { String unauthorizedUrl = (String) ((RegisteredServiceWithAttributes) registeredService).getExtraAttributes().get("unauthorizedUrl"); if (unauthorizedUrl != null) { context.getRequestScope().put("unauthorizedUrl", unauthorizedUrl); return no(); } } throw new UnauthorizedServiceException(); } return success(); } }
Internal polishing refactoring
src/main/java/net/unicon/cas/addons/web/flow/ServiceAuthorizationCheckWithCustomView.java
Internal polishing refactoring
Java
apache-2.0
1f37f02666c3fc9c93847e108a13676e8e2f5a21
0
code4craft/ibatis-plugin
package org.intellij.ibatis.inspections; import Zql.ZQuery; import Zql.ZSelectItem; import Zql.ZStatement; import Zql.ZqlParser; import com.intellij.lang.annotation.HighlightSeverity; import com.intellij.util.xml.highlighting.DomElementAnnotationHolder; import org.intellij.ibatis.IbatisSqlMapModel; import org.intellij.ibatis.dom.sqlMap.Result; import org.intellij.ibatis.dom.sqlMap.ResultMap; import org.intellij.ibatis.dom.sqlMap.Select; import org.intellij.ibatis.dom.sqlMap.SqlMap; import org.intellij.ibatis.util.IbatisBundle; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import java.io.ByteArrayInputStream; import java.util.HashMap; import java.util.Map; import java.util.Vector; /** * result map in select inspection */ public class ResultMapInSelectInspection extends SqlMapInspection { @Nls @NotNull public String getDisplayName() { return IbatisBundle.message("ibatis.sqlmap.inspection.resulmapinselect.name"); } @NonNls @NotNull public String getShortName() { return IbatisBundle.message("ibatis.sqlmap.inspection.resulmapinselect.id"); } protected void checkSelect(IbatisSqlMapModel sqlMapModel, SqlMap sqlMap, Select select, DomElementAnnotationHolder holder) { ResultMap resultMap = select.getResultMap().getValue(); if (resultMap != null) { String sql = select.getSQL() + ";"; sql = sql.toUpperCase(); if (sql.contains(" FROM ") && sql.contains("SELECT")) { try { sql = sql.replaceAll("\\#[\\w\\.]*\\#", "''"); sql = sql.replaceAll("\\$[\\w\\.]*\\$", "temp1"); Map<String, String> allSelectItems = new HashMap<String, String>(); ZqlParser parser = new ZqlParser(new ByteArrayInputStream(sql.getBytes())); ZStatement statement = parser.readStatement(); if (statement != null && statement instanceof ZQuery) { ZQuery query = (ZQuery) statement; Vector selectedItems = query.getSelect(); for (Object selectedItem : selectedItems) { if (selectedItem instanceof ZSelectItem) { ZSelectItem zSelectItem = (ZSelectItem) selectedItem; String alias = zSelectItem.getAlias(); if (alias == null) alias = zSelectItem.getColumn(); if (alias.equals("*")) return; allSelectItems.put(alias.toUpperCase(), zSelectItem.getColumn()); } } } for (Result result : resultMap.getAllResults()) { String columnName = result.getColumn().getValue(); if (columnName == null) columnName = result.getProperty().getValue(); if (columnName != null) { if (allSelectItems.get(columnName.toUpperCase()) == null) { holder.createProblem(select, HighlightSeverity.WARNING, IbatisBundle.message("ibatis.sqlmap.inspection.resulmapinselect.error", columnName)); break; } } } } catch (Throwable e) { e.printStackTrace(); } } } } }
src/org/intellij/ibatis/inspections/ResultMapInSelectInspection.java
package org.intellij.ibatis.inspections; import Zql.ZQuery; import Zql.ZSelectItem; import Zql.ZStatement; import Zql.ZqlParser; import com.intellij.lang.annotation.HighlightSeverity; import com.intellij.util.xml.highlighting.DomElementAnnotationHolder; import org.intellij.ibatis.IbatisSqlMapModel; import org.intellij.ibatis.dom.sqlMap.Result; import org.intellij.ibatis.dom.sqlMap.ResultMap; import org.intellij.ibatis.dom.sqlMap.Select; import org.intellij.ibatis.dom.sqlMap.SqlMap; import org.intellij.ibatis.util.IbatisBundle; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import java.io.ByteArrayInputStream; import java.util.HashMap; import java.util.Map; import java.util.Vector; /** * result map in select inspection */ public class ResultMapInSelectInspection extends SqlMapInspection { @Nls @NotNull public String getDisplayName() { return IbatisBundle.message("ibatis.sqlmap.inspection.resulmapinselect.name"); } @NonNls @NotNull public String getShortName() { return IbatisBundle.message("ibatis.sqlmap.inspection.resulmapinselect.id"); } protected void checkSelect(IbatisSqlMapModel sqlMapModel, SqlMap sqlMap, Select select, DomElementAnnotationHolder holder) { ResultMap resultMap = select.getResultMap().getValue(); if (resultMap != null) { String sql = select.getSQL() + ";"; sql = sql.toUpperCase(); if (sql.contains(" FROM ") && sql.contains("SELECT")) { try { sql = sql.replaceAll("\\#[\\w\\.]*\\#", "''"); sql = sql.replaceAll("\\$[\\w\\.]*\\$", "temp1"); Map<String, String> allSelectItems = new HashMap<String, String>(); ZqlParser parser = new ZqlParser(new ByteArrayInputStream(sql.getBytes())); ZStatement statement = parser.readStatement(); if (statement != null && statement instanceof ZQuery) { ZQuery query = (ZQuery) statement; Vector selectedItems = query.getSelect(); for (Object selectedItem : selectedItems) { if (selectedItem instanceof ZSelectItem) { ZSelectItem zSelectItem = (ZSelectItem) selectedItem; String alias = zSelectItem.getAlias(); if (alias == null) alias = zSelectItem.getColumn(); if (alias.equals("*")) return; allSelectItems.put(alias.toUpperCase(), zSelectItem.getColumn()); } } } for (Result result : resultMap.getAllResults()) { String columnName = result.getColumn().getValue(); if (columnName == null) columnName = result.getProperty().getValue(); if (columnName != null) { if (allSelectItems.get(columnName.toUpperCase()) == null) { holder.createProblem(select, HighlightSeverity.WARNING, IbatisBundle.message("ibatis.sqlmap.inspection.resulmapinselect.error", columnName)); break; } } } } catch (Throwable e) { } } } } }
minor update git-svn-id: a3757b7b28cb5f166982e3e590f726e1a71ef014@377 a27988d2-9830-0410-8773-31d6671a21de
src/org/intellij/ibatis/inspections/ResultMapInSelectInspection.java
minor update
Java
apache-2.0
15bee91fa70880df59411913214964b5a448a104
0
aalmiray/Json-lib,aalmiray/Json-lib
/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import java.util.Map; import junit.framework.TestCase; import net.sf.ezmorph.object.MapToDateMorpher; import net.sf.json.sample.ArrayBean; import net.sf.json.sample.BeanA; import net.sf.json.sample.BeanA1763699; import net.sf.json.sample.BeanB1763699; import net.sf.json.sample.BeanC; import net.sf.json.sample.ChildBean; import net.sf.json.sample.DateBean; import net.sf.json.sample.FieldBean; import net.sf.json.sample.IdBean; import net.sf.json.sample.InterfaceBean; import net.sf.json.sample.JSONTestBean; import net.sf.json.sample.ListingBean; import net.sf.json.sample.MappedBean; import net.sf.json.sample.Media; import net.sf.json.sample.MediaBean; import net.sf.json.sample.MediaList; import net.sf.json.sample.MediaListBean; import net.sf.json.sample.NumberArrayBean; import net.sf.json.sample.PackageProtectedBean; import net.sf.json.sample.ParentBean; import net.sf.json.sample.Player; import net.sf.json.sample.PlayerList; import net.sf.json.sample.PrimitiveBean; import net.sf.json.sample.PrivateConstructorBean; import net.sf.json.sample.UnstandardBean; import net.sf.json.sample.UnstandardBeanInstanceStrategy; import net.sf.json.util.JSONUtils; import net.sf.json.util.JavaIdentifierTransformer; import net.sf.json.util.JsonEventListener; import org.apache.commons.beanutils.DynaBean; import org.apache.commons.beanutils.PropertyUtils; /** * @author Andres Almiray <aalmiray@users.sourceforge.net> */ public class TestUserSubmitted extends TestCase { public static void main( String[] args ) { junit.textui.TestRunner.run( TestUserSubmitted.class ); } private JsonConfig jsonConfig; public TestUserSubmitted( String name ) { super( name ); } public void testPatch_2929940() { Map classMap = new HashMap(); classMap.put("attributes", Long.class); ListingBean original = new ListingBean(); original.addAttribute(Long.valueOf(12)); JSONObject jsonObject = JSONObject.fromObject(JSONObject.fromObject(original).toString()); // JSON config JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setRootClass(ListingBean.class); jsonConfig.setClassMap(classMap); // toBean ListingBean bean = (ListingBean)JSONObject.toBean(jsonObject, jsonConfig); assertTrue(bean.getAttributes().get(0) instanceof Long); } public void testBug_1635890() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { // submited by arco.vandenheuvel[at]points[dot].com String TEST_JSON_STRING = "{\"rateType\":\"HOTRATE\",\"rateBreakdown\":{\"rate\":[{\"amount\":\"109.74\",\"date\":{\"month\":\"01\",\"day\":\"15\",\"year\":\"2007\"}},{\"amount\":\"109.74\",\"date\":{\"month\":\"1\",\"day\":\"16\",\"year\":\"2007\"}}]}}"; DynaBean jsonBean = (DynaBean) JSONObject.toBean( JSONObject.fromObject( TEST_JSON_STRING ) ); assertNotNull( jsonBean ); assertEquals( "wrong rate Type", "HOTRATE", jsonBean.get( "rateType" ) ); assertNotNull( "null rate breakdown", jsonBean.get( "rateBreakdown" ) ); DynaBean jsonRateBreakdownBean = (DynaBean) jsonBean.get( "rateBreakdown" ); assertNotNull( "null rate breakdown ", jsonRateBreakdownBean ); Object jsonRateBean = jsonRateBreakdownBean.get( "rate" ); assertNotNull( "null rate ", jsonRateBean ); assertTrue( "list", jsonRateBean instanceof ArrayList ); assertNotNull( "null rate ", jsonRateBreakdownBean.get( "rate", 0 ) ); } public void testBug_1650535_builders() { // submitted by Paul Field <paulfield[at]users[dot]sourceforge[dot]net> String json = "{\"obj\":\"{}\",\"array\":\"[]\"}"; JSONObject object = JSONObject.fromObject( json ); assertNotNull( object ); assertTrue( object.has( "obj" ) ); assertTrue( object.has( "array" ) ); Object obj = object.get( "obj" ); assertTrue( obj instanceof String ); Object array = object.get( "array" ); assertTrue( array instanceof String ); json = "{'obj':'{}','array':'[]'}"; object = JSONObject.fromObject( json ); assertNotNull( object ); assertTrue( object.has( "obj" ) ); assertTrue( object.has( "array" ) ); obj = object.get( "obj" ); assertTrue( obj instanceof String ); array = object.get( "array" ); assertTrue( array instanceof String ); json = "[\"{}\",\"[]\"]"; JSONArray jarray = JSONArray.fromObject( json ); assertNotNull( jarray ); obj = jarray.get( 0 ); assertTrue( obj instanceof String ); array = jarray.get( 1 ); assertTrue( array instanceof String ); json = "['{}','[]']"; jarray = JSONArray.fromObject( json ); assertNotNull( jarray ); obj = jarray.get( 0 ); assertTrue( obj instanceof String ); array = jarray.get( 1 ); assertTrue( array instanceof String ); // submitted by Elizabeth Keogh <ekeogh[at]thoughtworks[dot]com> Map map = new HashMap(); map.put( "address", "1 The flats [Upper floor]" ); map.put( "phoneNumber", "[+44] 582 401923" ); map.put( "info1", "[Likes coffee]" ); map.put( "info2", "[Likes coffee] [Likes tea]" ); map.put( "info3", "[Likes coffee [but not with sugar]]" ); object = JSONObject.fromObject( map ); assertNotNull( object ); assertTrue( object.has( "address" ) ); assertTrue( object.has( "phoneNumber" ) ); assertTrue( object.has( "info1" ) ); assertTrue( object.has( "info2" ) ); assertTrue( object.has( "info3" ) ); assertTrue( object.get( "address" ) instanceof String ); assertTrue( object.get( "phoneNumber" ) instanceof String ); assertTrue( object.get( "info1" ) instanceof String ); assertTrue( object.get( "info2" ) instanceof String ); assertTrue( object.get( "info3" ) instanceof String ); } /* I consider this behavior of "oh I added string but it's not really a string" very evil, as there's no way to add a String that really looks like "{}" public void testBug_1650535_setters() { JSONObject object = new JSONObject(); object.element( "obj", "{}" ); object.element( "notobj", "{string}" ); object.element( "array", "[]" ); object.element( "notarray", "[string]" ); assertTrue( object.get( "obj" ) instanceof JSONObject ); assertTrue( object.get( "array" ) instanceof JSONArray ); assertTrue( object.get( "notobj" ) instanceof String ); assertTrue( object.get( "notarray" ) instanceof String ); object.element( "str", "json,json" ); assertTrue( object.get( "str" ) instanceof String ); } */ public void testBug_1753528_ArrayStringLiteralToString() { // submited bysckimos[at]gmail[dot]com BeanA bean = new BeanA(); bean.setString( "[1234]" ); JSONObject jsonObject = JSONObject.fromObject( bean ); assertEquals( "[1234]", jsonObject.get( "string" ) ); bean.setString( "{'key':'1234'}" ); jsonObject = JSONObject.fromObject( bean ); assertEquals( "{'key':'1234'}", jsonObject.get( "string" ) ); } public void testBug_1763699_toBean() { JSONObject json = JSONObject.fromObject( "{'bbeans':[{'str':'test'}]}" ); BeanA1763699 bean = (BeanA1763699) JSONObject.toBean( json, BeanA1763699.class ); assertNotNull( bean ); BeanB1763699[] bbeans = bean.getBbeans(); assertNotNull( bbeans ); assertEquals( 1, bbeans.length ); assertEquals( "test", bbeans[0].getStr() ); } public void testBug_1764768_toBean() { JSONObject json = JSONObject.fromObject( "{'beanA':''}" ); Map classMap = new HashMap(); classMap.put( "beanA", BeanA.class ); BeanC bean = (BeanC) JSONObject.toBean( json, BeanC.class, classMap ); assertNotNull( bean ); assertNotNull( bean.getBeanA() ); assertEquals( new BeanA(), bean.getBeanA() ); } public void testBug_1769559_array_conversion() { JSONObject jsonObject = new JSONObject().element( "beans", new JSONArray().element( "{}" ) .element( "{'bool':false,'integer':216,'string':'JsOn'}" ) ); ArrayBean bean = (ArrayBean) JSONObject.toBean( jsonObject, ArrayBean.class ); assertNotNull( bean ); // no error should happen here JSONArray jsonArray = jsonObject.getJSONArray( "beans" ); BeanA[] beans = (BeanA[]) JSONArray.toArray( jsonArray, BeanA.class ); assertNotNull( beans ); assertEquals( 2, beans.length ); assertEquals( new BeanA(), beans[0] ); assertEquals( new BeanA( false, 216, "JsOn" ), beans[1] ); } public void testBug_1769578_array_conversion() { JSONObject jsonObject = JSONObject .fromObject( "{'media':[{'title':'Giggles'},{'title':'Dreamland?'}]}" ); Map classMap = new HashMap(); classMap.put( "media", MediaBean.class ); MediaListBean bean = (MediaListBean) JSONObject.toBean( jsonObject, MediaListBean.class, classMap ); assertNotNull( bean ); assertNotNull( bean.getMedia() ); assertTrue( bean.getMedia().getClass().isArray() ); Object[] media = (Object[]) bean.getMedia(); assertEquals( 2, media.length ); Object mediaItem1 = media[0]; assertTrue( mediaItem1 instanceof MediaBean ); assertEquals( "Giggles", ((MediaBean) mediaItem1).getTitle() ); } public void testBug_1812682() { int[] numbers = new int[] { 1, 2, 3, 4, 5 }; JSONObject json = new JSONObject().element( "bytes", numbers ).element( "shorts", numbers ) .element( "ints", numbers ).element( "longs", numbers ).element( "floats", numbers ) .element( "doubles", numbers ); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setRootClass( NumberArrayBean.class ); NumberArrayBean bean = (NumberArrayBean) JSONObject.toBean( json, jsonConfig ); assertNotNull( bean ); } public void testBug_1813301() { List list = new ArrayList(); list.add( "1" ); list.add( "2" ); list.add( "3" ); JSONObject jsonObject = new JSONObject().element( "name", "JSON" ).element( "list", list ); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setRootClass( MappedBean.class ); MappedBean bean = (MappedBean) JSONObject.toBean( jsonObject, jsonConfig ); assertNotNull( bean ); assertEquals( "JSON", bean.getName() ); Assertions.assertEquals( list, bean.getList() ); } public void testBug_1875600_1() { JSONArray jArray = JSONArray.fromObject( "[]" ); int[] iArray = (int[]) JSONArray.toArray( jArray, int.class ); JSONArray actual = JSONArray.fromObject( iArray ); Assertions.assertEquals( new JSONArray(), actual ); } public void testBug_1875600_2() { JSONArray jArray = JSONArray.fromObject( "[ [] ]" ); int[][] iArray = (int[][]) JSONArray.toArray( jArray, int.class ); JSONArray actual = JSONArray.fromObject( iArray ); Assertions.assertEquals( new JSONArray().element( new JSONArray() ), actual ); } public void testConstructor_Object__nullArray() { // submitted by Matt Small String[] strarr = null; JSONObject jsonObject = JSONObject.fromObject( strarr, jsonConfig ); assertTrue( jsonObject.isNullObject() ); } public void testConstructor_Object_EnclosedArray() { // submitted by Matt Small PrimitiveBean bean = new PrimitiveBean(); bean.setOarray( new String[] { "hi", "bye" } ); JSONObject jsonObject = JSONObject.fromObject( bean, jsonConfig ); assertFalse( jsonObject.isNullObject() ); assertFalse( jsonObject.getJSONArray( "oarray" ).isEmpty() ); } public void testConstructor_Object_EnclosedNullArray() { // submitted by Matt Small PrimitiveBean bean = new PrimitiveBean(); bean.setOarray( null ); JSONObject jsonObject = JSONObject.fromObject( bean, jsonConfig ); assertFalse( jsonObject.isNullObject() ); assertTrue( jsonObject.getJSONArray( "oarray" ).isEmpty() ); } public void testConstructorAndToBean_Object_RoundTrip_EnclosedNullArray() { PrimitiveBean bean = new PrimitiveBean(); bean.setOarray( null ); JSONObject jsonObject = JSONObject.fromObject( bean, jsonConfig ); PrimitiveBean bean2 = (PrimitiveBean) JSONObject.toBean( jsonObject, PrimitiveBean.class ); assertNotNull( bean2 ); // bean.oarray == null // jsonObject.oarray == [] therefore // bean2.oarray != null assertEquals( 0, bean2.getOarray().length ); } public void testDynaBeanAttributeMap() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { // submited by arco.vandenheuvel[at]points[dot].com JSONObject jsonObject = JSONObject.fromObject( new JSONTestBean() ); String jsonString = jsonObject.toString(); DynaBean jsonBean = (DynaBean) JSONObject.toBean( JSONObject.fromObject( jsonString ) ); assertNotNull( jsonBean ); assertEquals( "wrong inventoryID", "", jsonBean.get( "inventoryID" ) ); } public void testFR_1768960_array_conversion() { // 2 items JSONObject jsonObject = JSONObject .fromObject( "{'media2':[{'title':'Giggles'},{'title':'Dreamland?'}]}" ); Map classMap = new HashMap(); classMap.put( "media2", MediaBean.class ); MediaListBean bean = (MediaListBean) JSONObject.toBean( jsonObject, MediaListBean.class, classMap ); assertNotNull( bean ); assertNotNull( bean.getMedia2() ); List media2 = bean.getMedia2(); assertEquals( 2, media2.size() ); Object mediaItem1 = media2.get( 0 ); assertTrue( mediaItem1 instanceof MediaBean ); assertEquals( "Giggles", ((MediaBean) mediaItem1).getTitle() ); // 1 // item jsonObject = JSONObject.fromObject( "{'media2':[{'title':'Giggles'}]}" ); bean = (MediaListBean) JSONObject.toBean( jsonObject, MediaListBean.class, classMap ); assertNotNull( bean ); assertNotNull( bean.getMedia2() ); media2 = bean.getMedia2(); assertEquals( 1, media2.size() ); mediaItem1 = media2.get( 0 ); assertTrue( mediaItem1 instanceof MediaBean ); assertEquals( "Giggles", ((MediaBean) mediaItem1).getTitle() ); } public void testFR_1808430_newBeanInstance() { JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setNewBeanInstanceStrategy( new UnstandardBeanInstanceStrategy() ); JSONObject jsonObject = new JSONObject(); jsonObject.element( "id", 1 ); jsonConfig.setRootClass( UnstandardBean.class ); UnstandardBean bean = (UnstandardBean) JSONObject.toBean( jsonObject, jsonConfig ); assertNotNull( bean ); assertEquals( UnstandardBean.class, bean.getClass() ); assertEquals( 1, bean.getId() ); } public void testFR_1832047_packageProtectedBean() { JSONObject jsonObject = new JSONObject().element( "value", "42" ); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setRootClass( PackageProtectedBean.class ); PackageProtectedBean bean = (PackageProtectedBean) JSONObject.toBean( jsonObject, jsonConfig ); assertNotNull( bean ); assertEquals( 42, bean.getValue() ); } public void testFR_1832047_privateProtectedBean() { JSONObject jsonObject = new JSONObject().element( "value", "42" ); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setRootClass( PrivateConstructorBean.class ); PrivateConstructorBean bean = (PrivateConstructorBean) JSONObject.toBean( jsonObject, jsonConfig ); assertNotNull( bean ); assertEquals( 42, bean.getValue() ); } public void testFR_1858073_preserveInsertionOrder() { JSONObject jsonObject = new JSONObject().element( "one", "one" ).element( "two", "two" ) .element( "three", "three" ); JSONArray actual = jsonObject.names(); JSONArray expected = new JSONArray().element( "one" ).element( "two" ).element( "three" ); Assertions.assertEquals( expected, actual ); } public void testFromObjectCurliesOnString() { String json = "{'prop':'{value}'}"; JSONObject jsonObject = JSONObject.fromObject( json ); assertNotNull( jsonObject ); assertEquals( 1, jsonObject.size() ); assertEquals( "{value}", jsonObject.get( "prop" ) ); json = "{'prop':'{{value}}'}"; jsonObject = JSONObject.fromObject( json ); assertNotNull( jsonObject ); assertEquals( 1, jsonObject.size() ); assertEquals( "{{value}}", jsonObject.get( "prop" ) ); json = "{'prop':'{{{value}}}'}"; jsonObject = JSONObject.fromObject( json ); assertNotNull( jsonObject ); assertEquals( 1, jsonObject.size() ); assertEquals( "{{{value}}}", jsonObject.get( "prop" ) ); } public void testHandleJettisonEmptyElement() { JSONObject jsonObject = JSONObject.fromObject( "{'beanA':'','beanB':''}" ); jsonConfig.setHandleJettisonEmptyElement( true ); jsonConfig.setRootClass( BeanC.class ); BeanC bean = (BeanC) JSONObject.toBean( jsonObject, jsonConfig ); assertNotNull( bean ); assertNull( bean.getBeanA() ); assertNull( bean.getBeanB() ); } public void testHandleJettisonSingleElementArray() { JSONObject jsonObject = JSONObject.fromObject( "{'media2':{'title':'Giggles'}}" ); Map classMap = new HashMap(); classMap.put( "media2", MediaBean.class ); jsonConfig.setHandleJettisonSingleElementArray( true ); jsonConfig.setRootClass( MediaListBean.class ); jsonConfig.setClassMap( classMap ); MediaListBean bean = (MediaListBean) JSONObject.toBean( jsonObject, jsonConfig ); assertNotNull( bean ); assertNotNull( bean.getMedia2() ); List media2 = bean.getMedia2(); assertEquals( 1, media2.size() ); Object mediaItem1 = media2.get( 0 ); assertTrue( mediaItem1 instanceof MediaBean ); assertEquals( "Giggles", ((MediaBean) mediaItem1).getTitle() ); } public void testHandleJettisonSingleElementArray2() { JSONObject jsonObject = JSONObject.fromObject( "{'mediaList':{'media':{'title':'Giggles'}}}" ); Map classMap = new HashMap(); classMap.put( "media", Media.class ); classMap.put( "mediaList", MediaList.class ); jsonConfig.setHandleJettisonSingleElementArray( true ); jsonConfig.setRootClass( Player.class ); jsonConfig.setClassMap( classMap ); Player bean = (Player) JSONObject.toBean( jsonObject, jsonConfig ); assertNotNull( bean ); assertNotNull( bean.getMediaList() ); MediaList mediaList = bean.getMediaList(); assertNotNull( mediaList.getMedia() ); ArrayList medias = mediaList.getMedia(); assertEquals( "Giggles", ((Media) medias.get( 0 )).getTitle() ); } public void testHandleJettisonSingleElementArray3() { JSONObject jsonObject = JSONObject .fromObject( "{'player':{'mediaList':{'media':{'title':'Giggles'}}}}" ); Map classMap = new HashMap(); classMap.put( "media", Media.class ); classMap.put( "mediaList", MediaList.class ); classMap.put( "player", Player.class ); jsonConfig.setHandleJettisonSingleElementArray( true ); jsonConfig.setRootClass( PlayerList.class ); jsonConfig.setClassMap( classMap ); PlayerList bean = (PlayerList) JSONObject.toBean( jsonObject, jsonConfig ); assertNotNull( bean ); assertNotNull( bean.getPlayer() ); ArrayList players = bean.getPlayer(); assertNotNull( players ); assertNotNull( players.get( 0 ) ); Player player = (Player) players.get( 0 ); assertNotNull( player.getMediaList() ); MediaList mediaList = player.getMediaList(); assertNotNull( mediaList.getMedia() ); ArrayList medias = mediaList.getMedia(); assertEquals( "Giggles", ((Media) medias.get( 0 )).getTitle() ); } public void testJsonWithNamespaceToDynaBean() throws Exception { // submited by Girish Ipadi jsonConfig.setJavaIdentifierTransformer( JavaIdentifierTransformer.NOOP ); String str = "{'version':'1.0'," + "'sid':'AmazonDocStyle', 'svcVersion':'0.1'," + "'oid':'ItemLookup', 'params':[{ 'ns:ItemLookup': {" + "'ns:SubscriptionId':'0525E2PQ81DD7ZTWTK82'," + "'ns:Validate':'False'," + "'ns:Request':{" + "'ns:ItemId':'SDGKJSHDGAJSGL'," + "'ns:IdType':'ASIN'," + "'ns:ResponseGroup':'Large'" + "}," + "'ns:Request':{" + "'ns:ItemId':'XXXXXXXXXX'," + "'ns:IdType':'ASIN'," + "'ns:ResponseGroup':'Large'" + "}" + "}" + "}]" + "} "; JSONObject json = JSONObject.fromObject( str, jsonConfig ); Object bean = JSONObject.toBean( (JSONObject) json ); assertNotNull( bean ); List params = (List) PropertyUtils.getProperty( bean, "params" ); DynaBean param0 = (DynaBean) params.get( 0 ); DynaBean itemLookup = (DynaBean) param0.get( "ns:ItemLookup" ); assertNotNull( itemLookup ); assertEquals( "0525E2PQ81DD7ZTWTK82", itemLookup.get( "ns:SubscriptionId" ) ); } /* No morpher, please - Kohsuke public void testToBeanSimpleToComplexValueTransformation() { // Submitted by Oliver Zyngier JSONObject jsonObject = JSONObject.fromObject( "{'id':null}" ); IdBean idBean = (IdBean) JSONObject.toBean( jsonObject, IdBean.class ); assertNotNull( idBean ); assertEquals( null, idBean.getId() ); jsonObject = JSONObject.fromObject( "{'id':1}" ); idBean = (IdBean) JSONObject.toBean( jsonObject, IdBean.class ); assertNotNull( idBean ); assertNotNull( idBean.getId() ); assertEquals( 0L, idBean.getId().getValue() ); JSONUtils.getMorpherRegistry().registerMorpher( new IdBean.IdMorpher(), true ); jsonObject = JSONObject.fromObject( "{'id':1}" ); idBean = (IdBean) JSONObject.toBean( jsonObject, IdBean.class ); assertNotNull( idBean ); assertEquals( new IdBean.Id( 1L ), idBean.getId() ); } public void testToBeanWithMultipleMorphersForTargetType() { Calendar c = Calendar.getInstance(); c.set( Calendar.YEAR, 2007 ); c.set( Calendar.MONTH, 5 ); c.set( Calendar.DATE, 17 ); c.set( Calendar.HOUR_OF_DAY, 12 ); c.set( Calendar.MINUTE, 13 ); c.set( Calendar.SECOND, 14 ); c.set( Calendar.MILLISECOND, 150 ); Date date = c.getTime(); DateBean bean = new DateBean(); bean.setDate( date ); JSONObject jsonObject = JSONObject.fromObject( bean ); JSONUtils.getMorpherRegistry().registerMorpher( new MapToDateMorpher() ); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setRootClass( DateBean.class ); DateBean actual = (DateBean) JSONObject.toBean( jsonObject, jsonConfig ); Calendar d = Calendar.getInstance(); d.setTime( actual.getDate() ); assertEquals( c.get( Calendar.YEAR ), d.get( Calendar.YEAR ) ); assertEquals( c.get( Calendar.MONTH ), d.get( Calendar.MONTH ) ); assertEquals( c.get( Calendar.DATE ), d.get( Calendar.DATE ) ); assertEquals( c.get( Calendar.HOUR_OF_DAY ), d.get( Calendar.HOUR_OF_DAY ) ); assertEquals( c.get( Calendar.MINUTE ), d.get( Calendar.MINUTE ) ); assertEquals( c.get( Calendar.SECOND ), d.get( Calendar.SECOND ) ); assertEquals( c.get( Calendar.MILLISECOND ), d.get( Calendar.MILLISECOND ) ); } public void testToBeanWithInterfaceField() { JSONObject jsonObject = JSONObject.fromObject( "{runnable:{}}" ); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setRootClass( InterfaceBean.class ); Map classMap = new HashMap(); classMap.put( "runnable", RunnableImpl.class ); jsonConfig.setClassMap( classMap ); InterfaceBean bean = (InterfaceBean) JSONObject.toBean( jsonObject, jsonConfig ); assertNotNull( bean ); assertNotNull( bean.getRunnable() ); assertTrue( bean.getRunnable() instanceof RunnableImpl ); } public void testCycleDetection_withExclusions() { ParentBean parent = new ParentBean(); parent.setChild( new ChildBean() ); // will fail if throws an exception jsonConfig.setExcludes( new String[] { "parent" } ); JSONObject.fromObject( parent, jsonConfig ); } public void testJSONArrayIterator() { JSONArray jsonArray = new JSONArray(); jsonArray.add( "1" ); jsonArray.add( "2" ); jsonArray.add( "3" ); List list = new LinkedList(); list.add( "4" ); list.add( "5" ); list.add( "6" ); jsonArray.add( list ); List newList = new LinkedList(); newList.add( "7" ); newList.add( "8" ); newList.add( "9" ); Assertions.assertEquals( JSONArray.fromObject( "['1','2','3',['4','5','6']]" ), jsonArray ); ListIterator listIterator = jsonArray.listIterator(); listIterator.add( newList ); Assertions.assertEquals( JSONArray.fromObject( "[['7','8','9'],'1','2','3',['4','5','6']]" ), jsonArray ); } public void testJSONArray_badFormattedString() { String badJson = "[{\"a\":\"b\"},"; try { JSONArray.fromObject(badJson); fail("Expecting a syntax error from JSONTokener."); }catch( JSONException jsone ) { assertTrue( jsone.getMessage().startsWith( "Found starting '[' but missing ']' at the end." )); } } public void testJSONObject_badFormattedString() { String badJson = "{\"a\":\"b\"},"; try { JSONObject.fromObject(badJson); fail("Expecting a syntax error from JSONTokener."); }catch( JSONException jsone ) { assertTrue( jsone.getMessage().startsWith( "Found starting '{' but missing '}' at the end." )); } */ public void testQuotedFunctions() { JSONObject json = JSONObject.fromObject( "{'func':\"function(){blah;}\"}" ); assertTrue( json.get( "func" ) instanceof String ); assertEquals( "function(){blah;}", json.get( "func" )); } public void testJsonWithNullKeys() { Map map = new HashMap(); map.put("key", "value"); map.put(null, "value2"); Object[] obj = {map}; try { JSONSerializer.toJSON( obj ); fail( "Should have thrown a ClassCastException" ); } catch( JSONException expected ) { // ok } } public void testJsonWithNullKeys2() { Map map = new HashMap(); map.put("key", "value"); map.put(null, "value2"); try { System.err.println(JSONSerializer.toJSON( map )); fail( "Should have thrown a ClassCastException" ); } catch( JSONException expected ) { // ok } } public void testJSONArray_JavascriptCompliant() { JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setJavascriptCompliant( true ); String json = "[null, undefined]"; JSONArray array = JSONArray.fromObject( json, jsonConfig ); assertNotNull(array); Assertions.assertEquals( JSONNull.getInstance(), array.get(1) ); } public void testJSONArray_JavascriptComplian2t() { JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setJavascriptCompliant( true ); JSONArray array = new JSONArray(); array.element("null", jsonConfig); array.element("undefined", jsonConfig); assertNotNull(array); Assertions.assertEquals( JSONNull.getInstance(), array.get(0) ); Assertions.assertEquals( JSONNull.getInstance(), array.get(1) ); } public void testJSONObject_JavascriptCompliant() { JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setJavascriptCompliant( true ); String json = "{key1: null, key2: undefined}"; JSONObject object = JSONObject.fromObject( json, jsonConfig ); assertNotNull(object); Assertions.assertEquals( JSONNull.getInstance(), object.get("key2") ); } public void testJSONObject_JavascriptCompliant2() { JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setJavascriptCompliant( true ); JSONObject object = new JSONObject(); object.element( "key1", "null", jsonConfig ); object.element( "key2", "undefined", jsonConfig ); assertNotNull(object); Assertions.assertEquals( JSONNull.getInstance(), object.get("key2") ); } public void testJSONObject_fromObject_FieldBean() { JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setIgnorePublicFields( false ); FieldBean bean = new FieldBean(); bean.setValue( 42 ); bean.string = "stringy"; JSONObject jsonObject = JSONObject.fromObject( bean ); assertNotNull( jsonObject ); assertEquals( 42, jsonObject.getInt( "value" )); assertFalse( jsonObject.has( "string" )); jsonObject = JSONObject.fromObject( bean, jsonConfig ); assertNotNull( jsonObject ); assertEquals( 42, jsonObject.getInt( "value" )); assertEquals( "stringy", jsonObject.getString( "string" )); } public void testJSONObject_toBean_FieldBean() { JSONObject jsonObject = new JSONObject(); jsonObject.element( "value", 42 ); jsonObject.element( "string", "stringy" ); FieldBean bean1 = (FieldBean) JSONObject.toBean( jsonObject, FieldBean.class ); assertNotNull( bean1 ); assertEquals( 42, bean1.getValue()); assertNull( bean1.string ); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setIgnorePublicFields( false ); jsonConfig.setRootClass( FieldBean.class ); FieldBean bean2 = (FieldBean) JSONObject.toBean( jsonObject, jsonConfig ); assertNotNull( bean2 ); assertEquals( 42, bean1.getValue()); assertEquals( "stringy", bean2.string ); } public void testBug_2692698() { String input = "[\"{'selectedOperatorIndex':2,'leftSideValue':'report.field9','rightSideValue':'2009-3-1'}\",\"all\"]"; JSON json = JSONArray.fromObject( input ); String output = json.toString(); assertEquals(input, output); } public void testWithoutAnyTroubleTheyMayBeAlreadyDoneByOtherTest() { JsonConfig tConfig = new JsonConfig(); tConfig.enableEventTriggering(); tConfig.addJsonEventListener(new JsonErrorDetector()); // String JSONObject jsonObject = JSONObject.fromObject( "{\"string\":\"aString\"}", tConfig ); assertTrue( "L'objet doit contenir une clef \"string\"", jsonObject.containsKey( "string" ) ); assertNotNull( "Le membre \"string\" doit être une String", jsonObject.optString( "string" ) ); assertEquals( "Le membre \"string\" doit être égal a \"aString\"", "aString", jsonObject.get( "string" ) ); // int jsonObject = JSONObject.fromObject( "{\"integer\":10}", tConfig ); assertTrue( "L'objet doit contenir une clef \"integer\"", jsonObject.containsKey( "integer" ) ); assertEquals( "Le membre \"integer\" doit être égal a 10", 10, jsonObject.optInt( "integer" ) ); // boolean jsonObject = JSONObject.fromObject( "{\"double\":2.02}", tConfig ); assertTrue( "L'objet doit contenir une clef \"double\"", jsonObject.containsKey( "double" ) ); assertEquals( "Le membre \"double\" doit être égal a 2.02", 2.02d, jsonObject.optDouble( "double" ), 0.0001 ); // double jsonObject = JSONObject.fromObject( "{\"boolean\":true}", tConfig ); assertTrue( "L'objet doit contenir une clef \"boolean\"", jsonObject.containsKey( "boolean" ) ); assertEquals( "Le membre \"boolean\" doit être égal a true", true, jsonObject.optBoolean( "boolean" ) ); // String array jsonObject = JSONObject.fromObject( "{\"strArray\":[\"a\",\"b\",\"c\"]}", tConfig ); assertTrue( "L'objet doit contenir une clef \"strArray\"", jsonObject.containsKey( "strArray" ) ); assertNotNull( "Le membre \"strArray\" doit être une Array", jsonObject.optJSONArray( "strArray" ) ); assertEquals( "L'element 0 de \"strArray\" doit être égal a \"a\"", "a", jsonObject.optJSONArray( "strArray" ) .optString( 0 ) ); assertEquals( "L'element 1 de \"strArray\" doit être égal a \"b\"", "b", jsonObject.optJSONArray( "strArray" ) .optString( 1 ) ); assertEquals( "L'element 2 de \"strArray\" doit être égal a \"c\"", "c", jsonObject.optJSONArray( "strArray" ) .optString( 2 ) ); // int array jsonObject = JSONObject.fromObject( "{\"intArray\":[1,2,3]}", tConfig ); assertTrue( "L'objet doit contenir une clef \"intArray\"", jsonObject.containsKey( "intArray" ) ); assertNotNull( "Le membre \"intArray\" doit être une Array", jsonObject.optJSONArray( "intArray" ) ); assertEquals( "L'element 0 de \"intArray\" doit être égal a 1", 1, jsonObject.optJSONArray( "intArray" ).optInt( 0 ) ); assertEquals( "L'element 1 de \"intArray\" doit être égal a 2", 2, jsonObject.optJSONArray( "intArray" ).optInt( 1 ) ); assertEquals( "L'element 2 de \"intArray\" doit être égal a 3", 3, jsonObject.optJSONArray( "intArray" ).optInt( 2 ) ); // boolean array jsonObject = JSONObject.fromObject( "{\"booleanArray\":[true, false, true]}", tConfig ); assertTrue( "L'objet doit contenir une clef \"booleanArray\"", jsonObject.containsKey( "booleanArray" ) ); assertNotNull( "Le membre \"strArray\" doit être une booleanArray", jsonObject.optJSONArray( "booleanArray" ) ); assertEquals( "L'element 0 de \"booleanArray\" doit être égal a true", true, jsonObject.optJSONArray( "booleanArray" ).optBoolean( 0 ) ); assertEquals( "L'element 1 de \"booleanArray\" doit être égal a false", false, jsonObject.optJSONArray( "booleanArray" ).optBoolean( 1 ) ); assertEquals( "L'element 2 de \"booleanArray\" doit être égal a true", true, jsonObject.optJSONArray( "booleanArray" ).optBoolean( 2 ) ); // double array jsonObject = JSONObject.fromObject( "{\"doubleArray\":[\"a\",\"b\",\"c\"]}", tConfig ); assertTrue( "L'objet doit contenir une clef \"doubleArray\"", jsonObject.containsKey( "doubleArray" ) ); assertNotNull( "Le membre \"doubleArray\" doit être une Array", jsonObject.optJSONArray( "doubleArray" ) ); assertEquals( "L'element 0 de \"doubleArray\" doit être égal a \"a\"", "a", jsonObject.optJSONArray( "doubleArray" ).optString( 0 ) ); jsonObject = JSONObject.fromObject( "{\"weirdString\":\"[Hello]\"}", tConfig ); assertTrue( "L'objet doit contenir une clef \"weirdString\"", jsonObject.containsKey( "weirdString" ) ); assertNotNull( "Le membre \"weirdString\" doit être une String", jsonObject.optString( "weirdString" ) ); assertEquals( "Le membre \"weirdString\" doit être égal a \"[Hello]\"", "[Hello]", jsonObject.get( "weirdString" ) ); jsonObject = JSONObject.fromObject( "{\"weirdString\":\"{912}\"}" ); assertTrue( "L'objet doit contenir une clef \"weirdString\"", jsonObject.containsKey( "weirdString" ) ); assertNotNull( "Le membre \"weirdString\" doit être une String", jsonObject.optString( "weirdString" ) ); assertEquals( "Le membre \"weirdString\" doit être égal a \"{912}\"", "{912}", jsonObject.get( "weirdString" ) ); } /* public void testDifferenceBetweenStringSerialisationWithJSONObjectAndJSONArray() { JsonConfig tConfig = new JsonConfig(); tConfig.enableEventTriggering(); tConfig.addJsonEventListener( new JsonErrorDetector() ); // This was Ko JSONObject tJsonSource = new JSONObject(); tJsonSource.element( "weirdString", "[{}][:,;:.[][[]", jsonConfig ); assertEquals( "[{}][:,;:.[][[]", tJsonSource.get( "weirdString" ) ); String tExpected = "{\"weirdString\":\"[{}][:,;:.[][[]\"}"; assertEquals( tExpected, tJsonSource.toString() ); // This was Ko too tJsonSource = new JSONObject(); JSONArray tArraySource = new JSONArray(); tArraySource.element( "{912}", jsonConfig ); tArraySource.element( "[Hello]", jsonConfig ); tArraySource.element( "[]{}[,;.:[[]", jsonConfig ); assertEquals( "[]{}[,;.:[[]", tArraySource.get( 2 ) ); tJsonSource.put( "weirdStringArray", tArraySource ); tExpected = "{\"weirdStringArray\":[\"{912}\",\"[Hello]\",\"[]{}[,;.:[[]\"]}"; assertEquals( tExpected, tJsonSource.toString() ); }*/ /* public void testDifferenceBetweenStringParsingIntoJSONObjectAndJSONArray() { JsonConfig tConfig = new JsonConfig(); tConfig.enableEventTriggering(); tConfig.addJsonEventListener( new JsonErrorDetector() ); // This part was Ok JSONObject jsonObject = JSONObject.fromObject( "{\"weirdString\":\"[{}][:,;:.[][[]\"}", tConfig ); assertTrue( jsonObject.containsKey( "weirdString" ) ); assertNotNull( jsonObject.optString( "weirdString" ) ); assertEquals( "[{}][:,;:.[][[]", jsonObject.get( "weirdString" ) ); // This part very similar to the previous part was Ko jsonObject = JSONObject.fromObject( "{\"weirdStringArray\":[\"{912}\",\"[Hello]\",\"[]{}[,;.:[[]\"]}", tConfig ); assertTrue( jsonObject.containsKey( "weirdStringArray" ) ); assertNotNull( jsonObject.optJSONArray( "weirdStringArray" ) ); assertEquals( "{912}", jsonObject.getJSONArray( "weirdStringArray" ).optString( 0 ) ); assertEquals( "[Hello]", jsonObject.getJSONArray( "weirdStringArray" ).optString( 1 ) ); assertEquals( "[]{}[,;.:[[]", jsonObject.getJSONArray( "weirdStringArray" ).optString( 2 ) ); } */ public void testBug_2893329() { String jsonStr = "{x:\"\\'hello\\'\"}"; JSONObject json = JSONObject.fromObject(jsonStr); assertEquals("'hello'", json.getString("x")); } public void testBug_3047519() { String jsonStr = "{data:\"[1,2,3]\"}"; JSONObject json = JSONObject.fromObject(jsonStr); Object data = json.get("data"); assertTrue(data instanceof String); assertEquals("[1,2,3]", data); } /* public void testBug_3074732() { String test = "{\"c\":\"{\\\"k\\\":\\\"k\\\", \\\"l\\\":\\\"l\\\"}\"}"; JSONObject jsonObject = JSONObject.fromObject(test); assertTrue(jsonObject.get("c") instanceof String); String test2 = "{\"a\":[{\"c\":\"{\\\"k\\\":\\\"k\\\", \\\"l\\\":\\\"l\\\"}\"}]}"; jsonObject = JSONObject.fromObject(test2); assertTrue(jsonObject.getJSONArray("a").getJSONObject(0).get("c") instanceof String); } */ public static class RunnableImpl implements Runnable { public void run() { } } public static class JsonErrorDetector implements JsonEventListener{ public void onArrayEnd() { } public void onArrayStart() { } public void onElementAdded( int index, Object element ) { } public void onError( JSONException jsone ) { fail("An error occurs during JsonProcessing "+ jsone.getMessage()); } public void onObjectEnd() { } public void onObjectStart() { } public void onPropertySet( String key, Object value, boolean accumulated ) { } public void onWarning( String warning ) { } } protected void setUp() throws Exception { super.setUp(); jsonConfig = new JsonConfig(); } }
src/test/java/net/sf/json/TestUserSubmitted.java
/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.json; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import java.util.Map; import junit.framework.TestCase; import net.sf.ezmorph.object.MapToDateMorpher; import net.sf.json.sample.ArrayBean; import net.sf.json.sample.BeanA; import net.sf.json.sample.BeanA1763699; import net.sf.json.sample.BeanB1763699; import net.sf.json.sample.BeanC; import net.sf.json.sample.ChildBean; import net.sf.json.sample.DateBean; import net.sf.json.sample.FieldBean; import net.sf.json.sample.IdBean; import net.sf.json.sample.InterfaceBean; import net.sf.json.sample.JSONTestBean; import net.sf.json.sample.ListingBean; import net.sf.json.sample.MappedBean; import net.sf.json.sample.Media; import net.sf.json.sample.MediaBean; import net.sf.json.sample.MediaList; import net.sf.json.sample.MediaListBean; import net.sf.json.sample.NumberArrayBean; import net.sf.json.sample.PackageProtectedBean; import net.sf.json.sample.ParentBean; import net.sf.json.sample.Player; import net.sf.json.sample.PlayerList; import net.sf.json.sample.PrimitiveBean; import net.sf.json.sample.PrivateConstructorBean; import net.sf.json.sample.UnstandardBean; import net.sf.json.sample.UnstandardBeanInstanceStrategy; import net.sf.json.util.JSONUtils; import net.sf.json.util.JavaIdentifierTransformer; import net.sf.json.util.JsonEventListener; import org.apache.commons.beanutils.DynaBean; import org.apache.commons.beanutils.PropertyUtils; /** * @author Andres Almiray <aalmiray@users.sourceforge.net> */ public class TestUserSubmitted extends TestCase { public static void main( String[] args ) { junit.textui.TestRunner.run( TestUserSubmitted.class ); } private JsonConfig jsonConfig; public TestUserSubmitted( String name ) { super( name ); } public void testPatch_2929940() { Map classMap = new HashMap(); classMap.put("attributes", Long.class); ListingBean original = new ListingBean(); original.addAttribute(Long.valueOf(12)); JSONObject jsonObject = JSONObject.fromObject(JSONObject.fromObject(original).toString()); // JSON config JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setRootClass(ListingBean.class); jsonConfig.setClassMap(classMap); // toBean ListingBean bean = (ListingBean)JSONObject.toBean(jsonObject, jsonConfig); assertTrue(bean.getAttributes().get(0) instanceof Long); } public void testBug_1635890() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { // submited by arco.vandenheuvel[at]points[dot].com String TEST_JSON_STRING = "{\"rateType\":\"HOTRATE\",\"rateBreakdown\":{\"rate\":[{\"amount\":\"109.74\",\"date\":{\"month\":\"01\",\"day\":\"15\",\"year\":\"2007\"}},{\"amount\":\"109.74\",\"date\":{\"month\":\"1\",\"day\":\"16\",\"year\":\"2007\"}}]}}"; DynaBean jsonBean = (DynaBean) JSONObject.toBean( JSONObject.fromObject( TEST_JSON_STRING ) ); assertNotNull( jsonBean ); assertEquals( "wrong rate Type", "HOTRATE", jsonBean.get( "rateType" ) ); assertNotNull( "null rate breakdown", jsonBean.get( "rateBreakdown" ) ); DynaBean jsonRateBreakdownBean = (DynaBean) jsonBean.get( "rateBreakdown" ); assertNotNull( "null rate breakdown ", jsonRateBreakdownBean ); Object jsonRateBean = jsonRateBreakdownBean.get( "rate" ); assertNotNull( "null rate ", jsonRateBean ); assertTrue( "list", jsonRateBean instanceof ArrayList ); assertNotNull( "null rate ", jsonRateBreakdownBean.get( "rate", 0 ) ); } public void testBug_1650535_builders() { // submitted by Paul Field <paulfield[at]users[dot]sourceforge[dot]net> String json = "{\"obj\":\"{}\",\"array\":\"[]\"}"; JSONObject object = JSONObject.fromObject( json ); assertNotNull( object ); assertTrue( object.has( "obj" ) ); assertTrue( object.has( "array" ) ); Object obj = object.get( "obj" ); assertTrue( obj instanceof String ); Object array = object.get( "array" ); assertTrue( array instanceof String ); json = "{'obj':'{}','array':'[]'}"; object = JSONObject.fromObject( json ); assertNotNull( object ); assertTrue( object.has( "obj" ) ); assertTrue( object.has( "array" ) ); obj = object.get( "obj" ); assertTrue( obj instanceof String ); array = object.get( "array" ); assertTrue( array instanceof String ); json = "[\"{}\",\"[]\"]"; JSONArray jarray = JSONArray.fromObject( json ); assertNotNull( jarray ); obj = jarray.get( 0 ); assertTrue( obj instanceof String ); array = jarray.get( 1 ); assertTrue( array instanceof String ); json = "['{}','[]']"; jarray = JSONArray.fromObject( json ); assertNotNull( jarray ); obj = jarray.get( 0 ); assertTrue( obj instanceof String ); array = jarray.get( 1 ); assertTrue( array instanceof String ); // submitted by Elizabeth Keogh <ekeogh[at]thoughtworks[dot]com> Map map = new HashMap(); map.put( "address", "1 The flats [Upper floor]" ); map.put( "phoneNumber", "[+44] 582 401923" ); map.put( "info1", "[Likes coffee]" ); map.put( "info2", "[Likes coffee] [Likes tea]" ); map.put( "info3", "[Likes coffee [but not with sugar]]" ); object = JSONObject.fromObject( map ); assertNotNull( object ); assertTrue( object.has( "address" ) ); assertTrue( object.has( "phoneNumber" ) ); assertTrue( object.has( "info1" ) ); assertTrue( object.has( "info2" ) ); assertTrue( object.has( "info3" ) ); assertTrue( object.get( "address" ) instanceof String ); assertTrue( object.get( "phoneNumber" ) instanceof String ); assertTrue( object.get( "info1" ) instanceof String ); assertTrue( object.get( "info2" ) instanceof String ); assertTrue( object.get( "info3" ) instanceof String ); } /* I consider this behavior of "oh I added string but it's not really a string" very evil, as there's no way to add a String that really looks like "{}" public void testBug_1650535_setters() { JSONObject object = new JSONObject(); object.element( "obj", "{}" ); object.element( "notobj", "{string}" ); object.element( "array", "[]" ); object.element( "notarray", "[string]" ); assertTrue( object.get( "obj" ) instanceof JSONObject ); assertTrue( object.get( "array" ) instanceof JSONArray ); assertTrue( object.get( "notobj" ) instanceof String ); assertTrue( object.get( "notarray" ) instanceof String ); object.element( "str", "json,json" ); assertTrue( object.get( "str" ) instanceof String ); } */ public void testBug_1753528_ArrayStringLiteralToString() { // submited bysckimos[at]gmail[dot]com BeanA bean = new BeanA(); bean.setString( "[1234]" ); JSONObject jsonObject = JSONObject.fromObject( bean ); assertEquals( "[1234]", jsonObject.get( "string" ) ); bean.setString( "{'key':'1234'}" ); jsonObject = JSONObject.fromObject( bean ); assertEquals( "{'key':'1234'}", jsonObject.get( "string" ) ); } public void testBug_1763699_toBean() { JSONObject json = JSONObject.fromObject( "{'bbeans':[{'str':'test'}]}" ); BeanA1763699 bean = (BeanA1763699) JSONObject.toBean( json, BeanA1763699.class ); assertNotNull( bean ); BeanB1763699[] bbeans = bean.getBbeans(); assertNotNull( bbeans ); assertEquals( 1, bbeans.length ); assertEquals( "test", bbeans[0].getStr() ); } public void testBug_1764768_toBean() { JSONObject json = JSONObject.fromObject( "{'beanA':''}" ); Map classMap = new HashMap(); classMap.put( "beanA", BeanA.class ); BeanC bean = (BeanC) JSONObject.toBean( json, BeanC.class, classMap ); assertNotNull( bean ); assertNotNull( bean.getBeanA() ); assertEquals( new BeanA(), bean.getBeanA() ); } public void testBug_1769559_array_conversion() { JSONObject jsonObject = new JSONObject().element( "beans", new JSONArray().element( "{}" ) .element( "{'bool':false,'integer':216,'string':'JsOn'}" ) ); ArrayBean bean = (ArrayBean) JSONObject.toBean( jsonObject, ArrayBean.class ); assertNotNull( bean ); // no error should happen here JSONArray jsonArray = jsonObject.getJSONArray( "beans" ); BeanA[] beans = (BeanA[]) JSONArray.toArray( jsonArray, BeanA.class ); assertNotNull( beans ); assertEquals( 2, beans.length ); assertEquals( new BeanA(), beans[0] ); assertEquals( new BeanA( false, 216, "JsOn" ), beans[1] ); } public void testBug_1769578_array_conversion() { JSONObject jsonObject = JSONObject .fromObject( "{'media':[{'title':'Giggles'},{'title':'Dreamland?'}]}" ); Map classMap = new HashMap(); classMap.put( "media", MediaBean.class ); MediaListBean bean = (MediaListBean) JSONObject.toBean( jsonObject, MediaListBean.class, classMap ); assertNotNull( bean ); assertNotNull( bean.getMedia() ); assertTrue( bean.getMedia().getClass().isArray() ); Object[] media = (Object[]) bean.getMedia(); assertEquals( 2, media.length ); Object mediaItem1 = media[0]; assertTrue( mediaItem1 instanceof MediaBean ); assertEquals( "Giggles", ((MediaBean) mediaItem1).getTitle() ); } public void testBug_1812682() { int[] numbers = new int[] { 1, 2, 3, 4, 5 }; JSONObject json = new JSONObject().element( "bytes", numbers ).element( "shorts", numbers ) .element( "ints", numbers ).element( "longs", numbers ).element( "floats", numbers ) .element( "doubles", numbers ); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setRootClass( NumberArrayBean.class ); NumberArrayBean bean = (NumberArrayBean) JSONObject.toBean( json, jsonConfig ); assertNotNull( bean ); } public void testBug_1813301() { List list = new ArrayList(); list.add( "1" ); list.add( "2" ); list.add( "3" ); JSONObject jsonObject = new JSONObject().element( "name", "JSON" ).element( "list", list ); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setRootClass( MappedBean.class ); MappedBean bean = (MappedBean) JSONObject.toBean( jsonObject, jsonConfig ); assertNotNull( bean ); assertEquals( "JSON", bean.getName() ); Assertions.assertEquals( list, bean.getList() ); } public void testBug_1875600_1() { JSONArray jArray = JSONArray.fromObject( "[]" ); int[] iArray = (int[]) JSONArray.toArray( jArray, int.class ); JSONArray actual = JSONArray.fromObject( iArray ); Assertions.assertEquals( new JSONArray(), actual ); } public void testBug_1875600_2() { JSONArray jArray = JSONArray.fromObject( "[ [] ]" ); int[][] iArray = (int[][]) JSONArray.toArray( jArray, int.class ); JSONArray actual = JSONArray.fromObject( iArray ); Assertions.assertEquals( new JSONArray().element( new JSONArray() ), actual ); } public void testConstructor_Object__nullArray() { // submitted by Matt Small String[] strarr = null; JSONObject jsonObject = JSONObject.fromObject( strarr, jsonConfig ); assertTrue( jsonObject.isNullObject() ); } public void testConstructor_Object_EnclosedArray() { // submitted by Matt Small PrimitiveBean bean = new PrimitiveBean(); bean.setOarray( new String[] { "hi", "bye" } ); JSONObject jsonObject = JSONObject.fromObject( bean, jsonConfig ); assertFalse( jsonObject.isNullObject() ); assertFalse( jsonObject.getJSONArray( "oarray" ).isEmpty() ); } public void testConstructor_Object_EnclosedNullArray() { // submitted by Matt Small PrimitiveBean bean = new PrimitiveBean(); bean.setOarray( null ); JSONObject jsonObject = JSONObject.fromObject( bean, jsonConfig ); assertFalse( jsonObject.isNullObject() ); assertTrue( jsonObject.getJSONArray( "oarray" ).isEmpty() ); } public void testConstructorAndToBean_Object_RoundTrip_EnclosedNullArray() { PrimitiveBean bean = new PrimitiveBean(); bean.setOarray( null ); JSONObject jsonObject = JSONObject.fromObject( bean, jsonConfig ); PrimitiveBean bean2 = (PrimitiveBean) JSONObject.toBean( jsonObject, PrimitiveBean.class ); assertNotNull( bean2 ); // bean.oarray == null // jsonObject.oarray == [] therefore // bean2.oarray != null assertEquals( 0, bean2.getOarray().length ); } public void testDynaBeanAttributeMap() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { // submited by arco.vandenheuvel[at]points[dot].com JSONObject jsonObject = JSONObject.fromObject( new JSONTestBean() ); String jsonString = jsonObject.toString(); DynaBean jsonBean = (DynaBean) JSONObject.toBean( JSONObject.fromObject( jsonString ) ); assertNotNull( jsonBean ); assertEquals( "wrong inventoryID", "", jsonBean.get( "inventoryID" ) ); } public void testFR_1768960_array_conversion() { // 2 items JSONObject jsonObject = JSONObject .fromObject( "{'media2':[{'title':'Giggles'},{'title':'Dreamland?'}]}" ); Map classMap = new HashMap(); classMap.put( "media2", MediaBean.class ); MediaListBean bean = (MediaListBean) JSONObject.toBean( jsonObject, MediaListBean.class, classMap ); assertNotNull( bean ); assertNotNull( bean.getMedia2() ); List media2 = bean.getMedia2(); assertEquals( 2, media2.size() ); Object mediaItem1 = media2.get( 0 ); assertTrue( mediaItem1 instanceof MediaBean ); assertEquals( "Giggles", ((MediaBean) mediaItem1).getTitle() ); // 1 // item jsonObject = JSONObject.fromObject( "{'media2':[{'title':'Giggles'}]}" ); bean = (MediaListBean) JSONObject.toBean( jsonObject, MediaListBean.class, classMap ); assertNotNull( bean ); assertNotNull( bean.getMedia2() ); media2 = bean.getMedia2(); assertEquals( 1, media2.size() ); mediaItem1 = media2.get( 0 ); assertTrue( mediaItem1 instanceof MediaBean ); assertEquals( "Giggles", ((MediaBean) mediaItem1).getTitle() ); } public void testFR_1808430_newBeanInstance() { JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setNewBeanInstanceStrategy( new UnstandardBeanInstanceStrategy() ); JSONObject jsonObject = new JSONObject(); jsonObject.element( "id", 1 ); jsonConfig.setRootClass( UnstandardBean.class ); UnstandardBean bean = (UnstandardBean) JSONObject.toBean( jsonObject, jsonConfig ); assertNotNull( bean ); assertEquals( UnstandardBean.class, bean.getClass() ); assertEquals( 1, bean.getId() ); } public void testFR_1832047_packageProtectedBean() { JSONObject jsonObject = new JSONObject().element( "value", "42" ); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setRootClass( PackageProtectedBean.class ); PackageProtectedBean bean = (PackageProtectedBean) JSONObject.toBean( jsonObject, jsonConfig ); assertNotNull( bean ); assertEquals( 42, bean.getValue() ); } public void testFR_1832047_privateProtectedBean() { JSONObject jsonObject = new JSONObject().element( "value", "42" ); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setRootClass( PrivateConstructorBean.class ); PrivateConstructorBean bean = (PrivateConstructorBean) JSONObject.toBean( jsonObject, jsonConfig ); assertNotNull( bean ); assertEquals( 42, bean.getValue() ); } public void testFR_1858073_preserveInsertionOrder() { JSONObject jsonObject = new JSONObject().element( "one", "one" ).element( "two", "two" ) .element( "three", "three" ); JSONArray actual = jsonObject.names(); JSONArray expected = new JSONArray().element( "one" ).element( "two" ).element( "three" ); Assertions.assertEquals( expected, actual ); } public void testFromObjectCurliesOnString() { String json = "{'prop':'{value}'}"; JSONObject jsonObject = JSONObject.fromObject( json ); assertNotNull( jsonObject ); assertEquals( 1, jsonObject.size() ); assertEquals( "{value}", jsonObject.get( "prop" ) ); json = "{'prop':'{{value}}'}"; jsonObject = JSONObject.fromObject( json ); assertNotNull( jsonObject ); assertEquals( 1, jsonObject.size() ); assertEquals( "{{value}}", jsonObject.get( "prop" ) ); json = "{'prop':'{{{value}}}'}"; jsonObject = JSONObject.fromObject( json ); assertNotNull( jsonObject ); assertEquals( 1, jsonObject.size() ); assertEquals( "{{{value}}}", jsonObject.get( "prop" ) ); } public void testHandleJettisonEmptyElement() { JSONObject jsonObject = JSONObject.fromObject( "{'beanA':'','beanB':''}" ); jsonConfig.setHandleJettisonEmptyElement( true ); jsonConfig.setRootClass( BeanC.class ); BeanC bean = (BeanC) JSONObject.toBean( jsonObject, jsonConfig ); assertNotNull( bean ); assertNull( bean.getBeanA() ); assertNull( bean.getBeanB() ); } public void testHandleJettisonSingleElementArray() { JSONObject jsonObject = JSONObject.fromObject( "{'media2':{'title':'Giggles'}}" ); Map classMap = new HashMap(); classMap.put( "media2", MediaBean.class ); jsonConfig.setHandleJettisonSingleElementArray( true ); jsonConfig.setRootClass( MediaListBean.class ); jsonConfig.setClassMap( classMap ); MediaListBean bean = (MediaListBean) JSONObject.toBean( jsonObject, jsonConfig ); assertNotNull( bean ); assertNotNull( bean.getMedia2() ); List media2 = bean.getMedia2(); assertEquals( 1, media2.size() ); Object mediaItem1 = media2.get( 0 ); assertTrue( mediaItem1 instanceof MediaBean ); assertEquals( "Giggles", ((MediaBean) mediaItem1).getTitle() ); } public void testHandleJettisonSingleElementArray2() { JSONObject jsonObject = JSONObject.fromObject( "{'mediaList':{'media':{'title':'Giggles'}}}" ); Map classMap = new HashMap(); classMap.put( "media", Media.class ); classMap.put( "mediaList", MediaList.class ); jsonConfig.setHandleJettisonSingleElementArray( true ); jsonConfig.setRootClass( Player.class ); jsonConfig.setClassMap( classMap ); Player bean = (Player) JSONObject.toBean( jsonObject, jsonConfig ); assertNotNull( bean ); assertNotNull( bean.getMediaList() ); MediaList mediaList = bean.getMediaList(); assertNotNull( mediaList.getMedia() ); ArrayList medias = mediaList.getMedia(); assertEquals( "Giggles", ((Media) medias.get( 0 )).getTitle() ); } public void testHandleJettisonSingleElementArray3() { JSONObject jsonObject = JSONObject .fromObject( "{'player':{'mediaList':{'media':{'title':'Giggles'}}}}" ); Map classMap = new HashMap(); classMap.put( "media", Media.class ); classMap.put( "mediaList", MediaList.class ); classMap.put( "player", Player.class ); jsonConfig.setHandleJettisonSingleElementArray( true ); jsonConfig.setRootClass( PlayerList.class ); jsonConfig.setClassMap( classMap ); PlayerList bean = (PlayerList) JSONObject.toBean( jsonObject, jsonConfig ); assertNotNull( bean ); assertNotNull( bean.getPlayer() ); ArrayList players = bean.getPlayer(); assertNotNull( players ); assertNotNull( players.get( 0 ) ); Player player = (Player) players.get( 0 ); assertNotNull( player.getMediaList() ); MediaList mediaList = player.getMediaList(); assertNotNull( mediaList.getMedia() ); ArrayList medias = mediaList.getMedia(); assertEquals( "Giggles", ((Media) medias.get( 0 )).getTitle() ); } public void testJsonWithNamespaceToDynaBean() throws Exception { // submited by Girish Ipadi jsonConfig.setJavaIdentifierTransformer( JavaIdentifierTransformer.NOOP ); String str = "{'version':'1.0'," + "'sid':'AmazonDocStyle', 'svcVersion':'0.1'," + "'oid':'ItemLookup', 'params':[{ 'ns:ItemLookup': {" + "'ns:SubscriptionId':'0525E2PQ81DD7ZTWTK82'," + "'ns:Validate':'False'," + "'ns:Request':{" + "'ns:ItemId':'SDGKJSHDGAJSGL'," + "'ns:IdType':'ASIN'," + "'ns:ResponseGroup':'Large'" + "}," + "'ns:Request':{" + "'ns:ItemId':'XXXXXXXXXX'," + "'ns:IdType':'ASIN'," + "'ns:ResponseGroup':'Large'" + "}" + "}" + "}]" + "} "; JSONObject json = JSONObject.fromObject( str, jsonConfig ); Object bean = JSONObject.toBean( (JSONObject) json ); assertNotNull( bean ); List params = (List) PropertyUtils.getProperty( bean, "params" ); DynaBean param0 = (DynaBean) params.get( 0 ); DynaBean itemLookup = (DynaBean) param0.get( "ns:ItemLookup" ); assertNotNull( itemLookup ); assertEquals( "0525E2PQ81DD7ZTWTK82", itemLookup.get( "ns:SubscriptionId" ) ); } /* No morpher, please - Kohsuke public void testToBeanSimpleToComplexValueTransformation() { // Submitted by Oliver Zyngier JSONObject jsonObject = JSONObject.fromObject( "{'id':null}" ); IdBean idBean = (IdBean) JSONObject.toBean( jsonObject, IdBean.class ); assertNotNull( idBean ); assertEquals( null, idBean.getId() ); jsonObject = JSONObject.fromObject( "{'id':1}" ); idBean = (IdBean) JSONObject.toBean( jsonObject, IdBean.class ); assertNotNull( idBean ); assertNotNull( idBean.getId() ); assertEquals( 0L, idBean.getId().getValue() ); JSONUtils.getMorpherRegistry().registerMorpher( new IdBean.IdMorpher(), true ); jsonObject = JSONObject.fromObject( "{'id':1}" ); idBean = (IdBean) JSONObject.toBean( jsonObject, IdBean.class ); assertNotNull( idBean ); assertEquals( new IdBean.Id( 1L ), idBean.getId() ); } public void testToBeanWithMultipleMorphersForTargetType() { Calendar c = Calendar.getInstance(); c.set( Calendar.YEAR, 2007 ); c.set( Calendar.MONTH, 5 ); c.set( Calendar.DATE, 17 ); c.set( Calendar.HOUR_OF_DAY, 12 ); c.set( Calendar.MINUTE, 13 ); c.set( Calendar.SECOND, 14 ); c.set( Calendar.MILLISECOND, 150 ); Date date = c.getTime(); DateBean bean = new DateBean(); bean.setDate( date ); JSONObject jsonObject = JSONObject.fromObject( bean ); JSONUtils.getMorpherRegistry().registerMorpher( new MapToDateMorpher() ); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setRootClass( DateBean.class ); DateBean actual = (DateBean) JSONObject.toBean( jsonObject, jsonConfig ); Calendar d = Calendar.getInstance(); d.setTime( actual.getDate() ); assertEquals( c.get( Calendar.YEAR ), d.get( Calendar.YEAR ) ); assertEquals( c.get( Calendar.MONTH ), d.get( Calendar.MONTH ) ); assertEquals( c.get( Calendar.DATE ), d.get( Calendar.DATE ) ); assertEquals( c.get( Calendar.HOUR_OF_DAY ), d.get( Calendar.HOUR_OF_DAY ) ); assertEquals( c.get( Calendar.MINUTE ), d.get( Calendar.MINUTE ) ); assertEquals( c.get( Calendar.SECOND ), d.get( Calendar.SECOND ) ); assertEquals( c.get( Calendar.MILLISECOND ), d.get( Calendar.MILLISECOND ) ); } public void testToBeanWithInterfaceField() { JSONObject jsonObject = JSONObject.fromObject( "{runnable:{}}" ); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setRootClass( InterfaceBean.class ); Map classMap = new HashMap(); classMap.put( "runnable", RunnableImpl.class ); jsonConfig.setClassMap( classMap ); InterfaceBean bean = (InterfaceBean) JSONObject.toBean( jsonObject, jsonConfig ); assertNotNull( bean ); assertNotNull( bean.getRunnable() ); assertTrue( bean.getRunnable() instanceof RunnableImpl ); } public void testCycleDetection_withExclusions() { ParentBean parent = new ParentBean(); parent.setChild( new ChildBean() ); // will fail if throws an exception jsonConfig.setExcludes( new String[] { "parent" } ); JSONObject.fromObject( parent, jsonConfig ); } public void testJSONArrayIterator() { JSONArray jsonArray = new JSONArray(); jsonArray.add( "1" ); jsonArray.add( "2" ); jsonArray.add( "3" ); List list = new LinkedList(); list.add( "4" ); list.add( "5" ); list.add( "6" ); jsonArray.add( list ); List newList = new LinkedList(); newList.add( "7" ); newList.add( "8" ); newList.add( "9" ); Assertions.assertEquals( JSONArray.fromObject( "['1','2','3',['4','5','6']]" ), jsonArray ); ListIterator listIterator = jsonArray.listIterator(); listIterator.add( newList ); Assertions.assertEquals( JSONArray.fromObject( "[['7','8','9'],'1','2','3',['4','5','6']]" ), jsonArray ); } public void testJSONArray_badFormattedString() { String badJson = "[{\"a\":\"b\"},"; try { JSONArray.fromObject(badJson); fail("Expecting a syntax error from JSONTokener."); }catch( JSONException jsone ) { assertTrue( jsone.getMessage().startsWith( "Found starting '[' but missing ']' at the end." )); } } public void testJSONObject_badFormattedString() { String badJson = "{\"a\":\"b\"},"; try { JSONObject.fromObject(badJson); fail("Expecting a syntax error from JSONTokener."); }catch( JSONException jsone ) { assertTrue( jsone.getMessage().startsWith( "Found starting '{' but missing '}' at the end." )); } */ public void testQuotedFunctions() { JSONObject json = JSONObject.fromObject( "{'func':\"function(){blah;}\"}" ); assertTrue( json.get( "func" ) instanceof String ); assertEquals( "\"function(){blah;}\"", json.get( "func" )); } public void testJsonWithNullKeys() { Map map = new HashMap(); map.put("key", "value"); map.put(null, "value2"); Object[] obj = {map}; try { JSONSerializer.toJSON( obj ); fail( "Should have thrown a ClassCastException" ); } catch( JSONException expected ) { // ok } } public void testJsonWithNullKeys2() { Map map = new HashMap(); map.put("key", "value"); map.put(null, "value2"); try { System.err.println(JSONSerializer.toJSON( map )); fail( "Should have thrown a ClassCastException" ); } catch( JSONException expected ) { // ok } } public void testJSONArray_JavascriptCompliant() { JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setJavascriptCompliant( true ); String json = "[null, undefined]"; JSONArray array = JSONArray.fromObject( json, jsonConfig ); assertNotNull(array); Assertions.assertEquals( JSONNull.getInstance(), array.get(1) ); } public void testJSONArray_JavascriptComplian2t() { JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setJavascriptCompliant( true ); JSONArray array = new JSONArray(); array.element("null", jsonConfig); array.element("undefined", jsonConfig); assertNotNull(array); Assertions.assertEquals( JSONNull.getInstance(), array.get(0) ); Assertions.assertEquals( JSONNull.getInstance(), array.get(1) ); } public void testJSONObject_JavascriptCompliant() { JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setJavascriptCompliant( true ); String json = "{key1: null, key2: undefined}"; JSONObject object = JSONObject.fromObject( json, jsonConfig ); assertNotNull(object); Assertions.assertEquals( JSONNull.getInstance(), object.get("key2") ); } public void testJSONObject_JavascriptCompliant2() { JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setJavascriptCompliant( true ); JSONObject object = new JSONObject(); object.element( "key1", "null", jsonConfig ); object.element( "key2", "undefined", jsonConfig ); assertNotNull(object); Assertions.assertEquals( JSONNull.getInstance(), object.get("key2") ); } public void testJSONObject_fromObject_FieldBean() { JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setIgnorePublicFields( false ); FieldBean bean = new FieldBean(); bean.setValue( 42 ); bean.string = "stringy"; JSONObject jsonObject = JSONObject.fromObject( bean ); assertNotNull( jsonObject ); assertEquals( 42, jsonObject.getInt( "value" )); assertFalse( jsonObject.has( "string" )); jsonObject = JSONObject.fromObject( bean, jsonConfig ); assertNotNull( jsonObject ); assertEquals( 42, jsonObject.getInt( "value" )); assertEquals( "stringy", jsonObject.getString( "string" )); } public void testJSONObject_toBean_FieldBean() { JSONObject jsonObject = new JSONObject(); jsonObject.element( "value", 42 ); jsonObject.element( "string", "stringy" ); FieldBean bean1 = (FieldBean) JSONObject.toBean( jsonObject, FieldBean.class ); assertNotNull( bean1 ); assertEquals( 42, bean1.getValue()); assertNull( bean1.string ); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setIgnorePublicFields( false ); jsonConfig.setRootClass( FieldBean.class ); FieldBean bean2 = (FieldBean) JSONObject.toBean( jsonObject, jsonConfig ); assertNotNull( bean2 ); assertEquals( 42, bean1.getValue()); assertEquals( "stringy", bean2.string ); } public void testBug_2692698() { String input = "[\"{'selectedOperatorIndex':2,'leftSideValue':'report.field9','rightSideValue':'2009-3-1'}\",\"all\"]"; JSON json = JSONArray.fromObject( input ); String output = json.toString(); assertEquals(input, output); } public void testWithoutAnyTroubleTheyMayBeAlreadyDoneByOtherTest() { JsonConfig tConfig = new JsonConfig(); tConfig.enableEventTriggering(); tConfig.addJsonEventListener(new JsonErrorDetector()); // String JSONObject jsonObject = JSONObject.fromObject( "{\"string\":\"aString\"}", tConfig ); assertTrue( "L'objet doit contenir une clef \"string\"", jsonObject.containsKey( "string" ) ); assertNotNull( "Le membre \"string\" doit être une String", jsonObject.optString( "string" ) ); assertEquals( "Le membre \"string\" doit être égal a \"aString\"", "aString", jsonObject.get( "string" ) ); // int jsonObject = JSONObject.fromObject( "{\"integer\":10}", tConfig ); assertTrue( "L'objet doit contenir une clef \"integer\"", jsonObject.containsKey( "integer" ) ); assertEquals( "Le membre \"integer\" doit être égal a 10", 10, jsonObject.optInt( "integer" ) ); // boolean jsonObject = JSONObject.fromObject( "{\"double\":2.02}", tConfig ); assertTrue( "L'objet doit contenir une clef \"double\"", jsonObject.containsKey( "double" ) ); assertEquals( "Le membre \"double\" doit être égal a 2.02", 2.02d, jsonObject.optDouble( "double" ), 0.0001 ); // double jsonObject = JSONObject.fromObject( "{\"boolean\":true}", tConfig ); assertTrue( "L'objet doit contenir une clef \"boolean\"", jsonObject.containsKey( "boolean" ) ); assertEquals( "Le membre \"boolean\" doit être égal a true", true, jsonObject.optBoolean( "boolean" ) ); // String array jsonObject = JSONObject.fromObject( "{\"strArray\":[\"a\",\"b\",\"c\"]}", tConfig ); assertTrue( "L'objet doit contenir une clef \"strArray\"", jsonObject.containsKey( "strArray" ) ); assertNotNull( "Le membre \"strArray\" doit être une Array", jsonObject.optJSONArray( "strArray" ) ); assertEquals( "L'element 0 de \"strArray\" doit être égal a \"a\"", "a", jsonObject.optJSONArray( "strArray" ) .optString( 0 ) ); assertEquals( "L'element 1 de \"strArray\" doit être égal a \"b\"", "b", jsonObject.optJSONArray( "strArray" ) .optString( 1 ) ); assertEquals( "L'element 2 de \"strArray\" doit être égal a \"c\"", "c", jsonObject.optJSONArray( "strArray" ) .optString( 2 ) ); // int array jsonObject = JSONObject.fromObject( "{\"intArray\":[1,2,3]}", tConfig ); assertTrue( "L'objet doit contenir une clef \"intArray\"", jsonObject.containsKey( "intArray" ) ); assertNotNull( "Le membre \"intArray\" doit être une Array", jsonObject.optJSONArray( "intArray" ) ); assertEquals( "L'element 0 de \"intArray\" doit être égal a 1", 1, jsonObject.optJSONArray( "intArray" ).optInt( 0 ) ); assertEquals( "L'element 1 de \"intArray\" doit être égal a 2", 2, jsonObject.optJSONArray( "intArray" ).optInt( 1 ) ); assertEquals( "L'element 2 de \"intArray\" doit être égal a 3", 3, jsonObject.optJSONArray( "intArray" ).optInt( 2 ) ); // boolean array jsonObject = JSONObject.fromObject( "{\"booleanArray\":[true, false, true]}", tConfig ); assertTrue( "L'objet doit contenir une clef \"booleanArray\"", jsonObject.containsKey( "booleanArray" ) ); assertNotNull( "Le membre \"strArray\" doit être une booleanArray", jsonObject.optJSONArray( "booleanArray" ) ); assertEquals( "L'element 0 de \"booleanArray\" doit être égal a true", true, jsonObject.optJSONArray( "booleanArray" ).optBoolean( 0 ) ); assertEquals( "L'element 1 de \"booleanArray\" doit être égal a false", false, jsonObject.optJSONArray( "booleanArray" ).optBoolean( 1 ) ); assertEquals( "L'element 2 de \"booleanArray\" doit être égal a true", true, jsonObject.optJSONArray( "booleanArray" ).optBoolean( 2 ) ); // double array jsonObject = JSONObject.fromObject( "{\"doubleArray\":[\"a\",\"b\",\"c\"]}", tConfig ); assertTrue( "L'objet doit contenir une clef \"doubleArray\"", jsonObject.containsKey( "doubleArray" ) ); assertNotNull( "Le membre \"doubleArray\" doit être une Array", jsonObject.optJSONArray( "doubleArray" ) ); assertEquals( "L'element 0 de \"doubleArray\" doit être égal a \"a\"", "a", jsonObject.optJSONArray( "doubleArray" ).optString( 0 ) ); jsonObject = JSONObject.fromObject( "{\"weirdString\":\"[Hello]\"}", tConfig ); assertTrue( "L'objet doit contenir une clef \"weirdString\"", jsonObject.containsKey( "weirdString" ) ); assertNotNull( "Le membre \"weirdString\" doit être une String", jsonObject.optString( "weirdString" ) ); assertEquals( "Le membre \"weirdString\" doit être égal a \"[Hello]\"", "[Hello]", jsonObject.get( "weirdString" ) ); jsonObject = JSONObject.fromObject( "{\"weirdString\":\"{912}\"}" ); assertTrue( "L'objet doit contenir une clef \"weirdString\"", jsonObject.containsKey( "weirdString" ) ); assertNotNull( "Le membre \"weirdString\" doit être une String", jsonObject.optString( "weirdString" ) ); assertEquals( "Le membre \"weirdString\" doit être égal a \"{912}\"", "{912}", jsonObject.get( "weirdString" ) ); } /* public void testDifferenceBetweenStringSerialisationWithJSONObjectAndJSONArray() { JsonConfig tConfig = new JsonConfig(); tConfig.enableEventTriggering(); tConfig.addJsonEventListener( new JsonErrorDetector() ); // This was Ko JSONObject tJsonSource = new JSONObject(); tJsonSource.element( "weirdString", "[{}][:,;:.[][[]", jsonConfig ); assertEquals( "[{}][:,;:.[][[]", tJsonSource.get( "weirdString" ) ); String tExpected = "{\"weirdString\":\"[{}][:,;:.[][[]\"}"; assertEquals( tExpected, tJsonSource.toString() ); // This was Ko too tJsonSource = new JSONObject(); JSONArray tArraySource = new JSONArray(); tArraySource.element( "{912}", jsonConfig ); tArraySource.element( "[Hello]", jsonConfig ); tArraySource.element( "[]{}[,;.:[[]", jsonConfig ); assertEquals( "[]{}[,;.:[[]", tArraySource.get( 2 ) ); tJsonSource.put( "weirdStringArray", tArraySource ); tExpected = "{\"weirdStringArray\":[\"{912}\",\"[Hello]\",\"[]{}[,;.:[[]\"]}"; assertEquals( tExpected, tJsonSource.toString() ); }*/ /* public void testDifferenceBetweenStringParsingIntoJSONObjectAndJSONArray() { JsonConfig tConfig = new JsonConfig(); tConfig.enableEventTriggering(); tConfig.addJsonEventListener( new JsonErrorDetector() ); // This part was Ok JSONObject jsonObject = JSONObject.fromObject( "{\"weirdString\":\"[{}][:,;:.[][[]\"}", tConfig ); assertTrue( jsonObject.containsKey( "weirdString" ) ); assertNotNull( jsonObject.optString( "weirdString" ) ); assertEquals( "[{}][:,;:.[][[]", jsonObject.get( "weirdString" ) ); // This part very similar to the previous part was Ko jsonObject = JSONObject.fromObject( "{\"weirdStringArray\":[\"{912}\",\"[Hello]\",\"[]{}[,;.:[[]\"]}", tConfig ); assertTrue( jsonObject.containsKey( "weirdStringArray" ) ); assertNotNull( jsonObject.optJSONArray( "weirdStringArray" ) ); assertEquals( "{912}", jsonObject.getJSONArray( "weirdStringArray" ).optString( 0 ) ); assertEquals( "[Hello]", jsonObject.getJSONArray( "weirdStringArray" ).optString( 1 ) ); assertEquals( "[]{}[,;.:[[]", jsonObject.getJSONArray( "weirdStringArray" ).optString( 2 ) ); } */ public void testBug_2893329() { String jsonStr = "{x:\"\\'hello\\'\"}"; JSONObject json = JSONObject.fromObject(jsonStr); assertEquals("'hello'", json.getString("x")); } public void testBug_3047519() { String jsonStr = "{data:\"[1,2,3]\"}"; JSONObject json = JSONObject.fromObject(jsonStr); Object data = json.get("data"); assertTrue(data instanceof String); assertEquals("[1,2,3]", data); } /* public void testBug_3074732() { String test = "{\"c\":\"{\\\"k\\\":\\\"k\\\", \\\"l\\\":\\\"l\\\"}\"}"; JSONObject jsonObject = JSONObject.fromObject(test); assertTrue(jsonObject.get("c") instanceof String); String test2 = "{\"a\":[{\"c\":\"{\\\"k\\\":\\\"k\\\", \\\"l\\\":\\\"l\\\"}\"}]}"; jsonObject = JSONObject.fromObject(test2); assertTrue(jsonObject.getJSONArray("a").getJSONObject(0).get("c") instanceof String); } */ public static class RunnableImpl implements Runnable { public void run() { } } public static class JsonErrorDetector implements JsonEventListener{ public void onArrayEnd() { } public void onArrayStart() { } public void onElementAdded( int index, Object element ) { } public void onError( JSONException jsone ) { fail("An error occurs during JsonProcessing "+ jsone.getMessage()); } public void onObjectEnd() { } public void onObjectStart() { } public void onPropertySet( String key, Object value, boolean accumulated ) { } public void onWarning( String warning ) { } } protected void setUp() throws Exception { super.setUp(); jsonConfig = new JsonConfig(); } }
I don't agree with this test {'func':"xyz"} should produce String value of xyz. Just because the string looks like a JavaScript function, it shouldn't treat it any differently. Needless to say, RFC 4627 do not describe any such special treatment to the content of the string
src/test/java/net/sf/json/TestUserSubmitted.java
I don't agree with this test
Java
bsd-3-clause
0bb6e99326b63e3623499202fd23da3fd44a91f2
0
arurke/contiki,bluerover/6lbr,arurke/contiki,MohamedSeliem/contiki,arurke/contiki,arurke/contiki,bluerover/6lbr,MohamedSeliem/contiki,bluerover/6lbr,MohamedSeliem/contiki,MohamedSeliem/contiki,arurke/contiki,MohamedSeliem/contiki,bluerover/6lbr,bluerover/6lbr,MohamedSeliem/contiki,bluerover/6lbr,arurke/contiki,arurke/contiki,MohamedSeliem/contiki,bluerover/6lbr
/* * Copyright (c) 2006, Swedish Institute of Computer Science. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. 2. Redistributions in * binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. 3. Neither the name of the * Institute nor the names of its contributors may be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * $Id: Simulation.java,v 1.42 2009/02/24 15:08:20 fros4943 Exp $ */ package se.sics.cooja; import java.util.*; import org.apache.log4j.Logger; import org.jdom.*; import se.sics.cooja.dialogs.*; /** * A simulation consists of a number of motes and mote types. * * The motes in the simulation are ticked every millisecond. * * A simulation is observable: * changed simulation state, added or deleted motes etc are observed. * To track mote changes, observe the mote (interfaces) itself. * * @author Fredrik sterlind */ public class Simulation extends Observable implements Runnable { private Vector<Mote> motes = new Vector<Mote>(); private Vector<MoteType> moteTypes = new Vector<MoteType>(); private int delayTime = 5; private long currentSimulationTime = 0; private int tickTime = 1; private String title = null; private RadioMedium currentRadioMedium = null; private static Logger logger = Logger.getLogger(Simulation.class); private boolean isRunning = false; private boolean stopSimulation = false; private Thread simulationThread = null; private GUI myGUI = null; private long randomSeed = 123456; private boolean randomSeedGenerated = false; private int maxMoteStartupDelay = 1000; private Random randomGenerator = new Random(); // Tick observable private class TickObservable extends Observable { private void allTicksPerformed() { setChanged(); notifyObservers(); } } private TickObservable tickObservable = new TickObservable(); /** * Add tick observer. This observer is notified once every tick loop, that is, * when all motes have been ticked. * * @see #deleteTickObserver(Observer) * @param newObserver * New observer */ public void addTickObserver(Observer newObserver) { tickObservable.addObserver(newObserver); } /** * Delete an existing tick observer. * * @see #addTickObserver(Observer) * @param observer * Observer to delete */ public void deleteTickObserver(Observer observer) { tickObservable.deleteObserver(observer); } protected void scheduleEventUnsafe(TimeEvent e, long time) { eventQueue.addEvent(e, time); } /** * Schedule event to be handled by event loop. * * @param e Event * @param time Simulated time */ public void scheduleEvent(TimeEvent e, long time) { if (Thread.currentThread() == simulationThread) { eventQueue.addEvent(e, time); } else { eventQueue.addEventUnsorted(e, time); } } private EventQueue eventQueue = new EventQueue(); private Mote[] emulatedMoteArray; private TimeEvent tickemulatedMotesEvent = new TimeEvent(0) { public void execute(long t) { /*logger.info("MSP motes tick at: " + t);*/ if (emulatedMoteArray.length == 0) { return; } /* Tick MSP motes */ boolean wantMoreTicks = true; while (wantMoreTicks) { /* Tick all MSP motes until none need more ticks */ wantMoreTicks = false; for (Mote element : emulatedMoteArray) { if (element.tick(currentSimulationTime)) { wantMoreTicks = true; } } } /* Reschedule MSP motes */ scheduleEventUnsafe(this, t+1); } }; private Mote[] moteArray; private TimeEvent tickMotesEvent = new TimeEvent(0) { public void execute(long t) { /*logger.info("Contiki motes tick at: " + t);*/ if (moteArray.length == 0) { return; } /* Tick Contiki motes */ for (Mote mote : moteArray) { mote.tick(t); } /* Reschedule Contiki motes */ scheduleEventUnsafe(this, t+1); } }; private TimeEvent delayEvent = new TimeEvent(0) { public void execute(long t) { /*logger.info("Delay at: " + t);*/ if (delayTime == 0) { return; } try { Thread.sleep(delayTime); } catch (InterruptedException e) { } scheduleEventUnsafe(this, t+1); } }; private void recreateTickLists() { /* Tick MSP motes separately */ ArrayList<Mote> emulatedMotes = new ArrayList<Mote>(); ArrayList<Mote> contikiMotes = new ArrayList<Mote>(); for (Mote mote: motes) { /* TODO: fixe an emulatedMote generic class */ if (mote.getType().getClass().toString().contains(".mspmote.")) { emulatedMotes.add(mote); } else if (mote.getType().getClass().toString().contains(".avrmote.")) { emulatedMotes.add(mote); } else { contikiMotes.add(mote); } } emulatedMoteArray = emulatedMotes.toArray(new Mote[emulatedMotes.size()]); moteArray = contikiMotes.toArray(new Mote[contikiMotes.size()]); } private boolean rescheduleEvents = false; public void run() { long lastStartTime = System.currentTimeMillis(); logger.info("Simulation main loop started, system time: " + lastStartTime); isRunning = true; /* Schedule tick events */ scheduleEventUnsafe(tickMotesEvent, currentSimulationTime); scheduleEventUnsafe(tickemulatedMotesEvent, currentSimulationTime); scheduleEventUnsafe(delayEvent, currentSimulationTime); /* Simulation starting */ this.setChanged(); this.notifyObservers(this); recreateTickLists(); boolean increasedTime; try { TimeEvent nextEvent; while (isRunning) { if (rescheduleEvents) { rescheduleEvents = false; scheduleEventUnsafe(tickMotesEvent, currentSimulationTime); scheduleEventUnsafe(tickemulatedMotesEvent, currentSimulationTime); scheduleEventUnsafe(delayEvent, currentSimulationTime); } nextEvent = eventQueue.popFirst(); if (nextEvent == null) { throw new RuntimeException("No more events"); } increasedTime = nextEvent.time > currentSimulationTime; currentSimulationTime = nextEvent.time; nextEvent.execute(currentSimulationTime); /* Notify tick observers */ if (increasedTime) { tickObservable.allTicksPerformed(); } if (stopSimulation) { isRunning = false; } } } catch (IllegalArgumentException e) { logger.warn("llegalArgumentException:" + e); } catch (IllegalMonitorStateException e) { logger.warn("IllegalMonitorStateException:" + e); } catch (RuntimeException e) { if (e.getClass().getName().contains("IllegalStateException")) { /* XXX Change exception type */ /* MSPSim memory alignment exception */ logger.fatal("MSPSim detected memory alignment error: " + e); } else { logger.warn("Simulation stopped for unknown reason: " + e); e.printStackTrace(); } } isRunning = false; simulationThread = null; stopSimulation = false; // Notify observers simulation has stopped this.setChanged(); this.notifyObservers(this); logger.info("Simulation main loop stopped, system time: " + System.currentTimeMillis() + "\tDuration: " + (System.currentTimeMillis() - lastStartTime) + " ms"); } /** * Creates a new simulation with a delay time of 100 ms. */ public Simulation(GUI gui) { myGUI = gui; } /** * Starts this simulation (notifies observers). */ public void startSimulation() { if (!isRunning()) { isRunning = true; simulationThread = new Thread(this); simulationThread.start(); } } /** * Stops this simulation (notifies observers). */ public void stopSimulation() { if (isRunning()) { stopSimulation = true; /* Wait until simulation stops */ if (Thread.currentThread() != simulationThread) { try { if (simulationThread != null) { simulationThread.join(); } } catch (InterruptedException e) { } } } } /** * Starts simulation if stopped, ticks all motes once, and finally stops * simulation again. */ public void tickSimulation() { addTickObserver(new Observer() { public void update(Observable obs, Object obj) { stopSimulation(); deleteTickObserver(this); } }); startSimulation(); } /** * @return GUI holding this simulation */ public GUI getGUI() { return myGUI; } /** * @return Random seed */ public long getRandomSeed() { return randomSeed; } /** * @param randomSeed Random seed */ public void setRandomSeed(long randomSeed) { this.randomSeed = randomSeed; randomGenerator.setSeed(randomSeed); logger.info("Simulation random seed: " + randomSeed); } /** * @param generated Autogenerated random seed at simulation load */ public void setRandomSeedGenerated(boolean generated) { this.randomSeedGenerated = generated; } /** * @return Autogenerated random seed at simulation load */ public boolean getRandomSeedGenerated() { return randomSeedGenerated; } public Random getRandomGenerator() { return randomGenerator; } /** * @return Maximum mote startup delay */ public int getDelayedMoteStartupTime() { return maxMoteStartupDelay; } /** * @param maxMoteStartupDelay Maximum mote startup delay */ public void setDelayedMoteStartupTime(int maxMoteStartupDelay) { this.maxMoteStartupDelay = Math.max(0, maxMoteStartupDelay); } /** * Returns the current simulation config represented by XML elements. This * config also includes the current radio medium, all mote types and motes. * * @return Current simulation config */ public Collection<Element> getConfigXML() { Vector<Element> config = new Vector<Element>(); Element element; // Title element = new Element("title"); element.setText(title); config.add(element); // Delay time element = new Element("delaytime"); element.setText(Integer.toString(delayTime)); config.add(element); // Tick time element = new Element("ticktime"); element.setText(Integer.toString(tickTime)); config.add(element); // Random seed element = new Element("randomseed"); if (randomSeedGenerated) { element.setText("generated"); } else { element.setText(Long.toString(getRandomSeed())); } config.add(element); // Max mote startup delay element = new Element("motedelay"); element.setText(Integer.toString(maxMoteStartupDelay)); config.add(element); // Radio Medium element = new Element("radiomedium"); element.setText(currentRadioMedium.getClass().getName()); Collection radioMediumXML = currentRadioMedium.getConfigXML(); if (radioMediumXML != null) { element.addContent(radioMediumXML); } config.add(element); // Mote types for (MoteType moteType : getMoteTypes()) { element = new Element("motetype"); element.setText(moteType.getClass().getName()); Collection moteTypeXML = moteType.getConfigXML(); if (moteTypeXML != null) { element.addContent(moteTypeXML); } config.add(element); } // Motes for (Mote mote : motes) { element = new Element("mote"); element.setText(mote.getClass().getName()); Collection moteXML = mote.getConfigXML(); if (moteXML != null) { element.addContent(moteXML); } config.add(element); } return config; } /** * Sets the current simulation config depending on the given XML elements. * * @see #getConfigXML() * @param configXML * Config XML elements * @param visAvailable * True if simulation is allowed to show visualizers while loading * the given config * @return True if simulation config set successfully * @throws Exception * If configuration could not be loaded */ public boolean setConfigXML(Collection<Element> configXML, boolean visAvailable) throws Exception { // Parse elements for (Element element : configXML) { // Title if (element.getName().equals("title")) { title = element.getText(); } // Delay time if (element.getName().equals("delaytime")) { delayTime = Integer.parseInt(element.getText()); } // Tick time if (element.getName().equals("ticktime")) { tickTime = Integer.parseInt(element.getText()); } // Random seed if (element.getName().equals("randomseed")) { if (element.getText().equals("generated")) { randomSeedGenerated = true; setRandomSeed(new Random().nextLong()); } else { setRandomSeed(Long.parseLong(element.getText())); } } // Max mote startup delay if (element.getName().equals("motedelay")) { maxMoteStartupDelay = Integer.parseInt(element.getText()); } // Radio medium if (element.getName().equals("radiomedium")) { String radioMediumClassName = element.getText().trim(); Class<? extends RadioMedium> radioMediumClass = myGUI.tryLoadClass( this, RadioMedium.class, radioMediumClassName); if (radioMediumClass != null) { // Create radio medium specified in config try { currentRadioMedium = RadioMedium.generateRadioMedium(radioMediumClass, this); } catch (Exception e) { currentRadioMedium = null; logger.warn("Could not load radio medium class: " + radioMediumClassName); } } // Show configure simulation dialog boolean createdOK = false; if (visAvailable) { createdOK = CreateSimDialog.showDialog(GUI.getTopParentContainer(), this); } else { createdOK = true; } if (!createdOK) { logger.debug("Simulation not created, aborting"); throw new Exception("Load aborted by user"); } // Check if radio medium specific config should be applied if (radioMediumClassName.equals(currentRadioMedium.getClass().getName())) { currentRadioMedium.setConfigXML(element.getChildren(), visAvailable); } else { logger.info("Radio Medium changed - ignoring radio medium specific config"); } } // Mote type if (element.getName().equals("motetype")) { String moteTypeClassName = element.getText().trim(); Class<? extends MoteType> moteTypeClass = myGUI.tryLoadClass(this, MoteType.class, moteTypeClassName); if (moteTypeClass == null) { logger.fatal("Could not load mote type class: " + moteTypeClassName); return false; } MoteType moteType = moteTypeClass.getConstructor((Class[]) null) .newInstance(); boolean createdOK = moteType.setConfigXML(this, element.getChildren(), visAvailable); if (createdOK) { addMoteType(moteType); } else { logger .fatal("Mote type was not created: " + element.getText().trim()); throw new Exception("All mote types were not recreated"); } } // Mote if (element.getName().equals("mote")) { Class<? extends Mote> moteClass = myGUI.tryLoadClass(this, Mote.class, element.getText().trim()); Mote mote = moteClass.getConstructor((Class[]) null).newInstance((Object[]) null); if (mote.setConfigXML(this, element.getChildren(), visAvailable)) { addMote(mote); } else { logger.fatal("Mote was not created: " + element.getText().trim()); throw new Exception("All motes were not recreated"); } } } setChanged(); notifyObservers(this); return true; } /** * Removes a mote from this simulation * * @param mote * Mote to remove */ public void removeMote(final Mote mote) { if (!isRunning()) { /* Simulation is stopped, remove mote immediately */ motes.remove(mote); currentRadioMedium.unregisterMote(mote, this); myGUI.closeMotePlugins(mote); this.setChanged(); this.notifyObservers(this); return; } /* Simulation is running, remove mote in simulation loop */ TimeEvent removeNewMoteEvent = new TimeEvent(0) { public void execute(long t) { motes.remove(mote); currentRadioMedium.unregisterMote(mote, Simulation.this); recreateTickLists(); Simulation.this.setChanged(); Simulation.this.notifyObservers(this); } }; scheduleEvent(removeNewMoteEvent, Simulation.this.getSimulationTime()); } /** * Adds a mote to this simulation * * @param mote * Mote to add */ public void addMote(final Mote mote) { if (maxMoteStartupDelay > 0 && mote.getInterfaces().getClock() != null) { mote.getInterfaces().getClock().setDrift( -randomGenerator.nextInt(maxMoteStartupDelay) ); } if (!isRunning()) { /* Simulation is stopped, add mote immediately */ motes.add(mote); currentRadioMedium.registerMote(mote, this); this.setChanged(); this.notifyObservers(this); return; } /* Simulation is running, add mote in simulation loop */ TimeEvent addNewMoteEvent = new TimeEvent(0) { public void execute(long t) { motes.add(mote); currentRadioMedium.registerMote(mote, Simulation.this); recreateTickLists(); Simulation.this.setChanged(); Simulation.this.notifyObservers(this); } }; scheduleEvent(addNewMoteEvent, Simulation.this.getSimulationTime()); } /** * Get a mote from this simulation. * * @param pos * Internal list position of mote * @return Mote */ public Mote getMote(int pos) { return motes.get(pos); } /** * Returns number of motes in this simulation. * * @return Number of motes */ public int getMotesCount() { return motes.size(); } /** * Returns all motes in this simulation. * * @return Motes */ public Mote[] getMotes() { Mote[] arr = new Mote[motes.size()]; motes.toArray(arr); return arr; } /** * Returns all mote types in simulation. * * @return All mote types */ public Vector<MoteType> getMoteTypes() { return moteTypes; } /** * Returns mote type with given identifier. * * @param identifier * Mote type identifier * @return Mote type or null if not found */ public MoteType getMoteType(String identifier) { for (MoteType moteType : getMoteTypes()) { if (moteType.getIdentifier().equals(identifier)) { return moteType; } } return null; } /** * Adds given mote type to simulation. * * @param newMoteType Mote type */ public void addMoteType(MoteType newMoteType) { moteTypes.add(newMoteType); this.setChanged(); this.notifyObservers(this); } /** * Set delay time to delayTime. When all motes have been ticked, the * simulation waits for this time before ticking again. * * @param delayTime * New delay time (ms) */ public void setDelayTime(int delayTime) { this.delayTime = delayTime; rescheduleEvents = true; this.setChanged(); this.notifyObservers(this); } /** * Returns current delay time. * * @return Delay time (ms) */ public int getDelayTime() { return delayTime; } /** * Set simulation time to simulationTime. * * @param simulationTime * New simulation time (ms) */ public void setSimulationTime(int simulationTime) { currentSimulationTime = simulationTime; this.setChanged(); this.notifyObservers(this); } /** * Returns current simulation time. * * @return Simulation time (ms) */ public long getSimulationTime() { return currentSimulationTime; } /** * Set tick time to tickTime. The tick time is the simulated time every tick * takes. When all motes have been ticked, current simulation time is * increased with tickTime. Default tick time is 1 ms. * * @see #getTickTime() * @see #getTickTimeInSeconds() * @param tickTime * New tick time (ms) */ public void setTickTime(int tickTime) { this.tickTime = tickTime; this.setChanged(); this.notifyObservers(this); } /** * Changes radio medium of this simulation to the given. * * @param radioMedium * New radio medium */ public void setRadioMedium(RadioMedium radioMedium) { // Remove current radio medium from observing motes if (currentRadioMedium != null) { for (int i = 0; i < motes.size(); i++) { currentRadioMedium.unregisterMote(motes.get(i), this); } } // Change current radio medium to new one if (radioMedium == null) { logger.fatal("Radio medium could not be created!"); return; } this.currentRadioMedium = radioMedium; // Add all current motes to the new radio medium for (int i = 0; i < motes.size(); i++) { currentRadioMedium.registerMote(motes.get(i), this); } } /** * Get currently used radio medium. * * @return Currently used radio medium */ public RadioMedium getRadioMedium() { return currentRadioMedium; } /** * Get current tick time (ms). * * @see #setTickTime(int) * @return Current tick time (ms) */ public int getTickTime() { return tickTime; } /** * Get current tick time (seconds). * * @see #setTickTime(int) * @return Current tick time (seconds) */ public double getTickTimeInSeconds() { return (tickTime) / 1000.0; } /** * Return true is simulation is running. * * @return True if simulation is running */ public boolean isRunning() { return isRunning && simulationThread != null; } /** * Get current simulation title (short description). * * @return Title */ public String getTitle() { return title; } /** * Set simulation title. * * @param title * New title */ public void setTitle(String title) { this.title = title; } }
tools/cooja/java/se/sics/cooja/Simulation.java
/* * Copyright (c) 2006, Swedish Institute of Computer Science. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. 2. Redistributions in * binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. 3. Neither the name of the * Institute nor the names of its contributors may be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * $Id: Simulation.java,v 1.41 2009/02/23 08:33:23 joxe Exp $ */ package se.sics.cooja; import java.util.*; import org.apache.log4j.Logger; import org.jdom.*; import se.sics.cooja.dialogs.*; /** * A simulation consists of a number of motes and mote types. * * The motes in the simulation are ticked every millisecond. * * A simulation is observable: * changed simulation state, added or deleted motes etc are observed. * To track mote changes, observe the mote (interfaces) itself. * * @author Fredrik sterlind */ public class Simulation extends Observable implements Runnable { private Vector<Mote> motes = new Vector<Mote>(); private Vector<MoteType> moteTypes = new Vector<MoteType>(); private int delayTime = 5; private long currentSimulationTime = 0; private int tickTime = 1; private String title = null; private RadioMedium currentRadioMedium = null; private static Logger logger = Logger.getLogger(Simulation.class); private boolean isRunning = false; private boolean stopSimulation = false; private Thread simulationThread = null; private GUI myGUI = null; private long randomSeed = 123456; private boolean randomSeedGenerated = false; private int maxMoteStartupDelay = 1000; private Random randomGenerator = new Random(); // Tick observable private class TickObservable extends Observable { private void allTicksPerformed() { setChanged(); notifyObservers(); } } private TickObservable tickObservable = new TickObservable(); /** * Add tick observer. This observer is notified once every tick loop, that is, * when all motes have been ticked. * * @see #deleteTickObserver(Observer) * @param newObserver * New observer */ public void addTickObserver(Observer newObserver) { tickObservable.addObserver(newObserver); } /** * Delete an existing tick observer. * * @see #addTickObserver(Observer) * @param observer * Observer to delete */ public void deleteTickObserver(Observer observer) { tickObservable.deleteObserver(observer); } protected void scheduleEventUnsafe(TimeEvent e, long time) { eventQueue.addEvent(e, time); } /** * Schedule event to be handled by event loop. * * @param e Event * @param time Simulated time */ public void scheduleEvent(TimeEvent e, long time) { if (Thread.currentThread() == simulationThread) { eventQueue.addEvent(e, time); } else { eventQueue.addEventUnsorted(e, time); } } private EventQueue eventQueue = new EventQueue(); private Mote[] emulatedMoteArray; private TimeEvent tickemulatedMotesEvent = new TimeEvent(0) { public void execute(long t) { /*logger.info("MSP motes tick at: " + t);*/ if (emulatedMoteArray.length == 0) { return; } /* Tick MSP motes */ boolean wantMoreTicks = true; while (wantMoreTicks) { /* Tick all MSP motes until none need more ticks */ wantMoreTicks = false; for (Mote element : emulatedMoteArray) { if (element.tick(currentSimulationTime)) { wantMoreTicks = true; } } } /* Reschedule MSP motes */ scheduleEventUnsafe(this, t+1); } }; private Mote[] moteArray; private TimeEvent tickMotesEvent = new TimeEvent(0) { public void execute(long t) { /*logger.info("Contiki motes tick at: " + t);*/ if (moteArray.length == 0) { return; } /* Tick Contiki motes */ for (Mote mote : moteArray) { mote.tick(t); } /* Reschedule Contiki motes */ scheduleEventUnsafe(this, t+1); } }; private TimeEvent delayEvent = new TimeEvent(0) { public void execute(long t) { /*logger.info("Delay at: " + t);*/ if (delayTime == 0) { return; } try { Thread.sleep(delayTime); } catch (InterruptedException e) { } scheduleEventUnsafe(this, t+1); } }; private void recreateTickLists() { /* Tick MSP motes separately */ ArrayList<Mote> emulatedMotes = new ArrayList<Mote>(); ArrayList<Mote> contikiMotes = new ArrayList<Mote>(); for (Mote mote: motes) { /* TODO: fixe an emulatedMote generic class */ if (mote.getType().getClass().toString().contains(".mspmote.")) { emulatedMotes.add(mote); } else if (mote.getType().getClass().toString().contains(".avrmote.")) { emulatedMotes.add(mote); } else { contikiMotes.add(mote); } } emulatedMoteArray = emulatedMotes.toArray(new Mote[emulatedMotes.size()]); moteArray = contikiMotes.toArray(new Mote[contikiMotes.size()]); } private boolean rescheduleEvents = false; public void run() { long lastStartTime = System.currentTimeMillis(); logger.info("Simulation main loop started, system time: " + lastStartTime); isRunning = true; /* Schedule tick events */ scheduleEventUnsafe(tickMotesEvent, currentSimulationTime); scheduleEventUnsafe(tickemulatedMotesEvent, currentSimulationTime); scheduleEventUnsafe(delayEvent, currentSimulationTime); /* Simulation starting */ this.setChanged(); this.notifyObservers(this); recreateTickLists(); boolean increasedTime; try { TimeEvent nextEvent; while (isRunning) { if (rescheduleEvents) { rescheduleEvents = false; scheduleEventUnsafe(tickMotesEvent, currentSimulationTime); scheduleEventUnsafe(tickemulatedMotesEvent, currentSimulationTime); scheduleEventUnsafe(delayEvent, currentSimulationTime); } nextEvent = eventQueue.popFirst(); if (nextEvent == null) { throw new RuntimeException("No more events"); } increasedTime = nextEvent.time > currentSimulationTime; currentSimulationTime = nextEvent.time; nextEvent.execute(currentSimulationTime); /* Notify tick observers */ if (increasedTime) { tickObservable.allTicksPerformed(); } if (stopSimulation) { isRunning = false; } } } catch (IllegalArgumentException e) { logger.warn("llegalArgumentException:" + e); } catch (IllegalMonitorStateException e) { logger.warn("IllegalMonitorStateException:" + e); } catch (RuntimeException e) { if (e.getClass().getName().contains("IllegalStateException")) { /* XXX Change exception type */ /* MSPSim memory alignment exception */ logger.fatal("MSPSim detected memory alignment error: " + e); } else { logger.warn("Simulation stopped for unknown reason: " + e); e.printStackTrace(); } } isRunning = false; simulationThread = null; stopSimulation = false; // Notify observers simulation has stopped this.setChanged(); this.notifyObservers(this); logger.info("Simulation main loop stopped, system time: " + System.currentTimeMillis() + "\tDuration: " + (System.currentTimeMillis() - lastStartTime) + " ms"); } /** * Creates a new simulation with a delay time of 100 ms. */ public Simulation(GUI gui) { myGUI = gui; } /** * Starts this simulation (notifies observers). */ public void startSimulation() { if (!isRunning()) { isRunning = true; simulationThread = new Thread(this); simulationThread.start(); } } /** * Stops this simulation (notifies observers). */ public void stopSimulation() { if (isRunning()) { stopSimulation = true; /* Wait until simulation stops */ if (Thread.currentThread() != simulationThread) { try { if (simulationThread != null) { simulationThread.join(); } } catch (InterruptedException e) { } } } } /** * Starts simulation if stopped, ticks all motes once, and finally stops * simulation again. */ public void tickSimulation() { addTickObserver(new Observer() { public void update(Observable obs, Object obj) { stopSimulation(); deleteTickObserver(this); } }); startSimulation(); } /** * @return GUI holding this simulation */ public GUI getGUI() { return myGUI; } /** * @return Random seed */ public long getRandomSeed() { return randomSeed; } /** * @param randomSeed Random seed */ public void setRandomSeed(long randomSeed) { this.randomSeed = randomSeed; randomGenerator.setSeed(randomSeed); logger.info("Simulation random seed: " + randomSeed); } /** * @param generated Autogenerated random seed at simulation load */ public void setRandomSeedGenerated(boolean generated) { this.randomSeedGenerated = generated; } /** * @return Autogenerated random seed at simulation load */ public boolean getRandomSeedGenerated() { return randomSeedGenerated; } public Random getRandomGenerator() { return randomGenerator; } /** * @return Maximum mote startup delay */ public int getDelayedMoteStartupTime() { return maxMoteStartupDelay; } /** * @param maxMoteStartupDelay Maximum mote startup delay */ public void setDelayedMoteStartupTime(int maxMoteStartupDelay) { this.maxMoteStartupDelay = Math.max(0, maxMoteStartupDelay); } /** * Returns the current simulation config represented by XML elements. This * config also includes the current radio medium, all mote types and motes. * * @return Current simulation config */ public Collection<Element> getConfigXML() { Vector<Element> config = new Vector<Element>(); Element element; // Title element = new Element("title"); element.setText(title); config.add(element); // Delay time element = new Element("delaytime"); element.setText(Integer.toString(delayTime)); config.add(element); // Tick time element = new Element("ticktime"); element.setText(Integer.toString(tickTime)); config.add(element); // Random seed element = new Element("randomseed"); if (randomSeedGenerated) { element.setText("generated"); } else { element.setText(Long.toString(getRandomSeed())); } config.add(element); // Max mote startup delay element = new Element("motedelay"); element.setText(Integer.toString(maxMoteStartupDelay)); config.add(element); // Radio Medium element = new Element("radiomedium"); element.setText(currentRadioMedium.getClass().getName()); Collection radioMediumXML = currentRadioMedium.getConfigXML(); if (radioMediumXML != null) { element.addContent(radioMediumXML); } config.add(element); // Mote types for (MoteType moteType : getMoteTypes()) { element = new Element("motetype"); element.setText(moteType.getClass().getName()); Collection moteTypeXML = moteType.getConfigXML(); if (moteTypeXML != null) { element.addContent(moteTypeXML); } config.add(element); } // Motes for (Mote mote : motes) { element = new Element("mote"); element.setText(mote.getClass().getName()); Collection moteXML = mote.getConfigXML(); if (moteXML != null) { element.addContent(moteXML); } config.add(element); } return config; } /** * Sets the current simulation config depending on the given XML elements. * * @see #getConfigXML() * @param configXML * Config XML elements * @param visAvailable * True if simulation is allowed to show visualizers while loading * the given config * @return True if simulation config set successfully * @throws Exception * If configuration could not be loaded */ public boolean setConfigXML(Collection<Element> configXML, boolean visAvailable) throws Exception { // Parse elements for (Element element : configXML) { // Title if (element.getName().equals("title")) { title = element.getText(); } // Delay time if (element.getName().equals("delaytime")) { delayTime = Integer.parseInt(element.getText()); } // Tick time if (element.getName().equals("ticktime")) { tickTime = Integer.parseInt(element.getText()); } // Random seed if (element.getName().equals("randomseed")) { if (element.getText().equals("generated")) { randomSeedGenerated = true; setRandomSeed(new Random().nextLong()); } else { setRandomSeed(Long.parseLong(element.getText())); } } // Max mote startup delay if (element.getName().equals("motedelay")) { maxMoteStartupDelay = Integer.parseInt(element.getText()); } // Radio medium if (element.getName().equals("radiomedium")) { String radioMediumClassName = element.getText().trim(); Class<? extends RadioMedium> radioMediumClass = myGUI.tryLoadClass( this, RadioMedium.class, radioMediumClassName); if (radioMediumClass != null) { // Create radio medium specified in config try { currentRadioMedium = RadioMedium.generateRadioMedium( radioMediumClass, this); } catch (Exception e) { currentRadioMedium = null; logger.warn("Could not load radio medium class: " + radioMediumClassName); } } // Show configure simulation dialog boolean createdOK = false; if (visAvailable) { createdOK = CreateSimDialog.showDialog(GUI.getTopParentContainer(), this); } else { createdOK = true; } if (!createdOK) { logger.debug("Simulation not created, aborting"); throw new Exception("Load aborted by user"); } // Check if radio medium specific config should be applied if (radioMediumClassName .equals(currentRadioMedium.getClass().getName())) { currentRadioMedium.setConfigXML(element.getChildren(), visAvailable); } else { logger .info("Radio Medium changed - ignoring radio medium specific config"); } } // Mote type if (element.getName().equals("motetype")) { String moteTypeClassName = element.getText().trim(); Class<? extends MoteType> moteTypeClass = myGUI.tryLoadClass(this, MoteType.class, moteTypeClassName); if (moteTypeClass == null) { logger.fatal("Could not load mote type class: " + moteTypeClassName); return false; } MoteType moteType = moteTypeClass.getConstructor((Class[]) null) .newInstance(); boolean createdOK = moteType.setConfigXML(this, element.getChildren(), visAvailable); if (createdOK) { addMoteType(moteType); } else { logger .fatal("Mote type was not created: " + element.getText().trim()); throw new Exception("All mote types were not recreated"); } } // Mote if (element.getName().equals("mote")) { Class<? extends Mote> moteClass = myGUI.tryLoadClass(this, Mote.class, element.getText().trim()); Mote mote = moteClass.getConstructor((Class[]) null).newInstance((Object[]) null); if (mote.setConfigXML(this, element.getChildren(), visAvailable)) { addMote(mote); } else { logger.fatal("Mote was not created: " + element.getText().trim()); throw new Exception("All motes were not recreated"); } } } setChanged(); notifyObservers(this); return true; } /** * Removes a mote from this simulation * * @param mote * Mote to remove */ public void removeMote(final Mote mote) { if (!isRunning()) { /* Simulation is stopped, remove mote immediately */ motes.remove(mote); currentRadioMedium.unregisterMote(mote, this); myGUI.closeMotePlugins(mote); this.setChanged(); this.notifyObservers(this); return; } /* Simulation is running, remove mote in simulation loop */ TimeEvent removeNewMoteEvent = new TimeEvent(0) { public void execute(long t) { motes.remove(mote); currentRadioMedium.unregisterMote(mote, Simulation.this); recreateTickLists(); Simulation.this.setChanged(); Simulation.this.notifyObservers(this); } }; scheduleEvent(removeNewMoteEvent, Simulation.this.getSimulationTime()); } /** * Adds a mote to this simulation * * @param mote * Mote to add */ public void addMote(final Mote mote) { if (maxMoteStartupDelay > 0 && mote.getInterfaces().getClock() != null) { mote.getInterfaces().getClock().setDrift( -randomGenerator.nextInt(maxMoteStartupDelay) ); } if (!isRunning()) { /* Simulation is stopped, add mote immediately */ motes.add(mote); currentRadioMedium.registerMote(mote, this); this.setChanged(); this.notifyObservers(this); return; } /* Simulation is running, add mote in simulation loop */ TimeEvent addNewMoteEvent = new TimeEvent(0) { public void execute(long t) { motes.add(mote); currentRadioMedium.registerMote(mote, Simulation.this); recreateTickLists(); Simulation.this.setChanged(); Simulation.this.notifyObservers(this); } }; scheduleEvent(addNewMoteEvent, Simulation.this.getSimulationTime()); } /** * Get a mote from this simulation. * * @param pos * Internal list position of mote * @return Mote */ public Mote getMote(int pos) { return motes.get(pos); } /** * Returns number of motes in this simulation. * * @return Number of motes */ public int getMotesCount() { return motes.size(); } /** * Returns all mote types in simulation. * * @return All mote types */ public Vector<MoteType> getMoteTypes() { return moteTypes; } /** * Returns mote type with given identifier. * * @param identifier * Mote type identifier * @return Mote type or null if not found */ public MoteType getMoteType(String identifier) { for (MoteType moteType : getMoteTypes()) { if (moteType.getIdentifier().equals(identifier)) { return moteType; } } return null; } /** * Adds given mote type to simulation. * * @param newMoteType Mote type */ public void addMoteType(MoteType newMoteType) { moteTypes.add(newMoteType); this.setChanged(); this.notifyObservers(this); } /** * Set delay time to delayTime. When all motes have been ticked, the * simulation waits for this time before ticking again. * * @param delayTime * New delay time (ms) */ public void setDelayTime(int delayTime) { this.delayTime = delayTime; rescheduleEvents = true; this.setChanged(); this.notifyObservers(this); } /** * Returns current delay time. * * @return Delay time (ms) */ public int getDelayTime() { return delayTime; } /** * Set simulation time to simulationTime. * * @param simulationTime * New simulation time (ms) */ public void setSimulationTime(int simulationTime) { currentSimulationTime = simulationTime; this.setChanged(); this.notifyObservers(this); } /** * Returns current simulation time. * * @return Simulation time (ms) */ public long getSimulationTime() { return currentSimulationTime; } /** * Set tick time to tickTime. The tick time is the simulated time every tick * takes. When all motes have been ticked, current simulation time is * increased with tickTime. Default tick time is 1 ms. * * @see #getTickTime() * @see #getTickTimeInSeconds() * @param tickTime * New tick time (ms) */ public void setTickTime(int tickTime) { this.tickTime = tickTime; this.setChanged(); this.notifyObservers(this); } /** * Changes radio medium of this simulation to the given. * * @param radioMedium * New radio medium */ public void setRadioMedium(RadioMedium radioMedium) { // Remove current radio medium from observing motes if (currentRadioMedium != null) { for (int i = 0; i < motes.size(); i++) { currentRadioMedium.unregisterMote(motes.get(i), this); } } // Change current radio medium to new one if (radioMedium == null) { logger.fatal("Radio medium could not be created!"); return; } this.currentRadioMedium = radioMedium; // Add all current motes to the new radio medium for (int i = 0; i < motes.size(); i++) { currentRadioMedium.registerMote(motes.get(i), this); } } /** * Get currently used radio medium. * * @return Currently used radio medium */ public RadioMedium getRadioMedium() { return currentRadioMedium; } /** * Get current tick time (ms). * * @see #setTickTime(int) * @return Current tick time (ms) */ public int getTickTime() { return tickTime; } /** * Get current tick time (seconds). * * @see #setTickTime(int) * @return Current tick time (seconds) */ public double getTickTimeInSeconds() { return (tickTime) / 1000.0; } /** * Return true is simulation is running. * * @return True if simulation is running */ public boolean isRunning() { return isRunning && simulationThread != null; } /** * Get current simulation title (short description). * * @return Title */ public String getTitle() { return title; } /** * Set simulation title. * * @param title * New title */ public void setTitle(String title) { this.title = title; } }
added method returning all motes, instead of using getMote(int) method
tools/cooja/java/se/sics/cooja/Simulation.java
added method returning all motes, instead of using getMote(int) method
Java
bsd-3-clause
63af36a758949a589859cc2146c8fe71eb89e385
0
bnorm-software/infinite
package com.bnorm.fsm4j; /** * The base implementation of a transition. * * @param <S> the class type of the states. * @author Brian Norman * @version 1.0 * @since 1.0 */ class TransitionBase<S extends State> implements Transition<S> { /** The source state of the transition. */ private final S source; /** The destination state of the transition. */ private final S destination; /** * Constructs a new transition from the specified source and destination states. * * @param source the source state of the transition. * @param destination the destination state of the transition. */ TransitionBase(S source, S destination) { this.source = source; this.destination = destination; } @Override public S getSource() { return source; } @Override public S getDestination() { return destination; } @Override public String toString() { return "TransitionBase[" + source + "->" + destination + "]"; } }
src/main/java/com/bnorm/fsm4j/TransitionBase.java
package com.bnorm.fsm4j; /** * The base implementation of a transition. * * @param <S> the class type of the states. * @author Brian Norman * @version 1.0 * @since 1.0 */ class TransitionBase<S extends State> implements Transition<S> { /** The source state of the transition. */ private final S source; /** The destination state of the transition. */ private S destination; /** * Constructs a new transition from the specified source and destination states. * * @param source the source state of the transition. * @param destination the destination state of the transition. */ TransitionBase(S source, S destination) { this.source = source; this.destination = destination; } @Override public S getSource() { return source; } @Override public S getDestination() { return destination; } @Override public String toString() { return "TransitionBase[" + source + "->" + destination + "]"; } }
Increased unmodifiable nature of the transition base class
src/main/java/com/bnorm/fsm4j/TransitionBase.java
Increased unmodifiable nature of the transition base class
Java
bsd-3-clause
e0e1432e504afef2742eff13b00523827618658d
0
yfpeng/pengyifan-bioc
package com.pengyifan.bioc; import java.util.Map; import java.util.Optional; public interface BioCInfons { /** * Returns the information. * * @return the information. */ Map<String, String> getInfons(); /** * Clears all information. */ default void clearInfons() { getInfons().clear(); } /** * Associates the specified value with the specified key. * * @param key key with which the specified value is to be associated * @param value value to be associated with the specified key */ default void putInfon(String key, String value) { getInfons().put(key, value); } /** * Copies all of the mappings from the specified infons. * * @param infons the information */ default void putAllInfos(Map<String, String> infons) { getInfons().putAll(infons); } /** * Removes the value for a key if it is present * (optional operation). * * @param key key with which the specified value is to be associated */ default void removeInfon(String key) { getInfons().remove(key); } /** * Sets the information. * * @param infons the information */ default void setInfons(Map<String, String> infons) { clearInfons(); getInfons().putAll(infons); } /** * Returns the value to which the specified key is mapped, or null if this * {@code infons} contains no mapping for the key. * * @param key the key whose associated value is to be returned * @return the value to which the specified key is mapped */ default Optional<String> getInfon(String key) { return Optional.ofNullable(getInfons().get(key)); } }
src/main/java/com/pengyifan/bioc/BioCInfons.java
package com.pengyifan.bioc; import java.util.Map; import java.util.Optional; public interface BioCInfons { /** * Returns the information. * * @return the information. */ Map<String, String> getInfons(); /** * Clears all information. */ default void clearInfons() { getInfons().clear(); } /** * Associates the specified value with the specified key. * * @param key key with which the specified value is to be associated * @param value value to be associated with the specified key */ default void putInfon(String key, String value) { getInfons().put(key, value); } /** * Removes the value for a key if it is present * (optional operation). * * @param key key with which the specified value is to be associated */ default void removeInfon(String key) { getInfons().remove(key); } /** * Sets the information. * * @param infons the information */ default void setInfons(Map<String, String> infons) { clearInfons(); getInfons().putAll(infons); } /** * Returns the value to which the specified key is mapped, or null if this * {@code infons} contains no mapping for the key. * * @param key the key whose associated value is to be returned * @return the value to which the specified key is mapped */ default Optional<String> getInfon(String key) { return Optional.ofNullable(getInfons().get(key)); } }
add map information to infons
src/main/java/com/pengyifan/bioc/BioCInfons.java
add map information to infons
Java
mit
d69434e0179498b39de6a607c002c71fb0702a02
0
budowski/iNaturalistAndroid,inaturalist/iNaturalistAndroid,inaturalist/iNaturalistAndroid,inaturalist/iNaturalistAndroid,inaturalist/iNaturalistAndroid
package org.inaturalist.android; import java.lang.ref.WeakReference; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import org.apache.commons.lang3.StringUtils; import org.inaturalist.android.INaturalistApp.INotificationCallback; import com.cocosw.bottomsheet.BottomSheet; import com.flurry.android.FlurryAgent; import com.handmark.pulltorefresh.library.PullToRefreshBase; import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener; import com.handmark.pulltorefresh.library.PullToRefreshListView; import com.koushikdutta.urlimageviewhelper.UrlImageViewHelper; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.content.DialogInterface; import android.os.AsyncTask; import android.os.Handler; import android.content.BroadcastReceiver; import android.content.ContentUris; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.support.v7.app.ActionBar; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.view.View.OnClickListener; import android.view.ViewTreeObserver.OnGlobalLayoutListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ImageView; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.SimpleCursorAdapter; import android.widget.TextView; import android.widget.Toast; public class ObservationListActivity extends BaseFragmentActivity implements OnItemClickListener, INotificationCallback, DialogInterface.OnClickListener { public static String TAG = "INAT:ObservationListActivity"; private PullToRefreshListView mPullRefreshListView; private SyncCompleteReceiver mSyncCompleteReceiver; private int mLastIndex; private int mLastTop; private ActionBar mTopActionBar; private TextView mSyncObservations; private ObservationCursorAdapter mAdapter; private TextView mTitleBar; private ActivityHelper mHelper; private String mLastMessage; private static final int COMMENTS_IDS_REQUEST_CODE = 100; private static final int OBSERVATION_LIST_LOADER = 0x01; private INaturalistApp mApp; @Override protected void onStart() { super.onStart(); FlurryAgent.onStartSession(this, INaturalistApp.getAppContext().getString(R.string.flurry_api_key)); FlurryAgent.logEvent(this.getClass().getSimpleName()); } @Override protected void onStop() { super.onStop(); FlurryAgent.onEndSession(this); } private boolean isNetworkAvailable() { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); } @Override public void onClick(DialogInterface dialogInterface, int i) { // User chose to cancel sync mApp.setCancelSync(true); refreshSyncBar(); } private class SyncCompleteReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Log.i(TAG, "Got ACTION_SYNC_COMPLETE"); mPullRefreshListView.onRefreshComplete(); mPullRefreshListView.refreshDrawableState(); mHelper.stopLoading(); ObservationCursorAdapter adapter = mAdapter; adapter.refreshCursor(); refreshSyncBar(); if (mApp.loggedIn() && !mApp.getIsSyncing() && (mAdapter.getCount() == 0)) { // Show a "no observations" message ((TextView)findViewById(android.R.id.empty)).setText(R.string.no_observations_yet); } if ((mLastMessage != null) && (mLastMessage.length() > 0)) { Toast.makeText(getApplicationContext(), mLastMessage, Toast.LENGTH_LONG).show(); mLastMessage = null; } } } public static Intent createIntent(Context context) { Intent i = new Intent(context, ObservationListActivity.class); i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); return i; } @Override protected void onDestroy() { super.onDestroy(); if (mSyncCompleteReceiver != null) { Log.i(TAG, "Unregistering ACTION_SYNC_COMPLETE"); try { unregisterReceiver(mSyncCompleteReceiver); unregisterReceiver(mConnectivityListener); } catch (Exception exc) { exc.printStackTrace(); } mSyncCompleteReceiver = null; mConnectivityListener = null; } } /** Shows the sync required bottom bar, if needed */ private void refreshSyncBar() { int syncCount = 0; int photoSyncCount = 0; if (mApp.getAutoSync()) { // Auto sync is on - no need for manual sync mSyncObservations.setVisibility(View.GONE); return; } Cursor c = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION, "((_updated_at > _synced_at AND _synced_at IS NOT NULL) OR (_synced_at IS NULL)) AND (_updated_at > _created_at)", null, Observation.SYNC_ORDER); syncCount = c.getCount(); c.close(); Cursor opc = getContentResolver().query(ObservationPhoto.CONTENT_URI, new String[]{ ObservationPhoto._ID, ObservationPhoto._OBSERVATION_ID, ObservationPhoto._PHOTO_ID, ObservationPhoto.PHOTO_URL, ObservationPhoto._UPDATED_AT, ObservationPhoto._SYNCED_AT }, "((photo_url IS NULL) AND (_updated_at IS NOT NULL) AND (_synced_at IS NULL)) OR " + "((photo_url IS NULL) AND (_updated_at IS NOT NULL) AND (_synced_at IS NOT NULL) AND (_updated_at > _synced_at))", null, ObservationPhoto._ID); photoSyncCount = opc.getCount(); opc.close(); if ((syncCount > 0) || (photoSyncCount > 0)) { mSyncObservations.setText(String.format(getResources().getString(R.string.sync_x_observations), (syncCount > 0 ? syncCount : photoSyncCount))); mSyncObservations.setVisibility(View.VISIBLE); } else { mSyncObservations.setVisibility(View.GONE); } } /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.observation_list); setTitle(R.string.observations); mHelper = new ActivityHelper(this); mApp = (INaturalistApp)getApplication(); mSyncObservations = (TextView) findViewById(R.id.sync_observations); mSyncObservations.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (!isNetworkAvailable()) { Toast.makeText(getApplicationContext(), R.string.not_connected, Toast.LENGTH_LONG).show(); return; } else if (!isLoggedIn()) { // User not logged-in - redirect to onboarding screen startActivity(new Intent(ObservationListActivity.this, OnboardingActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP)); return; } Intent serviceIntent = new Intent(INaturalistService.ACTION_SYNC, null, ObservationListActivity.this, INaturalistService.class); startService(serviceIntent); mSyncObservations.setVisibility(View.GONE); mHelper.loading(getResources().getString(R.string.syncing_observations), ObservationListActivity.this); } }); if (savedInstanceState != null) { mLastMessage = savedInstanceState.getString("mLastMessage"); } SharedPreferences pref = getSharedPreferences("iNaturalistPreferences", MODE_PRIVATE); String username = pref.getString("username", null); if (username == null) { if (!mApp.shownOnboarding()) { // Show login/onboarding screen mApp.setShownOnboarding(true); Intent intent = new Intent(this, OnboardingActivity.class); intent.putExtra(OnboardingActivity.SHOW_SKIP, true); startActivity(intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP)); } } refreshSyncBar(); mTopActionBar = getSupportActionBar(); View addButton = (View) findViewById(R.id.add_observation); addButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { new BottomSheet.Builder(ObservationListActivity.this).sheet(R.menu.observation_list_menu).listener(new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent intent; switch (which) { case R.id.camera: intent = new Intent(Intent.ACTION_INSERT, getIntent().getData(), ObservationListActivity.this, ObservationEditor.class); intent.putExtra(ObservationEditor.TAKE_PHOTO, true); startActivity(intent); break; case R.id.upload_photo: intent = new Intent(Intent.ACTION_INSERT, getIntent().getData(), ObservationListActivity.this, ObservationEditor.class); intent.putExtra(ObservationEditor.CHOOSE_PHOTO, true); startActivity(intent); break; case R.id.text: startActivity(new Intent(Intent.ACTION_INSERT, getIntent().getData(), ObservationListActivity.this, ObservationEditor.class)); break; } } }).show(); } }); INaturalistApp app = (INaturalistApp)(getApplication()); app.setNotificationCallback(this); Intent intent = getIntent(); if (intent.getData() == null) { intent.setData(Observation.CONTENT_URI); } mSyncCompleteReceiver = new SyncCompleteReceiver(); IntentFilter filter = new IntentFilter(INaturalistService.ACTION_SYNC_COMPLETE); Log.i(TAG, "Registering ACTION_SYNC_COMPLETE"); registerReceiver(mSyncCompleteReceiver, filter); mConnectivityListener = new ConnectivityBroadcastReceiver(); IntentFilter filter2 = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION); Log.i(TAG, "Registering CONNECTIVITY_ACTION"); registerReceiver(mConnectivityListener, filter2); mPullRefreshListView = (PullToRefreshListView) findViewById(R.id.observations_list); mPullRefreshListView.getLoadingLayoutProxy().setPullLabel(getResources().getString(R.string.pull_to_refresh)); mPullRefreshListView.getLoadingLayoutProxy().setReleaseLabel(getResources().getString(R.string.release_to_refresh)); mPullRefreshListView.getLoadingLayoutProxy().setRefreshingLabel(getResources().getString(R.string.refreshing)); mPullRefreshListView.setReleaseRatio(2.5f); // Set a listener to be invoked when the list should be refreshed. mPullRefreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() { @Override public void onRefresh(PullToRefreshBase<ListView> refreshView) { if (!isNetworkAvailable() || !isLoggedIn()) { Thread t = (new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } runOnUiThread(new Runnable() { @Override public void run() { mPullRefreshListView.onRefreshComplete(); } }); } })); t.start(); if (!isNetworkAvailable()) { Toast.makeText(getApplicationContext(), R.string.not_connected, Toast.LENGTH_LONG).show(); } else if (!isLoggedIn()) { Toast.makeText(getApplicationContext(), R.string.please_sign_in, Toast.LENGTH_LONG).show(); } return; } // Start sync Intent serviceIntent = new Intent(INaturalistService.ACTION_PULL_OBSERVATIONS, null, ObservationListActivity.this, INaturalistService.class); startService(serviceIntent); } }); onDrawerCreate(savedInstanceState); ListView actualListView = mPullRefreshListView.getRefreshableView(); // Need to use the Actual ListView when registering for Context Menu registerForContextMenu(actualListView); // Inform the list we provide context menus for items //getListView().setOnCreateContextMenuListener(this); SharedPreferences prefs = getSharedPreferences("iNaturalistPreferences", MODE_PRIVATE); String login = prefs.getString("username", null); // Perform a managed query. The Activity will handle closing and requerying the cursor // when needed. String conditions = "(_synced_at IS NULL"; if (login != null) { conditions += " OR user_login = '" + login + "'"; } conditions += ") AND (is_deleted = 0 OR is_deleted is NULL)"; // Don't show deleted observations Cursor cursor = getContentResolver().query(getIntent().getData(), Observation.PROJECTION, conditions, null, Observation.DEFAULT_SORT_ORDER); // Used to map notes entries from the database to views ObservationCursorAdapter adapter = new ObservationCursorAdapter( this, R.layout.list_item, cursor, new String[] { Observation.DESCRIPTION }, new int[] { R.id.subContent }); mAdapter = adapter; mPullRefreshListView.setEmptyView(findViewById(android.R.id.empty)); mPullRefreshListView.setAdapter(mAdapter); mPullRefreshListView.setOnItemClickListener(this); triggerSyncIfNeeded(); } private void triggerSyncIfNeeded() { boolean hasOldObs = hasOldObservations(); if ((mApp.getAutoSync() && !mApp.getIsSyncing()) || (hasOldObs)) { int syncCount = 0; if (!hasOldObs) { Cursor c = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION, "((_updated_at > _synced_at AND _synced_at IS NOT NULL) OR (_synced_at IS NULL) OR (is_deleted = 1))", null, Observation.SYNC_ORDER); syncCount = c.getCount(); c.close(); } // Trigger a sync (in case of auto-sync and unsynced obs OR when having old-style observations) if (hasOldObs || (syncCount > 0)) { Intent serviceIntent = new Intent(INaturalistService.ACTION_SYNC, null, ObservationListActivity.this, INaturalistService.class); startService(serviceIntent); } } } // Checks to see if there are any observations that have the "old" way of saving photos private boolean hasOldObservations() { Cursor c = getContentResolver().query(ObservationPhoto.CONTENT_URI, ObservationPhoto.PROJECTION, "(photo_filename IS NULL) AND (photo_url IS NULL)", null, ObservationPhoto.DEFAULT_SORT_ORDER); int count = c.getCount(); c.close(); return count > 0; } @SuppressLint("NewApi") @Override public void onPause() { super.onPause(); // save last position of list so we can resume there later // http://stackoverflow.com/questions/3014089/maintain-save-restore-scroll-position-when-returning-to-a-listview ListView lv = mPullRefreshListView.getRefreshableView(); mLastIndex = lv.getFirstVisiblePosition(); View v = lv.getChildAt(0); mLastTop = (v == null) ? 0 : v.getTop(); /* ObservationCursorAdapter adapter = mAdapter; adapter.notifyDataSetInvalidated(); if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB){ Cursor oldCursor = adapter.swapCursor(null); if ((oldCursor != null) && (!oldCursor.isClosed())) oldCursor.close(); } else { adapter.changeCursor(null); } */ super.onPause(); } @Override public void onResume() { super.onResume(); ListView lv = mPullRefreshListView.getRefreshableView(); lv.setSelectionFromTop(mLastIndex, mLastTop); refreshSyncBar(); ObservationCursorAdapter adapter = mAdapter; adapter.refreshCursor(); INaturalistApp app = (INaturalistApp)(getApplication()); if (app.getIsSyncing()) { // We're still syncing mHelper.stopLoading(); if ((mLastMessage != null) && (!mApp.getAutoSync())) mHelper.loading(mLastMessage, ObservationListActivity.this); app.setNotificationCallback(this); } (new Handler()).postDelayed(new Runnable() { @Override public void run() { if (mApp.loggedIn() && mApp.getIsSyncing() && (mAdapter.getCount() == 0)) { Toast.makeText(getApplicationContext(), getResources().getString(R.string.downloading_observations), Toast.LENGTH_LONG).show(); } } }, 100); if (mApp.loggedIn() && mApp.getIsSyncing() && (mAdapter.getCount() == 0)) { // Show a "downloading ..." message instead of "no observations yet" ((TextView)findViewById(android.R.id.empty)).setText(R.string.downloading_observations); } } @Override protected void onSaveInstanceState(Bundle outState) { if (mLastMessage != null) outState.putString("mLastMessage", mLastMessage); super.onSaveInstanceState(outState); } private boolean isLoggedIn() { SharedPreferences prefs = getSharedPreferences("iNaturalistPreferences", MODE_PRIVATE); return prefs.getString("username", null) != null; } @Override public void onItemClick(AdapterView<?> l, View v, int position, long id) { Uri uri = ContentUris.withAppendedId(getIntent().getData(), id); String action = getIntent().getAction(); if (Intent.ACTION_PICK.equals(action) || Intent.ACTION_GET_CONTENT.equals(action)) { // The caller is waiting for us to return a note selected by // the user. The have clicked on one, so return it now. setResult(RESULT_OK, new Intent().setData(uri)); } else { if ((!mAdapter.isLocked(uri)) || (mAdapter.isLocked(uri) && !mApp.getIsSyncing())) { // Launch activity to view/edit the currently selected item startActivity(new Intent(Intent.ACTION_VIEW, uri, this, ObservationViewerActivity.class)); } } } private class ObservationCursorAdapter extends SimpleCursorAdapter { private HashMap<Long, String[]> mPhotoInfo = new HashMap<Long, String[]>(); public ObservationCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to) { super(context, layout, c, from, to); getPhotoInfo(); } @TargetApi(Build.VERSION_CODES.HONEYCOMB) public void refreshCursor() { SharedPreferences prefs = getSharedPreferences("iNaturalistPreferences", MODE_PRIVATE); String login = prefs.getString("username", null); String conditions = "(_synced_at IS NULL"; if (login != null) { conditions += " OR user_login = '" + login + "'"; } conditions += ") AND (is_deleted = 0 OR is_deleted is NULL)"; // Don't show deleted observations Cursor newCursor = getContentResolver().query(getIntent().getData(), Observation.PROJECTION, conditions, null, Observation.DEFAULT_SORT_ORDER); if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB){ Cursor oldCursor = swapCursor(newCursor); if ((oldCursor != null) && (!oldCursor.isClosed())) oldCursor.close(); } else { changeCursor(newCursor); } } /** * Retrieves photo ids and orientations for photos associated with the listed observations. */ public void getPhotoInfo() { Cursor c = getCursor(); int originalPosition = c.getPosition(); if (c.getCount() == 0) return; c.moveToFirst(); ArrayList<Long> obsIds = new ArrayList<Long>(); ArrayList<Long> obsExternalIds = new ArrayList<Long>(); ArrayList<Long> photoIds = new ArrayList<Long>(); while (!c.isAfterLast()) { obsIds.add(c.getLong(c.getColumnIndexOrThrow(Observation._ID))); try { obsExternalIds.add(c.getLong(c.getColumnIndexOrThrow(Observation.ID))); } catch (Exception exc) { } c.moveToNext(); } c.moveToPosition(originalPosition); // Add any online-only photos Cursor onlinePc = getContentResolver().query(ObservationPhoto.CONTENT_URI, new String[]{ObservationPhoto._ID, ObservationPhoto._OBSERVATION_ID, ObservationPhoto._PHOTO_ID, ObservationPhoto.PHOTO_URL, ObservationPhoto.PHOTO_FILENAME}, "(_observation_id IN (" + StringUtils.join(obsIds, ',') + ") OR observation_id IN (" + StringUtils.join(obsExternalIds, ',') + ") )", null, ObservationPhoto.DEFAULT_SORT_ORDER); onlinePc.moveToFirst(); while (!onlinePc.isAfterLast()) { Long obsId = onlinePc.getLong(onlinePc.getColumnIndexOrThrow(ObservationPhoto._OBSERVATION_ID)); String photoUrl = onlinePc.getString(onlinePc.getColumnIndexOrThrow(ObservationPhoto.PHOTO_URL)); String photoFilename = onlinePc.getString(onlinePc.getColumnIndexOrThrow(ObservationPhoto.PHOTO_FILENAME)); if (!mPhotoInfo.containsKey(obsId)) { mPhotoInfo.put( obsId, new String[] { photoFilename, null, photoUrl, null, null }); } onlinePc.moveToNext(); } onlinePc.close(); /* Cursor opc = getContentResolver().query(ObservationPhoto.CONTENT_URI, new String[]{ ObservationPhoto._ID, ObservationPhoto._OBSERVATION_ID, ObservationPhoto._PHOTO_ID, ObservationPhoto.PHOTO_URL, ObservationPhoto.PHOTO_FILENAME, ObservationPhoto._UPDATED_AT, ObservationPhoto._SYNCED_AT }, "_observation_id IN ("+StringUtils.join(obsIds, ',')+") AND photo_url IS NULL", null, ObservationPhoto._ID); if (opc.getCount() == 0) return; opc.moveToFirst(); while (!opc.isAfterLast()) { Long obsId = opc.getLong(opc.getColumnIndexOrThrow(ObservationPhoto._OBSERVATION_ID)); String photoFilename = opc.getString(opc.getColumnIndexOrThrow(ObservationPhoto.PHOTO_FILENAME)); Long syncedAt = opc.getLong(opc.getColumnIndexOrThrow(ObservationPhoto._SYNCED_AT)); Long updatedAt = opc.getLong(opc.getColumnIndexOrThrow(ObservationPhoto._UPDATED_AT)); if (!mPhotoInfo.containsKey(obsId)) { mPhotoInfo.put( obsId, new String[] { photoFilename, null, null, updatedAt.toString(), syncedAt.toString() }); } opc.moveToNext(); } opc.close(); */ } public void refreshPhotoInfo() { mPhotoInfo = new HashMap<Long, String[]>(); getPhotoInfo(); } public void refreshPhotoInfo(long obsId) { if (mPhotoInfo.containsKey(obsId)) mPhotoInfo.remove(obsId); } public View getView(int position, View convertView, ViewGroup parent) { View view = super.getView(position, convertView, parent); Cursor c = this.getCursor(); if (c.getCount() == 0) { return view; } ImageView image = (ImageView) view.findViewById(R.id.image); c.moveToPosition(position); final Long obsId = c.getLong(c.getColumnIndexOrThrow(Observation._ID)); final Long externalObsId = c.getLong(c.getColumnIndexOrThrow(Observation.ID)); refreshPhotoInfo(obsId); getPhotoInfo(); String[] photoInfo = mPhotoInfo.get(obsId); if (photoInfo == null) { // Try getting the external observation photo info photoInfo = mPhotoInfo.get(externalObsId); } String iconicTaxonName = c.getString(c.getColumnIndexOrThrow(Observation.ICONIC_TAXON_NAME)); int iconResource = 0; if (iconicTaxonName == null) { iconResource = R.drawable.iconic_taxon_unknown; } else if (iconicTaxonName.equals("Animalia")) { iconResource = R.drawable.iconic_taxon_animalia; } else if (iconicTaxonName.equals("Plantae")) { iconResource = R.drawable.iconic_taxon_plantae; } else if (iconicTaxonName.equals("Chromista")) { iconResource = R.drawable.iconic_taxon_chromista; } else if (iconicTaxonName.equals("Fungi")) { iconResource = R.drawable.iconic_taxon_fungi; } else if (iconicTaxonName.equals("Protozoa")) { iconResource = R.drawable.iconic_taxon_protozoa; } else if (iconicTaxonName.equals("Actinopterygii")) { iconResource = R.drawable.iconic_taxon_actinopterygii; } else if (iconicTaxonName.equals("Amphibia")) { iconResource = R.drawable.iconic_taxon_amphibia; } else if (iconicTaxonName.equals("Reptilia")) { iconResource = R.drawable.iconic_taxon_reptilia; } else if (iconicTaxonName.equals("Aves")) { iconResource = R.drawable.iconic_taxon_aves; } else if (iconicTaxonName.equals("Mammalia")) { iconResource = R.drawable.iconic_taxon_mammalia; } else if (iconicTaxonName.equals("Mollusca")) { iconResource = R.drawable.iconic_taxon_mollusca; } else if (iconicTaxonName.equals("Insecta")) { iconResource = R.drawable.iconic_taxon_insecta; } else if (iconicTaxonName.equals("Arachnida")) { iconResource = R.drawable.iconic_taxon_arachnida; } else { iconResource = R.drawable.iconic_taxon_unknown; } if (photoInfo != null) { String photoFilename = photoInfo[0]; if (photoInfo[2] != null) { // Online-only photo UrlImageViewHelper.setUrlDrawable(image, photoInfo[2], iconResource); } else { // Offline photo BitmapWorkerTask task = new BitmapWorkerTask(image); task.execute(photoFilename, String.valueOf(iconResource)); } } TextView observedOn = (TextView) view.findViewById(R.id.dateObserved); Long observationTimestamp = c.getLong(c.getColumnIndexOrThrow(Observation.OBSERVED_ON)); if (observationTimestamp == 0) { // No observation date set - don't show it observedOn.setVisibility(View.INVISIBLE); } else { observedOn.setVisibility(View.VISIBLE); Timestamp observationDate = new Timestamp(observationTimestamp); observedOn.setText(new SimpleDateFormat("M/d/yyyy").format(observationDate)); } TextView commentIdCountText = (TextView) view.findViewById(R.id.commentIdCount); Long commentsCount = c.getLong(c.getColumnIndexOrThrow(Observation.COMMENTS_COUNT)); Long idCount = c.getLong(c.getColumnIndexOrThrow(Observation.IDENTIFICATIONS_COUNT)); Long lastCommentsCount = c.getLong(c.getColumnIndexOrThrow(Observation.LAST_COMMENTS_COUNT)); Long lastIdCount = c.getLong(c.getColumnIndexOrThrow(Observation.LAST_IDENTIFICATIONS_COUNT)); final Long taxonId = c.getLong(c.getColumnIndexOrThrow(Observation.TAXON_ID)); if (taxonId != 0 && idCount > 0) { idCount--; } Long totalCount = commentsCount + idCount; ViewGroup clickCatcher = (ViewGroup) view.findViewById(R.id.rightObsPart); if (totalCount == 0) { // No comments/IDs - don't display the indicator commentIdCountText.setVisibility(View.INVISIBLE); clickCatcher.setClickable(false); } else { clickCatcher.setClickable(true); commentIdCountText.setVisibility(View.VISIBLE); if ((lastCommentsCount == null) || (lastCommentsCount < commentsCount) || (lastIdCount == null) || (lastIdCount < idCount)) { // There are unread comments/IDs commentIdCountText.setBackgroundResource(R.drawable.comments_ids_background_highlighted); } else { commentIdCountText.setBackgroundResource(R.drawable.comments_ids_background); } refreshCommentsIdSize(commentIdCountText, totalCount); clickCatcher.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (!isNetworkAvailable()) { Toast.makeText(getApplicationContext(), R.string.not_connected, Toast.LENGTH_LONG).show(); return; } // Show the comments/IDs for the observation Uri uri = ContentUris.withAppendedId(getIntent().getData(), obsId); Intent intent = new Intent(Intent.ACTION_VIEW, uri, ObservationListActivity.this, ObservationViewerActivity.class); intent.putExtra(ObservationViewerActivity.SHOW_COMMENTS, true); startActivityForResult(intent, COMMENTS_IDS_REQUEST_CODE); } }); } Long syncedAt = c.getLong(c.getColumnIndexOrThrow(Observation._SYNCED_AT)); Long updatedAt = c.getLong(c.getColumnIndexOrThrow(Observation._UPDATED_AT)); Boolean syncNeeded = (syncedAt == null) || (updatedAt > syncedAt); // if there's a photo and it is local if (syncNeeded == false && photoInfo != null && photoInfo[2] == null && photoInfo[3] != null) { if (photoInfo[4] == null) { syncNeeded = true; } else { Long photoSyncedAt = Long.parseLong(photoInfo[4]); Long photoUpdatedAt = Long.parseLong(photoInfo[3]); if (photoUpdatedAt > photoSyncedAt) { syncNeeded = true; } } } if (!syncNeeded) { // See if it's an existing observation with a new photo:w Cursor opc = getContentResolver().query(ObservationPhoto.CONTENT_URI, new String[]{ ObservationPhoto._ID, ObservationPhoto._OBSERVATION_ID, ObservationPhoto._PHOTO_ID, ObservationPhoto.PHOTO_URL, ObservationPhoto._UPDATED_AT, ObservationPhoto._SYNCED_AT }, "_observation_id = ? AND photo_url IS NULL AND _synced_at IS NULL", new String[] { String.valueOf(obsId) }, ObservationPhoto._ID); if (opc.getCount() > 0) { syncNeeded = true; } opc.close(); } ImageView needToSync = (ImageView) view.findViewById(R.id.syncRequired); TextView subTitle = (TextView) view.findViewById(R.id.subContent); TextView title = (TextView) view.findViewById(R.id.speciesGuess); ProgressBar progress = (ProgressBar) view.findViewById(R.id.progress); ViewGroup commentCatcher = (ViewGroup) view.findViewById(R.id.commentsIdClickCatcher); String speciesGuess = c.getString(c.getColumnIndexOrThrow(Observation.SPECIES_GUESS)); String preferredCommonName = c.getString(c.getColumnIndexOrThrow(Observation.PREFERRED_COMMON_NAME)); title.setTextColor(Color.parseColor("#000000")); subTitle.setTextColor(Color.parseColor("#666666")); progress.setVisibility(View.GONE); observedOn.setVisibility(View.VISIBLE); commentCatcher.setVisibility(View.VISIBLE); if (preferredCommonName != null) { title.setText(preferredCommonName); } else if ((speciesGuess != null) && (speciesGuess.trim().length() > 0)) { title.setText("\"" + speciesGuess + "\""); } else { title.setText(R.string.unknown_species); } ImageView errorIcon = (ImageView) view.findViewById(R.id.error); boolean hasErrors = (mApp.getErrorsForObservation(externalObsId.intValue()).length() > 0); if (hasErrors) { errorIcon.setVisibility(View.VISIBLE); needToSync.setVisibility(View.GONE); commentIdCountText.setVisibility(View.GONE); view.setBackgroundColor(Color.parseColor("#F3D3DA")); subTitle.setText(R.string.needs_your_attention); } else { errorIcon.setVisibility(View.GONE); view.setBackgroundColor(Color.parseColor("#FFFFFF")); } if (syncNeeded) { // This observations needs to be synced needToSync.setVisibility(View.VISIBLE); if (mApp.getObservationIdBeingSynced() == obsId) { // Observation is currently being uploaded subTitle.setText(R.string.uploading); view.setBackgroundColor(Color.parseColor("#76AA1B")); title.setTextColor(Color.parseColor("#ffffff")); subTitle.setTextColor(Color.parseColor("#ffffff")); progress.setVisibility(View.VISIBLE); observedOn.setVisibility(View.GONE); commentCatcher.setVisibility(View.GONE); } else { // Observation is waiting to be uploaded if (!hasErrors) { subTitle.setText(R.string.waiting_to_upload); view.setBackgroundColor(Color.parseColor("#E3EDCD")); } } } else { needToSync.setVisibility(View.INVISIBLE); if (!hasErrors) view.setBackgroundColor(Color.parseColor("#FFFFFF")); } return view; } // Should the specified observation be locked for editing (e.g. it's currently being uploaded) public boolean isLocked(Uri uri) { Cursor c = managedQuery(uri, Observation.PROJECTION, null, null, null); Observation obs = new Observation(c); Integer obsId = obs._id; String[] photoInfo = mPhotoInfo.get(obsId); Timestamp syncedAt = obs._synced_at; Timestamp updatedAt = obs._updated_at; Boolean syncNeeded = (syncedAt == null) || (updatedAt.after(syncedAt)); // if there's a photo and it is local if (syncNeeded == false && photoInfo != null && photoInfo[2] == null && photoInfo[3] != null) { if (photoInfo[4] == null) { syncNeeded = true; } else { Long photoSyncedAt = Long.parseLong(photoInfo[4]); Long photoUpdatedAt = Long.parseLong(photoInfo[3]); if (photoUpdatedAt > photoSyncedAt) { syncNeeded = true; } } } if (!syncNeeded) { // See if it's an existing observation with a new photo:w Cursor opc = getContentResolver().query(ObservationPhoto.CONTENT_URI, new String[]{ ObservationPhoto._ID, ObservationPhoto._OBSERVATION_ID, ObservationPhoto._PHOTO_ID, ObservationPhoto.PHOTO_URL, ObservationPhoto._UPDATED_AT, ObservationPhoto._SYNCED_AT }, "_observation_id = ? AND photo_url IS NULL AND _synced_at IS NULL", new String[] { String.valueOf(obsId) }, ObservationPhoto._ID); if (opc.getCount() > 0) { syncNeeded = true; } opc.close(); } if (mApp.getObservationIdBeingSynced() == obsId) { // Observation is currently being uploaded - is locked! return true; } else { if (!syncNeeded) { // Item hasn't changed (shouldn't be locked) return false; } if (!mApp.getAutoSync() || !isNetworkAvailable()) { // Allow editing if not in auto sync mode or when network is not available return false; } else { return true; } } } private void refreshCommentsIdSize(final TextView view, Long value) { ViewTreeObserver observer = view.getViewTreeObserver(); // Make sure the height and width of the rectangle are the same (i.e. a square) observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { @TargetApi(Build.VERSION_CODES.JELLY_BEAN) @Override public void onGlobalLayout() { int dimension = view.getHeight(); ViewGroup.LayoutParams params = view.getLayoutParams(); if (dimension > view.getWidth()) { // Only resize if there's enough room params.width = dimension; view.setLayoutParams(params); } ViewTreeObserver observer = view.getViewTreeObserver(); if(Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { observer.removeGlobalOnLayoutListener(this); } else { observer.removeOnGlobalLayoutListener(this); } } }); view.setText(value.toString()); } } @Override public void onNotification(String title, final String content) { mLastMessage = content; runOnUiThread(new Runnable() { @Override public void run() { if (!mApp.getAutoSync()) { mHelper.loading(content, ObservationListActivity.this); } mAdapter.refreshCursor(); } }); } // For caching observation thumbnails private HashMap<String, Bitmap> mObservationThumbnails = new HashMap<>(); // Used for loading and processing the observation photo in the background (as to not block the UI) class BitmapWorkerTask extends AsyncTask<String, Void, Bitmap> { private final WeakReference<ImageView> mImageViewReference; private String mFilename = null; private int mIconResource; public BitmapWorkerTask(ImageView imageView) { // Use a WeakReference to ensure the ImageView can be garbage collected mImageViewReference = new WeakReference<ImageView>(imageView); } // Decode image in background. @Override protected Bitmap doInBackground(String... params) { mFilename = params[0]; mIconResource = Integer.valueOf(params[1]); Bitmap bitmapImage; if (mObservationThumbnails.containsKey(mFilename)) { // Load from cache bitmapImage = mObservationThumbnails.get(mFilename); } else { if (mImageViewReference != null) { runOnUiThread(new Runnable() { @Override public void run() { mImageViewReference.get().setImageResource(mIconResource); } } ); } // Decode into a thumbnail BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = ImageUtils.calculateInSampleSize(options, 100, 100); // Decode bitmap with inSampleSize set options.inJustDecodeBounds = false; // This decreases in-memory byte-storage per pixel options.inPreferredConfig = Bitmap.Config.ALPHA_8; bitmapImage = BitmapFactory.decodeFile(mFilename, options); mObservationThumbnails.put(mFilename, bitmapImage); } return bitmapImage; } // Once complete, see if ImageView is still around and set bitmap. @Override protected void onPostExecute(Bitmap bitmap) { if (mImageViewReference != null && bitmap != null) { final ImageView imageView = mImageViewReference.get(); if (imageView != null) { imageView.setImageBitmap(bitmap); } } } } private ConnectivityBroadcastReceiver mConnectivityListener = null; private class ConnectivityBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (!action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) { return; } boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false); if (!noConnectivity) { // We're connected to the Internet - try syncing again triggerSyncIfNeeded(); } } } }
iNaturalist/src/main/java/org/inaturalist/android/ObservationListActivity.java
package org.inaturalist.android; import java.lang.ref.WeakReference; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import org.apache.commons.lang3.StringUtils; import org.inaturalist.android.INaturalistApp.INotificationCallback; import com.cocosw.bottomsheet.BottomSheet; import com.flurry.android.FlurryAgent; import com.handmark.pulltorefresh.library.PullToRefreshBase; import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener; import com.handmark.pulltorefresh.library.PullToRefreshListView; import com.koushikdutta.urlimageviewhelper.UrlImageViewHelper; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.content.DialogInterface; import android.os.AsyncTask; import android.os.Handler; import android.content.BroadcastReceiver; import android.content.ContentUris; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.support.v7.app.ActionBar; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.view.View.OnClickListener; import android.view.ViewTreeObserver.OnGlobalLayoutListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ImageView; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.SimpleCursorAdapter; import android.widget.TextView; import android.widget.Toast; public class ObservationListActivity extends BaseFragmentActivity implements OnItemClickListener, INotificationCallback, DialogInterface.OnClickListener { public static String TAG = "INAT:ObservationListActivity"; private PullToRefreshListView mPullRefreshListView; private SyncCompleteReceiver mSyncCompleteReceiver; private int mLastIndex; private int mLastTop; private ActionBar mTopActionBar; private TextView mSyncObservations; private ObservationCursorAdapter mAdapter; private TextView mTitleBar; private ActivityHelper mHelper; private String mLastMessage; private static final int COMMENTS_IDS_REQUEST_CODE = 100; private static final int OBSERVATION_LIST_LOADER = 0x01; private INaturalistApp mApp; @Override protected void onStart() { super.onStart(); FlurryAgent.onStartSession(this, INaturalistApp.getAppContext().getString(R.string.flurry_api_key)); FlurryAgent.logEvent(this.getClass().getSimpleName()); } @Override protected void onStop() { super.onStop(); FlurryAgent.onEndSession(this); } private boolean isNetworkAvailable() { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); } @Override public void onClick(DialogInterface dialogInterface, int i) { // User chose to cancel sync mApp.setCancelSync(true); refreshSyncBar(); } private class SyncCompleteReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Log.i(TAG, "Got ACTION_SYNC_COMPLETE"); mPullRefreshListView.onRefreshComplete(); mPullRefreshListView.refreshDrawableState(); mHelper.stopLoading(); ObservationCursorAdapter adapter = mAdapter; adapter.refreshCursor(); refreshSyncBar(); if (mApp.loggedIn() && !mApp.getIsSyncing() && (mAdapter.getCount() == 0)) { // Show a "no observations" message ((TextView)findViewById(android.R.id.empty)).setText(R.string.no_observations_yet); } if ((mLastMessage != null) && (mLastMessage.length() > 0)) { Toast.makeText(getApplicationContext(), mLastMessage, Toast.LENGTH_LONG).show(); mLastMessage = null; } } } public static Intent createIntent(Context context) { Intent i = new Intent(context, ObservationListActivity.class); i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); return i; } @Override protected void onDestroy() { super.onDestroy(); if (mSyncCompleteReceiver != null) { Log.i(TAG, "Unregistering ACTION_SYNC_COMPLETE"); try { unregisterReceiver(mSyncCompleteReceiver); unregisterReceiver(mConnectivityListener); } catch (Exception exc) { exc.printStackTrace(); } mSyncCompleteReceiver = null; mConnectivityListener = null; } } /** Shows the sync required bottom bar, if needed */ private void refreshSyncBar() { int syncCount = 0; int photoSyncCount = 0; if (mApp.getAutoSync()) { // Auto sync is on - no need for manual sync mSyncObservations.setVisibility(View.GONE); return; } Cursor c = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION, "((_updated_at > _synced_at AND _synced_at IS NOT NULL) OR (_synced_at IS NULL)) AND (_updated_at > _created_at)", null, Observation.SYNC_ORDER); syncCount = c.getCount(); c.close(); Cursor opc = getContentResolver().query(ObservationPhoto.CONTENT_URI, new String[]{ ObservationPhoto._ID, ObservationPhoto._OBSERVATION_ID, ObservationPhoto._PHOTO_ID, ObservationPhoto.PHOTO_URL, ObservationPhoto._UPDATED_AT, ObservationPhoto._SYNCED_AT }, "((photo_url IS NULL) AND (_updated_at IS NOT NULL) AND (_synced_at IS NULL)) OR " + "((photo_url IS NULL) AND (_updated_at IS NOT NULL) AND (_synced_at IS NOT NULL) AND (_updated_at > _synced_at))", null, ObservationPhoto._ID); photoSyncCount = opc.getCount(); opc.close(); if ((syncCount > 0) || (photoSyncCount > 0)) { mSyncObservations.setText(String.format(getResources().getString(R.string.sync_x_observations), (syncCount > 0 ? syncCount : photoSyncCount))); mSyncObservations.setVisibility(View.VISIBLE); } else { mSyncObservations.setVisibility(View.GONE); } } /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.observation_list); setTitle(R.string.observations); mHelper = new ActivityHelper(this); mApp = (INaturalistApp)getApplication(); mSyncObservations = (TextView) findViewById(R.id.sync_observations); mSyncObservations.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (!isNetworkAvailable()) { Toast.makeText(getApplicationContext(), R.string.not_connected, Toast.LENGTH_LONG).show(); return; } else if (!isLoggedIn()) { // User not logged-in - redirect to onboarding screen startActivity(new Intent(ObservationListActivity.this, OnboardingActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP)); return; } Intent serviceIntent = new Intent(INaturalistService.ACTION_SYNC, null, ObservationListActivity.this, INaturalistService.class); startService(serviceIntent); mSyncObservations.setVisibility(View.GONE); mHelper.loading(getResources().getString(R.string.syncing_observations), ObservationListActivity.this); } }); if (savedInstanceState != null) { mLastMessage = savedInstanceState.getString("mLastMessage"); } SharedPreferences pref = getSharedPreferences("iNaturalistPreferences", MODE_PRIVATE); String username = pref.getString("username", null); if (username == null) { if (!mApp.shownOnboarding()) { // Show login/onboarding screen mApp.setShownOnboarding(true); Intent intent = new Intent(this, OnboardingActivity.class); intent.putExtra(OnboardingActivity.SHOW_SKIP, true); startActivity(intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP)); } } refreshSyncBar(); mTopActionBar = getSupportActionBar(); View addButton = (View) findViewById(R.id.add_observation); addButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { new BottomSheet.Builder(ObservationListActivity.this).sheet(R.menu.observation_list_menu).listener(new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent intent; switch (which) { case R.id.camera: intent = new Intent(Intent.ACTION_INSERT, getIntent().getData(), ObservationListActivity.this, ObservationEditor.class); intent.putExtra(ObservationEditor.TAKE_PHOTO, true); startActivity(intent); break; case R.id.upload_photo: intent = new Intent(Intent.ACTION_INSERT, getIntent().getData(), ObservationListActivity.this, ObservationEditor.class); intent.putExtra(ObservationEditor.CHOOSE_PHOTO, true); startActivity(intent); break; case R.id.text: startActivity(new Intent(Intent.ACTION_INSERT, getIntent().getData(), ObservationListActivity.this, ObservationEditor.class)); break; } } }).show(); } }); INaturalistApp app = (INaturalistApp)(getApplication()); app.setNotificationCallback(this); Intent intent = getIntent(); if (intent.getData() == null) { intent.setData(Observation.CONTENT_URI); } mSyncCompleteReceiver = new SyncCompleteReceiver(); IntentFilter filter = new IntentFilter(INaturalistService.ACTION_SYNC_COMPLETE); Log.i(TAG, "Registering ACTION_SYNC_COMPLETE"); registerReceiver(mSyncCompleteReceiver, filter); mConnectivityListener = new ConnectivityBroadcastReceiver(); IntentFilter filter2 = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION); Log.i(TAG, "Registering CONNECTIVITY_ACTION"); registerReceiver(mConnectivityListener, filter2); mPullRefreshListView = (PullToRefreshListView) findViewById(R.id.observations_list); mPullRefreshListView.getLoadingLayoutProxy().setPullLabel(getResources().getString(R.string.pull_to_refresh)); mPullRefreshListView.getLoadingLayoutProxy().setReleaseLabel(getResources().getString(R.string.release_to_refresh)); mPullRefreshListView.getLoadingLayoutProxy().setRefreshingLabel(getResources().getString(R.string.refreshing)); mPullRefreshListView.setReleaseRatio(2.5f); // Set a listener to be invoked when the list should be refreshed. mPullRefreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() { @Override public void onRefresh(PullToRefreshBase<ListView> refreshView) { if (!isNetworkAvailable() || !isLoggedIn()) { Thread t = (new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } runOnUiThread(new Runnable() { @Override public void run() { mPullRefreshListView.onRefreshComplete(); } }); } })); t.start(); if (!isNetworkAvailable()) { Toast.makeText(getApplicationContext(), R.string.not_connected, Toast.LENGTH_LONG).show(); } else if (!isLoggedIn()) { Toast.makeText(getApplicationContext(), R.string.please_sign_in, Toast.LENGTH_LONG).show(); } return; } // Start sync Intent serviceIntent = new Intent(INaturalistService.ACTION_PULL_OBSERVATIONS, null, ObservationListActivity.this, INaturalistService.class); startService(serviceIntent); } }); onDrawerCreate(savedInstanceState); ListView actualListView = mPullRefreshListView.getRefreshableView(); // Need to use the Actual ListView when registering for Context Menu registerForContextMenu(actualListView); // Inform the list we provide context menus for items //getListView().setOnCreateContextMenuListener(this); SharedPreferences prefs = getSharedPreferences("iNaturalistPreferences", MODE_PRIVATE); String login = prefs.getString("username", null); // Perform a managed query. The Activity will handle closing and requerying the cursor // when needed. String conditions = "(_synced_at IS NULL"; if (login != null) { conditions += " OR user_login = '" + login + "'"; } conditions += ") AND (is_deleted = 0 OR is_deleted is NULL)"; // Don't show deleted observations Cursor cursor = getContentResolver().query(getIntent().getData(), Observation.PROJECTION, conditions, null, Observation.DEFAULT_SORT_ORDER); // Used to map notes entries from the database to views ObservationCursorAdapter adapter = new ObservationCursorAdapter( this, R.layout.list_item, cursor, new String[] { Observation.DESCRIPTION }, new int[] { R.id.subContent }); mAdapter = adapter; mPullRefreshListView.setEmptyView(findViewById(android.R.id.empty)); mPullRefreshListView.setAdapter(mAdapter); mPullRefreshListView.setOnItemClickListener(this); triggerSyncIfNeeded(); } private void triggerSyncIfNeeded() { boolean hasOldObs = hasOldObservations(); if ((mApp.getAutoSync() && !mApp.getIsSyncing()) || (hasOldObs)) { int syncCount = 0; if (!hasOldObs) { Cursor c = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION, "((_updated_at > _synced_at AND _synced_at IS NOT NULL) OR (_synced_at IS NULL) OR (is_deleted = 1))", null, Observation.SYNC_ORDER); syncCount = c.getCount(); c.close(); } // Trigger a sync (in case of auto-sync and unsynced obs OR when having old-style observations) if (hasOldObs || (syncCount > 0)) { Intent serviceIntent = new Intent(INaturalistService.ACTION_SYNC, null, ObservationListActivity.this, INaturalistService.class); startService(serviceIntent); } } } // Checks to see if there are any observations that have the "old" way of saving photos private boolean hasOldObservations() { Cursor c = getContentResolver().query(ObservationPhoto.CONTENT_URI, ObservationPhoto.PROJECTION, "(photo_filename IS NULL) AND (photo_url IS NULL)", null, ObservationPhoto.DEFAULT_SORT_ORDER); int count = c.getCount(); c.close(); return count > 0; } @SuppressLint("NewApi") @Override public void onPause() { super.onPause(); // save last position of list so we can resume there later // http://stackoverflow.com/questions/3014089/maintain-save-restore-scroll-position-when-returning-to-a-listview ListView lv = mPullRefreshListView.getRefreshableView(); mLastIndex = lv.getFirstVisiblePosition(); View v = lv.getChildAt(0); mLastTop = (v == null) ? 0 : v.getTop(); /* ObservationCursorAdapter adapter = mAdapter; adapter.notifyDataSetInvalidated(); if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB){ Cursor oldCursor = adapter.swapCursor(null); if ((oldCursor != null) && (!oldCursor.isClosed())) oldCursor.close(); } else { adapter.changeCursor(null); } */ super.onPause(); } @Override public void onResume() { super.onResume(); ListView lv = mPullRefreshListView.getRefreshableView(); lv.setSelectionFromTop(mLastIndex, mLastTop); refreshSyncBar(); ObservationCursorAdapter adapter = mAdapter; adapter.refreshCursor(); INaturalistApp app = (INaturalistApp)(getApplication()); if (app.getIsSyncing()) { // We're still syncing mHelper.stopLoading(); if ((mLastMessage != null) && (!mApp.getAutoSync())) mHelper.loading(mLastMessage, ObservationListActivity.this); app.setNotificationCallback(this); } (new Handler()).postDelayed(new Runnable() { @Override public void run() { if (mApp.loggedIn() && mApp.getIsSyncing() && (mAdapter.getCount() == 0)) { Toast.makeText(getApplicationContext(), getResources().getString(R.string.downloading_observations), Toast.LENGTH_LONG).show(); } } }, 100); if (mApp.loggedIn() && mApp.getIsSyncing() && (mAdapter.getCount() == 0)) { // Show a "downloading ..." message instead of "no observations yet" ((TextView)findViewById(android.R.id.empty)).setText(R.string.downloading_observations); } } @Override protected void onSaveInstanceState(Bundle outState) { if (mLastMessage != null) outState.putString("mLastMessage", mLastMessage); super.onSaveInstanceState(outState); } private boolean isLoggedIn() { SharedPreferences prefs = getSharedPreferences("iNaturalistPreferences", MODE_PRIVATE); return prefs.getString("username", null) != null; } @Override public void onItemClick(AdapterView<?> l, View v, int position, long id) { Uri uri = ContentUris.withAppendedId(getIntent().getData(), id); String action = getIntent().getAction(); if (Intent.ACTION_PICK.equals(action) || Intent.ACTION_GET_CONTENT.equals(action)) { // The caller is waiting for us to return a note selected by // the user. The have clicked on one, so return it now. setResult(RESULT_OK, new Intent().setData(uri)); } else { if ((!mAdapter.isLocked(uri)) || (mAdapter.isLocked(uri) && !mApp.getIsSyncing())) { // Launch activity to view/edit the currently selected item startActivity(new Intent(Intent.ACTION_VIEW, uri, this, ObservationViewerActivity.class)); } } } private class ObservationCursorAdapter extends SimpleCursorAdapter { private HashMap<Long, String[]> mPhotoInfo = new HashMap<Long, String[]>(); public ObservationCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to) { super(context, layout, c, from, to); getPhotoInfo(); } @TargetApi(Build.VERSION_CODES.HONEYCOMB) public void refreshCursor() { SharedPreferences prefs = getSharedPreferences("iNaturalistPreferences", MODE_PRIVATE); String login = prefs.getString("username", null); String conditions = "(_synced_at IS NULL"; if (login != null) { conditions += " OR user_login = '" + login + "'"; } conditions += ") AND (is_deleted = 0 OR is_deleted is NULL)"; // Don't show deleted observations Cursor newCursor = getContentResolver().query(getIntent().getData(), Observation.PROJECTION, conditions, null, Observation.DEFAULT_SORT_ORDER); if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB){ Cursor oldCursor = swapCursor(newCursor); if ((oldCursor != null) && (!oldCursor.isClosed())) oldCursor.close(); } else { changeCursor(newCursor); } } /** * Retrieves photo ids and orientations for photos associated with the listed observations. */ public void getPhotoInfo() { Cursor c = getCursor(); int originalPosition = c.getPosition(); if (c.getCount() == 0) return; c.moveToFirst(); ArrayList<Long> obsIds = new ArrayList<Long>(); ArrayList<Long> obsExternalIds = new ArrayList<Long>(); ArrayList<Long> photoIds = new ArrayList<Long>(); while (!c.isAfterLast()) { obsIds.add(c.getLong(c.getColumnIndexOrThrow(Observation._ID))); try { obsExternalIds.add(c.getLong(c.getColumnIndexOrThrow(Observation.ID))); } catch (Exception exc) { } c.moveToNext(); } c.moveToPosition(originalPosition); // Add any online-only photos Cursor onlinePc = getContentResolver().query(ObservationPhoto.CONTENT_URI, new String[]{ObservationPhoto._ID, ObservationPhoto._OBSERVATION_ID, ObservationPhoto._PHOTO_ID, ObservationPhoto.PHOTO_URL, ObservationPhoto.PHOTO_FILENAME}, "(_observation_id IN (" + StringUtils.join(obsIds, ',') + ") OR observation_id IN (" + StringUtils.join(obsExternalIds, ',') + ") )", null, ObservationPhoto.DEFAULT_SORT_ORDER); onlinePc.moveToFirst(); while (!onlinePc.isAfterLast()) { Long obsId = onlinePc.getLong(onlinePc.getColumnIndexOrThrow(ObservationPhoto._OBSERVATION_ID)); String photoUrl = onlinePc.getString(onlinePc.getColumnIndexOrThrow(ObservationPhoto.PHOTO_URL)); String photoFilename = onlinePc.getString(onlinePc.getColumnIndexOrThrow(ObservationPhoto.PHOTO_FILENAME)); if (!mPhotoInfo.containsKey(obsId)) { mPhotoInfo.put( obsId, new String[] { photoFilename, null, photoUrl, null, null }); } onlinePc.moveToNext(); } onlinePc.close(); /* Cursor opc = getContentResolver().query(ObservationPhoto.CONTENT_URI, new String[]{ ObservationPhoto._ID, ObservationPhoto._OBSERVATION_ID, ObservationPhoto._PHOTO_ID, ObservationPhoto.PHOTO_URL, ObservationPhoto.PHOTO_FILENAME, ObservationPhoto._UPDATED_AT, ObservationPhoto._SYNCED_AT }, "_observation_id IN ("+StringUtils.join(obsIds, ',')+") AND photo_url IS NULL", null, ObservationPhoto._ID); if (opc.getCount() == 0) return; opc.moveToFirst(); while (!opc.isAfterLast()) { Long obsId = opc.getLong(opc.getColumnIndexOrThrow(ObservationPhoto._OBSERVATION_ID)); String photoFilename = opc.getString(opc.getColumnIndexOrThrow(ObservationPhoto.PHOTO_FILENAME)); Long syncedAt = opc.getLong(opc.getColumnIndexOrThrow(ObservationPhoto._SYNCED_AT)); Long updatedAt = opc.getLong(opc.getColumnIndexOrThrow(ObservationPhoto._UPDATED_AT)); if (!mPhotoInfo.containsKey(obsId)) { mPhotoInfo.put( obsId, new String[] { photoFilename, null, null, updatedAt.toString(), syncedAt.toString() }); } opc.moveToNext(); } opc.close(); */ } public void refreshPhotoInfo() { mPhotoInfo = new HashMap<Long, String[]>(); getPhotoInfo(); } public void refreshPhotoInfo(long obsId) { if (mPhotoInfo.containsKey(obsId)) mPhotoInfo.remove(obsId); } public View getView(int position, View convertView, ViewGroup parent) { View view = super.getView(position, convertView, parent); Cursor c = this.getCursor(); if (c.getCount() == 0) { return view; } ImageView image = (ImageView) view.findViewById(R.id.image); c.moveToPosition(position); final Long obsId = c.getLong(c.getColumnIndexOrThrow(Observation._ID)); final Long externalObsId = c.getLong(c.getColumnIndexOrThrow(Observation.ID)); refreshPhotoInfo(obsId); getPhotoInfo(); String[] photoInfo = mPhotoInfo.get(obsId); if (photoInfo == null) { // Try getting the external observation photo info photoInfo = mPhotoInfo.get(externalObsId); } String iconicTaxonName = c.getString(c.getColumnIndexOrThrow(Observation.ICONIC_TAXON_NAME)); if (iconicTaxonName == null) { image.setImageResource(R.drawable.iconic_taxon_unknown); } else if (iconicTaxonName.equals("Animalia")) { image.setImageResource(R.drawable.iconic_taxon_animalia); } else if (iconicTaxonName.equals("Plantae")) { image.setImageResource(R.drawable.iconic_taxon_plantae); } else if (iconicTaxonName.equals("Chromista")) { image.setImageResource(R.drawable.iconic_taxon_chromista); } else if (iconicTaxonName.equals("Fungi")) { image.setImageResource(R.drawable.iconic_taxon_fungi); } else if (iconicTaxonName.equals("Protozoa")) { image.setImageResource(R.drawable.iconic_taxon_protozoa); } else if (iconicTaxonName.equals("Actinopterygii")) { image.setImageResource(R.drawable.iconic_taxon_actinopterygii); } else if (iconicTaxonName.equals("Amphibia")) { image.setImageResource(R.drawable.iconic_taxon_amphibia); } else if (iconicTaxonName.equals("Reptilia")) { image.setImageResource(R.drawable.iconic_taxon_reptilia); } else if (iconicTaxonName.equals("Aves")) { image.setImageResource(R.drawable.iconic_taxon_aves); } else if (iconicTaxonName.equals("Mammalia")) { image.setImageResource(R.drawable.iconic_taxon_mammalia); } else if (iconicTaxonName.equals("Mollusca")) { image.setImageResource(R.drawable.iconic_taxon_mollusca); } else if (iconicTaxonName.equals("Insecta")) { image.setImageResource(R.drawable.iconic_taxon_insecta); } else if (iconicTaxonName.equals("Arachnida")) { image.setImageResource(R.drawable.iconic_taxon_arachnida); } else { image.setImageResource(R.drawable.iconic_taxon_unknown); } if (photoInfo != null) { String photoFilename = photoInfo[0]; if (photoInfo[2] != null) { // Online-only photo UrlImageViewHelper.setUrlDrawable(image, photoInfo[2]); } else { // Offline photo BitmapWorkerTask task = new BitmapWorkerTask(image); task.execute(photoFilename); } } TextView observedOn = (TextView) view.findViewById(R.id.dateObserved); Long observationTimestamp = c.getLong(c.getColumnIndexOrThrow(Observation.OBSERVED_ON)); if (observationTimestamp == 0) { // No observation date set - don't show it observedOn.setVisibility(View.INVISIBLE); } else { observedOn.setVisibility(View.VISIBLE); Timestamp observationDate = new Timestamp(observationTimestamp); observedOn.setText(new SimpleDateFormat("M/d/yyyy").format(observationDate)); } TextView commentIdCountText = (TextView) view.findViewById(R.id.commentIdCount); Long commentsCount = c.getLong(c.getColumnIndexOrThrow(Observation.COMMENTS_COUNT)); Long idCount = c.getLong(c.getColumnIndexOrThrow(Observation.IDENTIFICATIONS_COUNT)); Long lastCommentsCount = c.getLong(c.getColumnIndexOrThrow(Observation.LAST_COMMENTS_COUNT)); Long lastIdCount = c.getLong(c.getColumnIndexOrThrow(Observation.LAST_IDENTIFICATIONS_COUNT)); final Long taxonId = c.getLong(c.getColumnIndexOrThrow(Observation.TAXON_ID)); if (taxonId != 0 && idCount > 0) { idCount--; } Long totalCount = commentsCount + idCount; ViewGroup clickCatcher = (ViewGroup) view.findViewById(R.id.rightObsPart); if (totalCount == 0) { // No comments/IDs - don't display the indicator commentIdCountText.setVisibility(View.INVISIBLE); clickCatcher.setClickable(false); } else { clickCatcher.setClickable(true); commentIdCountText.setVisibility(View.VISIBLE); if ((lastCommentsCount == null) || (lastCommentsCount < commentsCount) || (lastIdCount == null) || (lastIdCount < idCount)) { // There are unread comments/IDs commentIdCountText.setBackgroundResource(R.drawable.comments_ids_background_highlighted); } else { commentIdCountText.setBackgroundResource(R.drawable.comments_ids_background); } refreshCommentsIdSize(commentIdCountText, totalCount); clickCatcher.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (!isNetworkAvailable()) { Toast.makeText(getApplicationContext(), R.string.not_connected, Toast.LENGTH_LONG).show(); return; } // Show the comments/IDs for the observation Uri uri = ContentUris.withAppendedId(getIntent().getData(), obsId); Intent intent = new Intent(Intent.ACTION_VIEW, uri, ObservationListActivity.this, ObservationViewerActivity.class); intent.putExtra(ObservationViewerActivity.SHOW_COMMENTS, true); startActivityForResult(intent, COMMENTS_IDS_REQUEST_CODE); } }); } Long syncedAt = c.getLong(c.getColumnIndexOrThrow(Observation._SYNCED_AT)); Long updatedAt = c.getLong(c.getColumnIndexOrThrow(Observation._UPDATED_AT)); Boolean syncNeeded = (syncedAt == null) || (updatedAt > syncedAt); // if there's a photo and it is local if (syncNeeded == false && photoInfo != null && photoInfo[2] == null && photoInfo[3] != null) { if (photoInfo[4] == null) { syncNeeded = true; } else { Long photoSyncedAt = Long.parseLong(photoInfo[4]); Long photoUpdatedAt = Long.parseLong(photoInfo[3]); if (photoUpdatedAt > photoSyncedAt) { syncNeeded = true; } } } if (!syncNeeded) { // See if it's an existing observation with a new photo:w Cursor opc = getContentResolver().query(ObservationPhoto.CONTENT_URI, new String[]{ ObservationPhoto._ID, ObservationPhoto._OBSERVATION_ID, ObservationPhoto._PHOTO_ID, ObservationPhoto.PHOTO_URL, ObservationPhoto._UPDATED_AT, ObservationPhoto._SYNCED_AT }, "_observation_id = ? AND photo_url IS NULL AND _synced_at IS NULL", new String[] { String.valueOf(obsId) }, ObservationPhoto._ID); if (opc.getCount() > 0) { syncNeeded = true; } opc.close(); } ImageView needToSync = (ImageView) view.findViewById(R.id.syncRequired); TextView subTitle = (TextView) view.findViewById(R.id.subContent); TextView title = (TextView) view.findViewById(R.id.speciesGuess); ProgressBar progress = (ProgressBar) view.findViewById(R.id.progress); ViewGroup commentCatcher = (ViewGroup) view.findViewById(R.id.commentsIdClickCatcher); String speciesGuess = c.getString(c.getColumnIndexOrThrow(Observation.SPECIES_GUESS)); String preferredCommonName = c.getString(c.getColumnIndexOrThrow(Observation.PREFERRED_COMMON_NAME)); title.setTextColor(Color.parseColor("#000000")); subTitle.setTextColor(Color.parseColor("#666666")); progress.setVisibility(View.GONE); observedOn.setVisibility(View.VISIBLE); commentCatcher.setVisibility(View.VISIBLE); if (preferredCommonName != null) { title.setText(preferredCommonName); } else if ((speciesGuess != null) && (speciesGuess.trim().length() > 0)) { title.setText("\"" + speciesGuess + "\""); } else { title.setText(R.string.unknown_species); } ImageView errorIcon = (ImageView) view.findViewById(R.id.error); boolean hasErrors = (mApp.getErrorsForObservation(externalObsId.intValue()).length() > 0); if (hasErrors) { errorIcon.setVisibility(View.VISIBLE); needToSync.setVisibility(View.GONE); commentIdCountText.setVisibility(View.GONE); view.setBackgroundColor(Color.parseColor("#F3D3DA")); subTitle.setText(R.string.needs_your_attention); } else { errorIcon.setVisibility(View.GONE); view.setBackgroundColor(Color.parseColor("#FFFFFF")); } if (syncNeeded) { // This observations needs to be synced needToSync.setVisibility(View.VISIBLE); if (mApp.getObservationIdBeingSynced() == obsId) { // Observation is currently being uploaded subTitle.setText(R.string.uploading); view.setBackgroundColor(Color.parseColor("#76AA1B")); title.setTextColor(Color.parseColor("#ffffff")); subTitle.setTextColor(Color.parseColor("#ffffff")); progress.setVisibility(View.VISIBLE); observedOn.setVisibility(View.GONE); commentCatcher.setVisibility(View.GONE); } else { // Observation is waiting to be uploaded if (!hasErrors) { subTitle.setText(R.string.waiting_to_upload); view.setBackgroundColor(Color.parseColor("#E3EDCD")); } } } else { needToSync.setVisibility(View.INVISIBLE); if (!hasErrors) view.setBackgroundColor(Color.parseColor("#FFFFFF")); } return view; } // Should the specified observation be locked for editing (e.g. it's currently being uploaded) public boolean isLocked(Uri uri) { Cursor c = managedQuery(uri, Observation.PROJECTION, null, null, null); Observation obs = new Observation(c); Integer obsId = obs._id; String[] photoInfo = mPhotoInfo.get(obsId); Timestamp syncedAt = obs._synced_at; Timestamp updatedAt = obs._updated_at; Boolean syncNeeded = (syncedAt == null) || (updatedAt.after(syncedAt)); // if there's a photo and it is local if (syncNeeded == false && photoInfo != null && photoInfo[2] == null && photoInfo[3] != null) { if (photoInfo[4] == null) { syncNeeded = true; } else { Long photoSyncedAt = Long.parseLong(photoInfo[4]); Long photoUpdatedAt = Long.parseLong(photoInfo[3]); if (photoUpdatedAt > photoSyncedAt) { syncNeeded = true; } } } if (!syncNeeded) { // See if it's an existing observation with a new photo:w Cursor opc = getContentResolver().query(ObservationPhoto.CONTENT_URI, new String[]{ ObservationPhoto._ID, ObservationPhoto._OBSERVATION_ID, ObservationPhoto._PHOTO_ID, ObservationPhoto.PHOTO_URL, ObservationPhoto._UPDATED_AT, ObservationPhoto._SYNCED_AT }, "_observation_id = ? AND photo_url IS NULL AND _synced_at IS NULL", new String[] { String.valueOf(obsId) }, ObservationPhoto._ID); if (opc.getCount() > 0) { syncNeeded = true; } opc.close(); } if (mApp.getObservationIdBeingSynced() == obsId) { // Observation is currently being uploaded - is locked! return true; } else { if (!syncNeeded) { // Item hasn't changed (shouldn't be locked) return false; } if (!mApp.getAutoSync() || !isNetworkAvailable()) { // Allow editing if not in auto sync mode or when network is not available return false; } else { return true; } } } private void refreshCommentsIdSize(final TextView view, Long value) { ViewTreeObserver observer = view.getViewTreeObserver(); // Make sure the height and width of the rectangle are the same (i.e. a square) observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { @TargetApi(Build.VERSION_CODES.JELLY_BEAN) @Override public void onGlobalLayout() { int dimension = view.getHeight(); ViewGroup.LayoutParams params = view.getLayoutParams(); if (dimension > view.getWidth()) { // Only resize if there's enough room params.width = dimension; view.setLayoutParams(params); } ViewTreeObserver observer = view.getViewTreeObserver(); if(Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { observer.removeGlobalOnLayoutListener(this); } else { observer.removeOnGlobalLayoutListener(this); } } }); view.setText(value.toString()); } } @Override public void onNotification(String title, final String content) { mLastMessage = content; runOnUiThread(new Runnable() { @Override public void run() { if (!mApp.getAutoSync()) { mHelper.loading(content, ObservationListActivity.this); } mAdapter.refreshCursor(); } }); } // For caching observation thumbnails private HashMap<String, Bitmap> mObservationThumbnails = new HashMap<>(); // Used for loading and processing the observation photo in the background (as to not block the UI) class BitmapWorkerTask extends AsyncTask<String, Void, Bitmap> { private final WeakReference<ImageView> mImageViewReference; private String mFilename = null; public BitmapWorkerTask(ImageView imageView) { // Use a WeakReference to ensure the ImageView can be garbage collected mImageViewReference = new WeakReference<ImageView>(imageView); } // Decode image in background. @Override protected Bitmap doInBackground(String... params) { mFilename = params[0]; Bitmap bitmapImage; if (mObservationThumbnails.containsKey(mFilename)) { // Load from cache bitmapImage = mObservationThumbnails.get(mFilename); } else { // Decode into a thumbnail BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = ImageUtils.calculateInSampleSize(options, 100, 100); // Decode bitmap with inSampleSize set options.inJustDecodeBounds = false; // This decreases in-memory byte-storage per pixel options.inPreferredConfig = Bitmap.Config.ALPHA_8; bitmapImage = BitmapFactory.decodeFile(mFilename, options); mObservationThumbnails.put(mFilename, bitmapImage); } return bitmapImage; } // Once complete, see if ImageView is still around and set bitmap. @Override protected void onPostExecute(Bitmap bitmap) { if (mImageViewReference != null && bitmap != null) { final ImageView imageView = mImageViewReference.get(); if (imageView != null) { imageView.setImageBitmap(bitmap); } } } } private ConnectivityBroadcastReceiver mConnectivityListener = null; private class ConnectivityBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (!action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) { return; } boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false); if (!noConnectivity) { // We're connected to the Internet - try syncing again triggerSyncIfNeeded(); } } } }
Fix #226
iNaturalist/src/main/java/org/inaturalist/android/ObservationListActivity.java
Fix #226
Java
mit
7639f78dceb49d54af3d9a7890d3a27b8e7f7780
0
mback2k/jlibamf
package de.uxnr.amf.flex.msg; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.List; import java.util.Vector; import de.uxnr.amf.AMF_Context; import de.uxnr.amf.AMF_Type; import de.uxnr.amf.v0.base.U8; import de.uxnr.amf.v3.AMF3_Type; import de.uxnr.amf.v3.base.UTF8; import de.uxnr.amf.v3.type.Object; public abstract class AbstractMessage extends Object { private static final UTF8[][] names = new UTF8[][] { { new UTF8("body"), new UTF8("clientId"), new UTF8("destination"), new UTF8("headers"), new UTF8("messageId"), new UTF8("timestamp"), new UTF8("timeToLive"), }, { new UTF8("clientId"), new UTF8("messageId"), } }; @Override public void write(AMF_Context context, DataOutputStream output) throws IOException { this.writeFields(context, output, AbstractMessage.names); } @Override public AMF_Type read(AMF_Context context, DataInputStream input) throws IOException { this.readFields(context, input, AbstractMessage.names); return this; } protected void writeFields(AMF_Context context, DataOutputStream output, UTF8[][] names) throws IOException { List<AMF3_Type> values = new Vector<AMF3_Type>(); List<Integer> flags = new Vector<Integer>(); for (UTF8[] name : names) { int flag = 0; for (int index = 0; index < name.length; index++) { AMF3_Type value = this.get(name[index]); if (value != null) { values.add(value); } } for (int index = name.length - 1; index >= 0; index--) { AMF3_Type value = this.get(name[index]); flag <<= 1; if (value != null) { flag |= 1; } } flags.add(flag); } if (flags.isEmpty()) { flags.add(0x00); } this.writeFlags(context, output, flags); for (AMF3_Type value : values) { AMF3_Type.writeType(context, output, value); } } protected void readFields(AMF_Context context, DataInputStream input, UTF8[][] names) throws IOException { List<Integer> flags = this.readFlags(context, input); int index = 0; for (int flag : flags) { int reserved = 0; if (index < names.length) { for (UTF8 name : names[index++]) { if (((flag >> (reserved++)) & 1) == 1) { this.set(name, AMF3_Type.readType(context, input), true); } } } } } private void writeFlags(AMF_Context context, DataOutputStream output, List<Integer> flags) throws IOException { U8 ubyte = new U8(0x00); for (int index = 0; index < flags.size(); index++) { if (index == flags.size() - 1) { ubyte = new U8(flags.get(index)); } else { ubyte = new U8(flags.get(index) | 0x80); } ubyte.write(context, output); } } private List<Integer> readFlags(AMF_Context context, DataInputStream input) throws IOException { List<Integer> flags = new Vector<Integer>(); U8 ubyte = new U8(0x80); do { ubyte = new U8(context, input); flags.add(ubyte.get() & ~0x80); } while ((ubyte.get() & 0x80) == 0x80); return flags; } }
src/de/uxnr/amf/flex/msg/AbstractMessage.java
package de.uxnr.amf.flex.msg; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.List; import java.util.Vector; import de.uxnr.amf.AMF_Context; import de.uxnr.amf.AMF_Type; import de.uxnr.amf.v0.base.U8; import de.uxnr.amf.v3.AMF3_Type; import de.uxnr.amf.v3.base.UTF8; import de.uxnr.amf.v3.type.Object; public abstract class AbstractMessage extends Object { private static final UTF8[][] names = new UTF8[][] { { new UTF8("body"), new UTF8("clientId"), new UTF8("destination"), new UTF8("headers"), new UTF8("messageId"), new UTF8("timestamp"), new UTF8("timeToLive"), }, { new UTF8("clientId"), new UTF8("messageId"), } }; @Override public void write(AMF_Context context, DataOutputStream output) throws IOException { this.writeFields(context, output, AbstractMessage.names); } @Override public AMF_Type read(AMF_Context context, DataInputStream input) throws IOException { this.readFields(context, input, AbstractMessage.names); return this; } protected void writeFields(AMF_Context context, DataOutputStream output, UTF8[][] names) throws IOException { List<AMF3_Type> values = new Vector<AMF3_Type>(); List<Integer> flags = new Vector<Integer>(); for (UTF8[] name : names) { int flag = 0; for (int index = 0; index < name.length; index++) { AMF3_Type value = this.get(name[index]); if (value != null) { values.add(value); } } for (int index = name.length - 1; index >= 0; index--) { AMF3_Type value = this.get(name[index]); if (value != null) { flag = (flag << 1) | 1; } } flags.add(flag); } if (flags.isEmpty()) { flags.add(0x00); } this.writeFlags(context, output, flags); for (AMF3_Type value : values) { AMF3_Type.writeType(context, output, value); } } protected void readFields(AMF_Context context, DataInputStream input, UTF8[][] names) throws IOException { List<Integer> flags = this.readFlags(context, input); int index = 0; for (int flag : flags) { int reserved = 0; if (index < names.length) { for (UTF8 name : names[index++]) { if (((flag >> (reserved++)) & 1) == 1) { this.set(name, AMF3_Type.readType(context, input), true); } } } } } private void writeFlags(AMF_Context context, DataOutputStream output, List<Integer> flags) throws IOException { U8 ubyte = new U8(0x00); for (int index = 0; index < flags.size(); index++) { if (index == flags.size() - 1) { ubyte = new U8(flags.get(index)); } else { ubyte = new U8(flags.get(index) | 0x80); } ubyte.write(context, output); } } private List<Integer> readFlags(AMF_Context context, DataInputStream input) throws IOException { List<Integer> flags = new Vector<Integer>(); U8 ubyte = new U8(0x80); do { ubyte = new U8(context, input); flags.add(ubyte.get() & ~0x80); } while ((ubyte.get() & 0x80) == 0x80); return flags; } }
Fixed Flex message writing
src/de/uxnr/amf/flex/msg/AbstractMessage.java
Fixed Flex message writing
Java
mit
20f04febf29c427d16f9202090352eae6ebcca2a
0
kohsuke/github-api
/* * The MIT License * * Copyright (c) 2010, Kohsuke Kawaguchi * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.kohsuke.github; import com.fasterxml.jackson.databind.JsonMappingException; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.InterruptedIOException; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.SocketException; import java.net.SocketTimeoutException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.NoSuchElementException; import java.util.Objects; import java.util.function.Consumer; import java.util.logging.Logger; import java.util.zip.GZIPInputStream; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import javax.annotation.WillClose; import static java.util.Arrays.asList; import static java.util.logging.Level.*; import static org.apache.commons.lang3.StringUtils.defaultString; import static org.kohsuke.github.GitHub.MAPPER; import static org.kohsuke.github.GitHub.connect; /** * A builder pattern for making HTTP call and parsing its output. * * @author Kohsuke Kawaguchi */ class Requester { private final GitHub root; private final List<Entry> args = new ArrayList<Entry>(); private final Map<String, String> headers = new LinkedHashMap<String, String>(); @Nonnull private String urlPath = "/"; /** * Request method. */ private String method = "GET"; private String contentType = null; private InputStream body; /** * Current connection. */ private HttpURLConnection uc; private boolean forceBody; private static class Entry { final String key; final Object value; private Entry(String key, Object value) { this.key = key; this.value = value; } } /** * If timeout issues let's retry after milliseconds. */ private static final int retryTimeoutMillis = 500; Requester(GitHub root) { this.root = root; } /** * Sets the request HTTP header. * <p> * If a header of the same name is already set, this method overrides it. * * @param name * the name * @param value * the value */ public void setHeader(String name, String value) { headers.put(name, value); } /** * With header requester. * * @param name * the name * @param value * the value * @return the requester */ public Requester withHeader(String name, String value) { setHeader(name, value); return this; } public Requester withPreview(String name) { return withHeader("Accept", name); } /** * With requester. * * @param key * the key * @param value * the value * @return the requester */ public Requester with(String key, int value) { return with(key, (Object) value); } /** * With requester. * * @param key * the key * @param value * the value * @return the requester */ public Requester with(String key, long value) { return with(key, (Object) value); } /** * With requester. * * @param key * the key * @param value * the value * @return the requester */ public Requester with(String key, boolean value) { return with(key, (Object) value); } /** * With requester. * * @param key * the key * @param e * the e * @return the requester */ public Requester with(String key, Enum e) { if (e == null) return with(key, (Object) null); return with(key, transformEnum(e)); } /** * With requester. * * @param key * the key * @param value * the value * @return the requester */ public Requester with(String key, String value) { return with(key, (Object) value); } /** * With requester. * * @param key * the key * @param value * the value * @return the requester */ public Requester with(String key, Collection<?> value) { return with(key, (Object) value); } /** * With requester. * * @param key * the key * @param value * the value * @return the requester */ public Requester with(String key, Map<String, String> value) { return with(key, (Object) value); } /** * With requester. * * @param body * the body * @return the requester */ public Requester with(@WillClose /* later */ InputStream body) { this.body = body; return this; } /** * With nullable requester. * * @param key * the key * @param value * the value * @return the requester */ public Requester withNullable(String key, Object value) { args.add(new Entry(key, value)); return this; } /** * With requester. * * @param key * the key * @param value * the value * @return the requester */ public Requester with(String key, Object value) { if (value != null) { args.add(new Entry(key, value)); } return this; } /** * Unlike {@link #with(String, String)}, overrides the existing value * * @param key * the key * @param value * the value * @return the requester */ public Requester set(String key, Object value) { for (int index = 0; index < args.size(); index++) { if (args.get(index).key.equals(key)) { args.set(index, new Entry(key, value)); return this; } } return with(key, value); } /** * Method requester. * * @param method * the method * @return the requester */ public Requester method(String method) { this.method = method; return this; } /** * Content type requester. * * @param contentType * the content type * @return the requester */ public Requester contentType(String contentType) { this.contentType = contentType; return this; } /** * NOT FOR PUBLIC USE. Do not make this method public. * <p> * Sets the path component of api URL without URI encoding. * <p> * Should only be used when passing a literal URL field from a GHObject, such as {@link GHContent#refresh()} or when * needing to set query parameters on requests methods that don't usually have them, such as * {@link GHRelease#uploadAsset(String, InputStream, String)}. * * @param urlOrPath * the content type * @return the requester */ Requester setRawUrlPath(String urlOrPath) { Objects.requireNonNull(urlOrPath); this.urlPath = urlOrPath; return this; } /** * Path component of api URL. Appended to api url. * <p> * If urlPath starts with a slash, it will be URI encoded as a path. If it starts with anything else, it will be * used as is. * * @param urlPathItems * the content type * @return the requester */ public Requester withUrlPath(String... urlPathItems) { if (!this.urlPath.startsWith("/")) { throw new GHException("Cannot append to url path after setting a raw path"); } if (urlPathItems.length == 1 && !urlPathItems[0].startsWith("/")) { return setRawUrlPath(urlPathItems[0]); } String tailUrlPath = String.join("/", urlPathItems); if (this.urlPath.endsWith("/")) { tailUrlPath = StringUtils.stripStart(tailUrlPath, "/"); } else { tailUrlPath = StringUtils.prependIfMissing(tailUrlPath, "/"); } this.urlPath += urlPathEncode(tailUrlPath); return this; } /** * Small number of GitHub APIs use HTTP methods somewhat inconsistently, and use a body where it's not expected. * Normally whether parameters go as query parameters or a body depends on the HTTP verb in use, but this method * forces the parameters to be sent as a body. */ public Requester inBody() { forceBody = true; return this; } /** * Sends a request to the specified URL and checks that it is sucessful. * * @throws IOException * the io exception */ public void send() throws IOException { _fetch(() -> parse(null, null)); } /** * Sends a request and parses the response into the given type via databinding. * * @param <T> * the type parameter * @param type * the type * @return {@link Reader} that reads the response. * @throws IOException * if the server returns 4xx/5xx responses. */ public <T> T fetch(@Nonnull Class<T> type) throws IOException { return _fetch(() -> parse(type, null)); } /** * Sends a request and parses the response into an array of the given type via databinding. * * @param <T> * the type parameter * @param type * the type * @return {@link Reader} that reads the response. * @throws IOException * if the server returns 4xx/5xx responses. */ public <T> T[] fetchArray(@Nonnull Class<T[]> type) throws IOException { T[] result = null; try { // for arrays we might have to loop for pagination // use the iterator to handle it List<T[]> pages = new ArrayList<>(); int totalSize = 0; for (Iterator<T[]> iterator = asIterator(type, 0); iterator.hasNext();) { T[] nextResult = iterator.next(); totalSize += Array.getLength(nextResult); pages.add(nextResult); } result = concatenatePages(type, pages, totalSize); } catch (GHException e) { // if there was an exception inside the iterator it is wrapped as a GHException // if the wrapped exception is an IOException, throw that if (e.getCause() instanceof IOException) { throw (IOException) e.getCause(); } else { throw e; } } return result; } /** * Like {@link #fetch(Class)} but updates an existing object instead of creating a new instance. * * @param <T> * the type parameter * @param existingInstance * the existing instance * @return the t * @throws IOException * the io exception */ public <T> T fetchInto(@Nonnull T existingInstance) throws IOException { return _fetch(() -> parse(null, existingInstance)); } /** * Makes a request and just obtains the HTTP status code. Method does not throw exceptions for many status codes * that would otherwise throw. * * @return the int * @throws IOException * the io exception */ public int fetchHttpStatusCode() throws IOException { return _fetch(() -> uc.getResponseCode()); } /** * As stream input stream. * * @return the input stream * @throws IOException * the io exception */ public InputStream fetchStream() throws IOException { return _fetch(() -> parse(InputStream.class, null)); } private <T> T _fetch(SupplierThrows<T, IOException> supplier) throws IOException { String tailApiUrl = buildTailApiUrl(urlPath); URL url = root.getApiURL(tailApiUrl); return _fetch(tailApiUrl, url, supplier); } private <T> T _fetch(String tailApiUrl, URL url, SupplierThrows<T, IOException> supplier) throws IOException { while (true) {// loop while API rate limit is hit uc = setupConnection(url); try { retryInvalidCached404Response(); return supplier.get(); } catch (IOException e) { handleApiError(e); } finally { noteRateLimit(tailApiUrl); } } } private <T> T[] concatenatePages(Class<T[]> type, List<T[]> pages, int totalLength) { T[] result = type.cast(Array.newInstance(type.getComponentType(), totalLength)); int position = 0; for (T[] page : pages) { final int pageLength = Array.getLength(page); System.arraycopy(page, 0, result, position, pageLength); position += pageLength; } return result; } private String buildTailApiUrl(String tailApiUrl) { if (!isMethodWithBody() && !args.isEmpty()) { try { boolean questionMarkFound = tailApiUrl.indexOf('?') != -1; StringBuilder argString = new StringBuilder(); argString.append(questionMarkFound ? '&' : '?'); for (Iterator<Entry> it = args.listIterator(); it.hasNext();) { Entry arg = it.next(); argString.append(URLEncoder.encode(arg.key, StandardCharsets.UTF_8.name())); argString.append('='); argString.append(URLEncoder.encode(arg.value.toString(), StandardCharsets.UTF_8.name())); if (it.hasNext()) { argString.append('&'); } } tailApiUrl += argString; } catch (UnsupportedEncodingException e) { throw new AssertionError(e); // UTF-8 is mandatory } } return tailApiUrl; } private void noteRateLimit(String tailApiUrl) { if (uc == null) { return; } if (tailApiUrl.startsWith("/search")) { // the search API uses a different rate limit return; } String limitString = uc.getHeaderField("X-RateLimit-Limit"); if (StringUtils.isBlank(limitString)) { // if we are missing a header, return fast return; } String remainingString = uc.getHeaderField("X-RateLimit-Remaining"); if (StringUtils.isBlank(remainingString)) { // if we are missing a header, return fast return; } String resetString = uc.getHeaderField("X-RateLimit-Reset"); if (StringUtils.isBlank(resetString)) { // if we are missing a header, return fast return; } int limit, remaining; long reset; try { limit = Integer.parseInt(limitString); } catch (NumberFormatException e) { if (LOGGER.isLoggable(FINEST)) { LOGGER.log(FINEST, "Malformed X-RateLimit-Limit header value " + limitString, e); } return; } try { remaining = Integer.parseInt(remainingString); } catch (NumberFormatException e) { if (LOGGER.isLoggable(FINEST)) { LOGGER.log(FINEST, "Malformed X-RateLimit-Remaining header value " + remainingString, e); } return; } try { reset = Long.parseLong(resetString); } catch (NumberFormatException e) { if (LOGGER.isLoggable(FINEST)) { LOGGER.log(FINEST, "Malformed X-RateLimit-Reset header value " + resetString, e); } return; } GHRateLimit.Record observed = new GHRateLimit.Record(limit, remaining, reset, uc.getHeaderField("Date")); root.updateCoreRateLimit(observed); } /** * Gets response header. * * @param header * the header * @return the response header */ public String getResponseHeader(String header) { return uc.getHeaderField(header); } /** * Set up the request parameters or POST payload. */ private void buildRequest(HttpURLConnection connection) throws IOException { if (isMethodWithBody()) { connection.setDoOutput(true); if (body == null) { connection.setRequestProperty("Content-type", defaultString(contentType, "application/json")); Map json = new HashMap(); for (Entry e : args) { json.put(e.key, e.value); } MAPPER.writeValue(connection.getOutputStream(), json); } else { connection.setRequestProperty("Content-type", defaultString(contentType, "application/x-www-form-urlencoded")); try { byte[] bytes = new byte[32768]; int read; while ((read = body.read(bytes)) != -1) { connection.getOutputStream().write(bytes, 0, read); } } finally { body.close(); } } } } private boolean isMethodWithBody() { return forceBody || !METHODS_WITHOUT_BODY.contains(method); } <T> PagedIterable<T> toIterable(Class<T[]> type, Consumer<T> consumer) { return new PagedIterableWithConsumer<>(type, consumer); } class PagedIterableWithConsumer<T> extends PagedIterable<T> { private final Class<T[]> clazz; private final Consumer<T> consumer; PagedIterableWithConsumer(Class<T[]> clazz, Consumer<T> consumer) { this.clazz = clazz; this.consumer = consumer; } @Override public PagedIterator<T> _iterator(int pageSize) { final Iterator<T[]> iterator = asIterator(clazz, pageSize); return new PagedIterator<T>(iterator) { @Override protected void wrapUp(T[] page) { if (consumer != null) { for (T item : page) { consumer.accept(item); } } } }; } } /** * Loads paginated resources. * * @param type * type of each page (not the items in the page). * @param pageSize * the size of the * @param <T> * type of each page (not the items in the page). * @return */ <T> Iterator<T> asIterator(Class<T> type, int pageSize) { if (!"GET".equals(method)) { throw new IllegalStateException("Request method \"GET\" is required for iterator."); } if (pageSize > 0) args.add(new Entry("per_page", pageSize)); String tailApiUrl = buildTailApiUrl(urlPath); try { return new PagingIterator<>(type, tailApiUrl, root.getApiURL(tailApiUrl)); } catch (IOException e) { throw new GHException("Unable to build github Api URL", e); } } /** * May be used for any item that has pagination information. * * Works for array responses, also works for search results which are single instances with an array of items * inside. * * @param <T> * type of each page (not the items in the page). */ class PagingIterator<T> implements Iterator<T> { private final Class<T> type; private final String tailApiUrl; /** * The next batch to be returned from {@link #next()}. */ private T next; /** * URL of the next resource to be retrieved, or null if no more data is available. */ private URL url; PagingIterator(Class<T> type, String tailApiUrl, URL url) { this.type = type; this.tailApiUrl = tailApiUrl; this.url = url; } public boolean hasNext() { fetch(); return next != null; } public T next() { fetch(); T r = next; if (r == null) throw new NoSuchElementException(); next = null; return r; } public void remove() { throw new UnsupportedOperationException(); } private void fetch() { if (next != null) return; // already fetched if (url == null) return; // no more data to fetch try { next = _fetch(tailApiUrl, url, () -> parse(type, null)); assert next != null; findNextURL(); } catch (IOException e) { throw new GHException("Failed to retrieve " + url, e); } } /** * Locate the next page from the pagination "Link" tag. */ private void findNextURL() throws MalformedURLException { url = null; // start defensively String link = uc.getHeaderField("Link"); if (link == null) return; for (String token : link.split(", ")) { if (token.endsWith("rel=\"next\"")) { // found the next page. This should look something like // <https://api.github.com/repos?page=3&per_page=100>; rel="next" int idx = token.indexOf('>'); url = new URL(token.substring(1, idx)); return; } } // no more "next" link. we are done. } } private HttpURLConnection setupConnection(URL url) throws IOException { if (LOGGER.isLoggable(FINE)) { LOGGER.log(FINE, "GitHub API request [" + (root.login == null ? "anonymous" : root.login) + "]: " + method + " " + url.toString()); } HttpURLConnection connection = root.getConnector().connect(url); // if the authentication is needed but no credential is given, try it anyway (so that some calls // that do work with anonymous access in the reduced form should still work.) if (root.encodedAuthorization != null) connection.setRequestProperty("Authorization", root.encodedAuthorization); for (Map.Entry<String, String> e : headers.entrySet()) { String v = e.getValue(); if (v != null) connection.setRequestProperty(e.getKey(), v); } setRequestMethod(connection); connection.setRequestProperty("Accept-Encoding", "gzip"); buildRequest(connection); return connection; } private void setRequestMethod(HttpURLConnection connection) throws IOException { try { connection.setRequestMethod(method); } catch (ProtocolException e) { // JDK only allows one of the fixed set of verbs. Try to override that try { Field $method = HttpURLConnection.class.getDeclaredField("method"); $method.setAccessible(true); $method.set(connection, method); } catch (Exception x) { throw (IOException) new IOException("Failed to set the custom verb").initCause(x); } // sun.net.www.protocol.https.DelegatingHttpsURLConnection delegates to another HttpURLConnection try { Field $delegate = connection.getClass().getDeclaredField("delegate"); $delegate.setAccessible(true); Object delegate = $delegate.get(connection); if (delegate instanceof HttpURLConnection) { HttpURLConnection nested = (HttpURLConnection) delegate; setRequestMethod(nested); } } catch (NoSuchFieldException x) { // no problem } catch (IllegalAccessException x) { throw (IOException) new IOException("Failed to set the custom verb").initCause(x); } } if (!connection.getRequestMethod().equals(method)) throw new IllegalStateException("Failed to set the request method to " + method); } @CheckForNull private <T> T parse(Class<T> type, T instance) throws IOException { return parse(type, instance, 2); } private <T> T parse(Class<T> type, T instance, int timeouts) throws IOException { InputStreamReader r = null; int responseCode = -1; String responseMessage = null; try { responseCode = uc.getResponseCode(); responseMessage = uc.getResponseMessage(); if (responseCode == 304) { return null; // special case handling for 304 unmodified, as the content will be "" } if (responseCode == 204 && type != null && type.isArray()) { // no content return type.cast(Array.newInstance(type.getComponentType(), 0)); } // Response code 202 means data is being generated still being cached. // This happens in for statistics: // See https://developer.github.com/v3/repos/statistics/#a-word-about-caching // And for fork creation: // See https://developer.github.com/v3/repos/forks/#create-a-fork if (responseCode == 202) { if (uc.getURL().toString().endsWith("/forks")) { LOGGER.log(INFO, "The fork is being created. Please try again in 5 seconds."); } else if (uc.getURL().toString().endsWith("/statistics")) { LOGGER.log(INFO, "The statistics are being generated. Please try again in 5 seconds."); } else { LOGGER.log(INFO, "Received 202 from " + uc.getURL().toString() + " . Please try again in 5 seconds."); } // Maybe throw an exception instead? return null; } if (type != null && type.equals(InputStream.class)) { return type.cast(wrapStream(uc.getInputStream())); } r = new InputStreamReader(wrapStream(uc.getInputStream()), StandardCharsets.UTF_8); String data = IOUtils.toString(r); if (type != null) try { return setResponseHeaders(MAPPER.readValue(data, type)); } catch (JsonMappingException e) { String message = "Failed to deserialize " + data; throw (IOException) new IOException(message).initCause(e); } if (instance != null) { return setResponseHeaders(MAPPER.readerForUpdating(instance).<T>readValue(data)); } return null; } catch (FileNotFoundException e) { // java.net.URLConnection handles 404 exception as FileNotFoundException, // don't wrap exception in HttpException to preserve backward compatibility throw e; } catch (IOException e) { if ((e instanceof SocketException || e instanceof SocketTimeoutException) && timeouts > 0) { LOGGER.log(INFO, "timed out accessing " + uc.getURL() + ". Sleeping " + Requester.retryTimeoutMillis + " milliseconds before retrying... ; will try " + timeouts + " more time(s)", e); try { Thread.sleep(Requester.retryTimeoutMillis); } catch (InterruptedException ie) { throw (IOException) new InterruptedIOException().initCause(e); } return parse(type, instance, timeouts - 1); } throw new HttpException(responseCode, responseMessage, uc.getURL(), e); } finally { IOUtils.closeQuietly(r); } } private void retryInvalidCached404Response() throws IOException { // WORKAROUND FOR ISSUE #669: // When the Requester detects a 404 response with an ETag (only happpens when the server's 304 // is bogus and would cause cache corruption), try the query again with new request header // that forces the server to not return 304 and return new data instead. // // This solution is transparent to users of this library and automatically handles a // situation that was cause insidious and hard to debug bad responses in caching // scenarios. If GitHub ever fixes their issue and/or begins providing accurate ETags to // their 404 responses, this will result in at worst two requests being made for each 404 // responses. However, only the second request will count against rate limit. int responseCode = uc.getResponseCode(); if (responseCode == 404 && Objects.equals(uc.getRequestMethod(), "GET") && uc.getHeaderField("ETag") != null && !Objects.equals(uc.getRequestProperty("Cache-Control"), "no-cache")) { uc = setupConnection(uc.getURL()); // Setting "Cache-Control" to "no-cache" stops the cache from supplying // "If-Modified-Since" or "If-None-Match" values. // This makes GitHub give us current data (not incorrectly cached data) uc.setRequestProperty("Cache-Control", "no-cache"); uc.getResponseCode(); } } private <T> T setResponseHeaders(T readValue) { if (readValue instanceof GHObject[]) { for (GHObject ghObject : (GHObject[]) readValue) { setResponseHeaders(ghObject); } } else if (readValue instanceof GHObject) { setResponseHeaders((GHObject) readValue); } else if (readValue instanceof JsonRateLimit) { // if we're getting a GHRateLimit it needs the server date ((JsonRateLimit) readValue).resources.getCore().recalculateResetDate(uc.getHeaderField("Date")); } return readValue; } private void setResponseHeaders(GHObject readValue) { readValue.responseHeaderFields = uc.getHeaderFields(); } /** * Handles the "Content-Encoding" header. */ private InputStream wrapStream(InputStream in) throws IOException { String encoding = uc.getContentEncoding(); if (encoding == null || in == null) return in; if (encoding.equals("gzip")) return new GZIPInputStream(in); throw new UnsupportedOperationException("Unexpected Content-Encoding: " + encoding); } /** * Handle API error by either throwing it or by returning normally to retry. */ void handleApiError(IOException e) throws IOException { int responseCode; try { responseCode = uc.getResponseCode(); } catch (IOException e2) { // likely to be a network exception (e.g. SSLHandshakeException), // uc.getResponseCode() and any other getter on the response will cause an exception if (LOGGER.isLoggable(FINE)) LOGGER.log(FINE, "Silently ignore exception retrieving response code for '" + uc.getURL() + "'" + " handling exception " + e, e); throw e; } InputStream es = wrapStream(uc.getErrorStream()); if (es != null) { try { String error = IOUtils.toString(es, StandardCharsets.UTF_8); if (e instanceof FileNotFoundException) { // pass through 404 Not Found to allow the caller to handle it intelligently e = (IOException) new GHFileNotFoundException(error).withResponseHeaderFields(uc).initCause(e); } else if (e instanceof HttpException) { HttpException http = (HttpException) e; e = new HttpException(error, http.getResponseCode(), http.getResponseMessage(), http.getUrl(), e); } else { e = (IOException) new GHIOException(error).withResponseHeaderFields(uc).initCause(e); } } finally { IOUtils.closeQuietly(es); } } if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) // 401 Unauthorized == bad creds or OTP request // In the case of a user with 2fa enabled, a header with X-GitHub-OTP // will be returned indicating the user needs to respond with an otp if (uc.getHeaderField("X-GitHub-OTP") != null) throw (IOException) new GHOTPRequiredException().withResponseHeaderFields(uc).initCause(e); else throw e; // usually org.kohsuke.github.HttpException (which extends IOException) if ("0".equals(uc.getHeaderField("X-RateLimit-Remaining"))) { root.rateLimitHandler.onError(e, uc); return; } // Retry-After is not documented but apparently that field exists if (responseCode == HttpURLConnection.HTTP_FORBIDDEN && uc.getHeaderField("Retry-After") != null) { this.root.abuseLimitHandler.onError(e, uc); return; } throw e; } /** * Transform Java Enum into Github constants given its conventions * * @param en * Enum to be transformed * @return a String containing the value of a Github constant */ static String transformEnum(Enum en) { // by convention Java constant names are upper cases, but github uses // lower-case constants. GitHub also uses '-', which in Java we always // replace by '_' return en.toString().toLowerCase(Locale.ENGLISH).replace('_', '-'); } /** * Encode the path to url safe string. * * @param value * string to be path encoded. * @return The encoded string. */ public static String urlPathEncode(String value) { try { return new URI(null, null, value, null, null).toString(); } catch (URISyntaxException ex) { throw new AssertionError(ex); } } private static final List<String> METHODS_WITHOUT_BODY = asList("GET", "DELETE"); private static final Logger LOGGER = Logger.getLogger(Requester.class.getName()); /** * Represents a supplier of results that can throw. * * <p> * This is a <a href="package-summary.html">functional interface</a> whose functional method is {@link #get()}. * * @param <T> * the type of results supplied by this supplier * @param <E> * the type of throwable that could be thrown */ @FunctionalInterface interface SupplierThrows<T, E extends Throwable> { /** * Gets a result. * * @return a result * @throws E */ T get() throws E; } }
src/main/java/org/kohsuke/github/Requester.java
/* * The MIT License * * Copyright (c) 2010, Kohsuke Kawaguchi * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.kohsuke.github; import com.fasterxml.jackson.databind.JsonMappingException; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.InterruptedIOException; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.SocketException; import java.net.SocketTimeoutException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.NoSuchElementException; import java.util.Objects; import java.util.function.Consumer; import java.util.logging.Logger; import java.util.zip.GZIPInputStream; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import javax.annotation.WillClose; import static java.util.Arrays.asList; import static java.util.logging.Level.*; import static org.apache.commons.lang3.StringUtils.defaultString; import static org.kohsuke.github.GitHub.MAPPER; import static org.kohsuke.github.GitHub.connect; /** * A builder pattern for making HTTP call and parsing its output. * * @author Kohsuke Kawaguchi */ class Requester { private final GitHub root; private final List<Entry> args = new ArrayList<Entry>(); private final Map<String, String> headers = new LinkedHashMap<String, String>(); @Nonnull private String urlPath = "/"; /** * Request method. */ private String method = "GET"; private String contentType = null; private InputStream body; /** * Current connection. */ private HttpURLConnection uc; private boolean forceBody; private static class Entry { final String key; final Object value; private Entry(String key, Object value) { this.key = key; this.value = value; } } Requester(GitHub root) { this.root = root; } /** * Sets the request HTTP header. * <p> * If a header of the same name is already set, this method overrides it. * * @param name * the name * @param value * the value */ public void setHeader(String name, String value) { headers.put(name, value); } /** * With header requester. * * @param name * the name * @param value * the value * @return the requester */ public Requester withHeader(String name, String value) { setHeader(name, value); return this; } public Requester withPreview(String name) { return withHeader("Accept", name); } /** * With requester. * * @param key * the key * @param value * the value * @return the requester */ public Requester with(String key, int value) { return with(key, (Object) value); } /** * With requester. * * @param key * the key * @param value * the value * @return the requester */ public Requester with(String key, long value) { return with(key, (Object) value); } /** * With requester. * * @param key * the key * @param value * the value * @return the requester */ public Requester with(String key, boolean value) { return with(key, (Object) value); } /** * With requester. * * @param key * the key * @param e * the e * @return the requester */ public Requester with(String key, Enum e) { if (e == null) return with(key, (Object) null); return with(key, transformEnum(e)); } /** * With requester. * * @param key * the key * @param value * the value * @return the requester */ public Requester with(String key, String value) { return with(key, (Object) value); } /** * With requester. * * @param key * the key * @param value * the value * @return the requester */ public Requester with(String key, Collection<?> value) { return with(key, (Object) value); } /** * With requester. * * @param key * the key * @param value * the value * @return the requester */ public Requester with(String key, Map<String, String> value) { return with(key, (Object) value); } /** * With requester. * * @param body * the body * @return the requester */ public Requester with(@WillClose /* later */ InputStream body) { this.body = body; return this; } /** * With nullable requester. * * @param key * the key * @param value * the value * @return the requester */ public Requester withNullable(String key, Object value) { args.add(new Entry(key, value)); return this; } /** * With requester. * * @param key * the key * @param value * the value * @return the requester */ public Requester with(String key, Object value) { if (value != null) { args.add(new Entry(key, value)); } return this; } /** * Unlike {@link #with(String, String)}, overrides the existing value * * @param key * the key * @param value * the value * @return the requester */ public Requester set(String key, Object value) { for (int index = 0; index < args.size(); index++) { if (args.get(index).key.equals(key)) { args.set(index, new Entry(key, value)); return this; } } return with(key, value); } /** * Method requester. * * @param method * the method * @return the requester */ public Requester method(String method) { this.method = method; return this; } /** * Content type requester. * * @param contentType * the content type * @return the requester */ public Requester contentType(String contentType) { this.contentType = contentType; return this; } /** * NOT FOR PUBLIC USE. Do not make this method public. * <p> * Sets the path component of api URL without URI encoding. * <p> * Should only be used when passing a literal URL field from a GHObject, such as {@link GHContent#refresh()} or when * needing to set query parameters on requests methods that don't usually have them, such as * {@link GHRelease#uploadAsset(String, InputStream, String)}. * * @param urlOrPath * the content type * @return the requester */ Requester setRawUrlPath(String urlOrPath) { Objects.requireNonNull(urlOrPath); this.urlPath = urlOrPath; return this; } /** * Path component of api URL. Appended to api url. * <p> * If urlPath starts with a slash, it will be URI encoded as a path. If it starts with anything else, it will be * used as is. * * @param urlPathItems * the content type * @return the requester */ public Requester withUrlPath(String... urlPathItems) { if (!this.urlPath.startsWith("/")) { throw new GHException("Cannot append to url path after setting a raw path"); } if (urlPathItems.length == 1 && !urlPathItems[0].startsWith("/")) { return setRawUrlPath(urlPathItems[0]); } String tailUrlPath = String.join("/", urlPathItems); if (this.urlPath.endsWith("/")) { tailUrlPath = StringUtils.stripStart(tailUrlPath, "/"); } else { tailUrlPath = StringUtils.prependIfMissing(tailUrlPath, "/"); } this.urlPath += urlPathEncode(tailUrlPath); return this; } /** * Small number of GitHub APIs use HTTP methods somewhat inconsistently, and use a body where it's not expected. * Normally whether parameters go as query parameters or a body depends on the HTTP verb in use, but this method * forces the parameters to be sent as a body. */ public Requester inBody() { forceBody = true; return this; } /** * Sends a request to the specified URL and checks that it is sucessful. * * @throws IOException * the io exception */ public void send() throws IOException { _fetch(() -> parse(null, null)); } /** * Sends a request and parses the response into the given type via databinding. * * @param <T> * the type parameter * @param type * the type * @return {@link Reader} that reads the response. * @throws IOException * if the server returns 4xx/5xx responses. */ public <T> T fetch(@Nonnull Class<T> type) throws IOException { return _fetch(() -> parse(type, null)); } /** * Sends a request and parses the response into an array of the given type via databinding. * * @param <T> * the type parameter * @param type * the type * @return {@link Reader} that reads the response. * @throws IOException * if the server returns 4xx/5xx responses. */ public <T> T[] fetchArray(@Nonnull Class<T[]> type) throws IOException { T[] result = null; try { // for arrays we might have to loop for pagination // use the iterator to handle it List<T[]> pages = new ArrayList<>(); int totalSize = 0; for (Iterator<T[]> iterator = asIterator(type, 0); iterator.hasNext();) { T[] nextResult = iterator.next(); totalSize += Array.getLength(nextResult); pages.add(nextResult); } result = concatenatePages(type, pages, totalSize); } catch (GHException e) { // if there was an exception inside the iterator it is wrapped as a GHException // if the wrapped exception is an IOException, throw that if (e.getCause() instanceof IOException) { throw (IOException) e.getCause(); } else { throw e; } } return result; } /** * Like {@link #fetch(Class)} but updates an existing object instead of creating a new instance. * * @param <T> * the type parameter * @param existingInstance * the existing instance * @return the t * @throws IOException * the io exception */ public <T> T fetchInto(@Nonnull T existingInstance) throws IOException { return _fetch(() -> parse(null, existingInstance)); } /** * Makes a request and just obtains the HTTP status code. Method does not throw exceptions for many status codes * that would otherwise throw. * * @return the int * @throws IOException * the io exception */ public int fetchHttpStatusCode() throws IOException { return _fetch(() -> uc.getResponseCode()); } /** * As stream input stream. * * @return the input stream * @throws IOException * the io exception */ public InputStream fetchStream() throws IOException { return _fetch(() -> parse(InputStream.class, null)); } private <T> T _fetch(SupplierThrows<T, IOException> supplier) throws IOException { String tailApiUrl = buildTailApiUrl(urlPath); URL url = root.getApiURL(tailApiUrl); return _fetch(tailApiUrl, url, supplier); } private <T> T _fetch(String tailApiUrl, URL url, SupplierThrows<T, IOException> supplier) throws IOException { while (true) {// loop while API rate limit is hit uc = setupConnection(url); try { retryInvalidCached404Response(); return supplier.get(); } catch (IOException e) { handleApiError(e); } finally { noteRateLimit(tailApiUrl); } } } private <T> T[] concatenatePages(Class<T[]> type, List<T[]> pages, int totalLength) { T[] result = type.cast(Array.newInstance(type.getComponentType(), totalLength)); int position = 0; for (T[] page : pages) { final int pageLength = Array.getLength(page); System.arraycopy(page, 0, result, position, pageLength); position += pageLength; } return result; } private String buildTailApiUrl(String tailApiUrl) { if (!isMethodWithBody() && !args.isEmpty()) { try { boolean questionMarkFound = tailApiUrl.indexOf('?') != -1; StringBuilder argString = new StringBuilder(); argString.append(questionMarkFound ? '&' : '?'); for (Iterator<Entry> it = args.listIterator(); it.hasNext();) { Entry arg = it.next(); argString.append(URLEncoder.encode(arg.key, StandardCharsets.UTF_8.name())); argString.append('='); argString.append(URLEncoder.encode(arg.value.toString(), StandardCharsets.UTF_8.name())); if (it.hasNext()) { argString.append('&'); } } tailApiUrl += argString; } catch (UnsupportedEncodingException e) { throw new AssertionError(e); // UTF-8 is mandatory } } return tailApiUrl; } private void noteRateLimit(String tailApiUrl) { if (uc == null) { return; } if (tailApiUrl.startsWith("/search")) { // the search API uses a different rate limit return; } String limitString = uc.getHeaderField("X-RateLimit-Limit"); if (StringUtils.isBlank(limitString)) { // if we are missing a header, return fast return; } String remainingString = uc.getHeaderField("X-RateLimit-Remaining"); if (StringUtils.isBlank(remainingString)) { // if we are missing a header, return fast return; } String resetString = uc.getHeaderField("X-RateLimit-Reset"); if (StringUtils.isBlank(resetString)) { // if we are missing a header, return fast return; } int limit, remaining; long reset; try { limit = Integer.parseInt(limitString); } catch (NumberFormatException e) { if (LOGGER.isLoggable(FINEST)) { LOGGER.log(FINEST, "Malformed X-RateLimit-Limit header value " + limitString, e); } return; } try { remaining = Integer.parseInt(remainingString); } catch (NumberFormatException e) { if (LOGGER.isLoggable(FINEST)) { LOGGER.log(FINEST, "Malformed X-RateLimit-Remaining header value " + remainingString, e); } return; } try { reset = Long.parseLong(resetString); } catch (NumberFormatException e) { if (LOGGER.isLoggable(FINEST)) { LOGGER.log(FINEST, "Malformed X-RateLimit-Reset header value " + resetString, e); } return; } GHRateLimit.Record observed = new GHRateLimit.Record(limit, remaining, reset, uc.getHeaderField("Date")); root.updateCoreRateLimit(observed); } /** * Gets response header. * * @param header * the header * @return the response header */ public String getResponseHeader(String header) { return uc.getHeaderField(header); } /** * Set up the request parameters or POST payload. */ private void buildRequest(HttpURLConnection connection) throws IOException { if (isMethodWithBody()) { connection.setDoOutput(true); if (body == null) { connection.setRequestProperty("Content-type", defaultString(contentType, "application/json")); Map json = new HashMap(); for (Entry e : args) { json.put(e.key, e.value); } MAPPER.writeValue(connection.getOutputStream(), json); } else { connection.setRequestProperty("Content-type", defaultString(contentType, "application/x-www-form-urlencoded")); try { byte[] bytes = new byte[32768]; int read; while ((read = body.read(bytes)) != -1) { connection.getOutputStream().write(bytes, 0, read); } } finally { body.close(); } } } } private boolean isMethodWithBody() { return forceBody || !METHODS_WITHOUT_BODY.contains(method); } <T> PagedIterable<T> toIterable(Class<T[]> type, Consumer<T> consumer) { return new PagedIterableWithConsumer<>(type, consumer); } class PagedIterableWithConsumer<T> extends PagedIterable<T> { private final Class<T[]> clazz; private final Consumer<T> consumer; PagedIterableWithConsumer(Class<T[]> clazz, Consumer<T> consumer) { this.clazz = clazz; this.consumer = consumer; } @Override public PagedIterator<T> _iterator(int pageSize) { final Iterator<T[]> iterator = asIterator(clazz, pageSize); return new PagedIterator<T>(iterator) { @Override protected void wrapUp(T[] page) { if (consumer != null) { for (T item : page) { consumer.accept(item); } } } }; } } /** * Loads paginated resources. * * @param type * type of each page (not the items in the page). * @param pageSize * the size of the * @param <T> * type of each page (not the items in the page). * @return */ <T> Iterator<T> asIterator(Class<T> type, int pageSize) { if (!"GET".equals(method)) { throw new IllegalStateException("Request method \"GET\" is required for iterator."); } if (pageSize > 0) args.add(new Entry("per_page", pageSize)); String tailApiUrl = buildTailApiUrl(urlPath); try { return new PagingIterator<>(type, tailApiUrl, root.getApiURL(tailApiUrl)); } catch (IOException e) { throw new GHException("Unable to build github Api URL", e); } } /** * May be used for any item that has pagination information. * * Works for array responses, also works for search results which are single instances with an array of items * inside. * * @param <T> * type of each page (not the items in the page). */ class PagingIterator<T> implements Iterator<T> { private final Class<T> type; private final String tailApiUrl; /** * The next batch to be returned from {@link #next()}. */ private T next; /** * URL of the next resource to be retrieved, or null if no more data is available. */ private URL url; PagingIterator(Class<T> type, String tailApiUrl, URL url) { this.type = type; this.tailApiUrl = tailApiUrl; this.url = url; } public boolean hasNext() { fetch(); return next != null; } public T next() { fetch(); T r = next; if (r == null) throw new NoSuchElementException(); next = null; return r; } public void remove() { throw new UnsupportedOperationException(); } private void fetch() { if (next != null) return; // already fetched if (url == null) return; // no more data to fetch try { next = _fetch(tailApiUrl, url, () -> parse(type, null)); assert next != null; findNextURL(); } catch (IOException e) { throw new GHException("Failed to retrieve " + url, e); } } /** * Locate the next page from the pagination "Link" tag. */ private void findNextURL() throws MalformedURLException { url = null; // start defensively String link = uc.getHeaderField("Link"); if (link == null) return; for (String token : link.split(", ")) { if (token.endsWith("rel=\"next\"")) { // found the next page. This should look something like // <https://api.github.com/repos?page=3&per_page=100>; rel="next" int idx = token.indexOf('>'); url = new URL(token.substring(1, idx)); return; } } // no more "next" link. we are done. } } private HttpURLConnection setupConnection(URL url) throws IOException { if (LOGGER.isLoggable(FINE)) { LOGGER.log(FINE, "GitHub API request [" + (root.login == null ? "anonymous" : root.login) + "]: " + method + " " + url.toString()); } HttpURLConnection connection = root.getConnector().connect(url); // if the authentication is needed but no credential is given, try it anyway (so that some calls // that do work with anonymous access in the reduced form should still work.) if (root.encodedAuthorization != null) connection.setRequestProperty("Authorization", root.encodedAuthorization); for (Map.Entry<String, String> e : headers.entrySet()) { String v = e.getValue(); if (v != null) connection.setRequestProperty(e.getKey(), v); } setRequestMethod(connection); connection.setRequestProperty("Accept-Encoding", "gzip"); buildRequest(connection); return connection; } private void setRequestMethod(HttpURLConnection connection) throws IOException { try { connection.setRequestMethod(method); } catch (ProtocolException e) { // JDK only allows one of the fixed set of verbs. Try to override that try { Field $method = HttpURLConnection.class.getDeclaredField("method"); $method.setAccessible(true); $method.set(connection, method); } catch (Exception x) { throw (IOException) new IOException("Failed to set the custom verb").initCause(x); } // sun.net.www.protocol.https.DelegatingHttpsURLConnection delegates to another HttpURLConnection try { Field $delegate = connection.getClass().getDeclaredField("delegate"); $delegate.setAccessible(true); Object delegate = $delegate.get(connection); if (delegate instanceof HttpURLConnection) { HttpURLConnection nested = (HttpURLConnection) delegate; setRequestMethod(nested); } } catch (NoSuchFieldException x) { // no problem } catch (IllegalAccessException x) { throw (IOException) new IOException("Failed to set the custom verb").initCause(x); } } if (!connection.getRequestMethod().equals(method)) throw new IllegalStateException("Failed to set the request method to " + method); } @CheckForNull private <T> T parse(Class<T> type, T instance) throws IOException { return parse(type, instance, 2); } private <T> T parse(Class<T> type, T instance, int timeouts) throws IOException { InputStreamReader r = null; int responseCode = -1; String responseMessage = null; try { responseCode = uc.getResponseCode(); responseMessage = uc.getResponseMessage(); if (responseCode == 304) { return null; // special case handling for 304 unmodified, as the content will be "" } if (responseCode == 204 && type != null && type.isArray()) { // no content return type.cast(Array.newInstance(type.getComponentType(), 0)); } // Response code 202 means data is being generated still being cached. // This happens in for statistics: // See https://developer.github.com/v3/repos/statistics/#a-word-about-caching // And for fork creation: // See https://developer.github.com/v3/repos/forks/#create-a-fork if (responseCode == 202) { if (uc.getURL().toString().endsWith("/forks")) { LOGGER.log(INFO, "The fork is being created. Please try again in 5 seconds."); } else if (uc.getURL().toString().endsWith("/statistics")) { LOGGER.log(INFO, "The statistics are being generated. Please try again in 5 seconds."); } else { LOGGER.log(INFO, "Received 202 from " + uc.getURL().toString() + " . Please try again in 5 seconds."); } // Maybe throw an exception instead? return null; } if (type != null && type.equals(InputStream.class)) { return type.cast(wrapStream(uc.getInputStream())); } r = new InputStreamReader(wrapStream(uc.getInputStream()), StandardCharsets.UTF_8); String data = IOUtils.toString(r); if (type != null) try { return setResponseHeaders(MAPPER.readValue(data, type)); } catch (JsonMappingException e) { String message = "Failed to deserialize " + data; throw (IOException) new IOException(message).initCause(e); } if (instance != null) { return setResponseHeaders(MAPPER.readerForUpdating(instance).<T>readValue(data)); } return null; } catch (FileNotFoundException e) { // java.net.URLConnection handles 404 exception as FileNotFoundException, // don't wrap exception in HttpException to preserve backward compatibility throw e; } catch (IOException e) { if ((e instanceof SocketException || e instanceof SocketTimeoutException) && timeouts > 0) { LOGGER.log(INFO, "timed out accessing " + uc.getURL() + ". Sleeping 5 seconds before retrying... ; will try" + timeouts + " more time(s)", e); try { Thread.sleep(5000); } catch (InterruptedException ie) { throw (IOException) new InterruptedIOException().initCause(e); } return parse(type, instance, timeouts - 1); } throw new HttpException(responseCode, responseMessage, uc.getURL(), e); } finally { IOUtils.closeQuietly(r); } } private void retryInvalidCached404Response() throws IOException { // WORKAROUND FOR ISSUE #669: // When the Requester detects a 404 response with an ETag (only happpens when the server's 304 // is bogus and would cause cache corruption), try the query again with new request header // that forces the server to not return 304 and return new data instead. // // This solution is transparent to users of this library and automatically handles a // situation that was cause insidious and hard to debug bad responses in caching // scenarios. If GitHub ever fixes their issue and/or begins providing accurate ETags to // their 404 responses, this will result in at worst two requests being made for each 404 // responses. However, only the second request will count against rate limit. int responseCode = uc.getResponseCode(); if (responseCode == 404 && Objects.equals(uc.getRequestMethod(), "GET") && uc.getHeaderField("ETag") != null && !Objects.equals(uc.getRequestProperty("Cache-Control"), "no-cache")) { uc = setupConnection(uc.getURL()); // Setting "Cache-Control" to "no-cache" stops the cache from supplying // "If-Modified-Since" or "If-None-Match" values. // This makes GitHub give us current data (not incorrectly cached data) uc.setRequestProperty("Cache-Control", "no-cache"); uc.getResponseCode(); } } private <T> T setResponseHeaders(T readValue) { if (readValue instanceof GHObject[]) { for (GHObject ghObject : (GHObject[]) readValue) { setResponseHeaders(ghObject); } } else if (readValue instanceof GHObject) { setResponseHeaders((GHObject) readValue); } else if (readValue instanceof JsonRateLimit) { // if we're getting a GHRateLimit it needs the server date ((JsonRateLimit) readValue).resources.getCore().recalculateResetDate(uc.getHeaderField("Date")); } return readValue; } private void setResponseHeaders(GHObject readValue) { readValue.responseHeaderFields = uc.getHeaderFields(); } /** * Handles the "Content-Encoding" header. */ private InputStream wrapStream(InputStream in) throws IOException { String encoding = uc.getContentEncoding(); if (encoding == null || in == null) return in; if (encoding.equals("gzip")) return new GZIPInputStream(in); throw new UnsupportedOperationException("Unexpected Content-Encoding: " + encoding); } /** * Handle API error by either throwing it or by returning normally to retry. */ void handleApiError(IOException e) throws IOException { int responseCode; try { responseCode = uc.getResponseCode(); } catch (IOException e2) { // likely to be a network exception (e.g. SSLHandshakeException), // uc.getResponseCode() and any other getter on the response will cause an exception if (LOGGER.isLoggable(FINE)) LOGGER.log(FINE, "Silently ignore exception retrieving response code for '" + uc.getURL() + "'" + " handling exception " + e, e); throw e; } InputStream es = wrapStream(uc.getErrorStream()); if (es != null) { try { String error = IOUtils.toString(es, StandardCharsets.UTF_8); if (e instanceof FileNotFoundException) { // pass through 404 Not Found to allow the caller to handle it intelligently e = (IOException) new GHFileNotFoundException(error).withResponseHeaderFields(uc).initCause(e); } else if (e instanceof HttpException) { HttpException http = (HttpException) e; e = new HttpException(error, http.getResponseCode(), http.getResponseMessage(), http.getUrl(), e); } else { e = (IOException) new GHIOException(error).withResponseHeaderFields(uc).initCause(e); } } finally { IOUtils.closeQuietly(es); } } if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) // 401 Unauthorized == bad creds or OTP request // In the case of a user with 2fa enabled, a header with X-GitHub-OTP // will be returned indicating the user needs to respond with an otp if (uc.getHeaderField("X-GitHub-OTP") != null) throw (IOException) new GHOTPRequiredException().withResponseHeaderFields(uc).initCause(e); else throw e; // usually org.kohsuke.github.HttpException (which extends IOException) if ("0".equals(uc.getHeaderField("X-RateLimit-Remaining"))) { root.rateLimitHandler.onError(e, uc); return; } // Retry-After is not documented but apparently that field exists if (responseCode == HttpURLConnection.HTTP_FORBIDDEN && uc.getHeaderField("Retry-After") != null) { this.root.abuseLimitHandler.onError(e, uc); return; } throw e; } /** * Transform Java Enum into Github constants given its conventions * * @param en * Enum to be transformed * @return a String containing the value of a Github constant */ static String transformEnum(Enum en) { // by convention Java constant names are upper cases, but github uses // lower-case constants. GitHub also uses '-', which in Java we always // replace by '_' return en.toString().toLowerCase(Locale.ENGLISH).replace('_', '-'); } /** * Encode the path to url safe string. * * @param value * string to be path encoded. * @return The encoded string. */ public static String urlPathEncode(String value) { try { return new URI(null, null, value, null, null).toString(); } catch (URISyntaxException ex) { throw new AssertionError(ex); } } private static final List<String> METHODS_WITHOUT_BODY = asList("GET", "DELETE"); private static final Logger LOGGER = Logger.getLogger(Requester.class.getName()); /** * Represents a supplier of results that can throw. * * <p> * This is a <a href="package-summary.html">functional interface</a> whose functional method is {@link #get()}. * * @param <T> * the type of results supplied by this supplier * @param <E> * the type of throwable that could be thrown */ @FunctionalInterface interface SupplierThrows<T, E extends Throwable> { /** * Gets a result. * * @return a result * @throws E */ T get() throws E; } }
As suggested in the code review, make a configurable sleep
src/main/java/org/kohsuke/github/Requester.java
As suggested in the code review, make a configurable sleep
Java
mit
c87191dfc90098c5c8b8bfe4488c97cf236cae46
0
sigopt/sigopt-java,sigopt/sigopt-java
package com.sigopt.model; import com.sigopt.net.APIMethodCaller; import com.sigopt.net.PaginatedAPIMethodCaller; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import java.util.Map; public class Experiment extends StructObject { public Experiment() { super(); } public Experiment(String id) { super(); this.set("id", id); } public String getId() { return (String) this.get("id"); } public String getUser() { return (String) this.get("user"); } public String getType() { return (String) this.get("type"); } public String getName() { return (String) this.get("name"); } public List<Parameter> getParameters() { return Utils.mergeIntoList(new ArrayList<Parameter>(), this.get("parameters"), Parameter.class); } public List<Metric> getMetrics() { return Utils.mergeIntoList(new ArrayList<Metric>(), this.get("metrics"), Metric.class); } public Metric getMetric() { return Utils.mergeInto(new Metric(), this.get("metric")); } public Progress getProgress() { return Utils.mergeInto(new Progress(), this.get("progress")); } public Metadata getMetadata() { return Utils.mergeInto(new Metadata(), this.get("metadata")); } public String getClient() { return (String) this.get("client"); } public String getState() { return (String) this.get("state"); } public Integer getCreated() { return Utils.asInteger(this.get("created")); } public Integer getUpdated() { return Utils.asInteger(this.get("updated")); } public Integer getObservationBudget() { return Utils.asInteger(this.get("observation_budget")); } public Integer getNumSolutions() { return Utils.asInteger(this.get("num_solutions")); } public Boolean getDevelopment() { return (Boolean) this.get("development"); } public Integer getFolds() { return Utils.asInteger(this.get("folds")); } public List<LinearConstraint> getLinearConstraints() { return Utils.mergeIntoList(new ArrayList<LinearConstraint>(), this.get("linear_constraints"), LinearConstraint.class); } public List<Conditional> getConditionals() { return Utils.mergeIntoList(new ArrayList<Conditional>(), this.get("conditionals"), Conditional.class); } public static APIMethodCaller<Experiment> fetch() { return new APIMethodCaller<Experiment>("get", "/experiments/:id", Experiment.class); } public static APIMethodCaller<Experiment> fetch(String id) { return Experiment.fetch().addPathComponent("id", id); } public static PaginatedAPIMethodCaller<Experiment> list() { return new PaginatedAPIMethodCaller<Experiment>("get", "/experiments", Experiment.class); } public static APIMethodCaller<Experiment> create() { return new APIMethodCaller<Experiment>("post", "/experiments", Experiment.class); } public static APIMethodCaller<Experiment> create(Experiment e) { return Experiment.create().data(e); } public static APIMethodCaller<Experiment> update() { return new APIMethodCaller<Experiment>("put", "/experiments/:id", Experiment.class); } public static APIMethodCaller<Experiment> update(String id) { return Experiment.update().addPathComponent("id", id); } public static APIMethodCaller<Experiment> update(String id, Experiment e) { return Experiment.update(id).data(e); } public static APIMethodCaller<VoidObject> delete() { return new APIMethodCaller<VoidObject>("delete", "/experiments/:id", VoidObject.class); } public static APIMethodCaller<VoidObject> delete(String id) { return Experiment.delete().addPathComponent("id", id); } /** * PropertyResource is used for a resource linked strongly to another e.g. * StoppingCriteria isn't a full object with its own id but still must be * retrieved as its own resource separate from Experiment */ public static class PropertyResource<T extends APIObject> extends BoundObject { String name; Class<T> klass; public PropertyResource(String prefix, String name, Class<T> klass) { super(prefix); this.name = name; this.klass = klass; } public APIMethodCaller<T> fetch() { return new APIMethodCaller<T>("get", this.prefix() + "/" + this.name, klass); } } public static class Subresource<T extends APIObject> extends BoundObject { String name; Class<T> klass; public Subresource(String prefix, String name, Class<T> klass) { super(prefix); this.name = name; this.klass = klass; } public APIMethodCaller<T> fetch() { return new APIMethodCaller<T>("get", this.prefix() + "/" + this.name + "/:id", klass); } public APIMethodCaller<T> fetch(String id) { return this.fetch().addPathComponent("id", id); } public PaginatedAPIMethodCaller<T> list() { return new PaginatedAPIMethodCaller<T>("get", this.prefix() + "/" + this.name, klass); } public APIMethodCaller<T> create() { return new APIMethodCaller<T>("post", this.prefix() + "/" + this.name, klass); } public APIMethodCaller<T> create(T o) { return this.create().data(o); } public APIMethodCaller<T> update() { return new APIMethodCaller<T>("put", this.prefix() + "/" + this.name + "/:id", klass); } public APIMethodCaller<T> update(String id) { return this.update().addPathComponent("id", id); } public APIMethodCaller<T> update(String id, T o) { return this.update(id).data(o); } public APIMethodCaller<VoidObject> deleteList() { return new APIMethodCaller<VoidObject>("delete", this.prefix() + "/" + this.name, VoidObject.class); } public APIMethodCaller<VoidObject> delete() { return new APIMethodCaller<VoidObject>("delete", this.prefix() + "/" + this.name + "/:id", VoidObject.class); } public APIMethodCaller<VoidObject> delete(String id) { return this.delete().addPathComponent("id", id); } } public Subresource<Observation> observations() { return new Subresource<Observation>("/experiments/" + this.getId(), "observations", Observation.class); } public PropertyResource<StoppingCriteria> stoppingCriteria() { return new PropertyResource<StoppingCriteria>("/experiments/" + this.getId(), "stopping_criteria", StoppingCriteria.class); } public Subresource<Suggestion> suggestions() { return new Subresource<Suggestion>("/experiments/" + this.getId(), "suggestions", Suggestion.class); } public Subresource<Token> tokens() { return new Subresource<Token>("/experiments/" + this.getId(), "tokens", Token.class); } public Subresource<BestAssignments> bestAssignments() { return new Subresource<BestAssignments>("/experiments/" + this.getId(), "best_assignments", BestAssignments.class); } public static class Builder { Experiment e; public Builder() { this.e = new Experiment(); } public Experiment build() { return this.e; } public Builder created(int created) { this.e.set("created", created); return this; } public Builder parameters(List<Parameter> parameters) { this.e.set("parameters", parameters); return this; } public Builder metrics(List<Metric> metrics) { this.e.set("metrics", metrics); return this; } public Builder metadata(Map<String, String> metadata) { this.e.set("metadata", metadata); return this; } public Builder metric(Metric metric) { this.e.set("metric", metric); return this; } public Builder progress(Progress progress) { this.e.set("progress", progress); return this; } public Builder client(String client) { this.e.set("client", client); return this; } public Builder id(String id) { this.e.set("id", id); return this; } public Builder name(String name) { this.e.set("name", name); return this; } public Builder state(String state) { this.e.set("state", state); return this; } public Builder type(String type) { this.e.set("type", type); return this; } public Builder observationBudget(int budget) { this.e.set("observation_budget", budget); return this; } public Builder numSolutions(int numSolutions) { this.e.set("num_solutions", numSolutions); return this; } public Builder development(boolean development) { this.e.set("development", development); return this; } public Builder folds(int folds) { this.e.set("folds", folds); return this; } public Builder conditionals(List<Conditional> conditionals) { this.e.set("conditionals", conditionals); return this; } public Builder linearConstraints(List<LinearConstraint> linearConstraints) { this.e.set("linear_constraints", linearConstraints); return this; } } }
src/main/java/com/sigopt/model/Experiment.java
package com.sigopt.model; import com.sigopt.net.APIMethodCaller; import com.sigopt.net.PaginatedAPIMethodCaller; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import java.util.Map; public class Experiment extends StructObject { public Experiment() { super(); } public Experiment(String id) { super(); this.set("id", id); } public String getId() { return (String) this.get("id"); } public String getType() { return (String) this.get("type"); } public String getName() { return (String) this.get("name"); } public List<Parameter> getParameters() { return Utils.mergeIntoList(new ArrayList<Parameter>(), this.get("parameters"), Parameter.class); } public List<Metric> getMetrics() { return Utils.mergeIntoList(new ArrayList<Metric>(), this.get("metrics"), Metric.class); } public Metric getMetric() { return Utils.mergeInto(new Metric(), this.get("metric")); } public Progress getProgress() { return Utils.mergeInto(new Progress(), this.get("progress")); } public Metadata getMetadata() { return Utils.mergeInto(new Metadata(), this.get("metadata")); } public String getClient() { return (String) this.get("client"); } public String getState() { return (String) this.get("state"); } public Integer getCreated() { return Utils.asInteger(this.get("created")); } public Integer getObservationBudget() { return Utils.asInteger(this.get("observation_budget")); } public Integer getNumSolutions() { return Utils.asInteger(this.get("num_solutions")); } public Boolean getDevelopment() { return (Boolean) this.get("development"); } public Integer getFolds() { return Utils.asInteger(this.get("folds")); } public List<LinearConstraint> getLinearConstraints() { return Utils.mergeIntoList(new ArrayList<LinearConstraint>(), this.get("linear_constraints"), LinearConstraint.class); } public List<Conditional> getConditionals() { return Utils.mergeIntoList(new ArrayList<Conditional>(), this.get("conditionals"), Conditional.class); } public static APIMethodCaller<Experiment> fetch() { return new APIMethodCaller<Experiment>("get", "/experiments/:id", Experiment.class); } public static APIMethodCaller<Experiment> fetch(String id) { return Experiment.fetch().addPathComponent("id", id); } public static PaginatedAPIMethodCaller<Experiment> list() { return new PaginatedAPIMethodCaller<Experiment>("get", "/experiments", Experiment.class); } public static APIMethodCaller<Experiment> create() { return new APIMethodCaller<Experiment>("post", "/experiments", Experiment.class); } public static APIMethodCaller<Experiment> create(Experiment e) { return Experiment.create().data(e); } public static APIMethodCaller<Experiment> update() { return new APIMethodCaller<Experiment>("put", "/experiments/:id", Experiment.class); } public static APIMethodCaller<Experiment> update(String id) { return Experiment.update().addPathComponent("id", id); } public static APIMethodCaller<Experiment> update(String id, Experiment e) { return Experiment.update(id).data(e); } public static APIMethodCaller<VoidObject> delete() { return new APIMethodCaller<VoidObject>("delete", "/experiments/:id", VoidObject.class); } public static APIMethodCaller<VoidObject> delete(String id) { return Experiment.delete().addPathComponent("id", id); } /** * PropertyResource is used for a resource linked strongly to another e.g. * StoppingCriteria isn't a full object with its own id but still must be * retrieved as its own resource separate from Experiment */ public static class PropertyResource<T extends APIObject> extends BoundObject { String name; Class<T> klass; public PropertyResource(String prefix, String name, Class<T> klass) { super(prefix); this.name = name; this.klass = klass; } public APIMethodCaller<T> fetch() { return new APIMethodCaller<T>("get", this.prefix() + "/" + this.name, klass); } } public static class Subresource<T extends APIObject> extends BoundObject { String name; Class<T> klass; public Subresource(String prefix, String name, Class<T> klass) { super(prefix); this.name = name; this.klass = klass; } public APIMethodCaller<T> fetch() { return new APIMethodCaller<T>("get", this.prefix() + "/" + this.name + "/:id", klass); } public APIMethodCaller<T> fetch(String id) { return this.fetch().addPathComponent("id", id); } public PaginatedAPIMethodCaller<T> list() { return new PaginatedAPIMethodCaller<T>("get", this.prefix() + "/" + this.name, klass); } public APIMethodCaller<T> create() { return new APIMethodCaller<T>("post", this.prefix() + "/" + this.name, klass); } public APIMethodCaller<T> create(T o) { return this.create().data(o); } public APIMethodCaller<T> update() { return new APIMethodCaller<T>("put", this.prefix() + "/" + this.name + "/:id", klass); } public APIMethodCaller<T> update(String id) { return this.update().addPathComponent("id", id); } public APIMethodCaller<T> update(String id, T o) { return this.update(id).data(o); } public APIMethodCaller<VoidObject> deleteList() { return new APIMethodCaller<VoidObject>("delete", this.prefix() + "/" + this.name, VoidObject.class); } public APIMethodCaller<VoidObject> delete() { return new APIMethodCaller<VoidObject>("delete", this.prefix() + "/" + this.name + "/:id", VoidObject.class); } public APIMethodCaller<VoidObject> delete(String id) { return this.delete().addPathComponent("id", id); } } public Subresource<Observation> observations() { return new Subresource<Observation>("/experiments/" + this.getId(), "observations", Observation.class); } public PropertyResource<StoppingCriteria> stoppingCriteria() { return new PropertyResource<StoppingCriteria>("/experiments/" + this.getId(), "stopping_criteria", StoppingCriteria.class); } public Subresource<Suggestion> suggestions() { return new Subresource<Suggestion>("/experiments/" + this.getId(), "suggestions", Suggestion.class); } public Subresource<Token> tokens() { return new Subresource<Token>("/experiments/" + this.getId(), "tokens", Token.class); } public Subresource<BestAssignments> bestAssignments() { return new Subresource<BestAssignments>("/experiments/" + this.getId(), "best_assignments", BestAssignments.class); } public static class Builder { Experiment e; public Builder() { this.e = new Experiment(); } public Experiment build() { return this.e; } public Builder created(int created) { this.e.set("created", created); return this; } public Builder parameters(List<Parameter> parameters) { this.e.set("parameters", parameters); return this; } public Builder metrics(List<Metric> metrics) { this.e.set("metrics", metrics); return this; } public Builder metadata(Map<String, String> metadata) { this.e.set("metadata", metadata); return this; } public Builder metric(Metric metric) { this.e.set("metric", metric); return this; } public Builder progress(Progress progress) { this.e.set("progress", progress); return this; } public Builder client(String client) { this.e.set("client", client); return this; } public Builder id(String id) { this.e.set("id", id); return this; } public Builder name(String name) { this.e.set("name", name); return this; } public Builder state(String state) { this.e.set("state", state); return this; } public Builder type(String type) { this.e.set("type", type); return this; } public Builder observationBudget(int budget) { this.e.set("observation_budget", budget); return this; } public Builder numSolutions(int numSolutions) { this.e.set("num_solutions", numSolutions); return this; } public Builder development(boolean development) { this.e.set("development", development); return this; } public Builder folds(int folds) { this.e.set("folds", folds); return this; } public Builder conditionals(List<Conditional> conditionals) { this.e.set("conditionals", conditionals); return this; } public Builder linearConstraints(List<LinearConstraint> linearConstraints) { this.e.set("linear_constraints", linearConstraints); return this; } } }
add experiment fields
src/main/java/com/sigopt/model/Experiment.java
add experiment fields
Java
epl-1.0
8f59230f8be208e876a66cccd87f1a2d81aeccd3
0
hansjoachim/junit,UnimibSoftEngCourse1516/lab2-es3-o.sertori,schauder/junit,UnimibSoftEngCourse1516/lab2-es3-m.vella6,onesfreedom/junit,UnimibSoftEngCourse1516/lab2-es3-s.renzo,dvberkel/junit,UnimibSoftEngCourse1516/lab2-es3-f.giannini3,mekwin87/junit4,yusuke/junit,UnimibSoftEngCourse1516/lab2-es3-f.cirelli1,jhfjhfj1/junit,UnimibSoftEngCourse1516/lab2-es3-a.mosini,avandeursen/junit,kobe73er/dUnit,UnimibSoftEngCourse1516/lab2-es3-e.nani1,AxelMonroyX/junit4,ashleyfrieze/junit,kcooney/junit,julien-sobczak/junit,Siddartha07/junit,UnimibSoftEngCourse1516/lab2-es3-f.cirelli1,UnimibSoftEngCourse1516/lab2-es3-o.sertori,edwardmlyte/junit,janocat/junit,MichaelJY91/junit,adko-pl/junit,songfj/junit,UnimibSoftEngCourse1516/lab2-es3-s.renzo,sposam/junit,chrisvest/junit,alohageck0/junit,remus32/junit,UnimibSoftEngCourse1516/lab2-es3-s.ravetta,hansjoachim/junit,freezhan/junit,UnimibSoftEngCourse1516/lab2-es3-f.giannini3,rwarren14/junit,alohageck0/junit,powazny/junit4,junit-team/junit4,easyMan-zzy/junit,eamonnmcmanus/junit,UnimibSoftEngCourse1516/lab2-es3-a.mosini,smayoorans/junit,Siddartha07/junit,schauder/junit,chrisvest/junit,alohageck0/junit,0359xiaodong/junit,alb-i986/junit,hhariri/junit,openhardnudd/junit,sposam/junit,stefanbirkner/junit,flomotlik/junit,eamonnmcmanus/junit,UnimibSoftEngCourse1516/lab2-es3-m.scarpone,MichaelJY91/junit,MingxuanChen/junit,hansjoachim/junit,y-kt/junit,UnimibSoftEngCourse1516/lab2-es3-m.scarpone,y-kt/junit,cherryleer/junit,smayoorans/junit,witcxc/junit,paulduffin/junit,freezhan/junit,freezhan/junit,elijah513/junit,jordancheah/junit,UnimibSoftEngCourse1516/lab2-es3-o.sertori,chrisvest/junit,avandeursen/junit,edwardmlyte/junit,janocat/junit,moinuddin14/junit,remus32/junit,ashleyfrieze/junit,UnimibSoftEngCourse1516/lab2-es3-a.tundo,stefanbirkner/junit,UnimibSoftEngCourse1516/lab2-es3-i.pigazzini,UnimibSoftEngCourse1516/lab2-es3-m.vella6,flomotlik/junit,panchenko/junit,panchenko/junit,jhfjhfj1/junit,UnimibSoftEngCourse1516/lab2-es3-s.ravetta,UnimibSoftEngCourse1516/lab2-es3-a.tundo,kobe73er/MyUnit,mnk/junit,0359xiaodong/junit,alb-i986/junit,eamonnmcmanus/junit,flomotlik/junit,UnimibSoftEngCourse1516/lab2-es3-f.spinardi,VikingDen/junit,baev/junit,mnk/junit,slezier/junit,baev/junit,GeeChao/junit,UnimibSoftEngCourse1516/lab2-es3-f.spinardi,yusuke/junit,UnimibSoftEngCourse1516/lab2-es3-l.salvestrini,rwarren14/junit,edwardmlyte/junit,marcphilipp/junit,witcxc/junit,1234-/junit,AxelMonroyX/junit4,UnimibSoftEngCourse1516/lab2-es3-m.vella6,1234-/junit,mekwin87/junit4,stefanbirkner/junit,hhariri/junit,quentin9696/junit,Siddartha07/junit,yusuke/junit,UnimibSoftEngCourse1516/lab2-es3-m.polonioli,MichaelJY91/junit,MingxuanChen/junit,UnimibSoftEngCourse1516/lab2-es3-f.spinardi,quentin9696/junit,dvberkel/junit,UnimibSoftEngCourse1516/lab2-es3-i.pigazzini,UnimibSoftEngCourse1516/lab2-es3-e.nani1,hhariri/junit,easyMan-zzy/junit,UnimibSoftEngCourse1516/lab2-es3-l.salvestrini,adko-pl/junit,jordancheah/junit,panchenko/junit,janocat/junit,alb-i986/junit,UnimibSoftEngCourse1516/lab2-es3-f.giannini3,1234-/junit,slezier/junit,powazny/junit4,cherryleer/junit,Clairebi/JUnit-Clone,openhardnudd/junit,junit-team/junit,Clairebi/JUnit-Clone,feisuo/junit,slezier/junit,UnimibSoftEngCourse1516/lab2-es3-l.salvestrini,UnimibSoftEngCourse1516/lab2-es3-m.polonioli,openhardnudd/junit,UnimibSoftEngCourse1516/lab2-es3-m.scarpone,ashleyfrieze/junit,moinuddin14/junit,laercioferracini/junit,jhfjhfj1/junit,rwarren14/junit,JoaquinSiabra/junit,kobe73er/MyUnit,moinuddin14/junit,Thothius/junit,UnimibSoftEngCourse1516/lab2-es3-e.nani1,feisuo/junit,avandeursen/junit,elijah513/junit,remus32/junit,julien-sobczak/junit,Clairebi/JUnit-Clone,easyMan-zzy/junit,UnimibSoftEngCourse1516/lab2-es3-f.cirelli1,jordancheah/junit,kcooney/junit,witcxc/junit,mekwin87/junit4,laercioferracini/junit,junit-team/junit,marcphilipp/junit,MingxuanChen/junit,junit-team/junit4,0359xiaodong/junit,laercioferracini/junit,y-kt/junit,JoaquinSiabra/junit,cherryleer/junit,onesfreedom/junit,GeeChao/junit,VikingDen/junit,kcooney/junit,junit-team/junit,smayoorans/junit,Thothius/junit,powazny/junit4,UnimibSoftEngCourse1516/lab2-es3-s.renzo,mekwin87/junit4,schauder/junit,julien-sobczak/junit,dvberkel/junit,UnimibSoftEngCourse1516/lab2-es3-s.ravetta,onesfreedom/junit,paulduffin/junit,JoaquinSiabra/junit,paulduffin/junit,UnimibSoftEngCourse1516/lab2-es3-m.polonioli,elijah513/junit,Thothius/junit,kobe73er/dUnit,UnimibSoftEngCourse1516/lab2-es3-a.mosini,sposam/junit,AxelMonroyX/junit4,songfj/junit,feisuo/junit,adko-pl/junit,baev/junit,marcphilipp/junit,junit-team/junit4,mnk/junit,songfj/junit,kobe73er/dUnit,quentin9696/junit,UnimibSoftEngCourse1516/lab2-es3-i.pigazzini,GeeChao/junit,VikingDen/junit,kobe73er/MyUnit,UnimibSoftEngCourse1516/lab2-es3-a.tundo
package org.junit.internal; import java.lang.reflect.Array; import java.util.Arrays; import org.junit.Assert; /** * Defines criteria for finding two items "equal enough". Concrete subclasses * may demand exact equality, or, for example, equality within a given delta. */ public abstract class ComparisonCriteria { /** * Asserts that two arrays are equal, according to the criteria defined by * the concrete subclass. If they are not, an {@link AssertionError} is * thrown with the given message. If <code>expecteds</code> and * <code>actuals</code> are <code>null</code>, they are considered equal. * * @param message the identifying message for the {@link AssertionError} ( * <code>null</code> okay) * @param expecteds Object array or array of arrays (multi-dimensional array) with * expected values. * @param actuals Object array or array of arrays (multi-dimensional array) with * actual values */ public void arrayEquals(String message, Object expecteds, Object actuals) throws ArrayComparisonFailure { if (expecteds == actuals || Arrays.deepEquals(new Object[] {expecteds}, new Object[] {actuals})) { // The reflection-based loop below is potentially very slow, especially for primitive // arrays. The deepEquals check allows us to circumvent it in the usual case where // the arrays are exactly equal. return; } String header = message == null ? "" : message + ": "; int expectedsLength = assertArraysAreSameLength(expecteds, actuals, header); for (int i = 0; i < expectedsLength; i++) { Object expected = Array.get(expecteds, i); Object actual = Array.get(actuals, i); if (isArray(expected) && isArray(actual)) { try { arrayEquals(message, expected, actual); } catch (ArrayComparisonFailure e) { e.addDimension(i); throw e; } } else { try { assertElementsEqual(expected, actual); } catch (AssertionError e) { throw new ArrayComparisonFailure(header, e, i); } } } } private boolean isArray(Object expected) { return expected != null && expected.getClass().isArray(); } private int assertArraysAreSameLength(Object expecteds, Object actuals, String header) { if (expecteds == null) { Assert.fail(header + "expected array was null"); } if (actuals == null) { Assert.fail(header + "actual array was null"); } int actualsLength = Array.getLength(actuals); int expectedsLength = Array.getLength(expecteds); if (actualsLength != expectedsLength) { Assert.fail(header + "array lengths differed, expected.length=" + expectedsLength + " actual.length=" + actualsLength); } return expectedsLength; } protected abstract void assertElementsEqual(Object expected, Object actual); }
src/main/java/org/junit/internal/ComparisonCriteria.java
package org.junit.internal; import java.lang.reflect.Array; import org.junit.Assert; /** * Defines criteria for finding two items "equal enough". Concrete subclasses * may demand exact equality, or, for example, equality within a given delta. */ public abstract class ComparisonCriteria { /** * Asserts that two arrays are equal, according to the criteria defined by * the concrete subclass. If they are not, an {@link AssertionError} is * thrown with the given message. If <code>expecteds</code> and * <code>actuals</code> are <code>null</code>, they are considered equal. * * @param message the identifying message for the {@link AssertionError} ( * <code>null</code> okay) * @param expecteds Object array or array of arrays (multi-dimensional array) with * expected values. * @param actuals Object array or array of arrays (multi-dimensional array) with * actual values */ public void arrayEquals(String message, Object expecteds, Object actuals) throws ArrayComparisonFailure { if (expecteds == actuals) { return; } String header = message == null ? "" : message + ": "; int expectedsLength = assertArraysAreSameLength(expecteds, actuals, header); for (int i = 0; i < expectedsLength; i++) { Object expected = Array.get(expecteds, i); Object actual = Array.get(actuals, i); if (isArray(expected) && isArray(actual)) { try { arrayEquals(message, expected, actual); } catch (ArrayComparisonFailure e) { e.addDimension(i); throw e; } } else { try { assertElementsEqual(expected, actual); } catch (AssertionError e) { throw new ArrayComparisonFailure(header, e, i); } } } } private boolean isArray(Object expected) { return expected != null && expected.getClass().isArray(); } private int assertArraysAreSameLength(Object expecteds, Object actuals, String header) { if (expecteds == null) { Assert.fail(header + "expected array was null"); } if (actuals == null) { Assert.fail(header + "actual array was null"); } int actualsLength = Array.getLength(actuals); int expectedsLength = Array.getLength(expecteds); if (actualsLength != expectedsLength) { Assert.fail(header + "array lengths differed, expected.length=" + expectedsLength + " actual.length=" + actualsLength); } return expectedsLength; } protected abstract void assertElementsEqual(Object expected, Object actual); }
Avoid a potentially expensive reflection-based loop in assertArrayEquals, in the usual case where the arrays are in fact exactly equal.
src/main/java/org/junit/internal/ComparisonCriteria.java
Avoid a potentially expensive reflection-based loop in assertArrayEquals, in the usual case where the arrays are in fact exactly equal.
Java
epl-1.0
2efae6d252086135706ea4c77c4cd717ef652d33
0
Cooperate-Project/CooperateModelingEnvironment,Cooperate-Project/Cooperate,Cooperate-Project/Cooperate,Cooperate-Project/CooperateModelingEnvironment
package de.cooperateproject.ui.wizards.modelnew.impl; import org.eclipse.core.databinding.AggregateValidationStatus; import org.eclipse.core.databinding.DataBindingContext; import org.eclipse.core.databinding.UpdateValueStrategy; import org.eclipse.core.databinding.beans.BeanProperties; import org.eclipse.core.databinding.observable.IChangeListener; import org.eclipse.core.databinding.observable.value.IObservableValue; import org.eclipse.core.databinding.observable.value.WritableValue; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.CoreException; import org.eclipse.jface.databinding.swt.WidgetProperties; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.window.Window; import org.eclipse.swt.SWT; import org.eclipse.swt.accessibility.ACC; import org.eclipse.swt.accessibility.Accessible; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.VerifyEvent; import org.eclipse.swt.events.VerifyListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.dialogs.ElementTreeSelectionDialog; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.cooperateproject.ui.wizards.modelnew.impl.AtomicProjectNameProcessor.ProjectName; import de.cooperateproject.ui.wizards.modelnew.impl.ModelContentProvider.ModelNode; import de.cooperateproject.ui.wizards.modelnew.impl.ModelContentProvider.ProjectNode; /** * Reusable composite that allows defining a model and diagram name based on a selection of available projects. */ public class ModelAndDiagramSelectionComposite extends Composite { private static final Logger LOGGER = LoggerFactory.getLogger(ModelAndDiagramSelectionComposite.class); private final Text textProject; private final Text textModelName; private final Text textDiagramName; private final SelectedNamesDTO dto; private final IChangeListener validatorStatusListener; private AggregateValidationStatus aggregatedStatus; /** * Create the composite. * * @param parent * The parent composite. * @param style * A style to be used in the parent. * @param dto * A transfer object that gives access to the names selected in the composite. * @param validatorStatusListener * A listener that will be notified if the state of the overall validation has changed. */ public ModelAndDiagramSelectionComposite(Composite parent, int style, SelectedNamesDTO dto, IChangeListener validatorStatusListener) { super(parent, style); this.dto = dto; this.validatorStatusListener = validatorStatusListener; setLayout(new GridLayout(3, false)); Label lblProject = new Label(this, SWT.NONE); lblProject.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); lblProject.setText("Project:"); textProject = new Text(this, SWT.BORDER); textProject.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); Accessible accLblProject = lblProject.getAccessible(); Accessible accTextProject = textProject.getAccessible(); accLblProject.addRelation(ACC.RELATION_LABEL_FOR, accTextProject); accTextProject.addRelation(ACC.RELATION_LABELLED_BY, accLblProject); SelectionAdapter selectionAdapter = new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { ElementTreeSelectionDialog dialog = new ElementTreeSelectionDialog(getShell(), new ModelLabelProvider(), new ModelContentProvider()); dialog.setInput(dto); dialog.setTitle("Project Selection"); dialog.setMessage("Choose a project:"); dialog.setHelpAvailable(false); if (dialog.open() == Window.OK) { Object element = dialog.getFirstResult(); if (element instanceof ProjectNode) { textProject.setText(((ProjectNode) element).getName()); } else if (element instanceof ModelNode) { textProject.setText(((ModelNode) element).getParent().get().getName()); textModelName.setText(((ModelNode) element).getName()); } } } }; Button btnBrowseProjects = new Button(this, SWT.PUSH); btnBrowseProjects.setText("Browse..."); btnBrowseProjects.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); btnBrowseProjects.addSelectionListener(selectionAdapter); Label lblModelName = new Label(this, SWT.NONE); lblModelName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); lblModelName.setText("Model Name:"); textModelName = new Text(this, SWT.BORDER); textModelName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); Accessible accLblModelName = lblModelName.getAccessible(); Accessible accTextModelName = textModelName.getAccessible(); accLblModelName.addRelation(ACC.RELATION_LABEL_FOR, accTextModelName); accTextModelName.addRelation(ACC.RELATION_LABELLED_BY, accLblModelName); Button btnBrowseModels = new Button(this, SWT.PUSH); btnBrowseModels.setText("Browse..."); btnBrowseModels.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); btnBrowseModels.addSelectionListener(selectionAdapter); Label lblDiagramName = new Label(this, SWT.NONE); lblDiagramName.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); lblDiagramName.setText("Diagram Name:"); textDiagramName = new Text(this, SWT.BORDER); textDiagramName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1)); Accessible accLblDiagramName = lblDiagramName.getAccessible(); Accessible accTextDiagramName = textDiagramName.getAccessible(); accLblDiagramName.addRelation(ACC.RELATION_LABEL_FOR, accTextDiagramName); accTextDiagramName.addRelation(ACC.RELATION_LABELLED_BY, accLblDiagramName); setProject(textProject, textModelName); initCustomDataBindings(); initCustomListeners(); } @Override protected void checkSubclass() { // Disable the check that prevents subclassing of SWT components } private void initCustomDataBindings() { DataBindingContext bindingContext = new DataBindingContext(); IObservableValue<?> observedDiagramName = WidgetProperties.text(SWT.Modify).observe(textDiagramName); IObservableValue<?> observedModelName = WidgetProperties.text(SWT.Modify).observe(textModelName); IObservableValue<?> observedProjectName = WidgetProperties.text(SWT.Modify).observe(textProject); IObservableValue<String> atomicValidatedDiagramName = new WritableValue<>(null, String.class); IObservableValue<String> atomicValidatedModelName = new WritableValue<>(null, String.class); IObservableValue<ProjectName> atomicValidatedProjectName = new WritableValue<>(null, ProjectName.class); UpdateValueStrategy strategyAtomicModelNameTargetToModel = new UpdateValueStrategy(); strategyAtomicModelNameTargetToModel.setAfterGetValidator(new AtomicModelNameProcessor()); bindingContext.bindValue(observedModelName, atomicValidatedModelName, strategyAtomicModelNameTargetToModel, new UpdateValueStrategy(UpdateValueStrategy.POLICY_NEVER)); UpdateValueStrategy strategyAtomicDiagramNameTargetToModel = new UpdateValueStrategy(); strategyAtomicDiagramNameTargetToModel.setAfterGetValidator(new AtomicDiagramNameProcessor()); bindingContext.bindValue(observedDiagramName, atomicValidatedDiagramName, strategyAtomicDiagramNameTargetToModel, new UpdateValueStrategy(UpdateValueStrategy.POLICY_NEVER)); UpdateValueStrategy strategyAtomicProjectNameTargetToModel = new UpdateValueStrategy(); strategyAtomicProjectNameTargetToModel.setAfterGetValidator(new AtomicProjectNameProcessor()); strategyAtomicProjectNameTargetToModel.setConverter(new AtomicProjectNameProcessor()); bindingContext.bindValue(observedProjectName, atomicValidatedProjectName, strategyAtomicProjectNameTargetToModel, new UpdateValueStrategy(UpdateValueStrategy.POLICY_NEVER)); CompoundNameValidator diagramNameValidator = new CompoundNameValidator(atomicValidatedDiagramName, atomicValidatedModelName, atomicValidatedProjectName); bindingContext.addValidationStatusProvider(diagramNameValidator); IObservableValue<?> validatedDiagramName = diagramNameValidator .observeValidatedValue(atomicValidatedDiagramName); IObservableValue<?> validatedModelName = diagramNameValidator.observeValidatedValue(atomicValidatedModelName); IObservableValue<?> validatedProjectName = diagramNameValidator .observeValidatedValue(atomicValidatedProjectName); @SuppressWarnings("unchecked") IObservableValue<String> modelSelectedModelName = BeanProperties .value(SelectedNamesDTO.class, "selectedModelName").observe(dto); @SuppressWarnings("unchecked") IObservableValue<String> modelSelectedDiagramName = BeanProperties .value(SelectedNamesDTO.class, "selectedDiagramName").observe(dto); @SuppressWarnings("unchecked") IObservableValue<ProjectName> modelSelectedProjectName = BeanProperties .value(SelectedNamesDTO.class, "selectedProjectName").observe(dto); // Bind to the validated value, not the middle/target bindingContext.bindValue(validatedDiagramName, modelSelectedDiagramName); bindingContext.bindValue(validatedModelName, modelSelectedModelName); bindingContext.bindValue(validatedProjectName, modelSelectedProjectName); aggregatedStatus = new AggregateValidationStatus(bindingContext, AggregateValidationStatus.MAX_SEVERITY); aggregatedStatus.addChangeListener(validatorStatusListener); } @Override public void dispose() { if (aggregatedStatus != null) { aggregatedStatus.removeChangeListener(validatorStatusListener); } super.dispose(); } private abstract static class TextFieldVerifier implements VerifyListener { @Override public void verifyText(VerifyEvent e) { if (e.text == null) { e.doit = true; } e.doit = allowModification(e.text); } protected abstract boolean allowModification(String text); } private static void setProject(Text projectText, Text modelText) { IStructuredSelection selection = (IStructuredSelection) PlatformUI.getWorkbench().getActiveWorkbenchWindow() .getSelectionService().getSelection(); String cooperateNature = "de.cooperateproject.ui.CooperateProjectNature"; try { if (selection.size() == 1) { Object element = selection.getFirstElement(); if (element instanceof IProject && ((IProject) element).hasNature(cooperateNature)) { projectText.setText(((IProject) selection.getFirstElement()).getName()); } else if (element instanceof IFolder && ((IFolder) element).getProject().hasNature(cooperateNature)) { projectText.setText(((IFolder) element).getProject().getName()); } else if (element instanceof IFile && ((IFile) element).getFileExtension().contains("cooperate")) { modelText.setText( ((IFile) element).getName().substring(0, ((IFile) element).getName().lastIndexOf("-") - 1)); projectText.setText(((IFile) element).getProject().getName()); } } } catch (CoreException e) { LOGGER.warn("Error ocurred while checking preconditions.", e); } } private void initCustomListeners() { textDiagramName.addVerifyListener(new TextFieldVerifier() { protected boolean allowModification(String text) { return text.matches("[a-zA-Z0-9_ .]*"); } }); textProject.addVerifyListener(new TextFieldVerifier() { @Override protected boolean allowModification(String text) { return text.matches("[a-zA-Z0-9_ ./]*"); } }); } /** * Changes the repository name and changes it back to what it was before to trigger validation of the * project properties. */ public void triggerValidation() { String empty = ""; String oldProject = textProject.getText(); textProject.setText(empty); textProject.setText(oldProject); String oldModel = textModelName.getText(); textModelName.setText(empty); textModelName.setText(oldModel); String oldDiagramName = textDiagramName.getText(); textDiagramName.setText(empty); textDiagramName.setText(oldDiagramName); } }
bundles/de.cooperateproject.ui/src/de/cooperateproject/ui/wizards/modelnew/impl/ModelAndDiagramSelectionComposite.java
package de.cooperateproject.ui.wizards.modelnew.impl; import org.eclipse.core.databinding.AggregateValidationStatus; import org.eclipse.core.databinding.DataBindingContext; import org.eclipse.core.databinding.UpdateValueStrategy; import org.eclipse.core.databinding.beans.BeanProperties; import org.eclipse.core.databinding.observable.IChangeListener; import org.eclipse.core.databinding.observable.value.IObservableValue; import org.eclipse.core.databinding.observable.value.WritableValue; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.CoreException; import org.eclipse.jface.databinding.swt.WidgetProperties; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.window.Window; import org.eclipse.swt.SWT; import org.eclipse.swt.accessibility.ACC; import org.eclipse.swt.accessibility.Accessible; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.VerifyEvent; import org.eclipse.swt.events.VerifyListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.dialogs.ElementTreeSelectionDialog; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.cooperateproject.ui.wizards.modelnew.impl.AtomicProjectNameProcessor.ProjectName; import de.cooperateproject.ui.wizards.modelnew.impl.ModelContentProvider.ModelNode; import de.cooperateproject.ui.wizards.modelnew.impl.ModelContentProvider.ProjectNode; /** * Reusable composite that allows defining a model and diagram name based on a selection of available projects. */ public class ModelAndDiagramSelectionComposite extends Composite { private static final Logger LOGGER = LoggerFactory.getLogger(ModelAndDiagramSelectionComposite.class); private final Text textProject; private final Text textModelName; private final Text textDiagramName; private final SelectedNamesDTO dto; private final IChangeListener validatorStatusListener; private AggregateValidationStatus aggregatedStatus; /** * Create the composite. * * @param parent * The parent composite. * @param style * A style to be used in the parent. * @param dto * A transfer object that gives access to the names selected in the composite. * @param validatorStatusListener * A listener that will be notified if the state of the overall validation has changed. */ public ModelAndDiagramSelectionComposite(Composite parent, int style, SelectedNamesDTO dto, IChangeListener validatorStatusListener) { super(parent, style); this.dto = dto; this.validatorStatusListener = validatorStatusListener; setLayout(new GridLayout(3, false)); Label lblProject = new Label(this, SWT.NONE); lblProject.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); lblProject.setText("Project:"); textProject = new Text(this, SWT.BORDER); textProject.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); Accessible accLblProject = lblProject.getAccessible(); Accessible accTextProject = textProject.getAccessible(); accLblProject.addRelation(ACC.RELATION_LABEL_FOR, accTextProject); accTextProject.addRelation(ACC.RELATION_LABELLED_BY, accLblProject); SelectionAdapter selectionAdapter = new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { ElementTreeSelectionDialog dialog = new ElementTreeSelectionDialog(getShell(), new ModelLabelProvider(), new ModelContentProvider()); dialog.setInput(dto); dialog.setTitle("Project Selection"); dialog.setMessage("Choose a project:"); dialog.setHelpAvailable(false); if (dialog.open() == Window.OK) { Object element = dialog.getFirstResult(); if (element instanceof ProjectNode) { textProject.setText(((ProjectNode) element).getName()); } else if (element instanceof ModelNode) { textProject.setText(((ModelNode) element).getParent().get().getName()); textModelName.setText(((ModelNode) element).getName()); } } } }; Button btnBrowseProjects = new Button(this, SWT.PUSH); btnBrowseProjects.setText("Browse..."); btnBrowseProjects.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); btnBrowseProjects.addSelectionListener(selectionAdapter); Label lblModelName = new Label(this, SWT.NONE); lblModelName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); lblModelName.setText("Model Name:"); textModelName = new Text(this, SWT.BORDER); textModelName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); Accessible accLblModelName = lblModelName.getAccessible(); Accessible accTextModelName = textModelName.getAccessible(); accLblModelName.addRelation(ACC.RELATION_LABEL_FOR, accTextModelName); accTextModelName.addRelation(ACC.RELATION_LABELLED_BY, accLblModelName); Button btnBrowseModels = new Button(this, SWT.PUSH); btnBrowseModels.setText("Browse..."); btnBrowseModels.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); btnBrowseModels.addSelectionListener(selectionAdapter); Label lblDiagramName = new Label(this, SWT.NONE); lblDiagramName.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); lblDiagramName.setText("Diagram Name:"); textDiagramName = new Text(this, SWT.BORDER); textDiagramName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1)); Accessible accLblDiagramName = lblDiagramName.getAccessible(); Accessible accTextDiagramName = textDiagramName.getAccessible(); accLblDiagramName.addRelation(ACC.RELATION_LABEL_FOR, accTextDiagramName); accTextDiagramName.addRelation(ACC.RELATION_LABELLED_BY, accLblDiagramName); setProject(textProject, textModelName); initCustomDataBindings(); initCustomListeners(); } @Override protected void checkSubclass() { // Disable the check that prevents subclassing of SWT components } private void initCustomDataBindings() { DataBindingContext bindingContext = new DataBindingContext(); IObservableValue<?> observedDiagramName = WidgetProperties.text(SWT.Modify).observe(textDiagramName); IObservableValue<?> observedModelName = WidgetProperties.text(SWT.Modify).observe(textModelName); IObservableValue<?> observedProjectName = WidgetProperties.text(SWT.Modify).observe(textProject); IObservableValue<String> atomicValidatedDiagramName = new WritableValue<>(null, String.class); IObservableValue<String> atomicValidatedModelName = new WritableValue<>(null, String.class); IObservableValue<ProjectName> atomicValidatedProjectName = new WritableValue<>(null, ProjectName.class); UpdateValueStrategy strategyAtomicModelNameTargetToModel = new UpdateValueStrategy(); strategyAtomicModelNameTargetToModel.setAfterGetValidator(new AtomicModelNameProcessor()); bindingContext.bindValue(observedModelName, atomicValidatedModelName, strategyAtomicModelNameTargetToModel, new UpdateValueStrategy(UpdateValueStrategy.POLICY_NEVER)); UpdateValueStrategy strategyAtomicDiagramNameTargetToModel = new UpdateValueStrategy(); strategyAtomicDiagramNameTargetToModel.setAfterGetValidator(new AtomicDiagramNameProcessor()); bindingContext.bindValue(observedDiagramName, atomicValidatedDiagramName, strategyAtomicDiagramNameTargetToModel, new UpdateValueStrategy(UpdateValueStrategy.POLICY_NEVER)); UpdateValueStrategy strategyAtomicProjectNameTargetToModel = new UpdateValueStrategy(); strategyAtomicProjectNameTargetToModel.setAfterGetValidator(new AtomicProjectNameProcessor()); strategyAtomicProjectNameTargetToModel.setConverter(new AtomicProjectNameProcessor()); bindingContext.bindValue(observedProjectName, atomicValidatedProjectName, strategyAtomicProjectNameTargetToModel, new UpdateValueStrategy(UpdateValueStrategy.POLICY_NEVER)); CompoundNameValidator diagramNameValidator = new CompoundNameValidator(atomicValidatedDiagramName, atomicValidatedModelName, atomicValidatedProjectName); bindingContext.addValidationStatusProvider(diagramNameValidator); IObservableValue<?> validatedDiagramName = diagramNameValidator .observeValidatedValue(atomicValidatedDiagramName); IObservableValue<?> validatedModelName = diagramNameValidator.observeValidatedValue(atomicValidatedModelName); IObservableValue<?> validatedProjectName = diagramNameValidator .observeValidatedValue(atomicValidatedProjectName); @SuppressWarnings("unchecked") IObservableValue<String> modelSelectedModelName = BeanProperties .value(SelectedNamesDTO.class, "selectedModelName").observe(dto); @SuppressWarnings("unchecked") IObservableValue<String> modelSelectedDiagramName = BeanProperties .value(SelectedNamesDTO.class, "selectedDiagramName").observe(dto); @SuppressWarnings("unchecked") IObservableValue<ProjectName> modelSelectedProjectName = BeanProperties .value(SelectedNamesDTO.class, "selectedProjectName").observe(dto); // Bind to the validated value, not the middle/target bindingContext.bindValue(validatedDiagramName, modelSelectedDiagramName); bindingContext.bindValue(validatedModelName, modelSelectedModelName); bindingContext.bindValue(validatedProjectName, modelSelectedProjectName); aggregatedStatus = new AggregateValidationStatus(bindingContext, AggregateValidationStatus.MAX_SEVERITY); aggregatedStatus.addChangeListener(validatorStatusListener); } @Override public void dispose() { if (aggregatedStatus != null) { aggregatedStatus.removeChangeListener(validatorStatusListener); } super.dispose(); } private abstract static class TextFieldVerifier implements VerifyListener { @Override public void verifyText(VerifyEvent e) { if (e.text == null) { e.doit = true; } e.doit = allowModification(e.text); } protected abstract boolean allowModification(String text); } private static void setProject(Text projectText, Text modelText) { IStructuredSelection selection = (IStructuredSelection) PlatformUI.getWorkbench().getActiveWorkbenchWindow() .getSelectionService().getSelection(); String cooperateNature = "de.cooperateproject.ui.CooperateProjectNature"; try { if (selection.size() == 1) { Object element = selection.getFirstElement(); if (element instanceof IProject && ((IProject) element).hasNature(cooperateNature)) { projectText.setText(((IProject) selection.getFirstElement()).getName()); } else if (element instanceof IFolder && ((IFolder) element).getProject().hasNature(cooperateNature)) { projectText.setText(((IFolder) element).getProject().getName()); } else if (element instanceof IFile && ((IFile) element).getFileExtension().contains("cooperate")) { modelText.setText( ((IFile) element).getName().substring(0, ((IFile) element).getName().lastIndexOf("-") - 1)); projectText.setText(((IFile) element).getProject().getName()); } } } catch (CoreException e) { LOGGER.warn("Error ocurred while checking preconditions.", e); } } private void initCustomListeners() { textDiagramName.addVerifyListener(new TextFieldVerifier() { protected boolean allowModification(String text) { return text.matches("[a-zA-Z0-9_ .]*"); } }); textProject.addVerifyListener(new TextFieldVerifier() { @Override protected boolean allowModification(String text) { return text.matches("[a-zA-Z0-9_ ./]*"); } }); } /** * Changes the repository name and changes it back to what it was before to trigger validation of the * project properties. */ public void triggerValidation() { String oldText = textProject.getText(); textProject.setText(""); textProject.setText(oldText); } }
#257 added missing validation of automatically filled in fields
bundles/de.cooperateproject.ui/src/de/cooperateproject/ui/wizards/modelnew/impl/ModelAndDiagramSelectionComposite.java
#257 added missing validation of automatically filled in fields
Java
agpl-3.0
c6224364a16200c3718877c3c5add1004485e498
0
antonini/spatial,kangkot/spatial,RobertBierbauer/spatial,antonini/spatial,kangkot/spatial,cgourlay/spatial,RobertBierbauer/spatial,antonini/spatial,cgourlay/spatial,RobertBierbauer/spatial,antonini/spatial,antonini/spatial,cgourlay/spatial,RobertBierbauer/spatial,cgourlay/spatial,RobertBierbauer/spatial,kangkot/spatial,kangkot/spatial,kangkot/spatial,cgourlay/spatial
/** * Copyright (c) 2002-2011 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.gis.spatial.pipes.processing; import org.neo4j.gis.spatial.pipes.AbstractGeoPipe; import org.neo4j.gis.spatial.pipes.GeoPipeFlow; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.Envelope; /** * This search assume Layer contains Points with Latitude / Longitude * coordinates in degrees. * Algorithm reference: http://www.movable-type.co.uk/scripts/latlong-db.html */ public class OrthodromicDistance extends AbstractGeoPipe { private Coordinate reference; public static final double earthRadiusInKm = 6371; public OrthodromicDistance(Coordinate reference) { this.reference = reference; } public OrthodromicDistance(Coordinate reference, String resultPropertyName) { super(resultPropertyName); this.reference = reference; } @Override protected GeoPipeFlow process(GeoPipeFlow flow) { // TODO check Geometry is a point? use Centroid? Coordinate point = flow.getGeometry().getCoordinate(); // d = acos(sin(lat1) * sin(lat2) + cos(lat1) * cos(lat2) * cos(lon2 - lon1)) * R double distanceInKm = calculateDistance(reference, point); setProperty(flow, distanceInKm); return flow; } public static Envelope suggestSearchWindow(Coordinate reference, double maxDistanceInKm) { double lat = reference.y; double lon = reference.x; // first-cut bounding box (in degrees) double maxLat = lat + Math.toDegrees(maxDistanceInKm / earthRadiusInKm); double minLat = lat - Math.toDegrees(maxDistanceInKm / earthRadiusInKm); // compensate for degrees longitude getting smaller with increasing latitude double maxLon = lon + Math.toDegrees(maxDistanceInKm / earthRadiusInKm / Math.cos(Math.toRadians(lat))); double minLon = lon - Math.toDegrees(maxDistanceInKm / earthRadiusInKm / Math.cos(Math.toRadians(lat))); return new Envelope(minLon, maxLon, minLat, maxLat); } public static double calculateDistance(Coordinate reference, Coordinate point) { // TODO use org.geotools.referencing.GeodeticCalculator? double distanceInKm = Math.acos(Math.sin(Math.toRadians(reference.y)) * Math.sin(Math.toRadians(point.y)) + Math.cos(Math.toRadians(reference.y)) * Math.cos(Math.toRadians(point.y)) * Math.cos(Math.toRadians(point.x) - Math.toRadians(reference.x))) * earthRadiusInKm; return distanceInKm; } }
src/main/java/org/neo4j/gis/spatial/pipes/processing/OrthodromicDistance.java
/** * Copyright (c) 2002-2011 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.gis.spatial.pipes.processing; import org.neo4j.gis.spatial.pipes.AbstractGeoPipe; import org.neo4j.gis.spatial.pipes.GeoPipeFlow; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.Envelope; /** * This search assume Layer contains Points with Latitude / Longitude * coordinates in degrees. * Algorithm reference: http://www.movable-type.co.uk/scripts/latlong-db.html */ public class OrthodromicDistance extends AbstractGeoPipe { private Coordinate reference; private static final double earthRadiusInKm = 6371; public OrthodromicDistance(Coordinate reference) { this.reference = reference; } public OrthodromicDistance(Coordinate reference, String resultPropertyName) { super(resultPropertyName); this.reference = reference; } @Override protected GeoPipeFlow process(GeoPipeFlow flow) { // TODO check Geometry is a point? use Centroid? Coordinate point = flow.getGeometry().getCoordinate(); // d = acos(sin(lat1) * sin(lat2) + cos(lat1) * cos(lat2) * cos(lon2 - lon1)) * R double distanceInKm = calculateDistance(reference, point); setProperty(flow, distanceInKm); return flow; } public static Envelope suggestSearchWindow(Coordinate reference, double maxDistanceInKm) { double lat = reference.y; double lon = reference.x; // first-cut bounding box (in degrees) double maxLat = lat + Math.toDegrees(maxDistanceInKm / earthRadiusInKm); double minLat = lat - Math.toDegrees(maxDistanceInKm / earthRadiusInKm); // compensate for degrees longitude getting smaller with increasing latitude double maxLon = lon + Math.toDegrees(maxDistanceInKm / earthRadiusInKm / Math.cos(Math.toRadians(lat))); double minLon = lon - Math.toDegrees(maxDistanceInKm / earthRadiusInKm / Math.cos(Math.toRadians(lat))); return new Envelope(minLon, maxLon, minLat, maxLat); } public static double calculateDistance(Coordinate reference, Coordinate point) { // TODO use org.geotools.referencing.GeodeticCalculator? double distanceInKm = Math.acos(Math.sin(Math.toRadians(reference.y)) * Math.sin(Math.toRadians(point.y)) + Math.cos(Math.toRadians(reference.y)) * Math.cos(Math.toRadians(point.y)) * Math.cos(Math.toRadians(point.x) - Math.toRadians(reference.x))) * earthRadiusInKm; return distanceInKm; } }
changed visibility of earthRadiusInKm
src/main/java/org/neo4j/gis/spatial/pipes/processing/OrthodromicDistance.java
changed visibility of earthRadiusInKm