diff
stringlengths 262
553k
| is_single_chunk
bool 2
classes | is_single_function
bool 1
class | buggy_function
stringlengths 20
391k
| fixed_function
stringlengths 0
392k
|
---|---|---|---|---|
diff --git a/webcam-capture-drivers/webcam-capture-driver-gstreamer/src/main/java/com/github/sarxos/webcam/ds/gstreamer/GStreamerDriver.java b/webcam-capture-drivers/webcam-capture-driver-gstreamer/src/main/java/com/github/sarxos/webcam/ds/gstreamer/GStreamerDriver.java
index 08ccf2b..5aef7af 100644
--- a/webcam-capture-drivers/webcam-capture-driver-gstreamer/src/main/java/com/github/sarxos/webcam/ds/gstreamer/GStreamerDriver.java
+++ b/webcam-capture-drivers/webcam-capture-driver-gstreamer/src/main/java/com/github/sarxos/webcam/ds/gstreamer/GStreamerDriver.java
@@ -1,141 +1,141 @@
package com.github.sarxos.webcam.ds.gstreamer;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import org.gstreamer.Element;
import org.gstreamer.ElementFactory;
import org.gstreamer.Gst;
import org.gstreamer.interfaces.PropertyProbe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.sarxos.webcam.WebcamDevice;
import com.github.sarxos.webcam.WebcamDriver;
import com.github.sarxos.webcam.WebcamException;
import com.github.sarxos.webcam.ds.gstreamer.impl.VideoDeviceFilenameFilter;
import com.sun.jna.NativeLibrary;
import com.sun.jna.Platform;
/**
* GStreamer capture driver.
*
* @author Bartosz Firyn (sarxos)
*/
public class GStreamerDriver implements WebcamDriver {
private static final Logger LOG = LoggerFactory.getLogger(GStreamerDriver.class);
private static final class GStreamerShutdownHook extends Thread {
public GStreamerShutdownHook() {
super("gstreamer-shutdown-hook");
}
@Override
public void run() {
LOG.debug("GStreamer deinitialization");
Gst.deinit();
}
}
private static final AtomicBoolean INITIALIZED = new AtomicBoolean(false);
public GStreamerDriver() {
if (INITIALIZED.compareAndSet(false, true)) {
init();
}
}
private static final void init() {
if (!Platform.isWindows() && !Platform.isLinux()) {
throw new WebcamException(String.format("%s has been designed to work only on Windows and Linux platforms", GStreamerDriver.class.getSimpleName()));
}
LOG.debug("GStreamer initialization");
String gpath = null;
if (Platform.isWindows()) {
String path = System.getenv("PATH");
for (String p : path.split(";")) {
LOG.trace("Search %PATH% for gstreamer bin {}", p);
if (p.indexOf("GStreamer\\v0.10.") != -1) {
gpath = p;
break;
}
}
if (gpath != null) {
LOG.debug("Add bin directory to JNA search paths {}", gpath);
NativeLibrary.addSearchPath("gstreamer-0.10", gpath);
} else {
- throw new WebcamException(String.format("GStreamer has not been installed or not in %PATH%: %s", path));
+ throw new WebcamException(String.format("GStreamer has not been installed or not available in PATH: %s", path));
}
}
//@formatter:off
String[] args = new String[] {
// "--gst-plugin-path", new File(".").getAbsolutePath(),
// "--gst-debug-level=3",
};
//@formatter:on
Gst.init(GStreamerDriver.class.getSimpleName(), args);
Runtime.getRuntime().addShutdownHook(new GStreamerShutdownHook());
}
@Override
public List<WebcamDevice> getDevices() {
List<WebcamDevice> devices = new ArrayList<WebcamDevice>();
String srcname = null;
if (Platform.isWindows()) {
srcname = "dshowvideosrc";
} else {
srcname = "v4l2src";
}
Element dshowsrc = ElementFactory.make(srcname, "source");
try {
if (Platform.isWindows()) {
PropertyProbe probe = PropertyProbe.wrap(dshowsrc);
for (Object name : probe.getValues("device-name")) {
devices.add(new GStreamerDevice(name.toString()));
}
} else if (Platform.isLinux()) {
VideoDeviceFilenameFilter vfilter = new VideoDeviceFilenameFilter();
for (File vfile : vfilter.getVideoFiles()) {
devices.add(new GStreamerDevice(vfile));
}
} else {
throw new RuntimeException("Platform unsupported by GStreamer capture driver");
}
} finally {
if (dshowsrc != null) {
dshowsrc.dispose();
}
}
return devices;
}
@Override
public boolean isThreadSafe() {
return false;
}
@Override
public String toString() {
return getClass().getSimpleName();
}
}
| true | true | private static final void init() {
if (!Platform.isWindows() && !Platform.isLinux()) {
throw new WebcamException(String.format("%s has been designed to work only on Windows and Linux platforms", GStreamerDriver.class.getSimpleName()));
}
LOG.debug("GStreamer initialization");
String gpath = null;
if (Platform.isWindows()) {
String path = System.getenv("PATH");
for (String p : path.split(";")) {
LOG.trace("Search %PATH% for gstreamer bin {}", p);
if (p.indexOf("GStreamer\\v0.10.") != -1) {
gpath = p;
break;
}
}
if (gpath != null) {
LOG.debug("Add bin directory to JNA search paths {}", gpath);
NativeLibrary.addSearchPath("gstreamer-0.10", gpath);
} else {
throw new WebcamException(String.format("GStreamer has not been installed or not in %PATH%: %s", path));
}
}
//@formatter:off
String[] args = new String[] {
// "--gst-plugin-path", new File(".").getAbsolutePath(),
// "--gst-debug-level=3",
};
//@formatter:on
Gst.init(GStreamerDriver.class.getSimpleName(), args);
Runtime.getRuntime().addShutdownHook(new GStreamerShutdownHook());
}
| private static final void init() {
if (!Platform.isWindows() && !Platform.isLinux()) {
throw new WebcamException(String.format("%s has been designed to work only on Windows and Linux platforms", GStreamerDriver.class.getSimpleName()));
}
LOG.debug("GStreamer initialization");
String gpath = null;
if (Platform.isWindows()) {
String path = System.getenv("PATH");
for (String p : path.split(";")) {
LOG.trace("Search %PATH% for gstreamer bin {}", p);
if (p.indexOf("GStreamer\\v0.10.") != -1) {
gpath = p;
break;
}
}
if (gpath != null) {
LOG.debug("Add bin directory to JNA search paths {}", gpath);
NativeLibrary.addSearchPath("gstreamer-0.10", gpath);
} else {
throw new WebcamException(String.format("GStreamer has not been installed or not available in PATH: %s", path));
}
}
//@formatter:off
String[] args = new String[] {
// "--gst-plugin-path", new File(".").getAbsolutePath(),
// "--gst-debug-level=3",
};
//@formatter:on
Gst.init(GStreamerDriver.class.getSimpleName(), args);
Runtime.getRuntime().addShutdownHook(new GStreamerShutdownHook());
}
|
diff --git a/src/jvm/clojure/lang/LispReader.java b/src/jvm/clojure/lang/LispReader.java
index 5bf22e66..368bc1fa 100644
--- a/src/jvm/clojure/lang/LispReader.java
+++ b/src/jvm/clojure/lang/LispReader.java
@@ -1,1067 +1,1080 @@
/**
* Copyright (c) Rich Hickey. All rights reserved.
* The use and distribution terms for this software are covered by the
* Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
* which can be found in the file epl-v10.html at the root of this distribution.
* By using this software in any fashion, you are agreeing to be bound by
* the terms of this license.
* You must not remove this notice, or any other, from this software.
**/
package clojure.lang;
import java.io.*;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.math.BigInteger;
import java.math.BigDecimal;
import java.lang.*;
public class LispReader{
static final Symbol QUOTE = Symbol.create("quote");
static final Symbol THE_VAR = Symbol.create("var");
//static Symbol SYNTAX_QUOTE = Symbol.create(null, "syntax-quote");
static Symbol UNQUOTE = Symbol.create("clojure.core", "unquote");
static Symbol UNQUOTE_SPLICING = Symbol.create("clojure.core", "unquote-splicing");
static Symbol CONCAT = Symbol.create("clojure.core", "concat");
static Symbol SEQ = Symbol.create("clojure.core", "seq");
static Symbol LIST = Symbol.create("clojure.core", "list");
static Symbol APPLY = Symbol.create("clojure.core", "apply");
static Symbol HASHMAP = Symbol.create("clojure.core", "hash-map");
static Symbol HASHSET = Symbol.create("clojure.core", "hash-set");
static Symbol VECTOR = Symbol.create("clojure.core", "vector");
static Symbol WITH_META = Symbol.create("clojure.core", "with-meta");
static Symbol META = Symbol.create("clojure.core", "meta");
static Symbol DEREF = Symbol.create("clojure.core", "deref");
//static Symbol DEREF_BANG = Symbol.create("clojure.core", "deref!");
static IFn[] macros = new IFn[256];
static IFn[] dispatchMacros = new IFn[256];
//static Pattern symbolPat = Pattern.compile("[:]?([\\D&&[^:/]][^:/]*/)?[\\D&&[^:/]][^:/]*");
static Pattern symbolPat = Pattern.compile("[:]?([\\D&&[^/]].*/)?([\\D&&[^/]][^/]*)");
//static Pattern varPat = Pattern.compile("([\\D&&[^:\\.]][^:\\.]*):([\\D&&[^:\\.]][^:\\.]*)");
//static Pattern intPat = Pattern.compile("[-+]?[0-9]+\\.?");
static Pattern intPat =
Pattern.compile(
"([-+]?)(?:(0)|([1-9][0-9]*)|0[xX]([0-9A-Fa-f]+)|0([0-7]+)|([1-9][0-9]?)[rR]([0-9A-Za-z]+)|0[0-9]+)");
static Pattern ratioPat = Pattern.compile("([-+]?[0-9]+)/([0-9]+)");
static Pattern floatPat = Pattern.compile("([-+]?[0-9]+(\\.[0-9]*)?([eE][-+]?[0-9]+)?)(M)?");
static final Symbol SLASH = Symbol.create("/");
static final Symbol CLOJURE_SLASH = Symbol.create("clojure.core","/");
//static Pattern accessorPat = Pattern.compile("\\.[a-zA-Z_]\\w*");
//static Pattern instanceMemberPat = Pattern.compile("\\.([a-zA-Z_][\\w\\.]*)\\.([a-zA-Z_]\\w*)");
//static Pattern staticMemberPat = Pattern.compile("([a-zA-Z_][\\w\\.]*)\\.([a-zA-Z_]\\w*)");
//static Pattern classNamePat = Pattern.compile("([a-zA-Z_][\\w\\.]*)\\.");
//symbol->gensymbol
static Var GENSYM_ENV = Var.create(null);
//sorted-map num->gensymbol
static Var ARG_ENV = Var.create(null);
static
{
macros['"'] = new StringReader();
macros[';'] = new CommentReader();
macros['\''] = new WrappingReader(QUOTE);
macros['@'] = new WrappingReader(DEREF);//new DerefReader();
macros['^'] = new WrappingReader(META);
macros['`'] = new SyntaxQuoteReader();
macros['~'] = new UnquoteReader();
macros['('] = new ListReader();
macros[')'] = new UnmatchedDelimiterReader();
macros['['] = new VectorReader();
macros[']'] = new UnmatchedDelimiterReader();
macros['{'] = new MapReader();
macros['}'] = new UnmatchedDelimiterReader();
// macros['|'] = new ArgVectorReader();
macros['\\'] = new CharacterReader();
macros['%'] = new ArgReader();
macros['#'] = new DispatchReader();
dispatchMacros['^'] = new MetaReader();
dispatchMacros['\''] = new VarReader();
dispatchMacros['"'] = new RegexReader();
dispatchMacros['('] = new FnReader();
dispatchMacros['{'] = new SetReader();
dispatchMacros['='] = new EvalReader();
dispatchMacros['!'] = new CommentReader();
dispatchMacros['<'] = new UnreadableReader();
dispatchMacros['_'] = new DiscardReader();
}
static boolean isWhitespace(int ch){
return Character.isWhitespace(ch) || ch == ',';
}
static void unread(PushbackReader r, int ch) throws IOException{
if(ch != -1)
r.unread(ch);
}
public static class ReaderException extends Exception{
final int line;
public ReaderException(int line, Throwable cause){
super(cause);
this.line = line;
}
}
static public Object read(PushbackReader r, boolean eofIsError, Object eofValue, boolean isRecursive)
throws Exception{
try
{
for(; ;)
{
int ch = r.read();
while(isWhitespace(ch))
ch = r.read();
if(ch == -1)
{
if(eofIsError)
throw new Exception("EOF while reading");
return eofValue;
}
if(Character.isDigit(ch))
{
Object n = readNumber(r, (char) ch);
if(RT.suppressRead())
return null;
return n;
}
IFn macroFn = getMacro(ch);
if(macroFn != null)
{
Object ret = macroFn.invoke(r, (char) ch);
if(RT.suppressRead())
return null;
//no op macros return the reader
if(ret == r)
continue;
return ret;
}
if(ch == '+' || ch == '-')
{
int ch2 = r.read();
if(Character.isDigit(ch2))
{
unread(r, ch2);
Object n = readNumber(r, (char) ch);
if(RT.suppressRead())
return null;
return n;
}
unread(r, ch2);
}
String token = readToken(r, (char) ch);
if(RT.suppressRead())
return null;
return interpretToken(token);
}
}
catch(Exception e)
{
if(isRecursive || !(r instanceof LineNumberingPushbackReader))
throw e;
LineNumberingPushbackReader rdr = (LineNumberingPushbackReader) r;
//throw new Exception(String.format("ReaderError:(%d,1) %s", rdr.getLineNumber(), e.getMessage()), e);
throw new ReaderException(rdr.getLineNumber(), e);
}
}
static private String readToken(PushbackReader r, char initch) throws Exception{
StringBuilder sb = new StringBuilder();
sb.append(initch);
for(; ;)
{
int ch = r.read();
if(ch == -1 || isWhitespace(ch) || isTerminatingMacro(ch))
{
unread(r, ch);
return sb.toString();
}
sb.append((char) ch);
}
}
static private Object readNumber(PushbackReader r, char initch) throws Exception{
StringBuilder sb = new StringBuilder();
sb.append(initch);
for(; ;)
{
int ch = r.read();
if(ch == -1 || isWhitespace(ch) || isMacro(ch))
{
unread(r, ch);
break;
}
sb.append((char) ch);
}
String s = sb.toString();
Object n = matchNumber(s);
if(n == null)
throw new NumberFormatException("Invalid number: " + s);
return n;
}
static private int readUnicodeChar(String token, int offset, int length, int base) throws Exception{
if(token.length() != offset + length)
throw new IllegalArgumentException("Invalid unicode character: \\" + token);
int uc = 0;
for(int i = offset; i < offset + length; ++i)
{
int d = Character.digit(token.charAt(i), base);
if(d == -1)
throw new IllegalArgumentException("Invalid digit: " + (char) d);
uc = uc * base + d;
}
return (char) uc;
}
static private int readUnicodeChar(PushbackReader r, int initch, int base, int length, boolean exact) throws Exception{
int uc = Character.digit(initch, base);
if(uc == -1)
throw new IllegalArgumentException("Invalid digit: " + initch);
int i = 1;
for(; i < length; ++i)
{
int ch = r.read();
if(ch == -1 || isWhitespace(ch) || isMacro(ch))
{
unread(r, ch);
break;
}
int d = Character.digit(ch, base);
if(d == -1)
throw new IllegalArgumentException("Invalid digit: " + (char) ch);
uc = uc * base + d;
}
if(i != length && exact)
throw new IllegalArgumentException("Invalid character length: " + i + ", should be: " + length);
return uc;
}
static private Object interpretToken(String s) throws Exception{
if(s.equals("nil"))
{
return null;
}
else if(s.equals("true"))
{
return RT.T;
}
else if(s.equals("false"))
{
return RT.F;
}
else if(s.equals("/"))
{
return SLASH;
}
else if(s.equals("clojure.core//"))
{
return CLOJURE_SLASH;
}
Object ret = null;
ret = matchSymbol(s);
if(ret != null)
return ret;
throw new Exception("Invalid token: " + s);
}
private static Object matchSymbol(String s){
Matcher m = symbolPat.matcher(s);
if(m.matches())
{
int gc = m.groupCount();
String ns = m.group(1);
String name = m.group(2);
if(ns != null && ns.endsWith(":/")
|| name.endsWith(":")
|| s.indexOf("::", 1) != -1)
return null;
if(s.startsWith("::"))
{
Symbol ks = Symbol.intern(s.substring(2));
Namespace kns;
if(ks.ns != null)
kns = Compiler.namespaceFor(ks);
else
kns = Compiler.currentNS();
//auto-resolving keyword
return Keyword.intern(kns.name.name,ks.name);
}
boolean isKeyword = s.charAt(0) == ':';
Symbol sym = Symbol.intern(s.substring(isKeyword ? 1 : 0));
if(isKeyword)
return Keyword.intern(sym);
return sym;
}
return null;
}
private static Object matchNumber(String s){
Matcher m = intPat.matcher(s);
if(m.matches())
{
if(m.group(2) != null)
return 0;
boolean negate = (m.group(1).equals("-"));
String n;
int radix = 10;
if((n = m.group(3)) != null)
radix = 10;
else if((n = m.group(4)) != null)
radix = 16;
else if((n = m.group(5)) != null)
radix = 8;
else if((n = m.group(7)) != null)
radix = Integer.parseInt(m.group(6));
if(n == null)
return null;
BigInteger bn = new BigInteger(n, radix);
return Numbers.reduce(negate ? bn.negate() : bn);
}
m = floatPat.matcher(s);
if(m.matches())
{
if(m.group(4) != null)
return new BigDecimal(m.group(1));
return Double.parseDouble(s);
}
m = ratioPat.matcher(s);
if(m.matches())
{
return Numbers.divide(new BigInteger(m.group(1)), new BigInteger(m.group(2)));
}
return null;
}
static private IFn getMacro(int ch){
if(ch < macros.length)
return macros[ch];
return null;
}
static private boolean isMacro(int ch){
return (ch < macros.length && macros[ch] != null);
}
static private boolean isTerminatingMacro(int ch){
return (ch != '#' && ch < macros.length && macros[ch] != null);
}
public static class RegexReader extends AFn{
static StringReader stringrdr = new StringReader();
public Object invoke(Object reader, Object doublequote) throws Exception{
StringBuilder sb = new StringBuilder();
Reader r = (Reader) reader;
for(int ch = r.read(); ch != '"'; ch = r.read())
{
if(ch == -1)
throw new Exception("EOF while reading regex");
sb.append( (char) ch );
if(ch == '\\') //escape
{
ch = r.read();
if(ch == -1)
throw new Exception("EOF while reading regex");
sb.append( (char) ch ) ;
}
}
return Pattern.compile(sb.toString());
}
}
public static class StringReader extends AFn{
public Object invoke(Object reader, Object doublequote) throws Exception{
StringBuilder sb = new StringBuilder();
Reader r = (Reader) reader;
for(int ch = r.read(); ch != '"'; ch = r.read())
{
if(ch == -1)
throw new Exception("EOF while reading string");
if(ch == '\\') //escape
{
ch = r.read();
if(ch == -1)
throw new Exception("EOF while reading string");
switch(ch)
{
case 't':
ch = '\t';
break;
case 'r':
ch = '\r';
break;
case 'n':
ch = '\n';
break;
case '\\':
break;
case '"':
break;
case 'b':
ch = '\b';
break;
case 'f':
ch = '\f';
break;
case 'u':
{
ch = r.read();
if (Character.digit(ch, 16) == -1)
throw new Exception("Invalid unicode escape: \\u" + (char) ch);
ch = readUnicodeChar((PushbackReader) r, ch, 16, 4, true);
break;
}
default:
{
if(Character.isDigit(ch))
{
ch = readUnicodeChar((PushbackReader) r, ch, 8, 3, false);
if(ch > 0377)
throw new Exception("Octal escape sequence must be in range [0, 377].");
}
else
throw new Exception("Unsupported escape character: \\" + (char) ch);
}
}
}
sb.append((char) ch);
}
return sb.toString();
}
}
public static class CommentReader extends AFn{
public Object invoke(Object reader, Object semicolon) throws Exception{
Reader r = (Reader) reader;
int ch;
do
{
ch = r.read();
} while(ch != -1 && ch != '\n' && ch != '\r');
return r;
}
}
public static class DiscardReader extends AFn{
public Object invoke(Object reader, Object underscore) throws Exception{
PushbackReader r = (PushbackReader) reader;
read(r, true, null, true);
return r;
}
}
public static class WrappingReader extends AFn{
final Symbol sym;
public WrappingReader(Symbol sym){
this.sym = sym;
}
public Object invoke(Object reader, Object quote) throws Exception{
PushbackReader r = (PushbackReader) reader;
Object o = read(r, true, null, true);
return RT.list(sym, o);
}
}
public static class VarReader extends AFn{
public Object invoke(Object reader, Object quote) throws Exception{
PushbackReader r = (PushbackReader) reader;
Object o = read(r, true, null, true);
// if(o instanceof Symbol)
// {
// Object v = Compiler.maybeResolveIn(Compiler.currentNS(), (Symbol) o);
// if(v instanceof Var)
// return v;
// }
return RT.list(THE_VAR, o);
}
}
/*
static class DerefReader extends AFn{
public Object invoke(Object reader, Object quote) throws Exception{
PushbackReader r = (PushbackReader) reader;
int ch = r.read();
if(ch == -1)
throw new Exception("EOF while reading character");
if(ch == '!')
{
Object o = read(r, true, null, true);
return RT.list(DEREF_BANG, o);
}
else
{
r.unread(ch);
Object o = read(r, true, null, true);
return RT.list(DEREF, o);
}
}
}
*/
public static class DispatchReader extends AFn{
public Object invoke(Object reader, Object hash) throws Exception{
int ch = ((Reader) reader).read();
if(ch == -1)
throw new Exception("EOF while reading character");
IFn fn = dispatchMacros[ch];
if(fn == null)
throw new Exception(String.format("No dispatch macro for: %c", (char) ch));
return fn.invoke(reader, ch);
}
}
static Symbol garg(int n){
return Symbol.intern(null, (n == -1 ? "rest" : ("p" + n)) + "__" + RT.nextID());
}
public static class FnReader extends AFn{
public Object invoke(Object reader, Object lparen) throws Exception{
PushbackReader r = (PushbackReader) reader;
if(ARG_ENV.deref() != null)
throw new IllegalStateException("Nested #()s are not allowed");
try
{
Var.pushThreadBindings(
RT.map(ARG_ENV, PersistentTreeMap.EMPTY));
r.unread('(');
Object form = read(r, true, null, true);
PersistentVector args = PersistentVector.EMPTY;
PersistentTreeMap argsyms = (PersistentTreeMap) ARG_ENV.deref();
ISeq rargs = argsyms.rseq();
if(rargs != null)
{
int higharg = (Integer) ((Map.Entry) rargs.first()).getKey();
if(higharg > 0)
{
for(int i = 1; i <= higharg; ++i)
{
Object sym = argsyms.valAt(i);
if(sym == null)
sym = garg(i);
args = args.cons(sym);
}
}
Object restsym = argsyms.valAt(-1);
if(restsym != null)
{
args = args.cons(Compiler._AMP_);
args = args.cons(restsym);
}
}
return RT.list(Compiler.FN, args, form);
}
finally
{
Var.popThreadBindings();
}
}
}
static Symbol registerArg(int n){
PersistentTreeMap argsyms = (PersistentTreeMap) ARG_ENV.deref();
if(argsyms == null)
{
throw new IllegalStateException("arg literal not in #()");
}
Symbol ret = (Symbol) argsyms.valAt(n);
if(ret == null)
{
ret = garg(n);
ARG_ENV.set(argsyms.assoc(n, ret));
}
return ret;
}
static class ArgReader extends AFn{
public Object invoke(Object reader, Object pct) throws Exception{
PushbackReader r = (PushbackReader) reader;
if(ARG_ENV.deref() == null)
{
return interpretToken(readToken(r, '%'));
}
int ch = r.read();
unread(r, ch);
//% alone is first arg
if(ch == -1 || isWhitespace(ch) || isTerminatingMacro(ch))
{
return registerArg(1);
}
Object n = read(r, true, null, true);
if(n.equals(Compiler._AMP_))
return registerArg(-1);
if(!(n instanceof Number))
throw new IllegalStateException("arg literal must be %, %& or %integer");
return registerArg(((Number) n).intValue());
}
}
public static class MetaReader extends AFn{
public Object invoke(Object reader, Object caret) throws Exception{
PushbackReader r = (PushbackReader) reader;
int line = -1;
if(r instanceof LineNumberingPushbackReader)
line = ((LineNumberingPushbackReader) r).getLineNumber();
Object meta = read(r, true, null, true);
if(meta instanceof Symbol || meta instanceof Keyword || meta instanceof String)
meta = RT.map(RT.TAG_KEY, meta);
else if(!(meta instanceof IPersistentMap))
throw new IllegalArgumentException("Metadata must be Symbol,Keyword,String or Map");
Object o = read(r, true, null, true);
if(o instanceof IMeta)
{
if(line != -1 && o instanceof ISeq)
meta = ((IPersistentMap) meta).assoc(RT.LINE_KEY, line);
if(o instanceof IReference)
{
((IReference)o).resetMeta((IPersistentMap) meta);
return o;
}
return ((IObj) o).withMeta((IPersistentMap) meta);
}
else
throw new IllegalArgumentException("Metadata can only be applied to IMetas");
}
}
public static class SyntaxQuoteReader extends AFn{
public Object invoke(Object reader, Object backquote) throws Exception{
PushbackReader r = (PushbackReader) reader;
try
{
Var.pushThreadBindings(
RT.map(GENSYM_ENV, PersistentHashMap.EMPTY));
Object form = read(r, true, null, true);
return syntaxQuote(form);
}
finally
{
Var.popThreadBindings();
}
}
static Object syntaxQuote(Object form) throws Exception{
Object ret;
if(Compiler.isSpecial(form))
ret = RT.list(Compiler.QUOTE, form);
else if(form instanceof Symbol)
{
Symbol sym = (Symbol) form;
if(sym.ns == null && sym.name.endsWith("#"))
{
IPersistentMap gmap = (IPersistentMap) GENSYM_ENV.deref();
if(gmap == null)
throw new IllegalStateException("Gensym literal not in syntax-quote");
Symbol gs = (Symbol) gmap.valAt(sym);
if(gs == null)
GENSYM_ENV.set(gmap.assoc(sym, gs = Symbol.intern(null,
sym.name.substring(0, sym.name.length() - 1)
+ "__" + RT.nextID() + "__auto__")));
sym = gs;
}
else if(sym.ns == null && sym.name.endsWith("."))
{
Symbol csym = Symbol.intern(null, sym.name.substring(0, sym.name.length() - 1));
csym = Compiler.resolveSymbol(csym);
sym = Symbol.intern(null, csym.name.concat("."));
}
else if(sym.ns == null && sym.name.startsWith("."))
{
// Simply quote method names.
}
else
- sym = Compiler.resolveSymbol(sym);
+ {
+ Object maybeClass = null;
+ if(sym.ns != null)
+ maybeClass = Compiler.currentNS().getMapping(
+ Symbol.intern(null, sym.ns));
+ if(maybeClass instanceof Class)
+ {
+ // Classname/foo -> package.qualified.Classname/foo
+ sym = Symbol.intern(
+ ((Class)maybeClass).getName(), sym.name);
+ }
+ else
+ sym = Compiler.resolveSymbol(sym);
+ }
ret = RT.list(Compiler.QUOTE, sym);
}
else if(isUnquote(form))
return RT.second(form);
else if(isUnquoteSplicing(form))
throw new IllegalStateException("splice not in list");
else if(form instanceof IPersistentCollection)
{
if(form instanceof IPersistentMap)
{
IPersistentVector keyvals = flattenMap(form);
ret = RT.list(APPLY, HASHMAP, RT.list(SEQ, RT.cons(CONCAT, sqExpandList(keyvals.seq()))));
}
else if(form instanceof IPersistentVector)
{
ret = RT.list(APPLY, VECTOR, RT.list(SEQ, RT.cons(CONCAT, sqExpandList(((IPersistentVector) form).seq()))));
}
else if(form instanceof IPersistentSet)
{
ret = RT.list(APPLY, HASHSET, RT.list(SEQ, RT.cons(CONCAT, sqExpandList(((IPersistentSet) form).seq()))));
}
else if(form instanceof ISeq || form instanceof IPersistentList)
{
ISeq seq = RT.seq(form);
if(seq == null)
ret = RT.cons(LIST,null);
else
ret = RT.list(SEQ, RT.cons(CONCAT, sqExpandList(seq)));
}
else
throw new UnsupportedOperationException("Unknown Collection type");
}
else if(form instanceof Keyword
|| form instanceof Number
|| form instanceof Character
|| form instanceof String)
ret = form;
else
ret = RT.list(Compiler.QUOTE, form);
if(form instanceof IObj && RT.meta(form) != null)
{
//filter line numbers
IPersistentMap newMeta = ((IObj) form).meta().without(RT.LINE_KEY);
if(newMeta.count() > 0)
return RT.list(WITH_META, ret, syntaxQuote(((IObj) form).meta()));
}
return ret;
}
private static ISeq sqExpandList(ISeq seq) throws Exception{
PersistentVector ret = PersistentVector.EMPTY;
for(; seq != null; seq = seq.next())
{
Object item = seq.first();
if(isUnquote(item))
ret = ret.cons(RT.list(LIST, RT.second(item)));
else if(isUnquoteSplicing(item))
ret = ret.cons(RT.second(item));
else
ret = ret.cons(RT.list(LIST, syntaxQuote(item)));
}
return ret.seq();
}
private static IPersistentVector flattenMap(Object form){
IPersistentVector keyvals = PersistentVector.EMPTY;
for(ISeq s = RT.seq(form); s != null; s = s.next())
{
IMapEntry e = (IMapEntry) s.first();
keyvals = (IPersistentVector) keyvals.cons(e.key());
keyvals = (IPersistentVector) keyvals.cons(e.val());
}
return keyvals;
}
}
static boolean isUnquoteSplicing(Object form){
return form instanceof ISeq && Util.equals(RT.first(form),UNQUOTE_SPLICING);
}
static boolean isUnquote(Object form){
return form instanceof ISeq && Util.equals(RT.first(form),UNQUOTE);
}
static class UnquoteReader extends AFn{
public Object invoke(Object reader, Object comma) throws Exception{
PushbackReader r = (PushbackReader) reader;
int ch = r.read();
if(ch == -1)
throw new Exception("EOF while reading character");
if(ch == '@')
{
Object o = read(r, true, null, true);
return RT.list(UNQUOTE_SPLICING, o);
}
else
{
unread(r, ch);
Object o = read(r, true, null, true);
return RT.list(UNQUOTE, o);
}
}
}
public static class CharacterReader extends AFn{
public Object invoke(Object reader, Object backslash) throws Exception{
PushbackReader r = (PushbackReader) reader;
int ch = r.read();
if(ch == -1)
throw new Exception("EOF while reading character");
String token = readToken(r, (char) ch);
if(token.length() == 1)
return Character.valueOf(token.charAt(0));
else if(token.equals("newline"))
return '\n';
else if(token.equals("space"))
return ' ';
else if(token.equals("tab"))
return '\t';
else if(token.equals("backspace"))
return '\b';
else if(token.equals("formfeed"))
return '\f';
else if(token.equals("return"))
return '\r';
else if(token.startsWith("u"))
{
char c = (char) readUnicodeChar(token, 1, 4, 16);
if(c >= '\uD800' && c <= '\uDFFF') // surrogate code unit?
throw new Exception("Invalid character constant: \\u" + Integer.toString(c, 16));
return c;
}
else if(token.startsWith("o"))
{
int len = token.length() - 1;
if(len > 3)
throw new Exception("Invalid octal escape sequence length: " + len);
int uc = readUnicodeChar(token, 1, len, 8);
if(uc > 0377)
throw new Exception("Octal escape sequence must be in range [0, 377].");
return (char) uc;
}
throw new Exception("Unsupported character: \\" + token);
}
}
public static class ListReader extends AFn{
public Object invoke(Object reader, Object leftparen) throws Exception{
PushbackReader r = (PushbackReader) reader;
int line = -1;
if(r instanceof LineNumberingPushbackReader)
line = ((LineNumberingPushbackReader) r).getLineNumber();
List list = readDelimitedList(')', r, true);
if(list.isEmpty())
return PersistentList.EMPTY;
IObj s = (IObj) PersistentList.create(list);
// IObj s = (IObj) RT.seq(list);
if(line != -1)
return s.withMeta(RT.map(RT.LINE_KEY, line));
else
return s;
}
}
static class CtorReader extends AFn{
static final Symbol cls = Symbol.create("class");
public Object invoke(Object reader, Object leftangle) throws Exception{
PushbackReader r = (PushbackReader) reader;
// #<class classname>
// #<classname args*>
// #<classname/staticMethod args*>
List list = readDelimitedList('>', r, true);
if(list.isEmpty())
throw new Exception("Must supply 'class', classname or classname/staticMethod");
Symbol s = (Symbol) list.get(0);
Object[] args = list.subList(1, list.size()).toArray();
if(s.equals(cls))
{
return RT.classForName(args[0].toString());
}
else if(s.ns != null) //static method
{
String classname = s.ns;
String method = s.name;
return Reflector.invokeStaticMethod(classname, method, args);
}
else
{
return Reflector.invokeConstructor(RT.classForName(s.name), args);
}
}
}
public static class EvalReader extends AFn{
public Object invoke(Object reader, Object eq) throws Exception{
if (!RT.booleanCast(RT.READEVAL.deref()))
{
throw new Exception("EvalReader not allowed when *read-eval* is false.");
}
PushbackReader r = (PushbackReader) reader;
Object o = read(r, true, null, true);
if(o instanceof Symbol)
{
return RT.classForName(o.toString());
}
else if(o instanceof IPersistentList)
{
Symbol fs = (Symbol) RT.first(o);
if(fs.equals(THE_VAR))
{
Symbol vs = (Symbol) RT.second(o);
return RT.var(vs.ns, vs.name); //Compiler.resolve((Symbol) RT.second(o),true);
}
if(fs.name.endsWith("."))
{
Object[] args = RT.toArray(RT.next(o));
return Reflector.invokeConstructor(RT.classForName(fs.name.substring(0, fs.name.length() - 1)), args);
}
if(Compiler.namesStaticMember(fs))
{
Object[] args = RT.toArray(RT.next(o));
return Reflector.invokeStaticMethod(fs.ns, fs.name, args);
}
Object v = Compiler.maybeResolveIn(Compiler.currentNS(), fs);
if(v instanceof Var)
{
return ((IFn) v).applyTo(RT.next(o));
}
throw new Exception("Can't resolve " + fs);
}
else
throw new IllegalArgumentException("Unsupported #= form");
}
}
//static class ArgVectorReader extends AFn{
// public Object invoke(Object reader, Object leftparen) throws Exception{
// PushbackReader r = (PushbackReader) reader;
// return ArgVector.create(readDelimitedList('|', r, true));
// }
//
//}
public static class VectorReader extends AFn{
public Object invoke(Object reader, Object leftparen) throws Exception{
PushbackReader r = (PushbackReader) reader;
return LazilyPersistentVector.create(readDelimitedList(']', r, true));
}
}
public static class MapReader extends AFn{
public Object invoke(Object reader, Object leftparen) throws Exception{
PushbackReader r = (PushbackReader) reader;
return RT.map(readDelimitedList('}', r, true).toArray());
}
}
public static class SetReader extends AFn{
public Object invoke(Object reader, Object leftbracket) throws Exception{
PushbackReader r = (PushbackReader) reader;
return PersistentHashSet.create(readDelimitedList('}', r, true));
}
}
public static class UnmatchedDelimiterReader extends AFn{
public Object invoke(Object reader, Object rightdelim) throws Exception{
throw new Exception("Unmatched delimiter: " + rightdelim);
}
}
public static class UnreadableReader extends AFn{
public Object invoke(Object reader, Object leftangle) throws Exception{
throw new Exception("Unreadable form");
}
}
public static List readDelimitedList(char delim, PushbackReader r, boolean isRecursive) throws Exception{
ArrayList a = new ArrayList();
for(; ;)
{
int ch = r.read();
while(isWhitespace(ch))
ch = r.read();
if(ch == -1)
throw new Exception("EOF while reading");
if(ch == delim)
break;
IFn macroFn = getMacro(ch);
if(macroFn != null)
{
Object mret = macroFn.invoke(r, (char) ch);
//no op macros return the reader
if(mret != r)
a.add(mret);
}
else
{
unread(r, ch);
Object o = read(r, true, null, isRecursive);
if(o != r)
a.add(o);
}
}
return a;
}
/*
public static void main(String[] args) throws Exception{
//RT.init();
PushbackReader rdr = new PushbackReader( new java.io.StringReader( "(+ 21 21)" ) );
Object input = LispReader.read(rdr, false, new Object(), false );
System.out.println(Compiler.eval(input));
}
public static void main(String[] args){
LineNumberingPushbackReader r = new LineNumberingPushbackReader(new InputStreamReader(System.in));
OutputStreamWriter w = new OutputStreamWriter(System.out);
Object ret = null;
try
{
for(; ;)
{
ret = LispReader.read(r, true, null, false);
RT.print(ret, w);
w.write('\n');
if(ret != null)
w.write(ret.getClass().toString());
w.write('\n');
w.flush();
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
*/
}
| true | true | static Object syntaxQuote(Object form) throws Exception{
Object ret;
if(Compiler.isSpecial(form))
ret = RT.list(Compiler.QUOTE, form);
else if(form instanceof Symbol)
{
Symbol sym = (Symbol) form;
if(sym.ns == null && sym.name.endsWith("#"))
{
IPersistentMap gmap = (IPersistentMap) GENSYM_ENV.deref();
if(gmap == null)
throw new IllegalStateException("Gensym literal not in syntax-quote");
Symbol gs = (Symbol) gmap.valAt(sym);
if(gs == null)
GENSYM_ENV.set(gmap.assoc(sym, gs = Symbol.intern(null,
sym.name.substring(0, sym.name.length() - 1)
+ "__" + RT.nextID() + "__auto__")));
sym = gs;
}
else if(sym.ns == null && sym.name.endsWith("."))
{
Symbol csym = Symbol.intern(null, sym.name.substring(0, sym.name.length() - 1));
csym = Compiler.resolveSymbol(csym);
sym = Symbol.intern(null, csym.name.concat("."));
}
else if(sym.ns == null && sym.name.startsWith("."))
{
// Simply quote method names.
}
else
sym = Compiler.resolveSymbol(sym);
ret = RT.list(Compiler.QUOTE, sym);
}
else if(isUnquote(form))
return RT.second(form);
else if(isUnquoteSplicing(form))
throw new IllegalStateException("splice not in list");
else if(form instanceof IPersistentCollection)
{
if(form instanceof IPersistentMap)
{
IPersistentVector keyvals = flattenMap(form);
ret = RT.list(APPLY, HASHMAP, RT.list(SEQ, RT.cons(CONCAT, sqExpandList(keyvals.seq()))));
}
else if(form instanceof IPersistentVector)
{
ret = RT.list(APPLY, VECTOR, RT.list(SEQ, RT.cons(CONCAT, sqExpandList(((IPersistentVector) form).seq()))));
}
else if(form instanceof IPersistentSet)
{
ret = RT.list(APPLY, HASHSET, RT.list(SEQ, RT.cons(CONCAT, sqExpandList(((IPersistentSet) form).seq()))));
}
else if(form instanceof ISeq || form instanceof IPersistentList)
{
ISeq seq = RT.seq(form);
if(seq == null)
ret = RT.cons(LIST,null);
else
ret = RT.list(SEQ, RT.cons(CONCAT, sqExpandList(seq)));
}
else
throw new UnsupportedOperationException("Unknown Collection type");
}
else if(form instanceof Keyword
|| form instanceof Number
|| form instanceof Character
|| form instanceof String)
ret = form;
else
ret = RT.list(Compiler.QUOTE, form);
if(form instanceof IObj && RT.meta(form) != null)
{
//filter line numbers
IPersistentMap newMeta = ((IObj) form).meta().without(RT.LINE_KEY);
if(newMeta.count() > 0)
return RT.list(WITH_META, ret, syntaxQuote(((IObj) form).meta()));
}
return ret;
}
| static Object syntaxQuote(Object form) throws Exception{
Object ret;
if(Compiler.isSpecial(form))
ret = RT.list(Compiler.QUOTE, form);
else if(form instanceof Symbol)
{
Symbol sym = (Symbol) form;
if(sym.ns == null && sym.name.endsWith("#"))
{
IPersistentMap gmap = (IPersistentMap) GENSYM_ENV.deref();
if(gmap == null)
throw new IllegalStateException("Gensym literal not in syntax-quote");
Symbol gs = (Symbol) gmap.valAt(sym);
if(gs == null)
GENSYM_ENV.set(gmap.assoc(sym, gs = Symbol.intern(null,
sym.name.substring(0, sym.name.length() - 1)
+ "__" + RT.nextID() + "__auto__")));
sym = gs;
}
else if(sym.ns == null && sym.name.endsWith("."))
{
Symbol csym = Symbol.intern(null, sym.name.substring(0, sym.name.length() - 1));
csym = Compiler.resolveSymbol(csym);
sym = Symbol.intern(null, csym.name.concat("."));
}
else if(sym.ns == null && sym.name.startsWith("."))
{
// Simply quote method names.
}
else
{
Object maybeClass = null;
if(sym.ns != null)
maybeClass = Compiler.currentNS().getMapping(
Symbol.intern(null, sym.ns));
if(maybeClass instanceof Class)
{
// Classname/foo -> package.qualified.Classname/foo
sym = Symbol.intern(
((Class)maybeClass).getName(), sym.name);
}
else
sym = Compiler.resolveSymbol(sym);
}
ret = RT.list(Compiler.QUOTE, sym);
}
else if(isUnquote(form))
return RT.second(form);
else if(isUnquoteSplicing(form))
throw new IllegalStateException("splice not in list");
else if(form instanceof IPersistentCollection)
{
if(form instanceof IPersistentMap)
{
IPersistentVector keyvals = flattenMap(form);
ret = RT.list(APPLY, HASHMAP, RT.list(SEQ, RT.cons(CONCAT, sqExpandList(keyvals.seq()))));
}
else if(form instanceof IPersistentVector)
{
ret = RT.list(APPLY, VECTOR, RT.list(SEQ, RT.cons(CONCAT, sqExpandList(((IPersistentVector) form).seq()))));
}
else if(form instanceof IPersistentSet)
{
ret = RT.list(APPLY, HASHSET, RT.list(SEQ, RT.cons(CONCAT, sqExpandList(((IPersistentSet) form).seq()))));
}
else if(form instanceof ISeq || form instanceof IPersistentList)
{
ISeq seq = RT.seq(form);
if(seq == null)
ret = RT.cons(LIST,null);
else
ret = RT.list(SEQ, RT.cons(CONCAT, sqExpandList(seq)));
}
else
throw new UnsupportedOperationException("Unknown Collection type");
}
else if(form instanceof Keyword
|| form instanceof Number
|| form instanceof Character
|| form instanceof String)
ret = form;
else
ret = RT.list(Compiler.QUOTE, form);
if(form instanceof IObj && RT.meta(form) != null)
{
//filter line numbers
IPersistentMap newMeta = ((IObj) form).meta().without(RT.LINE_KEY);
if(newMeta.count() > 0)
return RT.list(WITH_META, ret, syntaxQuote(((IObj) form).meta()));
}
return ret;
}
|
diff --git a/plugins/org.eclipse.incquery.patternlanguage.emf/src/org/eclipse/incquery/patternlanguage/emf/validation/EMFPatternLanguageSyntaxErrorMessageProvider.java b/plugins/org.eclipse.incquery.patternlanguage.emf/src/org/eclipse/incquery/patternlanguage/emf/validation/EMFPatternLanguageSyntaxErrorMessageProvider.java
index 519cfe9b..345afe04 100644
--- a/plugins/org.eclipse.incquery.patternlanguage.emf/src/org/eclipse/incquery/patternlanguage/emf/validation/EMFPatternLanguageSyntaxErrorMessageProvider.java
+++ b/plugins/org.eclipse.incquery.patternlanguage.emf/src/org/eclipse/incquery/patternlanguage/emf/validation/EMFPatternLanguageSyntaxErrorMessageProvider.java
@@ -1,43 +1,43 @@
/*******************************************************************************
* Copyright (c) 2010-2012, Zoltan Ujhelyi, Istvan Rath and Daniel Varro
* 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
*
* Contributors:
* Zoltan Ujhelyi - initial API and implementation
*******************************************************************************/
package org.eclipse.incquery.patternlanguage.emf.validation;
import org.antlr.runtime.MismatchedTokenException;
import org.eclipse.incquery.patternlanguage.emf.services.EMFPatternLanguageGrammarAccess;
import org.eclipse.xtext.nodemodel.SyntaxErrorMessage;
import org.eclipse.xtext.parser.antlr.SyntaxErrorMessageProvider;
import com.google.inject.Inject;
public class EMFPatternLanguageSyntaxErrorMessageProvider extends SyntaxErrorMessageProvider {
@Inject
EMFPatternLanguageGrammarAccess grammar;
@Override
public SyntaxErrorMessage getSyntaxErrorMessage(IParserErrorContext context) {
if (context.getRecognitionException() instanceof MismatchedTokenException) {
MismatchedTokenException exception = (MismatchedTokenException) context.getRecognitionException();
if (exception.expecting >= 0 && exception.getUnexpectedType() >= 0) {
String expectingTokenTypeName = context.getTokenNames()[exception.expecting];
String unexpectedTokenTypeName = context.getTokenNames()[exception.getUnexpectedType()];
- if ("RULE_ID".equals(expectingTokenTypeName)
+ if ("RULE_ID".equals(expectingTokenTypeName) && !unexpectedTokenTypeName.startsWith("RULE_")
&& Character.isJavaIdentifierStart(unexpectedTokenTypeName.replace("'", "").charAt(0))) {
return new SyntaxErrorMessage(
"Keywords of the query language are to be prefixed with the ^ character when used as an identifier",
EMFIssueCodes.IDENTIFIER_AS_KEYWORD);
}
}
}
return super.getSyntaxErrorMessage(context);
}
}
| true | true | public SyntaxErrorMessage getSyntaxErrorMessage(IParserErrorContext context) {
if (context.getRecognitionException() instanceof MismatchedTokenException) {
MismatchedTokenException exception = (MismatchedTokenException) context.getRecognitionException();
if (exception.expecting >= 0 && exception.getUnexpectedType() >= 0) {
String expectingTokenTypeName = context.getTokenNames()[exception.expecting];
String unexpectedTokenTypeName = context.getTokenNames()[exception.getUnexpectedType()];
if ("RULE_ID".equals(expectingTokenTypeName)
&& Character.isJavaIdentifierStart(unexpectedTokenTypeName.replace("'", "").charAt(0))) {
return new SyntaxErrorMessage(
"Keywords of the query language are to be prefixed with the ^ character when used as an identifier",
EMFIssueCodes.IDENTIFIER_AS_KEYWORD);
}
}
}
return super.getSyntaxErrorMessage(context);
}
| public SyntaxErrorMessage getSyntaxErrorMessage(IParserErrorContext context) {
if (context.getRecognitionException() instanceof MismatchedTokenException) {
MismatchedTokenException exception = (MismatchedTokenException) context.getRecognitionException();
if (exception.expecting >= 0 && exception.getUnexpectedType() >= 0) {
String expectingTokenTypeName = context.getTokenNames()[exception.expecting];
String unexpectedTokenTypeName = context.getTokenNames()[exception.getUnexpectedType()];
if ("RULE_ID".equals(expectingTokenTypeName) && !unexpectedTokenTypeName.startsWith("RULE_")
&& Character.isJavaIdentifierStart(unexpectedTokenTypeName.replace("'", "").charAt(0))) {
return new SyntaxErrorMessage(
"Keywords of the query language are to be prefixed with the ^ character when used as an identifier",
EMFIssueCodes.IDENTIFIER_AS_KEYWORD);
}
}
}
return super.getSyntaxErrorMessage(context);
}
|
diff --git a/bindings/java/test/org/sleuthkit/datamodel/DataModelTestSuite.java b/bindings/java/test/org/sleuthkit/datamodel/DataModelTestSuite.java
index 136557d5..f0957295 100644
--- a/bindings/java/test/org/sleuthkit/datamodel/DataModelTestSuite.java
+++ b/bindings/java/test/org/sleuthkit/datamodel/DataModelTestSuite.java
@@ -1,552 +1,552 @@
/*
* Sleuth Kit Data Model
*
* Copyright 2013 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* 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.sleuthkit.datamodel;
import java.io.FileFilter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
/**
*
* Runs all regression tests and contains utility methods for the tests
*/
@RunWith(Suite.class)
@Suite.SuiteClasses({org.sleuthkit.datamodel.TopDownTraversal.class, org.sleuthkit.datamodel.SequentialTraversal.class, org.sleuthkit.datamodel.CrossCompare.class, org.sleuthkit.datamodel.BottomUpTest.class, org.sleuthkit.datamodel.CPPtoJavaCompare.class})
public class DataModelTestSuite {
static final String TEST_IMAGE_DIR_NAME = "test" + java.io.File.separator + "Input";
static final String INPT = "inpt";
static final String GOLD = "gold";
static final String RSLT = "rslt";
static final String SEQ = "_Seq";
static final String TD = "_TD";
static final String LVS = "_Leaves";
static final String EX = "_Exceptions";
static final String TST = "types";
static final int READ_BUFFER_SIZE = 8192;
static final String HASH_ALGORITHM = "MD5";
private static final Logger logg = Logger.getLogger(DataModelTestSuite.class.getName());
/**
* Empties the results directory
*
* @throws Exception
*/
@BeforeClass
public static void setUpClass() throws Exception {
java.io.File results = new java.io.File(getRsltPath());
for (java.io.File del : results.listFiles()) {
del.delete();
}
}
/**
* Generates a list of the traversals to be used for standard creations
*
* @return
*/
public static List<ImgTraverser> getTests() {
List<ImgTraverser> ret = new ArrayList<ImgTraverser>();
ret.add(new SequentialTraversal(null));
ret.add(new TopDownTraversal(null));
return ret;
}
/**
* Creates the Sleuth Kit database for an image, then generates a string
* representation of the given traversal type of the resulting database to
* use as a standard for comparison, and saves the the standard to a file.
*
* @param standardPath The path to save the standard file to (will be
* overwritten if it already exists)
* @param tempDirPath An existing directory to create the test database in
* @param imagePaths The path(s) to the image file(s)
* @param type The type of traversal to run.
* @param exFile The exceptions file, will be used for logging purposes
*/
public static void createStandard(String standardPath, String tempDirPath, List<String> imagePaths, ImgTraverser type) {
java.io.File standardFile = new java.io.File(standardPath);
String exFile = standardFile.getAbsolutePath().replace(".txt", EX + ".txt");
try {
String firstImageFile = getImgName(imagePaths.get(0));
String dbPath = buildPath(tempDirPath, firstImageFile, type.getClass().getSimpleName(), ".db");
java.io.File dbFile = new java.io.File(dbPath);
standardFile.createNewFile();
dbFile.delete();
SleuthkitCase sk = SleuthkitCase.newCase(dbPath);
String timezone = "";
SleuthkitJNI.CaseDbHandle.AddImageProcess process = sk.makeAddImageProcess(timezone, true, false);
java.io.File xfile = new java.io.File(exFile);
xfile.createNewFile();
try {
process.run(imagePaths.toArray(new String[imagePaths.size()]));
} catch (TskDataException ex) {
writeExceptions(standardFile.getAbsolutePath(), ex);
}
process.commit();
FileWriter standardWriter = type.traverse(sk, standardFile.getAbsolutePath());
standardWriter.flush();
runSort(standardFile.getAbsolutePath());
} catch (IOException ex) {
logg.log(Level.SEVERE, "Couldn't create Standard", ex);
throw new RuntimeException(ex);
} catch (TskCoreException ex) {
writeExceptions(standardFile.getAbsolutePath(), ex);
}
}
/**
* Gets the paths to the test image files by looking for a test image in the
* given output directory
*
* @return A list of lists of paths to image parts
*/
static List<List<String>> getImagePaths() {
// needs to be absolute file because we're going to walk up its path
java.io.File dir = new java.io.File(System.getProperty(INPT, TEST_IMAGE_DIR_NAME));
FileFilter imageFilter = new FileFilter() {
@Override
public boolean accept(java.io.File f) {
return isImgFile(f.getName());
}
};
List<List<String>> images = new ArrayList<List<String>>();
for (java.io.File imageSet : dir.listFiles(imageFilter)) {
ArrayList<String> imgs = new ArrayList<String>();
imgs.add(imageSet.getAbsolutePath());
images.add(imgs);
}
return images;
}
/**
* Get the path for a standard corresponding to the given image path.
*
* @param imagePaths path of the image to get a standard for
* @return path to put/find the standard at
*/
static String standardPath(List<String> imagePaths, String type) {
String firstImage = getImgName(imagePaths.get(0));
String standardPath = goldStandardPath() + java.io.File.separator + firstImage + "_" + type + ".txt";
return standardPath;
}
/**
* removes the files with the file name from the from the given path
*
* @param path the path to the folder where files are to be deleted
* @param filename the name of the files to be deleted
*/
public static void emptyResults(String path, String filename) {
final String filt = filename.replace(TD, "").replace(".txt", "").replace(SEQ, "");
FileFilter imageResFilter = new FileFilter() {
@Override
public boolean accept(java.io.File f) {
return f.getName().contains(filt) & !f.getName().contains(LVS) & !f.getName().contains("Sorted");
}
};
java.io.File pth = new java.io.File(path);
for (java.io.File del : pth.listFiles(imageResFilter)) {
del.deleteOnExit();
}
}
/**
* Runs tsk_gettimes to create a standard for comparing DataModel and TSK
* output.
*
* @param standardPath The path to the file to put the tsk data in
* @param img the path to the image, is a list for compatability reasons
*/
- private static void getTSKData(String standardPath, List<String> img) {
+ private static void getTSKData(String standardPath, List<String> img) {
String tsk_loc;
java.io.File up = new java.io.File(System.getProperty("user.dir"));
up = up.getParentFile();
up = up.getParentFile();
if (System.getProperty("os.name").contains("Windows")) {
tsk_loc = up.getAbsolutePath() + "\\win32\\Release\\tsk_gettimes";
} else {
tsk_loc = up.getAbsolutePath() + "/tools/autotools/tsk_gettimes";
}
String[] cmd = {tsk_loc, img.get(0)};
try {
Process p = Runtime.getRuntime().exec(cmd);
Scanner read = new Scanner(p.getInputStream());
Scanner error1 = new Scanner(p.getErrorStream());
FileWriter out = new FileWriter(standardPath);
while (read.hasNextLine()) {
String line = read.nextLine();
line = line.replace(" (deleted)", "");
line = line.replace("(null)", "");
//removes unknown data attached to metaAddr
String[] linecontents = line.split("\\|");
String metaaddrcon = linecontents[2];
String mtad = metaaddrcon.split("\\-")[0];
line = line.replace(metaaddrcon, mtad);
out.append(line);
out.flush();
out.append("\n");
}
runSort(standardPath);
} catch (Exception ex) {
logg.log(Level.SEVERE, "Failed to run CPP program", ex);
}
java.io.File xfile = new java.io.File(standardPath.replace(".txt", DataModelTestSuite.EX + ".txt"));
try {
xfile.createNewFile();
} catch (IOException ex) {
logg.log(Level.SEVERE, "Failed to create exceptions file", ex);
}
}
/**
* Strips the file extension from the given string
*
* @param title the file to have its extension stripped
* @return
*/
private static String stripExtension(String title) {
return title.substring(0, title.lastIndexOf("."));
}
/**
* builds the path for an output file
*
* @param path the path to the directory for the file to be stored in
* @param name the name of the file
* @param type the output type of the file
* @param Ext the file extension
* @return the path for an output file
*/
public static String buildPath(String path, String name, String type, String Ext) {
return path + java.io.File.separator + name + "_" + type + Ext;
}
/**
* Returns the name of an image from the given path
*
* @param img
* @return
*/
public static String getImgName(String img) {
String[] imgSp;
if (System.getProperty("os.name").contains("Windows")) {
imgSp = img.split("\\\\");
} else {
imgSp = img.split("/");
}
return stripExtension(imgSp[imgSp.length - 1]);
}
/**
* Gets the location results are stored in.
*
* @return
*/
public static String getRsltPath() {
return System.getProperty(RSLT, "test" + java.io.File.separator + "output" + java.io.File.separator + "results");
}
/**
* returns the path to the sort command
*
* @return
*/
private static String getSortPath() {
if (!System.getProperty("os.name").contains("Windows")) {
return "sort";
} else {
return "\\cygwin\\bin\\sort.exe";
}
}
/**
* returns the path to the diff command
*
* @return
*/
private static String getDiffPath() {
if (!System.getProperty("os.name").contains("Windows")) {
return "diff";
} else {
return "\\cygwin\\bin\\diff.exe";
}
}
/**
* Writes the given exception to the given file
*
* @param filename the path of the file that exceptions are being stored for
* @param ex the exception to be written
*/
protected static void writeExceptions(String filename, Exception ex) {
filename = filename.replace(".txt", EX + ".txt");
FileWriter exWriter;
try {
exWriter = new FileWriter(filename, true);
exWriter.append(ex.toString());
exWriter.flush();
exWriter.close();
} catch (IOException ex1) {
logg.log(Level.SEVERE, "Couldn't log Exception", ex1);
}
}
/**
* returns the gold standard path
*
* @return
*/
private static String goldStandardPath() {
return System.getProperty(GOLD, ("test" + java.io.File.separator + "output" + java.io.File.separator + "gold"));
}
/**
* Reads the data for a given content object, used to create hashes
*
* @param c the content object to be read
* @param result the appendable to append the results to
* @param StrgFile the file path that the content is being read for
*/
public static void readContent(Content c, Appendable result, String StrgFile) {
long size = c.getSize();
byte[] readBuffer = new byte[READ_BUFFER_SIZE];
try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
for (long i = 0; i < size; i = i + READ_BUFFER_SIZE) {
c.read(readBuffer, i, Math.min(size - i, READ_BUFFER_SIZE));
md5.update(readBuffer);
}
String hash = toHex(md5.digest());
result.append("md5=" + hash);
} catch (NoSuchAlgorithmException ex) {
logg.log(Level.SEVERE, "Failed to generate Hash", ex);
} catch (IOException ex){
logg.log(Level.SEVERE, "Failed to generate Hash", ex);
} catch (TskCoreException ex) {
writeExceptions(StrgFile, ex);
}
}
/**
* Helper method for Read Content, converts a byte array to a Hexadecimal
* String
*
* @param bytes given byte array.
* @return a Hexadecimal String
*/
private static String toHex(byte[] bytes) {
StringBuilder hex = new StringBuilder();
for (byte b : bytes) {
hex.append(String.format("%02x", b & 0xFF));
}
return hex.toString();
}
/**
* gets the metadata from a datamodel file object
*
* @param fi
* @return
* @throws TskCoreException
*/
protected static String getFsCData(FsContent fi) throws TskCoreException {
String[] path = fi.getUniquePath().split("/", 3);
String name;
if (path[2].contains("vol_")) {
String[] pthget = path[2].split("_", 2);
name = pthget[pthget.length - 1];
} else {
name = path[2];
}
name = name.replaceAll("[^\\x20-\\x7e]", "");
String prpnd;
if (fi.isFile()) {
prpnd = "r/";
} else {
prpnd = "d/";
}
if (fi.isVirtual() && !fi.isDir()) {
prpnd = "v/";
}
return ("0|" + name + "|" + fi.metaAddr + "|" + fi.getMetaTypeAsString() + "/" + fi.getModesAsString() + "|" + fi.getUid() + "|0|" + fi.getSize() + "|" + fi.getAtime() + "|" + fi.getMtime() + "|" + fi.getCtime() + "|" + fi.getCrtime());
}
/**
* Calls {@link #createStandard(String, String, String[]) createStandard}
* with default arguments
*
* @param args Ignored
*/
public static void main(String[] args) {
if(System.getProperty("os.name").contains("Mac")||System.getProperty("os.name").toLowerCase().contains("unix")){
java.io.File dep = new java.io.File("/usr/local/lib");
boolean deps = false;
for(String chk: dep.list())
{
deps = (deps||chk.toLowerCase().contains("tsk"));
}
if(!deps)
{
System.out.println("Run make install on tsk");
throw new RuntimeException("Run make install on tsk");
}
}
String tempDirPath = System.getProperty("java.io.tmpdir");
tempDirPath = tempDirPath.substring(0, tempDirPath.length() - 1);
java.io.File pth = new java.io.File(DataModelTestSuite.goldStandardPath());
FileFilter testExFilter = new FileFilter() {
@Override
public boolean accept(java.io.File f) {
return f.getName().contains(EX);
}
};
for (java.io.File del : pth.listFiles(testExFilter)) {
del.delete();
}
List<ImgTraverser> tests = DataModelTestSuite.getTests();
List<List<String>> imagePaths = DataModelTestSuite.getImagePaths();
for (List<String> paths : imagePaths) {
for (ImgTraverser tstrn : tests) {
String standardPath = DataModelTestSuite.standardPath(paths, tstrn.getClass().getSimpleName());
System.out.println("Creating " + tstrn.getClass().getSimpleName() + " standard for: " + paths.get(0));
DataModelTestSuite.createStandard(standardPath, tempDirPath, paths, tstrn);
}
String standardPathCPP = DataModelTestSuite.standardPath(paths, CPPtoJavaCompare.class.getSimpleName());
DataModelTestSuite.getTSKData(standardPathCPP, paths);
}
}
/**
* Compares the content of two files to determine if they are equal, if they
* are it removes the file from the results folder
*
* @param original is the first file to be compared
* @param results is the second file to be compared
*/
protected static boolean comparecontent(String original, String results) {
try {
java.io.File fi1 = new java.io.File(original);
java.io.File fi2 = new java.io.File(results);
FileReader f1 = new FileReader(new java.io.File(original).getAbsolutePath());
FileReader f2 = new FileReader(new java.io.File(results).getAbsolutePath());
Scanner in1 = new Scanner(f1);
Scanner in2 = new Scanner(f2);
while (in1.hasNextLine() || in2.hasNextLine()) {
if ((in1.hasNextLine() ^ in2.hasNextLine()) || !(in1.nextLine().equals(in2.nextLine()))) {
in1.close();
in2.close();
f1.close();
f2.close();
runDiff(fi1.getAbsolutePath(), fi2.getAbsolutePath());
return false;
}
}
//DataModelTestSuite.emptyResults(fi2.getParent(), fi2.getName());
return true;
} catch (IOException ex) {
logg.log(Level.SEVERE, "Couldn't compare content", ex);
return false;
}
}
/**
* runs sort on the given file
*
* @param inp
*/
private static void runSort(String inp) {
String outp = sortedFlPth(inp);
String cygpath = getSortPath();
String[] cmd = {cygpath, inp, "-o", outp};
try {
Runtime.getRuntime().exec(cmd).waitFor();
} catch (InterruptedException ex) {
logg.log(Level.SEVERE, "Couldn't create Standard", ex);
throw new RuntimeException(ex);
} catch(IOException ex){
logg.log(Level.SEVERE, "Couldn't create Standard", ex);
throw new RuntimeException(ex);
}
}
/**
* Returns the name of the sorted file
*
* @param path the original name of the file
* @return
*/
protected static String sortedFlPth(String path) {
return path.replace(".txt", "_Sorted.txt");
}
/**
* Runs the Cygwin Diff algorithm on two files, is currently unused
*
* @param path1 is the path to the first file
* @param path2 is the path to the second file
*/
private static void runDiff(String path1, String path2) {
String diffPath = getDiffPath();
String outputLoc = path2.replace(".txt", "_Diff.txt");
String[] cmd = {diffPath, path1, path2};
try {
Process p = Runtime.getRuntime().exec(cmd);
Scanner read = new Scanner(p.getInputStream());
Scanner error1 = new Scanner(p.getErrorStream());
FileWriter out = new FileWriter(outputLoc);
while (read.hasNextLine()) {
String line = read.nextLine();
out.append(line);
out.flush();
out.append("\n");
out.flush();
}
} catch (Exception ex) {
logg.log(Level.SEVERE, "Failed to run Diff program", ex);
}
}
/**
* Returns whether or not a file is an image file
*
* @param name the name of the file
* @return a boolean that is true if the name ends with an image file
* extension
*/
protected static boolean isImgFile(String name) {
return name.endsWith(".001") || name.endsWith(".raw") || name.endsWith(".img") || name.endsWith(".E01") || name.endsWith(".dd");
}
}
| true | true | private static void getTSKData(String standardPath, List<String> img) {
String tsk_loc;
java.io.File up = new java.io.File(System.getProperty("user.dir"));
up = up.getParentFile();
up = up.getParentFile();
if (System.getProperty("os.name").contains("Windows")) {
tsk_loc = up.getAbsolutePath() + "\\win32\\Release\\tsk_gettimes";
} else {
tsk_loc = up.getAbsolutePath() + "/tools/autotools/tsk_gettimes";
}
String[] cmd = {tsk_loc, img.get(0)};
try {
Process p = Runtime.getRuntime().exec(cmd);
Scanner read = new Scanner(p.getInputStream());
Scanner error1 = new Scanner(p.getErrorStream());
FileWriter out = new FileWriter(standardPath);
while (read.hasNextLine()) {
String line = read.nextLine();
line = line.replace(" (deleted)", "");
line = line.replace("(null)", "");
//removes unknown data attached to metaAddr
String[] linecontents = line.split("\\|");
String metaaddrcon = linecontents[2];
String mtad = metaaddrcon.split("\\-")[0];
line = line.replace(metaaddrcon, mtad);
out.append(line);
out.flush();
out.append("\n");
}
runSort(standardPath);
} catch (Exception ex) {
logg.log(Level.SEVERE, "Failed to run CPP program", ex);
}
java.io.File xfile = new java.io.File(standardPath.replace(".txt", DataModelTestSuite.EX + ".txt"));
try {
xfile.createNewFile();
} catch (IOException ex) {
logg.log(Level.SEVERE, "Failed to create exceptions file", ex);
}
}
| private static void getTSKData(String standardPath, List<String> img) {
String tsk_loc;
java.io.File up = new java.io.File(System.getProperty("user.dir"));
up = up.getParentFile();
up = up.getParentFile();
if (System.getProperty("os.name").contains("Windows")) {
tsk_loc = up.getAbsolutePath() + "\\win32\\Release\\tsk_gettimes";
} else {
tsk_loc = up.getAbsolutePath() + "/tools/autotools/tsk_gettimes";
}
String[] cmd = {tsk_loc, img.get(0)};
try {
Process p = Runtime.getRuntime().exec(cmd);
Scanner read = new Scanner(p.getInputStream());
Scanner error1 = new Scanner(p.getErrorStream());
FileWriter out = new FileWriter(standardPath);
while (read.hasNextLine()) {
String line = read.nextLine();
line = line.replace(" (deleted)", "");
line = line.replace("(null)", "");
//removes unknown data attached to metaAddr
String[] linecontents = line.split("\\|");
String metaaddrcon = linecontents[2];
String mtad = metaaddrcon.split("\\-")[0];
line = line.replace(metaaddrcon, mtad);
out.append(line);
out.flush();
out.append("\n");
}
runSort(standardPath);
} catch (Exception ex) {
logg.log(Level.SEVERE, "Failed to run CPP program", ex);
}
java.io.File xfile = new java.io.File(standardPath.replace(".txt", DataModelTestSuite.EX + ".txt"));
try {
xfile.createNewFile();
} catch (IOException ex) {
logg.log(Level.SEVERE, "Failed to create exceptions file", ex);
}
}
|
diff --git a/update/org.eclipse.update.core/src/org/eclipse/update/internal/mirror/MirrorCommand.java b/update/org.eclipse.update.core/src/org/eclipse/update/internal/mirror/MirrorCommand.java
index 1d0d28ae0..99e4a3ffe 100644
--- a/update/org.eclipse.update.core/src/org/eclipse/update/internal/mirror/MirrorCommand.java
+++ b/update/org.eclipse.update.core/src/org/eclipse/update/internal/mirror/MirrorCommand.java
@@ -1,211 +1,211 @@
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.update.internal.mirror;
import java.io.*;
import java.net.*;
import java.util.*;
import org.eclipse.core.runtime.*;
import org.eclipse.update.core.*;
import org.eclipse.update.core.model.*;
import org.eclipse.update.internal.standalone.*;
/**
* Mirrors a remote site locally.
*/
public class MirrorCommand extends ScriptedCommand {
private String featureId;
private String featureVersion;
private String fromSiteUrl;
private String toSiteDir;
private MirrorSite mirrorSite;
public MirrorCommand(
String featureId,
String featureVersion,
String fromSiteUrl,
String toSiteDir) {
this.featureId = featureId;
this.featureVersion = featureVersion;
this.fromSiteUrl = fromSiteUrl;
this.toSiteDir = toSiteDir;
}
/**
* true if success
*/
public boolean run() {
if (!validateParameters()) {
return false;
}
try {
if (getMirrorSite() == null)
return false;
URL remoteSiteUrl = new URL(fromSiteUrl);
ISite remoteSite =
SiteManager.getSite(remoteSiteUrl, new NullProgressMonitor());
ISiteFeatureReference featureReferencesToMirror[] =
findFeaturesToMirror(remoteSite);
if (featureReferencesToMirror.length == 0) {
System.out.println(
"No matching features found on " + remoteSiteUrl + ".");
return false;
}
mirrorSite.mirrorAndExpose(
remoteSite,
featureReferencesToMirror,
null);
System.out.println("Mirror command completed successfully.");
return true;
} catch (MalformedURLException e) {
System.out.println(e);
e.printStackTrace();
return false;
} catch (CoreException ce) {
System.out.println(ce.getMessage());
ce.printStackTrace();
return false;
} finally {
JarContentReference.shutdown();
}
}
private boolean validateParameters() {
if (fromSiteUrl == null && fromSiteUrl.length() <= 0) {
System.out.println("from parameter missing.");
return false;
}
try {
new URL(fromSiteUrl);
} catch (MalformedURLException mue) {
System.out.println("from must be valid URL");
return false;
}
if (toSiteDir == null && toSiteDir.length() <= 0) {
System.out.println("to parameter missing.");
return false;
}
return true;
}
private MirrorSite getMirrorSite()
throws MalformedURLException, CoreException {
// Create mirror site
if (mirrorSite == null) {
if (toSiteDir != null) {
MirrorSiteFactory factory = new MirrorSiteFactory();
System.out.print("Analyzing features already mirrored ...");
try {
mirrorSite =
(MirrorSite) factory.createSite(new File(toSiteDir));
} catch (InvalidSiteTypeException iste) {
}
System.out.println(" Done.");
}
if (mirrorSite == null) {
System.out.println(
"Cannot access site to mirror to: " + toSiteDir);
return null;
}
}
return mirrorSite;
}
/**
* Returns subset of feature references on remote site
* as specified by optional featureId and featureVersion
* parameters
* @param remoteSite
* @return ISiteFeatureReference[]
* @throws CoreException
*/
private ISiteFeatureReference[] findFeaturesToMirror(ISite remoteSite)
throws CoreException {
ISiteFeatureReference remoteSiteFeatureReferences[] =
remoteSite.getRawFeatureReferences();
SiteFeatureReferenceModel existingFeatureModels[] =
mirrorSite.getFeatureReferenceModels();
Collection featureReferencesToMirror = new ArrayList();
PluginVersionIdentifier featureVersionIdentifier = null;
if (featureId == null) {
System.out.println(
"Parameter feature not specified. All features on the remote site will be mirrored.");
}
if (featureVersion == null) {
System.out.println(
"Parameter version not specified. All versions of features on the remote site will be mirrored.");
} else {
featureVersionIdentifier =
new PluginVersionIdentifier(featureVersion);
}
for (int i = 0; i < remoteSiteFeatureReferences.length; i++) {
VersionedIdentifier remoteFeatureVersionedIdentifier =
remoteSiteFeatureReferences[i].getVersionedIdentifier();
if (featureId != null
&& !featureId.equals(
remoteFeatureVersionedIdentifier.getIdentifier())) {
// id does not match
continue;
}
if (featureVersionIdentifier != null
&& !featureVersionIdentifier.isPerfect(
remoteFeatureVersionedIdentifier.getVersion())) {
// version does not match
continue;
}
for (int e = 0; e < existingFeatureModels.length; e++) {
if (existingFeatureModels[e]
.getVersionedIdentifier()
.equals(remoteFeatureVersionedIdentifier)) {
System.out.println(
"Feature "
+ remoteFeatureVersionedIdentifier
+ " already mirrored and exposed.");
// feature already mirrored and exposed in site.xml
continue;
}
}
// Check feature type
String type =
((SiteFeatureReference) remoteSiteFeatureReferences[i])
.getType();
- if (!ISite.DEFAULT_PACKAGED_FEATURE_TYPE.equals(type)) {
+ if (type!=null && !ISite.DEFAULT_PACKAGED_FEATURE_TYPE.equals(type)) {
// unsupported
throw Utilities.newCoreException(
"Feature "
+ remoteFeatureVersionedIdentifier
+ " is of type "
+ type
+ ". Only features of type "
+ ISite.DEFAULT_PACKAGED_FEATURE_TYPE
+ " are supported.",
null);
}
featureReferencesToMirror.add(remoteSiteFeatureReferences[i]);
System.out.println(
"Feature "
+ remoteSiteFeatureReferences[i].getVersionedIdentifier()
+ " will be mirrored.");
}
return (ISiteFeatureReference[]) featureReferencesToMirror.toArray(
new ISiteFeatureReference[featureReferencesToMirror.size()]);
}
}
| true | true | private ISiteFeatureReference[] findFeaturesToMirror(ISite remoteSite)
throws CoreException {
ISiteFeatureReference remoteSiteFeatureReferences[] =
remoteSite.getRawFeatureReferences();
SiteFeatureReferenceModel existingFeatureModels[] =
mirrorSite.getFeatureReferenceModels();
Collection featureReferencesToMirror = new ArrayList();
PluginVersionIdentifier featureVersionIdentifier = null;
if (featureId == null) {
System.out.println(
"Parameter feature not specified. All features on the remote site will be mirrored.");
}
if (featureVersion == null) {
System.out.println(
"Parameter version not specified. All versions of features on the remote site will be mirrored.");
} else {
featureVersionIdentifier =
new PluginVersionIdentifier(featureVersion);
}
for (int i = 0; i < remoteSiteFeatureReferences.length; i++) {
VersionedIdentifier remoteFeatureVersionedIdentifier =
remoteSiteFeatureReferences[i].getVersionedIdentifier();
if (featureId != null
&& !featureId.equals(
remoteFeatureVersionedIdentifier.getIdentifier())) {
// id does not match
continue;
}
if (featureVersionIdentifier != null
&& !featureVersionIdentifier.isPerfect(
remoteFeatureVersionedIdentifier.getVersion())) {
// version does not match
continue;
}
for (int e = 0; e < existingFeatureModels.length; e++) {
if (existingFeatureModels[e]
.getVersionedIdentifier()
.equals(remoteFeatureVersionedIdentifier)) {
System.out.println(
"Feature "
+ remoteFeatureVersionedIdentifier
+ " already mirrored and exposed.");
// feature already mirrored and exposed in site.xml
continue;
}
}
// Check feature type
String type =
((SiteFeatureReference) remoteSiteFeatureReferences[i])
.getType();
if (!ISite.DEFAULT_PACKAGED_FEATURE_TYPE.equals(type)) {
// unsupported
throw Utilities.newCoreException(
"Feature "
+ remoteFeatureVersionedIdentifier
+ " is of type "
+ type
+ ". Only features of type "
+ ISite.DEFAULT_PACKAGED_FEATURE_TYPE
+ " are supported.",
null);
}
featureReferencesToMirror.add(remoteSiteFeatureReferences[i]);
System.out.println(
"Feature "
+ remoteSiteFeatureReferences[i].getVersionedIdentifier()
+ " will be mirrored.");
}
return (ISiteFeatureReference[]) featureReferencesToMirror.toArray(
new ISiteFeatureReference[featureReferencesToMirror.size()]);
}
| private ISiteFeatureReference[] findFeaturesToMirror(ISite remoteSite)
throws CoreException {
ISiteFeatureReference remoteSiteFeatureReferences[] =
remoteSite.getRawFeatureReferences();
SiteFeatureReferenceModel existingFeatureModels[] =
mirrorSite.getFeatureReferenceModels();
Collection featureReferencesToMirror = new ArrayList();
PluginVersionIdentifier featureVersionIdentifier = null;
if (featureId == null) {
System.out.println(
"Parameter feature not specified. All features on the remote site will be mirrored.");
}
if (featureVersion == null) {
System.out.println(
"Parameter version not specified. All versions of features on the remote site will be mirrored.");
} else {
featureVersionIdentifier =
new PluginVersionIdentifier(featureVersion);
}
for (int i = 0; i < remoteSiteFeatureReferences.length; i++) {
VersionedIdentifier remoteFeatureVersionedIdentifier =
remoteSiteFeatureReferences[i].getVersionedIdentifier();
if (featureId != null
&& !featureId.equals(
remoteFeatureVersionedIdentifier.getIdentifier())) {
// id does not match
continue;
}
if (featureVersionIdentifier != null
&& !featureVersionIdentifier.isPerfect(
remoteFeatureVersionedIdentifier.getVersion())) {
// version does not match
continue;
}
for (int e = 0; e < existingFeatureModels.length; e++) {
if (existingFeatureModels[e]
.getVersionedIdentifier()
.equals(remoteFeatureVersionedIdentifier)) {
System.out.println(
"Feature "
+ remoteFeatureVersionedIdentifier
+ " already mirrored and exposed.");
// feature already mirrored and exposed in site.xml
continue;
}
}
// Check feature type
String type =
((SiteFeatureReference) remoteSiteFeatureReferences[i])
.getType();
if (type!=null && !ISite.DEFAULT_PACKAGED_FEATURE_TYPE.equals(type)) {
// unsupported
throw Utilities.newCoreException(
"Feature "
+ remoteFeatureVersionedIdentifier
+ " is of type "
+ type
+ ". Only features of type "
+ ISite.DEFAULT_PACKAGED_FEATURE_TYPE
+ " are supported.",
null);
}
featureReferencesToMirror.add(remoteSiteFeatureReferences[i]);
System.out.println(
"Feature "
+ remoteSiteFeatureReferences[i].getVersionedIdentifier()
+ " will be mirrored.");
}
return (ISiteFeatureReference[]) featureReferencesToMirror.toArray(
new ISiteFeatureReference[featureReferencesToMirror.size()]);
}
|
diff --git a/src/Eye.java b/src/Eye.java
index d46c7ef..486fbf3 100644
--- a/src/Eye.java
+++ b/src/Eye.java
@@ -1,99 +1,100 @@
import processing.core.*;
public class Eye {
/*
* This is a reference to our main class (which extends PApplet)
*
* We need this because in Eclipse all our custom classes are
* separate, whereas the processing IDE treats everything as
* an inner class of the main PApplet
* .
* If we want to use any core processing methods like
* ellipse(), background() etc. we have to have this, and
* call parent.ellipse(), parent.background() etc. to use them
*
*
*/
PApplet parent;
// The location of the eye
int xPos;
int yPos;
// The size of the various bits
float radius;
float radius_pupil;
float radius_glare;
/*
* Eye( PApplet _parent, int _xPos, int _yPos )
*
* Constructor method sets the x and y positions
*/
public Eye( PApplet _parent, int _xPos, int _yPos ){
parent = _parent;
xPos = _xPos;
yPos = _yPos;
// Generate a random value from 30-120 for the radius
setRadius( (int) parent.random(30,120) );
}
/*
* setRadius( int _radius )
*
* Sets the radius of the eye.
* Also updates the radiuses for the
* pupil and the glare appropriately
*/
public void setRadius( float _radius ){
radius = _radius;
radius_pupil = radius/2;
radius_glare = radius_pupil/5;
}
/*
* draw()
*
* Calculates the position of the pupil based on
* the mouse, then draws all the bits of the eye
*/
public void draw(){
// Calculate the X and Y offsets
// from the eye's location ( xPos, yPos )
// to the mouse's location ( mouseX, mouseY )
float dx = parent.mouseX-xPos;
float dy = parent.mouseY-yPos;
// Use these to calculate the angle
float angle = PApplet.atan2(dy,dx);
// Use the angle to calculate the offsets
// from the center to the pupil
- float xOffset = (PApplet.cos(angle)*radius_glare);
- float yOffset = (PApplet.sin(angle)*radius_glare);
+ float offsetRadius = PApplet.min( radius_glare*2, PApplet.dist( xPos, yPos, parent.mouseX, parent.mouseY ) );
+ float xOffset = (PApplet.cos(angle)*offsetRadius);
+ float yOffset = (PApplet.sin(angle)*offsetRadius);
// Draw the main circle in white
parent.fill(255);
parent.ellipse(xPos, yPos,
radius, radius);
// Draw the pupil in black
parent.fill(0);
parent.ellipse( xPos+xOffset, yPos+yOffset,
radius_pupil, radius_pupil);
// Draw the glare in white
parent.fill(255);
parent.ellipse( xPos+xOffset+radius_glare, yPos+yOffset-radius_glare,
radius_glare, radius_glare );
}
}
| true | true | public void draw(){
// Calculate the X and Y offsets
// from the eye's location ( xPos, yPos )
// to the mouse's location ( mouseX, mouseY )
float dx = parent.mouseX-xPos;
float dy = parent.mouseY-yPos;
// Use these to calculate the angle
float angle = PApplet.atan2(dy,dx);
// Use the angle to calculate the offsets
// from the center to the pupil
float xOffset = (PApplet.cos(angle)*radius_glare);
float yOffset = (PApplet.sin(angle)*radius_glare);
// Draw the main circle in white
parent.fill(255);
parent.ellipse(xPos, yPos,
radius, radius);
// Draw the pupil in black
parent.fill(0);
parent.ellipse( xPos+xOffset, yPos+yOffset,
radius_pupil, radius_pupil);
// Draw the glare in white
parent.fill(255);
parent.ellipse( xPos+xOffset+radius_glare, yPos+yOffset-radius_glare,
radius_glare, radius_glare );
}
| public void draw(){
// Calculate the X and Y offsets
// from the eye's location ( xPos, yPos )
// to the mouse's location ( mouseX, mouseY )
float dx = parent.mouseX-xPos;
float dy = parent.mouseY-yPos;
// Use these to calculate the angle
float angle = PApplet.atan2(dy,dx);
// Use the angle to calculate the offsets
// from the center to the pupil
float offsetRadius = PApplet.min( radius_glare*2, PApplet.dist( xPos, yPos, parent.mouseX, parent.mouseY ) );
float xOffset = (PApplet.cos(angle)*offsetRadius);
float yOffset = (PApplet.sin(angle)*offsetRadius);
// Draw the main circle in white
parent.fill(255);
parent.ellipse(xPos, yPos,
radius, radius);
// Draw the pupil in black
parent.fill(0);
parent.ellipse( xPos+xOffset, yPos+yOffset,
radius_pupil, radius_pupil);
// Draw the glare in white
parent.fill(255);
parent.ellipse( xPos+xOffset+radius_glare, yPos+yOffset-radius_glare,
radius_glare, radius_glare );
}
|
diff --git a/service/src/main/java/com/pms/service/service/impl/PurchaseContractServiceImpl.java b/service/src/main/java/com/pms/service/service/impl/PurchaseContractServiceImpl.java
index f79f9f72..130fcb83 100644
--- a/service/src/main/java/com/pms/service/service/impl/PurchaseContractServiceImpl.java
+++ b/service/src/main/java/com/pms/service/service/impl/PurchaseContractServiceImpl.java
@@ -1,1279 +1,1280 @@
package com.pms.service.service.impl;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.pms.service.dbhelper.DBQuery;
import com.pms.service.dbhelper.DBQueryOpertion;
import com.pms.service.exception.ApiResponseException;
import com.pms.service.mockbean.ApiConstants;
import com.pms.service.mockbean.ArrivalNoticeBean;
import com.pms.service.mockbean.CustomerBean;
import com.pms.service.mockbean.DBBean;
import com.pms.service.mockbean.GroupBean;
import com.pms.service.mockbean.InvoiceBean;
import com.pms.service.mockbean.MoneyBean;
import com.pms.service.mockbean.ProjectBean;
import com.pms.service.mockbean.PurchaseBack;
import com.pms.service.mockbean.PurchaseCommonBean;
import com.pms.service.mockbean.PurchaseRequest;
import com.pms.service.mockbean.RoleBean;
import com.pms.service.mockbean.SalesContractBean;
import com.pms.service.mockbean.ShipBean;
import com.pms.service.mockbean.UserBean;
import com.pms.service.service.AbstractService;
import com.pms.service.service.IArrivalNoticeService;
import com.pms.service.service.IPurchaseContractService;
import com.pms.service.service.IPurchaseService;
import com.pms.service.service.ISupplierService;
import com.pms.service.util.ApiUtil;
import com.pms.service.util.DateUtil;
import com.pms.service.util.EmailUtil;
import com.pms.service.util.status.ResponseCodeConstants;
public class PurchaseContractServiceImpl extends AbstractService implements IPurchaseContractService {
private static final String PURCHASE_ORDER_ID = "purchaseOrderId";
private static final String APPROVED = PurchaseRequest.STATUS_APPROVED;
private static final Logger logger = LogManager.getLogger(PurchaseContractServiceImpl.class);
private IPurchaseService backService;
private ISupplierService supplierService;
private IArrivalNoticeService arriveService;
public IArrivalNoticeService getArriveService() {
return arriveService;
}
public void setArriveService(IArrivalNoticeService arriveService) {
this.arriveService = arriveService;
}
public ISupplierService getSupplierService() {
return supplierService;
}
public void setSupplierService(ISupplierService supplierService) {
this.supplierService = supplierService;
}
@Override
public String geValidatorFileName() {
return null;
}
public Map<String, Object> getPurchaseBack(Map<String, Object> parameters){
Map<String, Object> results = backService.loadBack(parameters);
backService.mergeBackRestEqCount(results);
removeEmptyEqList(results, "pbLeftCount");
return results;
}
@Override
public Map<String, Object> listPurchaseContracts(Map<String, Object> parameters) {
mergeMyTaskQuery(parameters, DBBean.PURCHASE_CONTRACT);
Map<String, Object> results = dao.list(parameters, DBBean.PURCHASE_CONTRACT);
supplierService.mergeSupplierInfo(results, "supplier", new String[]{"supplierName"});
return results;
}
//非直发入库中选择项目信息,入库到同方自己的仓库的项目
public Map<String, Object> listProjectsFromApproveContractsForRepositorySelect(Map<String, Object> parameters) {
Map<String, Object> query = new HashMap<String, Object>();
query.put(PurchaseCommonBean.PROCESS_STATUS, PurchaseCommonBean.STATUS_APPROVED);
if (parameters.get("type") != null && parameters.get("type") .toString().equalsIgnoreCase("out")) {
query.put("eqcostDeliveryType", PurchaseCommonBean.EQCOST_DELIVERY_TYPE_DIRECTY);
} else {
query.put("eqcostDeliveryType", PurchaseCommonBean.EQCOST_DELIVERY_TYPE_REPOSITORY);
}
query.put(ApiConstants.LIMIT_KEYS, new String[] { "eqcostList.projectId", "supplier" });
Map<String, Object> results = dao.list(query, DBBean.PURCHASE_CONTRACT);
List<Map<String, Object>> contractList = (List<Map<String, Object>>) results.get(ApiConstants.RESULTS_DATA);
Set<String> projectIds = new HashSet<String>();
Map<String, Set<String>> projectSupplierMap = new HashMap<String, Set<String>>();
for (Map<String, Object> contract : contractList) {
List<Map<String, Object>> eqCostList = (List<Map<String, Object>>) contract.get("eqcostList");
for (Map<String, Object> p : eqCostList) {
String projectId = p.get("projectId").toString();
projectIds.add(projectId);
if (projectSupplierMap.get(projectId) == null) {
projectSupplierMap.put(projectId, new HashSet<String>());
}
projectSupplierMap.get(projectId).add(contract.get("supplier").toString());
}
}
Map<String, Object> projectQuery = new HashMap<String, Object>();
projectQuery.put(ApiConstants.MONGO_ID, new DBQuery(DBQueryOpertion.IN, projectIds));
projectQuery.put(ApiConstants.LIMIT_KEYS, ProjectBean.PROJECT_NAME);
Map<String, Object> projects = this.dao.list(projectQuery, DBBean.PROJECT);
List<Map<String, Object>> projectList = (List<Map<String, Object>>) projects.get(ApiConstants.RESULTS_DATA);
for (Map<String, Object> project : projectList) {
String id = project.get(ApiConstants.MONGO_ID).toString();
Set<String> suppliers = projectSupplierMap.get(id);
List<Map<String, Object>> suppliersMap = new ArrayList<Map<String, Object>>();
for (String supplierId : suppliers) {
Map<String, Object> supp = new HashMap<String, Object>();
supp.put(ApiConstants.MONGO_ID, supplierId);
suppliersMap.add(supp);
}
Map<String, Object> supplierMap = new HashMap<String, Object>();
supplierMap.put(ApiConstants.RESULTS_DATA, suppliersMap);
supplierService.mergeSupplierInfo(supplierMap, ApiConstants.MONGO_ID, new String[] { "supplierName" });
project.put("suppliers", supplierMap.get(ApiConstants.RESULTS_DATA));
}
return projects;
}
public Map<String, Object> listSalesContractsForShipSelect(Map<String, Object> params) {
Map<String, Object> query = new HashMap<String, Object>();
// query.put(PurchaseCommonBean.PROCESS_STATUS, PurchaseCommonBean.STATUS_OUT_REPOSITORY);
query.put(ApiConstants.LIMIT_KEYS, new String[] { "eqcostList.scId", "eqcostList.projectId" });
Set<Object> scIdsList = new HashSet();
String type = (String)params.get("type");
if("1".equalsIgnoreCase(type)){
query.put("type", "in");
}else{
query.put("type", "out");
}
List<Object> scResults = this.dao.listLimitKeyValues(query, DBBean.REPOSITORY);
// 2个LIMIT_KEYS字段以上是返回的list中的对象是MAP
for (Object sc : scResults) {
Map<String, Object> scMap = (Map<String, Object>) sc;
List<Map<String, Object>> list = (List<Map<String, Object>>) scMap.get(SalesContractBean.SC_EQ_LIST);
for (Map<String, Object> eqsc : list) {
scIdsList.add(eqsc.get(SalesContractBean.SC_ID));
}
}
Map<String, Object> scQuery = new HashMap<String, Object>();
scQuery.put(ApiConstants.MONGO_ID, new DBQuery(DBQueryOpertion.IN, new ArrayList<Object>(scIdsList)));
scQuery.put(ApiConstants.LIMIT_KEYS, new String[] { SalesContractBean.SC_CODE, SalesContractBean.SC_PROJECT_ID, SalesContractBean.SC_TYPE });
Map<String, Object> scList = this.dao.list(scQuery, DBBean.SALES_CONTRACT);
Map<String, Object> customers = this.dao.listToOneMapAndIdAsKey(null, DBBean.CUSTOMER);
Map<String, Object> projects = this.dao.listToOneMapAndIdAsKey(null, DBBean.PROJECT);
List<Map<String, Object>> scListItems = (List<Map<String, Object>>) scList.get(ApiConstants.RESULTS_DATA);
for (Map<String, Object> scMap : scListItems) {
Map<String, Object> project = (Map<String, Object>) projects.get(scMap.get(SalesContractBean.SC_PROJECT_ID));
scMap.put(ProjectBean.PROJECT_NAME, project.get(ProjectBean.PROJECT_NAME));
scMap.put(SalesContractBean.SC_PROJECT_ID, project.get(ApiConstants.MONGO_ID));
Map<String, Object> customer = (Map<String, Object>) customers.get(project.get(ProjectBean.PROJECT_CUSTOMER));
scMap.put("customerName", customer.get(CustomerBean.NAME));
scMap.put(SalesContractBean.SC_CUSTOMER_ID, project.get(ProjectBean.PROJECT_CUSTOMER));
}
return scList;
}
//非直发入库
public Map<String, Object> listContractsByProjectAndSupplier(Map<String, Object> params) {
Map<String, Object> query = new HashMap<String, Object>();
Object projectId = params.get("projectId");
query.put("eqcostList.projectId", projectId);
query.put("supplier", params.get("supplier"));
if (params.get("type") != null && params.get("type") .toString().equalsIgnoreCase("out")) {
query.put("eqcostDeliveryType", PurchaseCommonBean.EQCOST_DELIVERY_TYPE_DIRECTY);
}else{
query.put("eqcostDeliveryType", PurchaseCommonBean.EQCOST_DELIVERY_TYPE_REPOSITORY);
params.put("type", "in");
}
query.put(PurchaseCommonBean.PROCESS_STATUS, PurchaseCommonBean.STATUS_APPROVED);
Map<String, Object> results = this.dao.list(query, DBBean.PURCHASE_CONTRACT);
List<Map<String, Object>> list = (List<Map<String, Object>>) results.get(ApiConstants.RESULTS_DATA);
List<Map<String, Object>> eqclist = new ArrayList<Map<String, Object>>();
for (Map<String, Object> data : list) {
List<Map<String, Object>> pList = (List<Map<String, Object>>) data.get("eqcostList");
for (Map<String, Object> p : pList) {
if (p.get("projectId").equals(projectId)) {
eqclist.add(p);
}
}
}
Map<String, Object> requery = new HashMap<String, Object>();
requery.put(SalesContractBean.SC_PROJECT_ID, projectId);
requery.put("supplierId", params.get("supplier"));
requery.put("type", params.get("type"));
Map<String, Integer> eqCountMap = countEqByKey(requery, DBBean.REPOSITORY, "eqcostApplyAmount", null);
Map<String, Object> lresult = new HashMap<String, Object>();
lresult.put("data", scs.mergeEqListBasicInfo(eqclist));
List<Map<String, Object>> eqBackMapList = (List<Map<String, Object>>) lresult.get("data");
for (Map<String, Object> eqMap : eqBackMapList) {
int prCount = 0;
if (eqMap.get("eqcostApplyAmount") != null) {
prCount = ApiUtil.getInteger(eqMap.get("eqcostApplyAmount"), 0);
}
if (eqCountMap.get(eqMap.get(ApiConstants.MONGO_ID)) != null) {
eqMap.put("leftCount", prCount - eqCountMap.get(eqMap.get(ApiConstants.MONGO_ID)));
eqMap.put("eqcostApplyAmount", prCount - eqCountMap.get(eqMap.get(ApiConstants.MONGO_ID)));
} else {
eqMap.put("leftCount", prCount);
eqMap.put("eqcostApplyAmount", prCount);
}
}
return lresult;
}
public List<Map<String, Object>> listApprovedPurchaseContractCosts(String salesContractId) {
Map<String, Object> query = new HashMap<String, Object>();
query.put("eqcostList.scId", salesContractId);
query.put(PurchaseCommonBean.PROCESS_STATUS, PurchaseCommonBean.STATUS_APPROVED);
query.put(ApiConstants.LIMIT_KEYS, new String[] { SalesContractBean.SC_EQ_LIST });
Map<String, Object> results = this.dao.list(query, DBBean.PURCHASE_CONTRACT);
List<Map<String, Object>> list = (List<Map<String, Object>>) results.get(ApiConstants.RESULTS_DATA);
List<Map<String, Object>> eqclist = new ArrayList<Map<String, Object>>();
if (list != null) {
for (Map<String, Object> data : list) {
List<Map<String, Object>> pList = (List<Map<String, Object>>) data.get("eqcostList");
for (Map<String, Object> p : pList) {
if (p.get("scId").equals(salesContractId)) {
eqclist.add(p);
}
}
}
}
return scs.mergeEqListBasicInfo(eqclist);
}
public Map<String, Object> getPurchaseContract(Map<String, Object> parameters) {
Map<String, Object> result = this.dao.findOne(ApiConstants.MONGO_ID, parameters.get(ApiConstants.MONGO_ID), DBBean.PURCHASE_CONTRACT);
result.put(SalesContractBean.SC_EQ_LIST, scs.mergeEqListBasicInfo(result.get(SalesContractBean.SC_EQ_LIST)));
return result;
}
@Override
public void deletePurchaseContract(Map<String, Object> contract) {
List<String> ids = new ArrayList<String>();
ids.add(contract.get(ApiConstants.MONGO_ID).toString());
dao.deleteByIds(ids, DBBean.PURCHASE_CONTRACT);
}
@Override
public Map<String, Object> updatePurchaseContract(Map<String, Object> contract) {
Object eqList = contract.get(SalesContractBean.SC_EQ_LIST);
String keys[] = new String[] { "eqcostApplyAmount", "orderEqcostCode", "orderEqcostName", "orderEqcostModel", "eqcostProductUnitPrice", "purchaseOrderCode",
"salesContractCode", PURCHASE_ORDER_ID, "logisticsType", "logisticsArrivedTime", "logisticsStatus" };
contract.put(SalesContractBean.SC_EQ_LIST, mergeSavedEqList(keys, eqList));
return updatePurchase(contract, DBBean.PURCHASE_CONTRACT);
}
@Override
public Map<String, Object> listPurchaseOrders(Map<String, Object> parameters) {
mergeDataRoleQuery(parameters);
mergeMyTaskQuery(parameters, DBBean.PURCHASE_ORDER);
Map<String, Object> results = dao.list(parameters, DBBean.PURCHASE_ORDER);
List<Map<String, Object>> list = (List<Map<String, Object>>) results.get(ApiConstants.RESULTS_DATA);
for (Map<String, Object> data : list) {
mergeProjectInfo(data);
}
return results;
}
public Map<String, Object> listApprovedPurchaseOrderForSelect() {
Map<String, Object> query = new HashMap<String, Object>();
query.put(PurchaseCommonBean.EQCOST_DELIVERY_TYPE, PurchaseCommonBean.EQCOST_DELIVERY_TYPE_DIRECTY);
Map<String, Object> directOrders = listOrdersForSelect(query);
Map<String, Object> repOrders = listApprovedPurchaseOrderForRepositorySelect();
Map<String, Object> resutls = new HashMap<String ,Object>();
resutls.put("directly", directOrders.get(ApiConstants.RESULTS_DATA));
resutls.put("repository", repOrders.get(ApiConstants.RESULTS_DATA));
return resutls;
}
private Map<String, Object> listOrdersForSelect(Map<String, Object> query) {
query.put(PurchaseRequest.PROCESS_STATUS, new DBQuery(DBQueryOpertion.IN, new String[]{PurchaseCommonBean.STATUS_SUBMITED, PurchaseCommonBean.STATUS_ORDERING}));
Map<String, Object> results = dao.list(query, DBBean.PURCHASE_ORDER);
List<Map<String, Object>> list = (List<Map<String, Object>>) results.get(ApiConstants.RESULTS_DATA);
for (Map<String, Object> data : list) {
mergeOrderRestEqCount(data);
}
List<Map<String, Object>> removedList = new ArrayList<Map<String, Object>>();
for (Map<String, Object> data : list) {
if(data.get("isEqEmpty")!=null){
removedList.add(data);
}
}
for (Map<String, Object> orderMap : removedList) {
list.remove(orderMap);
}
for (Map<String, Object> data : list) {
data.put(SalesContractBean.SC_EQ_LIST, scs.mergeEqListBasicInfo(data.get(SalesContractBean.SC_EQ_LIST)));
}
return results;
}
public Map<String, Object> listApprovedPurchaseOrderForRepositorySelect(){
Map<String, Object> query = new HashMap<String, Object>();
query.put(PurchaseCommonBean.EQCOST_DELIVERY_TYPE, PurchaseCommonBean.EQCOST_DELIVERY_TYPE_REPOSITORY);
return listOrdersForSelect(query);
}
public Map<String, Object> mergeOrderRestEqCount(Map<String, Object> order) {
if (order.get(SalesContractBean.SC_EQ_LIST) == null) {
order = dao.findOne(ApiConstants.MONGO_ID, order.get(ApiConstants.MONGO_ID), DBBean.PURCHASE_ORDER);
}
List<Map<String, Object>> eqOrderMapList = (List<Map<String, Object>>) order.get(SalesContractBean.SC_EQ_LIST);
Map<String, Object> orderQuery = new HashMap<String, Object>();
orderQuery.put(ApiConstants.MONGO_ID, order.get(ApiConstants.MONGO_ID));
//订单下总数集合
Map<String, Integer> orderEqCountMap = countEqByKey(orderQuery, DBBean.PURCHASE_ORDER, "eqcostApplyAmount", null);
Map<String, Object> eqQuery = new HashMap<String, Object>();
eqQuery.put("eqcostList.purchaseOrderId", new DBQuery(DBQueryOpertion.IN, order.get(ApiConstants.MONGO_ID)));
//只统计此订单下的同样的设备清单
Map<String, Object> compareMap = new HashMap<String, Object>();
compareMap.put("purchaseOrderId", order.get(ApiConstants.MONGO_ID));
Map<String, Integer> contractCountMap = countEqByKey(eqQuery, DBBean.PURCHASE_CONTRACT, "eqcostApplyAmount", null, compareMap);
//过滤掉申请小于等于0的订单
//TODO: 也许需要支持采购合同里面可以编辑每次采购多少
List<Map<String, Object>> removedList = new ArrayList<Map<String, Object>>();
for (String key : orderEqCountMap.keySet()) {
if (contractCountMap.get(key) != null && contractCountMap.get(key) >= orderEqCountMap.get(key)) {
for (Map<String, Object> eqMap : eqOrderMapList) {
if (eqMap.get(ApiConstants.MONGO_ID).equals(key)) {
removedList.add(eqMap);
break;
}
}
}
}
for (Map<String, Object> eqMap : removedList) {
eqOrderMapList.remove(eqMap);
}
if(eqOrderMapList.isEmpty()){
order.put("isEqEmpty", eqOrderMapList.isEmpty());
}
return order;
}
@Override
public void deletePurchaseOrder(Map<String, Object> contract) {
List<String> ids = new ArrayList<String>();
ids.add(contract.get(ApiConstants.MONGO_ID).toString());
dao.deleteByIds(ids, DBBean.PURCHASE_ORDER);
}
@Override
public Map<String, Object> updatePurchaseOrder(Map<String, Object> parameters) {
PurchaseRequest request = (PurchaseRequest) new PurchaseRequest().toEntity(parameters);
Object eqList = parameters.get(SalesContractBean.SC_EQ_LIST);
if (ApiUtil.isEmpty(parameters.get(ApiConstants.MONGO_ID))) {
if (request.getStatus() == null) {
request.setStatus(PurchaseRequest.STATUS_DRAFT);
}
request.setApprovedDate(null);
request.setPurchaseOrderCode(generateCode("CGDD", DBBean.PURCHASE_ORDER));
parameters = request.toMap();
}
String keys[] = new String[] { "eqcostApplyAmount", "orderEqcostCode", "orderEqcostName", "orderEqcostModel", "eqcostProductUnitPrice" };
List<Map<String, Object>> mergeSavedEqList = mergeSavedEqList(keys, eqList);
parameters.put(SalesContractBean.SC_EQ_LIST, mergeSavedEqList);
Map<String, Object> order = updatePurchase(parameters, DBBean.PURCHASE_ORDER);
//发采购订单后 采购申请状态为采购中
Map<String, Object> prequest = this.dao.findOne(ApiConstants.MONGO_ID, order.get(PurchaseCommonBean.PURCHASE_REQUEST_ID),
new String[] { PurchaseCommonBean.PURCHASE_ORDER_ID, SalesContractBean.SC_EQ_LIST }, DBBean.PURCHASE_REQUEST);
if (prequest != null) {
prequest.put(PurchaseCommonBean.PURCHASE_ORDER_ID, order.get(ApiConstants.MONGO_ID));
prequest.put(PurchaseCommonBean.PURCHASE_ORDER_CODE, order.get(PurchaseCommonBean.PURCHASE_ORDER_CODE));
prequest.put(PurchaseCommonBean.PROCESS_STATUS, PurchaseCommonBean.STATUS_ORDERING);
this.dao.updateById(prequest, DBBean.PURCHASE_REQUEST);
}
return order;
}
private List<Map<String, Object>> mergeSavedEqList(String keys[], Object eqList) {
List<String> finalKeys = new ArrayList<String>();
for (String key : keys) {
finalKeys.add(key);
}
finalKeys.add(ApiConstants.MONGO_ID);
finalKeys.add(SalesContractBean.SC_ID);
finalKeys.add(SalesContractBean.SC_PROJECT_ID);
finalKeys.add("eqcostBrand");
finalKeys.add("remark");
List<Map<String, Object>> orgin = (List<Map<String, Object>>) eqList;
List<Map<String, Object>> maps = new ArrayList<Map<String, Object>>();
for (Map<String, Object> old : orgin) {
Map<String, Object> neq = new HashMap<String, Object>();
for (String key : finalKeys) {
neq.put(key, old.get(key));
}
maps.add(neq);
}
return maps;
}
public Map<String, Object> getPurchaseOrder(Map<String, Object> parameters) {
Map<String, Object> result = this.dao.findOne(ApiConstants.MONGO_ID, parameters.get(ApiConstants.MONGO_ID), DBBean.PURCHASE_ORDER);
List<Map<String, Object>> mergeLoadedEqList = scs.mergeEqListBasicInfo(result.get(SalesContractBean.SC_EQ_LIST));
result.put(SalesContractBean.SC_EQ_LIST, mergeLoadedEqList);
mergeProjectInfo(result);
Map<String, Object> purchaseRequest = this.dao.findOne(ApiConstants.MONGO_ID, result.get(PurchaseCommonBean.PURCHASE_REQUEST_ID), new String[]{SalesContractBean.SC_EQ_LIST}, DBBean.PURCHASE_REQUEST);
List<Map<String, Object>> prEqList = (List<Map<String, Object>>) purchaseRequest.get(SalesContractBean.SC_EQ_LIST);
for (Map<String, Object> orderEq : mergeLoadedEqList) {
for (Map<String, Object> prEq : prEqList) {
if (prEq.get(ApiConstants.MONGO_ID).equals(orderEq.get(ApiConstants.MONGO_ID))) {
orderEq.put("orderRequestCount", prEq.get(PurchaseCommonBean.EQCOST_APPLY_AMOUNT));
break;
}
}
}
return result;
}
public Map<String, Object> approvePurchaseContract(Map<String, Object> order) {
Map<String, Object> result = processRequest(order, DBBean.PURCHASE_CONTRACT, APPROVED);
Map<String, Object> contract = dao.findOne(ApiConstants.MONGO_ID, result.get(ApiConstants.MONGO_ID), new String[] { SalesContractBean.SC_EQ_LIST,
PurchaseCommonBean.PURCHASE_CONTRACT_TYPE, PurchaseCommonBean.PURCHASE_CONTRACT_CODE, PurchaseCommonBean.CONTRACT_EXECUTE_CATE, PurchaseCommonBean.PURCHASE_CONTRACT_CODE,
PurchaseCommonBean.EQCOST_DELIVERY_TYPE }, DBBean.PURCHASE_CONTRACT);
updateOrderFinalStatus(contract);
Map<String, Object> userQuery = new HashMap<String, Object>();
userQuery.put(UserBean.GROUPS,
new DBQuery(DBQueryOpertion.IN, this.dao.findOne(GroupBean.GROUP_NAME, GroupBean.DEPARTMENT_ASSISTANT_VALUE, DBBean.USER_GROUP).get(ApiConstants.MONGO_ID)));
userQuery.put(ApiConstants.LIMIT_KEYS, UserBean.EMAIL);
List<Object> emails = this.dao.listLimitKeyValues(userQuery, DBBean.USER);
if (contract.get(PurchaseCommonBean.CONTRACT_EXECUTE_CATE) != null) {
if (contract.get(PurchaseCommonBean.CONTRACT_EXECUTE_CATE).equals(PurchaseCommonBean.CONTRACT_EXECUTE_CATE_BEIJINGDAICAI)) {
String subject = String.format("采购合同 - %s -审批通过", contract.get(PurchaseCommonBean.PURCHASE_CONTRACT_CODE));
String content = String.format("采购合同 - %s -已审批通过, 附件为审批通过的设备清单,请到系统做入库处理", contract.get(PurchaseCommonBean.PURCHASE_CONTRACT_CODE));
EmailUtil.sendEqListEmails(subject, emails, content, contract.get(SalesContractBean.SC_EQ_LIST));
}else if (contract.get(PurchaseCommonBean.CONTRACT_EXECUTE_CATE).equals(PurchaseCommonBean.CONTRACT_EXECUTE_BJ_REPO)) {
createArriveNotice(contract);
createAutoShip(contract);
String subject = String.format("采购合同 - %s -审批通过", contract.get(PurchaseCommonBean.PURCHASE_CONTRACT_CODE));
String content = String.format("采购合同 - %s -已审批通过, 附件为审批通过的设备清单, 系统已经自动生成发货通知,请填写完整信息后发货", contract.get(PurchaseCommonBean.PURCHASE_CONTRACT_CODE));
EmailUtil.sendEqListEmails(subject, emails, content, contract.get(SalesContractBean.SC_EQ_LIST));
}else if (contract.get(PurchaseCommonBean.CONTRACT_EXECUTE_CATE).equals(PurchaseCommonBean.CONTRACT_EXECUTE_BJ_MAKE)) {
String subject = String.format("采购合同 - %s -审批通过", contract.get(PurchaseCommonBean.PURCHASE_CONTRACT_CODE));
String content = String.format("采购合同 - %s -已审批通过, 附件为审批通过的设备清单, 请到系统填写到货通知", contract.get(PurchaseCommonBean.PURCHASE_CONTRACT_CODE));
EmailUtil.sendEqListEmails(subject, emails, content, contract.get(SalesContractBean.SC_EQ_LIST));
}
}
return result;
}
private void updateOrderFinalStatus(Map<String, Object> contract) {
List<Map<String, Object>> eqListMap = (List<Map<String, Object>>)contract.get(SalesContractBean.SC_EQ_LIST);
Set<String> orderIds = new HashSet<String>();
// 批准后更新订单状态
for (Map<String, Object> eqMap : eqListMap) {
String orderId = eqMap.get(PURCHASE_ORDER_ID).toString();
orderIds.add(orderId);
eqMap.put(PurchaseCommonBean.EQCOST_DELIVERY_TYPE, contract.get(PurchaseCommonBean.EQCOST_DELIVERY_TYPE));
eqMap.put(PurchaseCommonBean.PURCHASE_CONTRACT_ID, contract.get(ApiConstants.MONGO_ID));
eqMap.put(PurchaseCommonBean.PURCHASE_CONTRACT_CODE, contract.get(PurchaseCommonBean.PURCHASE_CONTRACT_CODE));
eqMap.put(PurchaseCommonBean.PURCHASE_CONTRACT_TYPE, contract.get(PurchaseCommonBean.PURCHASE_CONTRACT_TYPE));
+ eqMap.put(PurchaseCommonBean.CONTRACT_EXECUTE_CATE, contract.get(PurchaseCommonBean.CONTRACT_EXECUTE_CATE));
}
this.dao.updateById(contract, DBBean.PURCHASE_CONTRACT);
Map<String, Object> query = new HashMap<String, Object>();
query.put(SalesContractBean.SC_EQ_LIST + "." + PURCHASE_ORDER_ID, new DBQuery(DBQueryOpertion.IN, new ArrayList<String>(orderIds)));
query.put(PurchaseCommonBean.PROCESS_STATUS, new DBQuery(DBQueryOpertion.IN, new String[] { PurchaseCommonBean.STATUS_APPROVED }));
Map<String, Integer> eqCountMap = countEqByKey(query, DBBean.PURCHASE_CONTRACT, "eqcostApplyAmount", null);
for (String orderId : orderIds) {
int count = 0;
Map<String, Object> orderQuery = new HashMap<String, Object>();
orderQuery.put(ApiConstants.MONGO_ID, orderId);
orderQuery.put(ApiConstants.LIMIT_KEYS, new String[]{SalesContractBean.SC_EQ_LIST, PurchaseCommonBean.EQCOST_DELIVERY_TYPE});
// 最外层就一个数组, 数组下面才是设备清单
Map<String, Object> orderMap = this.dao.findOneByQuery(orderQuery, DBBean.PURCHASE_ORDER);
if (orderMap != null) {
List<Map<String, Object>> orderEqlistMap = (List<Map<String, Object>>) orderMap.get(SalesContractBean.SC_EQ_LIST);
for (Map<String, Object> eqOrderMap : orderEqlistMap) {
int orderCount = ApiUtil.getInteger(eqOrderMap.get("eqcostApplyAmount"), 0);
int countractCount = ApiUtil.getInteger(eqCountMap.get(eqOrderMap.get(ApiConstants.MONGO_ID)), 0);
if (countractCount >= orderCount) {
count++;
}
if(eqCountMap.get(eqOrderMap.get(ApiConstants.MONGO_ID))!=null){
//合并货物递送方式和订单等等信息到设备清单
eqOrderMap.put(PurchaseCommonBean.EQCOST_DELIVERY_TYPE, orderMap.get(PurchaseCommonBean.EQCOST_DELIVERY_TYPE));
eqOrderMap.put(PurchaseCommonBean.PURCHASE_ORDER_ID, orderMap.get(ApiConstants.MONGO_ID));
eqOrderMap.put(PurchaseCommonBean.PURCHASE_ORDER_CODE, orderMap.get(PurchaseCommonBean.PURCHASE_ORDER_CODE));
eqOrderMap.put(PurchaseCommonBean.PURCHASE_REQUEST_ID, orderMap.get(PurchaseCommonBean.PURCHASE_REQUEST_ID));
eqOrderMap.put(PurchaseCommonBean.PURCHASE_REQUEST_CODE, orderMap.get(PurchaseCommonBean.PURCHASE_REQUEST_CODE));
eqOrderMap.put(PurchaseCommonBean.PURCHASE_CONTRACT_ID, contract.get(ApiConstants.MONGO_ID));
eqOrderMap.put(PurchaseCommonBean.PURCHASE_CONTRACT_CODE, contract.get(PurchaseCommonBean.PURCHASE_CONTRACT_CODE));
eqOrderMap.put(PurchaseCommonBean.PURCHASE_CONTRACT_TYPE, contract.get(PurchaseCommonBean.PURCHASE_CONTRACT_TYPE));
}
}
orderMap.put(SalesContractBean.SC_EQ_LIST, orderEqlistMap);
updatePurchase(orderMap, DBBean.PURCHASE_ORDER);
if (count == orderEqlistMap.size()) {
Map<String, Object> ordeUpdate = new HashMap<String, Object>();
ordeUpdate.put(ApiConstants.MONGO_ID, orderId);
ordeUpdate.put(PurchaseCommonBean.PROCESS_STATUS, PurchaseCommonBean.STATUS_ORDER_FINISHED);
this.dao.updateById(ordeUpdate, DBBean.PURCHASE_ORDER);
Map<String, Object> order = this.dao.findOne(ApiConstants.MONGO_ID, orderId, new String[] { PurchaseCommonBean.PURCHASE_REQUEST_ID, PurchaseCommonBean.PURCHASE_ORDER_CODE }, DBBean.PURCHASE_ORDER);
if (order != null && order.get(PurchaseCommonBean.PURCHASE_REQUEST_ID) != null) {
Map<String, Object> purRequest = new HashMap<String, Object>();
purRequest.put(ApiConstants.MONGO_ID, order.get(PurchaseCommonBean.PURCHASE_REQUEST_ID));
purRequest.put(PurchaseCommonBean.PROCESS_STATUS, PurchaseCommonBean.STATUS_ORDER_FINISHED);
this.dao.updateById(ordeUpdate, DBBean.PURCHASE_REQUEST);
}
} else {
Map<String, Object> ordeUpdate = new HashMap<String, Object>();
ordeUpdate.put(ApiConstants.MONGO_ID, orderId);
ordeUpdate.put(PurchaseCommonBean.PROCESS_STATUS, PurchaseCommonBean.STATUS_ORDERING);
this.dao.updateById(ordeUpdate, DBBean.PURCHASE_ORDER);
}
}
}
}
public Map<String, Object> processRequest(Map<String, Object> request, String db, String status) {
Map<String, Object> cc = dao.findOne(ApiConstants.MONGO_ID, request.get(ApiConstants.MONGO_ID), db);
request.put(ApiConstants.MONGO_ID, cc.get(ApiConstants.MONGO_ID));
request.put(PurchaseRequest.PROCESS_STATUS, status);
request.put(PurchaseRequest.APPROVED_DATE, ApiUtil.formateDate(new Date(), "yyy-MM-dd"));
return dao.updateById(request, db);
}
public Map<String, Object> rejectPurchaseContract(Map<String, Object> order) {
return processRequest(order, DBBean.PURCHASE_CONTRACT, PurchaseRequest.STATUS_REJECTED);
}
public void approvePurchaseOrder(Map<String, Object> order) {
// 此批准只批准中止申请
processRequest(order, DBBean.PURCHASE_ORDER, PurchaseRequest.STATUS_CANCELLED);
Map<String, Object> request = this.dao.findOne(ApiConstants.MONGO_ID, order.get(ApiConstants.MONGO_ID), new String[] { "purchaseRequestId" }, DBBean.PURCHASE_ORDER);
if (request.get("purchaseRequestId") != null) {
request.put(ApiConstants.MONGO_ID, request.get("purchaseRequestId"));
cancelPurchaseRequest(request);
approvePurchaseRequest(request);
}
}
public Map<String, Object> rejectPurchaseOrder(Map<String, Object> order) {
return processRequest(order, DBBean.PURCHASE_ORDER, PurchaseRequest.STATUS_REJECTED);
}
public Map<String, Object> cancelPurchaseOrder(Map<String, Object> request){
return processRequest(request, DBBean.PURCHASE_ORDER, PurchaseRequest.STATUS_CANCELL_NEED_APPROVED);
}
/**
*
* 选择已批准的备货申请,返回_id, pbCode, scCode 字段
*
*/
public Map<String, Object> listBackRequestForSelect() {
Map<String, Object> query = new HashMap<String, Object>();
// query.put(PurchaseBack.pbStatus, PurchaseStatus.approved.toString());
query.put(ApiConstants.LIMIT_KEYS, new String[] { PurchaseBack.pbCode, PurchaseBack.scCode });
return dao.list(query, DBBean.PURCHASE_BACK);
}
public Map<String, Object> listPurchaseRequests(Map<String, Object> params) {
mergeRefSearchQuery(params, "projectManager", "projectManager", UserBean.USER_NAME, DBBean.USER);
mergeRefSearchQuery(params, SalesContractBean.SC_PROJECT_ID, ProjectBean.PROJECT_NAME, ProjectBean.PROJECT_NAME, DBBean.PROJECT);
if (params.get("approvePage") != null) {
params.remove("approvePage");
params.put(PurchaseRequest.PROCESS_STATUS, new DBQuery(DBQueryOpertion.NOT_IN, new String[] { PurchaseRequest.STATUS_DRAFT, PurchaseRequest.STATUS_CANCELLED }));
}
mergeMyTaskQuery(params, DBBean.PURCHASE_REQUEST);
mergeDataRoleQuery(params);
Map<String, Object> results = dao.list(params, DBBean.PURCHASE_REQUEST);
List<Map<String, Object>> list = (List<Map<String, Object>>) results.get(ApiConstants.RESULTS_DATA);
for (Map<String, Object> data : list) {
mergeProjectInfo(data);
}
return results;
}
public void mergeProjectInfo(Map<String, Object> params) {
// FIXME: code refine
PurchaseCommonBean request = (PurchaseCommonBean) new PurchaseCommonBean().toEntity(params);
Map<String, Object> project = dao.findOne(ApiConstants.MONGO_ID, request.getProjectId(), DBBean.PROJECT);
if (project != null) {
Map<String, Object> pmQuery = new HashMap<String, Object>();
pmQuery.put(ApiConstants.LIMIT_KEYS, new String[] { UserBean.USER_NAME });
pmQuery.put(ApiConstants.MONGO_ID, project.get(ProjectBean.PROJECT_MANAGER));
Map<String, Object> pmData = dao.findOneByQuery(pmQuery, DBBean.USER);
if(pmData!=null){
project.put(ProjectBean.PROJECT_MANAGER, pmData.get(UserBean.USER_NAME));
}
String cId = (String) project.get(ProjectBean.PROJECT_CUSTOMER);
Map<String, Object> customerQuery = new HashMap<String, Object>();
customerQuery.put(ApiConstants.LIMIT_KEYS, new String[] { CustomerBean.NAME });
customerQuery.put(ApiConstants.MONGO_ID, cId);
Map<String, Object> customerData = dao.findOneByQuery(customerQuery, DBBean.CUSTOMER);
project.put(ProjectBean.PROJECT_CUSTOMER, customerData.get(CustomerBean.NAME));
params.put("customerName", project.get(ProjectBean.PROJECT_CUSTOMER));
params.put("projectName", project.get("projectName"));
params.put("projectManager", project.get("projectManager"));
params.put("projectCode", project.get(ProjectBean.PROJECT_CODE));
}
}
public Map<String, Object> listApprovedPurchaseRequestForSelect() {
Map<String, Object> query = new HashMap<String, Object>();
query.put(PurchaseCommonBean.PROCESS_STATUS, APPROVED);
query.put(PurchaseCommonBean.PURCHASE_ORDER_ID, null);
query.put(ApiConstants.LIMIT_KEYS, new String[] { "purchaseRequestCode" });
return dao.list(query, DBBean.PURCHASE_REQUEST);
}
public Map<String, Object> updatePurchaseRequest(Map<String, Object> parameters) {
PurchaseRequest request = (PurchaseRequest) new PurchaseRequest().toEntity(parameters);
boolean adding = false;
Map<String, Object> pcrequest = new HashMap<String, Object>();
if (ApiUtil.isEmpty(parameters.get(ApiConstants.MONGO_ID))) {
request.setPurchaseRequestCode(generateCode("CGSQ", DBBean.PURCHASE_ORDER));
pcrequest = request.toMap();
adding = true;
}else{
pcrequest.putAll(parameters);
}
String keys[] = new String[] { "eqcostApplyAmount", "orderEqcostCode", "orderEqcostName", "orderEqcostModel", "eqcostProductUnitPrice" };
pcrequest.put(SalesContractBean.SC_EQ_LIST, mergeSavedEqList(keys, parameters.get(SalesContractBean.SC_EQ_LIST)));
Map<String, Object> prequest = updatePurchase(pcrequest, DBBean.PURCHASE_REQUEST);
if (adding) {
updateRequestIdForBack(prequest);
}
return prequest;
}
private void updateRequestIdForBack(Map<String, Object> prequest) {
Map<String, Object> back = this.dao.findOne(ApiConstants.MONGO_ID, prequest.get("backRequestId"), new String[] { PurchaseBack.prId }, DBBean.PURCHASE_BACK);
back.put(PurchaseBack.prId, prequest.get(ApiConstants.MONGO_ID));
this.dao.updateById(back, DBBean.PURCHASE_BACK);
}
public Map<String, Object> approvePurchaseRequest(Map<String, Object> request) {
Map<String, Object> requestMap = this.dao.findOne(ApiConstants.MONGO_ID, request.get(ApiConstants.MONGO_ID),
new String[] { PurchaseCommonBean.PROCESS_STATUS }, DBBean.PURCHASE_REQUEST);
// if (requestMap.get(PurchaseCommonBean.PROCESS_STATUS) == null) {
// return processRequest(request, DBBean.PURCHASE_REQUEST, PurchaseRequest.MANAGER_APPROVED);
// }
// if (requestMap.get(PurchaseCommonBean.PROCESS_STATUS).toString().equalsIgnoreCase(PurchaseCommonBean.MANAGER_APPROVED)) {
// return processRequest(request, DBBean.PURCHASE_REQUEST, PurchaseRequest.STATUS_APPROVED);
// } else
if (requestMap.get(PurchaseCommonBean.PROCESS_STATUS).toString().equalsIgnoreCase(PurchaseCommonBean.STATUS_CANCELL_NEED_APPROVED)) {
Map<String,Object> result = processRequest(request, DBBean.PURCHASE_REQUEST, PurchaseRequest.STATUS_CANCELLED);
reduceBackEqCount((String)request.get(ApiConstants.MONGO_ID));
return result;
} else {
return processRequest(request, DBBean.PURCHASE_REQUEST, PurchaseCommonBean.STATUS_APPROVED);
}
}
private void reduceBackEqCount(String id){
if(ApiUtil.isEmpty(id)) return;
Map<String, Object> request = dao.findOne(ApiConstants.MONGO_ID, id, DBBean.PURCHASE_REQUEST);
List<Map<String,Object>> list1 = (List<Map<String,Object>>) request.get(SalesContractBean.SC_EQ_LIST);
String backId = (String)request.get(PurchaseCommonBean.BACK_REQUEST_ID);
Map<String, Object> back = dao.findOne(ApiConstants.MONGO_ID, backId, DBBean.PURCHASE_BACK);
List<Map<String,Object>> list2 = (List<Map<String,Object>>) back.get(SalesContractBean.SC_EQ_LIST);
Map<String,Double> map1 = new HashMap<String,Double>();
for(Map<String,Object> eq : list1){
map1.put((String)eq.get(ApiConstants.MONGO_ID), ApiUtil.getDouble(eq, PurchaseCommonBean.EQCOST_APPLY_AMOUNT, 0));
}
for(Map<String,Object> eq : list2){
String eqId = (String)eq.get(ApiConstants.MONGO_ID);
double backCount = ApiUtil.getDouble(eq, PurchaseBack.pbTotalCount, 0);
double reCount = map1.containsKey(eqId)? map1.get(eqId) : 0;
eq.put(PurchaseBack.pbTotalCount, backCount - reCount);
}
dao.updateById(back, DBBean.PURCHASE_BACK);
}
public Map<String, Object> cancelPurchaseRequest(Map<String, Object> request) {
return processRequest(request, DBBean.PURCHASE_REQUEST, PurchaseRequest.STATUS_CANCELL_NEED_APPROVED);
}
public Map<String, Object> rejectPurchaseRequest(Map<String, Object> request) {
return processRequest(request, DBBean.PURCHASE_REQUEST, PurchaseRequest.STATUS_REJECTED);
}
public Map<String, Object> getPurchaseRequest(Map<String, Object> parameters) {
Map<String, Object> result = this.dao.findOne(ApiConstants.MONGO_ID, parameters.get(ApiConstants.MONGO_ID), DBBean.PURCHASE_REQUEST);
List<Map<String, Object>> eqList = (List<Map<String, Object>>) result.get(SalesContractBean.SC_EQ_LIST);
eqList = scs.mergeEqListBasicInfo(eqList);
result.put(SalesContractBean.SC_EQ_LIST, eqList);
mergeProjectInfo(result);
Map<String, Object> backQuery = new HashMap<String, Object>();
backQuery.put(ApiConstants.MONGO_ID, result.get(PurchaseCommonBean.BACK_REQUEST_ID));
Map<String, Object> back = backService.mergeBackRestEqCount(backQuery);
List<Map<String, Object>> backEqList = (List<Map<String, Object>>) back.get(SalesContractBean.SC_EQ_LIST);
for (Map<String, Object> pr : eqList) {
for (Map<String, Object> be : backEqList) {
if (be.get(ApiConstants.MONGO_ID).equals(pr.get(ApiConstants.MONGO_ID))) {
pr.put(PurchaseBack.pbLeftCount, be.get(PurchaseBack.pbLeftCount));
pr.put(PurchaseBack.pbTotalCount, be.get(PurchaseBack.pbTotalCount));
break;
}
}
}
removeEmptyEqList(result, PurchaseBack.pbTotalCount);
return result;
}
public void deletePurchaseRequest(Map<String, Object> order) {
}
public Map<String, Object> updatePurchase(Map<String, Object> parameters, String db) {
if (parameters.get(PurchaseCommonBean.PROCESS_STATUS) == null) {
parameters.put(PurchaseCommonBean.PROCESS_STATUS, PurchaseRequest.STATUS_DRAFT);
}
if (parameters.get(PurchaseCommonBean.SALES_COUNTRACT_ID) != null) {
scs.mergeCommonFieldsFromSc(parameters, parameters.get(PurchaseCommonBean.SALES_COUNTRACT_ID));
}
if (parameters.get("requestedDate") == null && parameters.get(PurchaseCommonBean.PROCESS_STATUS) != null
&& parameters.get(PurchaseCommonBean.PROCESS_STATUS).toString().equalsIgnoreCase(PurchaseCommonBean.STATUS_NEW)) {
parameters.put("requestedDate", DateUtil.getDateString(new Date()));
}
Map<String, Object> result = null;
if (ApiUtil.isEmpty(parameters.get(ApiConstants.MONGO_ID))) {
result = this.dao.add(parameters, db);
} else {
result = dao.updateById(parameters, db);
}
return result;
}
@Override
public Map<String, Object> listRepositoryRequests(Map<String, Object> params) {
mergeMyTaskQuery(params, DBBean.REPOSITORY);
Map<String, Object> results = this.dao.list(params, DBBean.REPOSITORY);
List<Map<String, Object>> list = (List<Map<String, Object>>) results.get(ApiConstants.RESULTS_DATA);
Map<String, Object> query = new HashMap<String, Object>();
query.put(ApiConstants.LIMIT_KEYS, "supplierName");
Map<String, Object> suppliers = this.dao.listToOneMapAndIdAsKey(query, DBBean.SUPPLIER);
for (Map<String, Object> data : list) {
if (data.get("supplierId") != null) {
Map<String, Object> supplier = (Map<String, Object>) suppliers.get(data.get("supplierId"));
if (supplier != null) {
data.put("supplierName", supplier.get("supplierName"));
}
}
}
return results;
}
@Override
public Map<String, Object> getRepositoryRequest(Map<String, Object> parameters) {
Map<String, Object> result = this.dao.findOne(ApiConstants.MONGO_ID, parameters.get(ApiConstants.MONGO_ID), DBBean.REPOSITORY);
result.put(SalesContractBean.SC_EQ_LIST, scs.mergeEqListBasicInfo(result.get(SalesContractBean.SC_EQ_LIST)));
return result;
}
@Override
public void deleteRepositoryRequest(Map<String, Object> parserJsonParameters) {
}
@Override
public Map<String, Object> updateRepositoryRequest(Map<String, Object> parameters) {
String keys[] = new String[] { "eqcostApplyAmount", "orderEqcostCode", "orderEqcostName", "orderEqcostModel", "eqcostProductUnitPrice", "purchaseOrderCode",
"salesContractCode", PURCHASE_ORDER_ID, "purchaseRequestId", "purchaseRequestCode",
"eqcostDeliveryType", "logisticsArrivedTime", "logisticsStatus", "purchaseContractType", "purchaseContractCode", "purchaseContractId" };
List<Map<String, Object>> mergeSavedEqList = mergeSavedEqList(keys, parameters.get("eqcostList"));
double total = 0;
for(Map<String, Object> eq: mergeSavedEqList){
total += ApiUtil.getDouble(eq, "eqcostApplyAmount", 0);
}
if(parameters.get(ApiConstants.MONGO_ID) == null){
parameters.put("repositoryCode", generateCode("RKSQ", DBBean.REPOSITORY));
}
parameters.put("totalIn", (int)total);
parameters.put(SalesContractBean.SC_EQ_LIST, mergeSavedEqList);
return updatePurchase(parameters, DBBean.REPOSITORY);
}
@Override
public Map<String, Object> approveRepositoryRequest(Map<String, Object> params) {
if (params.get("type") != null && params.get("type").toString().equalsIgnoreCase("in")) {
//入库仓库
Map<String, Object> result = processRequest(params, DBBean.REPOSITORY, PurchaseRequest.STATUS_IN_REPOSITORY);
Map<String, Object> repo = dao.findOne(ApiConstants.MONGO_ID, params.get(ApiConstants.MONGO_ID), new String[] { SalesContractBean.SC_EQ_LIST },
DBBean.REPOSITORY);
createArriveNotice(repo);
return result;
} else {
//直发入库
return processRequest(params, DBBean.REPOSITORY, PurchaseRequest.STATUS_IN_OUT_REPOSITORY);
}
}
private void createArriveNotice(Map<String, Object> repo) {
List<Map<String, Object>> eqListMap = (List<Map<String, Object>>)repo.get(SalesContractBean.SC_EQ_LIST);
Map<String, List<Map<String, Object>>> eqOrderListMap = new HashMap<String, List<Map<String, Object>>>();
Set<String> orderIds = new HashSet<String>();
// 批准后更新订单状态
for (Map<String, Object> eqMap : eqListMap) {
String orderId = eqMap.get(PURCHASE_ORDER_ID).toString();
orderIds.add(orderId);
if (eqOrderListMap.get(orderId) == null) {
eqOrderListMap.put(orderId, new ArrayList<Map<String, Object>>());
}
eqMap.put(ArrivalNoticeBean.EQCOST_ARRIVAL_AMOUNT, eqMap.get(PurchaseCommonBean.EQCOST_APPLY_AMOUNT));
List<Map<String, Object>> list = eqOrderListMap.get(orderId);
list.add(eqMap);
eqOrderListMap.put(orderId, list);
}
for (String orderId : orderIds) {
Map<String, Object> arriveMap = new HashMap<String, Object>();
arriveMap.put(ApiConstants.MONGO_ID, orderId);
arriveMap.put(ArrivalNoticeBean.EQ_LIST, eqOrderListMap.get(orderId));
arriveService.createByOrder(arriveMap);
}
}
private void createAutoShip(Map<String, Object> repo) {
List<Map<String, Object>> eqListMap = (List<Map<String, Object>>)repo.get(SalesContractBean.SC_EQ_LIST);
Map<String, List<Map<String, Object>>> qeListMap = new HashMap<String, List<Map<String, Object>>>();
Map<String,Map<String, Object>> scMap = new HashMap<String, Map<String, Object>>();
Set<String> scIds = new HashSet<String>();
// 批准后更新订单状态
for (Map<String, Object> eqMap : eqListMap) {
String scId = eqMap.get(SalesContractBean.SC_ID).toString();
scIds.add(scId);
if (qeListMap.get(scId) == null) {
qeListMap.put(scId, new ArrayList<Map<String, Object>>());
}
eqMap.put(ShipBean.EQCOST_SHIP_AMOUNT, eqMap.get(PurchaseCommonBean.EQCOST_APPLY_AMOUNT));
List<Map<String, Object>> list = qeListMap.get(scId);
list.add(eqMap);
qeListMap.put(scId, list);
scMap.put(scId, eqMap);
}
for (String scId : scIds) {
Map<String, Object> ship = new HashMap<String, Object>();
ship.put(ShipBean.SHIP_SALES_CONTRACT_CODE, scMap.get(scId).get(PurchaseCommonBean.SALES_CONTRACT_CODE));
ship.put(ShipBean.SHIP_SALES_CONTRACT_ID, scMap.get(scId).get(SalesContractBean.SC_ID));
ship.put(ShipBean.SHIP_PROJECT_ID, scMap.get(scId).get(SalesContractBean.SC_PROJECT_ID));
ship.put(ShipBean.SHIP_STATUS, ShipBean.SHIP_STATUS_DRAFT);
ship.put(ArrivalNoticeBean.EQ_LIST, qeListMap.get(scId));
dao.add(ship, DBBean.SHIP);
}
}
public Map<String, Object> listProjectsForRepositoryDirect(Map<String, Object> params) {
Map<String, Object> query = new HashMap<String, Object>();
query.put(PurchaseCommonBean.PROCESS_STATUS, PurchaseCommonBean.STATUS_APPROVED);
query.put("eqcostDeliveryType", PurchaseCommonBean.EQCOST_DELIVERY_TYPE_DIRECTY);
query.put(ApiConstants.LIMIT_KEYS, new String[] { "eqcostList.scId", "eqcostList.projectId"});
List<Object> projectIds = this.dao.listLimitKeyValues(query, DBBean.PURCHASE_CONTRACT);
Set<String> proIds = new HashSet<String>();
for(Object map : projectIds){
Map<String, Object> eqMap = (HashMap<String, Object>) map;
List<Map<String, Object>> eqListMap = (List<Map<String, Object>>) eqMap.get("eqcostList");
for(Map<String, Object> eqItem: eqListMap){
if(eqItem.get(SalesContractBean.SC_PROJECT_ID)!=null){
proIds.add(eqItem.get(SalesContractBean.SC_PROJECT_ID).toString());
}
}
}
Map<String, Object> pquery = new HashMap<String, Object>();
pquery.put(ApiConstants.MONGO_ID, new DBQuery(DBQueryOpertion.IN, new ArrayList<>(proIds)));
pquery.put(ApiConstants.LIMIT_KEYS, ProjectBean.PROJECT_NAME);
return this.dao.list(pquery, DBBean.PROJECT);
}
@Override
public Map<String, Object> rejectRepositoryRequest(Map<String, Object> parserJsonParameters) {
return null;
}
public Map<String, Object> cancelRepositoryRequest(Map<String, Object> params) {
return processRequest(params, DBBean.REPOSITORY, PurchaseRequest.STATUS_CANCELLED);
}
// 采购合同列表为付款
public Map<String, Object> listSelectForPayment(Map<String, Object> params) {
Map<String, Object> query = new HashMap<String, Object>();
query.put(ApiConstants.LIMIT_KEYS, new String[] { "purchaseContractCode", "supplier" });
Map<String, Object> results = dao.list(query, DBBean.PURCHASE_CONTRACT);
List<Map<String, Object>> list =(List<Map<String, Object>>)results.get(ApiConstants.RESULTS_DATA);
Set<String> set = new HashSet<String>();
for(Map<String, Object> obj : list){
set.add((String)obj.get("supplier"));
}
set.remove(null);set.remove("");
Map<String,Object> query2 = new HashMap<String,Object>();
query2.put(ApiConstants.MONGO_ID, new DBQuery(DBQueryOpertion.IN, new ArrayList(set)));
Map<String,Object> suMap = dao.listToOneMapAndIdAsKey(query2, DBBean.SUPPLIER);
for(Map<String, Object> obj : list){
String id = (String)obj.get("supplier");
if(suMap.containsKey(id)){
Map<String,Object> su = (Map)suMap.get(id);
obj.put("supplierName", su.get("supplierName"));
obj.put(MoneyBean.supplierBankName, su.get(MoneyBean.supplierBankName));
obj.put(MoneyBean.supplierBankAccount, su.get(MoneyBean.supplierBankAccount));
}
}
return results;
}
@Override
public Map<String, Object> listPaymoney(Map<String, Object> params) {
Map<String,Object> query = new HashMap<String,Object>();//
if(params.get(InvoiceBean.purchaseContractId) != null){
query.put(InvoiceBean.purchaseContractId, params.get(InvoiceBean.purchaseContractId));
}
query.put(ApiConstants.LIMIT, params.get(ApiConstants.LIMIT));
query.put(ApiConstants.LIMIT_START, params.get(ApiConstants.LIMIT_START));
Map<String, Object> result = dao.list(query, DBBean.PAY_MONEY);
mergeSupplierInfo(result);
mergeCreatorInfo(result);
return result;
}
private void mergeSupplierInfo(Map<String,Object> params){
List<Map<String, Object>> list = (List<Map<String, Object>>) params.get(ApiConstants.RESULTS_DATA);
Set<String> suIds = new HashSet<String>();
for (Map<String, Object> obj : list) {
suIds.add((String) obj.get(MoneyBean.supplierId));
}
suIds.remove(null);
suIds.remove("");
Map<String, Object> query = new HashMap<String, Object>();
query.put(ApiConstants.MONGO_ID, new DBQuery(DBQueryOpertion.IN, new ArrayList(suIds)));
Map<String, Object> map = dao.listToOneMapAndIdAsKey(query, DBBean.SUPPLIER);
for (Map<String, Object> obj : list) {
String id = (String) obj.get(MoneyBean.supplierId);
if (map.get(id) != null) {
Map<String, Object> su = (Map<String, Object>) map.get(id);
obj.put("supplierName", su.get("supplierName"));
}
}
}
public Map<String, Object> savePaymoney(Map<String, Object> params) {
Map<String, Object> obj = new HashMap<String, Object>();
obj.put(ApiConstants.MONGO_ID, params.get(ApiConstants.MONGO_ID));
obj.put(MoneyBean.payMoneyActualMoney, ApiUtil.getDouble(params, MoneyBean.payMoneyActualMoney));
obj.put(MoneyBean.payMoneyActualDate, params.get(MoneyBean.payMoneyActualDate));
obj.put(MoneyBean.payMoneyComment, params.get(MoneyBean.payMoneyComment));
obj.put(MoneyBean.supplierBankAccount, params.get(MoneyBean.supplierBankAccount));
obj.put(MoneyBean.supplierBankName, params.get(MoneyBean.supplierBankName));
String[] keys = new String[] { "supplier", "purchaseContractCode" };
Map<String, Object> pc = dao.findOne("purchaseContractCode", params.get(MoneyBean.purchaseContractCode), keys,DBBean.PURCHASE_CONTRACT);
if(pc == null) {
throw new ApiResponseException("采购合同不存在", params, "请输入正确合同编号");
}
obj.put(MoneyBean.purchaseContractCode, pc.get("purchaseContractCode"));
obj.put(MoneyBean.purchaseContractId, pc.get(ApiConstants.MONGO_ID));
obj.put(MoneyBean.supplierId, pc.get("supplier"));
//如果供应商没有初始化 银行账号,则初始化
Map<String,Object> supplier = dao.findOne(ApiConstants.MONGO_ID, pc.get("supplier"), DBBean.SUPPLIER);
String cardName = (String)supplier.get(MoneyBean.supplierBankName);
if(cardName == null || cardName.isEmpty()){
supplier.put(MoneyBean.supplierBankName, params.get(MoneyBean.supplierBankName));
supplier.put(MoneyBean.supplierBankAccount, params.get(MoneyBean.supplierBankAccount));
dao.updateById(supplier, DBBean.SUPPLIER);
}
String oldComment = (String)dao.querySingleKeyById(MoneyBean.payMoneyComment, params.get(ApiConstants.MONGO_ID), DBBean.PAY_MONEY);
String comment = (String)params.get("tempComment");
comment = recordComment("提交",comment,oldComment);
obj.put("tempComment", params.get("tempComment"));
obj.put(MoneyBean.payMoneyComment, comment);
return dao.save(obj, DBBean.PAY_MONEY);
}
@Override
public void destoryPayMoney(Map<String, Object> params) {
List<String> ids = new ArrayList<String>();
ids.add(String.valueOf(params.get(ApiConstants.MONGO_ID)));
dao.deleteByIds(ids, DBBean.PAY_MONEY);
}
@Override
public Map<String, Object> listGetInvoice(Map<String, Object> params) {
Map<String,Object> result = dao.list(params, DBBean.GET_INVOICE);
mergeCreatorInfo(result);
return result;
}
@Override
public Map<String, Object> saveGetInvoice(Map<String, Object> params) {
Map<String,Object> invoice = new HashMap<String,Object>();
invoice.put(ApiConstants.MONGO_ID, params.get(ApiConstants.MONGO_ID));
invoice.put(InvoiceBean.getInvoiceActualDate, params.get(InvoiceBean.getInvoiceActualDate));
invoice.put(InvoiceBean.getInvoiceActualInvoiceNum, params.get(InvoiceBean.getInvoiceActualInvoiceNum));
invoice.put(InvoiceBean.getInvoiceActualMoney, ApiUtil.getDouble(params, InvoiceBean.getInvoiceActualMoney, 0));
invoice.put(InvoiceBean.getInvoiceActualSheetCount, ApiUtil.getInteger(params, InvoiceBean.getInvoiceActualSheetCount, 0));
invoice.put(InvoiceBean.getInvoiceReceivedMoneyStatus, params.get(InvoiceBean.getInvoiceReceivedMoneyStatus));
invoice.put(InvoiceBean.getInvoiceItemList, params.get(InvoiceBean.getInvoiceItemList));
Map<String,Object> pc = dao.findOne(ApiConstants.MONGO_ID, params.get(InvoiceBean.purchaseContractId), new String[]{"purchaseContractCode","supplier","invoiceType"}, DBBean.PURCHASE_CONTRACT);
invoice.put(InvoiceBean.purchaseContractId, pc.get(ApiConstants.MONGO_ID));
invoice.put(InvoiceBean.purchaseContractCode, pc.get("purchaseContractCode"));
invoice.put(InvoiceBean.invoiceType, pc.get("invoiceType"));
invoice.put(InvoiceBean.getInvoiceSupplierId, pc.get("supplier"));
String oldComment = (String)dao.querySingleKeyById(InvoiceBean.getInvoiceComment, params.get(ApiConstants.MONGO_ID), DBBean.GET_INVOICE);
String comment = (String)params.get("tempComment");
comment = recordComment("提交",comment,oldComment);
invoice.put(InvoiceBean.getInvoiceComment, comment);
return dao.save(invoice, DBBean.GET_INVOICE);
}
@Override
public Map<String, Object> viewPCForInvoice(Map<String, Object> params) {
String pcId = (String)params.get(InvoiceBean.purchaseContractId);
String[] keys = new String[]{"purchaseContractCode","requestedTotalMoney","purchaseContractType",
"eqcostDeliveryType","signDate","invoiceType","supplier"};
Map<String,Object> pc = dao.findOne(ApiConstants.MONGO_ID, pcId, keys, DBBean.PURCHASE_CONTRACT);
Map<String,Object> suppier = dao.findOne(ApiConstants.MONGO_ID, pc.get("supplier"), DBBean.SUPPLIER);
suppier.remove(ApiConstants.MONGO_ID);
pc.putAll(suppier);
return pc;
}
@Override
public Map<String, Object> prepareGetInvoice(Map<String, Object> params) {
Map<String,Object> result = viewPCForInvoice(params);
result.remove(ApiConstants.MONGO_ID);
result.put(InvoiceBean.purchaseContractId, params.get(InvoiceBean.purchaseContractId));
result.put(InvoiceBean.getInvoiceItemList, new ArrayList());
return result;
}
@Override
public Map<String, Object> loadGetInvoice(Map<String, Object> params) {
Map<String,Object> invoice = dao.findOne(ApiConstants.MONGO_ID, params.get(ApiConstants.MONGO_ID), DBBean.GET_INVOICE);
mergePcAndSupplierForInvoice(invoice);
return invoice;
}
private void mergePcAndSupplierForInvoice(Map<String,Object> params){
String[] keys = new String[]{"purchaseContractCode","requestedTotalMoney","purchaseContractType",
"eqcostDeliveryType","signDate","invoiceType","supplier"};
Map<String, Object> pc = dao.findOne(ApiConstants.MONGO_ID, params.get("purchaseContractId"),keys, DBBean.PURCHASE_CONTRACT);
if(pc != null){
Map<String, Object> supplier = dao.findOne(ApiConstants.MONGO_ID, pc.get("supplier"), DBBean.SUPPLIER);
pc.remove(ApiConstants.MONGO_ID);
params.putAll(pc);
if(supplier != null){
supplier.remove(ApiConstants.MONGO_ID);
params.putAll(supplier);
}
}
}
@Override
public Map<String, Object> updateGetInvoice(Map<String, Object> params) {
return dao.updateById(params, DBBean.GET_INVOICE);
}
@Override
public void destroyGetInvoice(Map<String, Object> params) {
List<String> ids = new ArrayList<String>();
ids.add(String.valueOf(params.get(ApiConstants.MONGO_ID)));
dao.deleteByIds(ids, DBBean.GET_INVOICE);
}
public IPurchaseService getBackService() {
return backService;
}
public void setBackService(IPurchaseService backService) {
this.backService = backService;
}
}
| true | true | private void updateOrderFinalStatus(Map<String, Object> contract) {
List<Map<String, Object>> eqListMap = (List<Map<String, Object>>)contract.get(SalesContractBean.SC_EQ_LIST);
Set<String> orderIds = new HashSet<String>();
// 批准后更新订单状态
for (Map<String, Object> eqMap : eqListMap) {
String orderId = eqMap.get(PURCHASE_ORDER_ID).toString();
orderIds.add(orderId);
eqMap.put(PurchaseCommonBean.EQCOST_DELIVERY_TYPE, contract.get(PurchaseCommonBean.EQCOST_DELIVERY_TYPE));
eqMap.put(PurchaseCommonBean.PURCHASE_CONTRACT_ID, contract.get(ApiConstants.MONGO_ID));
eqMap.put(PurchaseCommonBean.PURCHASE_CONTRACT_CODE, contract.get(PurchaseCommonBean.PURCHASE_CONTRACT_CODE));
eqMap.put(PurchaseCommonBean.PURCHASE_CONTRACT_TYPE, contract.get(PurchaseCommonBean.PURCHASE_CONTRACT_TYPE));
}
this.dao.updateById(contract, DBBean.PURCHASE_CONTRACT);
Map<String, Object> query = new HashMap<String, Object>();
query.put(SalesContractBean.SC_EQ_LIST + "." + PURCHASE_ORDER_ID, new DBQuery(DBQueryOpertion.IN, new ArrayList<String>(orderIds)));
query.put(PurchaseCommonBean.PROCESS_STATUS, new DBQuery(DBQueryOpertion.IN, new String[] { PurchaseCommonBean.STATUS_APPROVED }));
Map<String, Integer> eqCountMap = countEqByKey(query, DBBean.PURCHASE_CONTRACT, "eqcostApplyAmount", null);
for (String orderId : orderIds) {
int count = 0;
Map<String, Object> orderQuery = new HashMap<String, Object>();
orderQuery.put(ApiConstants.MONGO_ID, orderId);
orderQuery.put(ApiConstants.LIMIT_KEYS, new String[]{SalesContractBean.SC_EQ_LIST, PurchaseCommonBean.EQCOST_DELIVERY_TYPE});
// 最外层就一个数组, 数组下面才是设备清单
Map<String, Object> orderMap = this.dao.findOneByQuery(orderQuery, DBBean.PURCHASE_ORDER);
if (orderMap != null) {
List<Map<String, Object>> orderEqlistMap = (List<Map<String, Object>>) orderMap.get(SalesContractBean.SC_EQ_LIST);
for (Map<String, Object> eqOrderMap : orderEqlistMap) {
int orderCount = ApiUtil.getInteger(eqOrderMap.get("eqcostApplyAmount"), 0);
int countractCount = ApiUtil.getInteger(eqCountMap.get(eqOrderMap.get(ApiConstants.MONGO_ID)), 0);
if (countractCount >= orderCount) {
count++;
}
if(eqCountMap.get(eqOrderMap.get(ApiConstants.MONGO_ID))!=null){
//合并货物递送方式和订单等等信息到设备清单
eqOrderMap.put(PurchaseCommonBean.EQCOST_DELIVERY_TYPE, orderMap.get(PurchaseCommonBean.EQCOST_DELIVERY_TYPE));
eqOrderMap.put(PurchaseCommonBean.PURCHASE_ORDER_ID, orderMap.get(ApiConstants.MONGO_ID));
eqOrderMap.put(PurchaseCommonBean.PURCHASE_ORDER_CODE, orderMap.get(PurchaseCommonBean.PURCHASE_ORDER_CODE));
eqOrderMap.put(PurchaseCommonBean.PURCHASE_REQUEST_ID, orderMap.get(PurchaseCommonBean.PURCHASE_REQUEST_ID));
eqOrderMap.put(PurchaseCommonBean.PURCHASE_REQUEST_CODE, orderMap.get(PurchaseCommonBean.PURCHASE_REQUEST_CODE));
eqOrderMap.put(PurchaseCommonBean.PURCHASE_CONTRACT_ID, contract.get(ApiConstants.MONGO_ID));
eqOrderMap.put(PurchaseCommonBean.PURCHASE_CONTRACT_CODE, contract.get(PurchaseCommonBean.PURCHASE_CONTRACT_CODE));
eqOrderMap.put(PurchaseCommonBean.PURCHASE_CONTRACT_TYPE, contract.get(PurchaseCommonBean.PURCHASE_CONTRACT_TYPE));
}
}
orderMap.put(SalesContractBean.SC_EQ_LIST, orderEqlistMap);
updatePurchase(orderMap, DBBean.PURCHASE_ORDER);
if (count == orderEqlistMap.size()) {
Map<String, Object> ordeUpdate = new HashMap<String, Object>();
ordeUpdate.put(ApiConstants.MONGO_ID, orderId);
ordeUpdate.put(PurchaseCommonBean.PROCESS_STATUS, PurchaseCommonBean.STATUS_ORDER_FINISHED);
this.dao.updateById(ordeUpdate, DBBean.PURCHASE_ORDER);
Map<String, Object> order = this.dao.findOne(ApiConstants.MONGO_ID, orderId, new String[] { PurchaseCommonBean.PURCHASE_REQUEST_ID, PurchaseCommonBean.PURCHASE_ORDER_CODE }, DBBean.PURCHASE_ORDER);
if (order != null && order.get(PurchaseCommonBean.PURCHASE_REQUEST_ID) != null) {
Map<String, Object> purRequest = new HashMap<String, Object>();
purRequest.put(ApiConstants.MONGO_ID, order.get(PurchaseCommonBean.PURCHASE_REQUEST_ID));
purRequest.put(PurchaseCommonBean.PROCESS_STATUS, PurchaseCommonBean.STATUS_ORDER_FINISHED);
this.dao.updateById(ordeUpdate, DBBean.PURCHASE_REQUEST);
}
} else {
Map<String, Object> ordeUpdate = new HashMap<String, Object>();
ordeUpdate.put(ApiConstants.MONGO_ID, orderId);
ordeUpdate.put(PurchaseCommonBean.PROCESS_STATUS, PurchaseCommonBean.STATUS_ORDERING);
this.dao.updateById(ordeUpdate, DBBean.PURCHASE_ORDER);
}
}
}
}
| private void updateOrderFinalStatus(Map<String, Object> contract) {
List<Map<String, Object>> eqListMap = (List<Map<String, Object>>)contract.get(SalesContractBean.SC_EQ_LIST);
Set<String> orderIds = new HashSet<String>();
// 批准后更新订单状态
for (Map<String, Object> eqMap : eqListMap) {
String orderId = eqMap.get(PURCHASE_ORDER_ID).toString();
orderIds.add(orderId);
eqMap.put(PurchaseCommonBean.EQCOST_DELIVERY_TYPE, contract.get(PurchaseCommonBean.EQCOST_DELIVERY_TYPE));
eqMap.put(PurchaseCommonBean.PURCHASE_CONTRACT_ID, contract.get(ApiConstants.MONGO_ID));
eqMap.put(PurchaseCommonBean.PURCHASE_CONTRACT_CODE, contract.get(PurchaseCommonBean.PURCHASE_CONTRACT_CODE));
eqMap.put(PurchaseCommonBean.PURCHASE_CONTRACT_TYPE, contract.get(PurchaseCommonBean.PURCHASE_CONTRACT_TYPE));
eqMap.put(PurchaseCommonBean.CONTRACT_EXECUTE_CATE, contract.get(PurchaseCommonBean.CONTRACT_EXECUTE_CATE));
}
this.dao.updateById(contract, DBBean.PURCHASE_CONTRACT);
Map<String, Object> query = new HashMap<String, Object>();
query.put(SalesContractBean.SC_EQ_LIST + "." + PURCHASE_ORDER_ID, new DBQuery(DBQueryOpertion.IN, new ArrayList<String>(orderIds)));
query.put(PurchaseCommonBean.PROCESS_STATUS, new DBQuery(DBQueryOpertion.IN, new String[] { PurchaseCommonBean.STATUS_APPROVED }));
Map<String, Integer> eqCountMap = countEqByKey(query, DBBean.PURCHASE_CONTRACT, "eqcostApplyAmount", null);
for (String orderId : orderIds) {
int count = 0;
Map<String, Object> orderQuery = new HashMap<String, Object>();
orderQuery.put(ApiConstants.MONGO_ID, orderId);
orderQuery.put(ApiConstants.LIMIT_KEYS, new String[]{SalesContractBean.SC_EQ_LIST, PurchaseCommonBean.EQCOST_DELIVERY_TYPE});
// 最外层就一个数组, 数组下面才是设备清单
Map<String, Object> orderMap = this.dao.findOneByQuery(orderQuery, DBBean.PURCHASE_ORDER);
if (orderMap != null) {
List<Map<String, Object>> orderEqlistMap = (List<Map<String, Object>>) orderMap.get(SalesContractBean.SC_EQ_LIST);
for (Map<String, Object> eqOrderMap : orderEqlistMap) {
int orderCount = ApiUtil.getInteger(eqOrderMap.get("eqcostApplyAmount"), 0);
int countractCount = ApiUtil.getInteger(eqCountMap.get(eqOrderMap.get(ApiConstants.MONGO_ID)), 0);
if (countractCount >= orderCount) {
count++;
}
if(eqCountMap.get(eqOrderMap.get(ApiConstants.MONGO_ID))!=null){
//合并货物递送方式和订单等等信息到设备清单
eqOrderMap.put(PurchaseCommonBean.EQCOST_DELIVERY_TYPE, orderMap.get(PurchaseCommonBean.EQCOST_DELIVERY_TYPE));
eqOrderMap.put(PurchaseCommonBean.PURCHASE_ORDER_ID, orderMap.get(ApiConstants.MONGO_ID));
eqOrderMap.put(PurchaseCommonBean.PURCHASE_ORDER_CODE, orderMap.get(PurchaseCommonBean.PURCHASE_ORDER_CODE));
eqOrderMap.put(PurchaseCommonBean.PURCHASE_REQUEST_ID, orderMap.get(PurchaseCommonBean.PURCHASE_REQUEST_ID));
eqOrderMap.put(PurchaseCommonBean.PURCHASE_REQUEST_CODE, orderMap.get(PurchaseCommonBean.PURCHASE_REQUEST_CODE));
eqOrderMap.put(PurchaseCommonBean.PURCHASE_CONTRACT_ID, contract.get(ApiConstants.MONGO_ID));
eqOrderMap.put(PurchaseCommonBean.PURCHASE_CONTRACT_CODE, contract.get(PurchaseCommonBean.PURCHASE_CONTRACT_CODE));
eqOrderMap.put(PurchaseCommonBean.PURCHASE_CONTRACT_TYPE, contract.get(PurchaseCommonBean.PURCHASE_CONTRACT_TYPE));
}
}
orderMap.put(SalesContractBean.SC_EQ_LIST, orderEqlistMap);
updatePurchase(orderMap, DBBean.PURCHASE_ORDER);
if (count == orderEqlistMap.size()) {
Map<String, Object> ordeUpdate = new HashMap<String, Object>();
ordeUpdate.put(ApiConstants.MONGO_ID, orderId);
ordeUpdate.put(PurchaseCommonBean.PROCESS_STATUS, PurchaseCommonBean.STATUS_ORDER_FINISHED);
this.dao.updateById(ordeUpdate, DBBean.PURCHASE_ORDER);
Map<String, Object> order = this.dao.findOne(ApiConstants.MONGO_ID, orderId, new String[] { PurchaseCommonBean.PURCHASE_REQUEST_ID, PurchaseCommonBean.PURCHASE_ORDER_CODE }, DBBean.PURCHASE_ORDER);
if (order != null && order.get(PurchaseCommonBean.PURCHASE_REQUEST_ID) != null) {
Map<String, Object> purRequest = new HashMap<String, Object>();
purRequest.put(ApiConstants.MONGO_ID, order.get(PurchaseCommonBean.PURCHASE_REQUEST_ID));
purRequest.put(PurchaseCommonBean.PROCESS_STATUS, PurchaseCommonBean.STATUS_ORDER_FINISHED);
this.dao.updateById(ordeUpdate, DBBean.PURCHASE_REQUEST);
}
} else {
Map<String, Object> ordeUpdate = new HashMap<String, Object>();
ordeUpdate.put(ApiConstants.MONGO_ID, orderId);
ordeUpdate.put(PurchaseCommonBean.PROCESS_STATUS, PurchaseCommonBean.STATUS_ORDERING);
this.dao.updateById(ordeUpdate, DBBean.PURCHASE_ORDER);
}
}
}
}
|
diff --git a/src/test/java/com/huskycode/jpaquery/populator/ValuesPopulatorImplTest.java b/src/test/java/com/huskycode/jpaquery/populator/ValuesPopulatorImplTest.java
index aee7603..a2677ed 100644
--- a/src/test/java/com/huskycode/jpaquery/populator/ValuesPopulatorImplTest.java
+++ b/src/test/java/com/huskycode/jpaquery/populator/ValuesPopulatorImplTest.java
@@ -1,31 +1,31 @@
package com.huskycode.jpaquery.populator;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import com.huskycode.jpaquery.link.Attribute;
import com.huskycode.jpaquery.link.AttributeImpl;
import com.huskycode.jpaquery.testmodel.pizza.Customer;
public class ValuesPopulatorImplTest {
@Test
public void testValueIsPopulatedForTheGivenAttributeValues() throws SecurityException, NoSuchFieldException {
ValuesPopulatorImpl populator = ValuesPopulatorImpl.getInstance();
Long expectedValue = 1L;
Attribute<Customer, Long> customerIdAttr = AttributeImpl.newInstance(Customer.class,
Customer.class.getDeclaredField("customerId"));
AttributeValue<Customer, Long> customerIdValue = AttributeValue.newInstance(customerIdAttr, expectedValue);
List<AttributeValue<Customer, ?>> attributeValues
= new ArrayList<AttributeValue<Customer, ?>>();
attributeValues.add(customerIdValue);
Customer customer = new Customer();
populator.populateValue(customer, attributeValues);
- Assert.assertEquals(expectedValue.longValue(), customer.getCustomerId());
+ Assert.assertEquals(expectedValue, customer.getCustomerId());
}
}
| true | true | public void testValueIsPopulatedForTheGivenAttributeValues() throws SecurityException, NoSuchFieldException {
ValuesPopulatorImpl populator = ValuesPopulatorImpl.getInstance();
Long expectedValue = 1L;
Attribute<Customer, Long> customerIdAttr = AttributeImpl.newInstance(Customer.class,
Customer.class.getDeclaredField("customerId"));
AttributeValue<Customer, Long> customerIdValue = AttributeValue.newInstance(customerIdAttr, expectedValue);
List<AttributeValue<Customer, ?>> attributeValues
= new ArrayList<AttributeValue<Customer, ?>>();
attributeValues.add(customerIdValue);
Customer customer = new Customer();
populator.populateValue(customer, attributeValues);
Assert.assertEquals(expectedValue.longValue(), customer.getCustomerId());
}
| public void testValueIsPopulatedForTheGivenAttributeValues() throws SecurityException, NoSuchFieldException {
ValuesPopulatorImpl populator = ValuesPopulatorImpl.getInstance();
Long expectedValue = 1L;
Attribute<Customer, Long> customerIdAttr = AttributeImpl.newInstance(Customer.class,
Customer.class.getDeclaredField("customerId"));
AttributeValue<Customer, Long> customerIdValue = AttributeValue.newInstance(customerIdAttr, expectedValue);
List<AttributeValue<Customer, ?>> attributeValues
= new ArrayList<AttributeValue<Customer, ?>>();
attributeValues.add(customerIdValue);
Customer customer = new Customer();
populator.populateValue(customer, attributeValues);
Assert.assertEquals(expectedValue, customer.getCustomerId());
}
|
diff --git a/src/ie/broadsheet/app/CommentListActivity.java b/src/ie/broadsheet/app/CommentListActivity.java
index fd31c32..e6d8b69 100644
--- a/src/ie/broadsheet/app/CommentListActivity.java
+++ b/src/ie/broadsheet/app/CommentListActivity.java
@@ -1,106 +1,108 @@
package ie.broadsheet.app;
import ie.broadsheet.app.adapters.CommentAdapter;
import ie.broadsheet.app.dialog.MakeCommentDialog;
import ie.broadsheet.app.model.json.Comment;
import ie.broadsheet.app.model.json.Post;
import android.os.Bundle;
import android.text.Html;
import android.widget.ListView;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.PauseOnScrollListener;
public class CommentListActivity extends BaseFragmentActivity implements MakeCommentDialog.CommentMadeListener,
CommentAdapter.ReplyCommentListener {
private Post post;
private CommentAdapter comments;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_comment_list);
Bundle extras = getIntent().getExtras();
if (extras != null) {
BroadsheetApplication app = (BroadsheetApplication) getApplication();
- post = app.getPosts().get(extras.getInt("item_id"));
+ if (app.getPosts().size() > 0) {
+ post = app.getPosts().get(extras.getInt("item_id"));
+ }
}
ListView list = (ListView) findViewById(android.R.id.list);
comments = new CommentAdapter(this, R.layout.comment_list_item, post.getSortedComments());
comments.setReplyCommentListener(this);
list.setAdapter(comments);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
boolean pauseOnScroll = false;
boolean pauseOnFling = true;
PauseOnScrollListener listener = new PauseOnScrollListener(ImageLoader.getInstance(), pauseOnScroll,
pauseOnFling);
list.setOnScrollListener(listener);
setTitle(getResources().getString(R.string.comment));
}
@Override
public void onStart() {
super.onStart();
((BroadsheetApplication) getApplication()).getTracker().sendView(
"Comment List: " + Html.fromHtml(post.getTitle_plain()) + " " + Integer.toString(post.getId()));
}
@Override
public void onStop() {
super.onStop();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
if (post.getComment_status().equals("open")) {
getSupportMenuInflater().inflate(R.menu.comment_list, menu);
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
super.onBackPressed();
return true;
} else if (item.getItemId() == R.id.menu_make_comment) {
onReply(0);
}
return super.onOptionsItemSelected(item);
}
@Override
public void onCommentMade(Comment comment) {
post.addComment(comment);
comments.clear();
// comments.addAll(post.getSortedComments());
for (Comment addcomment : post.getSortedComments()) {
comments.add(addcomment);
}
comments.notifyDataSetChanged();
}
@Override
public void onReply(int commentId) {
MakeCommentDialog dialog = new MakeCommentDialog();
dialog.setPostId(post.getId());
dialog.setCommentMadeListener(this);
dialog.setCommentId(commentId);
dialog.show(this.getSupportFragmentManager(), "MakeCommentDialog");
}
}
| true | true | protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_comment_list);
Bundle extras = getIntent().getExtras();
if (extras != null) {
BroadsheetApplication app = (BroadsheetApplication) getApplication();
post = app.getPosts().get(extras.getInt("item_id"));
}
ListView list = (ListView) findViewById(android.R.id.list);
comments = new CommentAdapter(this, R.layout.comment_list_item, post.getSortedComments());
comments.setReplyCommentListener(this);
list.setAdapter(comments);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
boolean pauseOnScroll = false;
boolean pauseOnFling = true;
PauseOnScrollListener listener = new PauseOnScrollListener(ImageLoader.getInstance(), pauseOnScroll,
pauseOnFling);
list.setOnScrollListener(listener);
setTitle(getResources().getString(R.string.comment));
}
| protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_comment_list);
Bundle extras = getIntent().getExtras();
if (extras != null) {
BroadsheetApplication app = (BroadsheetApplication) getApplication();
if (app.getPosts().size() > 0) {
post = app.getPosts().get(extras.getInt("item_id"));
}
}
ListView list = (ListView) findViewById(android.R.id.list);
comments = new CommentAdapter(this, R.layout.comment_list_item, post.getSortedComments());
comments.setReplyCommentListener(this);
list.setAdapter(comments);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
boolean pauseOnScroll = false;
boolean pauseOnFling = true;
PauseOnScrollListener listener = new PauseOnScrollListener(ImageLoader.getInstance(), pauseOnScroll,
pauseOnFling);
list.setOnScrollListener(listener);
setTitle(getResources().getString(R.string.comment));
}
|
diff --git a/src/main/java/com/minecraftdimensions/bungeesuitechat/BungeeSuiteChat.java b/src/main/java/com/minecraftdimensions/bungeesuitechat/BungeeSuiteChat.java
index dbbc99f..a3fd9a9 100644
--- a/src/main/java/com/minecraftdimensions/bungeesuitechat/BungeeSuiteChat.java
+++ b/src/main/java/com/minecraftdimensions/bungeesuitechat/BungeeSuiteChat.java
@@ -1,156 +1,156 @@
package com.minecraftdimensions.bungeesuitechat;
import net.milkbowl.vault.chat.Chat;
import org.bukkit.Bukkit;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.java.JavaPlugin;
import com.massivecraft.factions.Factions;
import com.minecraftdimensions.bungeesuitechat.commands.AfkCommand;
import com.minecraftdimensions.bungeesuitechat.commands.ChatspyCommand;
import com.minecraftdimensions.bungeesuitechat.commands.IgnoreCommand;
import com.minecraftdimensions.bungeesuitechat.commands.IgnoresCommand;
import com.minecraftdimensions.bungeesuitechat.commands.MeCommand;
import com.minecraftdimensions.bungeesuitechat.commands.MessageCommand;
import com.minecraftdimensions.bungeesuitechat.commands.MuteAllCommand;
import com.minecraftdimensions.bungeesuitechat.commands.MuteCommand;
import com.minecraftdimensions.bungeesuitechat.commands.NicknameCommand;
import com.minecraftdimensions.bungeesuitechat.commands.NicknameOffCommand;
import com.minecraftdimensions.bungeesuitechat.commands.ReloadChatCommand;
import com.minecraftdimensions.bungeesuitechat.commands.ReplyCommand;
import com.minecraftdimensions.bungeesuitechat.commands.TempMuteCommand;
import com.minecraftdimensions.bungeesuitechat.commands.UnMuteAllCommand;
import com.minecraftdimensions.bungeesuitechat.commands.UnMuteCommand;
import com.minecraftdimensions.bungeesuitechat.commands.UnignoreCommand;
import com.minecraftdimensions.bungeesuitechat.commands.channel.AdminCommand;
import com.minecraftdimensions.bungeesuitechat.commands.channel.GlobalCommand;
import com.minecraftdimensions.bungeesuitechat.commands.channel.LocalCommand;
import com.minecraftdimensions.bungeesuitechat.commands.channel.ServerCommand;
import com.minecraftdimensions.bungeesuitechat.commands.channel.ToggleCommand;
import com.minecraftdimensions.bungeesuitechat.commands.factions.FactionChatAllyCommand;
import com.minecraftdimensions.bungeesuitechat.commands.factions.FactionChatCommand;
import com.minecraftdimensions.bungeesuitechat.commands.factions.FactionChatFactionCommand;
import com.minecraftdimensions.bungeesuitechat.listeners.AFKListener;
import com.minecraftdimensions.bungeesuitechat.listeners.ChatListener;
import com.minecraftdimensions.bungeesuitechat.listeners.LoginListener;
import com.minecraftdimensions.bungeesuitechat.listeners.LogoutListener;
import com.minecraftdimensions.bungeesuitechat.listeners.MessageListener;
import com.minecraftdimensions.bungeesuitechat.managers.ChannelManager;
public class BungeeSuiteChat extends JavaPlugin {
public static String OUTGOING_PLUGIN_CHANNEL = "BSChat";
public static String INCOMING_PLUGIN_CHANNEL = "BungeeSuiteChat";
public static BungeeSuiteChat instance;
public static Chat CHAT = null;
public static boolean usingVault;
public static boolean factionChat = false;
public static String serverName;
@Override
public void onEnable() {
instance = this;
registerCommands();
usingVault = setupVault();
registerListeners();
startTasks();
}
private void startTasks() {
this.getServer().getScheduler().runTaskTimerAsynchronously(this, new Runnable(){
@Override
public void run() {
ChannelManager.cleanChannels();
}
}, 36000, 36000);
}
private void registerListeners() {
this.getServer().getMessenger().registerOutgoingPluginChannel(this, OUTGOING_PLUGIN_CHANNEL);
Bukkit.getPluginManager().registerEvents(new ChatListener(), this);
Bukkit.getPluginManager().registerEvents(new LoginListener(), this);
Bukkit.getPluginManager().registerEvents(new LogoutListener(), this);
Bukkit.getPluginManager().registerEvents(new AFKListener(), this);
Bukkit.getMessenger().registerIncomingPluginChannel(this,
INCOMING_PLUGIN_CHANNEL, new MessageListener());
}
public void setupFactions() {
Factions factions = (Factions) Bukkit.getPluginManager().getPlugin("Factions");
if(factions!=null){
if(!factions.getDescription().getVersion().startsWith("1")){
factionChat = true;
getCommand("factionchat").setExecutor(new FactionChatCommand());
getCommand("factionchatally").setExecutor(new FactionChatAllyCommand());
getCommand("factionchatfaction").setExecutor(new FactionChatFactionCommand());
}
}
}
private void registerCommands() {
getCommand("admin").setExecutor(new AdminCommand());
getCommand("afk").setExecutor(new AfkCommand());
getCommand("chatspy").setExecutor(new ChatspyCommand());
- getCommand("channelinfo").setExecutor(new ChannelInfoCommand(this));
+ getCommand("channelinfo").setExecutor(new ChannelInfoCommand());
getCommand("global").setExecutor(new GlobalCommand());
getCommand("ignore").setExecutor(new IgnoreCommand());
getCommand("ignores").setExecutor(new IgnoresCommand());
getCommand("local").setExecutor(new LocalCommand());
getCommand("me").setExecutor(new MeCommand());
getCommand("message").setExecutor(new MessageCommand());
getCommand("mute").setExecutor(new MuteCommand());
getCommand("muteall").setExecutor(new MuteAllCommand());
getCommand("nickname").setExecutor(new NicknameCommand());
getCommand("nicknameoff").setExecutor(new NicknameOffCommand());
getCommand("reloadchat").setExecutor(new ReloadChatCommand());
getCommand("reply").setExecutor(new ReplyCommand());
getCommand("server").setExecutor(new ServerCommand());
getCommand("tempmute").setExecutor(new TempMuteCommand());
getCommand("toggle").setExecutor(new ToggleCommand());
getCommand("unignore").setExecutor(new UnignoreCommand());
getCommand("unmute").setExecutor(new UnMuteCommand());
getCommand("unmuteall").setExecutor(new UnMuteAllCommand());
// getCommand("createchannel").setExecutor(new WhoisCommand(this));
// getCommand("deletechannel").setExecutor(new WhoisCommand(this));
// getCommand("leavechannel").setExecutor(new WhoisCommand(this));
// getCommand("joinchannel").setExecutor(new WhoisCommand(this));
// getCommand("kickchannel").setExecutor(new WhoisCommand(this));
// getCommand("formatchannel").setExecutor(new WhoisCommand(this));
// getCommand("channelinfo").setExecutor(new WhoisCommand(this));
// getCommand("setchannelowner").setExecutor(new WhoisCommand(this));
}
private boolean setupVault()
{
if(!packageExists("net.milkbowl.vault.chat.Chat"))return false;
RegisteredServiceProvider<Chat> chatProvider = getServer().getServicesManager().getRegistration(net.milkbowl.vault.chat.Chat.class);
if (chatProvider != null) {
CHAT = chatProvider.getProvider();
} else {
this.getLogger().info("No Vault found");
}
return (CHAT != null);
}
private boolean packageExists(String...packages) {
try {
for (String pkg : packages) {
Class.forName(pkg);
}
return true;
} catch (Exception e) {
this.getLogger().info("No Vault found");
return false;
}
}
}
| true | true | private void registerCommands() {
getCommand("admin").setExecutor(new AdminCommand());
getCommand("afk").setExecutor(new AfkCommand());
getCommand("chatspy").setExecutor(new ChatspyCommand());
getCommand("channelinfo").setExecutor(new ChannelInfoCommand(this));
getCommand("global").setExecutor(new GlobalCommand());
getCommand("ignore").setExecutor(new IgnoreCommand());
getCommand("ignores").setExecutor(new IgnoresCommand());
getCommand("local").setExecutor(new LocalCommand());
getCommand("me").setExecutor(new MeCommand());
getCommand("message").setExecutor(new MessageCommand());
getCommand("mute").setExecutor(new MuteCommand());
getCommand("muteall").setExecutor(new MuteAllCommand());
getCommand("nickname").setExecutor(new NicknameCommand());
getCommand("nicknameoff").setExecutor(new NicknameOffCommand());
getCommand("reloadchat").setExecutor(new ReloadChatCommand());
getCommand("reply").setExecutor(new ReplyCommand());
getCommand("server").setExecutor(new ServerCommand());
getCommand("tempmute").setExecutor(new TempMuteCommand());
getCommand("toggle").setExecutor(new ToggleCommand());
getCommand("unignore").setExecutor(new UnignoreCommand());
getCommand("unmute").setExecutor(new UnMuteCommand());
getCommand("unmuteall").setExecutor(new UnMuteAllCommand());
// getCommand("createchannel").setExecutor(new WhoisCommand(this));
// getCommand("deletechannel").setExecutor(new WhoisCommand(this));
// getCommand("leavechannel").setExecutor(new WhoisCommand(this));
// getCommand("joinchannel").setExecutor(new WhoisCommand(this));
// getCommand("kickchannel").setExecutor(new WhoisCommand(this));
// getCommand("formatchannel").setExecutor(new WhoisCommand(this));
// getCommand("channelinfo").setExecutor(new WhoisCommand(this));
// getCommand("setchannelowner").setExecutor(new WhoisCommand(this));
}
| private void registerCommands() {
getCommand("admin").setExecutor(new AdminCommand());
getCommand("afk").setExecutor(new AfkCommand());
getCommand("chatspy").setExecutor(new ChatspyCommand());
getCommand("channelinfo").setExecutor(new ChannelInfoCommand());
getCommand("global").setExecutor(new GlobalCommand());
getCommand("ignore").setExecutor(new IgnoreCommand());
getCommand("ignores").setExecutor(new IgnoresCommand());
getCommand("local").setExecutor(new LocalCommand());
getCommand("me").setExecutor(new MeCommand());
getCommand("message").setExecutor(new MessageCommand());
getCommand("mute").setExecutor(new MuteCommand());
getCommand("muteall").setExecutor(new MuteAllCommand());
getCommand("nickname").setExecutor(new NicknameCommand());
getCommand("nicknameoff").setExecutor(new NicknameOffCommand());
getCommand("reloadchat").setExecutor(new ReloadChatCommand());
getCommand("reply").setExecutor(new ReplyCommand());
getCommand("server").setExecutor(new ServerCommand());
getCommand("tempmute").setExecutor(new TempMuteCommand());
getCommand("toggle").setExecutor(new ToggleCommand());
getCommand("unignore").setExecutor(new UnignoreCommand());
getCommand("unmute").setExecutor(new UnMuteCommand());
getCommand("unmuteall").setExecutor(new UnMuteAllCommand());
// getCommand("createchannel").setExecutor(new WhoisCommand(this));
// getCommand("deletechannel").setExecutor(new WhoisCommand(this));
// getCommand("leavechannel").setExecutor(new WhoisCommand(this));
// getCommand("joinchannel").setExecutor(new WhoisCommand(this));
// getCommand("kickchannel").setExecutor(new WhoisCommand(this));
// getCommand("formatchannel").setExecutor(new WhoisCommand(this));
// getCommand("channelinfo").setExecutor(new WhoisCommand(this));
// getCommand("setchannelowner").setExecutor(new WhoisCommand(this));
}
|
diff --git a/loci/formats/FileStitcher.java b/loci/formats/FileStitcher.java
index c1374cafb..874048bb5 100644
--- a/loci/formats/FileStitcher.java
+++ b/loci/formats/FileStitcher.java
@@ -1,780 +1,780 @@
//
// FileStitcher.java
//
/*
LOCI Bio-Formats package for reading and converting biological file formats.
Copyright (C) 2005-@year@ Melissa Linkert, Curtis Rueden, Chris Allan
and Eric Kjellman.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Library 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 Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package loci.formats;
import java.awt.image.BufferedImage;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;
/**
* Logic to stitch together files with similar names. Stitches based on the
* first series for each file, and assumes that all files have the same
* dimensions.
*/
public class FileStitcher implements IFormatReader {
// -- Fields --
/** FormatReader to use as a template for constituent readers. */
private IFormatReader reader;
/**
* Whether string ids given should be treated
* as file patterns rather than single file paths.
*/
private boolean patternIds = false;
/** Current file pattern string. */
private String currentId;
/** File pattern object used to build the list of files. */
private FilePattern fp;
/** Axis guesser object used to guess which dimensional axes are which. */
private AxisGuesser ag;
/** The matching files. */
private String[] files;
/** Reader used for each file. */
private IFormatReader[] readers;
/** Image dimensions. */
private int width, height;
/** Number of images per file. */
private int imagesPerFile;
/** Total number of image planes. */
private int totalImages;
/** Dimension order. */
private String order;
/** Dimensional axis lengths per file. */
private int sizeZ, sizeC, sizeT;
/** Total dimensional axis lengths. */
private int totalSizeZ, totalSizeC, totalSizeT;
/** Component lengths for each axis type. */
private int[] lenZ, lenC, lenT;
/** Whether or not we're doing channel stat calculation (no by default). */
protected boolean enableChannelStatCalculation = false;
/** Whether or not to ignore color tables, if present. */
protected boolean ignoreColorTable = false;
// -- Constructors --
/** Constructs a FileStitcher around a new image reader. */
public FileStitcher() { this(new ImageReader()); }
/**
* Constructs a FileStitcher with the given reader.
* @param r The reader to use for reading stitched files.
*/
public FileStitcher(IFormatReader r) { this(r, false); }
/**
* Constructs a FileStitcher with the given reader.
* @param r The reader to use for reading stitched files.
* @param patternIds Whether string ids given should be treated as file
* patterns rather than single file paths.
*/
public FileStitcher(IFormatReader r, boolean patternIds) {
reader = r;
this.patternIds = patternIds;
}
// -- FileStitcher API methods --
/**
* Gets the axis type for each dimensional block.
* @return An array containing values from the enumeration:
* <ul>
* <li>AxisGuesser.Z_AXIS: focal planes</li>
* <li>AxisGuesser.T_AXIS: time points</li>
* <li>AxisGuesser.C_AXIS: channels</li>
* </ul>
*/
public int[] getAxisTypes(String id)
throws FormatException, IOException
{
if (!id.equals(currentId)) initFile(id);
return ag.getAxisTypes();
}
/**
* Sets the axis type for each dimensional block.
* @param axes An array containing values from the enumeration:
* <ul>
* <li>AxisGuesser.Z_AXIS: focal planes</li>
* <li>AxisGuesser.T_AXIS: time points</li>
* <li>AxisGuesser.C_AXIS: channels</li>
* </ul>
*/
public void setAxisTypes(String id, int[] axes)
throws FormatException, IOException
{
if (!id.equals(currentId)) initFile(id);
ag.setAxisTypes(axes);
computeAxisLengths();
}
/** Gets the file pattern object used to build the list of files. */
public FilePattern getFilePattern(String id)
throws FormatException, IOException
{
if (!id.equals(currentId)) initFile(id);
return fp;
}
/**
* Gets the axis guesser object used to guess
* which dimensional axes are which.
*/
public AxisGuesser getAxisGuesser(String id)
throws FormatException, IOException
{
if (!id.equals(currentId)) initFile(id);
return ag;
}
// -- IFormatReader API methods --
/* @see IFormatReader#isThisType(byte[]) */
public boolean isThisType(byte[] block) {
return reader.isThisType(block);
}
/** Determines the number of images in the given file series. */
public int getImageCount(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return totalImages;
}
/** Checks if the images in the file are RGB. */
public boolean isRGB(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return reader.isRGB(files[0]);
}
/* @see IFormatReader#getSizeX(String) */
public int getSizeX(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return width;
}
/* @see IFormatReader#getSizeY(String) */
public int getSizeY(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return height;
}
/* @see IFormatReader#getSizeZ(String) */
public int getSizeZ(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return totalSizeZ;
}
/* @see IFormatReader#getSizeC(String) */
public int getSizeC(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return totalSizeC;
}
/* @see IFormatReader#getSizeT(String) */
public int getSizeT(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return totalSizeT;
}
/* @see IFormatReader#getPixelType(String) */
public int getPixelType(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return reader.getPixelType(files[0]);
}
/* @see IFormatReader#getChannelGlobalMinimum(String, int) */
public Double getChannelGlobalMinimum(String id, int theC)
throws FormatException, IOException
{
int[] include = getIncludeList(id, theC);
Double min = new Double(Double.POSITIVE_INFINITY);
for (int i=0; i<readers.length; i++) {
if (include[i] >= 0) {
Double d = readers[i].getChannelGlobalMinimum(files[i], include[i]);
if (d.compareTo(min) < 0) min = d;
}
}
return min;
}
/* @see IFormatReader#getChannelGlobalMaximum(String, int) */
public Double getChannelGlobalMaximum(String id, int theC)
throws FormatException, IOException
{
int[] include = getIncludeList(id, theC);
Double max = new Double(Double.NEGATIVE_INFINITY);
for (int i=0; i<readers.length; i++) {
if (include[i] >= 0) {
Double d = readers[i].getChannelGlobalMaximum(files[i], include[i]);
if (d.compareTo(max) > 0) max = d;
}
}
return max;
}
/* @see IFormatReader#getThumbSizeX(String) */
public int getThumbSizeX(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return reader.getThumbSizeX(files[0]);
}
/* @see IFormatReader#getThumbSizeY(String) */
public int getThumbSizeY(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return reader.getThumbSizeY(files[0]);
}
/* @see IFormatReader#isLittleEndian(String) */
public boolean isLittleEndian(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return reader.isLittleEndian(files[0]);
}
/**
* Gets a five-character string representing the
* dimension order across the file series.
*/
public String getDimensionOrder(String id)
throws FormatException, IOException
{
if (!id.equals(currentId)) initFile(id);
return order;
}
/* @see IFormatReader#isOrderCertain(String) */
public boolean isOrderCertain(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return ag.isCertain();
}
/* @see IFormatReader#setChannelStatCalculationStatus(boolean) */
public void setChannelStatCalculationStatus(boolean on) {
enableChannelStatCalculation = on;
}
/* @see IFormatReader#getChannelStatCalculationStatus */
public boolean getChannelStatCalculationStatus() {
return enableChannelStatCalculation;
}
/* @see IFormatReader#isInterleaved(String) */
public boolean isInterleaved(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return reader.isInterleaved(files[0]);
}
/** Obtains the specified image from the given file series. */
public BufferedImage openImage(String id, int no)
throws FormatException, IOException
{
int[] q = computeIndices(id, no);
int fno = q[0], ino = q[1];
return readers[fno].openImage(files[fno], ino);
//CTR TODO - come up with an API for Chris, for setting the axes for the
//various blocks (pretty easy -- just setAxisType(int num, int type) or
//something similar), and also the internal ordering within each file,
//but make it intelligible (only show the internal dimensions that actually
//have size > 1). Similar to the current VisBio API?
}
/** Obtains the specified image from the given file series as a byte array. */
public byte[] openBytes(String id, int no)
throws FormatException, IOException
{
int[] q = computeIndices(id, no);
int fno = q[0], ino = q[1];
return readers[fno].openBytes(files[fno], ino);
}
/* @see IFormatReader#openBytes(String, int, byte[]) */
public byte[] openBytes(String id, int no, byte[] buf)
throws FormatException, IOException
{
int[] q = computeIndices(id, no);
int fno = q[0], ino = q[1];
return readers[fno].openBytes(files[fno], ino, buf);
}
/* @see IFormatReader#openThumbImage(String, int) */
public BufferedImage openThumbImage(String id, int no)
throws FormatException, IOException
{
int[] q = computeIndices(id, no);
int fno = q[0], ino = q[1];
return readers[fno].openThumbImage(files[fno], ino);
}
/* @see IFormatReader#openThumbImage(String, int) */
public byte[] openThumbBytes(String id, int no)
throws FormatException, IOException
{
int[] q = computeIndices(id, no);
int fno = q[0], ino = q[1];
return readers[fno].openThumbBytes(files[fno], ino);
}
/* @see IFormatReader#close() */
public void close() throws FormatException, IOException {
if (readers != null) {
for (int i=0; i<readers.length; i++) readers[i].close();
}
readers = null;
currentId = null;
}
/* @see IFormatReader#getSeriesCount(String) */
public int getSeriesCount(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return reader.getSeriesCount(files[0]);
}
/* @see IFormatReader#setSeries(String, int) */
public void setSeries(String id, int no) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
reader.setSeries(files[0], no);
}
/* @see IFormatReader#getSeries(String) */
public int getSeries(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return reader.getSeries(files[0]);
}
/* @see IFormatReader#setIgnoreColorTable(boolean) */
public void setIgnoreColorTable(boolean ignore) {
ignoreColorTable = ignore;
}
/* @see IFormatReader#swapDimensions(String, String) */
public void swapDimensions(String id, String order)
throws FormatException, IOException
{
if (!id.equals(currentId)) initFile(id);
this.order = order;
String f0 = files[0];
reader.swapDimensions(f0, order);
sizeZ = reader.getSizeZ(f0);
sizeC = reader.getSizeC(f0);
sizeT = reader.getSizeT(f0);
computeAxisLengths();
}
/* @see IFormatReader#getIndex(String, int, int, int) */
public int getIndex(String id, int z, int c, int t)
throws FormatException, IOException
{
return FormatReader.getIndex(this, id, z, c, t);
}
/* @see IFormatReader#getZCTCoords(String, int) */
public int[] getZCTCoords(String id, int index)
throws FormatException, IOException
{
return FormatReader.getZCTCoords(this, id, index);
}
/* @see IFormatReader#getMetadataValue(String, String) */
public Object getMetadataValue(String id, String field)
throws FormatException, IOException
{
if (!id.equals(currentId)) initFile(id);
return reader.getMetadataValue(files[0], field);
}
/* @see IFormatReader#getMetadata(String) */
public Hashtable getMetadata(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return reader.getMetadata(files[0]);
}
/* @see IFormatReader#setMetadataStore(MetadataStore) */
public void setMetadataStore(MetadataStore store) {
reader.setMetadataStore(store);
}
/* @see IFormatReader#getMetadataStore(String) */
public MetadataStore getMetadataStore(String id)
throws FormatException, IOException
{
if (!id.equals(currentId)) initFile(id);
return reader.getMetadataStore(files[0]);
}
/* @see IFormatReader#getMetadataStoreRoot(String) */
public Object getMetadataStoreRoot(String id)
throws FormatException, IOException
{
if (!id.equals(currentId)) initFile(id);
return reader.getMetadataStoreRoot(files[0]);
}
/* @see IFormatReader#testRead(String[]) */
public boolean testRead(String[] args) throws FormatException, IOException {
return FormatReader.testRead(this, args);
}
// -- IFormatHandler API methods --
/* @see IFormatHandler#isThisType(String) */
public boolean isThisType(String name) {
return reader.isThisType(name);
}
/* @see IFormatHandler#isThisType(String, boolean) */
public boolean isThisType(String name, boolean open) {
return reader.isThisType(name, open);
}
/* @see IFormatHandler#getFormat() */
public String getFormat() {
return reader.getFormat();
}
/* @see IFormatHandler#getSuffixes() */
public String[] getSuffixes() {
return reader.getSuffixes();
}
/* @see IFormatHandler#getFileFilters() */
public FileFilter[] getFileFilters() {
return reader.getFileFilters();
}
/* @see IFormatHandler#getFileChooser() */
public JFileChooser getFileChooser() {
return reader.getFileChooser();
}
/* @see IFormatHandler#mapId(String, String) */
public void mapId(String id, String filename) {
// NB: all readers share the same ID map
reader.mapId(id, filename);
}
/* @see IFormatHandler#getMappedId(String) */
public String getMappedId(String id) {
return reader.getMappedId(id);
}
/* @see IFormatHandler#getIdMap() */
public Hashtable getIdMap() {
return reader.getIdMap();
}
/* @see IFormatHandler#setIdMap(Hashtable) */
public void setIdMap(Hashtable map) {
for (int i=0; i<readers.length; i++) readers[i].setIdMap(map);
}
// -- Helper methods --
/** Initializes the given file. */
protected void initFile(String id) throws FormatException, IOException {
currentId = id;
if (!patternIds) {
// find the containing pattern
Hashtable map = getIdMap();
if (map.containsKey(id)) {
// search ID map for pattern, rather than files on disk
String[] idList = new String[map.size()];
Enumeration en = map.keys();
for (int i=0; i<idList.length; i++) {
idList[i] = (String) en.nextElement();
}
id = FilePattern.findPattern(id, null, idList);
}
else {
// id is an unmapped file path; look to similar files on disk
id = FilePattern.findPattern(new File(id)); // id == getMapped(id)
}
}
fp = new FilePattern(id);
// verify that file pattern is valid and matches existing files
String msg = " Please rename your files or disable file stitching.";
if (!fp.isValid()) {
throw new FormatException("Invalid " +
(patternIds ? "file pattern" : "filename") +
" (" + currentId + "): " + fp.getErrorMessage() + msg);
}
files = fp.getFiles();
if (files == null) {
throw new FormatException("No files matching pattern (" +
fp.getPattern() + "). " + msg);
}
for (int i=0; i<files.length; i++) {
if (!new File(getMappedId(files[i])).exists()) {
throw new FormatException("File #" + i +
" (" + files[i] + ") does not exist.");
}
}
// determine reader type for these files; assume all are the same type
Vector classes = new Vector();
IFormatReader r = reader;
while (r instanceof ReaderWrapper) {
classes.add(r.getClass());
r = ((ReaderWrapper) r).getReader();
}
if (r instanceof ImageReader) r = ((ImageReader) r).getReader(files[0]);
classes.add(r.getClass());
// construct list of readers for all files
readers = new IFormatReader[files.length];
readers[0] = reader;
Hashtable map = reader.getIdMap();
for (int i=1; i<readers.length; i++) {
// use crazy reflection to instantiate a reader of the proper type
try {
r = null;
for (int j=classes.size()-1; j>=0; j--) {
Class c = (Class) classes.elementAt(j);
if (r == null) r = (IFormatReader) c.newInstance();
else {
r = (IFormatReader) c.getConstructor(
new Class[] {c}).newInstance(new Object[] {r});
}
}
readers[i] = (IFormatReader) r;
// NB: ensure all readers share the same ID map
readers[i].setIdMap(map);
}
catch (InstantiationException exc) { exc.printStackTrace(); }
catch (IllegalAccessException exc) { exc.printStackTrace(); }
catch (NoSuchMethodException exc) { exc.printStackTrace(); }
catch (InvocationTargetException exc) { exc.printStackTrace(); }
}
String f0 = files[0];
// analyze first file; assume each file has the same parameters
width = reader.getSizeX(f0);
height = reader.getSizeY(f0);
imagesPerFile = reader.getImageCount(f0);
totalImages = files.length * imagesPerFile;
order = reader.getDimensionOrder(f0);
sizeZ = reader.getSizeZ(f0);
sizeC = reader.getSizeC(f0);
sizeT = reader.getSizeT(f0);
boolean certain = reader.isOrderCertain(f0);
// guess at dimensions corresponding to file numbering
ag = new AxisGuesser(fp, order, sizeZ, sizeT, sizeC, certain);
// order may need to be adjusted
order = ag.getAdjustedOrder();
- swapDimensions(id, order);
+ swapDimensions(currentId, order);
}
/** Computes axis length arrays, and total axis lengths. */
protected void computeAxisLengths() throws FormatException, IOException {
int[] count = fp.getCount();
int[] axes = ag.getAxisTypes();
int numZ = ag.getAxisCountZ();
int numC = ag.getAxisCountC();
int numT = ag.getAxisCountT();
totalSizeZ = sizeZ;
totalSizeC = sizeC;
totalSizeT = sizeT;
lenZ = new int[numZ + 1];
lenC = new int[numC + 1];
lenT = new int[numT + 1];
lenZ[0] = sizeZ;
lenC[0] = sizeC;
lenT[0] = sizeT;
int z = 1, c = 1, t = 1;
for (int i=0; i<axes.length; i++) {
switch (axes[i]) {
case AxisGuesser.Z_AXIS:
totalSizeZ *= count[i];
lenZ[z++] = count[i];
break;
case AxisGuesser.C_AXIS:
totalSizeC *= count[i];
lenC[c++] = count[i];
break;
case AxisGuesser.T_AXIS:
totalSizeT *= count[i];
lenT[t++] = count[i];
break;
default:
throw new FormatException("Unknown axis type for axis #" +
i + ": " + axes[i]);
}
}
// populate metadata store
String f0 = files[0];
int pixelType = reader.getPixelType(f0);
boolean little = reader.isLittleEndian(f0);
MetadataStore s = reader.getMetadataStore(f0);
s.setPixels(new Integer(width), new Integer(height),
new Integer(totalSizeZ), new Integer(totalSizeC),
new Integer(totalSizeT), new Integer(pixelType),
new Boolean(!little), order, null);
}
/**
* Gets the file index, and image index into that file,
* corresponding to the given global image index.
*
* @return An array of size 2, dimensioned {file index, image index}.
*/
protected int[] computeIndices(String id, int no)
throws FormatException, IOException
{
if (!id.equals(currentId)) initFile(id);
int[] axes = ag.getAxisTypes();
int[] count = fp.getCount();
// get Z, C and T positions
int[] zct = getZCTCoords(id, no);
int[] posZ = rasterToPosition(lenZ, zct[0]);
int[] posC = rasterToPosition(lenC, zct[1]);
int[] posT = rasterToPosition(lenT, zct[2]);
// convert Z, C and T position lists into file index and image index
int[] pos = new int[axes.length];
int z = 1, c = 1, t = 1;
for (int i=0; i<axes.length; i++) {
if (axes[i] == AxisGuesser.Z_AXIS) pos[i] = posZ[z++];
else if (axes[i] == AxisGuesser.C_AXIS) pos[i] = posC[c++];
else if (axes[i] == AxisGuesser.T_AXIS) pos[i] = posT[t++];
else {
throw new FormatException("Unknown axis type for axis #" +
i + ": " + axes[i]);
}
}
int fno = positionToRaster(count, pos);
int ino = FormatReader.getIndex(order, sizeZ, sizeC, sizeT,
imagesPerFile, isRGB(id), posZ[0], posC[0], posT[0]);
// configure the reader, in case we haven't done this one yet
readers[fno].setChannelStatCalculationStatus(enableChannelStatCalculation);
readers[fno].setSeries(files[fno], reader.getSeries(files[0]));
readers[fno].setIgnoreColorTable(ignoreColorTable);
readers[fno].swapDimensions(files[fno], order);
return new int[] {fno, ino};
}
/**
* Gets a list of readers to include in relation to the given C position.
* @return Array with indices corresponding to the list of readers, and
* values indicating the internal channel index to use for that reader.
*/
protected int[] getIncludeList(String id, int theC)
throws FormatException, IOException
{
int[] include = new int[readers.length];
Arrays.fill(include, -1);
for (int t=0; t<sizeT; t++) {
for (int z=0; z<sizeZ; z++) {
int no = getIndex(id, z, theC, t);
int[] q = computeIndices(id, no);
int fno = q[0], ino = q[1];
include[fno] = ino;
}
}
return include;
}
// -- Utility methods --
/**
* Computes a unique 1-D index corresponding to the multidimensional
* position given in the pos array, using the specified lengths array
* as the maximum value at each positional dimension.
*/
public static int positionToRaster(int[] lengths, int[] pos) {
int[] offsets = new int[lengths.length];
if (offsets.length > 0) offsets[0] = 1;
for (int i=1; i<offsets.length; i++) {
offsets[i] = offsets[i - 1] * lengths[i - 1];
}
int raster = 0;
for (int i=0; i<pos.length; i++) raster += offsets[i] * pos[i];
return raster;
}
/**
* Computes a unique 3-D position corresponding to the given raster
* value, using the specified lengths array as the maximum value at
* each positional dimension.
*/
public static int[] rasterToPosition(int[] lengths, int raster) {
int[] offsets = new int[lengths.length];
if (offsets.length > 0) offsets[0] = 1;
for (int i=1; i<offsets.length; i++) {
offsets[i] = offsets[i - 1] * lengths[i - 1];
}
int[] pos = new int[lengths.length];
for (int i=0; i<pos.length; i++) {
int q = i < pos.length - 1 ? raster % offsets[i + 1] : raster;
pos[i] = q / offsets[i];
raster -= q;
}
return pos;
}
/**
* Computes the maximum raster value of a positional array with
* the given maximum values.
*/
public static int getRasterLength(int[] lengths) {
int len = 1;
for (int i=0; i<lengths.length; i++) len *= lengths[i];
return len;
}
// -- Main method --
public static void main(String[] args) throws FormatException, IOException {
if (!new FileStitcher().testRead(args)) System.exit(1);
}
}
| true | true | protected void initFile(String id) throws FormatException, IOException {
currentId = id;
if (!patternIds) {
// find the containing pattern
Hashtable map = getIdMap();
if (map.containsKey(id)) {
// search ID map for pattern, rather than files on disk
String[] idList = new String[map.size()];
Enumeration en = map.keys();
for (int i=0; i<idList.length; i++) {
idList[i] = (String) en.nextElement();
}
id = FilePattern.findPattern(id, null, idList);
}
else {
// id is an unmapped file path; look to similar files on disk
id = FilePattern.findPattern(new File(id)); // id == getMapped(id)
}
}
fp = new FilePattern(id);
// verify that file pattern is valid and matches existing files
String msg = " Please rename your files or disable file stitching.";
if (!fp.isValid()) {
throw new FormatException("Invalid " +
(patternIds ? "file pattern" : "filename") +
" (" + currentId + "): " + fp.getErrorMessage() + msg);
}
files = fp.getFiles();
if (files == null) {
throw new FormatException("No files matching pattern (" +
fp.getPattern() + "). " + msg);
}
for (int i=0; i<files.length; i++) {
if (!new File(getMappedId(files[i])).exists()) {
throw new FormatException("File #" + i +
" (" + files[i] + ") does not exist.");
}
}
// determine reader type for these files; assume all are the same type
Vector classes = new Vector();
IFormatReader r = reader;
while (r instanceof ReaderWrapper) {
classes.add(r.getClass());
r = ((ReaderWrapper) r).getReader();
}
if (r instanceof ImageReader) r = ((ImageReader) r).getReader(files[0]);
classes.add(r.getClass());
// construct list of readers for all files
readers = new IFormatReader[files.length];
readers[0] = reader;
Hashtable map = reader.getIdMap();
for (int i=1; i<readers.length; i++) {
// use crazy reflection to instantiate a reader of the proper type
try {
r = null;
for (int j=classes.size()-1; j>=0; j--) {
Class c = (Class) classes.elementAt(j);
if (r == null) r = (IFormatReader) c.newInstance();
else {
r = (IFormatReader) c.getConstructor(
new Class[] {c}).newInstance(new Object[] {r});
}
}
readers[i] = (IFormatReader) r;
// NB: ensure all readers share the same ID map
readers[i].setIdMap(map);
}
catch (InstantiationException exc) { exc.printStackTrace(); }
catch (IllegalAccessException exc) { exc.printStackTrace(); }
catch (NoSuchMethodException exc) { exc.printStackTrace(); }
catch (InvocationTargetException exc) { exc.printStackTrace(); }
}
String f0 = files[0];
// analyze first file; assume each file has the same parameters
width = reader.getSizeX(f0);
height = reader.getSizeY(f0);
imagesPerFile = reader.getImageCount(f0);
totalImages = files.length * imagesPerFile;
order = reader.getDimensionOrder(f0);
sizeZ = reader.getSizeZ(f0);
sizeC = reader.getSizeC(f0);
sizeT = reader.getSizeT(f0);
boolean certain = reader.isOrderCertain(f0);
// guess at dimensions corresponding to file numbering
ag = new AxisGuesser(fp, order, sizeZ, sizeT, sizeC, certain);
// order may need to be adjusted
order = ag.getAdjustedOrder();
swapDimensions(id, order);
}
| protected void initFile(String id) throws FormatException, IOException {
currentId = id;
if (!patternIds) {
// find the containing pattern
Hashtable map = getIdMap();
if (map.containsKey(id)) {
// search ID map for pattern, rather than files on disk
String[] idList = new String[map.size()];
Enumeration en = map.keys();
for (int i=0; i<idList.length; i++) {
idList[i] = (String) en.nextElement();
}
id = FilePattern.findPattern(id, null, idList);
}
else {
// id is an unmapped file path; look to similar files on disk
id = FilePattern.findPattern(new File(id)); // id == getMapped(id)
}
}
fp = new FilePattern(id);
// verify that file pattern is valid and matches existing files
String msg = " Please rename your files or disable file stitching.";
if (!fp.isValid()) {
throw new FormatException("Invalid " +
(patternIds ? "file pattern" : "filename") +
" (" + currentId + "): " + fp.getErrorMessage() + msg);
}
files = fp.getFiles();
if (files == null) {
throw new FormatException("No files matching pattern (" +
fp.getPattern() + "). " + msg);
}
for (int i=0; i<files.length; i++) {
if (!new File(getMappedId(files[i])).exists()) {
throw new FormatException("File #" + i +
" (" + files[i] + ") does not exist.");
}
}
// determine reader type for these files; assume all are the same type
Vector classes = new Vector();
IFormatReader r = reader;
while (r instanceof ReaderWrapper) {
classes.add(r.getClass());
r = ((ReaderWrapper) r).getReader();
}
if (r instanceof ImageReader) r = ((ImageReader) r).getReader(files[0]);
classes.add(r.getClass());
// construct list of readers for all files
readers = new IFormatReader[files.length];
readers[0] = reader;
Hashtable map = reader.getIdMap();
for (int i=1; i<readers.length; i++) {
// use crazy reflection to instantiate a reader of the proper type
try {
r = null;
for (int j=classes.size()-1; j>=0; j--) {
Class c = (Class) classes.elementAt(j);
if (r == null) r = (IFormatReader) c.newInstance();
else {
r = (IFormatReader) c.getConstructor(
new Class[] {c}).newInstance(new Object[] {r});
}
}
readers[i] = (IFormatReader) r;
// NB: ensure all readers share the same ID map
readers[i].setIdMap(map);
}
catch (InstantiationException exc) { exc.printStackTrace(); }
catch (IllegalAccessException exc) { exc.printStackTrace(); }
catch (NoSuchMethodException exc) { exc.printStackTrace(); }
catch (InvocationTargetException exc) { exc.printStackTrace(); }
}
String f0 = files[0];
// analyze first file; assume each file has the same parameters
width = reader.getSizeX(f0);
height = reader.getSizeY(f0);
imagesPerFile = reader.getImageCount(f0);
totalImages = files.length * imagesPerFile;
order = reader.getDimensionOrder(f0);
sizeZ = reader.getSizeZ(f0);
sizeC = reader.getSizeC(f0);
sizeT = reader.getSizeT(f0);
boolean certain = reader.isOrderCertain(f0);
// guess at dimensions corresponding to file numbering
ag = new AxisGuesser(fp, order, sizeZ, sizeT, sizeC, certain);
// order may need to be adjusted
order = ag.getAdjustedOrder();
swapDimensions(currentId, order);
}
|
diff --git a/src/main/java/org/atlasapi/search/AtlasSearchModule.java b/src/main/java/org/atlasapi/search/AtlasSearchModule.java
index aaaa361..3261527 100644
--- a/src/main/java/org/atlasapi/search/AtlasSearchModule.java
+++ b/src/main/java/org/atlasapi/search/AtlasSearchModule.java
@@ -1,80 +1,82 @@
package org.atlasapi.search;
import com.google.common.base.Splitter;
import org.atlasapi.persistence.content.mongo.MongoContentLister;
import org.atlasapi.persistence.content.mongo.MongoContentResolver;
import org.atlasapi.persistence.content.mongo.MongoPersonStore;
import org.atlasapi.search.searcher.LuceneSearcherProbe;
import org.atlasapi.search.searcher.ReloadingContentSearcher;
import org.atlasapi.search.view.JsonSearchResultsView;
import org.atlasapi.search.www.HealthController;
import org.atlasapi.search.www.WebAwareModule;
import org.springframework.context.annotation.Bean;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.metabroadcast.common.health.HealthProbe;
import com.metabroadcast.common.persistence.mongo.DatabasedMongo;
import com.metabroadcast.common.properties.Configurer;
import com.mongodb.Mongo;
import java.io.File;
import org.atlasapi.persistence.content.cassandra.CassandraContentStore;
import org.atlasapi.search.loader.ContentBootstrapper;
import org.atlasapi.search.searcher.LuceneContentSearcher;
public class AtlasSearchModule extends WebAwareModule {
private final String mongoHost = Configurer.get("mongo.host").get();
private final String mongoDbName = Configurer.get("mongo.dbName").get();
private final String cassandraSeeds = Configurer.get("cassandra.seeds").get();
private final String cassandraPort = Configurer.get("cassandra.port").get();
private final String cassandraConnectionTimeout = Configurer.get("cassandra.connectionTimeout").get();
private final String cassandraRequestTimeout = Configurer.get("cassandra.requestTimeout").get();
private final String luceneDir = Configurer.get("lucene.contentDir").get();
private final String enablePeople = Configurer.get("people.enabled").get();
@Override
public void configure() {
MongoContentResolver contentResolver = new MongoContentResolver(mongo());
ReloadingContentSearcher lucene = new ReloadingContentSearcher(new LuceneContentSearcher(new File(luceneDir), contentResolver), bootstrapper());
bind("/health", new HealthController(ImmutableList.<HealthProbe>of(new LuceneSearcherProbe(lucene))));
bind("/titles", new SearchServlet(new JsonSearchResultsView(), lucene));
lucene.start();
}
@Bean
ContentBootstrapper bootstrapper() {
ContentBootstrapper bootstrapper = new ContentBootstrapper();
bootstrapper.withContentListers(new MongoContentLister(mongo()), cassandra());
if (Boolean.valueOf(enablePeople)) {
bootstrapper.withPeopleListers(new MongoPersonStore(mongo()));
}
return bootstrapper;
}
public @Bean DatabasedMongo mongo() {
try {
Mongo mongo = new Mongo(mongoHost);
mongo.slaveOk();
return new DatabasedMongo(mongo, mongoDbName);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public @Bean CassandraContentStore cassandra() {
try {
- return new CassandraContentStore(Lists.newArrayList(Splitter.on(',').split(cassandraSeeds)),
+ CassandraContentStore cassandraContentStore = new CassandraContentStore(Lists.newArrayList(Splitter.on(',').split(cassandraSeeds)),
Integer.parseInt(cassandraPort),
Runtime.getRuntime().availableProcessors() * 10,
Integer.parseInt(cassandraConnectionTimeout),
Integer.parseInt(cassandraRequestTimeout));
+ cassandraContentStore.init();
+ return cassandraContentStore;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
| false | true | public @Bean CassandraContentStore cassandra() {
try {
return new CassandraContentStore(Lists.newArrayList(Splitter.on(',').split(cassandraSeeds)),
Integer.parseInt(cassandraPort),
Runtime.getRuntime().availableProcessors() * 10,
Integer.parseInt(cassandraConnectionTimeout),
Integer.parseInt(cassandraRequestTimeout));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
| public @Bean CassandraContentStore cassandra() {
try {
CassandraContentStore cassandraContentStore = new CassandraContentStore(Lists.newArrayList(Splitter.on(',').split(cassandraSeeds)),
Integer.parseInt(cassandraPort),
Runtime.getRuntime().availableProcessors() * 10,
Integer.parseInt(cassandraConnectionTimeout),
Integer.parseInt(cassandraRequestTimeout));
cassandraContentStore.init();
return cassandraContentStore;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
|
diff --git a/src/Roma/Cards/CardHolder.java b/src/Roma/Cards/CardHolder.java
index 4c4acf2..f5ea346 100644
--- a/src/Roma/Cards/CardHolder.java
+++ b/src/Roma/Cards/CardHolder.java
@@ -1,106 +1,106 @@
package Roma.Cards;
import Roma.Player;
import Roma.PlayerInterfaceFiles.CancelAction;
/**
* Created with IntelliJ IDEA.
* User: Andrew
* Date: 9/05/12
* Time: 6:26 PM
* To change this template use File | Settings | File Templates.
*/
public class CardHolder implements Card{
private final boolean isWrapper = false;
private boolean playable = false;
private Card contents;
public CardHolder(Card card){
contents = card;
}
public void setPlayable(boolean playable){
this.playable = playable;
}
public boolean getPlayable(){
return playable;
}
public Card getContents(){
return contents;
}
public void setContents(Card contents) {
this.contents = contents;
}
public Card getContainer(){
return null;
}
public void setContainer(Card holder){
assert false;
}
public boolean isActivateEnabled() {
return contents.isActivateEnabled();
}
public String getName() {
return contents.getName();
}
public String getType() {
return contents.getType();
}
public String getDescription() {
return contents.getDescription();
}
public int getCost() {
return contents.getCost();
}
public int getDefense() {
return contents.getDefense();
}
public boolean isWrapper() {
return isWrapper();
}
public String toString() {
return "Card Name: " + getName() + "; Type: " + getType() +
"\nDescription: " + getDescription() +
"\nCost: " + getCost() + "; Defence: " + getDefense();
}
@Override
public void gatherData(Player player, int position) throws CancelAction {
contents.gatherData(player, position);
}
@Override
public void activate(Player player, int position) {
contents.activate(player, position);
}
@Override
public void enterPlay(Player player, int position) {
contents.enterPlay(player, position);
}
@Override
public void leavePlay() {
Wrapper wrapper;
//remove all wrappers
- while(!contents.isWrapper()){
+ while(contents.isWrapper()){
wrapper = (Wrapper) contents;
wrapper.deleteThisWrapper();
}
contents.leavePlay();
}
}
| true | true | public void leavePlay() {
Wrapper wrapper;
//remove all wrappers
while(!contents.isWrapper()){
wrapper = (Wrapper) contents;
wrapper.deleteThisWrapper();
}
contents.leavePlay();
}
| public void leavePlay() {
Wrapper wrapper;
//remove all wrappers
while(contents.isWrapper()){
wrapper = (Wrapper) contents;
wrapper.deleteThisWrapper();
}
contents.leavePlay();
}
|
diff --git a/tool/src/java/org/sakaiproject/cheftool/ToolServlet.java b/tool/src/java/org/sakaiproject/cheftool/ToolServlet.java
index e05b6d6..7696c4f 100644
--- a/tool/src/java/org/sakaiproject/cheftool/ToolServlet.java
+++ b/tool/src/java/org/sakaiproject/cheftool/ToolServlet.java
@@ -1,593 +1,593 @@
/**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2003, 2004, 2005, 2006 The Sakai Foundation.
*
* Licensed under the Educational Community License, Version 1.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.opensource.org/licenses/ecl1.php
*
* 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.sakaiproject.cheftool;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.cheftool.api.Alert;
import org.sakaiproject.cheftool.api.Menu;
import org.sakaiproject.cheftool.menu.MenuImpl;
import org.sakaiproject.event.api.SessionState;
import org.sakaiproject.event.cover.UsageSessionService;
import org.sakaiproject.tool.api.ActiveTool;
import org.sakaiproject.tool.api.Session;
import org.sakaiproject.tool.api.Tool;
import org.sakaiproject.tool.api.ToolException;
import org.sakaiproject.tool.api.ToolSession;
import org.sakaiproject.tool.cover.ActiveToolManager;
import org.sakaiproject.tool.cover.SessionManager;
import org.sakaiproject.tool.cover.ToolManager;
import org.sakaiproject.util.ParameterParser;
import org.sakaiproject.vm.ActionURL;
/**
* <p>
* ToolServlet is a Servlet that support CHEF tools.
* </p>
* <p>
* Extending VmServlet provides support for component location and use of the Velocity Template Engine.
* </p>
*/
public abstract class ToolServlet extends VmServlet
{
/** Our logger. */
private static Log M_log = LogFactory.getLog(ToolServlet.class);
/** ToolSession attribute name holding the helper id, if we are in helper mode. NOTE: promote to Tool -ggolden */
protected static final String HELPER_ID = "sakai.tool.helper.id";
/**
* Add some standard references to the vm context.
*
* @param request
* The render request.
* @param response
* The render response.
*/
protected void setVmStdRef(HttpServletRequest request, HttpServletResponse response)
{
super.setVmStdRef(request, response);
// add the tool mode
setVmReference("sakai_toolMode", getToolMode(request), request);
// add alert
setVmReference("sakai_alert", getAlert(request), request);
// add menu
setVmReference("sakai_menu", getMenu(request), request);
} // setVmStdRef
/**********************************************************************************************************************************************************************************************************************************************************
* tool mode support ******************************************************************************* Tool mode is stored in the servlet session state.
*********************************************************************************************************************************************************************************************************************************************************/
/** The mode value when no mode has been set. */
protected final String TOOL_MODE_DEFAULT = "Default";
/** The mode attribute name base - postfix with the portlet mode. */
protected final String TOOL_MODE_ATTR = "sakai.toolMode";
/** The special panel name for the title. */
protected final String TITLE_PANEL = "Title";
/** The special panel name for the main. */
protected final String MAIN_PANEL = "Main";
/**
* Set the tool mode.
*
* @param toolMode
* The new tool mode.
* @param req
* The portlet request.
*/
protected void setToolMode(String toolMode, HttpServletRequest req)
{
// update the attribute in session state
getState(req).setAttribute(TOOL_MODE_ATTR, toolMode);
} // setToolMode
/**
* Access the tool mode for the current Portlet mode.
*
* @return the tool mode for the current Portlet mode.
* @param req
* The portlet request.
*/
protected String getToolMode(HttpServletRequest req)
{
String toolMode = (String) getState(req).getAttribute(TOOL_MODE_ATTR);
// use the default mode if nothing set
if (toolMode == null)
{
toolMode = TOOL_MODE_DEFAULT;
}
return toolMode;
} // getToolMode
/**
* Respond to a request by dispatching to a portlet like "do" method based on the portlet mode and tool mode
*/
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException
{
doGet(req, res);
} // doPost
/**
* Respond to a request by dispatching to a portlet like "do" method based on the portlet mode and tool mode
*/
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException
{
// get the panel
String panel = ((ParameterParser) req.getAttribute(ATTR_PARAMS)).getString(ActionURL.PARAM_PANEL);
if (panel == null) panel = MAIN_PANEL;
// HELPER_ID needs the panel appended
String helperId = HELPER_ID + panel;
// detect a helper done
ToolSession toolSession = SessionManager.getCurrentToolSession();
String helper = ((ParameterParser) req.getAttribute(ATTR_PARAMS)).getString(helperId);
if (helper != null)
{
// clear our helper id indicator from session
toolSession.removeAttribute(helperId);
// redirect to the same URL w/o the helper done indication, otherwise this is left in the browser and can be re-processed later
String newUrl = req.getContextPath() + req.getServletPath() + (req.getPathInfo() == null ? "" : req.getPathInfo()) + "?" + ActionURL.PARAM_PANEL + "=" + panel;
try
{
res.sendRedirect(newUrl);
}
catch (IOException e)
{
M_log.warn("redirecting after helper done detection to: " + newUrl + " : " + e.toString());
}
return;
}
// get the sakai.tool.helper.id helper id from the tool session
// if defined and it's not our tool id, we need to defer to the helper
helper = (String) toolSession.getAttribute(helperId);
Tool me = ToolManager.getCurrentTool();
if ((helper != null) && (!helper.equals(me.getId())))
{
// map the request to the helper
ActiveTool tool = ActiveToolManager.getActiveTool(helper);
- String context = req.getContextPath() + req.getServletPath() + (req.getPathInfo() == null ? "" : req.getPathInfo());
- String toolPath = "";
+ String context = req.getContextPath() + req.getServletPath();
+ String toolPath = req.getPathInfo() == null ? "/" : req.getPathInfo();
tool.help(req, res, context, toolPath);
return;
}
// init or update the session state
prepState(req, res);
// see if there's an action to process
processAction(req, res);
// if not redirected
if (!res.isCommitted())
{
// dispatch
toolModeDispatch("doView", getToolMode(req), req, res);
}
} // doGet
/**
* Setup for a helper tool - all subsequent requests will be directed there, till the tool is done.
*
* @param helperId
* The helper tool id.
*/
protected void startHelper(HttpServletRequest req, String helperId, String panel)
{
if (panel == null) panel = MAIN_PANEL;
ToolSession toolSession = SessionManager.getCurrentToolSession();
toolSession.setAttribute(HELPER_ID + panel, helperId);
// the done URL - this url and the extra parameter to indicate done
// also make sure the panel is indicated - assume that it needs to be main, assuming that helpers are taking over the entire tool response
String doneUrl = req.getContextPath() + req.getServletPath() + (req.getPathInfo() == null ? "" : req.getPathInfo()) + "?"
+ HELPER_ID + panel + "=done" + "&" + ActionURL.PARAM_PANEL + "=" + panel;
toolSession.setAttribute(helperId + Tool.HELPER_DONE_URL, doneUrl);
}
/**
* Setup for a helper tool - all subsequent requests will be directed there, till the tool is done.
*
* @param helperId
* The helper tool id.
*/
protected void startHelper(HttpServletRequest req, String helperId)
{
startHelper(req, helperId, MAIN_PANEL);
}
/**
* Dispatch to a "do" method based on reflection.
*
* @param methodBase
* The base name of the method to call.
* @param methodExt
* The end name of the method to call.
* @param req
* The HttpServletRequest.
* @param res
* The HttpServletResponse
* @throws PortletExcption,
* IOException, just like the "do" methods.
*/
protected void toolModeDispatch(String methodBase, String methodExt, HttpServletRequest req, HttpServletResponse res)
throws ToolException
{
String methodName = null;
try
{
// the method signature
Class[] signature = new Class[2];
signature[0] = HttpServletRequest.class;
signature[1] = HttpServletResponse.class;
// the method name
methodName = methodBase + methodExt;
// find a method of this class with this name and signature
Method method = getClass().getMethod(methodName, signature);
// the parameters
Object[] args = new Object[2];
args[0] = req;
args[1] = res;
// make the call
method.invoke(this, args);
}
catch (NoSuchMethodException e)
{
throw new ToolException(e);
}
catch (IllegalAccessException e)
{
throw new ToolException(e);
}
catch (InvocationTargetException e)
{
throw new ToolException(e);
}
} // toolModeDispatch
/**********************************************************************************************************************************************************************************************************************************************************
* action model support ******************************************************************************* Dispatch by reflection to the method named in the value of the "sakai_action" parameter. Option to use "sakai_action_ACTION" to dispatch to ACTION.
*********************************************************************************************************************************************************************************************************************************************************/
/** The request parameter name root that has the action name following. */
protected final static String PARAM_ACTION_COMBO = "sakai_action_";
/** The request parameter name whose value is the action. */
protected final static String PARAM_ACTION = "sakai_action";
/**
* Process a Portlet action.
*/
protected void processAction(HttpServletRequest req, HttpServletResponse res)
{
// see if there's an action parameter, whose value has the action to use
String action = ((ParameterParser) req.getAttribute(ATTR_PARAMS)).getString(PARAM_ACTION);
// if that's not present, see if there's a combination name with the action encoded in the name
if (action == null)
{
Enumeration names = req.getParameterNames();
while (names.hasMoreElements())
{
String name = (String) names.nextElement();
if (name.startsWith(PARAM_ACTION_COMBO))
{
action = name.substring(PARAM_ACTION_COMBO.length());
break;
}
}
}
// process the action if present
if (action != null)
{
actionDispatch("processAction", action, req, res);
}
} // processAction
/**
* Dispatch to a "processAction" method based on reflection.
*
* @param methodBase
* The base name of the method to call.
* @param methodExt
* The end name of the method to call.
* @param req
* The ActionRequest.
* @param res
* The ActionResponse
* @throws PortletExcption,
* IOException, just like the "do" methods.
*/
protected void actionDispatch(String methodBase, String methodExt, HttpServletRequest req, HttpServletResponse res)
{
String methodName = null;
try
{
// the method signature
Class[] signature = new Class[2];
signature[0] = HttpServletRequest.class;
signature[1] = HttpServletResponse.class;
// the method name
methodName = methodBase + methodExt;
// find a method of this class with this name and signature
Method method = getClass().getMethod(methodName, signature);
// the parameters
Object[] args = new Object[2];
args[0] = req;
args[1] = res;
// make the call
method.invoke(this, args);
}
catch (NoSuchMethodException e)
{
getServletContext().log("Exception calling method " + methodName + " " + e);
}
catch (IllegalAccessException e)
{
getServletContext().log("Exception calling method " + methodName + " " + e);
}
catch (InvocationTargetException e)
{
String xtra = "";
if (e.getCause() != null) xtra = " (Caused by " + e.getCause() + ")";
getServletContext().log("Exception calling method " + methodName + " " + e + xtra);
}
} // actionDispatch
/**********************************************************************************************************************************************************************************************************************************************************
* session state support ******************************************************************************* SessionState is a cover for the portlet's attributes in the session. Attributes are those that are portlet scoped. Attributes names are protected
* with a namespace.
*********************************************************************************************************************************************************************************************************************************************************/
/** The state attribute name used to store the marker of have been initialized. */
protected static final String ALERT_STATE_INITED = "sakai.inited";
/**
* Access the "pid" - portlet window id, tool id, from the request
*
* @param req
* The current request.
* @return the "pid" - portlet window id, tool id, from the request
*/
protected String getPid(HttpServletRequest req)
{
String pid = (String) req.getAttribute(Tool.PLACEMENT_ID);
return pid;
}
/**
* Access the SessionState for the current request. Note: this is scoped only for the current request.
*
* @param req
* The current portlet request.
* @return The SessionState objet for the current request.
*/
protected SessionState getState(HttpServletRequest req)
{
// key the state based on the pid, if present. If not we will use the servlet's class name
String key = getPid(req);
if (key == null)
{
key = this.toString() + ".";
M_log.warn("getState(): using servlet key: " + key);
}
SessionState rv = UsageSessionService.getSessionState(key);
if (rv == null)
{
M_log.warn("getState(): no state found for key: " + key + " " + req.getPathInfo() + " " + req.getQueryString() + " "
+ req.getRequestURI());
}
return rv;
}
/**
* Prepare state, either for first time or update
*
* @param req
* The current portlet request.
* @param res
* The current response.
*/
protected void prepState(HttpServletRequest req, HttpServletResponse res)
{
SessionState state = getState(req);
// If two requests from the same session to the same tool (pid) come in at the same time, we might
// get two threads in here doing initState() at once, which would not be good.
// We need to sync. on something... but we have no object that maps to a session/tool instance
// (state is a cover freshly created each time)
// lets try to sync on the Sakai session. That's more than we need but not too bad. -ggolden
Session session = SessionManager.getCurrentSession();
synchronized (session)
{
// if this is the first time, init it
if (state.getAttribute(ALERT_STATE_INITED) == null)
{
initState(state, req, res);
// mark this state as initialized
state.setAttribute(ALERT_STATE_INITED, new Boolean(true));
}
// othewise update it
else
{
updateState(state, req, res);
}
}
} // initState
/**
* Initialize for the first time the session state for this session. If overridden in a sub-class, make sure to call super.
*
* @param state
* The session state.
* @param req
* The current request.
* @param res
* The current response.
*/
protected void initState(SessionState state, HttpServletRequest req, HttpServletResponse res)
{
}
/**
* Update for this request processing the session state. If overridden in a sub-class, make sure to call super.
*
* @param state
* The session state.
* @param req
* The current request.
* @param res
* The current response.
*/
protected void updateState(SessionState state, HttpServletRequest req, HttpServletResponse res)
{
}
/**********************************************************************************************************************************************************************************************************************************************************
* alert support ******************************************************************************* Alerts are messages displayed to the user in the portlet output in a standard way. Alerts are added as needed. The Alert text reference is placed into the
* velocity context, and then cleared.
*********************************************************************************************************************************************************************************************************************************************************/
/** The state attribute name used to store the Alert. */
protected static final String ALERT_ATTR = "sakai.alert";
/**
* Access the Alert for the current request.
*
* @param req
* The current portlet request.
* @return The Alert objet for the current request.
*/
protected Alert getAlert(HttpServletRequest req)
{
// find the alert in state, if it's not there, make it.
SessionState state = getState(req);
Alert alert = (Alert) state.getAttribute(ALERT_ATTR);
if (alert == null)
{
alert = new AlertImpl();
state.setAttribute(ALERT_ATTR, alert);
}
return alert;
} // getAlert
/**
* Access the Alert in this state - will create one if needed.
*
* @param state
* The state in which to find the alert.
* @return The Alert objet.
*/
protected Alert getAlert(SessionState state)
{
// find the alert in state, if it's not there, make it.
Alert alert = (Alert) state.getAttribute(ALERT_ATTR);
if (alert == null)
{
alert = new AlertImpl();
state.setAttribute(ALERT_ATTR, alert);
}
return alert;
} // getAlert
/**********************************************************************************************************************************************************************************************************************************************************
* menu support ******************************************************************************* Menus are sets of commands to be displayed in the user interface.
*********************************************************************************************************************************************************************************************************************************************************/
/** The state attribute name used to store the Menu. */
protected static final String MENU_ATTR = "sakai.menu";
/**
* Access the Menu for the current request.
*
* @param req
* The current portlet request.
* @return The Menu objet for the current request.
*/
protected Menu getMenu(HttpServletRequest req)
{
// find the menu in state, if it's not there, make it.
SessionState state = getState(req);
Menu menu = (Menu) state.getAttribute(MENU_ATTR);
if (menu == null)
{
menu = new MenuImpl();
state.setAttribute(MENU_ATTR, menu);
}
return menu;
} // getMenu
} // class ToolServlet
| true | true | protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException
{
// get the panel
String panel = ((ParameterParser) req.getAttribute(ATTR_PARAMS)).getString(ActionURL.PARAM_PANEL);
if (panel == null) panel = MAIN_PANEL;
// HELPER_ID needs the panel appended
String helperId = HELPER_ID + panel;
// detect a helper done
ToolSession toolSession = SessionManager.getCurrentToolSession();
String helper = ((ParameterParser) req.getAttribute(ATTR_PARAMS)).getString(helperId);
if (helper != null)
{
// clear our helper id indicator from session
toolSession.removeAttribute(helperId);
// redirect to the same URL w/o the helper done indication, otherwise this is left in the browser and can be re-processed later
String newUrl = req.getContextPath() + req.getServletPath() + (req.getPathInfo() == null ? "" : req.getPathInfo()) + "?" + ActionURL.PARAM_PANEL + "=" + panel;
try
{
res.sendRedirect(newUrl);
}
catch (IOException e)
{
M_log.warn("redirecting after helper done detection to: " + newUrl + " : " + e.toString());
}
return;
}
// get the sakai.tool.helper.id helper id from the tool session
// if defined and it's not our tool id, we need to defer to the helper
helper = (String) toolSession.getAttribute(helperId);
Tool me = ToolManager.getCurrentTool();
if ((helper != null) && (!helper.equals(me.getId())))
{
// map the request to the helper
ActiveTool tool = ActiveToolManager.getActiveTool(helper);
String context = req.getContextPath() + req.getServletPath() + (req.getPathInfo() == null ? "" : req.getPathInfo());
String toolPath = "";
tool.help(req, res, context, toolPath);
return;
}
// init or update the session state
prepState(req, res);
// see if there's an action to process
processAction(req, res);
// if not redirected
if (!res.isCommitted())
{
// dispatch
toolModeDispatch("doView", getToolMode(req), req, res);
}
} // doGet
| protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException
{
// get the panel
String panel = ((ParameterParser) req.getAttribute(ATTR_PARAMS)).getString(ActionURL.PARAM_PANEL);
if (panel == null) panel = MAIN_PANEL;
// HELPER_ID needs the panel appended
String helperId = HELPER_ID + panel;
// detect a helper done
ToolSession toolSession = SessionManager.getCurrentToolSession();
String helper = ((ParameterParser) req.getAttribute(ATTR_PARAMS)).getString(helperId);
if (helper != null)
{
// clear our helper id indicator from session
toolSession.removeAttribute(helperId);
// redirect to the same URL w/o the helper done indication, otherwise this is left in the browser and can be re-processed later
String newUrl = req.getContextPath() + req.getServletPath() + (req.getPathInfo() == null ? "" : req.getPathInfo()) + "?" + ActionURL.PARAM_PANEL + "=" + panel;
try
{
res.sendRedirect(newUrl);
}
catch (IOException e)
{
M_log.warn("redirecting after helper done detection to: " + newUrl + " : " + e.toString());
}
return;
}
// get the sakai.tool.helper.id helper id from the tool session
// if defined and it's not our tool id, we need to defer to the helper
helper = (String) toolSession.getAttribute(helperId);
Tool me = ToolManager.getCurrentTool();
if ((helper != null) && (!helper.equals(me.getId())))
{
// map the request to the helper
ActiveTool tool = ActiveToolManager.getActiveTool(helper);
String context = req.getContextPath() + req.getServletPath();
String toolPath = req.getPathInfo() == null ? "/" : req.getPathInfo();
tool.help(req, res, context, toolPath);
return;
}
// init or update the session state
prepState(req, res);
// see if there's an action to process
processAction(req, res);
// if not redirected
if (!res.isCommitted())
{
// dispatch
toolModeDispatch("doView", getToolMode(req), req, res);
}
} // doGet
|
diff --git a/src/gov/nih/nci/nautilus/resultset/filter/CopyNumberFilter.java b/src/gov/nih/nci/nautilus/resultset/filter/CopyNumberFilter.java
index ff6bd3f9..38a7f3a1 100755
--- a/src/gov/nih/nci/nautilus/resultset/filter/CopyNumberFilter.java
+++ b/src/gov/nih/nci/nautilus/resultset/filter/CopyNumberFilter.java
@@ -1,123 +1,123 @@
package gov.nih.nci.nautilus.resultset.filter;
import gov.nih.nci.nautilus.query.OperatorType;
import gov.nih.nci.nautilus.resultset.DimensionalViewContainer;
import gov.nih.nci.nautilus.resultset.Resultant;
import gov.nih.nci.nautilus.resultset.ResultsContainer;
import gov.nih.nci.nautilus.resultset.copynumber.CopyNumberSingleViewResultsContainer;
import gov.nih.nci.nautilus.resultset.copynumber.CytobandResultset;
import gov.nih.nci.nautilus.resultset.copynumber.SampleCopyNumberValuesResultset;
import gov.nih.nci.nautilus.resultset.sample.SampleResultset;
import gov.nih.nci.nautilus.resultset.sample.SampleViewResultsContainer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import org.apache.log4j.Logger;
public class CopyNumberFilter {
static Logger logger = Logger.getLogger(CopyNumberFilter.class);
public static Collection filterCopyNumber(Resultant resultant,
Integer noOfConsectiveCalls, Integer percentCall,
OperatorType operator) {
List sampleIDs = new ArrayList();
if (resultant != null) {
ResultsContainer resultsContainer = resultant.getResultsContainer();
List reporterNames;
//Get the samples from the resultset object
if (resultsContainer != null) {
Collection samples = null;
CopyNumberSingleViewResultsContainer copyNumberContainer = null;
SampleViewResultsContainer sampleViewContainer = null;
if (resultsContainer instanceof DimensionalViewContainer) {
DimensionalViewContainer dimensionalViewContainer = (DimensionalViewContainer) resultsContainer;
sampleViewContainer = dimensionalViewContainer.getSampleViewResultsContainer();
copyNumberContainer = dimensionalViewContainer.getCopyNumberSingleViewContainer();
samples = sampleViewContainer.getBioSpecimenResultsets();
}
if (copyNumberContainer != null && samples != null
&& samples.size() > 0) {
reporterNames = copyNumberContainer.getReporterNames();
for (Iterator sampleIterator = samples.iterator(); sampleIterator.hasNext();) {
SampleResultset sampleResultset = (SampleResultset) sampleIterator.next();
if (processCopyNumberFilterPerSample(sampleResultset,reporterNames, noOfConsectiveCalls, percentCall, operator)) {
logger.debug(sampleResultset.getBiospecimen().getValue() + "\t"+ "TRUE");
sampleIDs.add(sampleResultset.getBiospecimen().getValue().toString());
}
else{
logger.debug(sampleResultset.getBiospecimen().getValue() + "\t"+ "FALSE");
}
}
}
}
}
return sampleIDs;
}
private static boolean processCopyNumberFilterPerSample(
SampleResultset sampleResultset, List reporterNames, Integer noOfConsectiveCalls, Integer percentCall,OperatorType operator ) {
- int totalCalls = 0;
+ float totalCalls = 0;
int consectiveCalls = 0;
boolean isConsectiveCall = false;
boolean isPercentCall = false;
if (sampleResultset.getCopyNumberSingleViewResultsContainer() != null
&& reporterNames != null) {
CopyNumberSingleViewResultsContainer copyNumberContainer = sampleResultset.getCopyNumberSingleViewResultsContainer();
String sampleId = sampleResultset.getBiospecimen().getValue()
.toString();
Collection cytobands = copyNumberContainer.getCytobandResultsets();
Collection labels = copyNumberContainer.getGroupsLabels();
for (Iterator cytobandIterator = cytobands.iterator(); cytobandIterator.hasNext();) {
CytobandResultset cytobandResultset = (CytobandResultset) cytobandIterator.next();
String cytoband = cytobandResultset.getCytoband().getValue().toString();
for (Iterator labelIterator = labels.iterator(); labelIterator.hasNext();) {
String label = (String) labelIterator.next();
for (Iterator reporterIterator = reporterNames.iterator(); reporterIterator.hasNext();) {
String reporterName = (String) reporterIterator.next();
SampleCopyNumberValuesResultset copyNumberValuesResultset = copyNumberContainer.
getSampleCopyNumberValuesResultsets(cytoband,
reporterName, label, sampleId);
if (copyNumberValuesResultset != null && copyNumberValuesResultset.getCopyNumber() != null) {
consectiveCalls++;
totalCalls++;
//logger.debug(sampleId + "\t"+ reporterName + copyNumberValuesResultset.getCopyNumber().getValue());
if(consectiveCalls >= noOfConsectiveCalls.intValue()){
isConsectiveCall = true;
logger.debug(sampleId + "TRUE "+consectiveCalls );
}
} else {
consectiveCalls = 0;
//logger.debug("B " + sampleId + "\t"+ reporterName + " count: " + consectiveCalls);
}
}
}
}
- int percent = (totalCalls/reporterNames.size()) * 100;
- if(percent >= percentCall.intValue()){
+ float percent = (totalCalls/reporterNames.size()) * 100;
+ if(percentCall.intValue() > 0 && percent >= percentCall.intValue()){
isPercentCall = true;
}
}
if(operator.equals(OperatorType.AND)){
if(isConsectiveCall && isPercentCall){
return true;
}
}
else if(operator.equals(OperatorType.OR)){
if(isConsectiveCall || isPercentCall){
return true;
}
}
return false;
}
}
| false | true | private static boolean processCopyNumberFilterPerSample(
SampleResultset sampleResultset, List reporterNames, Integer noOfConsectiveCalls, Integer percentCall,OperatorType operator ) {
int totalCalls = 0;
int consectiveCalls = 0;
boolean isConsectiveCall = false;
boolean isPercentCall = false;
if (sampleResultset.getCopyNumberSingleViewResultsContainer() != null
&& reporterNames != null) {
CopyNumberSingleViewResultsContainer copyNumberContainer = sampleResultset.getCopyNumberSingleViewResultsContainer();
String sampleId = sampleResultset.getBiospecimen().getValue()
.toString();
Collection cytobands = copyNumberContainer.getCytobandResultsets();
Collection labels = copyNumberContainer.getGroupsLabels();
for (Iterator cytobandIterator = cytobands.iterator(); cytobandIterator.hasNext();) {
CytobandResultset cytobandResultset = (CytobandResultset) cytobandIterator.next();
String cytoband = cytobandResultset.getCytoband().getValue().toString();
for (Iterator labelIterator = labels.iterator(); labelIterator.hasNext();) {
String label = (String) labelIterator.next();
for (Iterator reporterIterator = reporterNames.iterator(); reporterIterator.hasNext();) {
String reporterName = (String) reporterIterator.next();
SampleCopyNumberValuesResultset copyNumberValuesResultset = copyNumberContainer.
getSampleCopyNumberValuesResultsets(cytoband,
reporterName, label, sampleId);
if (copyNumberValuesResultset != null && copyNumberValuesResultset.getCopyNumber() != null) {
consectiveCalls++;
totalCalls++;
//logger.debug(sampleId + "\t"+ reporterName + copyNumberValuesResultset.getCopyNumber().getValue());
if(consectiveCalls >= noOfConsectiveCalls.intValue()){
isConsectiveCall = true;
logger.debug(sampleId + "TRUE "+consectiveCalls );
}
} else {
consectiveCalls = 0;
//logger.debug("B " + sampleId + "\t"+ reporterName + " count: " + consectiveCalls);
}
}
}
}
int percent = (totalCalls/reporterNames.size()) * 100;
if(percent >= percentCall.intValue()){
isPercentCall = true;
}
}
if(operator.equals(OperatorType.AND)){
if(isConsectiveCall && isPercentCall){
return true;
}
}
else if(operator.equals(OperatorType.OR)){
if(isConsectiveCall || isPercentCall){
return true;
}
}
return false;
}
| private static boolean processCopyNumberFilterPerSample(
SampleResultset sampleResultset, List reporterNames, Integer noOfConsectiveCalls, Integer percentCall,OperatorType operator ) {
float totalCalls = 0;
int consectiveCalls = 0;
boolean isConsectiveCall = false;
boolean isPercentCall = false;
if (sampleResultset.getCopyNumberSingleViewResultsContainer() != null
&& reporterNames != null) {
CopyNumberSingleViewResultsContainer copyNumberContainer = sampleResultset.getCopyNumberSingleViewResultsContainer();
String sampleId = sampleResultset.getBiospecimen().getValue()
.toString();
Collection cytobands = copyNumberContainer.getCytobandResultsets();
Collection labels = copyNumberContainer.getGroupsLabels();
for (Iterator cytobandIterator = cytobands.iterator(); cytobandIterator.hasNext();) {
CytobandResultset cytobandResultset = (CytobandResultset) cytobandIterator.next();
String cytoband = cytobandResultset.getCytoband().getValue().toString();
for (Iterator labelIterator = labels.iterator(); labelIterator.hasNext();) {
String label = (String) labelIterator.next();
for (Iterator reporterIterator = reporterNames.iterator(); reporterIterator.hasNext();) {
String reporterName = (String) reporterIterator.next();
SampleCopyNumberValuesResultset copyNumberValuesResultset = copyNumberContainer.
getSampleCopyNumberValuesResultsets(cytoband,
reporterName, label, sampleId);
if (copyNumberValuesResultset != null && copyNumberValuesResultset.getCopyNumber() != null) {
consectiveCalls++;
totalCalls++;
//logger.debug(sampleId + "\t"+ reporterName + copyNumberValuesResultset.getCopyNumber().getValue());
if(consectiveCalls >= noOfConsectiveCalls.intValue()){
isConsectiveCall = true;
logger.debug(sampleId + "TRUE "+consectiveCalls );
}
} else {
consectiveCalls = 0;
//logger.debug("B " + sampleId + "\t"+ reporterName + " count: " + consectiveCalls);
}
}
}
}
float percent = (totalCalls/reporterNames.size()) * 100;
if(percentCall.intValue() > 0 && percent >= percentCall.intValue()){
isPercentCall = true;
}
}
if(operator.equals(OperatorType.AND)){
if(isConsectiveCall && isPercentCall){
return true;
}
}
else if(operator.equals(OperatorType.OR)){
if(isConsectiveCall || isPercentCall){
return true;
}
}
return false;
}
|
diff --git a/platform/image/src/main/java/org/mayocat/image/store/jdbi/mapper/ThumbnailMapper.java b/platform/image/src/main/java/org/mayocat/image/store/jdbi/mapper/ThumbnailMapper.java
index bdf2ad5f..375bb3b7 100644
--- a/platform/image/src/main/java/org/mayocat/image/store/jdbi/mapper/ThumbnailMapper.java
+++ b/platform/image/src/main/java/org/mayocat/image/store/jdbi/mapper/ThumbnailMapper.java
@@ -1,29 +1,29 @@
package org.mayocat.image.store.jdbi.mapper;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.mayocat.image.model.Thumbnail;
import org.skife.jdbi.v2.StatementContext;
import org.skife.jdbi.v2.tweak.ResultSetMapper;
/**
* @version $Id$
*/
public class ThumbnailMapper implements ResultSetMapper<Thumbnail>
{
@Override
public Thumbnail map(int index, ResultSet result, StatementContext ctx) throws SQLException
{
Thumbnail thumbnail = new Thumbnail();
thumbnail.setAttachmentId(result.getLong("attachment_id"));
thumbnail.setHint(result.getString("hint"));
- thumbnail.setSource(result.getString("gestalt"));
+ thumbnail.setSource(result.getString("source"));
thumbnail.setRatio(result.getString("ratio"));
thumbnail.setX(result.getInt("x"));
thumbnail.setY(result.getInt("y"));
thumbnail.setWidth(result.getInt("width"));
thumbnail.setHeight(result.getInt("height"));
return thumbnail;
}
}
| true | true | public Thumbnail map(int index, ResultSet result, StatementContext ctx) throws SQLException
{
Thumbnail thumbnail = new Thumbnail();
thumbnail.setAttachmentId(result.getLong("attachment_id"));
thumbnail.setHint(result.getString("hint"));
thumbnail.setSource(result.getString("gestalt"));
thumbnail.setRatio(result.getString("ratio"));
thumbnail.setX(result.getInt("x"));
thumbnail.setY(result.getInt("y"));
thumbnail.setWidth(result.getInt("width"));
thumbnail.setHeight(result.getInt("height"));
return thumbnail;
}
| public Thumbnail map(int index, ResultSet result, StatementContext ctx) throws SQLException
{
Thumbnail thumbnail = new Thumbnail();
thumbnail.setAttachmentId(result.getLong("attachment_id"));
thumbnail.setHint(result.getString("hint"));
thumbnail.setSource(result.getString("source"));
thumbnail.setRatio(result.getString("ratio"));
thumbnail.setX(result.getInt("x"));
thumbnail.setY(result.getInt("y"));
thumbnail.setWidth(result.getInt("width"));
thumbnail.setHeight(result.getInt("height"));
return thumbnail;
}
|
diff --git a/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/l2gen/userInterface/L2genIfileSelector.java b/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/l2gen/userInterface/L2genIfileSelector.java
index 2fd56ab2..6623f932 100644
--- a/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/l2gen/userInterface/L2genIfileSelector.java
+++ b/seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/l2gen/userInterface/L2genIfileSelector.java
@@ -1,127 +1,123 @@
package gov.nasa.gsfc.seadas.processing.l2gen.userInterface;
import com.bc.ceres.swing.selection.AbstractSelectionChangeListener;
import com.bc.ceres.swing.selection.SelectionChangeEvent;
import gov.nasa.gsfc.seadas.processing.core.L2genDataProcessorModel;
import gov.nasa.gsfc.seadas.processing.general.SourceProductFileSelector;
import org.esa.beam.visat.VisatApp;
import javax.swing.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
/**
* Created by IntelliJ IDEA.
* User: knowles
* Date: 6/6/12
* Time: 11:22 AM
* To change this template use File | Settings | File Templates.
*/
public class L2genIfileSelector {
final private L2genDataProcessorModel l2genDataProcessorModel;
private SourceProductFileSelector sourceProductSelector;
private boolean controlHandlerEnabled = true;
private boolean eventHandlerEnabled = true;
public L2genIfileSelector(L2genDataProcessorModel l2genDataProcessorModel) {
this.l2genDataProcessorModel = l2genDataProcessorModel;
sourceProductSelector = new SourceProductFileSelector(VisatApp.getApp(), l2genDataProcessorModel.getPrimaryInputFileOptionName(), l2genDataProcessorModel.isMultipleInputFiles());
sourceProductSelector.initProducts();
sourceProductSelector.setProductNameLabel(new JLabel(l2genDataProcessorModel.getPrimaryInputFileOptionName()));
sourceProductSelector.getProductNameComboBox().setPrototypeDisplayValue(
"123456789 123456789 123456789 123456789 123456789 ");
addControlListeners();
addEventListeners();
}
private void addControlListeners() {
sourceProductSelector.addSelectionChangeListener(new AbstractSelectionChangeListener() {
@Override
public void selectionChanged(SelectionChangeEvent event) {
File iFile = getSelectedIFile();
if (isControlHandlerEnabled() && iFile != null) {
//if (l2genDataProcessorModel.getParamValue(l2genDataProcessorModel.getPrimaryInputFileOptionName()).equals(iFile.getAbsolutePath())) {
disableEventHandler();
//}
l2genDataProcessorModel.setParamValue(l2genDataProcessorModel.getPrimaryInputFileOptionName(), iFile.getAbsolutePath());
if (!l2genDataProcessorModel.getParamValue(l2genDataProcessorModel.getPrimaryInputFileOptionName()).equals(iFile.getAbsolutePath())) {
enableEventHandler();
}
l2genDataProcessorModel.updateParamValues(sourceProductSelector.getSelectedProduct());
}
}
});
}
private void addEventListeners() {
l2genDataProcessorModel.addPropertyChangeListener(l2genDataProcessorModel.getPrimaryInputFileOptionName(), new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
String ifileName = l2genDataProcessorModel.getParamValue(l2genDataProcessorModel.getPrimaryInputFileOptionName());
File iFile = new File(ifileName);
- String selectedIfileName = getSelectedIFile().getAbsolutePath();
disableControlHandler();
- if (isEventHandlerEnabled() ||
- !l2genDataProcessorModel.getParamValue(l2genDataProcessorModel.getPrimaryInputFileOptionName()).equals(selectedIfileName)) {
- if (iFile != null && iFile.exists()) {
- if (!l2genDataProcessorModel.getParamValue(l2genDataProcessorModel.getPrimaryInputFileOptionName()).equals(getSelectedIFile().getAbsolutePath())) {
- sourceProductSelector.setSelectedFile(iFile);
- }
+ if (isEventHandlerEnabled()) {
+ if(iFile.exists()) {
+ sourceProductSelector.setSelectedFile(iFile);
} else {
sourceProductSelector.setSelectedFile(null);
}
}
enableControlHandler();
}
}
);
}
private boolean isControlHandlerEnabled() {
return controlHandlerEnabled;
}
private boolean isEventHandlerEnabled() {
return eventHandlerEnabled;
}
private void enableControlHandler() {
controlHandlerEnabled = true;
}
private void disableControlHandler() {
controlHandlerEnabled = false;
}
private void enableEventHandler() {
eventHandlerEnabled = true;
}
private void disableEventHandler() {
eventHandlerEnabled = false;
}
public File getSelectedIFile() {
if (sourceProductSelector == null) {
return null;
}
if (sourceProductSelector.getSelectedProduct() == null) {
return null;
}
return sourceProductSelector.getSelectedProduct().getFileLocation();
}
public JPanel getJPanel() {
return sourceProductSelector.createDefaultPanel();
}
public SourceProductFileSelector getSourceProductSelector() {
return sourceProductSelector;
}
}
| false | true | private void addEventListeners() {
l2genDataProcessorModel.addPropertyChangeListener(l2genDataProcessorModel.getPrimaryInputFileOptionName(), new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
String ifileName = l2genDataProcessorModel.getParamValue(l2genDataProcessorModel.getPrimaryInputFileOptionName());
File iFile = new File(ifileName);
String selectedIfileName = getSelectedIFile().getAbsolutePath();
disableControlHandler();
if (isEventHandlerEnabled() ||
!l2genDataProcessorModel.getParamValue(l2genDataProcessorModel.getPrimaryInputFileOptionName()).equals(selectedIfileName)) {
if (iFile != null && iFile.exists()) {
if (!l2genDataProcessorModel.getParamValue(l2genDataProcessorModel.getPrimaryInputFileOptionName()).equals(getSelectedIFile().getAbsolutePath())) {
sourceProductSelector.setSelectedFile(iFile);
}
} else {
sourceProductSelector.setSelectedFile(null);
}
}
enableControlHandler();
}
}
);
}
| private void addEventListeners() {
l2genDataProcessorModel.addPropertyChangeListener(l2genDataProcessorModel.getPrimaryInputFileOptionName(), new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
String ifileName = l2genDataProcessorModel.getParamValue(l2genDataProcessorModel.getPrimaryInputFileOptionName());
File iFile = new File(ifileName);
disableControlHandler();
if (isEventHandlerEnabled()) {
if(iFile.exists()) {
sourceProductSelector.setSelectedFile(iFile);
} else {
sourceProductSelector.setSelectedFile(null);
}
}
enableControlHandler();
}
}
);
}
|
diff --git a/modules/analysis/common/src/test/org/apache/lucene/analysis/synonym/TestSynonymMapFilter.java b/modules/analysis/common/src/test/org/apache/lucene/analysis/synonym/TestSynonymMapFilter.java
index 6a8ee34d9..cbe5c2d15 100644
--- a/modules/analysis/common/src/test/org/apache/lucene/analysis/synonym/TestSynonymMapFilter.java
+++ b/modules/analysis/common/src/test/org/apache/lucene/analysis/synonym/TestSynonymMapFilter.java
@@ -1,709 +1,716 @@
/**
* 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.lucene.analysis.synonym;
import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.BaseTokenStreamTestCase;
import org.apache.lucene.analysis.MockAnalyzer;
import org.apache.lucene.analysis.MockTokenizer;
import org.apache.lucene.analysis.Tokenizer;
import org.apache.lucene.analysis.tokenattributes.*;
import org.apache.lucene.util.CharsRef;
import org.apache.lucene.util._TestUtil;
public class TestSynonymMapFilter extends BaseTokenStreamTestCase {
private SynonymMap.Builder b;
private Tokenizer tokensIn;
private SynonymFilter tokensOut;
private CharTermAttribute termAtt;
private PositionIncrementAttribute posIncrAtt;
private OffsetAttribute offsetAtt;
private void add(String input, String output, boolean keepOrig) {
b.add(new CharsRef(input.replaceAll(" +", "\u0000")),
new CharsRef(output.replaceAll(" +", "\u0000")),
keepOrig);
}
private void assertEquals(CharTermAttribute term, String expected) {
assertEquals(expected.length(), term.length());
final char[] buffer = term.buffer();
for(int chIDX=0;chIDX<expected.length();chIDX++) {
assertEquals(expected.charAt(chIDX), buffer[chIDX]);
}
}
// For the output string: separate positions with a space,
// and separate multiple tokens at each position with a
// /. If a token should have end offset != the input
// token's end offset then add :X to it:
// TODO: we should probably refactor this guy to use/take analyzer,
// the tests are a little messy
private void verify(String input, String output) throws Exception {
if (VERBOSE) {
System.out.println("TEST: verify input=" + input + " expectedOutput=" + output);
}
tokensIn.reset(new StringReader(input));
tokensOut.reset();
final String[] expected = output.split(" ");
int expectedUpto = 0;
while(tokensOut.incrementToken()) {
if (VERBOSE) {
System.out.println(" incr token=" + termAtt.toString() + " posIncr=" + posIncrAtt.getPositionIncrement() + " startOff=" + offsetAtt.startOffset() + " endOff=" + offsetAtt.endOffset());
}
assertTrue(expectedUpto < expected.length);
final int startOffset = offsetAtt.startOffset();
final int endOffset = offsetAtt.endOffset();
final String[] expectedAtPos = expected[expectedUpto++].split("/");
for(int atPos=0;atPos<expectedAtPos.length;atPos++) {
if (atPos > 0) {
assertTrue(tokensOut.incrementToken());
if (VERBOSE) {
System.out.println(" incr token=" + termAtt.toString() + " posIncr=" + posIncrAtt.getPositionIncrement() + " startOff=" + offsetAtt.startOffset() + " endOff=" + offsetAtt.endOffset());
}
}
final int colonIndex = expectedAtPos[atPos].indexOf(':');
final String expectedToken;
final int expectedEndOffset;
if (colonIndex != -1) {
expectedToken = expectedAtPos[atPos].substring(0, colonIndex);
expectedEndOffset = Integer.parseInt(expectedAtPos[atPos].substring(1+colonIndex));
} else {
expectedToken = expectedAtPos[atPos];
expectedEndOffset = endOffset;
}
assertEquals(expectedToken, termAtt.toString());
assertEquals(atPos == 0 ? 1 : 0,
posIncrAtt.getPositionIncrement());
// start/end offset of all tokens at same pos should
// be the same:
assertEquals(startOffset, offsetAtt.startOffset());
assertEquals(expectedEndOffset, offsetAtt.endOffset());
}
}
tokensOut.end();
tokensOut.close();
if (VERBOSE) {
System.out.println(" incr: END");
}
assertEquals(expectedUpto, expected.length);
}
public void testBasic() throws Exception {
b = new SynonymMap.Builder(true);
add("a", "foo", true);
add("a b", "bar fee", true);
add("b c", "dog collar", true);
add("c d", "dog harness holder extras", true);
add("m c e", "dog barks loudly", false);
add("i j k", "feep", true);
add("e f", "foo bar", false);
add("e f", "baz bee", false);
add("z", "boo", false);
add("y", "bee", true);
tokensIn = new MockTokenizer(new StringReader("a"),
MockTokenizer.WHITESPACE,
true);
tokensIn.reset();
assertTrue(tokensIn.incrementToken());
assertFalse(tokensIn.incrementToken());
tokensIn.end();
tokensIn.close();
tokensOut = new SynonymFilter(tokensIn,
b.build(),
true);
termAtt = tokensOut.addAttribute(CharTermAttribute.class);
posIncrAtt = tokensOut.addAttribute(PositionIncrementAttribute.class);
offsetAtt = tokensOut.addAttribute(OffsetAttribute.class);
verify("a b c", "a/bar b/fee c");
// syn output extends beyond input tokens
verify("x a b c d", "x a/bar b/fee c/dog d/harness holder extras");
verify("a b a", "a/bar b/fee a/foo");
// outputs that add to one another:
verify("c d c d", "c/dog d/harness c/holder/dog d/extras/harness holder extras");
// two outputs for same input
verify("e f", "foo/baz bar/bee");
// verify multi-word / single-output offsets:
verify("g i j k g", "g i/feep:7 j k g");
// mixed keepOrig true/false:
verify("a m c e x", "a/foo dog barks loudly x");
verify("c d m c e x", "c/dog d/harness holder/dog extras/barks loudly x");
assertTrue(tokensOut.getCaptureCount() > 0);
// no captureStates when no syns matched
verify("p q r s t", "p q r s t");
assertEquals(0, tokensOut.getCaptureCount());
// no captureStates when only single-input syns, w/ no
// lookahead needed, matched
verify("p q z y t", "p q boo y/bee t");
assertEquals(0, tokensOut.getCaptureCount());
}
private String getRandomString(char start, int alphabetSize, int length) {
assert alphabetSize <= 26;
char[] s = new char[2*length];
for(int charIDX=0;charIDX<length;charIDX++) {
s[2*charIDX] = (char) (start + random.nextInt(alphabetSize));
s[2*charIDX+1] = ' ';
}
return new String(s);
}
private static class OneSyn {
String in;
List<String> out;
boolean keepOrig;
}
public String slowSynMatcher(String doc, List<OneSyn> syns, int maxOutputLength) {
assertTrue(doc.length() % 2 == 0);
final int numInputs = doc.length()/2;
boolean[] keepOrigs = new boolean[numInputs];
boolean[] hasMatch = new boolean[numInputs];
Arrays.fill(keepOrigs, false);
String[] outputs = new String[numInputs + maxOutputLength];
OneSyn[] matches = new OneSyn[numInputs];
for(OneSyn syn : syns) {
int idx = -1;
while(true) {
idx = doc.indexOf(syn.in, 1+idx);
if (idx == -1) {
break;
}
assertTrue(idx % 2 == 0);
final int matchIDX = idx/2;
assertTrue(syn.in.length() % 2 == 1);
if (matches[matchIDX] == null) {
matches[matchIDX] = syn;
} else if (syn.in.length() > matches[matchIDX].in.length()) {
// Greedy conflict resolution: longer match wins:
matches[matchIDX] = syn;
} else {
assertTrue(syn.in.length() < matches[matchIDX].in.length());
}
}
}
// Greedy conflict resolution: if syn matches a range of inputs,
// it prevents other syns from matching that range
for(int inputIDX=0;inputIDX<numInputs;inputIDX++) {
final OneSyn match = matches[inputIDX];
if (match != null) {
final int synInLength = (1+match.in.length())/2;
for(int nextInputIDX=inputIDX+1;nextInputIDX<numInputs && nextInputIDX<(inputIDX+synInLength);nextInputIDX++) {
matches[nextInputIDX] = null;
}
}
}
// Fill overlapping outputs:
for(int inputIDX=0;inputIDX<numInputs;inputIDX++) {
final OneSyn syn = matches[inputIDX];
if (syn == null) {
continue;
}
for(int idx=0;idx<(1+syn.in.length())/2;idx++) {
hasMatch[inputIDX+idx] = true;
keepOrigs[inputIDX+idx] |= syn.keepOrig;
}
for(String synOut : syn.out) {
final String[] synOutputs = synOut.split(" ");
assertEquals(synOutputs.length, (1+synOut.length())/2);
final int matchEnd = inputIDX + synOutputs.length;
int synUpto = 0;
for(int matchIDX=inputIDX;matchIDX<matchEnd;matchIDX++) {
if (outputs[matchIDX] == null) {
outputs[matchIDX] = synOutputs[synUpto++];
} else {
outputs[matchIDX] = outputs[matchIDX] + "/" + synOutputs[synUpto++];
}
- if (synOutputs.length == 1) {
- // Add endOffset
- outputs[matchIDX] = outputs[matchIDX] + ":" + ((inputIDX*2) + syn.in.length());
+ final int endOffset;
+ if (matchIDX < numInputs) {
+ if (synOutputs.length == 1) {
+ // Add full endOffset
+ endOffset = (inputIDX*2) + syn.in.length();
+ } else {
+ // Add endOffset matching input token's
+ endOffset = (matchIDX*2) + 1;
+ }
+ outputs[matchIDX] = outputs[matchIDX] + ":" + endOffset;
}
}
}
}
StringBuilder sb = new StringBuilder();
String[] inputTokens = doc.split(" ");
final int limit = inputTokens.length + maxOutputLength;
for(int inputIDX=0;inputIDX<limit;inputIDX++) {
boolean posHasOutput = false;
if (inputIDX >= numInputs && outputs[inputIDX] == null) {
break;
}
if (inputIDX < numInputs && (!hasMatch[inputIDX] || keepOrigs[inputIDX])) {
assertTrue(inputTokens[inputIDX].length() != 0);
sb.append(inputTokens[inputIDX]);
posHasOutput = true;
}
if (outputs[inputIDX] != null) {
if (posHasOutput) {
sb.append('/');
}
sb.append(outputs[inputIDX]);
} else if (!posHasOutput) {
continue;
}
if (inputIDX < limit-1) {
sb.append(' ');
}
}
return sb.toString();
}
public void testRandom() throws Exception {
final int alphabetSize = _TestUtil.nextInt(random, 2, 7);
final int docLen = atLeast(3000);
//final int docLen = 50;
final String document = getRandomString('a', alphabetSize, docLen);
if (VERBOSE) {
System.out.println("TEST: doc=" + document);
}
final int numSyn = atLeast(5);
//final int numSyn = 2;
final Map<String,OneSyn> synMap = new HashMap<String,OneSyn>();
final List<OneSyn> syns = new ArrayList<OneSyn>();
final boolean dedup = random.nextBoolean();
if (VERBOSE) {
System.out.println(" dedup=" + dedup);
}
b = new SynonymMap.Builder(dedup);
for(int synIDX=0;synIDX<numSyn;synIDX++) {
final String synIn = getRandomString('a', alphabetSize, _TestUtil.nextInt(random, 1, 5)).trim();
OneSyn s = synMap.get(synIn);
if (s == null) {
s = new OneSyn();
s.in = synIn;
syns.add(s);
s.out = new ArrayList<String>();
synMap.put(synIn, s);
s.keepOrig = random.nextBoolean();
}
final String synOut = getRandomString('0', 10, _TestUtil.nextInt(random, 1, 5)).trim();
s.out.add(synOut);
add(synIn, synOut, s.keepOrig);
if (VERBOSE) {
System.out.println(" syns[" + synIDX + "] = " + s.in + " -> " + s.out + " keepOrig=" + s.keepOrig);
}
}
tokensIn = new MockTokenizer(new StringReader("a"),
MockTokenizer.WHITESPACE,
true);
tokensIn.reset();
assertTrue(tokensIn.incrementToken());
assertFalse(tokensIn.incrementToken());
tokensIn.end();
tokensIn.close();
tokensOut = new SynonymFilter(tokensIn,
b.build(),
true);
termAtt = tokensOut.addAttribute(CharTermAttribute.class);
posIncrAtt = tokensOut.addAttribute(PositionIncrementAttribute.class);
offsetAtt = tokensOut.addAttribute(OffsetAttribute.class);
if (dedup) {
pruneDups(syns);
}
final String expected = slowSynMatcher(document, syns, 5);
if (VERBOSE) {
System.out.println("TEST: expected=" + expected);
}
verify(document, expected);
}
private void pruneDups(List<OneSyn> syns) {
Set<String> seen = new HashSet<String>();
for(OneSyn syn : syns) {
int idx = 0;
while(idx < syn.out.size()) {
String out = syn.out.get(idx);
if (!seen.contains(out)) {
seen.add(out);
idx++;
} else {
syn.out.remove(idx);
}
}
seen.clear();
}
}
private String randomNonEmptyString() {
while(true) {
final String s = _TestUtil.randomUnicodeString(random).trim();
if (s.length() != 0 && s.indexOf('\u0000') == -1) {
return s;
}
}
}
/** simple random test, doesn't verify correctness.
* does verify it doesnt throw exceptions, or that the stream doesn't misbehave
*/
public void testRandom2() throws Exception {
final int numIters = atLeast(10);
for (int i = 0; i < numIters; i++) {
b = new SynonymMap.Builder(random.nextBoolean());
final int numEntries = atLeast(10);
for (int j = 0; j < numEntries; j++) {
add(randomNonEmptyString(), randomNonEmptyString(), random.nextBoolean());
}
final SynonymMap map = b.build();
final boolean ignoreCase = random.nextBoolean();
final Analyzer analyzer = new Analyzer() {
@Override
protected TokenStreamComponents createComponents(String fieldName, Reader reader) {
Tokenizer tokenizer = new MockTokenizer(reader, MockTokenizer.SIMPLE, true);
return new TokenStreamComponents(tokenizer, new SynonymFilter(tokenizer, map, ignoreCase));
}
};
checkRandomData(random, analyzer, 1000*RANDOM_MULTIPLIER);
}
}
// LUCENE-3375
public void testVanishingTerms() throws Exception {
String testFile =
"aaa => aaaa1 aaaa2 aaaa3\n" +
"bbb => bbbb1 bbbb2\n";
SolrSynonymParser parser = new SolrSynonymParser(true, true, new MockAnalyzer(random));
parser.add(new StringReader(testFile));
final SynonymMap map = parser.build();
Analyzer analyzer = new Analyzer() {
@Override
protected TokenStreamComponents createComponents(String fieldName, Reader reader) {
Tokenizer tokenizer = new MockTokenizer(reader, MockTokenizer.WHITESPACE, true);
return new TokenStreamComponents(tokenizer, new SynonymFilter(tokenizer, map, true));
}
};
// where did my pot go?!
assertAnalyzesTo(analyzer, "xyzzy bbb pot of gold",
new String[] { "xyzzy", "bbbb1", "pot", "bbbb2", "of", "gold" });
// this one nukes 'pot' and 'of'
// xyzzy aaa pot of gold -> xyzzy aaaa1 aaaa2 aaaa3 gold
assertAnalyzesTo(analyzer, "xyzzy aaa pot of gold",
new String[] { "xyzzy", "aaaa1", "pot", "aaaa2", "of", "aaaa3", "gold" });
}
public void testBasic2() throws Exception {
b = new SynonymMap.Builder(true);
final boolean keepOrig = false;
add("aaa", "aaaa1 aaaa2 aaaa3", keepOrig);
add("bbb", "bbbb1 bbbb2", keepOrig);
tokensIn = new MockTokenizer(new StringReader("a"),
MockTokenizer.WHITESPACE,
true);
tokensIn.reset();
assertTrue(tokensIn.incrementToken());
assertFalse(tokensIn.incrementToken());
tokensIn.end();
tokensIn.close();
tokensOut = new SynonymFilter(tokensIn,
b.build(),
true);
termAtt = tokensOut.addAttribute(CharTermAttribute.class);
posIncrAtt = tokensOut.addAttribute(PositionIncrementAttribute.class);
offsetAtt = tokensOut.addAttribute(OffsetAttribute.class);
if (keepOrig) {
verify("xyzzy bbb pot of gold", "xyzzy bbb/bbbb1 pot/bbbb2 of gold");
verify("xyzzy aaa pot of gold", "xyzzy aaa/aaaa1 pot/aaaa2 of/aaaa3 gold");
} else {
verify("xyzzy bbb pot of gold", "xyzzy bbbb1 pot/bbbb2 of gold");
verify("xyzzy aaa pot of gold", "xyzzy aaaa1 pot/aaaa2 of/aaaa3 gold");
}
}
public void testMatching() throws Exception {
b = new SynonymMap.Builder(true);
final boolean keepOrig = false;
add("a b", "ab", keepOrig);
add("a c", "ac", keepOrig);
add("a", "aa", keepOrig);
add("b", "bb", keepOrig);
add("z x c v", "zxcv", keepOrig);
add("x c", "xc", keepOrig);
final SynonymMap map = b.build();
Analyzer a = new Analyzer() {
@Override
protected TokenStreamComponents createComponents(String fieldName, Reader reader) {
Tokenizer tokenizer = new MockTokenizer(reader, MockTokenizer.WHITESPACE, false);
return new TokenStreamComponents(tokenizer, new SynonymFilter(tokenizer, map, true));
}
};
checkOneTerm(a, "$", "$");
checkOneTerm(a, "a", "aa");
checkOneTerm(a, "b", "bb");
assertAnalyzesTo(a, "a $",
new String[] { "aa", "$" },
new int[] { 1, 1 });
assertAnalyzesTo(a, "$ a",
new String[] { "$", "aa" },
new int[] { 1, 1 });
assertAnalyzesTo(a, "a a",
new String[] { "aa", "aa" },
new int[] { 1, 1 });
assertAnalyzesTo(a, "z x c v",
new String[] { "zxcv" },
new int[] { 1 });
assertAnalyzesTo(a, "z x c $",
new String[] { "z", "xc", "$" },
new int[] { 1, 1, 1 });
}
public void testRepeatsOff() throws Exception {
b = new SynonymMap.Builder(true);
final boolean keepOrig = false;
add("a b", "ab", keepOrig);
add("a b", "ab", keepOrig);
add("a b", "ab", keepOrig);
final SynonymMap map = b.build();
Analyzer a = new Analyzer() {
@Override
protected TokenStreamComponents createComponents(String fieldName, Reader reader) {
Tokenizer tokenizer = new MockTokenizer(reader, MockTokenizer.WHITESPACE, false);
return new TokenStreamComponents(tokenizer, new SynonymFilter(tokenizer, map, true));
}
};
assertAnalyzesTo(a, "a b",
new String[] { "ab" },
new int[] { 1 });
}
public void testRepeatsOn() throws Exception {
b = new SynonymMap.Builder(false);
final boolean keepOrig = false;
add("a b", "ab", keepOrig);
add("a b", "ab", keepOrig);
add("a b", "ab", keepOrig);
final SynonymMap map = b.build();
Analyzer a = new Analyzer() {
@Override
protected TokenStreamComponents createComponents(String fieldName, Reader reader) {
Tokenizer tokenizer = new MockTokenizer(reader, MockTokenizer.WHITESPACE, false);
return new TokenStreamComponents(tokenizer, new SynonymFilter(tokenizer, map, true));
}
};
assertAnalyzesTo(a, "a b",
new String[] { "ab", "ab", "ab" },
new int[] { 1, 0, 0 });
}
public void testRecursion() throws Exception {
b = new SynonymMap.Builder(true);
final boolean keepOrig = false;
add("zoo", "zoo", keepOrig);
final SynonymMap map = b.build();
Analyzer a = new Analyzer() {
@Override
protected TokenStreamComponents createComponents(String fieldName, Reader reader) {
Tokenizer tokenizer = new MockTokenizer(reader, MockTokenizer.WHITESPACE, false);
return new TokenStreamComponents(tokenizer, new SynonymFilter(tokenizer, map, true));
}
};
assertAnalyzesTo(a, "zoo zoo $ zoo",
new String[] { "zoo", "zoo", "$", "zoo" },
new int[] { 1, 1, 1, 1 });
}
public void testRecursion2() throws Exception {
b = new SynonymMap.Builder(true);
final boolean keepOrig = false;
add("zoo", "zoo", keepOrig);
add("zoo", "zoo zoo", keepOrig);
final SynonymMap map = b.build();
Analyzer a = new Analyzer() {
@Override
protected TokenStreamComponents createComponents(String fieldName, Reader reader) {
Tokenizer tokenizer = new MockTokenizer(reader, MockTokenizer.WHITESPACE, false);
return new TokenStreamComponents(tokenizer, new SynonymFilter(tokenizer, map, true));
}
};
// verify("zoo zoo $ zoo", "zoo/zoo zoo/zoo/zoo $/zoo zoo/zoo zoo");
assertAnalyzesTo(a, "zoo zoo $ zoo",
new String[] { "zoo", "zoo", "zoo", "zoo", "zoo", "$", "zoo", "zoo", "zoo", "zoo" },
new int[] { 1, 0, 1, 0, 0, 1, 0, 1, 0, 1 });
}
public void testIncludeOrig() throws Exception {
b = new SynonymMap.Builder(true);
final boolean keepOrig = true;
add("a b", "ab", keepOrig);
add("a c", "ac", keepOrig);
add("a", "aa", keepOrig);
add("b", "bb", keepOrig);
add("z x c v", "zxcv", keepOrig);
add("x c", "xc", keepOrig);
final SynonymMap map = b.build();
Analyzer a = new Analyzer() {
@Override
protected TokenStreamComponents createComponents(String fieldName, Reader reader) {
Tokenizer tokenizer = new MockTokenizer(reader, MockTokenizer.WHITESPACE, false);
return new TokenStreamComponents(tokenizer, new SynonymFilter(tokenizer, map, true));
}
};
assertAnalyzesTo(a, "$",
new String[] { "$" },
new int[] { 1 });
assertAnalyzesTo(a, "a",
new String[] { "a", "aa" },
new int[] { 1, 0 });
assertAnalyzesTo(a, "a",
new String[] { "a", "aa" },
new int[] { 1, 0 });
assertAnalyzesTo(a, "$ a",
new String[] { "$", "a", "aa" },
new int[] { 1, 1, 0 });
assertAnalyzesTo(a, "a $",
new String[] { "a", "aa", "$" },
new int[] { 1, 0, 1 });
assertAnalyzesTo(a, "$ a !",
new String[] { "$", "a", "aa", "!" },
new int[] { 1, 1, 0, 1 });
assertAnalyzesTo(a, "a a",
new String[] { "a", "aa", "a", "aa" },
new int[] { 1, 0, 1, 0 });
assertAnalyzesTo(a, "b",
new String[] { "b", "bb" },
new int[] { 1, 0 });
assertAnalyzesTo(a, "z x c v",
new String[] { "z", "zxcv", "x", "c", "v" },
new int[] { 1, 0, 1, 1, 1 });
assertAnalyzesTo(a, "z x c $",
new String[] { "z", "x", "xc", "c", "$" },
new int[] { 1, 1, 0, 1, 1 });
}
public void testRecursion3() throws Exception {
b = new SynonymMap.Builder(true);
final boolean keepOrig = true;
add("zoo zoo", "zoo", keepOrig);
final SynonymMap map = b.build();
Analyzer a = new Analyzer() {
@Override
protected TokenStreamComponents createComponents(String fieldName, Reader reader) {
Tokenizer tokenizer = new MockTokenizer(reader, MockTokenizer.WHITESPACE, false);
return new TokenStreamComponents(tokenizer, new SynonymFilter(tokenizer, map, true));
}
};
assertAnalyzesTo(a, "zoo zoo $ zoo",
new String[] { "zoo", "zoo", "zoo", "$", "zoo" },
new int[] { 1, 0, 1, 1, 1 });
}
public void testRecursion4() throws Exception {
b = new SynonymMap.Builder(true);
final boolean keepOrig = true;
add("zoo zoo", "zoo", keepOrig);
add("zoo", "zoo zoo", keepOrig);
final SynonymMap map = b.build();
Analyzer a = new Analyzer() {
@Override
protected TokenStreamComponents createComponents(String fieldName, Reader reader) {
Tokenizer tokenizer = new MockTokenizer(reader, MockTokenizer.WHITESPACE, false);
return new TokenStreamComponents(tokenizer, new SynonymFilter(tokenizer, map, true));
}
};
assertAnalyzesTo(a, "zoo zoo $ zoo",
new String[] { "zoo", "zoo", "zoo", "$", "zoo", "zoo", "zoo" },
new int[] { 1, 0, 1, 1, 1, 0, 1 });
}
public void testMultiwordOffsets() throws Exception {
b = new SynonymMap.Builder(true);
final boolean keepOrig = true;
add("national hockey league", "nhl", keepOrig);
final SynonymMap map = b.build();
Analyzer a = new Analyzer() {
@Override
protected TokenStreamComponents createComponents(String fieldName, Reader reader) {
Tokenizer tokenizer = new MockTokenizer(reader, MockTokenizer.WHITESPACE, false);
return new TokenStreamComponents(tokenizer, new SynonymFilter(tokenizer, map, true));
}
};
assertAnalyzesTo(a, "national hockey league",
new String[] { "national", "nhl", "hockey", "league" },
new int[] { 0, 0, 9, 16 },
new int[] { 8, 22, 15, 22 },
new int[] { 1, 0, 1, 1 });
}
}
| true | true | public String slowSynMatcher(String doc, List<OneSyn> syns, int maxOutputLength) {
assertTrue(doc.length() % 2 == 0);
final int numInputs = doc.length()/2;
boolean[] keepOrigs = new boolean[numInputs];
boolean[] hasMatch = new boolean[numInputs];
Arrays.fill(keepOrigs, false);
String[] outputs = new String[numInputs + maxOutputLength];
OneSyn[] matches = new OneSyn[numInputs];
for(OneSyn syn : syns) {
int idx = -1;
while(true) {
idx = doc.indexOf(syn.in, 1+idx);
if (idx == -1) {
break;
}
assertTrue(idx % 2 == 0);
final int matchIDX = idx/2;
assertTrue(syn.in.length() % 2 == 1);
if (matches[matchIDX] == null) {
matches[matchIDX] = syn;
} else if (syn.in.length() > matches[matchIDX].in.length()) {
// Greedy conflict resolution: longer match wins:
matches[matchIDX] = syn;
} else {
assertTrue(syn.in.length() < matches[matchIDX].in.length());
}
}
}
// Greedy conflict resolution: if syn matches a range of inputs,
// it prevents other syns from matching that range
for(int inputIDX=0;inputIDX<numInputs;inputIDX++) {
final OneSyn match = matches[inputIDX];
if (match != null) {
final int synInLength = (1+match.in.length())/2;
for(int nextInputIDX=inputIDX+1;nextInputIDX<numInputs && nextInputIDX<(inputIDX+synInLength);nextInputIDX++) {
matches[nextInputIDX] = null;
}
}
}
// Fill overlapping outputs:
for(int inputIDX=0;inputIDX<numInputs;inputIDX++) {
final OneSyn syn = matches[inputIDX];
if (syn == null) {
continue;
}
for(int idx=0;idx<(1+syn.in.length())/2;idx++) {
hasMatch[inputIDX+idx] = true;
keepOrigs[inputIDX+idx] |= syn.keepOrig;
}
for(String synOut : syn.out) {
final String[] synOutputs = synOut.split(" ");
assertEquals(synOutputs.length, (1+synOut.length())/2);
final int matchEnd = inputIDX + synOutputs.length;
int synUpto = 0;
for(int matchIDX=inputIDX;matchIDX<matchEnd;matchIDX++) {
if (outputs[matchIDX] == null) {
outputs[matchIDX] = synOutputs[synUpto++];
} else {
outputs[matchIDX] = outputs[matchIDX] + "/" + synOutputs[synUpto++];
}
if (synOutputs.length == 1) {
// Add endOffset
outputs[matchIDX] = outputs[matchIDX] + ":" + ((inputIDX*2) + syn.in.length());
}
}
}
}
StringBuilder sb = new StringBuilder();
String[] inputTokens = doc.split(" ");
final int limit = inputTokens.length + maxOutputLength;
for(int inputIDX=0;inputIDX<limit;inputIDX++) {
boolean posHasOutput = false;
if (inputIDX >= numInputs && outputs[inputIDX] == null) {
break;
}
if (inputIDX < numInputs && (!hasMatch[inputIDX] || keepOrigs[inputIDX])) {
assertTrue(inputTokens[inputIDX].length() != 0);
sb.append(inputTokens[inputIDX]);
posHasOutput = true;
}
if (outputs[inputIDX] != null) {
if (posHasOutput) {
sb.append('/');
}
sb.append(outputs[inputIDX]);
} else if (!posHasOutput) {
continue;
}
if (inputIDX < limit-1) {
sb.append(' ');
}
}
return sb.toString();
}
| public String slowSynMatcher(String doc, List<OneSyn> syns, int maxOutputLength) {
assertTrue(doc.length() % 2 == 0);
final int numInputs = doc.length()/2;
boolean[] keepOrigs = new boolean[numInputs];
boolean[] hasMatch = new boolean[numInputs];
Arrays.fill(keepOrigs, false);
String[] outputs = new String[numInputs + maxOutputLength];
OneSyn[] matches = new OneSyn[numInputs];
for(OneSyn syn : syns) {
int idx = -1;
while(true) {
idx = doc.indexOf(syn.in, 1+idx);
if (idx == -1) {
break;
}
assertTrue(idx % 2 == 0);
final int matchIDX = idx/2;
assertTrue(syn.in.length() % 2 == 1);
if (matches[matchIDX] == null) {
matches[matchIDX] = syn;
} else if (syn.in.length() > matches[matchIDX].in.length()) {
// Greedy conflict resolution: longer match wins:
matches[matchIDX] = syn;
} else {
assertTrue(syn.in.length() < matches[matchIDX].in.length());
}
}
}
// Greedy conflict resolution: if syn matches a range of inputs,
// it prevents other syns from matching that range
for(int inputIDX=0;inputIDX<numInputs;inputIDX++) {
final OneSyn match = matches[inputIDX];
if (match != null) {
final int synInLength = (1+match.in.length())/2;
for(int nextInputIDX=inputIDX+1;nextInputIDX<numInputs && nextInputIDX<(inputIDX+synInLength);nextInputIDX++) {
matches[nextInputIDX] = null;
}
}
}
// Fill overlapping outputs:
for(int inputIDX=0;inputIDX<numInputs;inputIDX++) {
final OneSyn syn = matches[inputIDX];
if (syn == null) {
continue;
}
for(int idx=0;idx<(1+syn.in.length())/2;idx++) {
hasMatch[inputIDX+idx] = true;
keepOrigs[inputIDX+idx] |= syn.keepOrig;
}
for(String synOut : syn.out) {
final String[] synOutputs = synOut.split(" ");
assertEquals(synOutputs.length, (1+synOut.length())/2);
final int matchEnd = inputIDX + synOutputs.length;
int synUpto = 0;
for(int matchIDX=inputIDX;matchIDX<matchEnd;matchIDX++) {
if (outputs[matchIDX] == null) {
outputs[matchIDX] = synOutputs[synUpto++];
} else {
outputs[matchIDX] = outputs[matchIDX] + "/" + synOutputs[synUpto++];
}
final int endOffset;
if (matchIDX < numInputs) {
if (synOutputs.length == 1) {
// Add full endOffset
endOffset = (inputIDX*2) + syn.in.length();
} else {
// Add endOffset matching input token's
endOffset = (matchIDX*2) + 1;
}
outputs[matchIDX] = outputs[matchIDX] + ":" + endOffset;
}
}
}
}
StringBuilder sb = new StringBuilder();
String[] inputTokens = doc.split(" ");
final int limit = inputTokens.length + maxOutputLength;
for(int inputIDX=0;inputIDX<limit;inputIDX++) {
boolean posHasOutput = false;
if (inputIDX >= numInputs && outputs[inputIDX] == null) {
break;
}
if (inputIDX < numInputs && (!hasMatch[inputIDX] || keepOrigs[inputIDX])) {
assertTrue(inputTokens[inputIDX].length() != 0);
sb.append(inputTokens[inputIDX]);
posHasOutput = true;
}
if (outputs[inputIDX] != null) {
if (posHasOutput) {
sb.append('/');
}
sb.append(outputs[inputIDX]);
} else if (!posHasOutput) {
continue;
}
if (inputIDX < limit-1) {
sb.append(' ');
}
}
return sb.toString();
}
|
diff --git a/src/com/slauson/dasher/objects/Asteroid.java b/src/com/slauson/dasher/objects/Asteroid.java
index 88d4367..7f5e402 100644
--- a/src/com/slauson/dasher/objects/Asteroid.java
+++ b/src/com/slauson/dasher/objects/Asteroid.java
@@ -1,548 +1,548 @@
package com.slauson.dasher.objects;
import java.util.ArrayList;
import java.util.Random;
import com.slauson.dasher.game.MyGameView;
import com.slauson.dasher.status.LocalStatistics;
import android.graphics.Canvas;
import android.graphics.Paint;
/**
* Asteroid that player ship has to avoid
* @author Josh Slauson
*
*/
public class Asteroid extends DrawObject {
/**
* Private fields
*/
private Random random;
private float factor;
private double[] angles;
private int leftPoints, rightPoints;
private int radius;
/**
* Private constants
*/
private static final int NUM_POINTS_MIN = 6;
private static final int NUM_POINTS_MAX = 12;
private static final float RADIUS_OFFSET = 0.25f;
private static final float HORIZONTAL_MOVEMENT_OFFSET = 0.25f;
private static final float SPEED_INVISIBLE = 100;
// durations
private static final int HELD_IN_PLACE_DURATION = 10000;
private static final int DISAPPEAR_DURATION = 10000;
private static final int INVISIBLE_DURATION = 2000;
private static final float SPEED_HELD_IN_PLACE_FACTOR = 0.5f;
/**
* Public constants
*/
public static final int FADE_OUT_FROM_BOMB = 0;
public static final int FADE_OUT_FROM_QUASAR = 1;
public static final int FADE_OUT_FROM_MAGNET = 2;
public Asteroid(float sizeFactor, float speedFactor, boolean horizontalMovement) {
// do width/height later
super(0, 0, 0, 0);
this.random = new Random();
int numPoints = NUM_POINTS_MIN + random.nextInt(NUM_POINTS_MAX - NUM_POINTS_MIN - 1);
points = new float[numPoints*4];
altPoints = new float[numPoints*4];
angles = new double[numPoints];
lineSegments = new ArrayList<LineSegment>();
radius = 0;
for (int i = 0; i < numPoints; i++) {
lineSegments.add(new LineSegment(0, 0, 0, 0));
}
reset(sizeFactor, speedFactor, horizontalMovement);
}
/**
* Resets asteroid
* @param radiusFactor radius factor of asteroid relative to screen width
* @param speedFactor speed factor of asteroid relative to screen height
* @param horizontalMovement whether or not the asteroid has horizontal movement
*/
public void reset(float sizeFactor, float speedFactor, boolean horizontalMovement) {
// calculate speed
speed = getRelativeHeightSize(speedFactor);
// calculate radius
radius = getRelativeWidthSize(sizeFactor);
width = radius*2;
height = radius*2;
if (horizontalMovement) {
dirX = -HORIZONTAL_MOVEMENT_OFFSET + (2*HORIZONTAL_MOVEMENT_OFFSET*random.nextFloat());
}
// clear out arrays of points
for (int i = 0; i < points.length; i++) {
points[i] = 0;
altPoints[i] = 0;
}
resetRandomPoints();
reset();
}
/**
* Resets asteroid
*/
public void reset() {
x = random.nextInt(MyGameView.canvasWidth);
if (MyGameView.direction == MyGameView.DIRECTION_NORMAL) {
y = -random.nextInt(MyGameView.canvasHeight);
} else {
y = MyGameView.canvasHeight + random.nextInt(MyGameView.canvasHeight);
}
dirY = 1 - dirX;
timeCounter = 0;
factor = 1;
status = STATUS_NORMAL;
}
/**
* Resets random points for asteroid
*/
private void resetRandomPoints() {
int numPoints = points.length/4;
double pointAngle = 2*Math.PI/numPoints;
rightPoints = 0;
leftPoints = 0;
// for each point
for(int i = 0; i < numPoints; i++) {
// calculate angle based on point number and random offset
double angle = 2*Math.PI*i/numPoints - pointAngle/2 + random.nextFloat()*pointAngle;
if (angle < Math.PI/2 || angle > 3*Math.PI/2) {
rightPoints++;
} else {
leftPoints++;
}
// calculate radius
float pointRadius = radius - (radius*RADIUS_OFFSET) + (2*RADIUS_OFFSET*random.nextFloat());
// get cos/sin values
double cos = Math.cos(angle);
double sin = Math.sin(angle);
// calculate x/y coordinates
float x = (float)(pointRadius*cos);
float y = (float)(pointRadius*sin);
angles[i] = angle;
if (i != 0) {
points[4*i-2] = x;
points[4*i-1] = y;
}
points[4*i] = x;
points[4*i+1] = y;
}
points[4*numPoints-2] = points[0];
points[4*numPoints-1] = points[1];
}
/**
* Make asteroid break up into line segments, caused by dash
*/
public void breakup() {
if (status == STATUS_NORMAL || status == STATUS_HELD_IN_PLACE) {
LineSegment lineSegment;
for (int i = 0; i < points.length; i+=4) {
lineSegment = lineSegments.get(i/4);
lineSegment.x1 = x + points[i];
lineSegment.y1 = y + points[i+1];
lineSegment.x2 = x + points[i+2];
lineSegment.y2 = y + points[i+3];
// need to get perpendicular (these are opposite on purpose)
float yDiff = Math.abs(points[i] - points[i+2]);
float xDiff = Math.abs(points[i+1] - points[i+3]);
yDiff += Math.abs(dirY)*speed;
xDiff += Math.abs(dirX)*speed;
lineSegment.move = BREAKING_UP_MOVE;
// x direction is sometimes positive
if (points[i] < 0) {
lineSegment.dirX = (-xDiff/(xDiff + yDiff));
} else {
lineSegment.dirX = (xDiff/(xDiff + yDiff));
}
// y direction is always positive
lineSegment.dirY = (yDiff/(xDiff + yDiff)) + 1;
}
speed = 0;
status = STATUS_BREAKING_UP;
timeCounter = BREAKING_UP_DURATION;
LocalStatistics.getInstance().asteroidsDestroyedByDash++;
}
}
/**
* Make asteroid disappear, caused by black hole
*/
public void disappear() {
if (status == STATUS_NORMAL) {
status = STATUS_DISAPPEARING;
timeCounter = DISAPPEAR_DURATION;
LocalStatistics.getInstance().asteroidsDestroyedByBlackHole++;
// create temporary array of points so we can shrink the asteroid
System.arraycopy(points, 0, altPoints, 0, points.length);
}
}
/**
* Fade out asteroid
* @param cause cause of the fadeout
*/
public void fadeOut(int cause) {
if (status == STATUS_NORMAL || status == STATUS_HELD_IN_PLACE) {
status = STATUS_FADING_OUT;
timeCounter = FADING_OUT_DURATION;
if (cause == FADE_OUT_FROM_BOMB) {
LocalStatistics.getInstance().asteroidsDestroyedByBomb++;
} else if (cause == FADE_OUT_FROM_QUASAR) {
LocalStatistics.getInstance().asteroidsDestroyedByBlackHole++;
}
}
}
/**
* Split up asteroid, caused by drill
*/
public void splitUp() {
if (status == STATUS_NORMAL || status == STATUS_HELD_IN_PLACE) {
int indexRight = 2, indexLeft = 0;
boolean leftSwitch = false, rightSwitch = false;
// start at 2 so we get each pair of points (same values) for each corresponding angle
for (int i = 2; i < points.length-2; i+=4) {
// right points
if (angles[(i+2)/4] < Math.PI/2.0 || angles[(i+2)/4] > 3.0*Math.PI/2.0) {
// add one right point to left side
if (leftSwitch && !rightSwitch) {
// perfect split
points[i] = 0;
points[i+2] = 0;
altPoints[indexLeft] = points[i];
altPoints[indexLeft+1] = points[i+1];
altPoints[indexLeft+2] = points[i+2];
altPoints[indexLeft+3] = points[i+3];
indexLeft += 4;
rightSwitch = true;
}
points[indexRight] = points[i];
points[indexRight+1] = points[i+1];
points[indexRight+2] = points[i+2];
points[indexRight+3] = points[i+3];
indexRight += 4;
}
// left points
else {
// add one left point to right side
if (!leftSwitch) {
// perfect split
points[i] = 0;
points[i+2] = 0;
points[indexRight] = points[i];
points[indexRight+1] = points[i+1];
points[indexRight+2] = points[i+2];
points[indexRight+3] = points[i+3];
indexRight += 4;
leftSwitch = true;
}
altPoints[indexLeft] = points[i];
altPoints[indexLeft+1] = points[i+1];
// only add first point once on left side
if (indexLeft == 0) {
indexLeft += 2;
} else {
altPoints[indexLeft+2] = points[i+2];
altPoints[indexLeft+3] = points[i+3];
indexLeft += 4;
}
}
}
// close right points
points[indexRight] = points[points.length-2];
points[indexRight+1] = points[points.length-1];
// close left points
altPoints[indexLeft] = altPoints[0];
altPoints[indexLeft+1] = altPoints[1];
- speed = 0;
+ // NOTE: don't reset speed here so that the split up animation looks smoother
status = STATUS_SPLITTING_UP;
timeCounter = SPLITTING_UP_DURATION;
LocalStatistics.getInstance().asteroidsDestroyedByDrill++;
}
}
/**
* Hold asteroid in place, caused by magnet
*/
public void holdInPlace() {
if (status == STATUS_NORMAL) {
status = STATUS_HELD_IN_PLACE;
timeCounter = HELD_IN_PLACE_DURATION;
}
}
@Override
public void draw(Canvas canvas, Paint paint) {
if (status != STATUS_INVISIBLE && onScreen()) {
// intact asteroid
if (status == STATUS_NORMAL) {
canvas.save();
canvas.translate(x, y);
canvas.drawLines(points, paint);
canvas.restore();
}
// broken up asteroid
else if (status == STATUS_BREAKING_UP){
paint.setAlpha((int)(255 * (1.f*timeCounter/BREAKING_UP_DURATION)));
for (LineSegment lineSegment : lineSegments) {
lineSegment.draw(canvas, paint);
}
paint.setAlpha(255);
}
// disappearing asteroid
else if (status == STATUS_DISAPPEARING) {
int alpha = (int)(4*255*(factor*(1-DISAPPEARING_FACTOR)));
if (alpha > 255) {
alpha = 255;
}
paint.setAlpha(alpha);
canvas.save();
canvas.translate(x, y);
canvas.drawLines(altPoints, paint);
canvas.restore();
paint.setAlpha(255);
}
// fading out asteroid
else if (status == STATUS_FADING_OUT) {
paint.setAlpha((int)(255 * (1.0*timeCounter/FADING_OUT_DURATION)));
canvas.save();
canvas.translate(x, y);
canvas.drawLines(points, paint);
canvas.restore();
paint.setAlpha(255);
}
// splitting up
else if (status == STATUS_SPLITTING_UP) {
paint.setAlpha((int)(255 * (1.0*timeCounter/SPLITTING_UP_DURATION)));
canvas.save();
canvas.translate(x + ((1.f*SPLITTING_UP_DURATION - timeCounter)/SPLITTING_UP_DURATION)*SPLITTING_UP_OFFSET, y);
canvas.drawLines(points, 0, rightPoints*4+4, paint);
canvas.restore();
canvas.save();
canvas.translate(x - ((1.f*SPLITTING_UP_DURATION - timeCounter)/SPLITTING_UP_DURATION)*SPLITTING_UP_OFFSET, y);
canvas.drawLines(altPoints, 0, leftPoints*4+4, paint);
canvas.restore();
paint.setAlpha(255);
}
// held in place
else if (status == STATUS_HELD_IN_PLACE) {
canvas.save();
canvas.translate(x, y);
canvas.drawLines(points, paint);
canvas.restore();
}
}
}
@Override
public void update() {
update(1.0f);
}
public void update(float speedModifier) {
long timeElapsed = System.currentTimeMillis() - lastUpdateTime;
lastUpdateTime = System.currentTimeMillis();
float timeModifier = 1.f*timeElapsed/1000;
x = x + (dirX*speed*timeModifier*speedModifier);
y = y + (MyGameView.gravity*dirY*speed*timeModifier*speedModifier);
if (timeCounter > 0) {
timeCounter -= timeElapsed;
}
// broken up item
if (status == STATUS_BREAKING_UP) {
for (LineSegment lineSegment : lineSegments) {
lineSegment.update(timeModifier*speedModifier);
}
if (timeCounter <= 0) {
setInvisible();
}
}
// disappearing asteroid
else if (status == STATUS_DISAPPEARING) {
// update all points
for (int i = 0; i < points.length; i++) {
altPoints[i] = factor*points[i];
}
if (factor < DISAPPEARING_FACTOR || timeCounter <= 0) {
setInvisible();
}
}
// fading out asteroid
else if (status == STATUS_FADING_OUT) {
if (timeCounter <= 0) {
setInvisible();
}
}
// splitting up asteroid
else if (status == STATUS_SPLITTING_UP) {
if (timeCounter <= 0) {
setInvisible();
}
}
// held in place asteroid
else if (status == STATUS_HELD_IN_PLACE) {
// update speed
speed *= SPEED_HELD_IN_PLACE_FACTOR;
if (speed < 0.01) {
speed = 0;
}
if (timeCounter <= 0) {
fadeOut(FADE_OUT_FROM_MAGNET);
}
}
// invisible asteroid
else if (status == STATUS_INVISIBLE) {
if (timeCounter <= 0) {
status = STATUS_NEEDS_RESET;
}
}
}
/**
* Makes asteroid invisible
*/
public void setInvisible() {
status = STATUS_INVISIBLE;
timeCounter = INVISIBLE_DURATION;
speed = SPEED_INVISIBLE;
dirX = 0;
dirY = 1;
}
/**
* Sets factor, used for black hole
* @param factor factor
*/
public void setFactor(float factor) {
this.factor = factor;
}
/**
* Returns index into points closest to the given angle
* @param angle angle to check
* @return index into points closest to the given angle
*/
public int getClosestPointsIndex(double angle) {
int i;
for(i = 0; i < angles.length; i++) {
if (angles[i] >= angle) {
break;
}
}
// handle special cases
if (i == 0 || i == angles.length) {
return points.length-2;
} else {
return 4*i-4;
}
}
}
| true | true | public void splitUp() {
if (status == STATUS_NORMAL || status == STATUS_HELD_IN_PLACE) {
int indexRight = 2, indexLeft = 0;
boolean leftSwitch = false, rightSwitch = false;
// start at 2 so we get each pair of points (same values) for each corresponding angle
for (int i = 2; i < points.length-2; i+=4) {
// right points
if (angles[(i+2)/4] < Math.PI/2.0 || angles[(i+2)/4] > 3.0*Math.PI/2.0) {
// add one right point to left side
if (leftSwitch && !rightSwitch) {
// perfect split
points[i] = 0;
points[i+2] = 0;
altPoints[indexLeft] = points[i];
altPoints[indexLeft+1] = points[i+1];
altPoints[indexLeft+2] = points[i+2];
altPoints[indexLeft+3] = points[i+3];
indexLeft += 4;
rightSwitch = true;
}
points[indexRight] = points[i];
points[indexRight+1] = points[i+1];
points[indexRight+2] = points[i+2];
points[indexRight+3] = points[i+3];
indexRight += 4;
}
// left points
else {
// add one left point to right side
if (!leftSwitch) {
// perfect split
points[i] = 0;
points[i+2] = 0;
points[indexRight] = points[i];
points[indexRight+1] = points[i+1];
points[indexRight+2] = points[i+2];
points[indexRight+3] = points[i+3];
indexRight += 4;
leftSwitch = true;
}
altPoints[indexLeft] = points[i];
altPoints[indexLeft+1] = points[i+1];
// only add first point once on left side
if (indexLeft == 0) {
indexLeft += 2;
} else {
altPoints[indexLeft+2] = points[i+2];
altPoints[indexLeft+3] = points[i+3];
indexLeft += 4;
}
}
}
// close right points
points[indexRight] = points[points.length-2];
points[indexRight+1] = points[points.length-1];
// close left points
altPoints[indexLeft] = altPoints[0];
altPoints[indexLeft+1] = altPoints[1];
speed = 0;
status = STATUS_SPLITTING_UP;
timeCounter = SPLITTING_UP_DURATION;
LocalStatistics.getInstance().asteroidsDestroyedByDrill++;
}
}
| public void splitUp() {
if (status == STATUS_NORMAL || status == STATUS_HELD_IN_PLACE) {
int indexRight = 2, indexLeft = 0;
boolean leftSwitch = false, rightSwitch = false;
// start at 2 so we get each pair of points (same values) for each corresponding angle
for (int i = 2; i < points.length-2; i+=4) {
// right points
if (angles[(i+2)/4] < Math.PI/2.0 || angles[(i+2)/4] > 3.0*Math.PI/2.0) {
// add one right point to left side
if (leftSwitch && !rightSwitch) {
// perfect split
points[i] = 0;
points[i+2] = 0;
altPoints[indexLeft] = points[i];
altPoints[indexLeft+1] = points[i+1];
altPoints[indexLeft+2] = points[i+2];
altPoints[indexLeft+3] = points[i+3];
indexLeft += 4;
rightSwitch = true;
}
points[indexRight] = points[i];
points[indexRight+1] = points[i+1];
points[indexRight+2] = points[i+2];
points[indexRight+3] = points[i+3];
indexRight += 4;
}
// left points
else {
// add one left point to right side
if (!leftSwitch) {
// perfect split
points[i] = 0;
points[i+2] = 0;
points[indexRight] = points[i];
points[indexRight+1] = points[i+1];
points[indexRight+2] = points[i+2];
points[indexRight+3] = points[i+3];
indexRight += 4;
leftSwitch = true;
}
altPoints[indexLeft] = points[i];
altPoints[indexLeft+1] = points[i+1];
// only add first point once on left side
if (indexLeft == 0) {
indexLeft += 2;
} else {
altPoints[indexLeft+2] = points[i+2];
altPoints[indexLeft+3] = points[i+3];
indexLeft += 4;
}
}
}
// close right points
points[indexRight] = points[points.length-2];
points[indexRight+1] = points[points.length-1];
// close left points
altPoints[indexLeft] = altPoints[0];
altPoints[indexLeft+1] = altPoints[1];
// NOTE: don't reset speed here so that the split up animation looks smoother
status = STATUS_SPLITTING_UP;
timeCounter = SPLITTING_UP_DURATION;
LocalStatistics.getInstance().asteroidsDestroyedByDrill++;
}
}
|
diff --git a/src/org/geometerplus/zlibrary/ui/android/view/AnimationProvider.java b/src/org/geometerplus/zlibrary/ui/android/view/AnimationProvider.java
index 2773a471..2455bd62 100644
--- a/src/org/geometerplus/zlibrary/ui/android/view/AnimationProvider.java
+++ b/src/org/geometerplus/zlibrary/ui/android/view/AnimationProvider.java
@@ -1,230 +1,230 @@
/*
* Copyright (C) 2007-2011 Geometer Plus <[email protected]>
*
* 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.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
package org.geometerplus.zlibrary.ui.android.view;
import java.util.*;
import android.graphics.*;
import android.util.FloatMath;
import org.geometerplus.zlibrary.core.library.ZLibrary;
import org.geometerplus.zlibrary.core.view.ZLView;
abstract class AnimationProvider {
static enum Mode {
NoScrolling(false),
ManualScrolling(false),
AnimatedScrollingForward(true),
AnimatedScrollingBackward(true);
final boolean Auto;
Mode(boolean auto) {
Auto = auto;
}
}
private Mode myMode = Mode.NoScrolling;
private final BitmapManager myBitmapManager;
protected int myStartX;
protected int myStartY;
protected int myEndX;
protected int myEndY;
protected ZLView.Direction myDirection;
protected float mySpeed;
protected int myWidth;
protected int myHeight;
protected AnimationProvider(BitmapManager bitmapManager) {
myBitmapManager = bitmapManager;
}
Mode getMode() {
return myMode;
}
final void terminate() {
myMode = Mode.NoScrolling;
mySpeed = 0;
myDrawInfos.clear();
}
final void startManualScrolling(int x, int y) {
if (!myMode.Auto) {
myMode = Mode.ManualScrolling;
myEndX = myStartX = x;
myEndY = myStartY = y;
}
}
void scrollTo(int x, int y) {
if (myMode == Mode.ManualScrolling) {
myEndX = x;
myEndY = y;
}
}
void startAnimatedScrolling(int x, int y, int speed) {
if (myMode != Mode.ManualScrolling) {
return;
}
if (getPageToScrollTo(x, y) == ZLView.PageIndex.current) {
return;
}
final int diff = myDirection.IsHorizontal ? x - myStartX : y - myStartY;
final int dpi = ZLibrary.Instance().getDisplayDPI();
final int minDiff = myDirection.IsHorizontal ?
(myWidth > myHeight ? myWidth / 4 : myWidth / 3) :
(myHeight > myWidth ? myHeight / 4 : myHeight / 3);
- boolean forward = Math.abs(diff) > Math.min(minDiff, dpi);
+ boolean forward = Math.abs(diff) > Math.min(minDiff, dpi / 2);
myMode = forward ? Mode.AnimatedScrollingForward : Mode.AnimatedScrollingBackward;
float velocity = 15;
if (myDrawInfos.size() > 1) {
int duration = 0;
for (DrawInfo info : myDrawInfos) {
duration += info.Duration;
}
duration /= myDrawInfos.size();
final long time = System.currentTimeMillis();
myDrawInfos.add(new DrawInfo(x, y, time, time + duration));
velocity = 0;
for (int i = 1; i < myDrawInfos.size(); ++i) {
final DrawInfo info0 = myDrawInfos.get(i - 1);
final DrawInfo info1 = myDrawInfos.get(i);
final float dX = info0.X - info1.X;
final float dY = info0.Y - info1.Y;
velocity += FloatMath.sqrt(dX * dX + dY * dY) / Math.max(1, info1.Start - info0.Start);
}
velocity /= myDrawInfos.size() - 1;
velocity *= duration;
velocity = Math.min(100, Math.max(15, velocity));
}
myDrawInfos.clear();
if (getPageToScrollTo() == ZLView.PageIndex.previous) {
forward = !forward;
}
switch (myDirection) {
case up:
case rightToLeft:
mySpeed = forward ? -velocity : velocity;
break;
case leftToRight:
case down:
mySpeed = forward ? velocity : -velocity;
break;
}
startAnimatedScrollingInternal(speed);
}
public void startAnimatedScrolling(ZLView.PageIndex pageIndex, Integer x, Integer y, int speed) {
if (myMode.Auto) {
return;
}
terminate();
myMode = Mode.AnimatedScrollingForward;
switch (myDirection) {
case up:
case rightToLeft:
mySpeed = pageIndex == ZLView.PageIndex.next ? -15 : 15;
break;
case leftToRight:
case down:
mySpeed = pageIndex == ZLView.PageIndex.next ? 15 : -15;
break;
}
setupAnimatedScrollingStart(x, y);
startAnimatedScrollingInternal(speed);
}
protected abstract void startAnimatedScrollingInternal(int speed);
protected abstract void setupAnimatedScrollingStart(Integer x, Integer y);
boolean inProgress() {
return myMode != Mode.NoScrolling;
}
protected int getScrollingShift() {
return myDirection.IsHorizontal ? myEndX - myStartX : myEndY - myStartY;
}
final void setup(ZLView.Direction direction, int width, int height) {
myDirection = direction;
myWidth = width;
myHeight = height;
}
abstract void doStep();
int getScrolledPercent() {
final int full = myDirection.IsHorizontal ? myWidth : myHeight;
final int shift = Math.abs(getScrollingShift());
return 100 * shift / full;
}
static class DrawInfo {
final int X, Y;
final long Start;
final int Duration;
DrawInfo(int x, int y, long start, long finish) {
X = x;
Y = y;
Start = start;
Duration = (int)(finish - start);
}
}
final private List<DrawInfo> myDrawInfos = new LinkedList<DrawInfo>();
final void draw(Canvas canvas) {
myBitmapManager.setSize(myWidth, myHeight);
final long start = System.currentTimeMillis();
drawInternal(canvas);
myDrawInfos.add(new DrawInfo(myEndX, myEndY, start, System.currentTimeMillis()));
if (myDrawInfos.size() > 3) {
myDrawInfos.remove(0);
}
}
protected abstract void drawInternal(Canvas canvas);
abstract ZLView.PageIndex getPageToScrollTo(int x, int y);
final ZLView.PageIndex getPageToScrollTo() {
return getPageToScrollTo(myEndX, myEndY);
}
protected Bitmap getBitmapFrom() {
return myBitmapManager.getBitmap(ZLView.PageIndex.current);
}
protected Bitmap getBitmapTo() {
return myBitmapManager.getBitmap(getPageToScrollTo());
}
}
| true | true | void startAnimatedScrolling(int x, int y, int speed) {
if (myMode != Mode.ManualScrolling) {
return;
}
if (getPageToScrollTo(x, y) == ZLView.PageIndex.current) {
return;
}
final int diff = myDirection.IsHorizontal ? x - myStartX : y - myStartY;
final int dpi = ZLibrary.Instance().getDisplayDPI();
final int minDiff = myDirection.IsHorizontal ?
(myWidth > myHeight ? myWidth / 4 : myWidth / 3) :
(myHeight > myWidth ? myHeight / 4 : myHeight / 3);
boolean forward = Math.abs(diff) > Math.min(minDiff, dpi);
myMode = forward ? Mode.AnimatedScrollingForward : Mode.AnimatedScrollingBackward;
float velocity = 15;
if (myDrawInfos.size() > 1) {
int duration = 0;
for (DrawInfo info : myDrawInfos) {
duration += info.Duration;
}
duration /= myDrawInfos.size();
final long time = System.currentTimeMillis();
myDrawInfos.add(new DrawInfo(x, y, time, time + duration));
velocity = 0;
for (int i = 1; i < myDrawInfos.size(); ++i) {
final DrawInfo info0 = myDrawInfos.get(i - 1);
final DrawInfo info1 = myDrawInfos.get(i);
final float dX = info0.X - info1.X;
final float dY = info0.Y - info1.Y;
velocity += FloatMath.sqrt(dX * dX + dY * dY) / Math.max(1, info1.Start - info0.Start);
}
velocity /= myDrawInfos.size() - 1;
velocity *= duration;
velocity = Math.min(100, Math.max(15, velocity));
}
myDrawInfos.clear();
if (getPageToScrollTo() == ZLView.PageIndex.previous) {
forward = !forward;
}
switch (myDirection) {
case up:
case rightToLeft:
mySpeed = forward ? -velocity : velocity;
break;
case leftToRight:
case down:
mySpeed = forward ? velocity : -velocity;
break;
}
startAnimatedScrollingInternal(speed);
}
| void startAnimatedScrolling(int x, int y, int speed) {
if (myMode != Mode.ManualScrolling) {
return;
}
if (getPageToScrollTo(x, y) == ZLView.PageIndex.current) {
return;
}
final int diff = myDirection.IsHorizontal ? x - myStartX : y - myStartY;
final int dpi = ZLibrary.Instance().getDisplayDPI();
final int minDiff = myDirection.IsHorizontal ?
(myWidth > myHeight ? myWidth / 4 : myWidth / 3) :
(myHeight > myWidth ? myHeight / 4 : myHeight / 3);
boolean forward = Math.abs(diff) > Math.min(minDiff, dpi / 2);
myMode = forward ? Mode.AnimatedScrollingForward : Mode.AnimatedScrollingBackward;
float velocity = 15;
if (myDrawInfos.size() > 1) {
int duration = 0;
for (DrawInfo info : myDrawInfos) {
duration += info.Duration;
}
duration /= myDrawInfos.size();
final long time = System.currentTimeMillis();
myDrawInfos.add(new DrawInfo(x, y, time, time + duration));
velocity = 0;
for (int i = 1; i < myDrawInfos.size(); ++i) {
final DrawInfo info0 = myDrawInfos.get(i - 1);
final DrawInfo info1 = myDrawInfos.get(i);
final float dX = info0.X - info1.X;
final float dY = info0.Y - info1.Y;
velocity += FloatMath.sqrt(dX * dX + dY * dY) / Math.max(1, info1.Start - info0.Start);
}
velocity /= myDrawInfos.size() - 1;
velocity *= duration;
velocity = Math.min(100, Math.max(15, velocity));
}
myDrawInfos.clear();
if (getPageToScrollTo() == ZLView.PageIndex.previous) {
forward = !forward;
}
switch (myDirection) {
case up:
case rightToLeft:
mySpeed = forward ? -velocity : velocity;
break;
case leftToRight:
case down:
mySpeed = forward ? velocity : -velocity;
break;
}
startAnimatedScrollingInternal(speed);
}
|
diff --git a/src/main/java/com/theoryinpractise/clojure/AbstractClojureCompilerMojo.java b/src/main/java/com/theoryinpractise/clojure/AbstractClojureCompilerMojo.java
index a1fe806..df739ad 100644
--- a/src/main/java/com/theoryinpractise/clojure/AbstractClojureCompilerMojo.java
+++ b/src/main/java/com/theoryinpractise/clojure/AbstractClojureCompilerMojo.java
@@ -1,465 +1,465 @@
/*
* Copyright (c) Mark Derricutt 2010.
*
* The use and distribution terms for this software are covered by the Eclipse Public License 1.0
* (http://opensource.org/licenses/eclipse-1.0.php) which can be found in the file epl-v10.html
* at the root of this distribution.
*
* By using this software in any fashion, you are agreeing to be bound by the terms of this license.
*
* You must not remove this notice, or any other, from this software.
*/
package com.theoryinpractise.clojure;
import org.apache.commons.exec.*;
import org.apache.commons.lang.SystemUtils;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.toolchain.Toolchain;
import org.apache.maven.toolchain.ToolchainManager;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;
public abstract class AbstractClojureCompilerMojo extends AbstractMojo {
/**
* The current toolchain maanager instance
*
* @component
*/
private ToolchainManager toolchainManager;
/**
* The current build session instance. This is used for
* toolchain manager API calls.
*
* @parameter expression="${session}"
* @required
* @readonly
*/
private MavenSession session;
/**
* Base directory of the project.
*
* @parameter expression="${basedir}"
* @required
* @readonly
*/
protected File baseDirectory;
/**
* Project classpath.
*
* @parameter default-value="${project.compileClasspathElements}"
* @required
* @readonly
*/
protected List<String> classpathElements;
/**
* Project test classpath.
*
* @parameter default-value="${project.testClasspathElements}"
* @required
* @readonly
*/
protected List<String> testClasspathElements;
/**
* Location of the file.
*
* @parameter default-value="${project.build.outputDirectory}"
* @required
*/
protected File outputDirectory;
/**
* Location of the file.
*
* @parameter default-value="${project.build.testOutputDirectory}"
* @required
*/
protected File testOutputDirectory;
/**
* Location of the source files.
*
* @parameter
*/
private String[] sourceDirectories = new String[]{"src/main/clojure"};
/**
* Location of the source files.
*
* @parameter
*/
private String[] testSourceDirectories = new String[]{"src/test/clojure"};
/**
* Location of the source files.
*
* @parameter default-value="${project.build.testSourceDirectory}"
* @required
*/
protected File baseTestSourceDirectory;
/**
* Location of the generated source files.
*
* @parameter default-value="${project.build.outputDirectory}/../generated-sources"
* @required
*/
protected File generatedSourceDirectory;
/**
* Working directory for forked java clojure process.
*
* @parameter
*/
protected File workingDirectory;
/**
* Should we compile all namespaces or only those defined?
*
* @parameter default-value="false"
*/
protected boolean compileDeclaredNamespaceOnly;
/**
* A list of namespaces to compile
*
* @parameter
*/
protected String[] namespaces;
/**
* Should we test all namespaces or only those defined?
*
* @parameter default-value="false"
*/
protected boolean testDeclaredNamespaceOnly;
/**
* A list of test namespaces to compile
*
* @parameter
*/
protected String[] testNamespaces;
/**
* Classes to put onto the command line before the main class
*
* @parameter
*/
private List<String> prependClasses;
/**
* Clojure/Java command-line options
*
* @parameter expression="${clojure.options}"
*/
private String clojureOptions = "";
/**
* Run with test-classpath or compile-classpath?
*
* @parameter expression="${clojure.runwith.test}" default-value="true"
*/
private boolean runWithTests;
/**
* A list of namespaces whose source files will be copied to the output.
*
* @parameter
*/
protected String[] copiedNamespaces;
/**
* Should we copy the source of all namespaces or only those defined?
*
* @parameter default-value="false"
*/
protected boolean copyDeclaredNamespaceOnly;
/**
* Should the source files of all compiled namespaces be copied to the output?
* This overrides copiedNamespaces and copyDeclaredNamespaceOnly.
*
* @parameter default-value="false"
*/
private boolean copyAllCompiledNamespaces;
/**
* Should reflective invocations in Clojure source emit warnings? Corresponds with
* the *warn-on-reflection* var and the clojure.compile.warn-on-reflection system property.
*
* @parameter default-value="false"
*/
private boolean warnOnReflection;
/**
* Specify additional vmargs to use when running clojure or swank.
*
* @parameter expression="${clojure.vmargs}"
*/
private String vmargs;
/**
* Escapes the given file path so that it's safe for inclusion in a
* Clojure string literal.
*
* @param directory directory path
* @param file file name
* @return escaped file path, ready for inclusion in a string literal
*/
protected String escapeFilePath(String directory, String file) {
return escapeFilePath(new File(directory, file));
}
/**
* Escapes the given file path so that it's safe for inclusion in a
* Clojure string literal.
*
* @param file
* @return escaped file path, ready for inclusion in a string literal
*/
protected String escapeFilePath(final File file) {
// TODO: Should handle also possible newlines, etc.
return file.getPath().replace("\\", "\\\\");
}
private String getJavaExecutable() throws MojoExecutionException {
Toolchain tc = toolchainManager.getToolchainFromBuildContext("jdk", //NOI18N
session);
if (tc != null) {
getLog().info("Toolchain in clojure-maven-plugin: " + tc);
String foundExecutable = tc.findTool("java");
if (foundExecutable != null) {
return foundExecutable;
} else {
throw new MojoExecutionException("Unable to find 'java' executable for toolchain: " + tc);
}
}
return "java";
}
protected File getWorkingDirectory() throws MojoExecutionException {
if (workingDirectory != null) {
if (workingDirectory.exists()) {
return workingDirectory;
} else {
throw new MojoExecutionException("Directory specified in <workingDirectory/> does not exists: " + workingDirectory.getPath());
}
} else {
return session.getCurrentProject().getBasedir();
}
}
private File[] translatePaths(String[] paths) {
File[] files = new File[paths.length];
for (int i = 0; i < paths.length; i++) {
files[i] = new File(baseDirectory, paths[i]);
}
return files;
}
protected NamespaceInFile[] discoverNamespaces() throws MojoExecutionException {
return new NamespaceDiscovery(getLog(), compileDeclaredNamespaceOnly).discoverNamespacesIn(namespaces, translatePaths(sourceDirectories));
}
protected NamespaceInFile[] discoverNamespacesToCopy() throws MojoExecutionException {
if (copyAllCompiledNamespaces)
return discoverNamespaces();
else
return new NamespaceDiscovery(getLog(), copyDeclaredNamespaceOnly).discoverNamespacesIn(copiedNamespaces, translatePaths(sourceDirectories));
}
public enum SourceDirectory {
COMPILE, TEST
}
public String getSourcePath(SourceDirectory... sourceDirectoryTypes) {
return getPath(getSourceDirectories(sourceDirectoryTypes));
}
public File[] getSourceDirectories(SourceDirectory... sourceDirectoryTypes) {
List<File> dirs = new ArrayList<File>();
if (Arrays.asList(sourceDirectoryTypes).contains(SourceDirectory.COMPILE)) {
dirs.add(generatedSourceDirectory);
dirs.addAll(Arrays.asList(translatePaths(sourceDirectories)));
}
if (Arrays.asList(sourceDirectoryTypes).contains(SourceDirectory.TEST)) {
dirs.add(baseTestSourceDirectory);
dirs.addAll(Arrays.asList(translatePaths(testSourceDirectories)));
}
return dirs.toArray(new File[]{});
}
private String getPath(File[] sourceDirectory) {
String cp = "";
for (File directory : sourceDirectory) {
cp = cp + directory.getPath() + File.pathSeparator;
}
return cp.substring(0, cp.length() - 1);
}
public List<String> getRunWithClasspathElements() {
return runWithTests ? testClasspathElements : classpathElements;
}
protected void copyNamespaceSourceFilesToOutput(File outputDirectory, NamespaceInFile[] discoveredNamespaces) throws MojoExecutionException {
for (NamespaceInFile ns : discoveredNamespaces) {
File outputFile = new File(outputDirectory, ns.getFilename());
outputFile.getParentFile().mkdirs();
try {
FileInputStream is = new FileInputStream(ns.getSourceFile());
try {
FileOutputStream os = new FileOutputStream(outputFile);
try {
int amountRead;
byte[] buffer = new byte[4096];
while ((amountRead = is.read(buffer)) >= 0) {
os.write(buffer, 0, amountRead);
}
is.close();
} finally {
is.close();
}
} finally {
is.close();
}
} catch (IOException ex) {
throw new MojoExecutionException("Couldn't copy the clojure source files to the output", ex);
}
}
}
protected void callClojureWith(
File[] sourceDirectory,
File outputDirectory,
List<String> compileClasspathElements,
String mainClass,
NamespaceInFile[] namespaceArgs) throws MojoExecutionException {
callClojureWith(ExecutionMode.BATCH, sourceDirectory, outputDirectory, compileClasspathElements, mainClass, namespaceArgs);
}
protected void callClojureWith(
File[] sourceDirectory,
File outputDirectory,
List<String> compileClasspathElements,
String mainClass,
String[] clojureArgs) throws MojoExecutionException {
callClojureWith(ExecutionMode.BATCH, sourceDirectory, outputDirectory, compileClasspathElements, mainClass, clojureArgs);
}
protected void callClojureWith(
ExecutionMode executionMode,
File[] sourceDirectory,
File outputDirectory,
List<String> compileClasspathElements,
String mainClass,
NamespaceInFile[] namespaceArgs) throws MojoExecutionException {
String[] stringArgs = new String[namespaceArgs.length];
for (int i = 0; i < namespaceArgs.length; i++) {
stringArgs[i] = namespaceArgs[i].getName();
}
callClojureWith(executionMode, sourceDirectory, outputDirectory, compileClasspathElements, mainClass, stringArgs);
}
protected void callClojureWith(
ExecutionMode executionMode,
File[] sourceDirectory,
File outputDirectory,
List<String> compileClasspathElements,
String mainClass,
String[] clojureArgs) throws MojoExecutionException {
outputDirectory.mkdirs();
String cp = getPath(sourceDirectory);
- cp = cp + outputDirectory.getPath() + File.pathSeparator;
+ cp = cp + File.pathSeparator + outputDirectory.getPath() + File.pathSeparator;
for (Object classpathElement : compileClasspathElements) {
cp = cp + File.pathSeparator + classpathElement;
}
cp = cp.replaceAll("\\s", "\\ ");
final String javaExecutable = getJavaExecutable();
getLog().debug("Java exectuable used: " + javaExecutable);
getLog().debug("Clojure classpath: " + cp);
CommandLine cl = null;
if (ExecutionMode.INTERACTIVE == executionMode && SystemUtils.IS_OS_WINDOWS) {
cl = new CommandLine("cmd");
cl.addArgument("/c");
cl.addArgument("start");
cl.addArgument(javaExecutable);
} else {
cl = new CommandLine(javaExecutable);
}
if (vmargs != null) {
cl.addArguments(vmargs, false);
}
cl.addArgument("-cp");
cl.addArgument(cp, false);
cl.addArgument("-Dclojure.compile.path=" + outputDirectory.getPath(), false);
if (warnOnReflection) cl.addArgument("-Dclojure.compile.warn-on-reflection=true");
cl.addArguments(clojureOptions, false);
if (prependClasses != null) {
cl.addArguments(prependClasses.toArray(new String[prependClasses.size()]));
}
cl.addArgument(mainClass);
if (clojureArgs != null) {
cl.addArguments(clojureArgs, false);
}
getLog().debug("Command line: " + cl.toString());
Executor exec = new DefaultExecutor();
Map<String, String> env = new HashMap<String, String>(System.getenv());
// env.put("path", ";");
// env.put("path", System.getProperty("java.home"));
ExecuteStreamHandler handler = new PumpStreamHandler(System.out, System.err, System.in);
exec.setStreamHandler(handler);
exec.setWorkingDirectory(getWorkingDirectory());
int status;
try {
status = exec.execute(cl, env);
} catch (ExecuteException e) {
status = e.getExitValue();
} catch (IOException e) {
status = 1;
}
if (status != 0) {
throw new MojoExecutionException("Clojure failed.");
}
}
}
| true | true | protected void callClojureWith(
ExecutionMode executionMode,
File[] sourceDirectory,
File outputDirectory,
List<String> compileClasspathElements,
String mainClass,
String[] clojureArgs) throws MojoExecutionException {
outputDirectory.mkdirs();
String cp = getPath(sourceDirectory);
cp = cp + outputDirectory.getPath() + File.pathSeparator;
for (Object classpathElement : compileClasspathElements) {
cp = cp + File.pathSeparator + classpathElement;
}
cp = cp.replaceAll("\\s", "\\ ");
final String javaExecutable = getJavaExecutable();
getLog().debug("Java exectuable used: " + javaExecutable);
getLog().debug("Clojure classpath: " + cp);
CommandLine cl = null;
if (ExecutionMode.INTERACTIVE == executionMode && SystemUtils.IS_OS_WINDOWS) {
cl = new CommandLine("cmd");
cl.addArgument("/c");
cl.addArgument("start");
cl.addArgument(javaExecutable);
} else {
cl = new CommandLine(javaExecutable);
}
if (vmargs != null) {
cl.addArguments(vmargs, false);
}
cl.addArgument("-cp");
cl.addArgument(cp, false);
cl.addArgument("-Dclojure.compile.path=" + outputDirectory.getPath(), false);
if (warnOnReflection) cl.addArgument("-Dclojure.compile.warn-on-reflection=true");
cl.addArguments(clojureOptions, false);
if (prependClasses != null) {
cl.addArguments(prependClasses.toArray(new String[prependClasses.size()]));
}
cl.addArgument(mainClass);
if (clojureArgs != null) {
cl.addArguments(clojureArgs, false);
}
getLog().debug("Command line: " + cl.toString());
Executor exec = new DefaultExecutor();
Map<String, String> env = new HashMap<String, String>(System.getenv());
// env.put("path", ";");
// env.put("path", System.getProperty("java.home"));
ExecuteStreamHandler handler = new PumpStreamHandler(System.out, System.err, System.in);
exec.setStreamHandler(handler);
exec.setWorkingDirectory(getWorkingDirectory());
int status;
try {
status = exec.execute(cl, env);
} catch (ExecuteException e) {
status = e.getExitValue();
} catch (IOException e) {
status = 1;
}
if (status != 0) {
throw new MojoExecutionException("Clojure failed.");
}
}
| protected void callClojureWith(
ExecutionMode executionMode,
File[] sourceDirectory,
File outputDirectory,
List<String> compileClasspathElements,
String mainClass,
String[] clojureArgs) throws MojoExecutionException {
outputDirectory.mkdirs();
String cp = getPath(sourceDirectory);
cp = cp + File.pathSeparator + outputDirectory.getPath() + File.pathSeparator;
for (Object classpathElement : compileClasspathElements) {
cp = cp + File.pathSeparator + classpathElement;
}
cp = cp.replaceAll("\\s", "\\ ");
final String javaExecutable = getJavaExecutable();
getLog().debug("Java exectuable used: " + javaExecutable);
getLog().debug("Clojure classpath: " + cp);
CommandLine cl = null;
if (ExecutionMode.INTERACTIVE == executionMode && SystemUtils.IS_OS_WINDOWS) {
cl = new CommandLine("cmd");
cl.addArgument("/c");
cl.addArgument("start");
cl.addArgument(javaExecutable);
} else {
cl = new CommandLine(javaExecutable);
}
if (vmargs != null) {
cl.addArguments(vmargs, false);
}
cl.addArgument("-cp");
cl.addArgument(cp, false);
cl.addArgument("-Dclojure.compile.path=" + outputDirectory.getPath(), false);
if (warnOnReflection) cl.addArgument("-Dclojure.compile.warn-on-reflection=true");
cl.addArguments(clojureOptions, false);
if (prependClasses != null) {
cl.addArguments(prependClasses.toArray(new String[prependClasses.size()]));
}
cl.addArgument(mainClass);
if (clojureArgs != null) {
cl.addArguments(clojureArgs, false);
}
getLog().debug("Command line: " + cl.toString());
Executor exec = new DefaultExecutor();
Map<String, String> env = new HashMap<String, String>(System.getenv());
// env.put("path", ";");
// env.put("path", System.getProperty("java.home"));
ExecuteStreamHandler handler = new PumpStreamHandler(System.out, System.err, System.in);
exec.setStreamHandler(handler);
exec.setWorkingDirectory(getWorkingDirectory());
int status;
try {
status = exec.execute(cl, env);
} catch (ExecuteException e) {
status = e.getExitValue();
} catch (IOException e) {
status = 1;
}
if (status != 0) {
throw new MojoExecutionException("Clojure failed.");
}
}
|
diff --git a/src/share/classes/com/sun/tools/javafx/comp/JavafxResolve.java b/src/share/classes/com/sun/tools/javafx/comp/JavafxResolve.java
index 143a2bc20..d6475c32d 100644
--- a/src/share/classes/com/sun/tools/javafx/comp/JavafxResolve.java
+++ b/src/share/classes/com/sun/tools/javafx/comp/JavafxResolve.java
@@ -1,2166 +1,2172 @@
/*
* Copyright 2008 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package com.sun.tools.javafx.comp;
import com.sun.tools.javac.comp.*;
import com.sun.tools.javac.util.*;
import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
import com.sun.tools.javac.code.*;
import com.sun.tools.javac.jvm.*;
import com.sun.tools.javac.tree.*;
import com.sun.tools.javac.code.Type.*;
import com.sun.tools.javac.code.Symbol.*;
import static com.sun.tools.javac.code.Flags.*;
import static com.sun.tools.javac.code.Kinds.*;
import static com.sun.tools.javac.code.TypeTags.*;
import javax.lang.model.element.ElementVisitor;
import com.sun.tools.javafx.code.*;
import com.sun.tools.javafx.tree.*;
import com.sun.tools.javafx.util.MsgSym;
import java.util.HashSet;
import java.util.Set;
/** Helper class for name resolution, used mostly by the attribution phase.
*
* <p><b>This is NOT part of any API supported by Sun Microsystems. If
* you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class JavafxResolve {
protected static final Context.Key<JavafxResolve> javafxResolveKey =
new Context.Key<JavafxResolve>();
Name.Table names;
Log log;
JavafxSymtab syms;
JavafxCheck chk;
Infer infer;
JavafxClassReader reader;
JavafxTreeInfo treeinfo;
JavafxTypes types;
public final boolean boxingEnabled; // = source.allowBoxing();
public final boolean varargsEnabled; // = source.allowVarargs();
private final boolean debugResolve;
public static JavafxResolve instance(Context context) {
JavafxResolve instance = context.get(javafxResolveKey);
if (instance == null)
instance = new JavafxResolve(context);
return instance;
}
protected JavafxResolve(Context context) {
context.put(javafxResolveKey, this);
syms = (JavafxSymtab)JavafxSymtab.instance(context);
varNotFound = new
ResolveError(ABSENT_VAR, syms.errSymbol, "variable not found");
wrongMethod = new
ResolveError(WRONG_MTH, syms.errSymbol, "method not found");
wrongMethods = new
ResolveError(WRONG_MTHS, syms.errSymbol, "wrong methods");
methodNotFound = new
ResolveError(ABSENT_MTH, syms.errSymbol, "method not found");
typeNotFound = new
ResolveError(ABSENT_TYP, syms.errSymbol, "type not found");
names = Name.Table.instance(context);
log = Log.instance(context);
chk = (JavafxCheck)JavafxCheck.instance(context);
infer = Infer.instance(context);
reader = JavafxClassReader.instance(context);
treeinfo = JavafxTreeInfo.instance(context);
types = JavafxTypes.instance(context);
Source source = Source.instance(context);
boxingEnabled = source.allowBoxing();
varargsEnabled = source.allowVarargs();
Options options = Options.instance(context);
debugResolve = options.get("debugresolve") != null;
}
/** error symbols, which are returned when resolution fails
*/
final ResolveError varNotFound;
final ResolveError wrongMethod;
final ResolveError wrongMethods;
final ResolveError methodNotFound;
final ResolveError typeNotFound;
/* ************************************************************************
* Identifier resolution
*************************************************************************/
/** An environment is "static" if its static level is greater than
* the one of its outer environment
*/
// JavaFX change
public
// JavaFX change
static boolean isStatic(JavafxEnv<JavafxAttrContext> env) {
return env.info.staticLevel > env.outer.info.staticLevel;
}
/** An environment is an "initializer" if it is a constructor or
* an instance initializer.
*/
static boolean isInitializer(JavafxEnv<JavafxAttrContext> env) {
Symbol owner = env.info.scope.owner;
return owner.isConstructor() ||
owner.owner.kind == TYP &&
(owner.kind == VAR ||
owner.kind == MTH && (owner.flags() & BLOCK) != 0) &&
(owner.flags() & STATIC) == 0;
}
/** Is class accessible in given evironment?
* @param env The current environment.
* @param c The class whose accessibility is checked.
*/
public boolean isAccessible(JavafxEnv<JavafxAttrContext> env, TypeSymbol c) {
// because the SCRIPT_PRIVATE bit is too high for the switch, test it later
switch ((short)(c.flags() & Flags.AccessFlags)) {
case PRIVATE:
return
env.enclClass.sym.outermostClass() ==
c.owner.outermostClass();
case 0:
if ((c.flags() & JavafxFlags.SCRIPT_PRIVATE) != 0) {
// script-private
//System.err.println("isAccessible " + c + " = " + (env.enclClass.sym.outermostClass() ==
// c.outermostClass()) + ", enclClass " + env.enclClass.getName());
//System.err.println(" encl outer: " + env.enclClass.sym.outermostClass() + ", c outer: " + c.outermostClass());
return env.enclClass.sym.outermostClass() == c.outermostClass();
};
// 'package' access
return
env.toplevel.packge == c.owner // fast special case
||
env.toplevel.packge == c.packge()
||
// Hack: this case is added since synthesized default constructors
// of anonymous classes should be allowed to access
// classes which would be inaccessible otherwise.
env.enclFunction != null &&
(env.enclFunction.mods.flags & ANONCONSTR) != 0;
default: // error recovery
case PUBLIC:
return true;
case PROTECTED:
return
env.toplevel.packge == c.owner // fast special case
||
env.toplevel.packge == c.packge()
||
isInnerSubClass(env.enclClass.sym, c.owner);
}
}
//where
/** Is given class a subclass of given base class, or an inner class
* of a subclass?
* Return null if no such class exists.
* @param c The class which is the subclass or is contained in it.
* @param base The base class
*/
private boolean isInnerSubClass(ClassSymbol c, Symbol base) {
while (c != null && !c.isSubClass(base, types)) {
c = c.owner.enclClass();
}
return c != null;
}
boolean isAccessible(JavafxEnv<JavafxAttrContext> env, Type t) {
return (t.tag == ARRAY)
? isAccessible(env, types.elemtype(t))
: isAccessible(env, t.tsym);
}
/** Is symbol accessible as a member of given type in given evironment?
* @param env The current environment.
* @param site The type of which the tested symbol is regarded
* as a member.
* @param sym The symbol.
*/
public boolean isAccessible(JavafxEnv<JavafxAttrContext> env, Type site, Symbol sym) {
if (sym.name == names.init && sym.owner != site.tsym) return false;
if ((sym.flags() & (JavafxFlags.PUBLIC_READ | JavafxFlags.PUBLIC_INIT)) != 0) {
// assignment access handled elsewhere -- treat like
return isAccessible(env, site);
}
// if the READABLE flag isn't set, then access for read is the same as for write
return isAccessibleForWrite(env, site, sym);
}
/** Is symbol accessible for write as a member of given type in given evironment?
* @param env The current environment.
* @param site The type of which the tested symbol is regarded
* as a member.
* @param sym The symbol.
*/
public boolean isAccessibleForWrite(JavafxEnv<JavafxAttrContext> env, Type site, Symbol sym) {
if (sym.name == names.init && sym.owner != site.tsym) return false;
// because the SCRIPT_PRIVATE bit is too high for the switch, test it later
switch ((short)(sym.flags() & Flags.AccessFlags)) {
case PRIVATE:
return
(env.enclClass.sym == sym.owner // fast special case
||
env.enclClass.sym.outermostClass() ==
sym.owner.outermostClass())
&&
isInheritedIn(sym, site.tsym, types);
case 0:
if ((sym.flags() & JavafxFlags.SCRIPT_PRIVATE) != 0) {
// script-private
//TODO: don't know what is right
if (env.enclClass.sym == sym.owner) {
return true; // fast special case -- in this class
}
Symbol enclOuter = env.enclClass.sym.outermostClass();
Symbol ownerOuter = sym.owner.outermostClass();
return enclOuter == ownerOuter;
};
// 'package' access
PackageSymbol pkg = env.toplevel.packge;
boolean samePkg =
(pkg == sym.owner.owner // fast special case
||
pkg == sym.packge());
boolean typeAccessible = isAccessible(env, site);
// TODO: javac logic is to also 'and'-in inheritedIn.
// Based possibly on bugs in what is passed in,
// this doesn't work when accessing static variables in an outer class.
// When called from findVar this works because the site in the actual
// owner of the sym, but when coming from an ident and checkAssignable
// this isn't true.
//boolean inheritedIn = isInheritedIn(sym, site.tsym, types);
return samePkg && typeAccessible;
case PROTECTED:
return
(env.toplevel.packge == sym.owner.owner // fast special case
||
env.toplevel.packge == sym.packge()
||
isProtectedAccessible(sym, env.enclClass.sym, site)
||
// OK to select instance method or field from 'super' or type name
// (but type names should be disallowed elsewhere!)
env.info.selectSuper && (sym.flags() & STATIC) == 0 && sym.kind != TYP)
&&
isAccessible(env, site)
&&
// `sym' is accessible only if not overridden by
// another symbol which is a member of `site'
// (because, if it is overridden, `sym' is not strictly
// speaking a member of `site'.)
(sym.kind != MTH || sym.isConstructor() ||
types.implementation((MethodSymbol)sym, site.tsym, true) == sym);
default: // this case includes erroneous combinations as well
return isAccessible(env, site);
}
}
//where
/** Is given protected symbol accessible if it is selected from given site
* and the selection takes place in given class?
* @param sym The symbol with protected access
* @param c The class where the access takes place
* @site The type of the qualifier
*/
private
boolean isProtectedAccessible(Symbol sym, ClassSymbol c, Type site) {
while (c != null &&
!(types.isSuperType(types.erasure(sym.owner.type), c) &&
(c.flags() & INTERFACE) == 0 &&
// In JLS 2e 6.6.2.1, the subclass restriction applies
// only to instance fields and methods -- types are excluded
// regardless of whether they are declared 'static' or not.
((sym.flags() & STATIC) != 0 || sym.kind == TYP || types.isSuperType(site, c))))
c = c.owner.enclClass();
return c != null;
}
/** Try to instantiate the type of a method so that it fits
* given type arguments and argument types. If succesful, return
* the method's instantiated type, else return null.
* The instantiation will take into account an additional leading
* formal parameter if the method is an instance method seen as a member
* of un underdetermined site In this case, we treat site as an additional
* parameter and the parameters of the class containing the method as
* additional type variables that get instantiated.
*
* @param env The current environment
* @param m The method symbol.
* @param mt The expected type.
* @param argtypes The invocation's given value arguments.
* @param typeargtypes The invocation's given type arguments.
* @param allowBoxing Allow boxing conversions of arguments.
* @param useVarargs Box trailing arguments into an array for varargs.
*/
Type rawInstantiate(JavafxEnv<JavafxAttrContext> env,
Symbol m,
Type mt,
List<Type> argtypes,
List<Type> typeargtypes,
boolean allowBoxing,
boolean useVarargs,
Warner warn)
throws Infer.NoInstanceException {
if (useVarargs && (m.flags() & VARARGS) == 0) return null;
m.complete();
// tvars is the list of formal type variables for which type arguments
// need to inferred.
List<Type> tvars = env.info.tvars;
if (typeargtypes == null) typeargtypes = List.nil();
if (mt.tag != FORALL && typeargtypes.nonEmpty()) {
// This is not a polymorphic method, but typeargs are supplied
// which is fine, see JLS3 15.12.2.1
} else if (mt.tag == FORALL && typeargtypes.nonEmpty()) {
ForAll pmt = (ForAll) mt;
if (typeargtypes.length() != pmt.tvars.length())
return null;
// Check type arguments are within bounds
List<Type> formals = pmt.tvars;
List<Type> actuals = typeargtypes;
while (formals.nonEmpty() && actuals.nonEmpty()) {
List<Type> bounds = types.subst(types.getBounds((TypeVar)formals.head),
pmt.tvars, typeargtypes);
for (; bounds.nonEmpty(); bounds = bounds.tail)
if (!types.isSubtypeUnchecked(actuals.head, bounds.head, warn))
return null;
formals = formals.tail;
actuals = actuals.tail;
}
mt = types.subst(pmt.qtype, pmt.tvars, typeargtypes);
} else if (mt.tag == FORALL) {
ForAll pmt = (ForAll) mt;
List<Type> tvars1 = types.newInstances(pmt.tvars);
tvars = tvars.appendList(tvars1);
mt = types.subst(pmt.qtype, pmt.tvars, tvars1);
}
// find out whether we need to go the slow route via infer
boolean instNeeded = tvars.tail != null/*inlined: tvars.nonEmpty()*/;
for (List<Type> l = argtypes;
l.tail != null/*inlined: l.nonEmpty()*/ && !instNeeded;
l = l.tail) {
if (l.head.tag == FORALL) instNeeded = true;
}
if (instNeeded)
return
infer.instantiateMethod(tvars,
(MethodType)mt,
argtypes,
allowBoxing,
useVarargs,
warn);
return
argumentsAcceptable(argtypes, mt.getParameterTypes(),
allowBoxing, useVarargs, warn)
? mt
: null;
}
/** Same but returns null instead throwing a NoInstanceException
*/
Type instantiate(JavafxEnv<JavafxAttrContext> env,
Type site,
Symbol m,
List<Type> argtypes,
List<Type> typeargtypes,
boolean allowBoxing,
boolean useVarargs,
Warner warn) {
try {
return rawInstantiate(env, m, types.memberType(site, m), argtypes, typeargtypes,
allowBoxing, useVarargs, warn);
} catch (Infer.NoInstanceException ex) {
return null;
}
}
/** Check if a parameter list accepts a list of args.
*/
boolean argumentsAcceptable(List<Type> argtypes,
List<Type> formals,
boolean allowBoxing,
boolean useVarargs,
Warner warn) {
Type varargsFormal = useVarargs ? formals.last() : null;
while (argtypes.nonEmpty() && formals.head != varargsFormal) {
boolean works = allowBoxing
? types.isConvertible(argtypes.head, formals.head, warn)
: types.isSubtypeUnchecked(argtypes.head, formals.head, warn);
if (!works) return false;
argtypes = argtypes.tail;
formals = formals.tail;
}
if (formals.head != varargsFormal) return false; // not enough args
if (!useVarargs)
return argtypes.isEmpty();
Type elt = types.elemtype(varargsFormal);
while (argtypes.nonEmpty()) {
if (!types.isConvertible(argtypes.head, elt, warn))
return false;
argtypes = argtypes.tail;
}
return true;
}
/* ***************************************************************************
* Symbol lookup
* the following naming conventions for arguments are used
*
* env is the environment where the symbol was mentioned
* site is the type of which the symbol is a member
* name is the symbol's name
* if no arguments are given
* argtypes are the value arguments, if we search for a method
*
* If no symbol was found, a ResolveError detailing the problem is returned.
****************************************************************************/
/** Find field. Synthetic fields are always skipped.
* @param env The current environment.
* @param site The original type from where the selection takes place.
* @param name The name of the field.
* @param c The class to search for the field. This is always
* a superclass or implemented interface of site's class.
*/
// Javafx change
public
// javafx change
Symbol findField(JavafxEnv<JavafxAttrContext> env,
Type site,
Name name,
TypeSymbol c) {
Symbol bestSoFar = varNotFound;
Symbol sym;
Scope.Entry e = c.members().lookup(name);
while (e.scope != null) {
if ((e.sym.kind & (VAR|MTH)) != 0 && (e.sym.flags_field & SYNTHETIC) == 0) {
sym = isAccessible(env, site, e.sym)
? e.sym : new AccessError(env, site, e.sym);
if (bestSoFar.kind < AMBIGUOUS && sym.kind < AMBIGUOUS &&
sym.owner != bestSoFar.owner)
bestSoFar = new AmbiguityError(bestSoFar, sym);
else if (sym.kind < bestSoFar.kind)
bestSoFar = sym;
}
e = e.next();
}
if (bestSoFar != varNotFound)
return bestSoFar;
Type st = types.supertype(c.type);
if (st != null && st.tag == CLASS) {
sym = findField(env, site, name, st.tsym);
if (sym.kind < bestSoFar.kind) bestSoFar = sym;
}
// We failed to find the field in the single Java class supertype of the
// Javafx class.
// Now try to find the filed in all of the Javafx supertypes.
if (bestSoFar.kind > AMBIGUOUS && c instanceof JavafxClassSymbol) {
List<Type> supertypes = ((JavafxClassSymbol)c).getSuperTypes();
for (Type tp : supertypes) {
if (tp != null && tp.tag == CLASS) {
sym = findField(env, site, name, tp.tsym);
if (sym.kind < bestSoFar.kind) bestSoFar = sym;
if (bestSoFar.kind < AMBIGUOUS) {
break;
}
}
}
}
for (List<Type> l = types.interfaces(c.type);
bestSoFar.kind != AMBIGUOUS && l.nonEmpty();
l = l.tail) {
sym = findField(env, site, name, l.head.tsym);
if (bestSoFar.kind < AMBIGUOUS && sym.kind < AMBIGUOUS &&
sym.owner != bestSoFar.owner)
bestSoFar = new AmbiguityError(bestSoFar, sym);
else if (sym.kind < bestSoFar.kind)
bestSoFar = sym;
}
return bestSoFar;
}
/** Resolve a field identifier, throw a fatal error if not found.
* @param pos The position to use for error reporting.
* @param env The environment current at the method invocation.
* @param site The type of the qualifying expression, in which
* identifier is searched.
* @param name The identifier's name.
*/
public VarSymbol resolveInternalField(DiagnosticPosition pos, JavafxEnv<JavafxAttrContext> env,
Type site, Name name) {
Symbol sym = findField(env, site, name, site.tsym);
if (sym.kind == VAR) return (VarSymbol)sym;
else throw new FatalError(
JCDiagnostic.fragment(MsgSym.MESSAGE_FATAL_ERR_CANNOT_LOCATE_FIELD,
name));
}
/** Find unqualified variable or field with given name.
* Synthetic fields always skipped.
* @param env The current environment.
* @param name The name of the variable or field.
*/
Symbol findVar(JavafxEnv<JavafxAttrContext> env, Name name, int kind, Type expected) {
Symbol bestSoFar = varNotFound;
Symbol sym;
JavafxEnv<JavafxAttrContext> env1 = env;
boolean staticOnly = false;
boolean innerAccess = false;
Type mtype = expected;
if (mtype instanceof FunctionType)
mtype = mtype.asMethodType();
boolean checkArgs = mtype instanceof MethodType || mtype instanceof ForAll;
while (env1 != null) {
Scope sc = env1.info.scope;
Type envClass;
if (env1.tree instanceof JFXClassDeclaration) {
JFXClassDeclaration cdecl = (JFXClassDeclaration) env1.tree;
if (cdecl.runMethod != null &&
name != names._this && name != names._super) {
envClass = null;
sc = cdecl.runBodyScope;
innerAccess = true;
}
envClass = cdecl.sym.type;
}
else
envClass = null;
if (envClass != null) {
sym = findMember(env1, envClass, name,
expected,
true, false, false);
if (sym.exists()) {
if (staticOnly) {
// Note: can't call isStatic with null owner
if (sym.owner != null) {
if (!sym.isStatic()) {
return new StaticError(sym);
}
}
}
return sym;
}
}
if (sc != null) {
for (Scope.Entry e = sc.lookup(name); e.scope != null; e = e.next()) {
if ((e.sym.flags_field & SYNTHETIC) != 0)
continue;
if ((e.sym.kind & (MTH|VAR)) != 0) {
if (innerAccess) {
e.sym.flags_field |= JavafxFlags.VARUSE_INNER_ACCESS;
}
if (checkArgs) {
return checkArgs(e.sym, mtype);
}
return e.sym;
}
}
}
if (env1.tree instanceof JFXFunctionDefinition)
innerAccess = true;
if (env1.outer != null && isStatic(env1)) staticOnly = true;
env1 = env1.outer;
}
Scope.Entry e = env.toplevel.namedImportScope.lookup(name);
for (; e.scope != null; e = e.next()) {
sym = e.sym;
Type origin = e.getOrigin().owner.type;
if ((sym.kind & (MTH|VAR)) != 0) {
if (e.sym.owner.type != origin)
sym = sym.clone(e.getOrigin().owner);
- return isAccessible(env, origin, sym)
- ? sym : new AccessError(env, origin, sym);
+ return selectBest(env, origin, mtype,
+ e.sym, bestSoFar,
+ true,
+ false,
+ false);
}
}
Symbol origin = null;
e = env.toplevel.starImportScope.lookup(name);
for (; e.scope != null; e = e.next()) {
sym = e.sym;
if ((sym.kind & (MTH|VAR)) == 0)
continue;
// invariant: sym.kind == VAR
if (bestSoFar.kind < AMBIGUOUS && sym.owner != bestSoFar.owner)
return new AmbiguityError(bestSoFar, sym);
else if (bestSoFar.kind >= VAR) {
origin = e.getOrigin().owner;
- bestSoFar = isAccessible(env, origin.type, sym)
- ? sym : new AccessError(env, origin.type, sym);
+ bestSoFar = selectBest(env, origin.type, mtype,
+ e.sym, bestSoFar,
+ true,
+ false,
+ false);
}
}
if (name == names.fromString("__DIR__") || name == names.fromString("__FILE__")
|| name == names.fromString("__PROFILE__")) {
Type type = syms.stringType;
return new VarSymbol(Flags.PUBLIC, name, type, env.enclClass.sym);
}
if (bestSoFar.kind == VAR && bestSoFar.owner.type != origin.type)
return bestSoFar.clone(origin);
else
return bestSoFar;
}
//where
private Symbol checkArgs(Symbol sym, Type mtype) {
Type mt = sym.type;
if (mt instanceof FunctionType) {
mt = mt.asMethodType();
}
// Better to use selectBest, but that requires some
// changes. FIXME
if (!(mt instanceof MethodType) ||
!argumentsAcceptable(mtype.getParameterTypes(), mt.getParameterTypes(),
true, false, Warner.noWarnings)) {
return wrongMethod.setWrongSym(sym);
}
return sym;
}
Warner noteWarner = new Warner();
/** Select the best method for a call site among two choices.
* @param env The current environment.
* @param site The original type from where the
* selection takes place.
* @param argtypes The invocation's value arguments,
* @param typeargtypes The invocation's type arguments,
* @param sym Proposed new best match.
* @param bestSoFar Previously found best match.
* @param allowBoxing Allow boxing conversions of arguments.
* @param useVarargs Box trailing arguments into an array for varargs.
*/
Symbol selectBest(JavafxEnv<JavafxAttrContext> env,
Type site,
Type expected,
Symbol sym,
Symbol bestSoFar,
boolean allowBoxing,
boolean useVarargs,
boolean operator) {
if (sym.kind == ERR) return bestSoFar;
if (!isInheritedIn(sym, site.tsym, types)) return bestSoFar;
assert sym.kind < AMBIGUOUS;
List<Type> argtypes = expected.getParameterTypes();
List<Type> typeargtypes = expected.getTypeArguments();
try {
if (rawInstantiate(env, sym, types.memberType(site, sym), argtypes, typeargtypes,
allowBoxing, useVarargs, Warner.noWarnings) == null) {
// inapplicable
switch (bestSoFar.kind) {
case ABSENT_MTH: return wrongMethod.setWrongSym(sym);
case WRONG_MTH: return wrongMethods;
default: return bestSoFar;
}
}
} catch (Infer.NoInstanceException ex) {
switch (bestSoFar.kind) {
case ABSENT_MTH:
return wrongMethod.setWrongSym(sym, ex.getDiagnostic());
case WRONG_MTH:
return wrongMethods;
default:
return bestSoFar;
}
}
if (!isAccessible(env, site, sym)) {
return (bestSoFar.kind == ABSENT_MTH)
? new AccessError(env, site, sym)
: bestSoFar;
}
return (bestSoFar.kind > AMBIGUOUS)
? sym
: mostSpecific(sym, bestSoFar, env, site,
allowBoxing && operator, useVarargs);
}
/* Return the most specific of the two methods for a call,
* given that both are accessible and applicable.
* @param m1 A new candidate for most specific.
* @param m2 The previous most specific candidate.
* @param env The current environment.
* @param site The original type from where the selection
* takes place.
* @param allowBoxing Allow boxing conversions of arguments.
* @param useVarargs Box trailing arguments into an array for varargs.
*/
Symbol mostSpecific(Symbol m1,
Symbol m2,
JavafxEnv<JavafxAttrContext> env,
Type site,
boolean allowBoxing,
boolean useVarargs) {
switch (m2.kind) {
case MTH:
if (m1 == m2) return m1;
Type mt1 = types.memberType(site, m1);
noteWarner.unchecked = false;
boolean m1SignatureMoreSpecific =
(instantiate(env, site, m2, types.lowerBoundArgtypes(mt1), null,
allowBoxing, false, noteWarner) != null ||
useVarargs && instantiate(env, site, m2, types.lowerBoundArgtypes(mt1), null,
allowBoxing, true, noteWarner) != null) &&
!noteWarner.unchecked;
Type mt2 = types.memberType(site, m2);
noteWarner.unchecked = false;
boolean m2SignatureMoreSpecific =
(instantiate(env, site, m1, types.lowerBoundArgtypes(mt2), null,
allowBoxing, false, noteWarner) != null ||
useVarargs && instantiate(env, site, m1, types.lowerBoundArgtypes(mt2), null,
allowBoxing, true, noteWarner) != null) &&
!noteWarner.unchecked;
if (m1SignatureMoreSpecific && m2SignatureMoreSpecific) {
if (!types.overrideEquivalent(mt1, mt2))
return new AmbiguityError(m1, m2);
// same signature; select (a) the non-bridge method, or
// (b) the one that overrides the other, or (c) the concrete
// one, or (d) merge both abstract signatures
if ((m1.flags() & BRIDGE) != (m2.flags() & BRIDGE)) {
return ((m1.flags() & BRIDGE) != 0) ? m2 : m1;
}
// if one overrides or hides the other, use it
TypeSymbol m1Owner = (TypeSymbol)m1.owner;
TypeSymbol m2Owner = (TypeSymbol)m2.owner;
if (types.asSuper(m1Owner.type, m2Owner) != null &&
((m1.owner.flags_field & INTERFACE) == 0 ||
(m2.owner.flags_field & INTERFACE) != 0) &&
m1.overrides(m2, m1Owner, types, false))
return m1;
if (types.asSuper(m2Owner.type, m1Owner) != null &&
((m2.owner.flags_field & INTERFACE) == 0 ||
(m1.owner.flags_field & INTERFACE) != 0) &&
m2.overrides(m1, m2Owner, types, false))
return m2;
boolean m1Abstract = (m1.flags() & ABSTRACT) != 0;
boolean m2Abstract = (m2.flags() & ABSTRACT) != 0;
if (m1Abstract && !m2Abstract) return m2;
if (m2Abstract && !m1Abstract) return m1;
// both abstract or both concrete
if (!m1Abstract && !m2Abstract)
return new AmbiguityError(m1, m2);
// check for same erasure
if (!types.isSameType(m1.erasure(types), m2.erasure(types)))
return new AmbiguityError(m1, m2);
// both abstract, neither overridden; merge throws clause and result type
Symbol result;
Type result2 = mt2.getReturnType();
if (mt2.tag == FORALL)
result2 = types.subst(result2, ((ForAll)mt2).tvars, ((ForAll)mt1).tvars);
if (types.isSubtype(mt1.getReturnType(), result2)) {
result = m1;
} else if (types.isSubtype(result2, mt1.getReturnType())) {
result = m2;
} else {
// Theoretically, this can't happen, but it is possible
// due to error recovery or mixing incompatible class files
return new AmbiguityError(m1, m2);
}
result = result.clone(result.owner);
result.type = (Type)result.type.clone();
result.type.setThrown(chk.intersect(mt1.getThrownTypes(),
mt2.getThrownTypes()));
return result;
}
if (m1SignatureMoreSpecific) return m1;
if (m2SignatureMoreSpecific) return m2;
return new AmbiguityError(m1, m2);
case AMBIGUOUS:
AmbiguityError e = (AmbiguityError)m2;
Symbol err1 = mostSpecific(m1, e.sym1, env, site, allowBoxing, useVarargs);
Symbol err2 = mostSpecific(m1, e.sym2, env, site, allowBoxing, useVarargs);
if (err1 == err2) return err1;
if (err1 == e.sym1 && err2 == e.sym2) return m2;
if (err1 instanceof AmbiguityError &&
err2 instanceof AmbiguityError &&
((AmbiguityError)err1).sym1 == ((AmbiguityError)err2).sym1)
return new AmbiguityError(m1, m2);
else
return new AmbiguityError(err1, err2);
default:
throw new AssertionError();
}
}
/** Find best qualified method matching given name, type and value
* arguments.
* @param env The current environment.
* @param site The original type from where the selection
* takes place.
* @param name The method's name.
* @param argtypes The method's value arguments.
* @param typeargtypes The method's type arguments
* @param allowBoxing Allow boxing conversions of arguments.
* @param useVarargs Box trailing arguments into an array for varargs.
*/
Symbol findMethod(JavafxEnv<JavafxAttrContext> env,
Type site,
Name name,
List<Type> argtypes,
List<Type> typeargtypes,
boolean allowBoxing,
boolean useVarargs,
boolean operator) {
return findMember(env,
site,
name,
newMethTemplate(argtypes, typeargtypes),
site.tsym.type,
methodNotFound,
allowBoxing,
useVarargs,
operator);
}
Symbol findMember(JavafxEnv<JavafxAttrContext> env,
Type site,
Name name,
Type expected,
boolean allowBoxing,
boolean useVarargs,
boolean operator) {
return findMember(env,
site,
name,
expected,
site.tsym.type,
methodNotFound,
allowBoxing,
useVarargs,
operator);
}
// where
private Symbol findMember(JavafxEnv<JavafxAttrContext> env,
Type site,
Name name,
Type expected,
Type intype,
Symbol bestSoFar,
boolean allowBoxing,
boolean useVarargs,
boolean operator) {
Symbol best = findMemberWithoutAccessChecks(env,
site,
name,
expected,
intype,
bestSoFar,
allowBoxing,
useVarargs,
operator);
if (!(best instanceof ResolveError) && !isAccessible(env, site, best)) {
// it is not accessible, return an error instead
best = new AccessError(env, site, best);
}
return best;
}
// where
private Symbol findMemberWithoutAccessChecks(JavafxEnv<JavafxAttrContext> env,
Type site,
Name name,
Type expected,
Type intype,
Symbol bestSoFar,
boolean allowBoxing,
boolean useVarargs,
boolean operator) {
Type mtype = expected;
if (mtype instanceof FunctionType)
mtype = mtype.asMethodType();
boolean checkArgs = mtype instanceof MethodType || mtype instanceof ForAll;
for (Type ct = intype; ct.tag == CLASS; ct = types.supertype(ct)) {
ClassSymbol c = (ClassSymbol)ct.tsym;
for (Scope.Entry e = c.members().lookup(name);
e.scope != null;
e = e.next()) {
if ((e.sym.kind & (VAR|MTH)) == 0 ||
(e.sym.flags_field & SYNTHETIC) != 0)
continue;
e.sym.complete();
if (! checkArgs) {
// No argument list to disambiguate.
if (bestSoFar.kind == ABSENT_VAR || bestSoFar.kind == ABSENT_MTH)
bestSoFar = e.sym;
else if (e.sym != bestSoFar)
bestSoFar = new AmbiguityError(bestSoFar, e.sym);
}
else if (e.sym.kind == MTH) {
if (isExactMatch(mtype, e.sym))
return e.sym;
bestSoFar = selectBest(env, site, mtype,
e.sym, bestSoFar,
allowBoxing,
useVarargs,
operator);
}
else if ((e.sym.kind & (VAR|MTH)) != 0 && bestSoFar == methodNotFound) {
// FIXME duplicates logic in findVar.
Type mt = e.sym.type;
if (mt instanceof FunctionType)
mt = mt.asMethodType();
if (! (mt instanceof MethodType) ||
! argumentsAcceptable(mtype.getParameterTypes(), mt.getParameterTypes(),
true, false, Warner.noWarnings))
return wrongMethod.setWrongSym(e.sym);
return e.sym;
}
}
if (! checkArgs &&
bestSoFar.kind != ABSENT_VAR && bestSoFar.kind != ABSENT_MTH) {
return bestSoFar;
}
Symbol concrete = methodNotFound;
if ((bestSoFar.flags() & ABSTRACT) == 0)
concrete = bestSoFar;
for (List<Type> l = types.interfaces(c.type);
l.nonEmpty();
l = l.tail) {
bestSoFar = findMemberWithoutAccessChecks(env, site, name, expected,
l.head, bestSoFar,
allowBoxing, useVarargs, operator);
}
if (concrete != bestSoFar &&
concrete.kind < ERR && bestSoFar.kind < ERR &&
types.isSubSignature(concrete.type, bestSoFar.type))
bestSoFar = concrete;
if (name == names.init)
return bestSoFar;
}
// We failed to find the field in the single Java class supertype of the
// Javafx class.
// Now try to find the filed in all of the Javafx supertypes.
if (bestSoFar.kind > AMBIGUOUS && intype.tsym instanceof JavafxClassSymbol) {
List<Type> supertypes = ((JavafxClassSymbol)intype.tsym).getSuperTypes();
for (Type tp : supertypes) {
bestSoFar = findMemberWithoutAccessChecks(env, site, name, expected, tp,
bestSoFar, allowBoxing, useVarargs, operator);
if (bestSoFar.kind < AMBIGUOUS) {
break;
}
}
}
return bestSoFar;
}
private boolean isExactMatch(Type mtype, Symbol bestSoFar) {
if (bestSoFar.kind == MTH && (bestSoFar.type instanceof MethodType) &&
mtype.tag == TypeTags.METHOD ) {
List<Type> actuals = ((MethodType)mtype).getParameterTypes();
List<Type> formals = ((MethodType)bestSoFar.type).getParameterTypes();
if (actuals != null && formals != null) {
if (actuals.size() == formals.size()) {
for (Type actual : actuals) {
if (! types.isSameType(actual, formals.head)) {
return false;
}
formals = formals.tail;
}
return true;
}
}
}
return false;
}
Type newMethTemplate(List<Type> argtypes, List<Type> typeargtypes) {
MethodType mt = new MethodType(argtypes, null, null, syms.methodClass);
return (typeargtypes == null) ? mt : (Type)new ForAll(typeargtypes, mt);
}
/** Load toplevel or member class with given fully qualified name and
* verify that it is accessible.
* @param env The current environment.
* @param name The fully qualified name of the class to be loaded.
*/
Symbol loadClass(JavafxEnv<JavafxAttrContext> env, Name name) {
try {
ClassSymbol c = reader.loadClass(name);
return isAccessible(env, c) ? c : new AccessError(c);
} catch (ClassReader.BadClassFile err) {
throw err;
} catch (CompletionFailure ex) {
return typeNotFound;
}
}
/** Find qualified member type.
* @param env The current environment.
* @param site The original type from where the selection takes
* place.
* @param name The type's name.
* @param c The class to search for the member type. This is
* always a superclass or implemented interface of
* site's class.
*/
// Javafx change
public
// Javafx change
Symbol findMemberType(JavafxEnv<JavafxAttrContext> env,
Type site,
Name name,
TypeSymbol c) {
Symbol bestSoFar = typeNotFound;
Symbol sym;
Scope.Entry e = c.members().lookup(name);
while (e.scope != null) {
if (e.sym.kind == TYP) {
return isAccessible(env, site, e.sym)
? e.sym
: new AccessError(env, site, e.sym);
}
e = e.next();
}
Type st = types.supertype(c.type);
if (st != null && st.tag == CLASS) {
sym = findMemberType(env, site, name, st.tsym);
if (sym.kind < bestSoFar.kind) bestSoFar = sym;
}
// We failed to find the field in the single Java class supertype of the
// Javafx class.
// Now try to find the filed in all of the Javafx supertypes.
if (bestSoFar.kind > AMBIGUOUS && c instanceof JavafxClassSymbol) {
List<Type> supertypes = ((JavafxClassSymbol)c).getSuperTypes();
for (Type tp : supertypes) {
if (tp != null && tp.tag == CLASS) {
sym = findField(env, site, name, tp.tsym);
if (sym.kind < bestSoFar.kind) bestSoFar = sym;
if (bestSoFar.kind < AMBIGUOUS) {
break;
}
}
}
}
for (List<Type> l = types.interfaces(c.type);
bestSoFar.kind != AMBIGUOUS && l.nonEmpty();
l = l.tail) {
sym = findMemberType(env, site, name, l.head.tsym);
if (bestSoFar.kind < AMBIGUOUS && sym.kind < AMBIGUOUS &&
sym.owner != bestSoFar.owner)
bestSoFar = new AmbiguityError(bestSoFar, sym);
else if (sym.kind < bestSoFar.kind)
bestSoFar = sym;
}
return bestSoFar;
}
/** Find a global type in given scope and load corresponding class.
* @param env The current environment.
* @param scope The scope in which to look for the type.
* @param name The type's name.
*/
Symbol findGlobalType(JavafxEnv<JavafxAttrContext> env, Scope scope, Name name) {
Symbol bestSoFar = typeNotFound;
for (Scope.Entry e = scope.lookup(name); e.scope != null; e = e.next()) {
Symbol sym = loadClass(env, e.sym.flatName());
if (bestSoFar.kind == TYP && sym.kind == TYP &&
bestSoFar != sym)
return new AmbiguityError(bestSoFar, sym);
else if (sym.kind < bestSoFar.kind)
bestSoFar = sym;
}
return bestSoFar;
}
Type findBuiltinType (Name typeName) {
if (typeName == syms.booleanTypeName)
return syms.javafx_BooleanType;
if (typeName == syms.charTypeName)
return syms.javafx_CharacterType;
if (typeName == syms.byteTypeName)
return syms.javafx_ByteType;
if (typeName == syms.shortTypeName)
return syms.javafx_ShortType;
if (typeName == syms.integerTypeName)
return syms.javafx_IntegerType;
if (typeName == syms.longTypeName)
return syms.javafx_LongType;
if (typeName == syms.floatTypeName)
return syms.javafx_FloatType;
if (typeName == syms.doubleTypeName)
return syms.javafx_DoubleType;
if (typeName == syms.numberTypeName)
return syms.javafx_NumberType;
if (typeName == syms.stringTypeName)
return syms.javafx_StringType;
if (typeName == syms.voidTypeName)
return syms.javafx_VoidType;
return null;
}
/** Find an unqualified type symbol.
* @param env The current environment.
* @param name The type's name.
*/
Symbol findType(JavafxEnv<JavafxAttrContext> env, Name name) {
Symbol bestSoFar = typeNotFound;
Symbol sym;
boolean staticOnly = false;
for (JavafxEnv<JavafxAttrContext> env1 = env; env1.outer != null; env1 = env1.outer) {
if (isStatic(env1)) staticOnly = true;
for (Scope.Entry e = env1.info.scope.lookup(name);
e.scope != null;
e = e.next()) {
if (e.sym.kind == TYP) {
if (staticOnly &&
e.sym.type.tag == TYPEVAR &&
e.sym.owner.kind == TYP) return new StaticError(e.sym);
return e.sym;
}
}
sym = findMemberType(env1, env1.enclClass.sym.type, name,
env1.enclClass.sym);
if (staticOnly && sym.kind == TYP &&
sym.type.tag == CLASS &&
sym.type.getEnclosingType().tag == CLASS &&
env1.enclClass.sym.type.isParameterized() &&
sym.type.getEnclosingType().isParameterized())
return new StaticError(sym);
else if (sym.exists()) return sym;
else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
JFXClassDeclaration encl = env1.baseClause ? (JFXClassDeclaration)env1.tree : env1.enclClass;
if ((encl.sym.flags() & STATIC) != 0)
staticOnly = true;
}
if (env.tree.getFXTag() != JavafxTag.IMPORT) {
sym = findGlobalType(env, env.toplevel.namedImportScope, name);
if (sym.exists()) return sym;
else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
}
sym = findGlobalType(env, env.toplevel.packge.members(), name);
if (sym.exists()) return sym;
else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
Type type = findBuiltinType(name);
if (type != null)
return type.tsym;
if (env.tree.getFXTag() != JavafxTag.IMPORT) {
sym = findGlobalType(env, env.toplevel.starImportScope, name);
if (sym.exists()) return sym;
else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
}
return bestSoFar;
}
/** Find an unqualified identifier which matches a specified kind set.
* @param env The current environment.
* @param name The indentifier's name.
* @param kind Indicates the possible symbol kinds
* (a subset of VAL, TYP, PCK).
*/
Symbol findIdent(JavafxEnv<JavafxAttrContext> env, Name name, int kind, Type expected) {
Symbol bestSoFar = typeNotFound;
Symbol sym;
if ((kind & (VAR|MTH)) != 0) {
sym = findVar(env, name, kind, expected);
if (sym.exists()) return sym;
else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
}
if ((kind & TYP) != 0) {
sym = findType(env, name);
if (sym.exists()) return sym;
else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
}
if ((kind & PCK) != 0) return reader.enterPackage(name);
else return bestSoFar;
}
/** Find an identifier in a package which matches a specified kind set.
* @param env The current environment.
* @param name The identifier's name.
* @param kind Indicates the possible symbol kinds
* (a nonempty subset of TYP, PCK).
*/
Symbol findIdentInPackage(JavafxEnv<JavafxAttrContext> env, TypeSymbol pck,
Name name, int kind) {
Name fullname = TypeSymbol.formFullName(name, pck);
Symbol bestSoFar = typeNotFound;
PackageSymbol pack = null;
if ((kind & PCK) != 0) {
pack = reader.enterPackage(fullname);
if (pack.exists()) return pack;
}
if ((kind & TYP) != 0) {
Symbol sym = loadClass(env, fullname);
if (sym.exists()) {
// don't allow programs to use flatnames
if (name == sym.name) return sym;
}
else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
}
return (pack != null) ? pack : bestSoFar;
}
/** Find an identifier among the members of a given type `site'.
* @param env The current environment.
* @param site The type containing the symbol to be found.
* @param name The identifier's name.
* @param kind Indicates the possible symbol kinds
* (a subset of VAL, TYP).
*/
Symbol findIdentInType(JavafxEnv<JavafxAttrContext> env, Type site,
Name name, int kind) {
Symbol bestSoFar = typeNotFound;
Symbol sym;
if ((kind & (VAR|MTH)) != 0) {
sym = findField(env, site, name, site.tsym);
if (sym.exists()) return sym;
else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
}
if ((kind & TYP) != 0) {
sym = findMemberType(env, site, name, site.tsym);
if (sym.exists()) return sym;
else if (sym.kind < bestSoFar.kind) bestSoFar = sym;
}
return bestSoFar;
}
/* ***************************************************************************
* Access checking
* The following methods convert ResolveErrors to ErrorSymbols, issuing
* an error message in the process
****************************************************************************/
/** If `sym' is a bad symbol: report error and return errSymbol
* else pass through unchanged,
* additional arguments duplicate what has been used in trying to find the
* symbol (--> flyweight pattern). This improves performance since we
* expect misses to happen frequently.
*
* @param sym The symbol that was found, or a ResolveError.
* @param pos The position to use for error reporting.
* @param site The original type from where the selection took place.
* @param name The symbol's name.
* @param argtypes The invocation's value arguments,
* if we looked for a method.
* @param typeargtypes The invocation's type arguments,
* if we looked for a method.
*/
Symbol access(Symbol sym,
DiagnosticPosition pos,
Type site,
Name name,
boolean qualified,
List<Type> argtypes,
List<Type> typeargtypes) {
if (sym.kind >= AMBIGUOUS) {
// printscopes(site.tsym.members());//DEBUG
if (!site.isErroneous() &&
!Type.isErroneous(argtypes) &&
(typeargtypes==null || !Type.isErroneous(typeargtypes))) {
((ResolveError)sym).report(log, pos, site, name, argtypes, typeargtypes);
}
do {
sym = ((ResolveError)sym).sym;
} while (sym.kind >= AMBIGUOUS);
if (sym == syms.errSymbol // preserve the symbol name through errors
|| ((sym.kind & ERRONEOUS) == 0 // make sure an error symbol is returned
&& (sym.kind & TYP) != 0))
sym = new ErrorType(name, qualified?site.tsym:syms.noSymbol).tsym;
}
return sym;
}
Symbol access(Symbol sym,
DiagnosticPosition pos,
Type site,
Name name,
boolean qualified,
Type expected) {
return access(sym, pos, site, name, qualified, expected.getParameterTypes(), expected.getTypeArguments());
}
/** Same as above, but without type arguments and arguments.
*/
// Javafx change
public
// Javafx change
Symbol access(Symbol sym,
DiagnosticPosition pos,
Type site,
Name name,
boolean qualified) {
if (sym.kind >= AMBIGUOUS)
return access(sym, pos, site, name, qualified, List.<Type>nil(), null);
else
return sym;
}
/** Check that sym is not an abstract method.
*/
void checkNonAbstract(DiagnosticPosition pos, Symbol sym) {
if ((sym.flags() & ABSTRACT) != 0)
log.error(pos, MsgSym.MESSAGE_ABSTRACT_CANNOT_BE_ACCESSED_DIRECTLY,
kindName(sym), sym, sym.location());
}
/* ***************************************************************************
* Debugging
****************************************************************************/
/** print all scopes starting with scope s and proceeding outwards.
* used for debugging.
*/
public void printscopes(Scope s) {
while (s != null) {
if (s.owner != null)
System.err.print(s.owner + ": ");
for (Scope.Entry e = s.elems; e != null; e = e.sibling) {
if ((e.sym.flags() & ABSTRACT) != 0)
System.err.print("abstract ");
System.err.print(e.sym + " ");
}
System.err.println();
s = s.next;
}
}
void printscopes(JavafxEnv<JavafxAttrContext> env) {
while (env.outer != null) {
System.err.println("------------------------------");
printscopes(env.info.scope);
env = env.outer;
}
}
public void printscopes(Type t) {
while (t.tag == CLASS) {
printscopes(t.tsym.members());
t = types.supertype(t);
}
}
/* ***************************************************************************
* Name resolution
* Naming conventions are as for symbol lookup
* Unlike the find... methods these methods will report access errors
****************************************************************************/
/** Resolve an unqualified (non-method) identifier.
* @param pos The position to use for error reporting.
* @param env The environment current at the identifier use.
* @param name The identifier's name.
* @param kind The set of admissible symbol kinds for the identifier.
* @param pt The expected type.
*/
Symbol resolveIdent(DiagnosticPosition pos, JavafxEnv<JavafxAttrContext> env,
Name name, int kind, Type pt) {
Symbol sym = findIdent(env, name, kind, pt);
if (sym.kind >= AMBIGUOUS)
return access(sym, pos, env.enclClass.sym.type, name, false, pt);
else
return sym;
}
/** Resolve a qualified method identifier
* @param pos The position to use for error reporting.
* @param env The environment current at the method invocation.
* @param site The type of the qualifying expression, in which
* identifier is searched.
* @param name The identifier's name.
* @param argtypes The types of the invocation's value arguments.
* @param typeargtypes The types of the invocation's type arguments.
*/
Symbol resolveQualifiedMethod(DiagnosticPosition pos, JavafxEnv<JavafxAttrContext> env,
Type site, Name name, Type expected) {
Symbol sym = findMember(env, site, name, expected, false,
env.info.varArgs=false, false);
if (varargsEnabled && sym.kind >= WRONG_MTHS) {
sym = findMember(env, site, name, expected, true,
false, false);
if (sym.kind >= WRONG_MTHS)
sym = findMember(env, site, name, expected, true,
env.info.varArgs=true, false);
}
if (sym.kind >= AMBIGUOUS) {
sym = access(sym, pos, site, name, true, expected);
}
return sym;
}
/** Resolve a qualified method identifier, throw a fatal error if not
* found.
* @param pos The position to use for error reporting.
* @param env The environment current at the method invocation.
* @param site The type of the qualifying expression, in which
* identifier is searched.
* @param name The identifier's name.
* @param argtypes The types of the invocation's value arguments.
* @param typeargtypes The types of the invocation's type arguments.
*/
public MethodSymbol resolveInternalMethod(DiagnosticPosition pos, JavafxEnv<JavafxAttrContext> env,
Type site, Name name,
List<Type> argtypes,
List<Type> typeargtypes) {
Symbol sym = resolveQualifiedMethod(
pos, env, site, name, newMethTemplate(argtypes, typeargtypes));
if (sym.kind == MTH) return (MethodSymbol)sym;
else throw new FatalError(
JCDiagnostic.fragment(MsgSym.MESSAGE_FATAL_ERR_CANNOT_LOCATE_METH,
name));
}
/** Resolve constructor.
* @param pos The position to use for error reporting.
* @param env The environment current at the constructor invocation.
* @param site The type of class for which a constructor is searched.
* @param argtypes The types of the constructor invocation's value
* arguments.
* @param typeargtypes The types of the constructor invocation's type
* arguments.
*/
public // Javafx change
Symbol resolveConstructor(DiagnosticPosition pos,
JavafxEnv<JavafxAttrContext> env,
Type site,
List<Type> argtypes,
List<Type> typeargtypes) {
Symbol sym = resolveConstructor(pos, env, site, argtypes, typeargtypes, false, env.info.varArgs=false);
if (varargsEnabled && sym.kind >= WRONG_MTHS) {
sym = resolveConstructor(pos, env, site, argtypes, typeargtypes, true, false);
if (sym.kind >= WRONG_MTHS)
sym = resolveConstructor(pos, env, site, argtypes, typeargtypes, true, env.info.varArgs=true);
}
if (sym.kind >= AMBIGUOUS) {
sym = access(sym, pos, site, names.init, true, argtypes, typeargtypes);
}
return sym;
}
/** Resolve constructor.
* @param pos The position to use for error reporting.
* @param env The environment current at the constructor invocation.
* @param site The type of class for which a constructor is searched.
* @param argtypes The types of the constructor invocation's value
* arguments.
* @param typeargtypes The types of the constructor invocation's type
* arguments.
* @param allowBoxing Allow boxing and varargs conversions.
* @param useVarargs Box trailing arguments into an array for varargs.
*/
public // Javafx change
Symbol resolveConstructor(DiagnosticPosition pos, JavafxEnv<JavafxAttrContext> env,
Type site, List<Type> argtypes,
List<Type> typeargtypes,
boolean allowBoxing,
boolean useVarargs) {
Symbol sym = findMethod(env, site,
names.init, argtypes,
typeargtypes, allowBoxing,
useVarargs, false);
if ((sym.flags() & DEPRECATED) != 0 &&
(env.info.scope.owner.flags() & DEPRECATED) == 0 &&
env.info.scope.owner.outermostClass() != sym.outermostClass())
chk.warnDeprecated(pos, sym);
return sym;
}
/** Resolve a constructor, throw a fatal error if not found.
* @param pos The position to use for error reporting.
* @param env The environment current at the method invocation.
* @param site The type to be constructed.
* @param argtypes The types of the invocation's value arguments.
* @param typeargtypes The types of the invocation's type arguments.
*/
public MethodSymbol resolveInternalConstructor(DiagnosticPosition pos, JavafxEnv<JavafxAttrContext> env,
Type site,
List<Type> argtypes,
List<Type> typeargtypes) {
Symbol sym = resolveConstructor(
pos, env, site, argtypes, typeargtypes);
if (sym.kind == MTH) return (MethodSymbol)sym;
else throw new FatalError(
JCDiagnostic.fragment(MsgSym.MESSAGE_FATAL_ERR_CANNOT_LOCATE_CTOR, site));
}
/** Resolve operator.
* @param pos The position to use for error reporting.
* @param optag The tag of the operation tree.
* @param env The environment current at the operation.
* @param argtypes The types of the operands.
*/
Symbol resolveOperator(DiagnosticPosition pos, JavafxTag optag,
JavafxEnv<JavafxAttrContext> env, List<Type> argtypes) {
Name name = treeinfo.operatorName(optag);
Symbol sym = findMethod(env, syms.predefClass.type, name, argtypes,
null, false, false, true);
if (boxingEnabled && sym.kind >= WRONG_MTHS)
sym = findMethod(env, syms.predefClass.type, name, argtypes,
null, true, false, true);
return access(sym, pos, env.enclClass.sym.type, name,
false, argtypes, null);
}
/** Resolve operator.
* @param pos The position to use for error reporting.
* @param optag The tag of the operation tree.
* @param env The environment current at the operation.
* @param arg The type of the operand.
*/
Symbol resolveUnaryOperator(DiagnosticPosition pos, JavafxTag optag, JavafxEnv<JavafxAttrContext> env, Type arg) {
// check for Duration unary minus
if (types.isSameType(arg, ((JavafxSymtab)syms).javafx_DurationType)) {
Symbol res = null;
switch (optag) {
case NEG:
res = resolveMethod(pos, env,
names.fromString("negate"),
arg, List.<Type>nil());
break;
}
if (res != null && res.kind == MTH) {
return res;
}
}
return resolveOperator(pos, optag, env, List.of(arg));
}
/** Resolve binary operator.
* @param pos The position to use for error reporting.
* @param optag The tag of the operation tree.
* @param env The environment current at the operation.
* @param left The types of the left operand.
* @param right The types of the right operand.
*/
Symbol resolveBinaryOperator(DiagnosticPosition pos,
JavafxTag optag,
JavafxEnv<JavafxAttrContext> env,
Type left,
Type right) {
// Duration operator overloading
if (types.isSameType(left, ((JavafxSymtab)syms).javafx_DurationType) ||
types.isSameType(right, ((JavafxSymtab)syms).javafx_DurationType)) {
Type dur = left;
Symbol res = null;
switch (optag) {
case PLUS:
res = resolveMethod(pos, env,
names.fromString("add"),
dur, List.of(right));
break;
case MINUS:
res = resolveMethod(pos, env,
names.fromString("sub"),
dur, List.of(right));
break;
case MUL:
if (!types.isSameType(left, ((JavafxSymtab)syms).javafx_DurationType)) {
left = right;
right = dur;
dur = left;
}
res = resolveMethod(pos, env,
names.fromString("mul"),
dur,
List.of(right));
break;
case DIV:
res = resolveMethod(pos, env,
names.fromString("div"),
dur, List.of(right));
break;
//fix me...inline or move to static helper?
case LT:
res = resolveMethod(pos, env,
names.fromString("lt"),
dur, List.of(right));
break;
case LE:
res = resolveMethod(pos, env,
names.fromString("le"),
dur, List.of(right));
break;
case GT:
res = resolveMethod(pos, env,
names.fromString("gt"),
dur, List.of(right));
break;
case GE:
res = resolveMethod(pos, env,
names.fromString("ge"),
dur, List.of(right));
break;
}
if (res != null && res.kind == MTH) {
return res;
} // else fall through
}
return resolveOperator(pos, optag, env, List.of(left, right));
}
Symbol resolveMethod(DiagnosticPosition pos,
JavafxEnv<JavafxAttrContext> env,
Name name,
Type type,
List<Type> argtypes) {
Symbol sym = findMethod(env, type, name, argtypes,
null, true, false, false);
if (sym.kind == MTH) { // skip access if method wasn't found
return access(sym, pos, env.enclClass.sym.type, name,
false, argtypes, null);
}
return sym;
}
/**
* Resolve `c.name' where name == this or name == super.
* @param pos The position to use for error reporting.
* @param env The environment current at the expression.
* @param c The qualifier.
* @param name The identifier's name.
*/
public // Javafx change
Symbol resolveSelf(DiagnosticPosition pos,
JavafxEnv<JavafxAttrContext> env,
TypeSymbol c,
Name name) {
JavafxEnv<JavafxAttrContext> env1 = env;
boolean staticOnly = false;
while (env1.outer != null) {
if (isStatic(env1)) staticOnly = true;
if (env1.enclClass.sym == c) {
Symbol sym = env1.info.scope.lookup(name).sym;
if (sym != null) {
if (staticOnly) sym = new StaticError(sym);
return access(sym, pos, env.enclClass.sym.type,
name, true);
}
}
if ((env1.enclClass.sym.flags() & STATIC) != 0) staticOnly = true;
env1 = env1.outer;
}
log.error(pos, MsgSym.MESSAGE_NOT_ENCL_CLASS, c);
return syms.errSymbol;
}
/**
* Resolve `c.this' for an enclosing class c that contains the
* named member.
* @param pos The position to use for error reporting.
* @param env The environment current at the expression.
* @param member The member that must be contained in the result.
*/
Symbol resolveSelfContaining(DiagnosticPosition pos,
JavafxEnv<JavafxAttrContext> env,
Symbol member) {
Name name = names._this;
JavafxEnv<JavafxAttrContext> env1 = env;
boolean staticOnly = false;
while (env1.outer != null) {
if (isStatic(env1)) staticOnly = true;
if (env1.enclClass.sym.isSubClass(member.owner, types) &&
isAccessible(env, env1.enclClass.sym.type, member)) {
Symbol sym = env1.info.scope.lookup(name).sym;
if (sym != null) {
if (staticOnly) sym = new StaticError(sym);
return access(sym, pos, env.enclClass.sym.type,
name, true);
}
}
if ((env1.enclClass.sym.flags() & STATIC) != 0)
staticOnly = true;
env1 = env1.outer;
}
log.error(pos, MsgSym.MESSAGE_ENCL_CLASS_REQUIRED, member);
return syms.errSymbol;
}
/**
* Resolve an appropriate implicit this instance for t's container.
* JLS2 8.8.5.1 and 15.9.2
*/
public // Javafx change
Type resolveImplicitThis(DiagnosticPosition pos, JavafxEnv<JavafxAttrContext> env, Type t) {
Type thisType = (((t.tsym.owner.kind & (MTH|VAR)) != 0)
? resolveSelf(pos, env, t.getEnclosingType().tsym, names._this)
: resolveSelfContaining(pos, env, t.tsym)).type;
if (env.info.isSelfCall && thisType.tsym == env.enclClass.sym)
log.error(pos, MsgSym.MESSAGE_CANNOT_REF_BEFORE_CTOR_CALLED, "this");
return thisType;
}
/* ***************************************************************************
* Methods related to kinds
****************************************************************************/
/** A localized string describing a given kind.
*/
public // Javafx change
static JCDiagnostic kindName(int kind) {
switch (kind) {
case PCK: return JCDiagnostic.fragment(MsgSym.KINDNAME_PACKAGE);
case TYP: return JCDiagnostic.fragment(MsgSym.KINDNAME_CLASS);
case VAR: return JCDiagnostic.fragment(MsgSym.KINDNAME_VARIABLE);
case VAL: return JCDiagnostic.fragment(MsgSym.KINDNAME_VALUE);
case MTH: return JCDiagnostic.fragment(MsgSym.KINDNAME_METHOD);
default : return JCDiagnostic.fragment(MsgSym.KINDNAME,
Integer.toString(kind)); //debug
}
}
static JCDiagnostic kindName(Symbol sym) {
switch (sym.getKind()) {
case PACKAGE:
return JCDiagnostic.fragment(MsgSym.KINDNAME_PACKAGE);
case ENUM:
case ANNOTATION_TYPE:
case INTERFACE:
case CLASS:
return JCDiagnostic.fragment(MsgSym.KINDNAME_CLASS);
case TYPE_PARAMETER:
return JCDiagnostic.fragment(MsgSym.KINDNAME_TYPE_VARIABLE);
case ENUM_CONSTANT:
case FIELD:
case PARAMETER:
case LOCAL_VARIABLE:
case EXCEPTION_PARAMETER:
return JCDiagnostic.fragment(MsgSym.KINDNAME_VARIABLE);
case METHOD:
case CONSTRUCTOR:
case STATIC_INIT:
case INSTANCE_INIT:
return JCDiagnostic.fragment(MsgSym.KINDNAME_METHOD);
default:
if (sym.kind == VAL)
// I don't think this can happen but it can't harm
// playing it safe --ahe
return JCDiagnostic.fragment(MsgSym.KINDNAME_VALUE);
else
return JCDiagnostic.fragment(MsgSym.KINDNAME, sym.getKind()); // debug
}
}
/** A localized string describing a given set of kinds.
*/
public // Javafx change
static JCDiagnostic kindNames(int kind) {
StringBuffer key = new StringBuffer();
key.append(MsgSym.KINDNAME);
if ((kind & VAL) != 0)
key.append(((kind & VAL) == VAR) ? MsgSym.KINDNAME_KEY_VARIABLE : MsgSym.KINDNAME_KEY_VALUE);
if ((kind & MTH) != 0) key.append(MsgSym.KINDNAME_KEY_METHOD);
if ((kind & TYP) != 0) key.append(MsgSym.KINDNAME_KEY_CLASS);
if ((kind & PCK) != 0) key.append(MsgSym.KINDNAME_KEY_PACKAGE);
return JCDiagnostic.fragment(key.toString(), kind);
}
/** A localized string describing the kind -- either class or interface --
* of a given type.
*/
static JCDiagnostic typeKindName(Type t) {
if (t.tag == TYPEVAR ||
t.tag == CLASS && (t.tsym.flags() & COMPOUND) != 0)
return JCDiagnostic.fragment(MsgSym.KINDNAME_TYPE_VARIABLE_BOUND);
else if (t.tag == PACKAGE)
return JCDiagnostic.fragment(MsgSym.KINDNAME_PACKAGE);
else if ((t.tsym.flags_field & ANNOTATION) != 0)
return JCDiagnostic.fragment(MsgSym.KINDNAME_ANNOTATION);
else if ((t.tsym.flags_field & INTERFACE) != 0)
return JCDiagnostic.fragment(MsgSym.KINDNAME_INTERFACE);
else
return JCDiagnostic.fragment(MsgSym.KINDNAME_CLASS);
}
/** A localized string describing the kind of a missing symbol, given an
* error kind.
*/
static JCDiagnostic absentKindName(int kind) {
switch (kind) {
case ABSENT_VAR:
return JCDiagnostic.fragment(MsgSym.KINDNAME_VARIABLE);
case WRONG_MTHS: case WRONG_MTH: case ABSENT_MTH:
return JCDiagnostic.fragment(MsgSym.KINDNAME_METHOD);
case ABSENT_TYP:
return JCDiagnostic.fragment(MsgSym.KINDNAME_CLASS);
default:
return JCDiagnostic.fragment(MsgSym.KINDNAME, kind);
}
}
/* ***************************************************************************
* ResolveError classes, indicating error situations when accessing symbols
****************************************************************************/
public void logAccessError(JavafxEnv<JavafxAttrContext> env, JCTree tree, Type type) {
AccessError error = new AccessError(env, type.getEnclosingType(), type.tsym);
error.report(log, tree.pos(), type.getEnclosingType(), null, null, null);
}
/** Root class for resolve errors.
* Instances of this class indicate "Symbol not found".
* Instances of subclass indicate other errors.
*/
private class ResolveError extends Symbol {
ResolveError(int kind, Symbol sym, String debugName) {
super(kind, 0, null, null, null);
this.debugName = debugName;
this.sym = sym;
}
/** The name of the kind of error, for debugging only.
*/
final String debugName;
/** The symbol that was determined by resolution, or errSymbol if none
* was found.
*/
final Symbol sym;
/** The symbol that was a close mismatch, or null if none was found.
* wrongSym is currently set if a simgle method with the correct name, but
* the wrong parameters was found.
*/
Symbol wrongSym;
/** An auxiliary explanation set in case of instantiation errors.
*/
JCDiagnostic explanation;
public <R, P> R accept(ElementVisitor<R, P> v, P p) {
throw new AssertionError();
}
/** Print the (debug only) name of the kind of error.
*/
@Override
public String toString() {
return debugName + " wrongSym=" + wrongSym + " explanation=" + explanation;
}
/** Update wrongSym and explanation and return this.
*/
ResolveError setWrongSym(Symbol sym, JCDiagnostic explanation) {
this.wrongSym = sym;
this.explanation = explanation;
return this;
}
/** Update wrongSym and return this.
*/
ResolveError setWrongSym(Symbol sym) {
this.wrongSym = sym;
this.explanation = null;
return this;
}
@Override
public boolean exists() {
switch (kind) {
case HIDDEN:
case ABSENT_VAR:
case ABSENT_MTH:
case ABSENT_TYP:
return false;
default:
return true;
}
}
/** Report error.
* @param log The error log to be used for error reporting.
* @param pos The position to be used for error reporting.
* @param site The original type from where the selection took place.
* @param name The name of the symbol to be resolved.
* @param argtypes The invocation's value arguments,
* if we looked for a method.
* @param typeargtypes The invocation's type arguments,
* if we looked for a method.
*/
void report(Log log, DiagnosticPosition pos, Type site, Name name,
List<Type> argtypes, List<Type> typeargtypes) {
if (name != name.table.error) {
JCDiagnostic kindname = absentKindName(kind);
String idname = name.toString();
String args = "";
String typeargs = "";
if (kind >= WRONG_MTHS && kind <= ABSENT_MTH) {
if (isOperator(name)) {
log.error(pos, MsgSym.MESSAGE_OPERATOR_CANNOT_BE_APPLIED,
name, Type.toString(argtypes));
return;
}
if (name == name.table.init) {
kindname = JCDiagnostic.fragment(MsgSym.KINDNAME_CONSTRUCTOR);
idname = site.tsym.name.toString();
}
args = "(" + Type.toString(argtypes) + ")";
if (typeargtypes != null && typeargtypes.nonEmpty())
typeargs = "<" + Type.toString(typeargtypes) + ">";
}
if (kind == WRONG_MTH) {
String wrongSymStr;
if (wrongSym instanceof MethodSymbol)
wrongSymStr =
types.toJavaFXString((MethodSymbol) wrongSym.asMemberOf(site, types),
((MethodSymbol) wrongSym).params);
else
wrongSymStr = wrongSym.toString();
log.error(pos,
MsgSym.MESSAGE_CANNOT_APPLY_SYMBOL + (explanation != null ? ".1" : ""),
wrongSymStr,
types.location(wrongSym, site),
typeargs,
types.toJavaFXString(argtypes),
explanation);
} else if (site.tsym.name.len != 0) {
if (site.tsym.kind == PCK && !site.tsym.exists())
log.error(pos, MsgSym.MESSAGE_DOES_NOT_EXIST, site.tsym);
else
log.error(pos, MsgSym.MESSAGE_CANNOT_RESOLVE_LOCATION,
kindname, idname, args, typeargs,
typeKindName(site), site);
} else {
log.error(pos, MsgSym.MESSAGE_CANNOT_RESOLVE, kindname, idname, args, typeargs);
}
}
}
//where
/** A name designates an operator if it consists
* of a non-empty sequence of operator symbols +-~!/*%&|^<>=
*/
boolean isOperator(Name name) {
int i = 0;
while (i < name.len &&
"+-~!*/%&|^<>=".indexOf(name.byteAt(i)) >= 0) i++;
return i > 0 && i == name.len;
}
}
/** Resolve error class indicating that a symbol is not accessible.
*/
class AccessError extends ResolveError {
AccessError(Symbol sym) {
this(null, null, sym);
}
AccessError(JavafxEnv<JavafxAttrContext> env, Type site, Symbol sym) {
super(HIDDEN, sym, "access error");
this.env = env;
this.site = site;
if (debugResolve)
log.error(MsgSym.MESSAGE_PROC_MESSAGER, sym + " @ " + site + " is inaccessible.");
}
private JavafxEnv<JavafxAttrContext> env;
private Type site;
/** Report error.
* @param log The error log to be used for error reporting.
* @param pos The position to be used for error reporting.
* @param site The original type from where the selection took place.
* @param name The name of the symbol to be resolved.
* @param argtypes The invocation's value arguments,
* if we looked for a method.
* @param typeargtypes The invocation's type arguments,
* if we looked for a method.
*/
@Override
void report(Log log, DiagnosticPosition pos, Type site, Name name,
List<Type> argtypes, List<Type> typeargtypes) {
if (sym.owner.type.tag != ERROR) {
if (sym.name == sym.name.table.init && sym.owner != site.tsym)
new ResolveError(ABSENT_MTH, sym.owner, "absent method " + sym).report(
log, pos, site, name, argtypes, typeargtypes);
if ((sym.flags() & PUBLIC) != 0
|| (env != null && this.site != null
&& !isAccessible(env, this.site)))
log.error(pos, MsgSym.MESSAGE_NOT_DEF_ACCESS_CLASS_INTF_CANNOT_ACCESS,
sym, sym.location());
else if ((sym.flags() & JavafxFlags.JavafxAccessFlags) == 0L) // 'package' access
log.error(pos, MsgSym.MESSAGE_NOT_DEF_PUBLIC_CANNOT_ACCESS,
sym, sym.location());
else
log.error(pos, MsgSym.MESSAGE_REPORT_ACCESS, sym,
JavafxCheck.protectionString(sym.flags()),
sym.location());
}
}
}
/** Resolve error class indicating that an instance member was accessed
* from a static context.
*/
class StaticError extends ResolveError {
StaticError(Symbol sym) {
super(STATICERR, sym, "static error");
}
/** Report error.
* @param log The error log to be used for error reporting.
* @param pos The position to be used for error reporting.
* @param site The original type from where the selection took place.
* @param name The name of the symbol to be resolved.
* @param argtypes The invocation's value arguments,
* if we looked for a method.
* @param typeargtypes The invocation's type arguments,
* if we looked for a method.
*/
@Override
void report(Log log,
DiagnosticPosition pos,
Type site,
Name name,
List<Type> argtypes,
List<Type> typeargtypes) {
String symstr = ((sym.kind == TYP && sym.type.tag == CLASS)
? types.erasure(sym.type)
: sym).toString();
log.error(pos, MsgSym.MESSAGE_NON_STATIC_CANNOT_BE_REF,
kindName(sym), symstr);
}
}
/** Resolve error class indicating an ambiguous reference.
*/
class AmbiguityError extends ResolveError {
Symbol sym1;
Symbol sym2;
AmbiguityError(Symbol sym1, Symbol sym2) {
super(AMBIGUOUS, sym1, "ambiguity error");
this.sym1 = sym1;
this.sym2 = sym2;
}
/** Report error.
* @param log The error log to be used for error reporting.
* @param pos The position to be used for error reporting.
* @param site The original type from where the selection took place.
* @param name The name of the symbol to be resolved.
* @param argtypes The invocation's value arguments,
* if we looked for a method.
* @param typeargtypes The invocation's type arguments,
* if we looked for a method.
*/
@Override
void report(Log log, DiagnosticPosition pos, Type site, Name name,
List<Type> argtypes, List<Type> typeargtypes) {
AmbiguityError pair = this;
while (true) {
if (pair.sym1.kind == AMBIGUOUS)
pair = (AmbiguityError)pair.sym1;
else if (pair.sym2.kind == AMBIGUOUS)
pair = (AmbiguityError)pair.sym2;
else break;
}
Name sname = pair.sym1.name;
if (sname == sname.table.init) sname = pair.sym1.owner.name;
log.error(pos, MsgSym.MESSAGE_REF_AMBIGUOUS, sname,
kindName(pair.sym1),
pair.sym1,
types.location(pair.sym1, site),
kindName(pair.sym2),
pair.sym2,
types.location(pair.sym2, site));
}
}
/**
* @param sym The symbol.
* @param clazz The type symbol of which the tested symbol is regarded
* as a member.
*
* From the javac code from which this was cloned --
*
* Is this symbol inherited into a given class?
* PRE: If symbol's owner is a interface,
* it is already assumed that the interface is a superinterface
* of given class.
* @param clazz The class for which we want to establish membership.
* This must be a subclass of the member's owner.
*/
public boolean isInheritedIn(Symbol sym, Symbol clazz, JavafxTypes types) {
// because the SCRIPT_PRIVATE bit is too high for the switch, test it later
switch ((short)(sym.flags_field & Flags.AccessFlags)) {
default: // error recovery
case PUBLIC:
return true;
case PRIVATE:
return sym.owner == clazz;
case PROTECTED:
// we model interfaces as extending Object
return (clazz.flags() & INTERFACE) == 0;
case 0:
if ((sym.flags() & JavafxFlags.SCRIPT_PRIVATE) != 0) {
// script-private
//TODO: this isn't right
//return sym.owner == clazz;
};
// 'package' access
boolean foundInherited = false;
for (Type supType : types.supertypes(clazz, clazz.type)) {
if (supType.tsym == sym.owner) {
foundInherited = true;
break;
}
else if (supType.isErroneous()) {
return true; // Error recovery
}
else if (supType.tsym != null && (supType.tsym.flags() & COMPOUND) != 0) {
continue;
}
}
return foundInherited && (clazz.flags() & INTERFACE) == 0;
}
}
}
| false | true | Symbol findVar(JavafxEnv<JavafxAttrContext> env, Name name, int kind, Type expected) {
Symbol bestSoFar = varNotFound;
Symbol sym;
JavafxEnv<JavafxAttrContext> env1 = env;
boolean staticOnly = false;
boolean innerAccess = false;
Type mtype = expected;
if (mtype instanceof FunctionType)
mtype = mtype.asMethodType();
boolean checkArgs = mtype instanceof MethodType || mtype instanceof ForAll;
while (env1 != null) {
Scope sc = env1.info.scope;
Type envClass;
if (env1.tree instanceof JFXClassDeclaration) {
JFXClassDeclaration cdecl = (JFXClassDeclaration) env1.tree;
if (cdecl.runMethod != null &&
name != names._this && name != names._super) {
envClass = null;
sc = cdecl.runBodyScope;
innerAccess = true;
}
envClass = cdecl.sym.type;
}
else
envClass = null;
if (envClass != null) {
sym = findMember(env1, envClass, name,
expected,
true, false, false);
if (sym.exists()) {
if (staticOnly) {
// Note: can't call isStatic with null owner
if (sym.owner != null) {
if (!sym.isStatic()) {
return new StaticError(sym);
}
}
}
return sym;
}
}
if (sc != null) {
for (Scope.Entry e = sc.lookup(name); e.scope != null; e = e.next()) {
if ((e.sym.flags_field & SYNTHETIC) != 0)
continue;
if ((e.sym.kind & (MTH|VAR)) != 0) {
if (innerAccess) {
e.sym.flags_field |= JavafxFlags.VARUSE_INNER_ACCESS;
}
if (checkArgs) {
return checkArgs(e.sym, mtype);
}
return e.sym;
}
}
}
if (env1.tree instanceof JFXFunctionDefinition)
innerAccess = true;
if (env1.outer != null && isStatic(env1)) staticOnly = true;
env1 = env1.outer;
}
Scope.Entry e = env.toplevel.namedImportScope.lookup(name);
for (; e.scope != null; e = e.next()) {
sym = e.sym;
Type origin = e.getOrigin().owner.type;
if ((sym.kind & (MTH|VAR)) != 0) {
if (e.sym.owner.type != origin)
sym = sym.clone(e.getOrigin().owner);
return isAccessible(env, origin, sym)
? sym : new AccessError(env, origin, sym);
}
}
Symbol origin = null;
e = env.toplevel.starImportScope.lookup(name);
for (; e.scope != null; e = e.next()) {
sym = e.sym;
if ((sym.kind & (MTH|VAR)) == 0)
continue;
// invariant: sym.kind == VAR
if (bestSoFar.kind < AMBIGUOUS && sym.owner != bestSoFar.owner)
return new AmbiguityError(bestSoFar, sym);
else if (bestSoFar.kind >= VAR) {
origin = e.getOrigin().owner;
bestSoFar = isAccessible(env, origin.type, sym)
? sym : new AccessError(env, origin.type, sym);
}
}
if (name == names.fromString("__DIR__") || name == names.fromString("__FILE__")
|| name == names.fromString("__PROFILE__")) {
Type type = syms.stringType;
return new VarSymbol(Flags.PUBLIC, name, type, env.enclClass.sym);
}
if (bestSoFar.kind == VAR && bestSoFar.owner.type != origin.type)
return bestSoFar.clone(origin);
else
return bestSoFar;
}
| Symbol findVar(JavafxEnv<JavafxAttrContext> env, Name name, int kind, Type expected) {
Symbol bestSoFar = varNotFound;
Symbol sym;
JavafxEnv<JavafxAttrContext> env1 = env;
boolean staticOnly = false;
boolean innerAccess = false;
Type mtype = expected;
if (mtype instanceof FunctionType)
mtype = mtype.asMethodType();
boolean checkArgs = mtype instanceof MethodType || mtype instanceof ForAll;
while (env1 != null) {
Scope sc = env1.info.scope;
Type envClass;
if (env1.tree instanceof JFXClassDeclaration) {
JFXClassDeclaration cdecl = (JFXClassDeclaration) env1.tree;
if (cdecl.runMethod != null &&
name != names._this && name != names._super) {
envClass = null;
sc = cdecl.runBodyScope;
innerAccess = true;
}
envClass = cdecl.sym.type;
}
else
envClass = null;
if (envClass != null) {
sym = findMember(env1, envClass, name,
expected,
true, false, false);
if (sym.exists()) {
if (staticOnly) {
// Note: can't call isStatic with null owner
if (sym.owner != null) {
if (!sym.isStatic()) {
return new StaticError(sym);
}
}
}
return sym;
}
}
if (sc != null) {
for (Scope.Entry e = sc.lookup(name); e.scope != null; e = e.next()) {
if ((e.sym.flags_field & SYNTHETIC) != 0)
continue;
if ((e.sym.kind & (MTH|VAR)) != 0) {
if (innerAccess) {
e.sym.flags_field |= JavafxFlags.VARUSE_INNER_ACCESS;
}
if (checkArgs) {
return checkArgs(e.sym, mtype);
}
return e.sym;
}
}
}
if (env1.tree instanceof JFXFunctionDefinition)
innerAccess = true;
if (env1.outer != null && isStatic(env1)) staticOnly = true;
env1 = env1.outer;
}
Scope.Entry e = env.toplevel.namedImportScope.lookup(name);
for (; e.scope != null; e = e.next()) {
sym = e.sym;
Type origin = e.getOrigin().owner.type;
if ((sym.kind & (MTH|VAR)) != 0) {
if (e.sym.owner.type != origin)
sym = sym.clone(e.getOrigin().owner);
return selectBest(env, origin, mtype,
e.sym, bestSoFar,
true,
false,
false);
}
}
Symbol origin = null;
e = env.toplevel.starImportScope.lookup(name);
for (; e.scope != null; e = e.next()) {
sym = e.sym;
if ((sym.kind & (MTH|VAR)) == 0)
continue;
// invariant: sym.kind == VAR
if (bestSoFar.kind < AMBIGUOUS && sym.owner != bestSoFar.owner)
return new AmbiguityError(bestSoFar, sym);
else if (bestSoFar.kind >= VAR) {
origin = e.getOrigin().owner;
bestSoFar = selectBest(env, origin.type, mtype,
e.sym, bestSoFar,
true,
false,
false);
}
}
if (name == names.fromString("__DIR__") || name == names.fromString("__FILE__")
|| name == names.fromString("__PROFILE__")) {
Type type = syms.stringType;
return new VarSymbol(Flags.PUBLIC, name, type, env.enclClass.sym);
}
if (bestSoFar.kind == VAR && bestSoFar.owner.type != origin.type)
return bestSoFar.clone(origin);
else
return bestSoFar;
}
|
diff --git a/src/uk/me/parabola/mkgmap/osmstyle/RuleSet.java b/src/uk/me/parabola/mkgmap/osmstyle/RuleSet.java
index 2c08a2b7..fcbe7a9f 100644
--- a/src/uk/me/parabola/mkgmap/osmstyle/RuleSet.java
+++ b/src/uk/me/parabola/mkgmap/osmstyle/RuleSet.java
@@ -1,219 +1,222 @@
/*
* Copyright (C) 2008 Steve Ratcliffe
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* 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.
*
*
* Author: Steve Ratcliffe
* Create date: 08-Nov-2008
*/
package uk.me.parabola.mkgmap.osmstyle;
import java.util.Collections;
import java.util.Formatter;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import uk.me.parabola.mkgmap.osmstyle.eval.BinaryOp;
import uk.me.parabola.mkgmap.osmstyle.eval.EqualsOp;
import uk.me.parabola.mkgmap.osmstyle.eval.ExistsOp;
import uk.me.parabola.mkgmap.osmstyle.eval.Op;
import uk.me.parabola.mkgmap.osmstyle.eval.ValueOp;
import uk.me.parabola.mkgmap.reader.osm.Element;
import uk.me.parabola.mkgmap.reader.osm.GType;
import uk.me.parabola.mkgmap.reader.osm.Rule;
/**
* A group of rules. Basically just a map of a tag=value strings that is used
* as an index and the rule that applies for that tag,value pair.
*
* The main purpose is to separate out the code to add a new rule
* which is moderately complex.
*
* @author Steve Ratcliffe
*/
public class RuleSet implements Rule {
private final Map<String, RuleList> rules = new LinkedHashMap<String, RuleList>();
private boolean initRun;
public void add(String key, RuleHolder rule) {
RuleList rl = rules.get(key);
if (rl == null) {
rl = new RuleList();
rules.put(key, rl);
}
rl.add(rule);
}
/**
* Initialise this rule set before it gets used. What we do is find all
* the rules that might be needed as a result of tags being set during the
* execution of other rules.
*/
public void init() {
for (RuleList rl : rules.values()) {
RuleList ruleList = new RuleList();
for (RuleHolder rh : rl) {
if (rh.getChangeableTags() != null)
initExtraRules(rh, ruleList);
}
rl.add(ruleList);
}
initRun = true;
}
/**
* Initialise the extra rules that could be needed for a given rule.
* Normally we search for rules by looking up the tags that are on an
* element (to save having to really look through each rule). However
* if an action causes a tag to be set, we might miss a rule that
* would match the newly set tag.
*
* So we have to search for all rules that could match a newly set tag.
* These get added to the rule list.
*
* @param rule An individual rule.
* @param extraRules This is a output parameter, new rules are saved here
* by this method. All rules that might be required due to actions
* that set a tag.
*/
private void initExtraRules(RuleHolder rule, RuleList extraRules) {
Set<String> tags = rule.getChangeableTags();
Set<String> moreTags = new HashSet<String>();
do {
for (String t : tags) {
String match = t + '=';
for (Map.Entry<String, RuleList> ent : rules.entrySet()) {
if (ent.getKey().startsWith(match)) {
String exprstr = ent.getKey();
RuleList other = ent.getValue();
// As we are going to run this rule no matter what
// tags were present, we need to add back the condition
// that was represented by the key in the rule map.
Op op = createExpression(exprstr);
for (RuleHolder rh : other) {
// There may be even more changeable tags
// so add them here.
- moreTags.addAll(rh.getChangeableTags());
+ Set<String> changeableTags = rh.getChangeableTags();
+ if (changeableTags == null)
+ continue;
+ moreTags.addAll(changeableTags);
// Re-construct the rule and add it to the output list
Rule r = new ExpressionSubRule(op, rh);
extraRules.add(rh.createCopy(r));
}
}
}
}
// Remove the tags we already know about, and run through the others.
moreTags.removeAll(tags);
tags = Collections.unmodifiableSet(new HashSet<String>(moreTags));
} while (!tags.isEmpty());
}
/**
* Create an expression from a plain string.
* @param expr The string containing an expression.
* @return The compiled form of the expression.
*/
private Op createExpression(String expr) {
String[] keyVal = expr.split("=", 2);
Op op;
if (keyVal[1].equals("*")) {
op = new ExistsOp();
op.setFirst(new ValueOp(keyVal[0]));
} else {
op = new EqualsOp();
op.setFirst(new ValueOp(keyVal[0]));
((BinaryOp) op).setSecond(new ValueOp(keyVal[1]));
}
return op;
}
/**
* Resolve the type for this element by running the rules in order.
*
* This is a very performance critical part of the style system as parts
* of the code are run for every tag in the input file.
*
* @param el The element as read from an OSM xml file in 'tag' format.
* @return A GType describing the Garmin type of the first rule that
* matches. If there is no match then null is returned.
*/
public GType resolveType(Element el) {
assert initRun;
RuleList combined = new RuleList();
for (String tagKey : el) {
RuleList rl = rules.get(tagKey);
if (rl != null)
combined.add(rl);
}
return combined.resolveType(el);
}
/**
* Add all rules from the given rule set to this one.
* @param rs The other rule set.
*/
public void addAll(RuleSet rs) {
rules.putAll(rs.rules);
}
/**
* Format the rule set. Warning: this doesn't produce a valid input
* rule file.
*/
public String toString() {
Formatter fmt = new Formatter();
for (Map.Entry<String, RuleList> ent: rules.entrySet()) {
String first = ent.getKey();
RuleList r = ent.getValue();
r.dumpRules(fmt, first);
}
return fmt.toString();
}
public Set<Map.Entry<String, RuleList>> entrySet() {
return rules.entrySet();
}
public Rule getRule(String key) {
return rules.get(key);
}
public void merge(RuleSet rs) {
for (Map.Entry<String, RuleList> ent : rs.rules.entrySet()) {
String key = ent.getKey();
RuleList otherList = ent.getValue();
// get our list for this key and merge the lists.
// if we don't already have a list then just add it.
RuleList ourList = rules.get(key);
if (ourList == null) {
rules.put(key, otherList);
} else {
for (RuleHolder rh : otherList) {
ourList.add(rh);
}
}
}
}
}
| true | true | private void initExtraRules(RuleHolder rule, RuleList extraRules) {
Set<String> tags = rule.getChangeableTags();
Set<String> moreTags = new HashSet<String>();
do {
for (String t : tags) {
String match = t + '=';
for (Map.Entry<String, RuleList> ent : rules.entrySet()) {
if (ent.getKey().startsWith(match)) {
String exprstr = ent.getKey();
RuleList other = ent.getValue();
// As we are going to run this rule no matter what
// tags were present, we need to add back the condition
// that was represented by the key in the rule map.
Op op = createExpression(exprstr);
for (RuleHolder rh : other) {
// There may be even more changeable tags
// so add them here.
moreTags.addAll(rh.getChangeableTags());
// Re-construct the rule and add it to the output list
Rule r = new ExpressionSubRule(op, rh);
extraRules.add(rh.createCopy(r));
}
}
}
}
// Remove the tags we already know about, and run through the others.
moreTags.removeAll(tags);
tags = Collections.unmodifiableSet(new HashSet<String>(moreTags));
} while (!tags.isEmpty());
}
| private void initExtraRules(RuleHolder rule, RuleList extraRules) {
Set<String> tags = rule.getChangeableTags();
Set<String> moreTags = new HashSet<String>();
do {
for (String t : tags) {
String match = t + '=';
for (Map.Entry<String, RuleList> ent : rules.entrySet()) {
if (ent.getKey().startsWith(match)) {
String exprstr = ent.getKey();
RuleList other = ent.getValue();
// As we are going to run this rule no matter what
// tags were present, we need to add back the condition
// that was represented by the key in the rule map.
Op op = createExpression(exprstr);
for (RuleHolder rh : other) {
// There may be even more changeable tags
// so add them here.
Set<String> changeableTags = rh.getChangeableTags();
if (changeableTags == null)
continue;
moreTags.addAll(changeableTags);
// Re-construct the rule and add it to the output list
Rule r = new ExpressionSubRule(op, rh);
extraRules.add(rh.createCopy(r));
}
}
}
}
// Remove the tags we already know about, and run through the others.
moreTags.removeAll(tags);
tags = Collections.unmodifiableSet(new HashSet<String>(moreTags));
} while (!tags.isEmpty());
}
|
diff --git a/src/test/java/jenkins/plugins/svn_revert/ChangedRevisionsTest.java b/src/test/java/jenkins/plugins/svn_revert/ChangedRevisionsTest.java
index 15c4061..d445df1 100644
--- a/src/test/java/jenkins/plugins/svn_revert/ChangedRevisionsTest.java
+++ b/src/test/java/jenkins/plugins/svn_revert/ChangedRevisionsTest.java
@@ -1,45 +1,45 @@
package jenkins.plugins.svn_revert;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import hudson.model.AbstractBuild;
import hudson.scm.ChangeLogSet;
import java.util.List;
import org.junit.Test;
import org.jvnet.hudson.test.FakeChangeLogSCM.EntryImpl;
import org.jvnet.hudson.test.FakeChangeLogSCM.FakeChangeLogSet;
import org.mockito.Mock;
import com.google.common.collect.Lists;
@SuppressWarnings("rawtypes")
public class ChangedRevisionsTest extends AbstractMockitoTestCase {
private final List<EntryImpl> entries = Lists.newLinkedList();
@Mock
private AbstractBuild build;
private final ChangeLogSet changeLogSet = new FakeChangeLogSet(build, entries);
@Test
public void shouldCalculateChangedRevisions() throws Exception {
when(build.getChangeSet()).thenReturn(changeLogSet);
givenChangedRevision(7);
givenChangedRevision(9);
givenChangedRevision(3);
final Revisions revisions = new ChangedRevisions().getFor(build);
- assertThat(revisions, is(Revisions.create(3, 9)));
+ assertThat(revisions, is(Revisions.create(3, 7, 9)));
}
private void givenChangedRevision(final int revision) {
final EntryImpl entry = mock(EntryImpl.class);
when(entry.getCommitId()).thenReturn(Integer.toString(revision));
entries.add(entry);
}
}
| true | true | public void shouldCalculateChangedRevisions() throws Exception {
when(build.getChangeSet()).thenReturn(changeLogSet);
givenChangedRevision(7);
givenChangedRevision(9);
givenChangedRevision(3);
final Revisions revisions = new ChangedRevisions().getFor(build);
assertThat(revisions, is(Revisions.create(3, 9)));
}
| public void shouldCalculateChangedRevisions() throws Exception {
when(build.getChangeSet()).thenReturn(changeLogSet);
givenChangedRevision(7);
givenChangedRevision(9);
givenChangedRevision(3);
final Revisions revisions = new ChangedRevisions().getFor(build);
assertThat(revisions, is(Revisions.create(3, 7, 9)));
}
|
diff --git a/src/com/android/deskclock/CircleTimerView.java b/src/com/android/deskclock/CircleTimerView.java
index 3551f66a..873df122 100644
--- a/src/com/android/deskclock/CircleTimerView.java
+++ b/src/com/android/deskclock/CircleTimerView.java
@@ -1,205 +1,207 @@
package com.android.deskclock;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.view.View;
/**
* TODO: Insert description here. (generated by isaackatz)
*/
public class CircleTimerView extends View {
private int mRedColor;
private int mWhiteColor;
private long mIntervalTime = 0;
private long mIntervalStartTime = -1;
private long mMarkerTime = -1;
private long mCurrentIntervalTime = 0;
private long mAccumulatedTime = 0;
private boolean mPaused = false;
private static float mStrokeSize = 4;
private static float mDiamondStrokeSize = 12;
private static float mMarkerStrokeSize = 2;
private final Paint mPaint = new Paint();
private final RectF mArcRect = new RectF();
private Resources mResources;
private float mRadiusOffset; // amount to remove from radius to account for markers on circle
// Class has 2 modes:
// Timer mode - counting down. in this mode the animation is counter-clockwise and stops at 0
// Stop watch mode - counting up - in this mode the animation is clockwise and will keep the
// animation until stopped.
private boolean mTimerMode = false; // default is stop watch view
Runnable mAnimationThread = new Runnable() {
@Override
public void run() {
mCurrentIntervalTime =
System.currentTimeMillis() - mIntervalStartTime + mAccumulatedTime;
invalidate();
postDelayed(mAnimationThread, 20);
}
};
public CircleTimerView(Context context) {
this(context, null);
}
public CircleTimerView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public void setIntervalTime(long t) {
mIntervalTime = t;
postInvalidate();
}
public void setMarkerTime(long t) {
mMarkerTime = mCurrentIntervalTime;
postInvalidate();
}
public void reset() {
mIntervalStartTime = -1;
mMarkerTime = -1;
postInvalidate();
}
public void startIntervalAnimation() {
mIntervalStartTime = System.currentTimeMillis();
this.post(mAnimationThread);
mPaused = false;
}
public void stopIntervalAnimation() {
this.removeCallbacks(mAnimationThread);
mIntervalStartTime = -1;
mAccumulatedTime = 0;
}
public boolean isAnimating() {
return (mIntervalStartTime != -1);
}
public void pauseIntervalAnimation() {
this.removeCallbacks(mAnimationThread);
mAccumulatedTime += System.currentTimeMillis() - mIntervalStartTime;
mPaused = true;
}
public void setPassedTime(long time) {
mAccumulatedTime = time;
postInvalidate();
}
private void init(Context c) {
mResources = c.getResources();
mStrokeSize = mResources.getDimension(R.dimen.circletimer_circle_size);
mDiamondStrokeSize = mResources.getDimension(R.dimen.circletimer_diamond_size);
mMarkerStrokeSize =
mResources.getDimension(R.dimen.circletimer_marker_size) * 2 + mStrokeSize;
mPaint.setAntiAlias(true);
mPaint.setStyle(Paint.Style.STROKE);
mWhiteColor = mResources.getColor(R.color.clock_white);
mRedColor = mResources.getColor(R.color.clock_red);
mRadiusOffset = Math.max(mStrokeSize, Math.max(mDiamondStrokeSize, mMarkerStrokeSize));
}
public void setTimerMode(boolean mode) {
mTimerMode = mode;
}
@Override
public void onDraw(Canvas canvas) {
int xCenter = getWidth() / 2 + 1;
int yCenter = getHeight() / 2;
mPaint.setStrokeWidth(mStrokeSize);
float radius = Math.min(xCenter, yCenter) - mRadiusOffset;
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
xCenter = (int) (radius + mRadiusOffset);
}
mPaint.setColor(mWhiteColor);
canvas.drawCircle (xCenter, yCenter, radius, mPaint);
mPaint.setColor(mRedColor);
if (mIntervalStartTime != -1) {
mArcRect.top = yCenter - radius;
mArcRect.bottom = yCenter + radius;
mArcRect.left = xCenter - radius;
mArcRect.right = xCenter + radius;
float percent = (float)mCurrentIntervalTime / (float)mIntervalTime;
+ // prevent timer from doing more than one full circle
+ percent = (percent > 1 && mTimerMode) ? 1 : percent;
if (mTimerMode){
canvas.drawArc (mArcRect, 270, - percent * 360 , false, mPaint);
} else {
canvas.drawArc (mArcRect, 270, + percent * 360 , false, mPaint);
}
mPaint.setStrokeWidth(mDiamondStrokeSize);
if (mTimerMode){
canvas.drawArc (mArcRect, 265 - percent * 360, 10 , false, mPaint);
} else {
canvas.drawArc (mArcRect, 265 + percent * 360, 10 , false, mPaint);
}
}
if (mMarkerTime != -1) {
mPaint.setStrokeWidth(mMarkerStrokeSize);
mPaint.setColor(mWhiteColor);
float angle = (float)(mMarkerTime % mIntervalTime) / (float)mIntervalTime * 360;
canvas.drawArc (mArcRect, 270 + angle, 1 , false, mPaint);
}
}
private static final String PREF_CTV_PAUSED = "_ctv_paused";
private static final String PREF_CTV_INTERVAL = "_ctv_interval";
private static final String PREF_CTV_INTERVAL_START = "_ctv_interval_start";
private static final String PREF_CTV_CURRENT_INTERVAL = "_ctv_current_interval";
private static final String PREF_CTV_ACCUM_TIME = "_ctv_accum_time";
private static final String PREF_CTV_TIMER_MODE = "_ctv_timer_mode";
private static final String PREF_CTV_MARKER_TIME = "_ctv_marker_time";
// Since this view is used in multiple places, use the key to save different instances
public void writeToSharedPref(SharedPreferences prefs, String key) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean (key + PREF_CTV_PAUSED, mPaused);
editor.putLong (key + PREF_CTV_INTERVAL, mIntervalTime);
editor.putLong (key + PREF_CTV_INTERVAL_START, mIntervalStartTime);
editor.putLong (key + PREF_CTV_CURRENT_INTERVAL, mCurrentIntervalTime);
editor.putLong (key + PREF_CTV_ACCUM_TIME, mAccumulatedTime);
editor.putLong (key + PREF_CTV_MARKER_TIME, mMarkerTime);
editor.putBoolean (key + PREF_CTV_TIMER_MODE, mTimerMode);
editor.apply();
}
public void readFromSharedPref(SharedPreferences prefs, String key) {
mPaused = prefs.getBoolean(key + PREF_CTV_PAUSED, false);
mIntervalTime = prefs.getLong(key + PREF_CTV_INTERVAL, 0);
mIntervalStartTime = prefs.getLong(key + PREF_CTV_INTERVAL_START, -1);
mCurrentIntervalTime = prefs.getLong(key + PREF_CTV_CURRENT_INTERVAL, 0);
mAccumulatedTime = prefs.getLong(key + PREF_CTV_ACCUM_TIME, 0);
mMarkerTime = prefs.getLong(key + PREF_CTV_MARKER_TIME, -1);
mTimerMode = prefs.getBoolean(key + PREF_CTV_TIMER_MODE, false);
if (mIntervalStartTime != -1 && !mPaused) {
this.post(mAnimationThread);
}
}
}
| true | true | public void onDraw(Canvas canvas) {
int xCenter = getWidth() / 2 + 1;
int yCenter = getHeight() / 2;
mPaint.setStrokeWidth(mStrokeSize);
float radius = Math.min(xCenter, yCenter) - mRadiusOffset;
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
xCenter = (int) (radius + mRadiusOffset);
}
mPaint.setColor(mWhiteColor);
canvas.drawCircle (xCenter, yCenter, radius, mPaint);
mPaint.setColor(mRedColor);
if (mIntervalStartTime != -1) {
mArcRect.top = yCenter - radius;
mArcRect.bottom = yCenter + radius;
mArcRect.left = xCenter - radius;
mArcRect.right = xCenter + radius;
float percent = (float)mCurrentIntervalTime / (float)mIntervalTime;
if (mTimerMode){
canvas.drawArc (mArcRect, 270, - percent * 360 , false, mPaint);
} else {
canvas.drawArc (mArcRect, 270, + percent * 360 , false, mPaint);
}
mPaint.setStrokeWidth(mDiamondStrokeSize);
if (mTimerMode){
canvas.drawArc (mArcRect, 265 - percent * 360, 10 , false, mPaint);
} else {
canvas.drawArc (mArcRect, 265 + percent * 360, 10 , false, mPaint);
}
}
if (mMarkerTime != -1) {
mPaint.setStrokeWidth(mMarkerStrokeSize);
mPaint.setColor(mWhiteColor);
float angle = (float)(mMarkerTime % mIntervalTime) / (float)mIntervalTime * 360;
canvas.drawArc (mArcRect, 270 + angle, 1 , false, mPaint);
}
}
| public void onDraw(Canvas canvas) {
int xCenter = getWidth() / 2 + 1;
int yCenter = getHeight() / 2;
mPaint.setStrokeWidth(mStrokeSize);
float radius = Math.min(xCenter, yCenter) - mRadiusOffset;
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
xCenter = (int) (radius + mRadiusOffset);
}
mPaint.setColor(mWhiteColor);
canvas.drawCircle (xCenter, yCenter, radius, mPaint);
mPaint.setColor(mRedColor);
if (mIntervalStartTime != -1) {
mArcRect.top = yCenter - radius;
mArcRect.bottom = yCenter + radius;
mArcRect.left = xCenter - radius;
mArcRect.right = xCenter + radius;
float percent = (float)mCurrentIntervalTime / (float)mIntervalTime;
// prevent timer from doing more than one full circle
percent = (percent > 1 && mTimerMode) ? 1 : percent;
if (mTimerMode){
canvas.drawArc (mArcRect, 270, - percent * 360 , false, mPaint);
} else {
canvas.drawArc (mArcRect, 270, + percent * 360 , false, mPaint);
}
mPaint.setStrokeWidth(mDiamondStrokeSize);
if (mTimerMode){
canvas.drawArc (mArcRect, 265 - percent * 360, 10 , false, mPaint);
} else {
canvas.drawArc (mArcRect, 265 + percent * 360, 10 , false, mPaint);
}
}
if (mMarkerTime != -1) {
mPaint.setStrokeWidth(mMarkerStrokeSize);
mPaint.setColor(mWhiteColor);
float angle = (float)(mMarkerTime % mIntervalTime) / (float)mIntervalTime * 360;
canvas.drawArc (mArcRect, 270 + angle, 1 , false, mPaint);
}
}
|
diff --git a/src/euler/level2/Problem084.java b/src/euler/level2/Problem084.java
index 1d2c0cb..e7ba0cd 100644
--- a/src/euler/level2/Problem084.java
+++ b/src/euler/level2/Problem084.java
@@ -1,224 +1,224 @@
package euler.level2;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map.Entry;
import euler.Problem;
public class Problem084 extends Problem<Integer> {
class ChanceField extends Field {
public ChanceField(int id, String name) {
super(id, name);
}
@Override
protected void addToMap(ChanceMap chances, double chance) {
board[0].addToMap(chances, 1 / 16. * chance); // GO
board[10].addToMap(chances, 1 / 16. * chance); // JAIL
board[11].addToMap(chances, 1 / 16. * chance); // C1
board[24].addToMap(chances, 1 / 16. * chance); // E3
board[39].addToMap(chances, 1 / 16. * chance); // H2
board[5].addToMap(chances, 1 / 16. * chance); // R1
nextRailway().addToMap(chances, 2 / 16. * chance);
nextUtility().addToMap(chances, 1 / 16. * chance);
board[getId() - 3].addToMap(chances, 1 / 16. * chance); // back 3
super.addToMap(chances, 6 / 16. * chance);
}
private Field nextRailway() {
for (int ix = getId() + 1;; ix = (ix + 1) % board.length) {
if (board[ix].getName().startsWith("R")) {
return board[ix];
}
}
}
private Field nextUtility() {
for (int ix = getId() + 1;; ix = (ix + 1) % board.length) {
if (board[ix].getName().startsWith("U")) {
return board[ix];
}
}
}
}
static class ChanceMap extends HashMap<Field, Double> {
private static final long serialVersionUID = -2044704161069978938L;
public void add(Field field, double chance) {
if (containsKey(field)) {
chance += get(field);
}
put(field, chance);
}
}
class CommunityChestField extends Field {
public CommunityChestField(int id, String name) {
super(id, name);
}
@Override
protected void addToMap(ChanceMap chances, double chance) {
board[0].addToMap(chances, 1 / 16. * chance); // GO
board[10].addToMap(chances, 1 / 16. * chance); // JAIL
super.addToMap(chances, 14 / 16. * chance);
}
}
class Field {
private final int id;
private final String name;
private double chance, newChance;
public Field(int id, String name) {
this.id = id;
this.name = name;
chance = 1;
}
protected void addToMap(ChanceMap chances, double chance) {
chances.add(this, chance);
}
public double getChance() {
return chance;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public double getNewChance() {
return newChance;
}
private void propagateChance(ChanceMap chances, int nrDice, double baseChance, int doublesTrown) {
for (int dice1 = 1; dice1 <= nrDice; dice1++) {
for (int dice2 = 1; dice2 <= nrDice; dice2++) {
Field next = board[(id + dice1 + dice2) % board.length];
if (dice1 == dice2 && next != board[10]) {
if (doublesTrown < 2) {
// Trow again from the new fields?
ChanceMap nextMap = new ChanceMap();
next.addToMap(nextMap, baseChance);
for (Entry<Field, Double> entry : nextMap.entrySet()) {
entry.getKey().propagateChance(chances, nrDice, entry.getValue() * baseChance, doublesTrown + 1);
}
} else {
board[10].addToMap(chances, baseChance); // 3 doubles, go to jail!
}
} else {
next.addToMap(chances, baseChance);
}
}
}
}
public void propagateChance(int nrDice) {
ChanceMap chances = new ChanceMap();
propagateChance(chances, nrDice, 1. / (nrDice * nrDice), 0);
for (Entry<Field, Double> chance : chances.entrySet()) {
chance.getKey().newChance += this.chance * chance.getValue();
}
}
public void reset(double factor) {
chance = newChance * factor;
newChance = 0;
}
@Override
public String toString() {
return String.format("(%02d) %4s -> %1.2f%%", id, name, chance * 100);
}
}
class GotoJailField extends Field {
public GotoJailField(int id, String name) {
super(id, name);
}
@Override
protected void addToMap(ChanceMap chances, double chance) {
board[10].addToMap(chances, chance); // JAIL
}
}
private final Field[] board = new Field[] { new Field(0, "GO"),
new Field(1, "A1"),
new CommunityChestField(2, "CC1"),
new Field(3, "A2"),
new Field(4, "T1"),
new Field(5, "R1"),
new Field(6, "B1"),
new ChanceField(7, "CH1"),
new Field(8, "B2"),
new Field(9, "B3"),
new Field(10, "JAIL"),
new Field(11, "C1"),
new Field(12, "U1"),
new Field(13, "C2"),
new Field(14, "C3"),
new Field(15, "R2"),
new Field(16, "D1"),
new CommunityChestField(17, "CC2"),
new Field(18, "D2"),
new Field(19, "D3"),
new Field(20, "FP"),
new Field(21, "E1"),
new ChanceField(22, "CH2"),
new Field(23, "E2"),
new Field(24, "E3"),
new Field(25, "R3"),
new Field(26, "F1"),
new Field(27, "F2"),
new Field(28, "U2"),
new Field(29, "F3"),
new GotoJailField(30, "G2J"),
new Field(31, "G1"),
new Field(32, "G2"),
new CommunityChestField(33, "CC3"),
new Field(34, "G3"),
new Field(35, "R4"),
new ChanceField(36, "CH3"),
new Field(37, "H1"),
new Field(38, "T2"),
new Field(39, "H2"), };
@Override
public Integer solve() {
double total = 0;
for (int it = 0; it < 10; it++) {
for (Field field : board) {
- field.propagateChance(6);
+ field.propagateChance(4);
}
total = 0;
for (Field field : board) {
total += field.getNewChance();
}
double factor = 1 / total;
for (Field field : board) {
field.reset(factor);
}
}
Arrays.sort(board, new Comparator<Field>() {
@Override
public int compare(Field o1, Field o2) {
return (int) ((o2.getChance() - o1.getChance()) * 10000);
};
});
return board[0].getId() * 10000 + board[1].getId() * 100 + board[2].getId();
}
}
| true | true | public Integer solve() {
double total = 0;
for (int it = 0; it < 10; it++) {
for (Field field : board) {
field.propagateChance(6);
}
total = 0;
for (Field field : board) {
total += field.getNewChance();
}
double factor = 1 / total;
for (Field field : board) {
field.reset(factor);
}
}
Arrays.sort(board, new Comparator<Field>() {
@Override
public int compare(Field o1, Field o2) {
return (int) ((o2.getChance() - o1.getChance()) * 10000);
};
});
return board[0].getId() * 10000 + board[1].getId() * 100 + board[2].getId();
}
| public Integer solve() {
double total = 0;
for (int it = 0; it < 10; it++) {
for (Field field : board) {
field.propagateChance(4);
}
total = 0;
for (Field field : board) {
total += field.getNewChance();
}
double factor = 1 / total;
for (Field field : board) {
field.reset(factor);
}
}
Arrays.sort(board, new Comparator<Field>() {
@Override
public int compare(Field o1, Field o2) {
return (int) ((o2.getChance() - o1.getChance()) * 10000);
};
});
return board[0].getId() * 10000 + board[1].getId() * 100 + board[2].getId();
}
|
diff --git a/src/main/java/org/apache/commons/net/smtp/AuthSMTPClient.java b/src/main/java/org/apache/commons/net/smtp/AuthSMTPClient.java
index 3dbf9c355..aebc9115d 100644
--- a/src/main/java/org/apache/commons/net/smtp/AuthSMTPClient.java
+++ b/src/main/java/org/apache/commons/net/smtp/AuthSMTPClient.java
@@ -1,176 +1,176 @@
// Copyright (C) 2009 The Android Open Source Project
//
// 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.apache.commons.net.smtp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.eclipse.jgit.util.Base64;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
public class AuthSMTPClient extends SMTPClient {
private static final Logger log =
LoggerFactory.getLogger(AuthSMTPClient.class);
private String authTypes;
private Set<String> allowedRcptTo;
public AuthSMTPClient(final String charset) {
super(charset);
}
public void setAllowRcpt(final String[] allowed) {
if (allowed != null && allowed.length > 0) {
if (allowedRcptTo == null) {
allowedRcptTo = new HashSet<String>();
}
for (final String addr : allowed) {
allowedRcptTo.add(addr);
}
}
}
@Override
public int rcpt(final String forwardPath) throws IOException {
if (allowRcpt(forwardPath)) {
return super.rcpt(forwardPath);
} else {
log.warn("Not emailing " + forwardPath + " (prohibited by allowrcpt)");
return SMTPReply.ACTION_OK;
}
}
private boolean allowRcpt(String addr) {
if (allowedRcptTo == null) {
return true;
}
if (addr.startsWith("<") && addr.endsWith(">")) {
addr = addr.substring(1, addr.length() - 1);
}
if (allowedRcptTo.contains(addr)) {
return true;
}
final int at = addr.indexOf('@');
if (at > 0) {
return allowedRcptTo.contains(addr.substring(at))
|| allowedRcptTo.contains(addr.substring(at + 1));
}
return false;
}
@Override
public String[] getReplyStrings() {
return _replyLines.toArray(new String[_replyLines.size()]);
}
@Override
public boolean login() throws IOException {
final String name = getLocalAddress().getHostName();
if (name == null) {
return false;
}
boolean ok = SMTPReply.isPositiveCompletion(sendCommand("EHLO", name));
authTypes = "";
for (String line : getReplyStrings()) {
if (line != null && line.startsWith("250 AUTH ")) {
authTypes = line;
break;
}
}
return ok;
}
public boolean auth(String smtpUser, String smtpPass) throws IOException {
List<String> types = Arrays.asList(authTypes.split(" "));
- if (types.isEmpty()) {
+ if ("".equals(authTypes)) {
// Server didn't advertise authentication support.
//
return true;
}
if (smtpPass == null) {
smtpPass = "";
}
if (types.contains("CRAM-SHA1")) {
return authCram(smtpUser, smtpPass, "SHA1");
}
if (types.contains("CRAM-MD5")) {
return authCram(smtpUser, smtpPass, "MD5");
}
if (types.contains("PLAIN")) {
return authPlain(smtpUser, smtpPass);
}
throw new IOException("Unsupported AUTH: " + authTypes);
}
private boolean authCram(String smtpUser, String smtpPass, String alg)
throws UnsupportedEncodingException, IOException {
final String macName = "Hmac" + alg;
if (sendCommand("AUTH", "CRAM-" + alg) != 334) {
return false;
}
final byte[] nonce = Base64.decode(getReplyStrings()[0].split(" ", 2)[1]);
final String sec;
try {
Mac mac = Mac.getInstance(macName);
mac.init(new SecretKeySpec(smtpPass.getBytes("UTF-8"), macName));
sec = toHex(mac.doFinal(nonce));
} catch (NoSuchAlgorithmException e) {
throw new IOException("Cannot use CRAM-" + alg, e);
} catch (InvalidKeyException e) {
throw new IOException("Cannot use CRAM-" + alg, e);
}
String token = smtpUser + ' ' + sec;
String cmd = Base64.encodeBytes(token.getBytes("UTF-8"));
return SMTPReply.isPositiveCompletion(sendCommand(cmd));
}
private static final char[] hexchar =
{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
'e', 'f'};
private String toHex(final byte[] b) {
final StringBuilder sec = new StringBuilder();
for (int i = 0; i < b.length; i++) {
final int u = (b[i] >> 4) & 0xf;
final int l = b[i] & 0xf;
sec.append(hexchar[u]);
sec.append(hexchar[l]);
}
return sec.toString();
}
private boolean authPlain(String smtpUser, String smtpPass)
throws UnsupportedEncodingException, IOException {
String token = '\0' + smtpUser + '\0' + smtpPass;
String cmd = "PLAIN " + Base64.encodeBytes(token.getBytes("UTF-8"));
return SMTPReply.isPositiveCompletion(sendCommand("AUTH", cmd));
}
}
| true | true | public boolean auth(String smtpUser, String smtpPass) throws IOException {
List<String> types = Arrays.asList(authTypes.split(" "));
if (types.isEmpty()) {
// Server didn't advertise authentication support.
//
return true;
}
if (smtpPass == null) {
smtpPass = "";
}
if (types.contains("CRAM-SHA1")) {
return authCram(smtpUser, smtpPass, "SHA1");
}
if (types.contains("CRAM-MD5")) {
return authCram(smtpUser, smtpPass, "MD5");
}
if (types.contains("PLAIN")) {
return authPlain(smtpUser, smtpPass);
}
throw new IOException("Unsupported AUTH: " + authTypes);
}
| public boolean auth(String smtpUser, String smtpPass) throws IOException {
List<String> types = Arrays.asList(authTypes.split(" "));
if ("".equals(authTypes)) {
// Server didn't advertise authentication support.
//
return true;
}
if (smtpPass == null) {
smtpPass = "";
}
if (types.contains("CRAM-SHA1")) {
return authCram(smtpUser, smtpPass, "SHA1");
}
if (types.contains("CRAM-MD5")) {
return authCram(smtpUser, smtpPass, "MD5");
}
if (types.contains("PLAIN")) {
return authPlain(smtpUser, smtpPass);
}
throw new IOException("Unsupported AUTH: " + authTypes);
}
|
diff --git a/amibe/src/org/jcae/mesh/amibe/algos3d/Remesh.java b/amibe/src/org/jcae/mesh/amibe/algos3d/Remesh.java
index aae9f55b..1f3489da 100644
--- a/amibe/src/org/jcae/mesh/amibe/algos3d/Remesh.java
+++ b/amibe/src/org/jcae/mesh/amibe/algos3d/Remesh.java
@@ -1,1015 +1,1022 @@
/* jCAE stand for Java Computer Aided Engineering. Features are : Small CAD
modeler, Finite element mesher, Plugin architecture.
Copyright (C) 2009,2010,2011, by EADS France
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.jcae.mesh.amibe.algos3d;
import org.jcae.mesh.amibe.ds.Mesh;
import org.jcae.mesh.amibe.ds.Triangle;
import org.jcae.mesh.amibe.ds.AbstractHalfEdge;
import org.jcae.mesh.amibe.ds.Vertex;
import org.jcae.mesh.amibe.metrics.KdTree;
import org.jcae.mesh.amibe.projection.MeshLiaison;
import org.jcae.mesh.amibe.ds.HalfEdge;
import org.jcae.mesh.amibe.metrics.EuclidianMetric3D;
import org.jcae.mesh.amibe.metrics.Matrix3D;
import org.jcae.mesh.amibe.metrics.Metric;
import org.jcae.mesh.amibe.traits.MeshTraitsBuilder;
import org.jcae.mesh.xmldata.MeshReader;
import org.jcae.mesh.xmldata.MeshWriter;
import org.jcae.mesh.xmldata.DoubleFileReader;
import org.jcae.mesh.xmldata.PrimitiveFileReaderFactory;
import gnu.trove.PrimeFinder;
import gnu.trove.TIntObjectHashMap;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Map;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Collection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Remesh an existing mesh.
*
* See org.jcae.mesh.amibe.algos2d.Insertion
* @author Denis Barbier
*/
public class Remesh
{
private final static Logger LOGGER = Logger.getLogger(Remesh.class.getName());
private static final double ONE_PLUS_SQRT2 = 1.0 + Math.sqrt(2.0);
private int progressBarStatus = 10000;
private final Mesh mesh;
private final MeshLiaison liaison;
// Octree to find nearest Vertex in current mesh
private final KdTree<Vertex> kdTree;
private Map<Vertex, Vertex> neighborBgMap = new HashMap<Vertex, Vertex>();
private DoubleFileReader dfrMetrics;
private final double minlen;
private final double maxlen;
// useful to see if addCandidatePoints() does its job
private int nrInterpolations;
private int nrFailedInterpolations;
Map<Triangle, Collection<Vertex>> mapTriangleVertices = new HashMap<Triangle, Collection<Vertex>>();
Map<Vertex, Triangle> surroundingTriangle = new HashMap<Vertex, Triangle>();
private final boolean project;
private final boolean hasRidges;
// true if mesh has free edges, ridges or nonmanifold edges, false otherwise
private final boolean hasFeatureEdges;
private final double coplanarity;
private final boolean allowNearNodes;
private final boolean remeshOnlyFeatureEdges;
private AnalyticMetricInterface analyticMetric = LATER_BINDING;
private final Map<Vertex, EuclidianMetric3D> metrics;
private static final AnalyticMetricInterface LATER_BINDING = new AnalyticMetricInterface() {
public double getTargetSize(double x, double y, double z)
{
throw new RuntimeException();
}
};
private TIntObjectHashMap<AnalyticMetricInterface> metricsPartitionMap = new TIntObjectHashMap<AnalyticMetricInterface>();
public interface AnalyticMetricInterface
{
double getTargetSize(double x, double y, double z);
}
/**
* Creates a <code>Remesh</code> instance.
*
* @param m the <code>Mesh</code> instance to refine.
*/
@Deprecated
public Remesh(Mesh m)
{
this(m, MeshTraitsBuilder.getDefault3D(), new HashMap<String, String>());
}
@Deprecated
public Remesh(Mesh m, Map<String, String> opts)
{
this(m, MeshTraitsBuilder.getDefault3D(), opts);
}
/**
* Creates a <code>Remesh</code> instance.
*
* @param bgMesh the <code>Mesh</code> instance to refine.
* @param options map containing key-value pairs to modify algorithm
* behaviour. No options are available for now.
*/
private Remesh(final Mesh bgMesh, final MeshTraitsBuilder mtb, final Map<String, String> options)
{
this(new MeshLiaison(bgMesh, mtb), options);
}
public Remesh(final MeshLiaison liaison, final Map<String, String> options)
{
this(liaison.getMesh(), liaison, options);
}
private Remesh(final Mesh m, final MeshLiaison meshLiaison, final Map<String, String> options)
{
liaison = meshLiaison;
mesh = m;
double size = 0.0;
double nearLengthRatio = 1.0 / Math.sqrt(2.0);
boolean proj = false;
boolean nearNodes = false;
boolean onlyFeatureEdges = false;
double copl = 0.8;
Map<String, String> decimateOptions = new HashMap<String, String>();
for (final Map.Entry<String, String> opt: options.entrySet())
{
final String key = opt.getKey();
final String val = opt.getValue();
if (key.equals("size"))
{
size = Double.valueOf(val).doubleValue();
analyticMetric = null;
dfrMetrics = null;
}
else if (key.equals("nearLengthRatio"))
{
nearLengthRatio = Double.valueOf(val).doubleValue();
}
else if (key.equals("coplanarity"))
{
copl = Double.valueOf(val).doubleValue();
}
else if (key.equals("decimateSize"))
{
decimateOptions.put("size", val);
}
else if (key.equals("decimateTarget"))
{
decimateOptions.put("maxtriangles", val);
}
else if (key.equals("metricsFile"))
{
PrimitiveFileReaderFactory pfrf = new PrimitiveFileReaderFactory();
try {
dfrMetrics = pfrf.getDoubleReader(new File(val));
} catch (FileNotFoundException ex) {
LOGGER.log(Level.SEVERE, null, ex);
} catch (IOException ex) {
LOGGER.log(Level.SEVERE, null, ex);
}
analyticMetric = null;
}
else if (key.equals("project"))
proj = Boolean.valueOf(val).booleanValue();
else if (key.equals("allowNearNodes"))
nearNodes = Boolean.valueOf(val).booleanValue();
else if (key.equals("features"))
onlyFeatureEdges = Boolean.valueOf(val).booleanValue();
else
LOGGER.warning("Unknown option: "+key);
}
if (meshLiaison == null)
mesh.buildRidges(copl);
double targetSize = size;
minlen = nearLengthRatio;
maxlen = Math.sqrt(2.0);
project = proj;
coplanarity = copl;
allowNearNodes = nearNodes;
remeshOnlyFeatureEdges = onlyFeatureEdges;
liaison.buildSkeleton();
if (!decimateOptions.isEmpty())
{
new QEMDecimateHalfEdge(liaison, decimateOptions).compute();
}
boolean ridges = false;
boolean features = false;
for (Triangle f: mesh.getTriangles())
{
if (f.hasAttributes(AbstractHalfEdge.OUTER))
continue;
if (!ridges && f.hasAttributes(AbstractHalfEdge.SHARP))
ridges = true;
if (!features && f.hasAttributes(AbstractHalfEdge.BOUNDARY | AbstractHalfEdge.NONMANIFOLD))
features = true;
}
hasRidges = ridges;
hasFeatureEdges = ridges | features;
Collection<Vertex> nodeset = mesh.getNodes();
if (nodeset == null)
{
nodeset = new LinkedHashSet<Vertex>(mesh.getTriangles().size() / 2);
for (Triangle f : mesh.getTriangles())
{
if (f.hasAttributes(AbstractHalfEdge.OUTER))
continue;
nodeset.addAll(Arrays.asList(f.vertex));
}
}
// Compute bounding box
double [] bbox = new double[6];
bbox[0] = bbox[1] = bbox[2] = Double.MAX_VALUE;
bbox[3] = bbox[4] = bbox[5] = - (Double.MAX_VALUE / 2.0);
for (Vertex v : nodeset)
{
double[] xyz = v.getUV();
for (int k = 2; k >= 0; k--)
{
if (xyz[k] < bbox[k])
bbox[k] = xyz[k];
if (xyz[k] > bbox[3+k])
bbox[3+k] = xyz[k];
}
}
LOGGER.fine("Bounding box: lower("+bbox[0]+", "+bbox[1]+", "+bbox[2]+"), upper("+bbox[3]+", "+bbox[4]+", "+bbox[5]+")");
kdTree = new KdTree<Vertex>(bbox);
for (Vertex v : nodeset)
kdTree.add(v);
for (Vertex v : nodeset)
{
if (null == v.getLink())
continue;
Triangle t = liaison.getBackgroundTriangle(v);
double d0 = v.sqrDistance3D(t.vertex[0]);
double d1 = v.sqrDistance3D(t.vertex[1]);
double d2 = v.sqrDistance3D(t.vertex[2]);
if (d0 <= d1 && d0 <= d2)
neighborBgMap.put(v, t.vertex[0]);
else if (d1 <= d0 && d1 <= d2)
neighborBgMap.put(v, t.vertex[1]);
else
neighborBgMap.put(v, t.vertex[2]);
}
// Arbitrary size: 2*initial number of nodes
metrics = new HashMap<Vertex, EuclidianMetric3D>(2*nodeset.size());
if (dfrMetrics != null)
{
try {
for (Vertex v : nodeset)
metrics.put(v, new EuclidianMetric3D(dfrMetrics.get(v.getLabel() - 1)));
} catch (IOException ex) {
LOGGER.log(Level.SEVERE, null, ex);
throw new RuntimeException("Error when loading metrics map file");
}
}
else if (targetSize > 0.0)
{
// If targetSize is 0.0, metrics will be set by calling setAnalyticMetric()
// below.
for (Vertex v : nodeset)
metrics.put(v, new EuclidianMetric3D(targetSize));
}
}
public void setAnalyticMetric(AnalyticMetricInterface m)
{
analyticMetric = m;
}
public void setAnalyticMetric(int groupId, AnalyticMetricInterface m)
{
metricsPartitionMap.put(groupId, m);
}
public final Mesh getOutputMesh()
{
return mesh;
}
// Can be extended by subclasses
protected void afterSplitHook()
{
}
// Can be extended by subclasses
protected void afterSwapHook()
{
}
// Can be extended by subclasses
protected void afterIterationHook()
{
}
private static boolean isInside(double[] pos, Triangle t)
{
double [][] temp = new double[4][3];
double[] p0 = t.vertex[0].getUV();
double[] p1 = t.vertex[1].getUV();
double[] p2 = t.vertex[2].getUV();
Matrix3D.computeNormal3D(p0, p1, p2, temp[0], temp[1], temp[2]);
Matrix3D.computeNormal3D(p0, p1, pos, temp[0], temp[1], temp[3]);
if (Matrix3D.prodSca(temp[2], temp[3]) < 0.0)
return false;
Matrix3D.computeNormal3D(p1, p2, pos, temp[0], temp[1], temp[3]);
if (Matrix3D.prodSca(temp[2], temp[3]) < 0.0)
return false;
Matrix3D.computeNormal3D(p2, p0, pos, temp[0], temp[1], temp[3]);
return Matrix3D.prodSca(temp[2], temp[3]) >= 0.0;
}
private static double interpolatedDistance(Vertex pt1, Metric m1, Vertex pt2, Metric m2)
{
assert m1 != null : "Metric null at point "+pt1;
assert m2 != null : "Metric null at point "+pt2;
double[] p1 = pt1.getUV();
double[] p2 = pt2.getUV();
double a = Math.sqrt(m1.distance2(p1, p2));
double b = Math.sqrt(m2.distance2(p1, p2));
// Linear interpolation:
//double l = (2.0/3.0) * (a*a + a*b + b*b) / (a + b);
// Geometric interpolation
double l = Math.abs(a-b) < 1.e-6*(a+b) ? 0.5*(a+b) : (a - b)/Math.log(a/b);
return l;
}
private Map<Triangle, Collection<Vertex>> collectVertices(AbstractHalfEdge ot)
{
Map <Triangle, Collection<Vertex>> verticesToDispatch = new HashMap<Triangle, Collection<Vertex>>();
if (ot.hasAttributes(AbstractHalfEdge.NONMANIFOLD))
{
for (Iterator<AbstractHalfEdge> itf = ot.fanIterator(); itf.hasNext(); )
{
Triangle t = itf.next().getTri();
assert !t.hasAttributes(AbstractHalfEdge.OUTER);
Collection<Vertex> prev = mapTriangleVertices.remove(t);
if (prev != null)
{
verticesToDispatch.put(t, new ArrayList<Vertex>(prev));
prev.clear();
}
}
}
else
{
Triangle t = ot.getTri();
Collection<Vertex> prev = mapTriangleVertices.remove(t);
if (prev != null)
{
verticesToDispatch.put(t, new ArrayList<Vertex>(prev));
prev.clear();
}
if (!ot.hasAttributes(AbstractHalfEdge.BOUNDARY))
{
ot = ot.sym();
t = ot.getTri();
prev = mapTriangleVertices.remove(t);
ot = ot.sym();
if (prev != null)
{
verticesToDispatch.put(t, new ArrayList<Vertex>(prev));
prev.clear();
}
}
}
return verticesToDispatch;
}
private void dispatchVertices(Vertex newVertex, Map<Triangle, Collection<Vertex>> verticesToDispatch)
{
for (Map.Entry<Triangle, Collection<Vertex>> entry : verticesToDispatch.entrySet())
{
Triangle t = entry.getKey();
for (Vertex v : entry.getValue())
{
surroundingTriangle.remove(v);
if (v == newVertex)
{
// There is no need to insert this vertex
continue;
}
Triangle vT = MeshLiaison.findSurroundingInAdjacentTriangles(v, t);
surroundingTriangle.put(v, vT);
Collection<Vertex> c = mapTriangleVertices.get(vT);
if (c == null)
{
c = new ArrayList<Vertex>();
mapTriangleVertices.put(vT, c);
}
c.add(v);
}
}
}
public final Remesh compute()
{
LOGGER.info("Run "+getClass().getName());
mesh.getTrace().println("# Begin Remesh");
if (analyticMetric != null || !metricsPartitionMap.isEmpty())
{
for (Triangle t : mesh.getTriangles())
{
if (!t.isReadable())
continue;
AnalyticMetricInterface metric = metricsPartitionMap.get(t.getGroupId());
if (metric == null)
metric = analyticMetric;
if (metric.equals(LATER_BINDING))
throw new RuntimeException("Cannot determine metrics, either set 'size' or 'metricsMap' arguments, or call Remesh.setAnalyticMetric()");
for (Vertex v : t.vertex)
{
double[] pos = v.getUV();
EuclidianMetric3D curMetric = metrics.get(v);
EuclidianMetric3D newMetric = new EuclidianMetric3D(metric.getTargetSize(pos[0], pos[1], pos[2]));
if (curMetric == null || curMetric.getUnitBallBBox()[0] > newMetric.getUnitBallBBox()[0])
metrics.put(v, newMetric);
}
}
}
ArrayList<Vertex> nodes = new ArrayList<Vertex>();
ArrayList<Vertex> triNodes = new ArrayList<Vertex>();
ArrayList<EuclidianMetric3D> triMetrics = new ArrayList<EuclidianMetric3D>();
Map<Vertex, Vertex> neighborMap = new HashMap<Vertex, Vertex>();
int nrIter = 0;
int processed = 0;
// Number of nodes which were skipped
int skippedNodes = 0;
AbstractHalfEdge h = null;
AbstractHalfEdge sym = null;
double[][] temp = new double[4][3];
// We try to insert new nodes by splitting large edges. As edge collapse
// is costful, nodes are inserted only if it does not create small edges,
// which means that nodes are not deleted.
// We iterate over all edges, and put candidate nodes into triNodes.
// If an edge has no candidates, either because it is small or because no
// nodes can be inserted, it is tagged and will not have to be checked
// during next iterations.
// Clear MARKED attribute
for (Triangle f : mesh.getTriangles())
f.clearAttributes(AbstractHalfEdge.MARKED);
// Tag IMMUTABLE edges
mesh.tagIf(AbstractHalfEdge.IMMUTABLE, AbstractHalfEdge.MARKED);
boolean reversed = true;
while (true)
{
nrIter++;
reversed = !reversed;
// Maximal number of nodes which are inserted on an edge
int maxNodes = 0;
// Number of checked edges
int checked = 0;
// Number of nodes which are too near from existing vertices
int tooNearNodes = 0;
nodes.clear();
surroundingTriangle.clear();
mapTriangleVertices.clear();
neighborMap.clear();
skippedNodes = 0;
LOGGER.fine("Check all edges");
for(Triangle t : mesh.getTriangles())
{
if (t.hasAttributes(AbstractHalfEdge.OUTER))
continue;
h = t.getAbstractHalfEdge(h);
sym = t.getAbstractHalfEdge(sym);
triNodes.clear();
triMetrics.clear();
Collection<Vertex> newVertices = mapTriangleVertices.get(t);
if (newVertices == null)
newVertices = new ArrayList<Vertex>();
// Maximal number of nodes which are inserted on edges of this triangle
int nrTriNodes = 0;
for (int i = 0; i < 3; i++)
{
h = h.next();
if (h.hasAttributes(AbstractHalfEdge.MARKED))
{
// This edge has already been checked and cannot be split
continue;
}
// Tag symmetric edge to process edges only once
if (!h.hasAttributes(AbstractHalfEdge.NONMANIFOLD))
{
sym = h.sym(sym);
sym.setAttributes(AbstractHalfEdge.MARKED);
}
else
{
for (Iterator<AbstractHalfEdge> it = h.fanIterator(); it.hasNext(); )
{
AbstractHalfEdge f = it.next();
f.setAttributes(AbstractHalfEdge.MARKED);
f.sym().setAttributes(AbstractHalfEdge.MARKED);
}
}
Vertex start = h.origin();
Vertex end = h.destination();
EuclidianMetric3D mS = metrics.get(start);
EuclidianMetric3D mE = metrics.get(end);
double l = interpolatedDistance(start, mS, end, mE);
if (l < maxlen)
{
// This edge is smaller than target size and is not split
h.setAttributes(AbstractHalfEdge.MARKED);
continue;
}
int nrNodes = addCandidatePoints(h, l, reversed, triNodes, triMetrics, neighborMap);
if (nrNodes > nrTriNodes)
{
nrTriNodes = nrNodes;
}
checked++;
}
if (nrTriNodes > maxNodes)
maxNodes = nrTriNodes;
if (!triNodes.isEmpty())
{
// Process in pseudo-random order
int prime = PrimeFinder.nextPrime(nrTriNodes);
int imax = triNodes.size();
while (imax % prime == 0)
prime = PrimeFinder.nextPrime(prime+1);
if (prime >= imax)
prime = 1;
int index = imax / 2;
for (int i = 0; i < imax; i++)
{
Vertex v = triNodes.get(index);
EuclidianMetric3D metric = triMetrics.get(index);
assert metric != null;
double localSize = 0.5 * metric.getUnitBallBBox()[0];
double localSize2 = localSize * localSize;
Vertex bgNear = neighborBgMap.get(neighborMap.get(v));
Triangle bgT = liaison.findSurroundingTriangle(v, bgNear, localSize2, true).getTri();
liaison.addVertex(v, bgT);
liaison.move(v, v.getUV());
double[] uv = v.getUV();
Vertex n = kdTree.getNearestVertex(metric, uv);
if (allowNearNodes || interpolatedDistance(v, metric, n, metrics.get(n)) > minlen)
{
kdTree.add(v);
metrics.put(v, metric);
nodes.add(v);
newVertices.add(v);
surroundingTriangle.put(v, t);
double d0 = v.sqrDistance3D(bgT.vertex[0]);
double d1 = v.sqrDistance3D(bgT.vertex[1]);
double d2 = v.sqrDistance3D(bgT.vertex[2]);
if (d0 <= d1 && d0 <= d2)
neighborBgMap.put(v, bgT.vertex[0]);
else if (d1 <= d0 && d1 <= d2)
neighborBgMap.put(v, bgT.vertex[1]);
else
neighborBgMap.put(v, bgT.vertex[2]);
}
else
{
tooNearNodes++;
liaison.removeVertex(v);
}
index += prime;
if (index >= imax)
index -= imax;
}
if (!newVertices.isEmpty())
mapTriangleVertices.put(t, newVertices);
}
}
if (nodes.isEmpty())
break;
for (Vertex v : nodes)
{
// These vertices are not bound to any triangles, so
// they must be removed, otherwise getSurroundingOTriangle
// may return a null pointer.
kdTree.remove(v);
}
LOGGER.fine("Try to insert "+nodes.size()+" nodes");
// Process in pseudo-random order. There are at most maxNodes nodes
// on an edge, we choose an increment step greater than this value
// to try to split all edges.
int prime = PrimeFinder.nextPrime(maxNodes);
int imax = nodes.size();
while (imax % prime == 0)
prime = PrimeFinder.nextPrime(prime+1);
if (prime >= imax)
prime = 1;
int index = imax / 2 - prime;
int totNrSwap = 0;
for (int i = 0; i < imax; i++)
{
index += prime;
if (index >= imax)
index -= imax;
Vertex v = nodes.get(index);
Triangle start = surroundingTriangle.remove(v);
AbstractHalfEdge ot = MeshLiaison.findNearestEdge(v, start);
sym = ot.sym(sym);
if (ot.hasAttributes(AbstractHalfEdge.IMMUTABLE))
{
// Vertex is not inserted
skippedNodes++;
mapTriangleVertices.get(start).remove(v);
liaison.removeVertex(v);
neighborBgMap.remove(v);
continue;
}
if (!ot.hasAttributes(AbstractHalfEdge.BOUNDARY | AbstractHalfEdge.NONMANIFOLD))
{
// Check whether edge can be split
Vertex o = ot.origin();
Vertex d = ot.destination();
Vertex n = sym.apex();
double[] pos = v.getUV();
Matrix3D.computeNormal3D(o.getUV(), n.getUV(), pos, temp[0], temp[1], temp[2]);
Matrix3D.computeNormal3D(n.getUV(), d.getUV(), pos, temp[0], temp[1], temp[3]);
if (Matrix3D.prodSca(temp[2], temp[3]) <= 0.0)
{
// Vertex is not inserted
skippedNodes++;
mapTriangleVertices.get(start).remove(v);
liaison.removeVertex(v);
neighborBgMap.remove(v);
continue;
}
}
else
{
// Split boundary edge. Project the vertex onto this edge
double [] xo = ot.origin().getUV();
double [] xd = ot.destination().getUV();
double xNorm2 =
(xd[0] - xo[0]) * (xd[0] - xo[0]) +
(xd[1] - xo[1]) * (xd[1] - xo[1]) +
(xd[2] - xo[2]) * (xd[2] - xo[2]);
if (xNorm2 > 0)
{
double[] pos = v.getUV();
double xScal = (1.0 / xNorm2) * (
(xd[0] - xo[0]) * (pos[0] - xo[0]) +
(xd[1] - xo[1]) * (pos[1] - xo[1]) +
(xd[2] - xo[2]) * (pos[2] - xo[2])
);
if (xScal < 0.01 || xScal > 0.99)
{
// Vertex is not inserted
skippedNodes++;
mapTriangleVertices.get(start).remove(v);
liaison.removeVertex(v);
neighborBgMap.remove(v);
continue;
}
v.moveTo(
xo[0] + xScal * (xd[0] - xo[0]),
xo[1] + xScal * (xd[1] - xo[1]),
xo[2] + xScal * (xd[2] - xo[2]));
mesh.getTrace().moveVertex(v);
}
else
{
// Vertex is not inserted
skippedNodes++;
mapTriangleVertices.get(start).remove(v);
liaison.removeVertex(v);
neighborBgMap.remove(v);
continue;
}
}
Map<Triangle, Collection<Vertex>> verticesToDispatch = collectVertices(ot);
ot = mesh.vertexSplit(ot, v);
assert ot.destination() == v : v+" "+ot;
dispatchVertices(v, verticesToDispatch);
kdTree.add(v);
processed++;
afterSplitHook();
// Swap edges
HalfEdge edge = (HalfEdge) ot;
edge = edge.prev();
Vertex s = edge.origin();
boolean advance = true;
+ double [] tNormal = liaison.getBackgroundNormal(v);
do
{
advance = true;
- if (edge.checkSwap3D(mesh, coplanarity) >= 0.0)
+ double checkNormal = edge.checkSwapNormal(mesh, coplanarity, tNormal);
+ if (checkNormal < -1.0)
+ {
+ edge = edge.nextApexLoop();
+ continue;
+ }
+ if (edge.checkSwap3D(mesh, -2.0) > 0.0)
{
edge.getTri().clearAttributes(AbstractHalfEdge.MARKED);
edge.sym().getTri().clearAttributes(AbstractHalfEdge.MARKED);
Map<Triangle, Collection<Vertex>> vTri = collectVertices(edge);
edge = (HalfEdge) mesh.edgeSwap(edge);
dispatchVertices(null, vTri);
totNrSwap++;
advance = false;
}
else
edge = edge.nextApexLoop();
}
while (!advance || edge.origin() != s);
afterSwapHook();
if (processed > 0 && (processed % progressBarStatus) == 0)
LOGGER.info("Vertices inserted: "+processed);
}
afterIterationHook();
assert mesh.isValid();
if (hasRidges)
{
assert mesh.checkNoInvertedTriangles();
}
assert mesh.checkNoDegeneratedTriangles();
assert surroundingTriangle.isEmpty() : "surroundingTriangle still contains "+surroundingTriangle.size()+" vertices";
if (LOGGER.isLoggable(Level.FINE))
{
LOGGER.fine("Mesh now contains "+mesh.getTriangles().size()+" triangles");
if (checked > 0)
LOGGER.fine(checked+" edges checked");
if (imax > 0)
LOGGER.fine(imax+" nodes added");
if (tooNearNodes > 0)
LOGGER.fine(tooNearNodes+" nodes are too near from existing vertices and cannot be inserted");
if (skippedNodes > 0)
LOGGER.fine(skippedNodes+" nodes are skipped");
if (totNrSwap > 0)
LOGGER.fine(totNrSwap+" edges have been swapped during processing");
}
if (nodes.size() == skippedNodes)
break;
}
LOGGER.info("Number of inserted vertices: "+processed);
LOGGER.fine("Number of iterations to insert all nodes: "+nrIter);
if (nrFailedInterpolations > 0)
LOGGER.info("Number of failed interpolations: "+nrFailedInterpolations);
LOGGER.config("Leave compute()");
mesh.getTrace().println("# End Remesh");
return this;
}
private int addCandidatePoints(AbstractHalfEdge ot, double edgeLength, boolean reversed,
ArrayList<Vertex> triNodes, ArrayList<EuclidianMetric3D> triMetrics,
Map<Vertex, Vertex> neighborMap)
{
int nrNodes = 0;
Vertex start = ot.origin();
Vertex end = ot.destination();
EuclidianMetric3D mS = metrics.get(start);
EuclidianMetric3D mE = metrics.get(end);
// Ensure that start point has the lowest edge size
double [] xs = start.getUV();
double [] xe = end.getUV();
if (reversed || mS.distance2(xs, xe) < mE.distance2(xs, xe))
{
Vertex tempV = start;
start = end;
end = tempV;
xs = xe;
xe = end.getUV();
EuclidianMetric3D tempM = mS;
mS = mE;
mE = tempM;
}
double hS = mS.getUnitBallBBox()[0];
double hE = mE.getUnitBallBBox()[0];
double logRatio = Math.log(hE/hS);
double [] lower = new double[3];
double [] upper = new double[3];
boolean border = ot.hasAttributes(AbstractHalfEdge.BOUNDARY | AbstractHalfEdge.NONMANIFOLD);
int borderGroup = ot.getTri().getGroupId();
int nr;
double maxError, target;
if (edgeLength < ONE_PLUS_SQRT2)
{
// Add middle point; otherwise point would be too near from end point
nr = 1;
target = 0.5*edgeLength;
maxError = Math.min(0.02, 0.9*Math.abs(target - 0.5*Math.sqrt(2)));
}
else if (edgeLength > 3.0)
{
// Long edges are discretized, but do not create more than 4 subsegments
nr = 3;
target = edgeLength / (nr + 1);
maxError = 0.1;
}
else
{
nr = (int) edgeLength;
target = 1.0;
maxError = 0.05;
}
// One could take nrDichotomy = 1-log(maxError)/log(2), but this
// value may not work when surface parameters have a large
// gradient, so take a larger value to be safe.
int nrDichotomy = 20;
int r = nr;
Vertex last = start;
Metric lastMetric = metrics.get(last);
while (r > 0)
{
System.arraycopy(last.getUV(), 0, lower, 0, 3);
System.arraycopy(end.getUV(), 0, upper, 0, 3);
// 1-d coordinate between lower and upper points
double alpha = 0.5;
double delta = 0.5;
Vertex np = mesh.createVertex(
0.5*(lower[0]+upper[0]),
0.5*(lower[1]+upper[1]),
0.5*(lower[2]+upper[2]));
int cnt = nrDichotomy;
while(cnt >= 0)
{
cnt--;
nrInterpolations++;
// Update vertex position if 'project' flag was set
double [] pos = np.getUV();
if (project && !ot.hasAttributes(AbstractHalfEdge.SHARP | AbstractHalfEdge.BOUNDARY | AbstractHalfEdge.NONMANIFOLD))
{
liaison.project(np, pos, start);
}
// Compute metrics at this position
EuclidianMetric3D m;
AnalyticMetricInterface metric = metricsPartitionMap.get(ot.getTri().getGroupId());
if (metric == null)
metric = analyticMetric;
if (metric != null)
m = new EuclidianMetric3D(metric.getTargetSize(pos[0], pos[1], pos[2]));
else
m = new EuclidianMetric3D(hS*Math.exp(alpha*logRatio));
double l = interpolatedDistance(last, lastMetric, np, m);
if (Math.abs(l - target) < maxError)
{
last = np;
lastMetric = m;
if (!border)
{
// Check that point is not near of a border
double localSize = 0.9 * minlen * m.getUnitBallBBox()[0];
double localSize2 = localSize * localSize;
if (liaison.isNearSkeleton(np, borderGroup, localSize2))
{
r--;
break;
}
}
triNodes.add(last);
triMetrics.add(m);
if (start.getRef() == 0 && end.getRef() != 0)
neighborMap.put(last, start);
else if (start.getRef() != 0 && end.getRef() == 0)
neighborMap.put(last, end);
else if (m.distance2(pos, start.getUV()) < m.distance2(pos, end.getUV()))
neighborMap.put(last, start);
else
neighborMap.put(last, end);
nrNodes++;
r--;
break;
}
else if (l > target)
{
delta *= 0.5;
alpha -= delta;
System.arraycopy(pos, 0, upper, 0, 3);
np.moveTo(
0.5*(lower[0] + pos[0]),
0.5*(lower[1] + pos[1]),
0.5*(lower[2] + pos[2]));
}
else
{
delta *= 0.5;
alpha += delta;
System.arraycopy(pos, 0, lower, 0, 3);
np.moveTo(
0.5*(upper[0] + pos[0]),
0.5*(upper[1] + pos[1]),
0.5*(upper[2] + pos[2]));
}
}
if (cnt < 0)
{
nrFailedInterpolations++;
return nrNodes;
}
}
return nrNodes;
}
protected void postProcessIteration(Mesh mesh, int i)
{
// Can be overridden
}
public void setProgressBarStatus(int n)
{
progressBarStatus = n;
}
private static void usage(int rc)
{
System.out.println("Usage: Remesh [options] xmlDir outDir");
System.out.println("Options:");
System.out.println(" -h, --help Display this message and exit");
System.exit(rc);
}
/**
*
* @param args [options] xmlDir outDir
*/
public static void main(String[] args) throws IOException
{
org.jcae.mesh.amibe.traits.MeshTraitsBuilder mtb = org.jcae.mesh.amibe.traits.MeshTraitsBuilder.getDefault3D();
mtb.addNodeList();
Mesh mesh = new Mesh(mtb);
Map<String, String> opts = new HashMap<String, String>();
int argc = 0;
for (String arg: args)
if (arg.equals("--help") || arg.equals("-h"))
usage(0);
if (argc + 3 != args.length)
usage(1);
opts.put("size", args[1]);
opts.put("coplanarity", "0.9");
if(false) {
String metricsFile = args[0]+File.separator+"metricsMap";
opts.put("metricsFile", metricsFile);
PrimitiveFileReaderFactory pfrf = new PrimitiveFileReaderFactory();
DoubleFileReader dfr = pfrf.getDoubleReader(new File(args[0]+File.separator+"jcae3d.files"+File.separator+"nodes3d.bin"));
long n = dfr.size();
java.io.DataOutputStream out = new java.io.DataOutputStream(new java.io.BufferedOutputStream(new java.io.FileOutputStream(metricsFile)));
for (long i = 0; i < n; i += 3)
{
double x = dfr.get();
double y = dfr.get();
double z = dfr.get();
double val = (x - 9000.0)*(x - 9000.0) / 2250.0;
if (val > 200.0)
val = 200.0;
out.writeDouble(val);
}
out.close();
}
System.out.println("Running "+args[0]+" "+args[1]+" "+args[2]);
try
{
MeshReader.readObject3D(mesh, args[0]);
}
catch (IOException ex)
{
ex.printStackTrace();
throw new RuntimeException(ex);
}
Remesh smoother = new Remesh(mesh, opts);
smoother.compute();
try
{
MeshWriter.writeObject3D(smoother.getOutputMesh(), args[2], null);
}
catch (IOException ex)
{
ex.printStackTrace();
throw new RuntimeException(ex);
}
}
}
| false | true | public final Remesh compute()
{
LOGGER.info("Run "+getClass().getName());
mesh.getTrace().println("# Begin Remesh");
if (analyticMetric != null || !metricsPartitionMap.isEmpty())
{
for (Triangle t : mesh.getTriangles())
{
if (!t.isReadable())
continue;
AnalyticMetricInterface metric = metricsPartitionMap.get(t.getGroupId());
if (metric == null)
metric = analyticMetric;
if (metric.equals(LATER_BINDING))
throw new RuntimeException("Cannot determine metrics, either set 'size' or 'metricsMap' arguments, or call Remesh.setAnalyticMetric()");
for (Vertex v : t.vertex)
{
double[] pos = v.getUV();
EuclidianMetric3D curMetric = metrics.get(v);
EuclidianMetric3D newMetric = new EuclidianMetric3D(metric.getTargetSize(pos[0], pos[1], pos[2]));
if (curMetric == null || curMetric.getUnitBallBBox()[0] > newMetric.getUnitBallBBox()[0])
metrics.put(v, newMetric);
}
}
}
ArrayList<Vertex> nodes = new ArrayList<Vertex>();
ArrayList<Vertex> triNodes = new ArrayList<Vertex>();
ArrayList<EuclidianMetric3D> triMetrics = new ArrayList<EuclidianMetric3D>();
Map<Vertex, Vertex> neighborMap = new HashMap<Vertex, Vertex>();
int nrIter = 0;
int processed = 0;
// Number of nodes which were skipped
int skippedNodes = 0;
AbstractHalfEdge h = null;
AbstractHalfEdge sym = null;
double[][] temp = new double[4][3];
// We try to insert new nodes by splitting large edges. As edge collapse
// is costful, nodes are inserted only if it does not create small edges,
// which means that nodes are not deleted.
// We iterate over all edges, and put candidate nodes into triNodes.
// If an edge has no candidates, either because it is small or because no
// nodes can be inserted, it is tagged and will not have to be checked
// during next iterations.
// Clear MARKED attribute
for (Triangle f : mesh.getTriangles())
f.clearAttributes(AbstractHalfEdge.MARKED);
// Tag IMMUTABLE edges
mesh.tagIf(AbstractHalfEdge.IMMUTABLE, AbstractHalfEdge.MARKED);
boolean reversed = true;
while (true)
{
nrIter++;
reversed = !reversed;
// Maximal number of nodes which are inserted on an edge
int maxNodes = 0;
// Number of checked edges
int checked = 0;
// Number of nodes which are too near from existing vertices
int tooNearNodes = 0;
nodes.clear();
surroundingTriangle.clear();
mapTriangleVertices.clear();
neighborMap.clear();
skippedNodes = 0;
LOGGER.fine("Check all edges");
for(Triangle t : mesh.getTriangles())
{
if (t.hasAttributes(AbstractHalfEdge.OUTER))
continue;
h = t.getAbstractHalfEdge(h);
sym = t.getAbstractHalfEdge(sym);
triNodes.clear();
triMetrics.clear();
Collection<Vertex> newVertices = mapTriangleVertices.get(t);
if (newVertices == null)
newVertices = new ArrayList<Vertex>();
// Maximal number of nodes which are inserted on edges of this triangle
int nrTriNodes = 0;
for (int i = 0; i < 3; i++)
{
h = h.next();
if (h.hasAttributes(AbstractHalfEdge.MARKED))
{
// This edge has already been checked and cannot be split
continue;
}
// Tag symmetric edge to process edges only once
if (!h.hasAttributes(AbstractHalfEdge.NONMANIFOLD))
{
sym = h.sym(sym);
sym.setAttributes(AbstractHalfEdge.MARKED);
}
else
{
for (Iterator<AbstractHalfEdge> it = h.fanIterator(); it.hasNext(); )
{
AbstractHalfEdge f = it.next();
f.setAttributes(AbstractHalfEdge.MARKED);
f.sym().setAttributes(AbstractHalfEdge.MARKED);
}
}
Vertex start = h.origin();
Vertex end = h.destination();
EuclidianMetric3D mS = metrics.get(start);
EuclidianMetric3D mE = metrics.get(end);
double l = interpolatedDistance(start, mS, end, mE);
if (l < maxlen)
{
// This edge is smaller than target size and is not split
h.setAttributes(AbstractHalfEdge.MARKED);
continue;
}
int nrNodes = addCandidatePoints(h, l, reversed, triNodes, triMetrics, neighborMap);
if (nrNodes > nrTriNodes)
{
nrTriNodes = nrNodes;
}
checked++;
}
if (nrTriNodes > maxNodes)
maxNodes = nrTriNodes;
if (!triNodes.isEmpty())
{
// Process in pseudo-random order
int prime = PrimeFinder.nextPrime(nrTriNodes);
int imax = triNodes.size();
while (imax % prime == 0)
prime = PrimeFinder.nextPrime(prime+1);
if (prime >= imax)
prime = 1;
int index = imax / 2;
for (int i = 0; i < imax; i++)
{
Vertex v = triNodes.get(index);
EuclidianMetric3D metric = triMetrics.get(index);
assert metric != null;
double localSize = 0.5 * metric.getUnitBallBBox()[0];
double localSize2 = localSize * localSize;
Vertex bgNear = neighborBgMap.get(neighborMap.get(v));
Triangle bgT = liaison.findSurroundingTriangle(v, bgNear, localSize2, true).getTri();
liaison.addVertex(v, bgT);
liaison.move(v, v.getUV());
double[] uv = v.getUV();
Vertex n = kdTree.getNearestVertex(metric, uv);
if (allowNearNodes || interpolatedDistance(v, metric, n, metrics.get(n)) > minlen)
{
kdTree.add(v);
metrics.put(v, metric);
nodes.add(v);
newVertices.add(v);
surroundingTriangle.put(v, t);
double d0 = v.sqrDistance3D(bgT.vertex[0]);
double d1 = v.sqrDistance3D(bgT.vertex[1]);
double d2 = v.sqrDistance3D(bgT.vertex[2]);
if (d0 <= d1 && d0 <= d2)
neighborBgMap.put(v, bgT.vertex[0]);
else if (d1 <= d0 && d1 <= d2)
neighborBgMap.put(v, bgT.vertex[1]);
else
neighborBgMap.put(v, bgT.vertex[2]);
}
else
{
tooNearNodes++;
liaison.removeVertex(v);
}
index += prime;
if (index >= imax)
index -= imax;
}
if (!newVertices.isEmpty())
mapTriangleVertices.put(t, newVertices);
}
}
if (nodes.isEmpty())
break;
for (Vertex v : nodes)
{
// These vertices are not bound to any triangles, so
// they must be removed, otherwise getSurroundingOTriangle
// may return a null pointer.
kdTree.remove(v);
}
LOGGER.fine("Try to insert "+nodes.size()+" nodes");
// Process in pseudo-random order. There are at most maxNodes nodes
// on an edge, we choose an increment step greater than this value
// to try to split all edges.
int prime = PrimeFinder.nextPrime(maxNodes);
int imax = nodes.size();
while (imax % prime == 0)
prime = PrimeFinder.nextPrime(prime+1);
if (prime >= imax)
prime = 1;
int index = imax / 2 - prime;
int totNrSwap = 0;
for (int i = 0; i < imax; i++)
{
index += prime;
if (index >= imax)
index -= imax;
Vertex v = nodes.get(index);
Triangle start = surroundingTriangle.remove(v);
AbstractHalfEdge ot = MeshLiaison.findNearestEdge(v, start);
sym = ot.sym(sym);
if (ot.hasAttributes(AbstractHalfEdge.IMMUTABLE))
{
// Vertex is not inserted
skippedNodes++;
mapTriangleVertices.get(start).remove(v);
liaison.removeVertex(v);
neighborBgMap.remove(v);
continue;
}
if (!ot.hasAttributes(AbstractHalfEdge.BOUNDARY | AbstractHalfEdge.NONMANIFOLD))
{
// Check whether edge can be split
Vertex o = ot.origin();
Vertex d = ot.destination();
Vertex n = sym.apex();
double[] pos = v.getUV();
Matrix3D.computeNormal3D(o.getUV(), n.getUV(), pos, temp[0], temp[1], temp[2]);
Matrix3D.computeNormal3D(n.getUV(), d.getUV(), pos, temp[0], temp[1], temp[3]);
if (Matrix3D.prodSca(temp[2], temp[3]) <= 0.0)
{
// Vertex is not inserted
skippedNodes++;
mapTriangleVertices.get(start).remove(v);
liaison.removeVertex(v);
neighborBgMap.remove(v);
continue;
}
}
else
{
// Split boundary edge. Project the vertex onto this edge
double [] xo = ot.origin().getUV();
double [] xd = ot.destination().getUV();
double xNorm2 =
(xd[0] - xo[0]) * (xd[0] - xo[0]) +
(xd[1] - xo[1]) * (xd[1] - xo[1]) +
(xd[2] - xo[2]) * (xd[2] - xo[2]);
if (xNorm2 > 0)
{
double[] pos = v.getUV();
double xScal = (1.0 / xNorm2) * (
(xd[0] - xo[0]) * (pos[0] - xo[0]) +
(xd[1] - xo[1]) * (pos[1] - xo[1]) +
(xd[2] - xo[2]) * (pos[2] - xo[2])
);
if (xScal < 0.01 || xScal > 0.99)
{
// Vertex is not inserted
skippedNodes++;
mapTriangleVertices.get(start).remove(v);
liaison.removeVertex(v);
neighborBgMap.remove(v);
continue;
}
v.moveTo(
xo[0] + xScal * (xd[0] - xo[0]),
xo[1] + xScal * (xd[1] - xo[1]),
xo[2] + xScal * (xd[2] - xo[2]));
mesh.getTrace().moveVertex(v);
}
else
{
// Vertex is not inserted
skippedNodes++;
mapTriangleVertices.get(start).remove(v);
liaison.removeVertex(v);
neighborBgMap.remove(v);
continue;
}
}
Map<Triangle, Collection<Vertex>> verticesToDispatch = collectVertices(ot);
ot = mesh.vertexSplit(ot, v);
assert ot.destination() == v : v+" "+ot;
dispatchVertices(v, verticesToDispatch);
kdTree.add(v);
processed++;
afterSplitHook();
// Swap edges
HalfEdge edge = (HalfEdge) ot;
edge = edge.prev();
Vertex s = edge.origin();
boolean advance = true;
do
{
advance = true;
if (edge.checkSwap3D(mesh, coplanarity) >= 0.0)
{
edge.getTri().clearAttributes(AbstractHalfEdge.MARKED);
edge.sym().getTri().clearAttributes(AbstractHalfEdge.MARKED);
Map<Triangle, Collection<Vertex>> vTri = collectVertices(edge);
edge = (HalfEdge) mesh.edgeSwap(edge);
dispatchVertices(null, vTri);
totNrSwap++;
advance = false;
}
else
edge = edge.nextApexLoop();
}
while (!advance || edge.origin() != s);
afterSwapHook();
if (processed > 0 && (processed % progressBarStatus) == 0)
LOGGER.info("Vertices inserted: "+processed);
}
afterIterationHook();
assert mesh.isValid();
if (hasRidges)
{
assert mesh.checkNoInvertedTriangles();
}
assert mesh.checkNoDegeneratedTriangles();
assert surroundingTriangle.isEmpty() : "surroundingTriangle still contains "+surroundingTriangle.size()+" vertices";
if (LOGGER.isLoggable(Level.FINE))
{
LOGGER.fine("Mesh now contains "+mesh.getTriangles().size()+" triangles");
if (checked > 0)
LOGGER.fine(checked+" edges checked");
if (imax > 0)
LOGGER.fine(imax+" nodes added");
if (tooNearNodes > 0)
LOGGER.fine(tooNearNodes+" nodes are too near from existing vertices and cannot be inserted");
if (skippedNodes > 0)
LOGGER.fine(skippedNodes+" nodes are skipped");
if (totNrSwap > 0)
LOGGER.fine(totNrSwap+" edges have been swapped during processing");
}
if (nodes.size() == skippedNodes)
break;
}
LOGGER.info("Number of inserted vertices: "+processed);
LOGGER.fine("Number of iterations to insert all nodes: "+nrIter);
if (nrFailedInterpolations > 0)
LOGGER.info("Number of failed interpolations: "+nrFailedInterpolations);
LOGGER.config("Leave compute()");
mesh.getTrace().println("# End Remesh");
return this;
}
| public final Remesh compute()
{
LOGGER.info("Run "+getClass().getName());
mesh.getTrace().println("# Begin Remesh");
if (analyticMetric != null || !metricsPartitionMap.isEmpty())
{
for (Triangle t : mesh.getTriangles())
{
if (!t.isReadable())
continue;
AnalyticMetricInterface metric = metricsPartitionMap.get(t.getGroupId());
if (metric == null)
metric = analyticMetric;
if (metric.equals(LATER_BINDING))
throw new RuntimeException("Cannot determine metrics, either set 'size' or 'metricsMap' arguments, or call Remesh.setAnalyticMetric()");
for (Vertex v : t.vertex)
{
double[] pos = v.getUV();
EuclidianMetric3D curMetric = metrics.get(v);
EuclidianMetric3D newMetric = new EuclidianMetric3D(metric.getTargetSize(pos[0], pos[1], pos[2]));
if (curMetric == null || curMetric.getUnitBallBBox()[0] > newMetric.getUnitBallBBox()[0])
metrics.put(v, newMetric);
}
}
}
ArrayList<Vertex> nodes = new ArrayList<Vertex>();
ArrayList<Vertex> triNodes = new ArrayList<Vertex>();
ArrayList<EuclidianMetric3D> triMetrics = new ArrayList<EuclidianMetric3D>();
Map<Vertex, Vertex> neighborMap = new HashMap<Vertex, Vertex>();
int nrIter = 0;
int processed = 0;
// Number of nodes which were skipped
int skippedNodes = 0;
AbstractHalfEdge h = null;
AbstractHalfEdge sym = null;
double[][] temp = new double[4][3];
// We try to insert new nodes by splitting large edges. As edge collapse
// is costful, nodes are inserted only if it does not create small edges,
// which means that nodes are not deleted.
// We iterate over all edges, and put candidate nodes into triNodes.
// If an edge has no candidates, either because it is small or because no
// nodes can be inserted, it is tagged and will not have to be checked
// during next iterations.
// Clear MARKED attribute
for (Triangle f : mesh.getTriangles())
f.clearAttributes(AbstractHalfEdge.MARKED);
// Tag IMMUTABLE edges
mesh.tagIf(AbstractHalfEdge.IMMUTABLE, AbstractHalfEdge.MARKED);
boolean reversed = true;
while (true)
{
nrIter++;
reversed = !reversed;
// Maximal number of nodes which are inserted on an edge
int maxNodes = 0;
// Number of checked edges
int checked = 0;
// Number of nodes which are too near from existing vertices
int tooNearNodes = 0;
nodes.clear();
surroundingTriangle.clear();
mapTriangleVertices.clear();
neighborMap.clear();
skippedNodes = 0;
LOGGER.fine("Check all edges");
for(Triangle t : mesh.getTriangles())
{
if (t.hasAttributes(AbstractHalfEdge.OUTER))
continue;
h = t.getAbstractHalfEdge(h);
sym = t.getAbstractHalfEdge(sym);
triNodes.clear();
triMetrics.clear();
Collection<Vertex> newVertices = mapTriangleVertices.get(t);
if (newVertices == null)
newVertices = new ArrayList<Vertex>();
// Maximal number of nodes which are inserted on edges of this triangle
int nrTriNodes = 0;
for (int i = 0; i < 3; i++)
{
h = h.next();
if (h.hasAttributes(AbstractHalfEdge.MARKED))
{
// This edge has already been checked and cannot be split
continue;
}
// Tag symmetric edge to process edges only once
if (!h.hasAttributes(AbstractHalfEdge.NONMANIFOLD))
{
sym = h.sym(sym);
sym.setAttributes(AbstractHalfEdge.MARKED);
}
else
{
for (Iterator<AbstractHalfEdge> it = h.fanIterator(); it.hasNext(); )
{
AbstractHalfEdge f = it.next();
f.setAttributes(AbstractHalfEdge.MARKED);
f.sym().setAttributes(AbstractHalfEdge.MARKED);
}
}
Vertex start = h.origin();
Vertex end = h.destination();
EuclidianMetric3D mS = metrics.get(start);
EuclidianMetric3D mE = metrics.get(end);
double l = interpolatedDistance(start, mS, end, mE);
if (l < maxlen)
{
// This edge is smaller than target size and is not split
h.setAttributes(AbstractHalfEdge.MARKED);
continue;
}
int nrNodes = addCandidatePoints(h, l, reversed, triNodes, triMetrics, neighborMap);
if (nrNodes > nrTriNodes)
{
nrTriNodes = nrNodes;
}
checked++;
}
if (nrTriNodes > maxNodes)
maxNodes = nrTriNodes;
if (!triNodes.isEmpty())
{
// Process in pseudo-random order
int prime = PrimeFinder.nextPrime(nrTriNodes);
int imax = triNodes.size();
while (imax % prime == 0)
prime = PrimeFinder.nextPrime(prime+1);
if (prime >= imax)
prime = 1;
int index = imax / 2;
for (int i = 0; i < imax; i++)
{
Vertex v = triNodes.get(index);
EuclidianMetric3D metric = triMetrics.get(index);
assert metric != null;
double localSize = 0.5 * metric.getUnitBallBBox()[0];
double localSize2 = localSize * localSize;
Vertex bgNear = neighborBgMap.get(neighborMap.get(v));
Triangle bgT = liaison.findSurroundingTriangle(v, bgNear, localSize2, true).getTri();
liaison.addVertex(v, bgT);
liaison.move(v, v.getUV());
double[] uv = v.getUV();
Vertex n = kdTree.getNearestVertex(metric, uv);
if (allowNearNodes || interpolatedDistance(v, metric, n, metrics.get(n)) > minlen)
{
kdTree.add(v);
metrics.put(v, metric);
nodes.add(v);
newVertices.add(v);
surroundingTriangle.put(v, t);
double d0 = v.sqrDistance3D(bgT.vertex[0]);
double d1 = v.sqrDistance3D(bgT.vertex[1]);
double d2 = v.sqrDistance3D(bgT.vertex[2]);
if (d0 <= d1 && d0 <= d2)
neighborBgMap.put(v, bgT.vertex[0]);
else if (d1 <= d0 && d1 <= d2)
neighborBgMap.put(v, bgT.vertex[1]);
else
neighborBgMap.put(v, bgT.vertex[2]);
}
else
{
tooNearNodes++;
liaison.removeVertex(v);
}
index += prime;
if (index >= imax)
index -= imax;
}
if (!newVertices.isEmpty())
mapTriangleVertices.put(t, newVertices);
}
}
if (nodes.isEmpty())
break;
for (Vertex v : nodes)
{
// These vertices are not bound to any triangles, so
// they must be removed, otherwise getSurroundingOTriangle
// may return a null pointer.
kdTree.remove(v);
}
LOGGER.fine("Try to insert "+nodes.size()+" nodes");
// Process in pseudo-random order. There are at most maxNodes nodes
// on an edge, we choose an increment step greater than this value
// to try to split all edges.
int prime = PrimeFinder.nextPrime(maxNodes);
int imax = nodes.size();
while (imax % prime == 0)
prime = PrimeFinder.nextPrime(prime+1);
if (prime >= imax)
prime = 1;
int index = imax / 2 - prime;
int totNrSwap = 0;
for (int i = 0; i < imax; i++)
{
index += prime;
if (index >= imax)
index -= imax;
Vertex v = nodes.get(index);
Triangle start = surroundingTriangle.remove(v);
AbstractHalfEdge ot = MeshLiaison.findNearestEdge(v, start);
sym = ot.sym(sym);
if (ot.hasAttributes(AbstractHalfEdge.IMMUTABLE))
{
// Vertex is not inserted
skippedNodes++;
mapTriangleVertices.get(start).remove(v);
liaison.removeVertex(v);
neighborBgMap.remove(v);
continue;
}
if (!ot.hasAttributes(AbstractHalfEdge.BOUNDARY | AbstractHalfEdge.NONMANIFOLD))
{
// Check whether edge can be split
Vertex o = ot.origin();
Vertex d = ot.destination();
Vertex n = sym.apex();
double[] pos = v.getUV();
Matrix3D.computeNormal3D(o.getUV(), n.getUV(), pos, temp[0], temp[1], temp[2]);
Matrix3D.computeNormal3D(n.getUV(), d.getUV(), pos, temp[0], temp[1], temp[3]);
if (Matrix3D.prodSca(temp[2], temp[3]) <= 0.0)
{
// Vertex is not inserted
skippedNodes++;
mapTriangleVertices.get(start).remove(v);
liaison.removeVertex(v);
neighborBgMap.remove(v);
continue;
}
}
else
{
// Split boundary edge. Project the vertex onto this edge
double [] xo = ot.origin().getUV();
double [] xd = ot.destination().getUV();
double xNorm2 =
(xd[0] - xo[0]) * (xd[0] - xo[0]) +
(xd[1] - xo[1]) * (xd[1] - xo[1]) +
(xd[2] - xo[2]) * (xd[2] - xo[2]);
if (xNorm2 > 0)
{
double[] pos = v.getUV();
double xScal = (1.0 / xNorm2) * (
(xd[0] - xo[0]) * (pos[0] - xo[0]) +
(xd[1] - xo[1]) * (pos[1] - xo[1]) +
(xd[2] - xo[2]) * (pos[2] - xo[2])
);
if (xScal < 0.01 || xScal > 0.99)
{
// Vertex is not inserted
skippedNodes++;
mapTriangleVertices.get(start).remove(v);
liaison.removeVertex(v);
neighborBgMap.remove(v);
continue;
}
v.moveTo(
xo[0] + xScal * (xd[0] - xo[0]),
xo[1] + xScal * (xd[1] - xo[1]),
xo[2] + xScal * (xd[2] - xo[2]));
mesh.getTrace().moveVertex(v);
}
else
{
// Vertex is not inserted
skippedNodes++;
mapTriangleVertices.get(start).remove(v);
liaison.removeVertex(v);
neighborBgMap.remove(v);
continue;
}
}
Map<Triangle, Collection<Vertex>> verticesToDispatch = collectVertices(ot);
ot = mesh.vertexSplit(ot, v);
assert ot.destination() == v : v+" "+ot;
dispatchVertices(v, verticesToDispatch);
kdTree.add(v);
processed++;
afterSplitHook();
// Swap edges
HalfEdge edge = (HalfEdge) ot;
edge = edge.prev();
Vertex s = edge.origin();
boolean advance = true;
double [] tNormal = liaison.getBackgroundNormal(v);
do
{
advance = true;
double checkNormal = edge.checkSwapNormal(mesh, coplanarity, tNormal);
if (checkNormal < -1.0)
{
edge = edge.nextApexLoop();
continue;
}
if (edge.checkSwap3D(mesh, -2.0) > 0.0)
{
edge.getTri().clearAttributes(AbstractHalfEdge.MARKED);
edge.sym().getTri().clearAttributes(AbstractHalfEdge.MARKED);
Map<Triangle, Collection<Vertex>> vTri = collectVertices(edge);
edge = (HalfEdge) mesh.edgeSwap(edge);
dispatchVertices(null, vTri);
totNrSwap++;
advance = false;
}
else
edge = edge.nextApexLoop();
}
while (!advance || edge.origin() != s);
afterSwapHook();
if (processed > 0 && (processed % progressBarStatus) == 0)
LOGGER.info("Vertices inserted: "+processed);
}
afterIterationHook();
assert mesh.isValid();
if (hasRidges)
{
assert mesh.checkNoInvertedTriangles();
}
assert mesh.checkNoDegeneratedTriangles();
assert surroundingTriangle.isEmpty() : "surroundingTriangle still contains "+surroundingTriangle.size()+" vertices";
if (LOGGER.isLoggable(Level.FINE))
{
LOGGER.fine("Mesh now contains "+mesh.getTriangles().size()+" triangles");
if (checked > 0)
LOGGER.fine(checked+" edges checked");
if (imax > 0)
LOGGER.fine(imax+" nodes added");
if (tooNearNodes > 0)
LOGGER.fine(tooNearNodes+" nodes are too near from existing vertices and cannot be inserted");
if (skippedNodes > 0)
LOGGER.fine(skippedNodes+" nodes are skipped");
if (totNrSwap > 0)
LOGGER.fine(totNrSwap+" edges have been swapped during processing");
}
if (nodes.size() == skippedNodes)
break;
}
LOGGER.info("Number of inserted vertices: "+processed);
LOGGER.fine("Number of iterations to insert all nodes: "+nrIter);
if (nrFailedInterpolations > 0)
LOGGER.info("Number of failed interpolations: "+nrFailedInterpolations);
LOGGER.config("Leave compute()");
mesh.getTrace().println("# End Remesh");
return this;
}
|
diff --git a/src/main/java/edu/cmu/lti/oaqa/openqa/hellobioqa/keyterm/GoogleSynonymEngine.java b/src/main/java/edu/cmu/lti/oaqa/openqa/hellobioqa/keyterm/GoogleSynonymEngine.java
index 648c6f1..7e0b1b6 100644
--- a/src/main/java/edu/cmu/lti/oaqa/openqa/hellobioqa/keyterm/GoogleSynonymEngine.java
+++ b/src/main/java/edu/cmu/lti/oaqa/openqa/hellobioqa/keyterm/GoogleSynonymEngine.java
@@ -1,125 +1,125 @@
package edu.cmu.lti.oaqa.openqa.hellobioqa.keyterm;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;
public class GoogleSynonymEngine {
private static List<String> stoplist;
public GoogleSynonymEngine() {
try {
loadStoplist();
} catch (IOException e) {
e.printStackTrace();
}
}
public List<String> getSynonyms(String term) {
List<String> synonyms = new ArrayList<String>();
//File file = new File("model/google1/" + term + ".txt");
//File file = new File("src/main/resources/model/google1/" + term + ".txt");
try {
URL url = new URL("file:src/main/resources/model/google1/" + term + ".txt");
Scanner scanner = new Scanner(url.openStream());
// Term frequency map
Map<String, Integer> tmap = new HashMap<String, Integer>();
// Document frequency map
Map<String, Integer> dmap = new HashMap<String, Integer>();
Map<String, Integer> tdmap = new HashMap<String, Integer>();
while (scanner.hasNextLine()) {
String[] tokens = scanner.nextLine().split(" ");
Set<String> unique = new HashSet<String>();
for (String token : tokens) {
token = token.toLowerCase();
if (!stoplist.contains(token)) {
if (tmap.containsKey(token)) {
tmap.put(token, tmap.get(token) + 1);
} else {
tmap.put(token, 1);
}
unique.add(token);
}
}
for (String token : unique) {
if (dmap.containsKey(token)) {
dmap.put(token, dmap.get(token) + 1);
} else {
dmap.put(token, 1);
}
}
}
// Calculate score of TF * DF
for (String token : tmap.keySet()) {
tdmap.put(token, tmap.get(token) * dmap.get(token));
}
// Sort terms according to their score of TF * DF
List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(
tdmap.entrySet());
Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Entry<String, Integer> e0, Entry<String, Integer> e1) {
return e1.getValue().compareTo(e0.getValue());
}
});
// Pick the top 6 terms
for (int i = 0; i < 6; i++) {
if (!list.get(i).getKey().equals(term.toLowerCase())
&& list.get(i).getValue() >= 4) {
System.out.println("[GOOGLE] " + list.get(i).getKey() + " : " + list.get(i).getValue());
synonyms.add(list.get(i).getKey());
}
}
} catch (IOException e) {
- e.printStackTrace();
+ System.err.println("[MISSING] Term : " + term);
return synonyms;
}
return synonyms;
}
/**
* Load the stop list from 'stoplist.txt'.
* @throws IOException
*/
public void loadStoplist() throws IOException {
stoplist = new ArrayList<String>();
// File file = new File("stoplist.txt");
//File file = new File("src/main/resources/stoplist.txt");
URL url = new URL("file:src/main/resources/stoplist.txt");
Scanner scanner = new Scanner(url.openStream());
while (scanner.hasNextLine()) {
stoplist.add(scanner.nextLine());
}
scanner.close();
}
public static void main(String[] argv) {
GoogleSynonymEngine engine = new GoogleSynonymEngine();
// engine.getSynonyms("BARD1%20gene");
engine.getSynonyms("NM23");
}
}
| true | true | public List<String> getSynonyms(String term) {
List<String> synonyms = new ArrayList<String>();
//File file = new File("model/google1/" + term + ".txt");
//File file = new File("src/main/resources/model/google1/" + term + ".txt");
try {
URL url = new URL("file:src/main/resources/model/google1/" + term + ".txt");
Scanner scanner = new Scanner(url.openStream());
// Term frequency map
Map<String, Integer> tmap = new HashMap<String, Integer>();
// Document frequency map
Map<String, Integer> dmap = new HashMap<String, Integer>();
Map<String, Integer> tdmap = new HashMap<String, Integer>();
while (scanner.hasNextLine()) {
String[] tokens = scanner.nextLine().split(" ");
Set<String> unique = new HashSet<String>();
for (String token : tokens) {
token = token.toLowerCase();
if (!stoplist.contains(token)) {
if (tmap.containsKey(token)) {
tmap.put(token, tmap.get(token) + 1);
} else {
tmap.put(token, 1);
}
unique.add(token);
}
}
for (String token : unique) {
if (dmap.containsKey(token)) {
dmap.put(token, dmap.get(token) + 1);
} else {
dmap.put(token, 1);
}
}
}
// Calculate score of TF * DF
for (String token : tmap.keySet()) {
tdmap.put(token, tmap.get(token) * dmap.get(token));
}
// Sort terms according to their score of TF * DF
List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(
tdmap.entrySet());
Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Entry<String, Integer> e0, Entry<String, Integer> e1) {
return e1.getValue().compareTo(e0.getValue());
}
});
// Pick the top 6 terms
for (int i = 0; i < 6; i++) {
if (!list.get(i).getKey().equals(term.toLowerCase())
&& list.get(i).getValue() >= 4) {
System.out.println("[GOOGLE] " + list.get(i).getKey() + " : " + list.get(i).getValue());
synonyms.add(list.get(i).getKey());
}
}
} catch (IOException e) {
e.printStackTrace();
return synonyms;
}
return synonyms;
}
| public List<String> getSynonyms(String term) {
List<String> synonyms = new ArrayList<String>();
//File file = new File("model/google1/" + term + ".txt");
//File file = new File("src/main/resources/model/google1/" + term + ".txt");
try {
URL url = new URL("file:src/main/resources/model/google1/" + term + ".txt");
Scanner scanner = new Scanner(url.openStream());
// Term frequency map
Map<String, Integer> tmap = new HashMap<String, Integer>();
// Document frequency map
Map<String, Integer> dmap = new HashMap<String, Integer>();
Map<String, Integer> tdmap = new HashMap<String, Integer>();
while (scanner.hasNextLine()) {
String[] tokens = scanner.nextLine().split(" ");
Set<String> unique = new HashSet<String>();
for (String token : tokens) {
token = token.toLowerCase();
if (!stoplist.contains(token)) {
if (tmap.containsKey(token)) {
tmap.put(token, tmap.get(token) + 1);
} else {
tmap.put(token, 1);
}
unique.add(token);
}
}
for (String token : unique) {
if (dmap.containsKey(token)) {
dmap.put(token, dmap.get(token) + 1);
} else {
dmap.put(token, 1);
}
}
}
// Calculate score of TF * DF
for (String token : tmap.keySet()) {
tdmap.put(token, tmap.get(token) * dmap.get(token));
}
// Sort terms according to their score of TF * DF
List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(
tdmap.entrySet());
Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Entry<String, Integer> e0, Entry<String, Integer> e1) {
return e1.getValue().compareTo(e0.getValue());
}
});
// Pick the top 6 terms
for (int i = 0; i < 6; i++) {
if (!list.get(i).getKey().equals(term.toLowerCase())
&& list.get(i).getValue() >= 4) {
System.out.println("[GOOGLE] " + list.get(i).getKey() + " : " + list.get(i).getValue());
synonyms.add(list.get(i).getKey());
}
}
} catch (IOException e) {
System.err.println("[MISSING] Term : " + term);
return synonyms;
}
return synonyms;
}
|
diff --git a/src/Player.java b/src/Player.java
index 9afa08b..30486c3 100644
--- a/src/Player.java
+++ b/src/Player.java
@@ -1,84 +1,93 @@
/**
* Player Class.
* This class is in charge of the Player.
* This class has a reference to the current room that the player is in.
* As well, there is a playerHistory variable, in order to undo and redo certain moves.
* This class implements a doCommand method which will take the input command words and correlate them to actual actions.
*
*/
public class Player extends Humanoid {
private PlayerHistory playerHistory;
private Room currentRoom;
public Player(int health, Room r, String name){
super(health, name);
currentRoom = r;
playerHistory = new PlayerHistory();
}
public Player(Room r){
super();
currentRoom = r;
playerHistory = new PlayerHistory();
}
public void doCommand(Command c){
+ boolean b = false;
if (c.getCommandWord().equals(CommandWords.UNDO)){
c = playerHistory.undo();
+ b = true;
} else if (c.getCommandWord().equals(CommandWords.REDO)){
c = playerHistory.redo();
+ b = true;
+ }
+ if(c==null){
+ return; //TODO tell view about it
}
if (c.getCommandWord().equals(CommandWords.GO)){
Direction d = (Direction) c.getSecondWord();
Room r = currentRoom.getExit(d);
if(r!=null){
currentRoom = r;
} // else error TODO
+ if(b == false){
+ playerHistory.addStep(c);
+ }
} else if (c.getCommandWord().equals(CommandWords.FIGHT)){
Monster m = currentRoom.getMonster();
if(m==null){
System.out.println("Nothing to Fight!");
//should probably call the view here..shouldn't be a system.out in this class
} else {
//if(this.getBestItem().compareTo(m.getBestItem()) == 1){
m.updateHealth(this.getBestItem().getValue());
this.updateHealth(m.getBestItem().getValue());
if(m.getHealth()<=0){
currentRoom.removeMonster(m);
}
}
} else if (c.getCommandWord().equals(CommandWords.HELP)){
System.out.println("You are lost. You are alone. You wander around in a cave.\n");
System.out.println("Your command words are:");
System.out.println("GO, PICKUP, DROP, UNDO, REDO, FIGHT, HELP, QUIT");
//HELP may be implemented in another class.
} else if (c.getCommandWord().equals(CommandWords.PICKUP)){
Item i = (Item) c.getSecondWord();
addItem(i);
playerHistory.addStep(c);
} else if (c.getCommandWord().equals(CommandWords.DROP)){
Item i = (Item) c.getSecondWord();
removeItem(i);
playerHistory.addStep(c);
} else {
//TODO some sort of extraneous error checking
}//QUIT command does not get passed to the player
}
public Room getCurrentRoom(){
return currentRoom;
}
}
| false | true | public void doCommand(Command c){
if (c.getCommandWord().equals(CommandWords.UNDO)){
c = playerHistory.undo();
} else if (c.getCommandWord().equals(CommandWords.REDO)){
c = playerHistory.redo();
}
if (c.getCommandWord().equals(CommandWords.GO)){
Direction d = (Direction) c.getSecondWord();
Room r = currentRoom.getExit(d);
if(r!=null){
currentRoom = r;
} // else error TODO
} else if (c.getCommandWord().equals(CommandWords.FIGHT)){
Monster m = currentRoom.getMonster();
if(m==null){
System.out.println("Nothing to Fight!");
//should probably call the view here..shouldn't be a system.out in this class
} else {
//if(this.getBestItem().compareTo(m.getBestItem()) == 1){
m.updateHealth(this.getBestItem().getValue());
this.updateHealth(m.getBestItem().getValue());
if(m.getHealth()<=0){
currentRoom.removeMonster(m);
}
}
} else if (c.getCommandWord().equals(CommandWords.HELP)){
System.out.println("You are lost. You are alone. You wander around in a cave.\n");
System.out.println("Your command words are:");
System.out.println("GO, PICKUP, DROP, UNDO, REDO, FIGHT, HELP, QUIT");
//HELP may be implemented in another class.
} else if (c.getCommandWord().equals(CommandWords.PICKUP)){
Item i = (Item) c.getSecondWord();
addItem(i);
playerHistory.addStep(c);
} else if (c.getCommandWord().equals(CommandWords.DROP)){
Item i = (Item) c.getSecondWord();
removeItem(i);
playerHistory.addStep(c);
} else {
//TODO some sort of extraneous error checking
}//QUIT command does not get passed to the player
}
| public void doCommand(Command c){
boolean b = false;
if (c.getCommandWord().equals(CommandWords.UNDO)){
c = playerHistory.undo();
b = true;
} else if (c.getCommandWord().equals(CommandWords.REDO)){
c = playerHistory.redo();
b = true;
}
if(c==null){
return; //TODO tell view about it
}
if (c.getCommandWord().equals(CommandWords.GO)){
Direction d = (Direction) c.getSecondWord();
Room r = currentRoom.getExit(d);
if(r!=null){
currentRoom = r;
} // else error TODO
if(b == false){
playerHistory.addStep(c);
}
} else if (c.getCommandWord().equals(CommandWords.FIGHT)){
Monster m = currentRoom.getMonster();
if(m==null){
System.out.println("Nothing to Fight!");
//should probably call the view here..shouldn't be a system.out in this class
} else {
//if(this.getBestItem().compareTo(m.getBestItem()) == 1){
m.updateHealth(this.getBestItem().getValue());
this.updateHealth(m.getBestItem().getValue());
if(m.getHealth()<=0){
currentRoom.removeMonster(m);
}
}
} else if (c.getCommandWord().equals(CommandWords.HELP)){
System.out.println("You are lost. You are alone. You wander around in a cave.\n");
System.out.println("Your command words are:");
System.out.println("GO, PICKUP, DROP, UNDO, REDO, FIGHT, HELP, QUIT");
//HELP may be implemented in another class.
} else if (c.getCommandWord().equals(CommandWords.PICKUP)){
Item i = (Item) c.getSecondWord();
addItem(i);
playerHistory.addStep(c);
} else if (c.getCommandWord().equals(CommandWords.DROP)){
Item i = (Item) c.getSecondWord();
removeItem(i);
playerHistory.addStep(c);
} else {
//TODO some sort of extraneous error checking
}//QUIT command does not get passed to the player
}
|
diff --git a/src/VASSAL/counters/PieceDefiner.java b/src/VASSAL/counters/PieceDefiner.java
index 89c527e8..700ec472 100644
--- a/src/VASSAL/counters/PieceDefiner.java
+++ b/src/VASSAL/counters/PieceDefiner.java
@@ -1,679 +1,679 @@
/*
* $Id$
*
* Copyright (c) 2000-2003 by Rodney Kinney
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License (LGPL) as published by the Free Software Foundation.
*
* 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, copies are available
* at http://www.opensource.org.
*/
package VASSAL.counters;
import java.awt.Component;
import java.awt.Dialog;
import java.awt.Frame;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.BoxLayout;
import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListCellRenderer;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.border.TitledBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import VASSAL.build.GameModule;
import VASSAL.build.GpIdSupport;
import VASSAL.build.module.documentation.HelpFile;
import VASSAL.build.module.documentation.HelpWindow;
import VASSAL.build.module.documentation.HelpWindowExtension;
import VASSAL.build.widget.PieceSlot;
import VASSAL.tools.BrowserSupport;
import VASSAL.tools.ErrorLog;
/**
* This is the GamePiece designer dialog. It appears when you edit
* the properties of a "Single Piece" in the Configuration window.
*/
public class PieceDefiner extends JPanel implements HelpWindowExtension {
private static final long serialVersionUID = 1L;
protected static DefaultListModel availableModel;
protected DefaultListModel inUseModel;
protected ListCellRenderer r;
protected PieceSlot slot;
private GamePiece piece;
protected static TraitClipboard clipBoard;
protected String pieceId = "";
protected JLabel pieceIdLabel = new JLabel("");
protected GpIdSupport gpidSupport;
/** Creates new form test */
public PieceDefiner() {
initDefinitions();
inUseModel = new DefaultListModel();
r = new Renderer();
slot = new PieceSlot();
initComponents();
availableList.setSelectedIndex(0);
}
public PieceDefiner(String id, GpIdSupport s) {
this();
pieceId = id;
pieceIdLabel.setText("Id: "+id);
gpidSupport = s;
}
public PieceDefiner(GpIdSupport s) {
this();
gpidSupport = s;
}
protected static void initDefinitions() {
if (availableModel == null) {
availableModel = new DefaultListModel();
availableModel.addElement(new BasicPiece());
availableModel.addElement(new Delete());
availableModel.addElement(new Clone());
availableModel.addElement(new Embellishment());
availableModel.addElement(new UsePrototype());
availableModel.addElement(new Labeler());
availableModel.addElement(new ReportState());
availableModel.addElement(new TriggerAction());
availableModel.addElement(new GlobalHotKey());
availableModel.addElement(new ActionButton());
availableModel.addElement(new FreeRotator());
availableModel.addElement(new Pivot());
availableModel.addElement(new Hideable());
availableModel.addElement(new Obscurable());
availableModel.addElement(new SendToLocation());
availableModel.addElement(new CounterGlobalKeyCommand());
availableModel.addElement(new Translate());
availableModel.addElement(new ReturnToDeck());
availableModel.addElement(new Immobilized());
availableModel.addElement(new PropertySheet());
availableModel.addElement(new TableInfo());
availableModel.addElement(new PlaceMarker());
availableModel.addElement(new Replace());
availableModel.addElement(new NonRectangular());
availableModel.addElement(new PlaySound());
availableModel.addElement(new MovementMarkable());
availableModel.addElement(new Footprint());
availableModel.addElement(new AreaOfEffect());
availableModel.addElement(new SubMenu());
availableModel.addElement(new RestrictCommands());
availableModel.addElement(new Restricted());
availableModel.addElement(new Marker());
availableModel.addElement(new DynamicProperty());
availableModel.addElement(new SetGlobalProperty());
}
}
/**
* Plugins can add additional GamePiece definitions
* @param definition
*/
public static void addDefinition(GamePiece definition) {
initDefinitions();
availableModel.addElement(definition);
}
public void setPiece(GamePiece piece) {
inUseModel.clear();
while (piece instanceof Decorator) {
inUseModel.insertElementAt(piece, 0);
boolean contains = false;
for (int i = 0,j = availableModel.size(); i < j; ++i) {
if (piece.getClass().isInstance(availableModel.elementAt(i))) {
contains = true;
break;
}
}
if (!contains) {
try {
availableModel.addElement(piece.getClass().newInstance());
}
catch (Throwable ex) {
}
}
piece = ((Decorator) piece).piece;
}
if (piece == null) {
inUseModel.insertElementAt(new BasicPiece(), 0);
}
else {
inUseModel.insertElementAt(piece, 0);
}
inUseList.setSelectedIndex(0);
refresh();
}
@Deprecated
public void setBaseWindow(HelpWindow w) {
}
private void refresh() {
if (inUseModel.getSize() > 0) {
piece = (GamePiece) inUseModel.lastElement();
}
else {
piece = null;
}
slot.setPiece(piece);
slot.getComponent().repaint();
}
public GamePiece getPiece() {
return piece;
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the FormEditor.
*/
private void initComponents() {
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
add(slot.getComponent());
JPanel controls = new JPanel();
controls.setLayout(new BoxLayout(controls, BoxLayout.X_AXIS));
availablePanel = new JPanel();
availableScroll = new JScrollPane();
availableList = new JList();
helpButton = new JButton();
importButton = new JButton();
addRemovePanel = new JPanel();
addButton = new JButton();
removeButton = new JButton();
inUsePanel = new JPanel();
inUseScroll = new JScrollPane();
inUseList = new JList();
propsButton = new JButton();
moveUpDownPanel = new JPanel();
moveUpButton = new JButton();
moveDownButton = new JButton();
copyButton = new JButton();
pasteButton = new JButton();
// setLayout(new BoxLayout(this, 0));
availablePanel.setLayout(new BoxLayout(availablePanel, 1));
availableList.setModel(availableModel);
availableList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
availableList.setCellRenderer(r);
availableList.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent evt) {
Object o = availableList.getSelectedValue();
helpButton.setEnabled(o instanceof EditablePiece
&& ((EditablePiece) o).getHelpFile() != null);
addButton.setEnabled(o instanceof Decorator);
}
});
availableScroll.setViewportView(availableList);
availableScroll.setBorder(new TitledBorder("Available Traits"));
availablePanel.add(availableScroll);
helpButton.setText("Help");
helpButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
showHelpForPiece();
}
}
);
availablePanel.add(helpButton);
importButton.setText("Import");
importButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
String className = JOptionPane.showInputDialog(PieceDefiner.this, "Enter fully-qualified name of Java class to import");
importPiece(className);
}
}
);
availablePanel.add(importButton);
controls.add(availablePanel);
addRemovePanel.setLayout(new BoxLayout(addRemovePanel, 1));
addButton.setText("Add ->");
addButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
Object selected = availableList.getSelectedValue();
if (selected instanceof Decorator) {
if (inUseModel.getSize() > 0) {
Decorator c = (Decorator) selected;
addTrait(c);
if (inUseModel.lastElement().getClass() == c.getClass()) {
if (edit(inUseModel.size() - 1)) { // Add was successful
}
else { // Add was cancelled
if (!inUseModel.isEmpty())
removeTrait(inUseModel.size() - 1);
}
}
}
}
else if (selected instanceof GamePiece
&& inUseModel.getSize() == 0) {
try {
GamePiece p = (GamePiece) selected.getClass().newInstance();
setPiece(p);
if (inUseModel.getSize() > 0) {
if (edit(0)) { // Add was successful
}
else { // Add was cancelled
removeTrait(0);
}
}
}
catch (Exception e) {
ErrorLog.log(e);
}
}
}
});
addButton.setAlignmentX(Component.CENTER_ALIGNMENT);
addRemovePanel.add(addButton);
removeButton.setText("<- Remove");
removeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
int index = inUseList.getSelectedIndex();
if (index >= 0) {
removeTrait(index);
if (inUseModel.getSize() > 0) {
inUseList.setSelectedIndex(
Math.min(inUseModel.getSize() - 1, Math.max(index, 0)));
}
}
}
}
);
removeButton.setAlignmentX(Component.CENTER_ALIGNMENT);
addRemovePanel.add(removeButton);
pieceIdLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
addRemovePanel.add(pieceIdLabel);
controls.add(addRemovePanel);
inUsePanel.setLayout(new BoxLayout(inUsePanel, 1));
inUseList.setModel(inUseModel);
inUseList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
inUseList.setCellRenderer(r);
inUseList.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent evt) {
Object o = inUseList.getSelectedValue();
int index = inUseList.getSelectedIndex();
propsButton.setEnabled(o instanceof EditablePiece);
if (inUseModel.size() > 1) {
removeButton.setEnabled(index > 0);
copyButton.setEnabled(index > 0);
}
else if (inUseModel.size() == 1) {
removeButton.setEnabled(index == 0 &&
!(inUseModel.getElementAt(0) instanceof BasicPiece));
copyButton.setEnabled(index == 0);
}
else {
removeButton.setEnabled(false);
copyButton.setEnabled(false);
}
pasteButton.setEnabled(clipBoard != null);
moveUpButton.setEnabled(index > 1);
moveDownButton.setEnabled(index > 0
&& index < inUseModel.size() - 1);
}
});
inUseList.addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent evt) {
if (evt.getClickCount() == 2) {
int index = inUseList.locationToIndex(evt.getPoint());
if (index >= 0) {
edit(index);
}
}
}
});
inUseScroll.setViewportView(inUseList);
inUseScroll.setBorder(new TitledBorder("Current Traits"));
inUsePanel.add(inUseScroll);
propsButton.setText("Properties");
propsButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
int index = inUseList.getSelectedIndex();
if (index >= 0) {
edit(index);
}
}
}
);
inUsePanel.add(propsButton);
controls.add(inUsePanel);
moveUpDownPanel.setLayout(new BoxLayout(moveUpDownPanel, BoxLayout.Y_AXIS));
moveUpButton.setText("Move Up");
moveUpButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
int index = inUseList.getSelectedIndex();
if (index > 1 && index < inUseModel.size()) {
moveDecoratorUp(index);
}
}
}
);
moveUpDownPanel.add(moveUpButton);
moveDownButton.setText("Move Down");
moveDownButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
int index = inUseList.getSelectedIndex();
if (index > 0 && index < inUseModel.size() - 1) {
moveDecoratorDown(index);
}
}
}
);
moveUpDownPanel.add(moveDownButton);
copyButton.setText("Copy");
copyButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
pasteButton.setEnabled(true);
int index = inUseList.getSelectedIndex();
clipBoard = new TraitClipboard((Decorator) inUseModel.get(index));
}});
moveUpDownPanel.add(copyButton);
pasteButton.setText("Paste");
pasteButton.setEnabled(clipBoard != null);
pasteButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (clipBoard != null) {
Decorator c = (Decorator) GameModule.getGameModule().createPiece(clipBoard.getType(), null);
if (c instanceof PlaceMarker) {
- ((PlaceMarker) c).updateGpId();
+ ((PlaceMarker) c).updateGpId(GameModule.getGameModule().getGpIdSupport());
}
c.setInner((GamePiece) inUseModel.lastElement());
inUseModel.addElement(c);
c.mySetState(clipBoard.getState());
refresh();
}
}});
moveUpDownPanel.add(pasteButton);
controls.add(moveUpDownPanel);
add(controls);
}
protected void moveDecoratorDown(int index) {
GamePiece selm1 = (GamePiece) inUseModel.elementAt(index - 1);
Decorator sel = (Decorator) inUseModel.elementAt(index);
Decorator selp1 = (Decorator) inUseModel.elementAt(index + 1);
Decorator selp2 = index < inUseModel.size() - 2 ? (Decorator) inUseModel.elementAt(index + 2) : null;
selp1.setInner(selm1);
sel.setInner(selp1);
if (selp2 != null) {
selp2.setInner(sel);
}
inUseModel.setElementAt(selp1, index);
inUseModel.setElementAt(sel, index + 1);
((GamePiece) inUseModel.lastElement()).setProperty(Properties.OUTER, null);
inUseList.setSelectedIndex(index + 1);
refresh();
}
protected void moveDecoratorUp(int index) {
GamePiece selm2 = (GamePiece) inUseModel.elementAt(index - 2);
Decorator sel = (Decorator) inUseModel.elementAt(index);
Decorator selm1 = (Decorator) inUseModel.elementAt(index - 1);
Decorator selp1 = index < inUseModel.size() - 1 ? (Decorator) inUseModel.elementAt(index + 1) : null;
sel.setInner(selm2);
selm1.setInner(sel);
if (selp1 != null) {
selp1.setInner(selm1);
}
inUseModel.setElementAt(selm1, index);
inUseModel.setElementAt(sel, index - 1);
((GamePiece) inUseModel.lastElement()).setProperty(Properties.OUTER, null);
inUseList.setSelectedIndex(index - 1);
refresh();
}
protected void importPiece(String className) {
try {
Class<?> c = GameModule.getGameModule().getDataArchive().loadClass(className);
Object o = c.newInstance();
if (o instanceof GamePiece) {
availableModel.addElement(o);
}
else {
JOptionPane.showMessageDialog(this, "Class must implement the GamePiece interface.", "Class error", JOptionPane.ERROR_MESSAGE);
}
}
catch (ClassNotFoundException noClass) {
JOptionPane.showMessageDialog(this, "Couldn't find class.\nClass file must exist in module zipfile with correct package structure.", "Class not found", JOptionPane.ERROR_MESSAGE);
}
catch (InstantiationException iex) {
JOptionPane.showMessageDialog(this, "Couldn't instantiate class.\nClass must not be abstract.", "Class not initialized", JOptionPane.ERROR_MESSAGE);
}
catch (IllegalAccessException ilex) {
JOptionPane.showMessageDialog(this, "Error accessing class", "Access error", JOptionPane.ERROR_MESSAGE);
}
catch (NoSuchMethodError noMethod) {
JOptionPane.showMessageDialog(this, "Couldn't instantiate class.\nClass must have a no-argument constructor.", "Class not initialized", JOptionPane.ERROR_MESSAGE);
}
}
private void showHelpForPiece() {
Object o = availableList.getSelectedValue();
if (o instanceof EditablePiece) {
HelpFile h = ((EditablePiece) o).getHelpFile();
BrowserSupport.openURL(h.getContents().toString());
}
}
protected boolean edit(int index) {
Object o = inUseModel.elementAt(index);
if (!(o instanceof EditablePiece)) {
return false;
}
EditablePiece p = (EditablePiece) o;
if (p.getEditor() != null) {
Ed ed = null;
Window w = SwingUtilities.getWindowAncestor(this);
if (w instanceof Frame) {
ed = new Ed((Frame) w, p);
}
else if (w instanceof Dialog) {
ed = new Ed((Dialog) w, p);
}
else {
ed = new Ed((Frame) null, p);
}
ed.setVisible(true);
PieceEditor c = ed.getEditor();
if (c != null) {
p.mySetType(c.getType());
if (p instanceof Decorator) {
((Decorator) p).mySetState(c.getState());
}
else {
p.setState(c.getState());
}
refresh();
return true;
}
}
return false;
}
/** A Dialog for editing an EditablePiece's properties */
protected static class Ed extends JDialog {
private static final long serialVersionUID = 1L;
PieceEditor ed;
private Ed(Frame owner, final EditablePiece p) {
super(owner, p.getDescription() + " properties", true);
initialize(p);
}
private Ed(Dialog owner, final EditablePiece p) {
super(owner, p.getDescription() + " properties", true);
initialize(p);
}
private void initialize(final EditablePiece p) {
ed = p.getEditor();
setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
add(ed.getControls());
JButton b = new JButton("Ok");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
dispose();
}
});
JPanel panel = new JPanel();
panel.add(b);
b = new JButton("Cancel");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
ed = null;
dispose();
}
});
panel.add(b);
add(panel);
pack();
setLocationRelativeTo(getOwner());
}
public PieceEditor getEditor() {
return ed;
}
}
protected void removeTrait(int index) {
inUseModel.removeElementAt(index);
if (index < inUseModel.size()) {
((Decorator) inUseModel.elementAt(index)).setInner((GamePiece) inUseModel.elementAt(index - 1));
}
refresh();
}
protected void addTrait(Decorator c) {
try {
c = c.getClass().newInstance();
if (c instanceof PlaceMarker) {
((PlaceMarker) c).updateGpId(gpidSupport);
}
c.setInner((GamePiece) inUseModel.lastElement());
inUseModel.addElement(c);
}
catch (Exception ex) {
ErrorLog.log(ex);
}
refresh();
}
private JPanel availablePanel;
private JScrollPane availableScroll;
private JList availableList;
private JButton helpButton;
private JButton importButton;
private JPanel addRemovePanel;
private JButton addButton;
private JButton removeButton;
private JPanel inUsePanel;
private JScrollPane inUseScroll;
private JList inUseList;
private JButton propsButton;
private JPanel moveUpDownPanel;
private JButton moveUpButton;
private JButton moveDownButton;
protected JButton copyButton;
protected JButton pasteButton;
private static class Renderer extends DefaultListCellRenderer {
private static final long serialVersionUID = 1L;
public java.awt.Component getListCellRendererComponent
(JList list, Object value, int index, boolean selected, boolean hasFocus) {
super.getListCellRendererComponent(list, value, index, selected, hasFocus);
if (value instanceof EditablePiece) {
setText(((EditablePiece) value).getDescription());
}
else {
String s = value.getClass().getName();
setText(s.substring(s.lastIndexOf(".") + 1));
}
return this;
}
}
/**
* Contents of the Copy/Paste buffer for traits in the editor
* @author rkinney
*
*/
private static class TraitClipboard {
private String type;
private String state;
public TraitClipboard(Decorator copy) {
type = copy.myGetType();
state = copy.myGetState();
}
public String getType() {
return type;
}
public String getState() {
return state;
}
}
}
| true | true | private void initComponents() {
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
add(slot.getComponent());
JPanel controls = new JPanel();
controls.setLayout(new BoxLayout(controls, BoxLayout.X_AXIS));
availablePanel = new JPanel();
availableScroll = new JScrollPane();
availableList = new JList();
helpButton = new JButton();
importButton = new JButton();
addRemovePanel = new JPanel();
addButton = new JButton();
removeButton = new JButton();
inUsePanel = new JPanel();
inUseScroll = new JScrollPane();
inUseList = new JList();
propsButton = new JButton();
moveUpDownPanel = new JPanel();
moveUpButton = new JButton();
moveDownButton = new JButton();
copyButton = new JButton();
pasteButton = new JButton();
// setLayout(new BoxLayout(this, 0));
availablePanel.setLayout(new BoxLayout(availablePanel, 1));
availableList.setModel(availableModel);
availableList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
availableList.setCellRenderer(r);
availableList.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent evt) {
Object o = availableList.getSelectedValue();
helpButton.setEnabled(o instanceof EditablePiece
&& ((EditablePiece) o).getHelpFile() != null);
addButton.setEnabled(o instanceof Decorator);
}
});
availableScroll.setViewportView(availableList);
availableScroll.setBorder(new TitledBorder("Available Traits"));
availablePanel.add(availableScroll);
helpButton.setText("Help");
helpButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
showHelpForPiece();
}
}
);
availablePanel.add(helpButton);
importButton.setText("Import");
importButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
String className = JOptionPane.showInputDialog(PieceDefiner.this, "Enter fully-qualified name of Java class to import");
importPiece(className);
}
}
);
availablePanel.add(importButton);
controls.add(availablePanel);
addRemovePanel.setLayout(new BoxLayout(addRemovePanel, 1));
addButton.setText("Add ->");
addButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
Object selected = availableList.getSelectedValue();
if (selected instanceof Decorator) {
if (inUseModel.getSize() > 0) {
Decorator c = (Decorator) selected;
addTrait(c);
if (inUseModel.lastElement().getClass() == c.getClass()) {
if (edit(inUseModel.size() - 1)) { // Add was successful
}
else { // Add was cancelled
if (!inUseModel.isEmpty())
removeTrait(inUseModel.size() - 1);
}
}
}
}
else if (selected instanceof GamePiece
&& inUseModel.getSize() == 0) {
try {
GamePiece p = (GamePiece) selected.getClass().newInstance();
setPiece(p);
if (inUseModel.getSize() > 0) {
if (edit(0)) { // Add was successful
}
else { // Add was cancelled
removeTrait(0);
}
}
}
catch (Exception e) {
ErrorLog.log(e);
}
}
}
});
addButton.setAlignmentX(Component.CENTER_ALIGNMENT);
addRemovePanel.add(addButton);
removeButton.setText("<- Remove");
removeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
int index = inUseList.getSelectedIndex();
if (index >= 0) {
removeTrait(index);
if (inUseModel.getSize() > 0) {
inUseList.setSelectedIndex(
Math.min(inUseModel.getSize() - 1, Math.max(index, 0)));
}
}
}
}
);
removeButton.setAlignmentX(Component.CENTER_ALIGNMENT);
addRemovePanel.add(removeButton);
pieceIdLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
addRemovePanel.add(pieceIdLabel);
controls.add(addRemovePanel);
inUsePanel.setLayout(new BoxLayout(inUsePanel, 1));
inUseList.setModel(inUseModel);
inUseList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
inUseList.setCellRenderer(r);
inUseList.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent evt) {
Object o = inUseList.getSelectedValue();
int index = inUseList.getSelectedIndex();
propsButton.setEnabled(o instanceof EditablePiece);
if (inUseModel.size() > 1) {
removeButton.setEnabled(index > 0);
copyButton.setEnabled(index > 0);
}
else if (inUseModel.size() == 1) {
removeButton.setEnabled(index == 0 &&
!(inUseModel.getElementAt(0) instanceof BasicPiece));
copyButton.setEnabled(index == 0);
}
else {
removeButton.setEnabled(false);
copyButton.setEnabled(false);
}
pasteButton.setEnabled(clipBoard != null);
moveUpButton.setEnabled(index > 1);
moveDownButton.setEnabled(index > 0
&& index < inUseModel.size() - 1);
}
});
inUseList.addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent evt) {
if (evt.getClickCount() == 2) {
int index = inUseList.locationToIndex(evt.getPoint());
if (index >= 0) {
edit(index);
}
}
}
});
inUseScroll.setViewportView(inUseList);
inUseScroll.setBorder(new TitledBorder("Current Traits"));
inUsePanel.add(inUseScroll);
propsButton.setText("Properties");
propsButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
int index = inUseList.getSelectedIndex();
if (index >= 0) {
edit(index);
}
}
}
);
inUsePanel.add(propsButton);
controls.add(inUsePanel);
moveUpDownPanel.setLayout(new BoxLayout(moveUpDownPanel, BoxLayout.Y_AXIS));
moveUpButton.setText("Move Up");
moveUpButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
int index = inUseList.getSelectedIndex();
if (index > 1 && index < inUseModel.size()) {
moveDecoratorUp(index);
}
}
}
);
moveUpDownPanel.add(moveUpButton);
moveDownButton.setText("Move Down");
moveDownButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
int index = inUseList.getSelectedIndex();
if (index > 0 && index < inUseModel.size() - 1) {
moveDecoratorDown(index);
}
}
}
);
moveUpDownPanel.add(moveDownButton);
copyButton.setText("Copy");
copyButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
pasteButton.setEnabled(true);
int index = inUseList.getSelectedIndex();
clipBoard = new TraitClipboard((Decorator) inUseModel.get(index));
}});
moveUpDownPanel.add(copyButton);
pasteButton.setText("Paste");
pasteButton.setEnabled(clipBoard != null);
pasteButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (clipBoard != null) {
Decorator c = (Decorator) GameModule.getGameModule().createPiece(clipBoard.getType(), null);
if (c instanceof PlaceMarker) {
((PlaceMarker) c).updateGpId();
}
c.setInner((GamePiece) inUseModel.lastElement());
inUseModel.addElement(c);
c.mySetState(clipBoard.getState());
refresh();
}
}});
moveUpDownPanel.add(pasteButton);
controls.add(moveUpDownPanel);
add(controls);
}
| private void initComponents() {
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
add(slot.getComponent());
JPanel controls = new JPanel();
controls.setLayout(new BoxLayout(controls, BoxLayout.X_AXIS));
availablePanel = new JPanel();
availableScroll = new JScrollPane();
availableList = new JList();
helpButton = new JButton();
importButton = new JButton();
addRemovePanel = new JPanel();
addButton = new JButton();
removeButton = new JButton();
inUsePanel = new JPanel();
inUseScroll = new JScrollPane();
inUseList = new JList();
propsButton = new JButton();
moveUpDownPanel = new JPanel();
moveUpButton = new JButton();
moveDownButton = new JButton();
copyButton = new JButton();
pasteButton = new JButton();
// setLayout(new BoxLayout(this, 0));
availablePanel.setLayout(new BoxLayout(availablePanel, 1));
availableList.setModel(availableModel);
availableList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
availableList.setCellRenderer(r);
availableList.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent evt) {
Object o = availableList.getSelectedValue();
helpButton.setEnabled(o instanceof EditablePiece
&& ((EditablePiece) o).getHelpFile() != null);
addButton.setEnabled(o instanceof Decorator);
}
});
availableScroll.setViewportView(availableList);
availableScroll.setBorder(new TitledBorder("Available Traits"));
availablePanel.add(availableScroll);
helpButton.setText("Help");
helpButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
showHelpForPiece();
}
}
);
availablePanel.add(helpButton);
importButton.setText("Import");
importButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
String className = JOptionPane.showInputDialog(PieceDefiner.this, "Enter fully-qualified name of Java class to import");
importPiece(className);
}
}
);
availablePanel.add(importButton);
controls.add(availablePanel);
addRemovePanel.setLayout(new BoxLayout(addRemovePanel, 1));
addButton.setText("Add ->");
addButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
Object selected = availableList.getSelectedValue();
if (selected instanceof Decorator) {
if (inUseModel.getSize() > 0) {
Decorator c = (Decorator) selected;
addTrait(c);
if (inUseModel.lastElement().getClass() == c.getClass()) {
if (edit(inUseModel.size() - 1)) { // Add was successful
}
else { // Add was cancelled
if (!inUseModel.isEmpty())
removeTrait(inUseModel.size() - 1);
}
}
}
}
else if (selected instanceof GamePiece
&& inUseModel.getSize() == 0) {
try {
GamePiece p = (GamePiece) selected.getClass().newInstance();
setPiece(p);
if (inUseModel.getSize() > 0) {
if (edit(0)) { // Add was successful
}
else { // Add was cancelled
removeTrait(0);
}
}
}
catch (Exception e) {
ErrorLog.log(e);
}
}
}
});
addButton.setAlignmentX(Component.CENTER_ALIGNMENT);
addRemovePanel.add(addButton);
removeButton.setText("<- Remove");
removeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
int index = inUseList.getSelectedIndex();
if (index >= 0) {
removeTrait(index);
if (inUseModel.getSize() > 0) {
inUseList.setSelectedIndex(
Math.min(inUseModel.getSize() - 1, Math.max(index, 0)));
}
}
}
}
);
removeButton.setAlignmentX(Component.CENTER_ALIGNMENT);
addRemovePanel.add(removeButton);
pieceIdLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
addRemovePanel.add(pieceIdLabel);
controls.add(addRemovePanel);
inUsePanel.setLayout(new BoxLayout(inUsePanel, 1));
inUseList.setModel(inUseModel);
inUseList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
inUseList.setCellRenderer(r);
inUseList.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent evt) {
Object o = inUseList.getSelectedValue();
int index = inUseList.getSelectedIndex();
propsButton.setEnabled(o instanceof EditablePiece);
if (inUseModel.size() > 1) {
removeButton.setEnabled(index > 0);
copyButton.setEnabled(index > 0);
}
else if (inUseModel.size() == 1) {
removeButton.setEnabled(index == 0 &&
!(inUseModel.getElementAt(0) instanceof BasicPiece));
copyButton.setEnabled(index == 0);
}
else {
removeButton.setEnabled(false);
copyButton.setEnabled(false);
}
pasteButton.setEnabled(clipBoard != null);
moveUpButton.setEnabled(index > 1);
moveDownButton.setEnabled(index > 0
&& index < inUseModel.size() - 1);
}
});
inUseList.addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent evt) {
if (evt.getClickCount() == 2) {
int index = inUseList.locationToIndex(evt.getPoint());
if (index >= 0) {
edit(index);
}
}
}
});
inUseScroll.setViewportView(inUseList);
inUseScroll.setBorder(new TitledBorder("Current Traits"));
inUsePanel.add(inUseScroll);
propsButton.setText("Properties");
propsButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
int index = inUseList.getSelectedIndex();
if (index >= 0) {
edit(index);
}
}
}
);
inUsePanel.add(propsButton);
controls.add(inUsePanel);
moveUpDownPanel.setLayout(new BoxLayout(moveUpDownPanel, BoxLayout.Y_AXIS));
moveUpButton.setText("Move Up");
moveUpButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
int index = inUseList.getSelectedIndex();
if (index > 1 && index < inUseModel.size()) {
moveDecoratorUp(index);
}
}
}
);
moveUpDownPanel.add(moveUpButton);
moveDownButton.setText("Move Down");
moveDownButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
int index = inUseList.getSelectedIndex();
if (index > 0 && index < inUseModel.size() - 1) {
moveDecoratorDown(index);
}
}
}
);
moveUpDownPanel.add(moveDownButton);
copyButton.setText("Copy");
copyButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
pasteButton.setEnabled(true);
int index = inUseList.getSelectedIndex();
clipBoard = new TraitClipboard((Decorator) inUseModel.get(index));
}});
moveUpDownPanel.add(copyButton);
pasteButton.setText("Paste");
pasteButton.setEnabled(clipBoard != null);
pasteButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (clipBoard != null) {
Decorator c = (Decorator) GameModule.getGameModule().createPiece(clipBoard.getType(), null);
if (c instanceof PlaceMarker) {
((PlaceMarker) c).updateGpId(GameModule.getGameModule().getGpIdSupport());
}
c.setInner((GamePiece) inUseModel.lastElement());
inUseModel.addElement(c);
c.mySetState(clipBoard.getState());
refresh();
}
}});
moveUpDownPanel.add(pasteButton);
controls.add(moveUpDownPanel);
add(controls);
}
|
diff --git a/base/src/edu/berkeley/cs/cs162/User.java b/base/src/edu/berkeley/cs/cs162/User.java
index b52b04e..fdc529a 100644
--- a/base/src/edu/berkeley/cs/cs162/User.java
+++ b/base/src/edu/berkeley/cs/cs162/User.java
@@ -1,55 +1,55 @@
package edu.berkeley.cs.cs162;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class User extends BaseUser {
private ChatServer server;
private String username;
private List<ChatGroup> groupsJoined;
private Map<String, ChatLog> chatlogs;
public User(ChatServer server, String username) {
this.server = server;
this.username = username;
groupsJoined = new LinkedList<ChatGroup>();
chatlogs = new HashMap<String, ChatLog>();
}
public void getGroups() {
Set<String> groups = server.getGroups();
// Do something with group list
}
public void getUsers() {
Set<String> users = server.getUsers();
// Do something with users list
}
public void send(String dest, String msg) {
MsgSendError msgStatus = server.processMessage(username, dest, msg);
// Do something with message send error
}
public void msgReceived(Message msg) {
// Add to chatlog
String source = msg.getSource();
ChatLog log;
if (chatlogs.containsKey(source)) {
log = chatlogs.get(source);
} else {
- log = new ChatLog(source, username);
+ log = new ChatLog(source, this);
}
log.add(msg);
msgReceived(msg.getContent());
}
public void msgReceived(String msg) {
System.out.println(username + " received the message: " + msg);
}
}
| true | true | public void msgReceived(Message msg) {
// Add to chatlog
String source = msg.getSource();
ChatLog log;
if (chatlogs.containsKey(source)) {
log = chatlogs.get(source);
} else {
log = new ChatLog(source, username);
}
log.add(msg);
msgReceived(msg.getContent());
}
| public void msgReceived(Message msg) {
// Add to chatlog
String source = msg.getSource();
ChatLog log;
if (chatlogs.containsKey(source)) {
log = chatlogs.get(source);
} else {
log = new ChatLog(source, this);
}
log.add(msg);
msgReceived(msg.getContent());
}
|
diff --git a/jsf-ri/src/com/sun/faces/application/NamedEventManager.java b/jsf-ri/src/com/sun/faces/application/NamedEventManager.java
index f4bf973da..ffe47b3ab 100644
--- a/jsf-ri/src/com/sun/faces/application/NamedEventManager.java
+++ b/jsf-ri/src/com/sun/faces/application/NamedEventManager.java
@@ -1,81 +1,80 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.sun.faces.application;
import com.sun.faces.util.Util;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import javax.faces.FacesException;
import javax.faces.event.PostAddToViewEvent;
import javax.faces.event.PostValidateEvent;
import javax.faces.event.PreValidateEvent;
import javax.faces.event.ComponentSystemEvent;
import javax.faces.event.PreRenderComponentEvent;
import javax.faces.event.PreRenderViewEvent;
import javax.faces.event.SystemEvent;
/**
* Note: New, relevant spec'd ComponentSystemEvents must be added to the constructor
*/
public class NamedEventManager {
private Map<String, Class<? extends SystemEvent>> namedEvents =
new ConcurrentHashMap<String, Class<? extends SystemEvent>>();
private Map<String, Set<Class<? extends SystemEvent>>> duplicateNames =
new ConcurrentHashMap<String, Set<Class<? extends SystemEvent>>>();
public NamedEventManager() {
namedEvents.put("javax.faces.event.PreRenderComponent", PreRenderComponentEvent.class);
namedEvents.put("javax.faces.event.PreRenderView", PreRenderViewEvent.class);
namedEvents.put("javax.faces.event.PostAddToView", PostAddToViewEvent.class);
namedEvents.put("javax.faces.event.PreValidate", PreValidateEvent.class);
namedEvents.put("javax.faces.event.PostValidate", PostValidateEvent.class);
namedEvents.put("preRenderComponent", PreRenderComponentEvent.class);
namedEvents.put("preRenderView", PreRenderViewEvent.class);
namedEvents.put("postAddToView", PostAddToViewEvent.class);
namedEvents.put("preValidate", PreValidateEvent.class);
namedEvents.put("postValidate", PostValidateEvent.class);
}
public void addNamedEvent(String name, Class<? extends SystemEvent> event) {
namedEvents.put(name, event);
}
public Class<? extends SystemEvent> getNamedEvent(String name) {
- String foo = namedEvents.toString();
Class<? extends SystemEvent> namedEvent = namedEvents.get(name);
if (namedEvent == null) {
try {
namedEvent = Util.loadClass(name, this);
} catch (ClassNotFoundException ex) {
throw new FacesException ("An unknown event type was specified: " + name, ex);
}
}
if (!ComponentSystemEvent.class.isAssignableFrom(namedEvent)) {
throw new ClassCastException();
}
return namedEvent;
}
public void addDuplicateName(String name, Class<? extends SystemEvent> event) {
Class<? extends SystemEvent> registeredEvent = namedEvents.remove(name);
Set<Class<? extends SystemEvent>> events = duplicateNames.get(name);
if (events == null) {
events = new HashSet<Class<? extends SystemEvent>>();
duplicateNames.put(name, events);
}
events.add(event);
if (registeredEvent != null) {
events.add(registeredEvent);
}
}
public boolean isDuplicateNamedEvent(String name) {
return (namedEvents.get(name) != null) || (duplicateNames.get(name) != null);
}
}
| true | true | public Class<? extends SystemEvent> getNamedEvent(String name) {
String foo = namedEvents.toString();
Class<? extends SystemEvent> namedEvent = namedEvents.get(name);
if (namedEvent == null) {
try {
namedEvent = Util.loadClass(name, this);
} catch (ClassNotFoundException ex) {
throw new FacesException ("An unknown event type was specified: " + name, ex);
}
}
if (!ComponentSystemEvent.class.isAssignableFrom(namedEvent)) {
throw new ClassCastException();
}
return namedEvent;
}
| public Class<? extends SystemEvent> getNamedEvent(String name) {
Class<? extends SystemEvent> namedEvent = namedEvents.get(name);
if (namedEvent == null) {
try {
namedEvent = Util.loadClass(name, this);
} catch (ClassNotFoundException ex) {
throw new FacesException ("An unknown event type was specified: " + name, ex);
}
}
if (!ComponentSystemEvent.class.isAssignableFrom(namedEvent)) {
throw new ClassCastException();
}
return namedEvent;
}
|
diff --git a/bundles/org.eclipse.wst.xsd.ui/src-adt-xsd/org/eclipse/wst/xsd/editor/XSDTabbedPropertySheetPage.java b/bundles/org.eclipse.wst.xsd.ui/src-adt-xsd/org/eclipse/wst/xsd/editor/XSDTabbedPropertySheetPage.java
index d7a4f55c0..a0d6fa81e 100644
--- a/bundles/org.eclipse.wst.xsd.ui/src-adt-xsd/org/eclipse/wst/xsd/editor/XSDTabbedPropertySheetPage.java
+++ b/bundles/org.eclipse.wst.xsd.ui/src-adt-xsd/org/eclipse/wst/xsd/editor/XSDTabbedPropertySheetPage.java
@@ -1,95 +1,94 @@
/*******************************************************************************
* Copyright (c) 2001, 2006 IBM Corporation 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
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.wst.xsd.editor;
import org.eclipse.emf.common.notify.Adapter;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.views.properties.tabbed.ITabbedPropertySheetPageContributor;
import org.eclipse.ui.views.properties.tabbed.TabbedPropertySheetPage;
import org.eclipse.wst.xsd.adt.facade.IADTObjectListener;
import org.eclipse.wst.xsd.editor.internal.adapters.XSDAdapterFactory;
import org.eclipse.wst.xsd.editor.internal.adapters.XSDBaseAdapter;
import org.eclipse.wst.xsd.editor.internal.adapters.XSDElementDeclarationAdapter;
import org.eclipse.wst.xsd.editor.internal.adapters.XSDParticleAdapter;
import org.eclipse.xsd.XSDConcreteComponent;
import org.eclipse.xsd.XSDElementDeclaration;
public class XSDTabbedPropertySheetPage extends TabbedPropertySheetPage implements IADTObjectListener
{
XSDBaseAdapter oldSelection;
public XSDTabbedPropertySheetPage(ITabbedPropertySheetPageContributor tabbedPropertySheetPageContributor)
{
super(tabbedPropertySheetPageContributor);
}
/* (non-Javadoc)
* @see org.eclipse.ui.ISelectionListener#selectionChanged(org.eclipse.ui.IWorkbenchPart, org.eclipse.jface.viewers.ISelection)
*/
public void selectionChanged(IWorkbenchPart part, ISelection selection) {
Object selected = ((StructuredSelection)selection).getFirstElement();
- System.out.println(selected);
if (selected instanceof XSDBaseAdapter)
{
XSDBaseAdapter adapter = (XSDBaseAdapter)selected;
if (oldSelection != null)
{
oldSelection.unregisterListener(this);
if (oldSelection instanceof XSDElementDeclarationAdapter)
{
XSDElementDeclaration elem = (XSDElementDeclaration)((XSDElementDeclarationAdapter)oldSelection).getTarget();
Adapter adap = XSDAdapterFactory.getInstance().adapt(elem.getContainer());
if (adap instanceof XSDParticleAdapter)
{
XSDParticleAdapter particleAdapter = (XSDParticleAdapter)adap;
particleAdapter.unregisterListener(this);
}
}
}
if (adapter instanceof XSDElementDeclarationAdapter)
{
XSDElementDeclaration elem = (XSDElementDeclaration)((XSDElementDeclarationAdapter)adapter).getTarget();
Adapter adap = XSDAdapterFactory.getInstance().adapt(elem.getContainer());
if (adap instanceof XSDParticleAdapter)
{
XSDParticleAdapter particleAdapter = (XSDParticleAdapter)adap;
particleAdapter.registerListener(this);
}
if (elem.isElementDeclarationReference())
{
XSDElementDeclarationAdapter resolvedElementAdapter = (XSDElementDeclarationAdapter)XSDAdapterFactory.getInstance().adapt(elem.getResolvedElementDeclaration());
resolvedElementAdapter.registerListener(this);
}
}
adapter.registerListener(this);
oldSelection = adapter;
Object model = adapter.getTarget();
if (model instanceof XSDConcreteComponent)
{
selection = new StructuredSelection((XSDConcreteComponent)model);
}
super.selectionChanged(part, selection);
return;
}
super.selectionChanged(part, selection);
}
public void propertyChanged(Object object, String property)
{
if (getCurrentTab() != null)
{
refresh();
}
}
}
| true | true | public void selectionChanged(IWorkbenchPart part, ISelection selection) {
Object selected = ((StructuredSelection)selection).getFirstElement();
System.out.println(selected);
if (selected instanceof XSDBaseAdapter)
{
XSDBaseAdapter adapter = (XSDBaseAdapter)selected;
if (oldSelection != null)
{
oldSelection.unregisterListener(this);
if (oldSelection instanceof XSDElementDeclarationAdapter)
{
XSDElementDeclaration elem = (XSDElementDeclaration)((XSDElementDeclarationAdapter)oldSelection).getTarget();
Adapter adap = XSDAdapterFactory.getInstance().adapt(elem.getContainer());
if (adap instanceof XSDParticleAdapter)
{
XSDParticleAdapter particleAdapter = (XSDParticleAdapter)adap;
particleAdapter.unregisterListener(this);
}
}
}
if (adapter instanceof XSDElementDeclarationAdapter)
{
XSDElementDeclaration elem = (XSDElementDeclaration)((XSDElementDeclarationAdapter)adapter).getTarget();
Adapter adap = XSDAdapterFactory.getInstance().adapt(elem.getContainer());
if (adap instanceof XSDParticleAdapter)
{
XSDParticleAdapter particleAdapter = (XSDParticleAdapter)adap;
particleAdapter.registerListener(this);
}
if (elem.isElementDeclarationReference())
{
XSDElementDeclarationAdapter resolvedElementAdapter = (XSDElementDeclarationAdapter)XSDAdapterFactory.getInstance().adapt(elem.getResolvedElementDeclaration());
resolvedElementAdapter.registerListener(this);
}
}
adapter.registerListener(this);
oldSelection = adapter;
Object model = adapter.getTarget();
if (model instanceof XSDConcreteComponent)
{
selection = new StructuredSelection((XSDConcreteComponent)model);
}
super.selectionChanged(part, selection);
return;
}
super.selectionChanged(part, selection);
}
| public void selectionChanged(IWorkbenchPart part, ISelection selection) {
Object selected = ((StructuredSelection)selection).getFirstElement();
if (selected instanceof XSDBaseAdapter)
{
XSDBaseAdapter adapter = (XSDBaseAdapter)selected;
if (oldSelection != null)
{
oldSelection.unregisterListener(this);
if (oldSelection instanceof XSDElementDeclarationAdapter)
{
XSDElementDeclaration elem = (XSDElementDeclaration)((XSDElementDeclarationAdapter)oldSelection).getTarget();
Adapter adap = XSDAdapterFactory.getInstance().adapt(elem.getContainer());
if (adap instanceof XSDParticleAdapter)
{
XSDParticleAdapter particleAdapter = (XSDParticleAdapter)adap;
particleAdapter.unregisterListener(this);
}
}
}
if (adapter instanceof XSDElementDeclarationAdapter)
{
XSDElementDeclaration elem = (XSDElementDeclaration)((XSDElementDeclarationAdapter)adapter).getTarget();
Adapter adap = XSDAdapterFactory.getInstance().adapt(elem.getContainer());
if (adap instanceof XSDParticleAdapter)
{
XSDParticleAdapter particleAdapter = (XSDParticleAdapter)adap;
particleAdapter.registerListener(this);
}
if (elem.isElementDeclarationReference())
{
XSDElementDeclarationAdapter resolvedElementAdapter = (XSDElementDeclarationAdapter)XSDAdapterFactory.getInstance().adapt(elem.getResolvedElementDeclaration());
resolvedElementAdapter.registerListener(this);
}
}
adapter.registerListener(this);
oldSelection = adapter;
Object model = adapter.getTarget();
if (model instanceof XSDConcreteComponent)
{
selection = new StructuredSelection((XSDConcreteComponent)model);
}
super.selectionChanged(part, selection);
return;
}
super.selectionChanged(part, selection);
}
|
diff --git a/src/main/java/org/qburst/search/controller/SearchController.java b/src/main/java/org/qburst/search/controller/SearchController.java
index caae8e6..d8ac019 100644
--- a/src/main/java/org/qburst/search/controller/SearchController.java
+++ b/src/main/java/org/qburst/search/controller/SearchController.java
@@ -1,126 +1,128 @@
/**
*
*/
package org.qburst.search.controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocumentList;
import org.codehaus.jackson.map.ObjectMapper;
import org.qburst.search.model.Search;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* @author Cyril
*
*/
@Controller
public class SearchController {
private ObjectMapper mapper = new ObjectMapper();
public SearchController() {
}
@RequestMapping(value = "/search", method = RequestMethod.GET)
public @ResponseBody
String listNewJoinee(
@RequestParam(required = true, value = "query") String q) {
String jsonData = "";
try {
HttpSolrServer solr = new HttpSolrServer(
"http://10.4.0.56:8983/solr");
SolrQuery query = new SolrQuery();
query.setQuery(q);
query.setFields("content", "author", "url", "title");
query.setHighlight(true);
query.addHighlightField("content");
- query.setHighlightSnippets(3);
+ query.setHighlightSnippets(1000);
+ query.setHighlightSimplePost("</span>");
+ query.setHighlightSimplePre("<span class='label label-important'>");
QueryResponse response = solr.query(query);
SolrDocumentList results = response.getResults();
Map<String, Map<String, List<String>>> highlights = response
.getHighlighting();
ArrayList<Search> mySearch = new ArrayList<Search>();
int idx = 0;
for (String key : highlights.keySet()) {
List<String> data = highlights.get(key).get("content");
if (data != null) {
Search s = new Search();
s.setHighlights(data);
s.setId(key);
s.setAuthor(results.get(idx).containsKey("author") ? stringify(results
.get(idx).get("author")) : "");
s.setUrl(results.get(idx).containsKey("url") ? results
.get(idx).get("url").toString() : "");
s.setTitle(results.get(idx).containsKey("title") ? stringify(results
.get(idx).get("title")) : "");
mySearch.add(s);
}
idx++;
}
ObjectMapper mapper = new ObjectMapper();
jsonData = mapper.writeValueAsString(mySearch);
solr.shutdown();
} catch (Exception e) {
e.printStackTrace();
}
String a = "aaData";
return "{" + '"' + a + '"' + ":" + jsonData + "}";
}
private String stringify(Object ary) {
String ret = "";
if (ary != null && ary instanceof ArrayList) {
ArrayList objects = (ArrayList) ary;
ret = StringUtils.arrayToDelimitedString(objects.toArray(), ", ");
}
return ret;
}
@RequestMapping(value = "/export", method = RequestMethod.GET)
public void doDownload(HttpServletRequest request,HttpServletResponse response,@RequestParam(required = true, value = "filePath") String filePath)
throws IOException {
int BUFFER_SIZE = 4096;
ServletContext context = request.getServletContext();
File downloadFile = new File(filePath);
if(downloadFile.exists()){
String appPath = context.getRealPath("");
String fullPath = appPath + filePath;
FileInputStream inputStream = new FileInputStream(downloadFile);
String mimeType = context.getMimeType(fullPath);
if (mimeType == null) {
mimeType = "application/pdf";
}
response.setContentType(mimeType);
response.setContentLength((int) downloadFile.length());
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"",downloadFile.getName());
response.setHeader(headerKey, headerValue);
OutputStream outStream = response.getOutputStream();
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outStream.write(buffer, 0, bytesRead);
}
inputStream.close();
outStream.close();
}
}
}
| true | true | String listNewJoinee(
@RequestParam(required = true, value = "query") String q) {
String jsonData = "";
try {
HttpSolrServer solr = new HttpSolrServer(
"http://10.4.0.56:8983/solr");
SolrQuery query = new SolrQuery();
query.setQuery(q);
query.setFields("content", "author", "url", "title");
query.setHighlight(true);
query.addHighlightField("content");
query.setHighlightSnippets(3);
QueryResponse response = solr.query(query);
SolrDocumentList results = response.getResults();
Map<String, Map<String, List<String>>> highlights = response
.getHighlighting();
ArrayList<Search> mySearch = new ArrayList<Search>();
int idx = 0;
for (String key : highlights.keySet()) {
List<String> data = highlights.get(key).get("content");
if (data != null) {
Search s = new Search();
s.setHighlights(data);
s.setId(key);
s.setAuthor(results.get(idx).containsKey("author") ? stringify(results
.get(idx).get("author")) : "");
s.setUrl(results.get(idx).containsKey("url") ? results
.get(idx).get("url").toString() : "");
s.setTitle(results.get(idx).containsKey("title") ? stringify(results
.get(idx).get("title")) : "");
mySearch.add(s);
}
idx++;
}
ObjectMapper mapper = new ObjectMapper();
jsonData = mapper.writeValueAsString(mySearch);
solr.shutdown();
} catch (Exception e) {
e.printStackTrace();
}
String a = "aaData";
return "{" + '"' + a + '"' + ":" + jsonData + "}";
}
| String listNewJoinee(
@RequestParam(required = true, value = "query") String q) {
String jsonData = "";
try {
HttpSolrServer solr = new HttpSolrServer(
"http://10.4.0.56:8983/solr");
SolrQuery query = new SolrQuery();
query.setQuery(q);
query.setFields("content", "author", "url", "title");
query.setHighlight(true);
query.addHighlightField("content");
query.setHighlightSnippets(1000);
query.setHighlightSimplePost("</span>");
query.setHighlightSimplePre("<span class='label label-important'>");
QueryResponse response = solr.query(query);
SolrDocumentList results = response.getResults();
Map<String, Map<String, List<String>>> highlights = response
.getHighlighting();
ArrayList<Search> mySearch = new ArrayList<Search>();
int idx = 0;
for (String key : highlights.keySet()) {
List<String> data = highlights.get(key).get("content");
if (data != null) {
Search s = new Search();
s.setHighlights(data);
s.setId(key);
s.setAuthor(results.get(idx).containsKey("author") ? stringify(results
.get(idx).get("author")) : "");
s.setUrl(results.get(idx).containsKey("url") ? results
.get(idx).get("url").toString() : "");
s.setTitle(results.get(idx).containsKey("title") ? stringify(results
.get(idx).get("title")) : "");
mySearch.add(s);
}
idx++;
}
ObjectMapper mapper = new ObjectMapper();
jsonData = mapper.writeValueAsString(mySearch);
solr.shutdown();
} catch (Exception e) {
e.printStackTrace();
}
String a = "aaData";
return "{" + '"' + a + '"' + ":" + jsonData + "}";
}
|
diff --git a/geocoder/src/main/java/cz/opendata/linked/geocoder/Extractor.java b/geocoder/src/main/java/cz/opendata/linked/geocoder/Extractor.java
index 52d0fc32..347ea7e8 100644
--- a/geocoder/src/main/java/cz/opendata/linked/geocoder/Extractor.java
+++ b/geocoder/src/main/java/cz/opendata/linked/geocoder/Extractor.java
@@ -1,166 +1,168 @@
package cz.opendata.linked.geocoder;
import java.io.File;
import org.openrdf.model.URI;
import org.openrdf.model.vocabulary.RDF;
import org.openrdf.query.BindingSet;
import org.openrdf.query.QueryEvaluationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cz.cuni.mff.xrg.odcs.commons.dpu.DPU;
import cz.cuni.mff.xrg.odcs.commons.dpu.DPUContext;
import cz.cuni.mff.xrg.odcs.commons.dpu.DPUException;
import cz.cuni.mff.xrg.odcs.commons.dpu.annotation.AsExtractor;
import cz.cuni.mff.xrg.odcs.commons.dpu.annotation.InputDataUnit;
import cz.cuni.mff.xrg.odcs.commons.dpu.annotation.OutputDataUnit;
import cz.cuni.mff.xrg.odcs.commons.message.MessageType;
import cz.cuni.mff.xrg.odcs.commons.module.dpu.ConfigurableBase;
import cz.cuni.mff.xrg.odcs.commons.web.AbstractConfigDialog;
import cz.cuni.mff.xrg.odcs.commons.web.ConfigDialogProvider;
import cz.cuni.mff.xrg.odcs.rdf.exceptions.InvalidQueryException;
import cz.cuni.mff.xrg.odcs.rdf.impl.MyTupleQueryResult;
import cz.cuni.mff.xrg.odcs.rdf.interfaces.RDFDataUnit;
import cz.opendata.linked.geocoder.lib.Geocoder;
import cz.opendata.linked.geocoder.lib.Geocoder.GeoProvider;
import cz.opendata.linked.geocoder.lib.Geocoder.GeoProviderFactory;
import cz.opendata.linked.geocoder.lib.Position;
@AsExtractor
public class Extractor
extends ConfigurableBase<ExtractorConfig>
implements DPU, ConfigDialogProvider<ExtractorConfig> {
/**
* DPU's configuration.
*/
private Logger logger = LoggerFactory.getLogger(DPU.class);
@InputDataUnit(name = "Schema.org addresses")
public RDFDataUnit sAddresses;
@OutputDataUnit(name = "Geocoordinates")
public RDFDataUnit outGeo;
public Extractor() {
super(ExtractorConfig.class);
}
@Override
public AbstractConfigDialog<ExtractorConfig> getConfigurationDialog() {
return new ExtractorDialog();
}
public void execute(DPUContext ctx) throws DPUException
{
java.util.Date date = new java.util.Date();
long start = date.getTime();
URI geoURI = outGeo.createURI("http://schema.org/geo");
URI geocoordsURI = outGeo.createURI("http://schema.org/GeoCoordinates");
URI xsdDouble = outGeo.createURI("http://www.w3.org/2001/XMLSchema#double");
URI longURI = outGeo.createURI("http://schema.org/longitude");
URI latURI = outGeo.createURI("http://schema.org/latitude");
String geoCache = new File(ctx.getGlobalDirectory(), "cache/geocoder.cache").getAbsolutePath();
String sOrgQuery = "PREFIX s: <http://schema.org/> "
+ "SELECT DISTINCT * "
+ "WHERE "
+ "{"
+ "?address a s:PostalAddress . "
+ "OPTIONAL { ?address s:streetAddress ?street . } "
+ "OPTIONAL { ?address s:addressRegion ?region . } "
+ "OPTIONAL { ?address s:addressLocality ?locality . } "
+ "OPTIONAL { ?address s:postalCode ?postal . } "
+ "OPTIONAL { ?address s:addressCountry ?country . } "
+ ". }";
logger.debug("Geocoder init");
Geocoder.loadCacheIfEmpty(geoCache);
GeoProvider gisgraphy = GeoProviderFactory.createXMLGeoProvider(
config.geocoderURI + "/fulltext/fulltextsearch?allwordsrequired=false&from=1&to=1&q=",
"/response/result/doc[1]/double[@name=\"lat\"]",
"/response/result/doc[1]/double[@name=\"lng\"]",
0);
logger.debug("Geocoder initialized");
int count = 0;
int failed = 0;
try {
//Schema.org addresses
logger.debug("Executing Schema.org query: " + sOrgQuery);
MyTupleQueryResult res = sAddresses.executeSelectQueryAsTuples(sOrgQuery);
logger.debug("Starting geocoding.");
String[] props = new String [] {"street", "locality", "region", "postal", "country"};
while (res.hasNext())
{
count++;
BindingSet s = res.next();
StringBuilder addressToGeoCode = new StringBuilder();
for (String currentBinding : props)
{
if (s.hasBinding(currentBinding))
{
addressToGeoCode.append(s.getValue(currentBinding).stringValue());
addressToGeoCode.append(" ");
}
}
String address = addressToGeoCode.toString();
logger.debug("Address to geocode (" + count + "): " + address);
Position pos = Geocoder.locate(address, gisgraphy);
Double latitude = null;
Double longitude = null;
if (pos != null)
{
latitude = pos.getLatitude();
longitude = pos.getLongitude();
logger.debug("Located " + address + " Latitude: " + latitude + " Longitude: " + longitude);
String uri = s.getValue("address").stringValue();
URI addressURI = outGeo.createURI(uri);
URI coordURI = outGeo.createURI(uri+"/geocoordinates");
outGeo.addTriple(addressURI, geoURI , coordURI);
outGeo.addTriple(coordURI, RDF.TYPE, geocoordsURI);
outGeo.addTriple(coordURI, longURI, outGeo.createLiteral(longitude.toString(), xsdDouble));
outGeo.addTriple(coordURI, latURI, outGeo.createLiteral(latitude.toString(), xsdDouble));
}
else {
failed++;
logger.warn("Failed to locate: " + address);
}
}
} catch (InvalidQueryException e) {
logger.error(e.getLocalizedMessage());
} catch (QueryEvaluationException e) {
logger.error(e.getLocalizedMessage());
}
logger.info("Geocoding done.");
- logger.debug("Saving geo cache");
- Geocoder.saveCache(geoCache);
- logger.debug("Geo cache saved.");
+ if (config.rewriteCache) {
+ logger.debug("Saving geo cache");
+ Geocoder.saveCache(geoCache);
+ logger.debug("Geo cache saved.");
+ }
java.util.Date date2 = new java.util.Date();
long end = date2.getTime();
ctx.sendMessage(MessageType.INFO, "Processed " + count + " in " + (end-start) + "ms, failed attempts: " + failed);
}
@Override
public void cleanUp() { }
}
| true | true | public void execute(DPUContext ctx) throws DPUException
{
java.util.Date date = new java.util.Date();
long start = date.getTime();
URI geoURI = outGeo.createURI("http://schema.org/geo");
URI geocoordsURI = outGeo.createURI("http://schema.org/GeoCoordinates");
URI xsdDouble = outGeo.createURI("http://www.w3.org/2001/XMLSchema#double");
URI longURI = outGeo.createURI("http://schema.org/longitude");
URI latURI = outGeo.createURI("http://schema.org/latitude");
String geoCache = new File(ctx.getGlobalDirectory(), "cache/geocoder.cache").getAbsolutePath();
String sOrgQuery = "PREFIX s: <http://schema.org/> "
+ "SELECT DISTINCT * "
+ "WHERE "
+ "{"
+ "?address a s:PostalAddress . "
+ "OPTIONAL { ?address s:streetAddress ?street . } "
+ "OPTIONAL { ?address s:addressRegion ?region . } "
+ "OPTIONAL { ?address s:addressLocality ?locality . } "
+ "OPTIONAL { ?address s:postalCode ?postal . } "
+ "OPTIONAL { ?address s:addressCountry ?country . } "
+ ". }";
logger.debug("Geocoder init");
Geocoder.loadCacheIfEmpty(geoCache);
GeoProvider gisgraphy = GeoProviderFactory.createXMLGeoProvider(
config.geocoderURI + "/fulltext/fulltextsearch?allwordsrequired=false&from=1&to=1&q=",
"/response/result/doc[1]/double[@name=\"lat\"]",
"/response/result/doc[1]/double[@name=\"lng\"]",
0);
logger.debug("Geocoder initialized");
int count = 0;
int failed = 0;
try {
//Schema.org addresses
logger.debug("Executing Schema.org query: " + sOrgQuery);
MyTupleQueryResult res = sAddresses.executeSelectQueryAsTuples(sOrgQuery);
logger.debug("Starting geocoding.");
String[] props = new String [] {"street", "locality", "region", "postal", "country"};
while (res.hasNext())
{
count++;
BindingSet s = res.next();
StringBuilder addressToGeoCode = new StringBuilder();
for (String currentBinding : props)
{
if (s.hasBinding(currentBinding))
{
addressToGeoCode.append(s.getValue(currentBinding).stringValue());
addressToGeoCode.append(" ");
}
}
String address = addressToGeoCode.toString();
logger.debug("Address to geocode (" + count + "): " + address);
Position pos = Geocoder.locate(address, gisgraphy);
Double latitude = null;
Double longitude = null;
if (pos != null)
{
latitude = pos.getLatitude();
longitude = pos.getLongitude();
logger.debug("Located " + address + " Latitude: " + latitude + " Longitude: " + longitude);
String uri = s.getValue("address").stringValue();
URI addressURI = outGeo.createURI(uri);
URI coordURI = outGeo.createURI(uri+"/geocoordinates");
outGeo.addTriple(addressURI, geoURI , coordURI);
outGeo.addTriple(coordURI, RDF.TYPE, geocoordsURI);
outGeo.addTriple(coordURI, longURI, outGeo.createLiteral(longitude.toString(), xsdDouble));
outGeo.addTriple(coordURI, latURI, outGeo.createLiteral(latitude.toString(), xsdDouble));
}
else {
failed++;
logger.warn("Failed to locate: " + address);
}
}
} catch (InvalidQueryException e) {
logger.error(e.getLocalizedMessage());
} catch (QueryEvaluationException e) {
logger.error(e.getLocalizedMessage());
}
logger.info("Geocoding done.");
logger.debug("Saving geo cache");
Geocoder.saveCache(geoCache);
logger.debug("Geo cache saved.");
java.util.Date date2 = new java.util.Date();
long end = date2.getTime();
ctx.sendMessage(MessageType.INFO, "Processed " + count + " in " + (end-start) + "ms, failed attempts: " + failed);
}
| public void execute(DPUContext ctx) throws DPUException
{
java.util.Date date = new java.util.Date();
long start = date.getTime();
URI geoURI = outGeo.createURI("http://schema.org/geo");
URI geocoordsURI = outGeo.createURI("http://schema.org/GeoCoordinates");
URI xsdDouble = outGeo.createURI("http://www.w3.org/2001/XMLSchema#double");
URI longURI = outGeo.createURI("http://schema.org/longitude");
URI latURI = outGeo.createURI("http://schema.org/latitude");
String geoCache = new File(ctx.getGlobalDirectory(), "cache/geocoder.cache").getAbsolutePath();
String sOrgQuery = "PREFIX s: <http://schema.org/> "
+ "SELECT DISTINCT * "
+ "WHERE "
+ "{"
+ "?address a s:PostalAddress . "
+ "OPTIONAL { ?address s:streetAddress ?street . } "
+ "OPTIONAL { ?address s:addressRegion ?region . } "
+ "OPTIONAL { ?address s:addressLocality ?locality . } "
+ "OPTIONAL { ?address s:postalCode ?postal . } "
+ "OPTIONAL { ?address s:addressCountry ?country . } "
+ ". }";
logger.debug("Geocoder init");
Geocoder.loadCacheIfEmpty(geoCache);
GeoProvider gisgraphy = GeoProviderFactory.createXMLGeoProvider(
config.geocoderURI + "/fulltext/fulltextsearch?allwordsrequired=false&from=1&to=1&q=",
"/response/result/doc[1]/double[@name=\"lat\"]",
"/response/result/doc[1]/double[@name=\"lng\"]",
0);
logger.debug("Geocoder initialized");
int count = 0;
int failed = 0;
try {
//Schema.org addresses
logger.debug("Executing Schema.org query: " + sOrgQuery);
MyTupleQueryResult res = sAddresses.executeSelectQueryAsTuples(sOrgQuery);
logger.debug("Starting geocoding.");
String[] props = new String [] {"street", "locality", "region", "postal", "country"};
while (res.hasNext())
{
count++;
BindingSet s = res.next();
StringBuilder addressToGeoCode = new StringBuilder();
for (String currentBinding : props)
{
if (s.hasBinding(currentBinding))
{
addressToGeoCode.append(s.getValue(currentBinding).stringValue());
addressToGeoCode.append(" ");
}
}
String address = addressToGeoCode.toString();
logger.debug("Address to geocode (" + count + "): " + address);
Position pos = Geocoder.locate(address, gisgraphy);
Double latitude = null;
Double longitude = null;
if (pos != null)
{
latitude = pos.getLatitude();
longitude = pos.getLongitude();
logger.debug("Located " + address + " Latitude: " + latitude + " Longitude: " + longitude);
String uri = s.getValue("address").stringValue();
URI addressURI = outGeo.createURI(uri);
URI coordURI = outGeo.createURI(uri+"/geocoordinates");
outGeo.addTriple(addressURI, geoURI , coordURI);
outGeo.addTriple(coordURI, RDF.TYPE, geocoordsURI);
outGeo.addTriple(coordURI, longURI, outGeo.createLiteral(longitude.toString(), xsdDouble));
outGeo.addTriple(coordURI, latURI, outGeo.createLiteral(latitude.toString(), xsdDouble));
}
else {
failed++;
logger.warn("Failed to locate: " + address);
}
}
} catch (InvalidQueryException e) {
logger.error(e.getLocalizedMessage());
} catch (QueryEvaluationException e) {
logger.error(e.getLocalizedMessage());
}
logger.info("Geocoding done.");
if (config.rewriteCache) {
logger.debug("Saving geo cache");
Geocoder.saveCache(geoCache);
logger.debug("Geo cache saved.");
}
java.util.Date date2 = new java.util.Date();
long end = date2.getTime();
ctx.sendMessage(MessageType.INFO, "Processed " + count + " in " + (end-start) + "ms, failed attempts: " + failed);
}
|
diff --git a/src/com/android/browser/ShortcutActivity.java b/src/com/android/browser/ShortcutActivity.java
index 612116e1..56e9c30b 100644
--- a/src/com/android/browser/ShortcutActivity.java
+++ b/src/com/android/browser/ShortcutActivity.java
@@ -1,73 +1,72 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* 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.android.browser;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
public class ShortcutActivity extends Activity
implements BookmarksPageCallbacks, OnClickListener {
private BrowserBookmarksPage mBookmarks;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
- // TODO: Is this needed?
- setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
+ setTitle(R.string.shortcut_bookmark_title);
setContentView(R.layout.pick_bookmark);
mBookmarks = (BrowserBookmarksPage) getFragmentManager()
.findFragmentById(R.id.bookmarks);
mBookmarks.setEnableContextMenu(false);
mBookmarks.setCallbackListener(this);
View cancel = findViewById(R.id.cancel);
if (cancel != null) {
cancel.setOnClickListener(this);
}
}
// BookmarksPageCallbacks
@Override
public boolean onBookmarkSelected(Cursor c, boolean isFolder) {
if (isFolder) {
return false;
}
Intent intent = BrowserBookmarksPage.createShortcutIntent(this, c);
setResult(RESULT_OK, intent);
finish();
return true;
}
@Override
public boolean onOpenInNewWindow(String... urls) {
return false;
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.cancel:
finish();
break;
}
}
}
| true | true | protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// TODO: Is this needed?
setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
setContentView(R.layout.pick_bookmark);
mBookmarks = (BrowserBookmarksPage) getFragmentManager()
.findFragmentById(R.id.bookmarks);
mBookmarks.setEnableContextMenu(false);
mBookmarks.setCallbackListener(this);
View cancel = findViewById(R.id.cancel);
if (cancel != null) {
cancel.setOnClickListener(this);
}
}
| protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle(R.string.shortcut_bookmark_title);
setContentView(R.layout.pick_bookmark);
mBookmarks = (BrowserBookmarksPage) getFragmentManager()
.findFragmentById(R.id.bookmarks);
mBookmarks.setEnableContextMenu(false);
mBookmarks.setCallbackListener(this);
View cancel = findViewById(R.id.cancel);
if (cancel != null) {
cancel.setOnClickListener(this);
}
}
|
diff --git a/de.gebit.integrity.dsl/src/de/gebit/integrity/utils/DateUtil.java b/de.gebit.integrity.dsl/src/de/gebit/integrity/utils/DateUtil.java
index 113c93f7..b155ecc4 100644
--- a/de.gebit.integrity.dsl/src/de/gebit/integrity/utils/DateUtil.java
+++ b/de.gebit.integrity.dsl/src/de/gebit/integrity/utils/DateUtil.java
@@ -1,376 +1,376 @@
/*******************************************************************************
* Copyright (c) 2013 Rene Schneider, GEBIT Solutions GmbH 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 de.gebit.integrity.utils;
import java.lang.reflect.Field;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import de.gebit.integrity.dsl.DateAndTimeValue;
import de.gebit.integrity.dsl.DateValue;
import de.gebit.integrity.dsl.EuropeanDateAnd12HrsTimeValue;
import de.gebit.integrity.dsl.EuropeanDateAnd24HrsTimeValue;
import de.gebit.integrity.dsl.EuropeanDateValue;
import de.gebit.integrity.dsl.IsoDateAndTimeValue;
import de.gebit.integrity.dsl.IsoDateValue;
import de.gebit.integrity.dsl.IsoTimeValue;
import de.gebit.integrity.dsl.Simple12HrsTimeValue;
import de.gebit.integrity.dsl.Simple24HrsTimeValue;
import de.gebit.integrity.dsl.TimeValue;
import de.gebit.integrity.dsl.USDateAnd12HrsTimeValue;
import de.gebit.integrity.dsl.USDateValue;
/**
* A utility class to handle date/time parsing and other date stuff. Sorry for the uglyness, but date/time handling just
* IS ugly crap, especially when using Java's built-in functionality :-(.
*
* @author Rene Schneider - initial API and implementation
*
*/
public final class DateUtil {
private DateUtil() {
// nothing to do
}
/**
* Creates a preconfigured {@link SimpleDateFormat} for the given format string which can be used by the class
* internally.
*
* @param aFormatString
* the format string to use
* @return the date format instance
*/
private static SimpleDateFormat getSimpleDateFormat(String aFormatString) {
SimpleDateFormat tempFormat = new SimpleDateFormat(aFormatString);
tempFormat.setLenient(false);
return tempFormat;
}
/**
* Converts a given date value to a {@link Calendar}.
*
* @param aValue
* the date value
* @return the calendar set to the specified date
* @throws ParseException
* if the value cannot be parsed because it is of wrong format or depicts an illegal date/time
*/
public static Calendar convertDateValue(DateValue aValue) throws ParseException {
if (aValue instanceof IsoDateValue) {
return parseIsoDateAndTimeString(aValue.getDateValue(), null);
} else if (aValue instanceof EuropeanDateValue) {
return parseDateOrTimeString(aValue.getDateValue(), "dd.MM.yyyy");
} else if (aValue instanceof USDateValue) {
return parseDateOrTimeString(aValue.getDateValue(), "MM/dd/yyyy");
} else {
throw new UnsupportedOperationException("Someone forgot to implement a new date format!");
}
}
/**
* Converts a given time value to a {@link Calendar}.
*
* @param aValue
* the time value
* @return the calendar set to the specified date
* @throws ParseException
* if the value cannot be parsed because it is of wrong format or depicts an illegal date/time
*/
public static Calendar convertTimeValue(TimeValue aValue) throws ParseException {
if (aValue instanceof IsoTimeValue) {
return parseIsoDateAndTimeString(null, aValue.getTimeValue());
} else if (aValue instanceof Simple24HrsTimeValue) {
return parseEuropeanDateAnd24HrsTimeString(null, aValue.getTimeValue());
} else if (aValue instanceof Simple12HrsTimeValue) {
return parseEuropeanDateAnd12HrsTimeString(null, aValue.getTimeValue());
} else {
throw new UnsupportedOperationException("Someone forgot to implement a new time format!");
}
}
/**
* Converts a given date and time to a {@link Calendar}.
*
* @param aValue
* the date value
* @return the calendar set to the specified date
* @throws ParseException
* if the value cannot be parsed because it is of wrong format or depicts an illegal date/time
*/
public static Calendar convertDateAndTimeValue(DateAndTimeValue aValue) throws ParseException {
if (aValue instanceof IsoDateAndTimeValue) {
return parseIsoDateAndTimeString(aValue.getDateValue(), aValue.getTimeValue());
} else if (aValue instanceof EuropeanDateAnd24HrsTimeValue) {
return parseEuropeanDateAnd24HrsTimeString(aValue.getDateValue(), aValue.getTimeValue());
} else if (aValue instanceof EuropeanDateAnd12HrsTimeValue) {
return parseEuropeanDateAnd12HrsTimeString(aValue.getDateValue(), aValue.getTimeValue());
} else if (aValue instanceof USDateAnd12HrsTimeValue) {
return parseUSDateAnd12HrsTimeString(aValue.getDateValue(), aValue.getTimeValue());
} else {
throw new UnsupportedOperationException("Someone forgot to implement a new time format!");
}
}
/**
* Strips the time information from a given {@link Date} (sets all time fields to zero).
*
* @param aDate
* the date
* @return a new Date without time information
*/
public static Date stripTimeFromDate(Date aDate) {
Calendar tempCalendar = Calendar.getInstance();
tempCalendar.setTime(aDate);
tempCalendar.set(Calendar.HOUR_OF_DAY, 0);
tempCalendar.set(Calendar.MINUTE, 0);
tempCalendar.set(Calendar.SECOND, 0);
tempCalendar.set(Calendar.MILLISECOND, 0);
return tempCalendar.getTime();
}
/**
* Strips the date information from a given {@link Date} (sets all time fields to zero).
*
* @param aTime
* the time
* @return a new Time without the date information
*/
public static Date stripDateFromTime(Date aTime) {
if (aTime == null) {
return null;
}
Calendar tempCalendar = Calendar.getInstance();
tempCalendar.setTime(aTime);
tempCalendar.set(Calendar.YEAR, 0);
tempCalendar.set(Calendar.MONTH, 0);
tempCalendar.set(Calendar.DAY_OF_MONTH, 0);
return tempCalendar.getTime();
}
private static Calendar parseDateOrTimeString(String aDateString, String aFormatString) throws ParseException {
Calendar tempCalendar = Calendar.getInstance();
tempCalendar.setTime(getSimpleDateFormat(aFormatString).parse(aDateString));
return tempCalendar;
}
private static Calendar parseEuropeanDateAnd24HrsTimeString(String aDateString, String aTimeString)
throws ParseException {
String tempStringToParse;
if (aDateString != null) {
tempStringToParse = aDateString;
} else {
// use the common "zero" date if no date was given.
tempStringToParse = "01.01.1970";
}
// append a divider
tempStringToParse += "T";
if (aTimeString.length() < 6) {
// append seconds if they're not given; they're optional, but if not present :00 is assumed
tempStringToParse += aTimeString + ":00.000";
} else {
if (aTimeString.length() < 9) {
// append milliseconds if they're not given
tempStringToParse += aTimeString + ".000";
} else {
tempStringToParse += aTimeString;
}
}
return parseDateOrTimeString(tempStringToParse, "dd.MM.yyyy'T'HH:mm:ss.SSS");
}
private static Calendar parseEuropeanDateAnd12HrsTimeString(String aDateString, String aTimeString)
throws ParseException {
String tempStringToParse;
if (aDateString != null) {
tempStringToParse = aDateString;
} else {
// use the common "zero" date if no date was given.
tempStringToParse = "01.01.1970";
}
// append a divider
tempStringToParse += "T";
if (aTimeString.length() < 8) {
// inject seconds if they're not given; they're optional, but if not present :00 is assumed
tempStringToParse += aTimeString.substring(0, aTimeString.length() - 2) + ":00.000"
+ aTimeString.substring(aTimeString.length() - 2);
} else {
if (aTimeString.length() < 11) {
// inject just milliseconds
tempStringToParse += aTimeString.substring(0, aTimeString.length() - 2) + ".000"
+ aTimeString.substring(aTimeString.length() - 2);
} else {
tempStringToParse += aTimeString;
}
}
return parseDateOrTimeString(tempStringToParse, "dd.MM.yyyy'T'hh:mm:ss.SSSaa");
}
private static Calendar parseUSDateAnd12HrsTimeString(String aDateString, String aTimeString) throws ParseException {
String tempStringToParse;
if (aDateString != null) {
tempStringToParse = aDateString;
} else {
// use the common "zero" date if no date was given.
tempStringToParse = "01/01/1970";
}
// append a divider
tempStringToParse += "T";
if (aTimeString.length() < 8) {
// inject seconds if they're not given; they're optional, but if not present :00 is assumed
tempStringToParse += aTimeString.substring(0, aTimeString.length() - 2) + ":00.000"
+ aTimeString.substring(aTimeString.length() - 2);
} else {
if (aTimeString.length() < 11) {
// inject just milliseconds
tempStringToParse += aTimeString.substring(0, aTimeString.length() - 2) + ".000"
+ aTimeString.substring(aTimeString.length() - 2);
} else {
tempStringToParse += aTimeString;
}
}
return parseDateOrTimeString(tempStringToParse, "MM/dd/yyyy'T'hh:mm:ss.SSSaa");
}
private static Calendar parseIsoDateAndTimeString(String aDateString, String aTimeString) throws ParseException {
String tempDateValue = aDateString;
if (tempDateValue == null) {
// in case no date is given, use the "zero" date
tempDateValue = "1970-01-01";
}
String tempTimeValue;
if (aTimeString == null) {
// in case no time is given, use the "zero" time
tempTimeValue = "T00:00:00.000";
} else {
tempTimeValue = aTimeString;
if (!tempTimeValue.startsWith("T")) {
tempTimeValue = "T" + tempTimeValue;
}
// handle Zulu time
tempTimeValue = tempTimeValue.replace("Z", "+0000");
}
boolean tempHasTimezone = tempTimeValue.contains("+") | tempTimeValue.contains("-");
boolean tempHasSeconds = (!tempHasTimezone && tempTimeValue.length() > 6)
| (tempHasTimezone && tempTimeValue.length() > 12);
if (tempHasTimezone) {
if (tempTimeValue.charAt(tempTimeValue.length() - 3) == ':') {
// remove the optional colon in the timezone, if present
tempTimeValue = tempTimeValue.substring(0, tempTimeValue.length() - 3)
+ tempTimeValue.substring(tempTimeValue.length() - 2, tempTimeValue.length());
}
}
if (tempHasSeconds) {
if (!tempTimeValue.contains(".")) {
// inject milliseconds, if none are present but seconds are given
if (tempHasTimezone) {
- tempTimeValue = tempTimeValue.substring(0, aTimeString.length() - 4) + ".000"
- + tempTimeValue.substring(aTimeString.length() - 4);
+ tempTimeValue = tempTimeValue.substring(0, tempTimeValue.length() - 5) + ".000"
+ + tempTimeValue.substring(tempTimeValue.length() - 5);
} else {
tempTimeValue += ".000";
}
}
}
Calendar tempCalendar;
if (tempHasTimezone) {
if (tempTimeValue.charAt(tempTimeValue.length() - 3) == ':') {
// remove the optional colon in the timezone, if present
tempTimeValue = tempTimeValue.substring(0, tempTimeValue.length() - 3)
+ tempTimeValue.substring(tempTimeValue.length() - 2, tempTimeValue.length());
}
tempCalendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"
+ tempTimeValue.substring(tempHasSeconds ? 9 : 6)));
if (tempHasSeconds) {
tempCalendar.setTime(getSimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ").parse(
tempDateValue + tempTimeValue));
} else {
tempCalendar.setTime(getSimpleDateFormat("yyyy-MM-dd'T'HH:mmZ").parse(tempDateValue + tempTimeValue));
}
} else {
tempCalendar = Calendar.getInstance();
if (tempHasSeconds) {
tempCalendar.setTime(getSimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS").parse(
tempDateValue + tempTimeValue));
} else {
tempCalendar.setTime(getSimpleDateFormat("yyyy-MM-dd'T'HH:mm").parse(tempDateValue + tempTimeValue));
}
}
return tempCalendar;
}
/**
* Performs date formatting using the provided format, but injects millisecond precision if the millisecond value is
* not "000". This is intended to be used with the standard date/time formats returned by DateFormat factory
* methods, which don't include milliseconds in most cases unfortunately. It employs a rather ugly hack to enhance
* the pattern which only works with {@link SimpleDateFormat}, but as far as I know there's no better method to
* achieve this result.
*
* @param aFormat
* the base format
* @param aDate
* the date to format
* @return the formatted string
*/
public static String formatDateWithMilliseconds(DateFormat aFormat, Date aDate) {
DateFormat tempFormat = aFormat;
if (aDate.getTime() % 1000 != 0) {
if (aFormat instanceof SimpleDateFormat) {
Field tempField;
try {
tempField = SimpleDateFormat.class.getDeclaredField("pattern");
tempField.setAccessible(true);
String tempPattern = (String) tempField.get(aFormat);
tempPattern = tempPattern.replace(":ss", ":ss.SSS");
tempFormat = new SimpleDateFormat(tempPattern);
} catch (SecurityException exc) {
exc.printStackTrace();
} catch (NoSuchFieldException exc) {
exc.printStackTrace();
} catch (IllegalArgumentException exc) {
exc.printStackTrace();
} catch (IllegalAccessException exc) {
exc.printStackTrace();
}
}
}
return tempFormat.format(aDate);
}
}
| true | true | private static Calendar parseIsoDateAndTimeString(String aDateString, String aTimeString) throws ParseException {
String tempDateValue = aDateString;
if (tempDateValue == null) {
// in case no date is given, use the "zero" date
tempDateValue = "1970-01-01";
}
String tempTimeValue;
if (aTimeString == null) {
// in case no time is given, use the "zero" time
tempTimeValue = "T00:00:00.000";
} else {
tempTimeValue = aTimeString;
if (!tempTimeValue.startsWith("T")) {
tempTimeValue = "T" + tempTimeValue;
}
// handle Zulu time
tempTimeValue = tempTimeValue.replace("Z", "+0000");
}
boolean tempHasTimezone = tempTimeValue.contains("+") | tempTimeValue.contains("-");
boolean tempHasSeconds = (!tempHasTimezone && tempTimeValue.length() > 6)
| (tempHasTimezone && tempTimeValue.length() > 12);
if (tempHasTimezone) {
if (tempTimeValue.charAt(tempTimeValue.length() - 3) == ':') {
// remove the optional colon in the timezone, if present
tempTimeValue = tempTimeValue.substring(0, tempTimeValue.length() - 3)
+ tempTimeValue.substring(tempTimeValue.length() - 2, tempTimeValue.length());
}
}
if (tempHasSeconds) {
if (!tempTimeValue.contains(".")) {
// inject milliseconds, if none are present but seconds are given
if (tempHasTimezone) {
tempTimeValue = tempTimeValue.substring(0, aTimeString.length() - 4) + ".000"
+ tempTimeValue.substring(aTimeString.length() - 4);
} else {
tempTimeValue += ".000";
}
}
}
Calendar tempCalendar;
if (tempHasTimezone) {
if (tempTimeValue.charAt(tempTimeValue.length() - 3) == ':') {
// remove the optional colon in the timezone, if present
tempTimeValue = tempTimeValue.substring(0, tempTimeValue.length() - 3)
+ tempTimeValue.substring(tempTimeValue.length() - 2, tempTimeValue.length());
}
tempCalendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"
+ tempTimeValue.substring(tempHasSeconds ? 9 : 6)));
if (tempHasSeconds) {
tempCalendar.setTime(getSimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ").parse(
tempDateValue + tempTimeValue));
} else {
tempCalendar.setTime(getSimpleDateFormat("yyyy-MM-dd'T'HH:mmZ").parse(tempDateValue + tempTimeValue));
}
} else {
tempCalendar = Calendar.getInstance();
if (tempHasSeconds) {
tempCalendar.setTime(getSimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS").parse(
tempDateValue + tempTimeValue));
} else {
tempCalendar.setTime(getSimpleDateFormat("yyyy-MM-dd'T'HH:mm").parse(tempDateValue + tempTimeValue));
}
}
return tempCalendar;
}
| private static Calendar parseIsoDateAndTimeString(String aDateString, String aTimeString) throws ParseException {
String tempDateValue = aDateString;
if (tempDateValue == null) {
// in case no date is given, use the "zero" date
tempDateValue = "1970-01-01";
}
String tempTimeValue;
if (aTimeString == null) {
// in case no time is given, use the "zero" time
tempTimeValue = "T00:00:00.000";
} else {
tempTimeValue = aTimeString;
if (!tempTimeValue.startsWith("T")) {
tempTimeValue = "T" + tempTimeValue;
}
// handle Zulu time
tempTimeValue = tempTimeValue.replace("Z", "+0000");
}
boolean tempHasTimezone = tempTimeValue.contains("+") | tempTimeValue.contains("-");
boolean tempHasSeconds = (!tempHasTimezone && tempTimeValue.length() > 6)
| (tempHasTimezone && tempTimeValue.length() > 12);
if (tempHasTimezone) {
if (tempTimeValue.charAt(tempTimeValue.length() - 3) == ':') {
// remove the optional colon in the timezone, if present
tempTimeValue = tempTimeValue.substring(0, tempTimeValue.length() - 3)
+ tempTimeValue.substring(tempTimeValue.length() - 2, tempTimeValue.length());
}
}
if (tempHasSeconds) {
if (!tempTimeValue.contains(".")) {
// inject milliseconds, if none are present but seconds are given
if (tempHasTimezone) {
tempTimeValue = tempTimeValue.substring(0, tempTimeValue.length() - 5) + ".000"
+ tempTimeValue.substring(tempTimeValue.length() - 5);
} else {
tempTimeValue += ".000";
}
}
}
Calendar tempCalendar;
if (tempHasTimezone) {
if (tempTimeValue.charAt(tempTimeValue.length() - 3) == ':') {
// remove the optional colon in the timezone, if present
tempTimeValue = tempTimeValue.substring(0, tempTimeValue.length() - 3)
+ tempTimeValue.substring(tempTimeValue.length() - 2, tempTimeValue.length());
}
tempCalendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"
+ tempTimeValue.substring(tempHasSeconds ? 9 : 6)));
if (tempHasSeconds) {
tempCalendar.setTime(getSimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ").parse(
tempDateValue + tempTimeValue));
} else {
tempCalendar.setTime(getSimpleDateFormat("yyyy-MM-dd'T'HH:mmZ").parse(tempDateValue + tempTimeValue));
}
} else {
tempCalendar = Calendar.getInstance();
if (tempHasSeconds) {
tempCalendar.setTime(getSimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS").parse(
tempDateValue + tempTimeValue));
} else {
tempCalendar.setTime(getSimpleDateFormat("yyyy-MM-dd'T'HH:mm").parse(tempDateValue + tempTimeValue));
}
}
return tempCalendar;
}
|
diff --git a/src/com/android/browser/AddBookmarkPage.java b/src/com/android/browser/AddBookmarkPage.java
index 7878762a..71bf481b 100644
--- a/src/com/android/browser/AddBookmarkPage.java
+++ b/src/com/android/browser/AddBookmarkPage.java
@@ -1,183 +1,183 @@
/*
* Copyright (C) 2006 The Android Open Source Project
*
* 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.android.browser;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.ParseException;
import android.net.WebAddress;
import android.os.Bundle;
import android.provider.Browser;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Date;
public class AddBookmarkPage extends Activity {
private final String LOGTAG = "Bookmarks";
private EditText mTitle;
private EditText mAddress;
private TextView mButton;
private View mCancelButton;
private boolean mEditingExisting;
private Bundle mMap;
private String mTouchIconUrl;
private Bitmap mThumbnail;
private String mOriginalUrl;
private View.OnClickListener mSaveBookmark = new View.OnClickListener() {
public void onClick(View v) {
if (save()) {
finish();
Toast.makeText(AddBookmarkPage.this, R.string.bookmark_saved,
Toast.LENGTH_LONG).show();
}
}
};
private View.OnClickListener mCancel = new View.OnClickListener() {
public void onClick(View v) {
finish();
}
};
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
requestWindowFeature(Window.FEATURE_LEFT_ICON);
setContentView(R.layout.browser_add_bookmark);
setTitle(R.string.save_to_bookmarks);
getWindow().setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, R.drawable.ic_dialog_bookmark);
String title = null;
String url = null;
mMap = getIntent().getExtras();
if (mMap != null) {
Bundle b = mMap.getBundle("bookmark");
if (b != null) {
mMap = b;
mEditingExisting = true;
setTitle(R.string.edit_bookmark);
}
title = mMap.getString("title");
url = mOriginalUrl = mMap.getString("url");
mTouchIconUrl = mMap.getString("touch_icon_url");
mThumbnail = (Bitmap) mMap.getParcelable("thumbnail");
}
mTitle = (EditText) findViewById(R.id.title);
mTitle.setText(title);
mAddress = (EditText) findViewById(R.id.address);
mAddress.setText(url);
View.OnClickListener accept = mSaveBookmark;
mButton = (TextView) findViewById(R.id.OK);
mButton.setOnClickListener(accept);
mCancelButton = findViewById(R.id.cancel);
mCancelButton.setOnClickListener(mCancel);
if (!getWindow().getDecorView().isInTouchMode()) {
mButton.requestFocus();
}
}
/**
* Save the data to the database.
* Also, change the view to dialog stating
* that the webpage has been saved.
*/
boolean save() {
String title = mTitle.getText().toString().trim();
String unfilteredUrl =
BrowserActivity.fixUrl(mAddress.getText().toString());
boolean emptyTitle = title.length() == 0;
boolean emptyUrl = unfilteredUrl.trim().length() == 0;
Resources r = getResources();
if (emptyTitle || emptyUrl) {
if (emptyTitle) {
mTitle.setError(r.getText(R.string.bookmark_needs_title));
}
if (emptyUrl) {
mAddress.setError(r.getText(R.string.bookmark_needs_url));
}
return false;
}
String url = unfilteredUrl;
try {
URI uriObj = new URI(url);
String scheme = uriObj.getScheme();
if (!("about".equals(scheme) || "data".equals(scheme)
|| "javascript".equals(scheme)
|| "file".equals(scheme) || "content".equals(scheme))) {
WebAddress address;
try {
address = new WebAddress(unfilteredUrl);
} catch (ParseException e) {
throw new URISyntaxException("", "");
}
if (address.mHost.length() == 0) {
throw new URISyntaxException("", "");
}
url = address.toString();
}
} catch (URISyntaxException e) {
mAddress.setError(r.getText(R.string.bookmark_url_not_valid));
return false;
}
try {
if (mEditingExisting) {
mMap.putString("title", title);
mMap.putString("url", url);
setResult(RESULT_OK, (new Intent()).setAction(
getIntent().toString()).putExtras(mMap));
} else {
final ContentResolver cr = getContentResolver();
// Only use mThumbnail if url and mOriginalUrl are matches.
// Otherwise the user edited the url and the thumbnail no longer applies.
- if (mOriginalUrl.equals(url)) {
+ if (url.equals(mOriginalUrl)) {
Bookmarks.addBookmark(null, cr, url, title, mThumbnail, true);
} else {
Bookmarks.addBookmark(null, cr, url, title, null, true);
}
if (mTouchIconUrl != null) {
final Cursor c =
BrowserBookmarksAdapter.queryBookmarksForUrl(
cr, null, url, true);
new DownloadTouchIcon(cr, c, url).execute(mTouchIconUrl);
}
setResult(RESULT_OK);
}
} catch (IllegalStateException e) {
setTitle(r.getText(R.string.no_database));
return false;
}
return true;
}
}
| true | true | boolean save() {
String title = mTitle.getText().toString().trim();
String unfilteredUrl =
BrowserActivity.fixUrl(mAddress.getText().toString());
boolean emptyTitle = title.length() == 0;
boolean emptyUrl = unfilteredUrl.trim().length() == 0;
Resources r = getResources();
if (emptyTitle || emptyUrl) {
if (emptyTitle) {
mTitle.setError(r.getText(R.string.bookmark_needs_title));
}
if (emptyUrl) {
mAddress.setError(r.getText(R.string.bookmark_needs_url));
}
return false;
}
String url = unfilteredUrl;
try {
URI uriObj = new URI(url);
String scheme = uriObj.getScheme();
if (!("about".equals(scheme) || "data".equals(scheme)
|| "javascript".equals(scheme)
|| "file".equals(scheme) || "content".equals(scheme))) {
WebAddress address;
try {
address = new WebAddress(unfilteredUrl);
} catch (ParseException e) {
throw new URISyntaxException("", "");
}
if (address.mHost.length() == 0) {
throw new URISyntaxException("", "");
}
url = address.toString();
}
} catch (URISyntaxException e) {
mAddress.setError(r.getText(R.string.bookmark_url_not_valid));
return false;
}
try {
if (mEditingExisting) {
mMap.putString("title", title);
mMap.putString("url", url);
setResult(RESULT_OK, (new Intent()).setAction(
getIntent().toString()).putExtras(mMap));
} else {
final ContentResolver cr = getContentResolver();
// Only use mThumbnail if url and mOriginalUrl are matches.
// Otherwise the user edited the url and the thumbnail no longer applies.
if (mOriginalUrl.equals(url)) {
Bookmarks.addBookmark(null, cr, url, title, mThumbnail, true);
} else {
Bookmarks.addBookmark(null, cr, url, title, null, true);
}
if (mTouchIconUrl != null) {
final Cursor c =
BrowserBookmarksAdapter.queryBookmarksForUrl(
cr, null, url, true);
new DownloadTouchIcon(cr, c, url).execute(mTouchIconUrl);
}
setResult(RESULT_OK);
}
} catch (IllegalStateException e) {
setTitle(r.getText(R.string.no_database));
return false;
}
return true;
}
| boolean save() {
String title = mTitle.getText().toString().trim();
String unfilteredUrl =
BrowserActivity.fixUrl(mAddress.getText().toString());
boolean emptyTitle = title.length() == 0;
boolean emptyUrl = unfilteredUrl.trim().length() == 0;
Resources r = getResources();
if (emptyTitle || emptyUrl) {
if (emptyTitle) {
mTitle.setError(r.getText(R.string.bookmark_needs_title));
}
if (emptyUrl) {
mAddress.setError(r.getText(R.string.bookmark_needs_url));
}
return false;
}
String url = unfilteredUrl;
try {
URI uriObj = new URI(url);
String scheme = uriObj.getScheme();
if (!("about".equals(scheme) || "data".equals(scheme)
|| "javascript".equals(scheme)
|| "file".equals(scheme) || "content".equals(scheme))) {
WebAddress address;
try {
address = new WebAddress(unfilteredUrl);
} catch (ParseException e) {
throw new URISyntaxException("", "");
}
if (address.mHost.length() == 0) {
throw new URISyntaxException("", "");
}
url = address.toString();
}
} catch (URISyntaxException e) {
mAddress.setError(r.getText(R.string.bookmark_url_not_valid));
return false;
}
try {
if (mEditingExisting) {
mMap.putString("title", title);
mMap.putString("url", url);
setResult(RESULT_OK, (new Intent()).setAction(
getIntent().toString()).putExtras(mMap));
} else {
final ContentResolver cr = getContentResolver();
// Only use mThumbnail if url and mOriginalUrl are matches.
// Otherwise the user edited the url and the thumbnail no longer applies.
if (url.equals(mOriginalUrl)) {
Bookmarks.addBookmark(null, cr, url, title, mThumbnail, true);
} else {
Bookmarks.addBookmark(null, cr, url, title, null, true);
}
if (mTouchIconUrl != null) {
final Cursor c =
BrowserBookmarksAdapter.queryBookmarksForUrl(
cr, null, url, true);
new DownloadTouchIcon(cr, c, url).execute(mTouchIconUrl);
}
setResult(RESULT_OK);
}
} catch (IllegalStateException e) {
setTitle(r.getText(R.string.no_database));
return false;
}
return true;
}
|
diff --git a/sonar/sonar-plugin-sourcemonitor/src/test/java/org/sonar/plugin/dotnet/srcmon/SourceMonitorResultParserTest.java b/sonar/sonar-plugin-sourcemonitor/src/test/java/org/sonar/plugin/dotnet/srcmon/SourceMonitorResultParserTest.java
index ae5b30cab..e9e9d8dc6 100644
--- a/sonar/sonar-plugin-sourcemonitor/src/test/java/org/sonar/plugin/dotnet/srcmon/SourceMonitorResultParserTest.java
+++ b/sonar/sonar-plugin-sourcemonitor/src/test/java/org/sonar/plugin/dotnet/srcmon/SourceMonitorResultParserTest.java
@@ -1,63 +1,63 @@
/*
* Maven and Sonar plugin for .Net
* Copyright (C) 2010 Jose Chillan and Alexandre Victoor
* mailto: [email protected] or [email protected]
*
* Sonar 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 3 of the License, or (at your option) any later version.
*
* Sonar 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 Sonar; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
*/
package org.sonar.plugin.dotnet.srcmon;
import static org.junit.Assert.*;
import java.io.File;
import java.util.List;
import org.junit.Test;
import org.sonar.plugin.dotnet.srcmon.model.FileMetrics;
public class SourceMonitorResultParserTest {
@Test
public void testParse() {
SourceMonitorResultParser parser = new SourceMonitorResultStaxParser();
File projectDirectory = new File("target/test-classes/solution/MessyTestSolution");
File reportFile = new File("target/test-classes/solution/MessyTestSolution/target/metrics-report.xml");
File moneyFile = new File("target/test-classes/solution/MessyTestSolution/MessyTestApplication/Money.cs");
List<FileMetrics> metrics = parser.parse(projectDirectory, reportFile);
assertNotNull(metrics);
assertEquals(5, metrics.size());
FileMetrics firstFile = metrics.get(0);
assertEquals(62, firstFile.getComplexity());
- assertEquals(moneyFile.getAbsoluteFile(), firstFile.getSourcePath().getAbsoluteFile());
+ assertEquals(moneyFile.getName(), firstFile.getSourcePath().getName());
assertEquals(3, firstFile.getCountClasses());
assertEquals(29, firstFile.getCommentLines());
assertEquals(1.77, firstFile.getAverageComplexity(),0.00001D);
assertEquals("MessyTestApplication.Money", firstFile.getClassName());
assertEquals(10, firstFile.getCountAccessors());
assertEquals(53, firstFile.getCountBlankLines());
assertEquals(3, firstFile.getCountCalls());
assertEquals(387, firstFile.getCountLines());
assertEquals(11, firstFile.getCountMethods());
assertEquals(4, firstFile.getCountMethodStatements());
assertEquals(199, firstFile.getCountStatements());
assertEquals(10, firstFile.getDocumentationLines());
// TODO does not seem to be used
//assertEquals(0, firstFile.getPercentCommentLines(), 0.00001D);
//assertEquals(10, firstFile.getPercentDocumentationLines(), 0.00001D);
}
}
| true | true | public void testParse() {
SourceMonitorResultParser parser = new SourceMonitorResultStaxParser();
File projectDirectory = new File("target/test-classes/solution/MessyTestSolution");
File reportFile = new File("target/test-classes/solution/MessyTestSolution/target/metrics-report.xml");
File moneyFile = new File("target/test-classes/solution/MessyTestSolution/MessyTestApplication/Money.cs");
List<FileMetrics> metrics = parser.parse(projectDirectory, reportFile);
assertNotNull(metrics);
assertEquals(5, metrics.size());
FileMetrics firstFile = metrics.get(0);
assertEquals(62, firstFile.getComplexity());
assertEquals(moneyFile.getAbsoluteFile(), firstFile.getSourcePath().getAbsoluteFile());
assertEquals(3, firstFile.getCountClasses());
assertEquals(29, firstFile.getCommentLines());
assertEquals(1.77, firstFile.getAverageComplexity(),0.00001D);
assertEquals("MessyTestApplication.Money", firstFile.getClassName());
assertEquals(10, firstFile.getCountAccessors());
assertEquals(53, firstFile.getCountBlankLines());
assertEquals(3, firstFile.getCountCalls());
assertEquals(387, firstFile.getCountLines());
assertEquals(11, firstFile.getCountMethods());
assertEquals(4, firstFile.getCountMethodStatements());
assertEquals(199, firstFile.getCountStatements());
assertEquals(10, firstFile.getDocumentationLines());
// TODO does not seem to be used
//assertEquals(0, firstFile.getPercentCommentLines(), 0.00001D);
//assertEquals(10, firstFile.getPercentDocumentationLines(), 0.00001D);
}
| public void testParse() {
SourceMonitorResultParser parser = new SourceMonitorResultStaxParser();
File projectDirectory = new File("target/test-classes/solution/MessyTestSolution");
File reportFile = new File("target/test-classes/solution/MessyTestSolution/target/metrics-report.xml");
File moneyFile = new File("target/test-classes/solution/MessyTestSolution/MessyTestApplication/Money.cs");
List<FileMetrics> metrics = parser.parse(projectDirectory, reportFile);
assertNotNull(metrics);
assertEquals(5, metrics.size());
FileMetrics firstFile = metrics.get(0);
assertEquals(62, firstFile.getComplexity());
assertEquals(moneyFile.getName(), firstFile.getSourcePath().getName());
assertEquals(3, firstFile.getCountClasses());
assertEquals(29, firstFile.getCommentLines());
assertEquals(1.77, firstFile.getAverageComplexity(),0.00001D);
assertEquals("MessyTestApplication.Money", firstFile.getClassName());
assertEquals(10, firstFile.getCountAccessors());
assertEquals(53, firstFile.getCountBlankLines());
assertEquals(3, firstFile.getCountCalls());
assertEquals(387, firstFile.getCountLines());
assertEquals(11, firstFile.getCountMethods());
assertEquals(4, firstFile.getCountMethodStatements());
assertEquals(199, firstFile.getCountStatements());
assertEquals(10, firstFile.getDocumentationLines());
// TODO does not seem to be used
//assertEquals(0, firstFile.getPercentCommentLines(), 0.00001D);
//assertEquals(10, firstFile.getPercentDocumentationLines(), 0.00001D);
}
|
diff --git a/test/unit/edu/northwestern/bioinformatics/studycalendar/web/StudyListControllerTest.java b/test/unit/edu/northwestern/bioinformatics/studycalendar/web/StudyListControllerTest.java
index 1f832b3a5..84f0708d1 100644
--- a/test/unit/edu/northwestern/bioinformatics/studycalendar/web/StudyListControllerTest.java
+++ b/test/unit/edu/northwestern/bioinformatics/studycalendar/web/StudyListControllerTest.java
@@ -1,62 +1,64 @@
package edu.northwestern.bioinformatics.studycalendar.web;
import edu.northwestern.bioinformatics.studycalendar.dao.StudyDao;
import edu.northwestern.bioinformatics.studycalendar.domain.Study;
import edu.northwestern.bioinformatics.studycalendar.domain.Site;
import edu.northwestern.bioinformatics.studycalendar.domain.Fixtures;
import edu.northwestern.bioinformatics.studycalendar.service.TemplateService;
import edu.northwestern.bioinformatics.studycalendar.service.SiteService;
import edu.northwestern.bioinformatics.studycalendar.utils.accesscontrol.ApplicationSecurityManager;
import org.easymock.classextension.EasyMock;
import static org.easymock.classextension.EasyMock.*;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
/**
* @author Rhett Sutphin
*/
public class StudyListControllerTest extends ControllerTestCase {
private StudyListController controller;
private StudyDao studyDao;
private TemplateService templateService;
private SiteService siteService;
protected void setUp() throws Exception {
super.setUp();
controller = new StudyListController();
studyDao = registerDaoMockFor(StudyDao.class);
templateService = registerMockFor(TemplateService.class);
siteService = registerMockFor(SiteService.class);
controller.setStudyDao(studyDao);
controller.setTemplateService(templateService);
controller.setSiteService(siteService);
}
public void testModelAndView() throws Exception {
Study complete = Fixtures.createSingleEpochStudy("Complete", "E1");
+ complete.setAmended(false);
complete.getPlannedCalendar().setComplete(true);
Study incomplete = Fixtures.createSingleEpochStudy("Incomplete", "E1");
+ incomplete.setAmended(false);
incomplete.getPlannedCalendar().setComplete(false);
List<Study> studies = Arrays.asList(incomplete, complete);
List<Site> sites = new ArrayList<Site>();
ApplicationSecurityManager.setUser(request, "jimbo");
expect(studyDao.getAll()).andReturn(studies);
expect(templateService.checkOwnership("jimbo", studies)).andReturn(studies);
expect(siteService.getSitesForSiteCd("jimbo")).andReturn(sites);
replayMocks();
ModelAndView mv = controller.handleRequest(request, response);
verifyMocks();
assertEquals("Complete studies list missing or wrong", Arrays.asList(complete),
mv.getModel().get("completeStudies"));
assertEquals("Incomplete studies list missing or wrong", Arrays.asList(incomplete),
mv.getModel().get("incompleteStudies"));
assertSame("Sites list missing or wrong", sites, mv.getModel().get("sites"));
assertEquals("studyList", mv.getViewName());
}
}
| false | true | public void testModelAndView() throws Exception {
Study complete = Fixtures.createSingleEpochStudy("Complete", "E1");
complete.getPlannedCalendar().setComplete(true);
Study incomplete = Fixtures.createSingleEpochStudy("Incomplete", "E1");
incomplete.getPlannedCalendar().setComplete(false);
List<Study> studies = Arrays.asList(incomplete, complete);
List<Site> sites = new ArrayList<Site>();
ApplicationSecurityManager.setUser(request, "jimbo");
expect(studyDao.getAll()).andReturn(studies);
expect(templateService.checkOwnership("jimbo", studies)).andReturn(studies);
expect(siteService.getSitesForSiteCd("jimbo")).andReturn(sites);
replayMocks();
ModelAndView mv = controller.handleRequest(request, response);
verifyMocks();
assertEquals("Complete studies list missing or wrong", Arrays.asList(complete),
mv.getModel().get("completeStudies"));
assertEquals("Incomplete studies list missing or wrong", Arrays.asList(incomplete),
mv.getModel().get("incompleteStudies"));
assertSame("Sites list missing or wrong", sites, mv.getModel().get("sites"));
assertEquals("studyList", mv.getViewName());
}
| public void testModelAndView() throws Exception {
Study complete = Fixtures.createSingleEpochStudy("Complete", "E1");
complete.setAmended(false);
complete.getPlannedCalendar().setComplete(true);
Study incomplete = Fixtures.createSingleEpochStudy("Incomplete", "E1");
incomplete.setAmended(false);
incomplete.getPlannedCalendar().setComplete(false);
List<Study> studies = Arrays.asList(incomplete, complete);
List<Site> sites = new ArrayList<Site>();
ApplicationSecurityManager.setUser(request, "jimbo");
expect(studyDao.getAll()).andReturn(studies);
expect(templateService.checkOwnership("jimbo", studies)).andReturn(studies);
expect(siteService.getSitesForSiteCd("jimbo")).andReturn(sites);
replayMocks();
ModelAndView mv = controller.handleRequest(request, response);
verifyMocks();
assertEquals("Complete studies list missing or wrong", Arrays.asList(complete),
mv.getModel().get("completeStudies"));
assertEquals("Incomplete studies list missing or wrong", Arrays.asList(incomplete),
mv.getModel().get("incompleteStudies"));
assertSame("Sites list missing or wrong", sites, mv.getModel().get("sites"));
assertEquals("studyList", mv.getViewName());
}
|
diff --git a/src/core/java/org/wyona/yanel/servlet/YanelServlet.java b/src/core/java/org/wyona/yanel/servlet/YanelServlet.java
index 650e45fbf..b7ab2ce8f 100644
--- a/src/core/java/org/wyona/yanel/servlet/YanelServlet.java
+++ b/src/core/java/org/wyona/yanel/servlet/YanelServlet.java
@@ -1,1236 +1,1235 @@
package org.wyona.yanel.servlet;
import java.io.File;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.net.URL;
import java.util.Enumeration;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamSource;
import org.wyona.yanel.core.Path;
import org.wyona.yanel.core.Resource;
import org.wyona.yanel.core.ResourceTypeDefinition;
import org.wyona.yanel.core.ResourceTypeIdentifier;
import org.wyona.yanel.core.ResourceTypeRegistry;
import org.wyona.yanel.core.Yanel;
import org.wyona.yanel.core.api.attributes.ModifiableV1;
import org.wyona.yanel.core.api.attributes.ModifiableV2;
import org.wyona.yanel.core.api.attributes.VersionableV2;
import org.wyona.yanel.core.api.attributes.ViewableV1;
import org.wyona.yanel.core.api.attributes.ViewableV2;
import org.wyona.yanel.core.attributes.viewable.View;
import org.wyona.yanel.core.map.Map;
import org.wyona.yanel.core.map.Realm;
import org.wyona.yanel.servlet.CreateUsecaseHelper;
import org.wyona.yanel.servlet.communication.HttpRequest;
import org.wyona.yanel.servlet.communication.HttpResponse;
import org.wyona.yanel.util.ResourceAttributeHelper;
import org.wyona.security.core.api.Identity;
import org.wyona.security.core.api.IdentityManager;
import org.wyona.security.core.api.PolicyManager;
import org.wyona.security.core.api.Role;
import org.apache.log4j.Category;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.DefaultConfigurationBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
*
*/
public class YanelServlet extends HttpServlet {
private static Category log = Category.getInstance(YanelServlet.class);
private ServletConfig config;
ResourceTypeRegistry rtr;
PolicyManager pm;
IdentityManager im;
Map map;
Yanel yanel;
private static String IDENTITY_KEY = "identity";
private static final String METHOD_PROPFIND = "PROPFIND";
private static final String METHOD_GET = "GET";
private static final String METHOD_POST = "POST";
private static final String METHOD_PUT = "PUT";
private static final String METHOD_DELETE = "DELETE";
private String sslPort = null;
/**
*
*/
public void init(ServletConfig config) throws ServletException {
this.config = config;
try {
yanel = Yanel.getInstance();
yanel.init();
rtr = yanel.getResourceTypeRegistry();
pm = (PolicyManager) yanel.getBeanFactory().getBean("policyManager");
im = (IdentityManager) yanel.getBeanFactory().getBean("identityManager");
map = (Map) yanel.getBeanFactory().getBean("map");
//sslPort = "8443";
sslPort = config.getInitParameter("ssl-port");
} catch (Exception e) {
log.error(e);
throw new ServletException(e.getMessage(), e);
}
}
/**
*
*/
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String httpAcceptMediaTypes = request.getHeader("Accept");
log.debug("HTTP Accept Media Types: " + httpAcceptMediaTypes);
String httpUserAgent = request.getHeader("User-Agent");
log.debug("HTTP User Agent: " + httpUserAgent);
String httpAcceptLanguage = request.getHeader("Accept-Language");
log.debug("HTTP Accept Language: " + httpAcceptLanguage);
// Logout from Yanel
String yanelUsecase = request.getParameter("yanel.usecase");
if(yanelUsecase != null && yanelUsecase.equals("logout")) {
if(doLogout(request, response) != null) return;
}
// Authentication
if(doAuthenticate(request, response) != null) return;
// Check authorization
if(doAuthorize(request, response) != null) return;
// Delegate ...
String method = request.getMethod();
if (method.equals(METHOD_PROPFIND)) {
doPropfind(request, response);
} else if (method.equals(METHOD_GET)) {
doGet(request, response);
} else if (method.equals(METHOD_POST)) {
doPost(request, response);
} else if (method.equals(METHOD_PUT)) {
doPut(request, response);
} else if (method.equals(METHOD_DELETE)) {
doDelete(request, response);
} else {
log.error("No such method implemented: " + method);
}
}
/**
*
*/
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Check if a new resource shall be created ...
String yanelUsecase = request.getParameter("yanel.usecase");
if(yanelUsecase != null && yanelUsecase.equals("create")) {
CreateUsecaseHelper creator = new CreateUsecaseHelper();
creator.create(request, response, yanel);
return;
}
getContent(request, response);
}
/**
*
*/
private void getContent(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
View view = null;
org.w3c.dom.Document doc = null;
javax.xml.parsers.DocumentBuilderFactory dbf= javax.xml.parsers.DocumentBuilderFactory.newInstance();
try {
javax.xml.parsers.DocumentBuilder parser = dbf.newDocumentBuilder();
org.w3c.dom.DOMImplementation impl = parser.getDOMImplementation();
org.w3c.dom.DocumentType doctype = null;
doc = impl.createDocument("http://www.wyona.org/yanel/1.0", "yanel", doctype);
} catch(Exception e) {
log.error(e.getMessage(), e);
throw new ServletException(e.getMessage());
}
Element rootElement = doc.getDocumentElement();
String servletContextRealPath = config.getServletContext().getRealPath("/");
rootElement.setAttribute("servlet-context-real-path", servletContextRealPath);
//log.deubg("servletContextRealPath: " + servletContextRealPath);
//log.debug("contextPath: " + request.getContextPath());
//log.debug("servletPath: " + request.getServletPath());
Element requestElement = (Element) rootElement.appendChild(doc.createElement("request"));
requestElement.setAttribute("uri", request.getRequestURI());
requestElement.setAttribute("servlet-path", request.getServletPath());
HttpSession session = request.getSession(true);
Element sessionElement = (Element) rootElement.appendChild(doc.createElement("session"));
sessionElement.setAttribute("id", session.getId());
Enumeration attrNames = session.getAttributeNames();
if (!attrNames.hasMoreElements()) {
Element sessionNoAttributesElement = (Element) sessionElement.appendChild(doc.createElement("no-attributes"));
}
while (attrNames.hasMoreElements()) {
String name = (String)attrNames.nextElement();
String value = session.getAttribute(name).toString();
Element sessionAttributeElement = (Element) sessionElement.appendChild(doc.createElement("attribute"));
sessionAttributeElement.setAttribute("name", name);
sessionAttributeElement.appendChild(doc.createTextNode(value));
}
Realm realm;
Path path;
ResourceTypeIdentifier rti;
try {
realm = map.getRealm(request.getServletPath());
path = map.getPath(realm, request.getServletPath());
rti = yanel.getResourceManager().getResourceTypeIdentifier(realm, path);
} catch (Exception e) {
String message = "URL could not be mapped to realm/path " + e.getMessage();
log.error(message, e);
Element exceptionElement = (Element) rootElement.appendChild(doc.createElement("exception"));
exceptionElement.appendChild(doc.createTextNode(message));
setYanelOutput(response, doc);
response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
//String rti = map.getResourceTypeIdentifier(new Path(request.getServletPath()));
Resource res = null;
long lastModified = -1;
long size = -1;
if (rti != null) {
ResourceTypeDefinition rtd = rtr.getResourceTypeDefinition(rti.getUniversalName());
if (rtd == null) {
String message = "No such resource type registered: " + rti.getUniversalName() + ", check " + rtr.getConfigurationFile();
log.error(message);
Element exceptionElement = (Element) rootElement.appendChild(doc.createElement("exception"));
exceptionElement.appendChild(doc.createTextNode(message));
setYanelOutput(response, doc);
response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
Element rtiElement = (Element) rootElement.appendChild(doc.createElement("resource-type-identifier"));
rtiElement.setAttribute("namespace", rtd.getResourceTypeNamespace());
rtiElement.setAttribute("local-name", rtd.getResourceTypeLocalName());
try {
HttpRequest httpRequest = new HttpRequest(request);
HttpResponse httpResponse = new HttpResponse(response);
res = yanel.getResourceManager().getResource(httpRequest, httpResponse, realm, path, rtd, rti);
if (res != null) {
Element resourceElement = (Element) rootElement.appendChild(doc.createElement("resource"));
if (ResourceAttributeHelper.hasAttributeImplemented(res, "Viewable", "1")) {
Element viewElement = (Element) resourceElement.appendChild(doc.createElement("view"));
viewElement.appendChild(doc.createTextNode("View Descriptors: " + ((ViewableV1) res).getViewDescriptors()));
String viewId = request.getParameter("yanel.resource.viewid");
try {
view = ((ViewableV1) res).getView(request, viewId);
} catch(org.wyona.yarep.core.NoSuchNodeException e) {
// TODO: Log all 404 within a dedicated file (with client info attached) such that an admin can react to it ...
String message = "No such node exception: " + e;
log.warn(e);
//log.error(e.getMessage(), e);
Element exceptionElement = (Element) rootElement.appendChild(doc.createElement("exception"));
exceptionElement.appendChild(doc.createTextNode(message));
exceptionElement.setAttribute("status", "404");
response.setStatus(javax.servlet.http.HttpServletResponse.SC_NOT_FOUND);
setYanelOutput(response, doc);
return;
} catch(Exception e) {
log.error(e.getMessage(), e);
String message = e.toString();
log.error(e.getMessage(), e);
Element exceptionElement = (Element) rootElement.appendChild(doc.createElement("exception"));
exceptionElement.appendChild(doc.createTextNode(message));
exceptionElement.setAttribute("status", "500");
response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
setYanelOutput(response, doc);
return;
}
} else if (ResourceAttributeHelper.hasAttributeImplemented(res, "Viewable", "2")) {
- log.error("DEBUG: Resource is viewable V2");
+ log.info("Resource is viewable V2");
String viewId = request.getParameter("yanel.resource.viewid");
Element viewElement = (Element) resourceElement.appendChild(doc.createElement("view"));
viewElement.appendChild(doc.createTextNode("View Descriptors: " + ((ViewableV2) res).getViewDescriptors()));
size = ((ViewableV2) res).getSize();
Element sizeElement = (Element) resourceElement.appendChild(doc.createElement("size"));
sizeElement.appendChild(doc.createTextNode(String.valueOf(size)));
view = ((ViewableV2) res).getView(viewId);
} else {
Element noViewElement = (Element) resourceElement.appendChild(doc.createElement("no-view"));
noViewElement.appendChild(doc.createTextNode(res.getClass().getName() + " is not viewable!"));
}
if (ResourceAttributeHelper.hasAttributeImplemented(res, "Modifiable", "2")) {
lastModified = ((ModifiableV2) res).getLastModified();
Element lastModifiedElement = (Element) resourceElement.appendChild(doc.createElement("last-modified"));
lastModifiedElement.appendChild(doc.createTextNode(new java.util.Date(lastModified).toString()));
} else {
Element noLastModifiedElement = (Element) resourceElement.appendChild(doc.createElement("no-last-modified"));
}
if (ResourceAttributeHelper.hasAttributeImplemented(res, "Versionable", "2")) {
// retrieve the revisions, but only in the meta usecase (for performance reasons):
if (request.getParameter("yanel.resource.meta") != null) {
String[] revisions = ((VersionableV2)res).getRevisions();
Element revisionsElement = (Element) resourceElement.appendChild(doc.createElement("revisions"));
if (revisions != null) {
for (int i=0; i<revisions.length; i++) {
Element revisionElement = (Element) revisionsElement.appendChild(doc.createElement("revision"));
revisionElement.appendChild(doc.createTextNode(revisions[i]));
}
}
}
}
} else {
Element resourceIsNullElement = (Element) rootElement.appendChild(doc.createElement("resource-is-null"));
}
} catch(Exception e) {
log.error(e.getMessage(), e);
String message = e.toString();
- log.error(e.getMessage(), e);
Element exceptionElement = (Element) rootElement.appendChild(doc.createElement("exception"));
exceptionElement.appendChild(doc.createTextNode(message));
setYanelOutput(response, doc);
response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
} else {
Element noRTIFoundElement = (Element) rootElement.appendChild(doc.createElement("no-resource-type-identifier-found"));
noRTIFoundElement.setAttribute("servlet-path", request.getServletPath());
}
String usecase = request.getParameter("yanel.resource.usecase");
if (usecase != null && usecase.equals("checkout")) {
log.debug("Checkout data ...");
// TODO: Implement checkout ...
log.warn("Acquire lock has not been implemented yet ...!");
// acquireLock();
}
String meta = request.getParameter("yanel.resource.meta");
if (meta != null) {
if (meta.length() > 0) {
log.error("DEBUG: meta length: " + meta.length());
} else {
log.error("DEBUG: Show all meta");
}
response.setStatus(javax.servlet.http.HttpServletResponse.SC_OK);
setYanelOutput(response, doc);
return;
}
if (view != null) {
// check if the view contatins the response (otherwise assume that the resource
// wrote the response, and just return).
if (!view.isResponse()) return;
response.setContentType(patchContentType(view.getMimeType(), request));
InputStream is = view.getInputStream();
//BufferedReader reader = new BufferedReader(new InputStreamReader(is));
//String line;
//System.out.println("getContentXML: "+path);
//while ((line = reader.readLine()) != null) System.out.println(line);
byte buffer[] = new byte[8192];
int bytesRead;
if (is != null) {
// TODO: Yarep does not set returned Stream to null resp. is missing Exception Handling for the constructor. Exceptions should be handled here, but rather within Yarep or whatever repositary layer is being used ...
bytesRead = is.read(buffer);
if (bytesRead == -1) {
String message = "InputStream of view does not seem to contain any data!";
Element exceptionElement = (Element) rootElement.appendChild(doc.createElement("exception"));
exceptionElement.appendChild(doc.createTextNode(message));
setYanelOutput(response, doc);
response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
// TODO: Compare If-Modified-Since with lastModified and return 304 without content resp. check on ETag
String ifModifiedSince = request.getHeader("If-Modified-Since");
if (ifModifiedSince != null) {
log.error("DEBUG: TODO: Implement 304 ...");
}
java.io.OutputStream os = response.getOutputStream();
os.write(buffer, 0, bytesRead);
while ((bytesRead = is.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead);
}
if(lastModified >= 0) response.setDateHeader("Last-Modified", lastModified);
return;
} else {
String message = "InputStream of view is null!";
Element exceptionElement = (Element) rootElement.appendChild(doc.createElement("exception"));
exceptionElement.appendChild(doc.createTextNode(message));
}
} else {
String message = "View is null!";
Element exceptionElement = (Element) rootElement.appendChild(doc.createElement("exception"));
exceptionElement.appendChild(doc.createTextNode(message));
}
setYanelOutput(response, doc);
response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
/**
*
*/
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String value = request.getParameter("yanel.resource.usecase");
if (value != null && value.equals("save")) {
log.debug("Save data ...");
save(request, response);
return;
} else if (value != null && value.equals("checkin")) {
log.debug("Checkin data ...");
save(request, response);
// TODO: Implement checkin ...
log.warn("Release lock has not been implemented yet ...");
// releaseLock();
return;
} else {
log.info("No parameter yanel.resource.usecase!");
String contentType = request.getContentType();
if (contentType.indexOf("application/atom+xml") >= 0) {
InputStream in = intercept(request.getInputStream());
try {
Resource atomEntry = rtr.newResource("<{http://www.wyona.org/yanel/resource/1.0}atom-entry/>");
atomEntry.setYanel(yanel);
// TODO: Initiate Atom Feed Resource Type to get actual path for saving ...
log.error("DEBUG: Atom Feed: " + request.getServletPath() + " " + request.getRequestURI());
Path entryPath = new Path(request.getServletPath() + "/" + new java.util.Date().getTime() + ".xml");
atomEntry.setPath(entryPath);
((ModifiableV2)atomEntry).write(in);
byte buffer[] = new byte[8192];
int bytesRead;
InputStream resourceIn = ((ModifiableV2)atomEntry).getInputStream();
OutputStream responseOut = response.getOutputStream();
while ((bytesRead = resourceIn.read(buffer)) != -1) {
responseOut.write(buffer, 0, bytesRead);
}
// TODO: Fix Location ...
response.setHeader("Location", "http://ulysses.wyona.org" + entryPath);
response.setStatus(javax.servlet.http.HttpServletResponse.SC_CREATED);
return;
} catch (Exception e) {
log.error(e.getMessage(), e);
throw new IOException(e.getMessage());
}
}
getContent(request, response);
}
}
/**
* HTTP PUT implementation
*/
public void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO: Reuse code doPost resp. share code with doPut
String value = request.getParameter("yanel.resource.usecase");
if (value != null && value.equals("save")) {
log.debug("Save data ...");
save(request, response);
return;
} else if (value != null && value.equals("checkin")) {
log.debug("Checkin data ...");
save(request, response);
// TODO: Implement checkin ...
log.warn("Release lock has not been implemented yet ...!");
// releaseLock();
return;
} else {
log.warn("No parameter yanel.resource.usecase!");
String contentType = request.getContentType();
if (contentType.indexOf("application/atom+xml") >= 0) {
InputStream in = intercept(request.getInputStream());
try {
Resource atomEntry = rtr.newResource("<{http://www.wyona.org/yanel/resource/1.0}atom-entry/>");
atomEntry.setYanel(yanel);
log.error("DEBUG: Atom Entry: " + request.getServletPath() + " " + request.getRequestURI());
Path entryPath = new Path(request.getServletPath());
atomEntry.setPath(entryPath);
// TODO: There seems to be a problem ...
((ModifiableV2)atomEntry).write(in);
// NOTE: This method does not update updated date
/*
OutputStream out = ((ModifiableV2)atomEntry).getOutputStream(entryPath);
byte buffer[] = new byte[8192];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
*/
log.error("DEBUG: Atom entry has been saved: " + entryPath);
response.setStatus(javax.servlet.http.HttpServletResponse.SC_OK);
return;
} catch (Exception e) {
log.error(e.getMessage(), e);
throw new IOException(e.getMessage());
}
} else {
save(request, response);
/*
log.warn("TODO: WebDAV PUT ...");
response.setStatus(javax.servlet.http.HttpServletResponse.SC_NOT_IMPLEMENTED);
return;
*/
}
}
}
/**
* HTTP DELETE implementation
*/
public void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
Resource res = getResource(request, response);
res.setPath(new Path(request.getServletPath()));
if (ResourceAttributeHelper.hasAttributeImplemented(res, "Modifiable", "2")) {
if (((ModifiableV2) res).delete()) {
log.debug("Resource has been deleted: " + res);
response.setStatus(response.SC_OK);
return;
} else {
log.warn("Resource could not be deleted: " + res);
response.setStatus(response.SC_FORBIDDEN);
return;
}
} else {
log.error("Resource '" + res + "' has interface ModifiableV2 not implemented." );
response.sendError(response.SC_NOT_IMPLEMENTED);
return;
}
} catch (Exception e) {
log.error("Could not delete resource with URL " + request.getRequestURL() + " " + e.getMessage(), e);
throw new ServletException(e.getMessage(), e);
}
}
/**
*
*/
private Resource getResource(HttpServletRequest request, HttpServletResponse response) {
try {
Realm realm = map.getRealm(request.getServletPath());
Path path = map.getPath(realm, request.getServletPath());
HttpRequest httpRequest = new HttpRequest(request);
HttpResponse httpResponse = new HttpResponse(response);
Resource res = yanel.getResourceManager().getResource(httpRequest, httpResponse, realm, path);
return res;
} catch(Exception e) {
log.error(e.getMessage(), e);
return null;
}
}
/**
*
*/
private void save(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
log.debug("Save data ...");
InputStream in = request.getInputStream();
java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();
byte[] buf = new byte[8192];
int bytesR;
while ((bytesR = in.read(buf)) != -1) {
baos.write(buf, 0, bytesR);
}
// Buffer within memory (TODO: Maybe replace with File-buffering ...)
// http://www-128.ibm.com/developerworks/java/library/j-io1/
byte[] memBuffer = baos.toByteArray();
// TODO: Should be delegated to resource type, e.g. <{http://...}xml/>!
// Check on well-formedness ...
String contentType = request.getContentType();
log.debug("Content-Type: " + contentType);
if (contentType.indexOf("application/xml") >= 0 || contentType.indexOf("application/xhtml+xml") >= 0) {
log.info("Check well-formedness ...");
javax.xml.parsers.DocumentBuilderFactory dbf= javax.xml.parsers.DocumentBuilderFactory.newInstance();
try {
javax.xml.parsers.DocumentBuilder parser = dbf.newDocumentBuilder();
// TODO: Get log messages into log4j ...
//parser.setErrorHandler(...);
// NOTE: DOCTYPE is being resolved/retrieved (e.g. xhtml schema from w3.org) also
// if isValidating is set to false.
// Hence, for performance and network reasons we use a local catalog ...
// Also see http://www.xml.com/pub/a/2004/03/03/catalogs.html
// resp. http://xml.apache.org/commons/components/resolver/
// TODO: What about a resolver factory?
parser.setEntityResolver(new org.apache.xml.resolver.tools.CatalogResolver());
parser.parse(new java.io.ByteArrayInputStream(memBuffer));
//org.w3c.dom.Document document = parser.parse(new ByteArrayInputStream(memBuffer));
} catch (org.xml.sax.SAXException e) {
log.warn("Data is not well-formed: "+e.getMessage());
StringBuffer sb = new StringBuffer();
sb.append("<?xml version=\"1.0\"?>");
sb.append("<exception xmlns=\"http://www.wyona.org/neutron/1.0\" type=\"data-not-well-formed\">");
sb.append("<message>Data is not well-formed: "+e.getMessage()+"</message>");
sb.append("</exception>");
response.setContentType("application/xml");
response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
PrintWriter w = response.getWriter();
w.print(sb);
return;
} catch (Exception e) {
log.error(e.getMessage(), e);
StringBuffer sb = new StringBuffer();
sb.append("<?xml version=\"1.0\"?>");
sb.append("<exception xmlns=\"http://www.wyona.org/neutron/1.0\" type=\"neutron\">");
//sb.append("<message>" + e.getStackTrace() + "</message>");
//sb.append("<message>" + e.getMessage() + "</message>");
sb.append("<message>" + e + "</message>");
sb.append("</exception>");
response.setContentType("application/xml");
response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
PrintWriter w = response.getWriter();
w.print(sb);
return;
}
log.info("Data seems to be well-formed :-)");
} else {
log.info("No well-formedness check required for content type: " + contentType);
}
/*
if (bytesRead == -1) {
response.setContentType("text/plain");
PrintWriter writer = response.getWriter();
writer.print("No content!");
return;
}
*/
OutputStream out = null;
Resource res = getResource(request, response);
if (ResourceAttributeHelper.hasAttributeImplemented(res, "Modifiable", "1")) {
out = ((ModifiableV1) res).getOutputStream(new Path(request.getServletPath()));
} else if (ResourceAttributeHelper.hasAttributeImplemented(res, "Modifiable", "2")) {
try {
out = ((ModifiableV2) res).getOutputStream();
} catch (Exception e) {
log.error(e.getMessage(), e);
throw new ServletException(e.getMessage(), e);
}
} else {
String message = res.getClass().getName() + " is not modifiable (neither V1 nor V2)!";
log.warn(message);
StringBuffer sb = new StringBuffer();
// TODO: Differentiate between Neutron based and other clients ...
/*
sb.append("<?xml version=\"1.0\"?>");
sb.append("<html>");
sb.append("<body>");
sb.append("<resource>" + message + "</resource>");
sb.append("</body>");
sb.append("</html>");
response.setContentType("application/xhtml+xml");
*/
sb.append("<?xml version=\"1.0\"?>");
sb.append("<exception xmlns=\"http://www.wyona.org/neutron/1.0\" type=\"neutron\">");
sb.append("<message>" + message + "</message>");
sb.append("</exception>");
response.setContentType("application/xml");
PrintWriter w = response.getWriter();
w.print(sb);
response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
if (out != null) {
log.debug("Content-Type: " + contentType);
// TODO: Compare mime-type from response with mime-type of resource
//if (contentType.equals("text/xml")) { ... }
byte[] buffer = new byte[8192];
int bytesRead;
java.io.ByteArrayInputStream memIn = new java.io.ByteArrayInputStream(memBuffer);
while ((bytesRead = memIn.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
out.flush();
out.close();
StringBuffer sb = new StringBuffer();
sb.append("<?xml version=\"1.0\"?>");
sb.append("<html>");
sb.append("<body>");
sb.append("<p>Data has been saved ...</p>");
sb.append("</body>");
sb.append("</html>");
response.setStatus(javax.servlet.http.HttpServletResponse.SC_OK);
response.setContentType("application/xhtml+xml");
PrintWriter w = response.getWriter();
w.print(sb);
log.info("Data has been saved ...");
return;
} else {
log.error("OutputStream is null!");
StringBuffer sb = new StringBuffer();
sb.append("<?xml version=\"1.0\"?>");
sb.append("<html>");
sb.append("<body>");
sb.append("<p>Exception: OutputStream is null!</p>");
sb.append("</body>");
sb.append("</html>");
PrintWriter w = response.getWriter();
w.print(sb);
response.setContentType("application/xhtml+xml");
response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
}
/**
* Authorize request
*/
private HttpServletResponse doAuthorize(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Role role = null;
// TODO: Replace hardcoded roles by mapping between roles amd query strings ...
String value = request.getParameter("yanel.resource.usecase");
String contentType = request.getContentType();
String method = request.getMethod();
if (value != null && value.equals("save")) {
log.debug("Save data ...");
role = new Role("write");
} else if (value != null && value.equals("checkin")) {
log.debug("Checkin data ...");
role = new Role("write");
} else if (value != null && value.equals("checkout")) {
log.debug("Checkout data ...");
role = new Role("open");
} else if (contentType != null && contentType.indexOf("application/atom+xml") >= 0 && (method.equals(METHOD_PUT) || method.equals(METHOD_POST))) {
log.error("DEBUG: Write/Checkin Atom entry ...");
role = new Role("write");
} else if (method.equals(METHOD_DELETE)) {
log.error("DEBUG: Delete resource ...");
role = new Role("delete");
} else {
log.debug("Role will be 'view'!");
role = new Role("view");
}
value = request.getParameter("yanel.usecase");
if (value != null && value.equals("create")) {
log.debug("Create new resource ...");
role = new Role("create");
}
boolean authorized = false;
// HTTP BASIC Authorization (For clients without session handling, e.g. OpenOffice or cadaver)
String authorization = request.getHeader("Authorization");
log.debug("Checking for Authorization Header: " + authorization);
if (authorization != null) {
if (authorization.toUpperCase().startsWith("BASIC")) {
log.debug("Using BASIC authorization ...");
// Get encoded user and password, comes after "BASIC "
String userpassEncoded = authorization.substring(6);
// Decode it, using any base 64 decoder
sun.misc.BASE64Decoder dec = new sun.misc.BASE64Decoder();
String userpassDecoded = new String(dec.decodeBuffer(userpassEncoded));
log.error("DEBUG: userpassDecoded: " + userpassDecoded);
// TODO: Use security package and remove hardcoded ...
// Authenticate every request ...
//if (im.authenticate(...)) {
if (userpassDecoded.equals("lenya:levi")) {
//return pm.authorize(new org.wyona.commons.io.Path(request.getServletPath()), new Identity(...), new Role("view"));
authorized = true;
return null;
}
authorized = false;
response.setHeader("WWW-Authenticate", "BASIC realm=\"yanel\"");
response.sendError(response.SC_UNAUTHORIZED);
PrintWriter writer = response.getWriter();
writer.print("BASIC Authorization/Authentication Failed!");
return response;
} else if (authorization.toUpperCase().startsWith("DIGEST")) {
log.error("DIGEST is not implemented");
authorized = false;
response.sendError(response.SC_UNAUTHORIZED);
response.setHeader("WWW-Authenticate", "DIGEST realm=\"yanel\"");
PrintWriter writer = response.getWriter();
writer.print("DIGEST is not implemented!");
return response;
} else {
log.warn("No such authorization implemented resp. handled by session based authorization: " + authorization);
authorized = false;
}
}
// Custom Authorization
log.debug("Do session based custom authorization");
//String[] groupnames = {"null", "null"};
HttpSession session = request.getSession(true);
Identity identity = (Identity) session.getAttribute(IDENTITY_KEY);
if (identity == null) {
log.debug("Identity is WORLD");
identity = new Identity();
}
authorized = pm.authorize(new org.wyona.commons.io.Path(request.getServletPath()), identity, role);
if(!authorized) {
log.warn("Access denied: " + getRequestURLQS(request, null, false));
if(!request.isSecure()) {
if(sslPort != null) {
log.error("DEBUG: Redirect to SSL ...");
try {
URL url = new URL(getRequestURLQS(request, null, false).toString());
url = new URL("https", url.getHost(), new Integer(sslPort).intValue(), url.getFile());
response.setHeader("Location", url.toString());
// TODO: Yulup has a bug re TEMPORARY_REDIRECT
//response.setStatus(javax.servlet.http.HttpServletResponse.SC_TEMPORARY_REDIRECT);
response.setStatus(javax.servlet.http.HttpServletResponse.SC_MOVED_PERMANENTLY);
return response;
} catch (Exception e) {
log.error(e);
}
} else {
log.warn("SSL does not seem to be configured!");
}
}
// TODO: Shouldn't this be here instead at the beginning of service() ...?
//if(doAuthenticate(request, response) != null) return response;
// HTTP Authorization/Authentication
// TODO: Ulysses has not HTTP BASIC or DIGEST implemented yet!
/*
response.setHeader("WWW-Authenticate", "BASIC realm=\"yanel\"");
response.sendError(response.SC_UNAUTHORIZED);
*/
// Custom Authorization/Authentication
// ...
// TODO: Check if this is a neutron request or just a common GET request
StringBuffer sb = new StringBuffer("");
String neutronVersions = request.getHeader("Neutron");
// http://lists.w3.org/Archives/Public/w3c-dist-auth/2006AprJun/0064.html
String clientSupportedAuthScheme = request.getHeader("WWW-Authenticate");
Realm realm = map.getRealm(new Path(request.getServletPath()));
if (clientSupportedAuthScheme != null && clientSupportedAuthScheme.equals("Neutron-Auth")) {
log.debug("Neutron Versions supported by client: " + neutronVersions);
log.debug("Authentication Scheme supported by client: " + clientSupportedAuthScheme);
sb.append("<?xml version=\"1.0\"?>");
sb.append("<exception xmlns=\"http://www.wyona.org/neutron/1.0\" type=\"authorization\">");
sb.append("<message>Authorization denied: " + getRequestURLQS(request, null, true) + "</message>");
sb.append("<authentication>");
sb.append("<original-request url=\"" + getRequestURLQS(request, null, true) + "\"/>");
//TODO: Also support https ...
sb.append("<login url=\"" + getRequestURLQS(request, "yanel.usecase=neutron-auth", true) + "\" method=\"POST\">");
sb.append("<form>");
sb.append("<message>Enter username and password for \"" + realm.getName() + "\" at \"" + realm.getMountPoint() + "\"</message>");
sb.append("<param description=\"Username\" name=\"username\"/>");
sb.append("<param description=\"Password\" name=\"password\"/>");
sb.append("</form>");
sb.append("</login>");
// NOTE: Needs to be a full URL, because user might switch the server ...
sb.append("<logout url=\"" + getRequestURLQS(request, "yanel.usecase=logout", true) + "\" realm=\"" + realm.getName() + "\"/>");
sb.append("</authentication>");
sb.append("</exception>");
log.debug("Neutron-Auth response: " + sb);
response.setContentType("application/xml");
response.setStatus(javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED);
response.setHeader("WWW-Authenticate", "NEUTRON-AUTH");
} else {
// Custom HTML Form authentication
// TODO: Use configurable XSLT for layout, whereas each realm should be able to overwrite ...
sb.append("<?xml version=\"1.0\"?>");
sb.append("<html xmlns=\"http://www.w3.org/1999/xhtml\">");
sb.append("<body>");
sb.append("<p>Authorization denied: " + getRequestURLQS(request, null, true) + "</p>");
sb.append("<p>Enter username and password for realm \"" + realm.getName() + "\" at \"" + realm.getMountPoint() + "\" (Context Path: " + request.getContextPath() + ")</p>");
sb.append("<form method=\"POST\">");
sb.append("<p>");
sb.append("<table>");
sb.append("<tr><td>Username:</td><td> </td><td><input type=\"text\" name=\"yanel.login.username\"/></td></tr>");
sb.append("<tr><td>Password:</td><td> </td><td><input type=\"password\" name=\"yanel.login.password\"/></td></tr>");
sb.append("<tr><td colspan=\"2\"> </td><td align=\"right\"><input type=\"submit\" value=\"Login\"/></td></tr>");
sb.append("</table>");
sb.append("</p>");
sb.append("</form>");
sb.append("</body>");
sb.append("</html>");
response.setContentType("application/xhtml+xml");
}
PrintWriter w = response.getWriter();
w.print(sb);
return response;
} else {
log.info("Access granted: " + getRequestURLQS(request, null, false));
return null;
}
}
/**
*
*/
private String getRequestURLQS(HttpServletRequest request, String addQS, boolean xml) {
Realm realm = map.getRealm(new Path(request.getServletPath()));
// TODO: Handle this exception more gracefully!
if (realm == null) log.error("No realm found for path " + new Path(request.getServletPath()));
String proxyHostName = realm.getProxyHostName();
String proxyPort = realm.getProxyPort();
String proxyPrefix = realm.getProxyPrefix();
URL url = null;
try {
url = new URL(request.getRequestURL().toString());
if (proxyHostName != null) {
url = new URL(url.getProtocol(), proxyHostName, url.getPort(), url.getFile());
}
if (proxyPort != null) {
if (proxyPort.length() > 0) {
url = new URL(url.getProtocol(), url.getHost(), new Integer(proxyPort).intValue(), url.getFile());
} else {
url = new URL(url.getProtocol(), url.getHost(), url.getDefaultPort(), url.getFile());
}
}
if (proxyPrefix != null) {
url = new URL(url.getProtocol(), url.getHost(), url.getPort(), url.getFile().substring(proxyPrefix.length()));
}
if(proxyHostName != null || proxyPort != null || proxyPrefix != null) {
log.debug("Proxy enabled request: " + url);
}
} catch (Exception e) {
log.error(e);
}
String urlQS = url.toString();
if (request.getQueryString() != null) {
urlQS = urlQS + "?" + request.getQueryString();
if (addQS != null) urlQS = urlQS + "&" + addQS;
} else {
if (addQS != null) urlQS = urlQS + "?" + addQS;
}
if (xml) urlQS = urlQS.replaceAll("&", "&");
log.debug("Request: " + urlQS);
return urlQS;
}
/**
* Also see https://svn.apache.org/repos/asf/tomcat/container/branches/tc5.0.x/catalina/src/share/org/apache/catalina/servlets/WebdavServlet.java
* Also maybe interesting http://sourceforge.net/projects/openharmonise
*/
public void doPropfind(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
getContent(request, response);
}
/**
*
*/
public HttpServletResponse doAuthenticate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Realm realm = map.getRealm(new Path(request.getServletPath()));
// HTML Form based authentication
String loginUsername = request.getParameter("yanel.login.username");
if(loginUsername != null) {
HttpSession session = request.getSession(true);
if (im.authenticate(loginUsername, request.getParameter("yanel.login.password"), realm.getID())) {
log.debug("Realm: " + realm);
session.setAttribute(IDENTITY_KEY, new Identity(loginUsername, null));
return null;
} else {
log.warn("Login failed: " + loginUsername);
// TODO: Implement form based response ...
response.setHeader("WWW-Authenticate", "BASIC realm=\"yanel\"");
response.sendError(response.SC_UNAUTHORIZED);
return response;
}
}
// Neutron-Auth based authentication
String yanelUsecase = request.getParameter("yanel.usecase");
if(yanelUsecase != null && yanelUsecase.equals("neutron-auth")) {
log.debug("Neutron Authentication ...");
String username = null;
String password = null;
String originalRequest = null;
DefaultConfigurationBuilder builder = new DefaultConfigurationBuilder();
try {
Configuration config = builder.build(request.getInputStream());
Configuration originalRequestConfig = config.getChild("original-request");
originalRequest = originalRequestConfig.getAttribute("url", null);
Configuration[] paramConfig = config.getChildren("param");
for (int i = 0; i < paramConfig.length; i++) {
String paramName = paramConfig[i].getAttribute("name", null);
if (paramName != null) {
if (paramName.equals("username")) {
username = paramConfig[i].getValue();
} else if (paramName.equals("password")) {
password = paramConfig[i].getValue();
}
}
}
} catch(Exception e) {
log.warn(e);
}
log.debug("Username: " + username);
if (username != null) {
HttpSession session = request.getSession(true);
log.debug("Realm ID: " + realm.getID());
if (im.authenticate(username, password, realm.getID())) {
log.info("Authentication successful: " + username);
session.setAttribute(IDENTITY_KEY, new Identity(username, null));
// TODO: send some XML content, e.g. <authentication-successful/>
response.setContentType("text/plain");
response.setStatus(response.SC_OK);
PrintWriter writer = response.getWriter();
writer.print("Neutron Authentication Successful!");
return response;
} else {
log.warn("Neutron Authentication failed: " + username);
// TODO: Refactor this code with the one from doAuthenticate ...
log.debug("Original Request: " + originalRequest);
StringBuffer sb = new StringBuffer("");
sb.append("<?xml version=\"1.0\"?>");
sb.append("<exception xmlns=\"http://www.wyona.org/neutron/1.0\" type=\"authentication\">");
sb.append("<message>Authentication failed!</message>");
sb.append("<authentication>");
// TODO: ...
sb.append("<original-request url=\"" + originalRequest + "\"/>");
//sb.append("<original-request url=\"" + getRequestURLQS(request, null, true) + "\"/>");
//TODO: Also support https ...
// TODO: ...
sb.append("<login url=\"" + originalRequest + "&yanel.usecase=neutron-auth" + "\" method=\"POST\">");
//sb.append("<login url=\"" + getRequestURLQS(request, "yanel.usecase=neutron-auth", true) + "\" method=\"POST\">");
sb.append("<form>");
sb.append("<message>Enter username and password for \"" + realm.getName() + "\" at \"" + realm.getMountPoint() + "\"</message>");
sb.append("<param description=\"Username\" name=\"username\"/>");
sb.append("<param description=\"Password\" name=\"password\"/>");
sb.append("</form>");
sb.append("</login>");
// NOTE: Needs to be a full URL, because user might switch the server ...
// TODO: ...
sb.append("<logout url=\"" + originalRequest + "&yanel.usecase=logout" + "\" realm=\"" + realm.getName() + "\"/>");
sb.append("</authentication>");
sb.append("</exception>");
log.debug("Neutron-Auth response: " + sb);
response.setContentType("application/xml");
response.setStatus(javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED);
response.setHeader("WWW-Authenticate", "NEUTRON-AUTH");
PrintWriter w = response.getWriter();
w.print(sb);
return response;
}
} else {
// TODO: Refactor resp. reuse response from above ...
log.warn("Neutron Authentication failed because username is NULL!");
StringBuffer sb = new StringBuffer("");
sb.append("<?xml version=\"1.0\"?>");
sb.append("<exception xmlns=\"http://www.wyona.org/neutron/1.0\" type=\"authentication\">");
sb.append("<message>Authentication failed because no username was sent!</message>");
sb.append("<authentication>");
// TODO: ...
sb.append("<original-request url=\"" + originalRequest + "\"/>");
//sb.append("<original-request url=\"" + getRequestURLQS(request, null, true) + "\"/>");
//TODO: Also support https ...
// TODO: ...
sb.append("<login url=\"" + originalRequest + "&yanel.usecase=neutron-auth" + "\" method=\"POST\">");
//sb.append("<login url=\"" + getRequestURLQS(request, "yanel.usecase=neutron-auth", true) + "\" method=\"POST\">");
sb.append("<form>");
sb.append("<message>Enter username and password for \"" + realm.getName() + "\" at \"" + realm.getMountPoint() + "\"</message>");
sb.append("<param description=\"Username\" name=\"username\"/>");
sb.append("<param description=\"Password\" name=\"password\"/>");
sb.append("</form>");
sb.append("</login>");
// NOTE: Needs to be a full URL, because user might switch the server ...
// TODO: ...
sb.append("<logout url=\"" + originalRequest + "&yanel.usecase=logout" + "\" realm=\"" + realm.getName() + "\"/>");
sb.append("</authentication>");
sb.append("</exception>");
response.setContentType("application/xml");
response.setStatus(javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED);
response.setHeader("WWW-Authenticate", "NEUTRON-AUTH");
PrintWriter writer = response.getWriter();
writer.print(sb);
return response;
}
} else {
log.debug("Neutron Authentication successful.");
return null;
}
}
/**
*
*/
public HttpServletResponse doLogout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
log.info("Logout from Yanel ...");
HttpSession session = request.getSession(true);
session.setAttribute(IDENTITY_KEY, null);
String clientSupportedAuthScheme = request.getHeader("WWW-Authenticate");
if (clientSupportedAuthScheme != null && clientSupportedAuthScheme.equals("Neutron-Auth")) {
// TODO: send some XML content, e.g. <logout-successful/>
response.setContentType("text/plain");
response.setStatus(response.SC_OK);
PrintWriter writer = response.getWriter();
writer.print("Neutron Logout Successful!");
return response;
}
return null;
}
/**
* Microsoft Internet Explorer does not understand application/xhtml+xml
* See http://en.wikipedia.org/wiki/Criticisms_of_Internet_Explorer#XHTML
*/
public String patchContentType(String contentType, HttpServletRequest request) throws ServletException, IOException {
String httpAcceptMediaTypes = request.getHeader("Accept");
log.debug("HTTP Accept Media Types: " + httpAcceptMediaTypes);
if (contentType != null && contentType.equals("application/xhtml+xml") && httpAcceptMediaTypes != null && httpAcceptMediaTypes.indexOf("application/xhtml+xml") < 0) {
log.error("DEBUG: Patch contentType with text/html because client (" + request.getHeader("User-Agent") + ") does not seem to understand application/xhtml+xml");
return "text/html";
}
return contentType;
}
/**
* Intercept InputStream and log content ...
*/
public InputStream intercept(InputStream in) throws IOException {
java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();
byte[] buf = new byte[8192];
int bytesR;
while ((bytesR = in.read(buf)) != -1) {
baos.write(buf, 0, bytesR);
}
// Buffer within memory (TODO: Maybe replace with File-buffering ...)
// http://www-128.ibm.com/developerworks/java/library/j-io1/
byte[] memBuffer = baos.toByteArray();
log.error("DEBUG: InputStream: " + baos);
return new java.io.ByteArrayInputStream(memBuffer);
}
/**
*
*/
private void setYanelOutput(HttpServletResponse response, Document doc) throws ServletException {
response.setContentType("application/xml");
try {
File xsltFile = org.wyona.commons.io.FileUtil.file(config.getServletContext().getRealPath("/"), "xslt" + File.separator + "xmlInfo2xhtml.xsl");
Transformer transformer = TransformerFactory.newInstance().newTransformer(new StreamSource(xsltFile));
transformer.transform(new javax.xml.transform.dom.DOMSource(doc), new javax.xml.transform.stream.StreamResult(response.getWriter()));
/*
OutputStream out = response.getOutputStream();
javax.xml.transform.TransformerFactory.newInstance().newTransformer().transform(new javax.xml.transform.dom.DOMSource(doc), new javax.xml.transform.stream.StreamResult(out));
out.close();
*/
} catch (Exception e) {
log.error(e.getMessage(), e);
throw new ServletException(e.getMessage());
}
}
}
| false | true | private void getContent(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
View view = null;
org.w3c.dom.Document doc = null;
javax.xml.parsers.DocumentBuilderFactory dbf= javax.xml.parsers.DocumentBuilderFactory.newInstance();
try {
javax.xml.parsers.DocumentBuilder parser = dbf.newDocumentBuilder();
org.w3c.dom.DOMImplementation impl = parser.getDOMImplementation();
org.w3c.dom.DocumentType doctype = null;
doc = impl.createDocument("http://www.wyona.org/yanel/1.0", "yanel", doctype);
} catch(Exception e) {
log.error(e.getMessage(), e);
throw new ServletException(e.getMessage());
}
Element rootElement = doc.getDocumentElement();
String servletContextRealPath = config.getServletContext().getRealPath("/");
rootElement.setAttribute("servlet-context-real-path", servletContextRealPath);
//log.deubg("servletContextRealPath: " + servletContextRealPath);
//log.debug("contextPath: " + request.getContextPath());
//log.debug("servletPath: " + request.getServletPath());
Element requestElement = (Element) rootElement.appendChild(doc.createElement("request"));
requestElement.setAttribute("uri", request.getRequestURI());
requestElement.setAttribute("servlet-path", request.getServletPath());
HttpSession session = request.getSession(true);
Element sessionElement = (Element) rootElement.appendChild(doc.createElement("session"));
sessionElement.setAttribute("id", session.getId());
Enumeration attrNames = session.getAttributeNames();
if (!attrNames.hasMoreElements()) {
Element sessionNoAttributesElement = (Element) sessionElement.appendChild(doc.createElement("no-attributes"));
}
while (attrNames.hasMoreElements()) {
String name = (String)attrNames.nextElement();
String value = session.getAttribute(name).toString();
Element sessionAttributeElement = (Element) sessionElement.appendChild(doc.createElement("attribute"));
sessionAttributeElement.setAttribute("name", name);
sessionAttributeElement.appendChild(doc.createTextNode(value));
}
Realm realm;
Path path;
ResourceTypeIdentifier rti;
try {
realm = map.getRealm(request.getServletPath());
path = map.getPath(realm, request.getServletPath());
rti = yanel.getResourceManager().getResourceTypeIdentifier(realm, path);
} catch (Exception e) {
String message = "URL could not be mapped to realm/path " + e.getMessage();
log.error(message, e);
Element exceptionElement = (Element) rootElement.appendChild(doc.createElement("exception"));
exceptionElement.appendChild(doc.createTextNode(message));
setYanelOutput(response, doc);
response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
//String rti = map.getResourceTypeIdentifier(new Path(request.getServletPath()));
Resource res = null;
long lastModified = -1;
long size = -1;
if (rti != null) {
ResourceTypeDefinition rtd = rtr.getResourceTypeDefinition(rti.getUniversalName());
if (rtd == null) {
String message = "No such resource type registered: " + rti.getUniversalName() + ", check " + rtr.getConfigurationFile();
log.error(message);
Element exceptionElement = (Element) rootElement.appendChild(doc.createElement("exception"));
exceptionElement.appendChild(doc.createTextNode(message));
setYanelOutput(response, doc);
response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
Element rtiElement = (Element) rootElement.appendChild(doc.createElement("resource-type-identifier"));
rtiElement.setAttribute("namespace", rtd.getResourceTypeNamespace());
rtiElement.setAttribute("local-name", rtd.getResourceTypeLocalName());
try {
HttpRequest httpRequest = new HttpRequest(request);
HttpResponse httpResponse = new HttpResponse(response);
res = yanel.getResourceManager().getResource(httpRequest, httpResponse, realm, path, rtd, rti);
if (res != null) {
Element resourceElement = (Element) rootElement.appendChild(doc.createElement("resource"));
if (ResourceAttributeHelper.hasAttributeImplemented(res, "Viewable", "1")) {
Element viewElement = (Element) resourceElement.appendChild(doc.createElement("view"));
viewElement.appendChild(doc.createTextNode("View Descriptors: " + ((ViewableV1) res).getViewDescriptors()));
String viewId = request.getParameter("yanel.resource.viewid");
try {
view = ((ViewableV1) res).getView(request, viewId);
} catch(org.wyona.yarep.core.NoSuchNodeException e) {
// TODO: Log all 404 within a dedicated file (with client info attached) such that an admin can react to it ...
String message = "No such node exception: " + e;
log.warn(e);
//log.error(e.getMessage(), e);
Element exceptionElement = (Element) rootElement.appendChild(doc.createElement("exception"));
exceptionElement.appendChild(doc.createTextNode(message));
exceptionElement.setAttribute("status", "404");
response.setStatus(javax.servlet.http.HttpServletResponse.SC_NOT_FOUND);
setYanelOutput(response, doc);
return;
} catch(Exception e) {
log.error(e.getMessage(), e);
String message = e.toString();
log.error(e.getMessage(), e);
Element exceptionElement = (Element) rootElement.appendChild(doc.createElement("exception"));
exceptionElement.appendChild(doc.createTextNode(message));
exceptionElement.setAttribute("status", "500");
response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
setYanelOutput(response, doc);
return;
}
} else if (ResourceAttributeHelper.hasAttributeImplemented(res, "Viewable", "2")) {
log.error("DEBUG: Resource is viewable V2");
String viewId = request.getParameter("yanel.resource.viewid");
Element viewElement = (Element) resourceElement.appendChild(doc.createElement("view"));
viewElement.appendChild(doc.createTextNode("View Descriptors: " + ((ViewableV2) res).getViewDescriptors()));
size = ((ViewableV2) res).getSize();
Element sizeElement = (Element) resourceElement.appendChild(doc.createElement("size"));
sizeElement.appendChild(doc.createTextNode(String.valueOf(size)));
view = ((ViewableV2) res).getView(viewId);
} else {
Element noViewElement = (Element) resourceElement.appendChild(doc.createElement("no-view"));
noViewElement.appendChild(doc.createTextNode(res.getClass().getName() + " is not viewable!"));
}
if (ResourceAttributeHelper.hasAttributeImplemented(res, "Modifiable", "2")) {
lastModified = ((ModifiableV2) res).getLastModified();
Element lastModifiedElement = (Element) resourceElement.appendChild(doc.createElement("last-modified"));
lastModifiedElement.appendChild(doc.createTextNode(new java.util.Date(lastModified).toString()));
} else {
Element noLastModifiedElement = (Element) resourceElement.appendChild(doc.createElement("no-last-modified"));
}
if (ResourceAttributeHelper.hasAttributeImplemented(res, "Versionable", "2")) {
// retrieve the revisions, but only in the meta usecase (for performance reasons):
if (request.getParameter("yanel.resource.meta") != null) {
String[] revisions = ((VersionableV2)res).getRevisions();
Element revisionsElement = (Element) resourceElement.appendChild(doc.createElement("revisions"));
if (revisions != null) {
for (int i=0; i<revisions.length; i++) {
Element revisionElement = (Element) revisionsElement.appendChild(doc.createElement("revision"));
revisionElement.appendChild(doc.createTextNode(revisions[i]));
}
}
}
}
} else {
Element resourceIsNullElement = (Element) rootElement.appendChild(doc.createElement("resource-is-null"));
}
} catch(Exception e) {
log.error(e.getMessage(), e);
String message = e.toString();
log.error(e.getMessage(), e);
Element exceptionElement = (Element) rootElement.appendChild(doc.createElement("exception"));
exceptionElement.appendChild(doc.createTextNode(message));
setYanelOutput(response, doc);
response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
} else {
Element noRTIFoundElement = (Element) rootElement.appendChild(doc.createElement("no-resource-type-identifier-found"));
noRTIFoundElement.setAttribute("servlet-path", request.getServletPath());
}
String usecase = request.getParameter("yanel.resource.usecase");
if (usecase != null && usecase.equals("checkout")) {
log.debug("Checkout data ...");
// TODO: Implement checkout ...
log.warn("Acquire lock has not been implemented yet ...!");
// acquireLock();
}
String meta = request.getParameter("yanel.resource.meta");
if (meta != null) {
if (meta.length() > 0) {
log.error("DEBUG: meta length: " + meta.length());
} else {
log.error("DEBUG: Show all meta");
}
response.setStatus(javax.servlet.http.HttpServletResponse.SC_OK);
setYanelOutput(response, doc);
return;
}
if (view != null) {
// check if the view contatins the response (otherwise assume that the resource
// wrote the response, and just return).
if (!view.isResponse()) return;
response.setContentType(patchContentType(view.getMimeType(), request));
InputStream is = view.getInputStream();
//BufferedReader reader = new BufferedReader(new InputStreamReader(is));
//String line;
//System.out.println("getContentXML: "+path);
//while ((line = reader.readLine()) != null) System.out.println(line);
byte buffer[] = new byte[8192];
int bytesRead;
if (is != null) {
// TODO: Yarep does not set returned Stream to null resp. is missing Exception Handling for the constructor. Exceptions should be handled here, but rather within Yarep or whatever repositary layer is being used ...
bytesRead = is.read(buffer);
if (bytesRead == -1) {
String message = "InputStream of view does not seem to contain any data!";
Element exceptionElement = (Element) rootElement.appendChild(doc.createElement("exception"));
exceptionElement.appendChild(doc.createTextNode(message));
setYanelOutput(response, doc);
response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
// TODO: Compare If-Modified-Since with lastModified and return 304 without content resp. check on ETag
String ifModifiedSince = request.getHeader("If-Modified-Since");
if (ifModifiedSince != null) {
log.error("DEBUG: TODO: Implement 304 ...");
}
java.io.OutputStream os = response.getOutputStream();
os.write(buffer, 0, bytesRead);
while ((bytesRead = is.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead);
}
if(lastModified >= 0) response.setDateHeader("Last-Modified", lastModified);
return;
} else {
String message = "InputStream of view is null!";
Element exceptionElement = (Element) rootElement.appendChild(doc.createElement("exception"));
exceptionElement.appendChild(doc.createTextNode(message));
}
} else {
String message = "View is null!";
Element exceptionElement = (Element) rootElement.appendChild(doc.createElement("exception"));
exceptionElement.appendChild(doc.createTextNode(message));
}
setYanelOutput(response, doc);
response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
| private void getContent(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
View view = null;
org.w3c.dom.Document doc = null;
javax.xml.parsers.DocumentBuilderFactory dbf= javax.xml.parsers.DocumentBuilderFactory.newInstance();
try {
javax.xml.parsers.DocumentBuilder parser = dbf.newDocumentBuilder();
org.w3c.dom.DOMImplementation impl = parser.getDOMImplementation();
org.w3c.dom.DocumentType doctype = null;
doc = impl.createDocument("http://www.wyona.org/yanel/1.0", "yanel", doctype);
} catch(Exception e) {
log.error(e.getMessage(), e);
throw new ServletException(e.getMessage());
}
Element rootElement = doc.getDocumentElement();
String servletContextRealPath = config.getServletContext().getRealPath("/");
rootElement.setAttribute("servlet-context-real-path", servletContextRealPath);
//log.deubg("servletContextRealPath: " + servletContextRealPath);
//log.debug("contextPath: " + request.getContextPath());
//log.debug("servletPath: " + request.getServletPath());
Element requestElement = (Element) rootElement.appendChild(doc.createElement("request"));
requestElement.setAttribute("uri", request.getRequestURI());
requestElement.setAttribute("servlet-path", request.getServletPath());
HttpSession session = request.getSession(true);
Element sessionElement = (Element) rootElement.appendChild(doc.createElement("session"));
sessionElement.setAttribute("id", session.getId());
Enumeration attrNames = session.getAttributeNames();
if (!attrNames.hasMoreElements()) {
Element sessionNoAttributesElement = (Element) sessionElement.appendChild(doc.createElement("no-attributes"));
}
while (attrNames.hasMoreElements()) {
String name = (String)attrNames.nextElement();
String value = session.getAttribute(name).toString();
Element sessionAttributeElement = (Element) sessionElement.appendChild(doc.createElement("attribute"));
sessionAttributeElement.setAttribute("name", name);
sessionAttributeElement.appendChild(doc.createTextNode(value));
}
Realm realm;
Path path;
ResourceTypeIdentifier rti;
try {
realm = map.getRealm(request.getServletPath());
path = map.getPath(realm, request.getServletPath());
rti = yanel.getResourceManager().getResourceTypeIdentifier(realm, path);
} catch (Exception e) {
String message = "URL could not be mapped to realm/path " + e.getMessage();
log.error(message, e);
Element exceptionElement = (Element) rootElement.appendChild(doc.createElement("exception"));
exceptionElement.appendChild(doc.createTextNode(message));
setYanelOutput(response, doc);
response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
//String rti = map.getResourceTypeIdentifier(new Path(request.getServletPath()));
Resource res = null;
long lastModified = -1;
long size = -1;
if (rti != null) {
ResourceTypeDefinition rtd = rtr.getResourceTypeDefinition(rti.getUniversalName());
if (rtd == null) {
String message = "No such resource type registered: " + rti.getUniversalName() + ", check " + rtr.getConfigurationFile();
log.error(message);
Element exceptionElement = (Element) rootElement.appendChild(doc.createElement("exception"));
exceptionElement.appendChild(doc.createTextNode(message));
setYanelOutput(response, doc);
response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
Element rtiElement = (Element) rootElement.appendChild(doc.createElement("resource-type-identifier"));
rtiElement.setAttribute("namespace", rtd.getResourceTypeNamespace());
rtiElement.setAttribute("local-name", rtd.getResourceTypeLocalName());
try {
HttpRequest httpRequest = new HttpRequest(request);
HttpResponse httpResponse = new HttpResponse(response);
res = yanel.getResourceManager().getResource(httpRequest, httpResponse, realm, path, rtd, rti);
if (res != null) {
Element resourceElement = (Element) rootElement.appendChild(doc.createElement("resource"));
if (ResourceAttributeHelper.hasAttributeImplemented(res, "Viewable", "1")) {
Element viewElement = (Element) resourceElement.appendChild(doc.createElement("view"));
viewElement.appendChild(doc.createTextNode("View Descriptors: " + ((ViewableV1) res).getViewDescriptors()));
String viewId = request.getParameter("yanel.resource.viewid");
try {
view = ((ViewableV1) res).getView(request, viewId);
} catch(org.wyona.yarep.core.NoSuchNodeException e) {
// TODO: Log all 404 within a dedicated file (with client info attached) such that an admin can react to it ...
String message = "No such node exception: " + e;
log.warn(e);
//log.error(e.getMessage(), e);
Element exceptionElement = (Element) rootElement.appendChild(doc.createElement("exception"));
exceptionElement.appendChild(doc.createTextNode(message));
exceptionElement.setAttribute("status", "404");
response.setStatus(javax.servlet.http.HttpServletResponse.SC_NOT_FOUND);
setYanelOutput(response, doc);
return;
} catch(Exception e) {
log.error(e.getMessage(), e);
String message = e.toString();
log.error(e.getMessage(), e);
Element exceptionElement = (Element) rootElement.appendChild(doc.createElement("exception"));
exceptionElement.appendChild(doc.createTextNode(message));
exceptionElement.setAttribute("status", "500");
response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
setYanelOutput(response, doc);
return;
}
} else if (ResourceAttributeHelper.hasAttributeImplemented(res, "Viewable", "2")) {
log.info("Resource is viewable V2");
String viewId = request.getParameter("yanel.resource.viewid");
Element viewElement = (Element) resourceElement.appendChild(doc.createElement("view"));
viewElement.appendChild(doc.createTextNode("View Descriptors: " + ((ViewableV2) res).getViewDescriptors()));
size = ((ViewableV2) res).getSize();
Element sizeElement = (Element) resourceElement.appendChild(doc.createElement("size"));
sizeElement.appendChild(doc.createTextNode(String.valueOf(size)));
view = ((ViewableV2) res).getView(viewId);
} else {
Element noViewElement = (Element) resourceElement.appendChild(doc.createElement("no-view"));
noViewElement.appendChild(doc.createTextNode(res.getClass().getName() + " is not viewable!"));
}
if (ResourceAttributeHelper.hasAttributeImplemented(res, "Modifiable", "2")) {
lastModified = ((ModifiableV2) res).getLastModified();
Element lastModifiedElement = (Element) resourceElement.appendChild(doc.createElement("last-modified"));
lastModifiedElement.appendChild(doc.createTextNode(new java.util.Date(lastModified).toString()));
} else {
Element noLastModifiedElement = (Element) resourceElement.appendChild(doc.createElement("no-last-modified"));
}
if (ResourceAttributeHelper.hasAttributeImplemented(res, "Versionable", "2")) {
// retrieve the revisions, but only in the meta usecase (for performance reasons):
if (request.getParameter("yanel.resource.meta") != null) {
String[] revisions = ((VersionableV2)res).getRevisions();
Element revisionsElement = (Element) resourceElement.appendChild(doc.createElement("revisions"));
if (revisions != null) {
for (int i=0; i<revisions.length; i++) {
Element revisionElement = (Element) revisionsElement.appendChild(doc.createElement("revision"));
revisionElement.appendChild(doc.createTextNode(revisions[i]));
}
}
}
}
} else {
Element resourceIsNullElement = (Element) rootElement.appendChild(doc.createElement("resource-is-null"));
}
} catch(Exception e) {
log.error(e.getMessage(), e);
String message = e.toString();
Element exceptionElement = (Element) rootElement.appendChild(doc.createElement("exception"));
exceptionElement.appendChild(doc.createTextNode(message));
setYanelOutput(response, doc);
response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
} else {
Element noRTIFoundElement = (Element) rootElement.appendChild(doc.createElement("no-resource-type-identifier-found"));
noRTIFoundElement.setAttribute("servlet-path", request.getServletPath());
}
String usecase = request.getParameter("yanel.resource.usecase");
if (usecase != null && usecase.equals("checkout")) {
log.debug("Checkout data ...");
// TODO: Implement checkout ...
log.warn("Acquire lock has not been implemented yet ...!");
// acquireLock();
}
String meta = request.getParameter("yanel.resource.meta");
if (meta != null) {
if (meta.length() > 0) {
log.error("DEBUG: meta length: " + meta.length());
} else {
log.error("DEBUG: Show all meta");
}
response.setStatus(javax.servlet.http.HttpServletResponse.SC_OK);
setYanelOutput(response, doc);
return;
}
if (view != null) {
// check if the view contatins the response (otherwise assume that the resource
// wrote the response, and just return).
if (!view.isResponse()) return;
response.setContentType(patchContentType(view.getMimeType(), request));
InputStream is = view.getInputStream();
//BufferedReader reader = new BufferedReader(new InputStreamReader(is));
//String line;
//System.out.println("getContentXML: "+path);
//while ((line = reader.readLine()) != null) System.out.println(line);
byte buffer[] = new byte[8192];
int bytesRead;
if (is != null) {
// TODO: Yarep does not set returned Stream to null resp. is missing Exception Handling for the constructor. Exceptions should be handled here, but rather within Yarep or whatever repositary layer is being used ...
bytesRead = is.read(buffer);
if (bytesRead == -1) {
String message = "InputStream of view does not seem to contain any data!";
Element exceptionElement = (Element) rootElement.appendChild(doc.createElement("exception"));
exceptionElement.appendChild(doc.createTextNode(message));
setYanelOutput(response, doc);
response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
// TODO: Compare If-Modified-Since with lastModified and return 304 without content resp. check on ETag
String ifModifiedSince = request.getHeader("If-Modified-Since");
if (ifModifiedSince != null) {
log.error("DEBUG: TODO: Implement 304 ...");
}
java.io.OutputStream os = response.getOutputStream();
os.write(buffer, 0, bytesRead);
while ((bytesRead = is.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead);
}
if(lastModified >= 0) response.setDateHeader("Last-Modified", lastModified);
return;
} else {
String message = "InputStream of view is null!";
Element exceptionElement = (Element) rootElement.appendChild(doc.createElement("exception"));
exceptionElement.appendChild(doc.createTextNode(message));
}
} else {
String message = "View is null!";
Element exceptionElement = (Element) rootElement.appendChild(doc.createElement("exception"));
exceptionElement.appendChild(doc.createTextNode(message));
}
setYanelOutput(response, doc);
response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
|
diff --git a/src/com/groupon/ExecuteCommand.java b/src/com/groupon/ExecuteCommand.java
index 516face..66d9cf3 100644
--- a/src/com/groupon/ExecuteCommand.java
+++ b/src/com/groupon/ExecuteCommand.java
@@ -1,109 +1,109 @@
/**
* Copyright (c) 2013, Groupon, Inc.
* 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.
*
* Neither the name of GROUPON 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 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.
* Created with IntelliJ IDEA.
* User: Dima Kovalenko (@dimacus) && Darko Marinov
* Date: 5/10/13
* Time: 4:06 PM
*/
package com.groupon;
import java.io.IOException;
import java.io.InputStream;
class ExecuteCommand {
public static String execRuntime(String cmd) {
return execRuntime(cmd, true);
}
public static String execRuntime(String cmd, boolean waitToFinish) {
System.out.println("Starting to execute - " + cmd);
JsonResponseBuilder jsonResponse = new JsonResponseBuilder();
- jsonResponse.addKeyValues("exit_code", 1);
- jsonResponse.addKeyValues("out", "");
- jsonResponse.addKeyValues("error", "");
Process process;
try {
process = Runtime.getRuntime().exec(cmd);
} catch (IOException e) {
jsonResponse.addKeyValues("error", "Problems in running " + cmd + "\n" + e.toString());
return jsonResponse.toString();
}
int exitCode;
if (waitToFinish) {
try {
System.out.println("Waiting to finish");
exitCode = process.waitFor();
System.out.println("Command Finished");
} catch (InterruptedException e) {
jsonResponse.addKeyValues("error", "Interrupted running " + cmd + "\n" + e.toString());
return jsonResponse.toString();
}
} else {
System.out.println("Not waiting for finish");
- jsonResponse.addKeyValues("exit_code", 0);
jsonResponse.addKeyValues("out", "Background process started");
return jsonResponse.toString();
}
try {
String output = inputStreamToString(process.getInputStream());
String error = inputStreamToString(process.getErrorStream());
jsonResponse.addKeyValues("exit_code", exitCode);
jsonResponse.addKeyValues("out", output);
- jsonResponse.addKeyValues("error", error);
+ if (!error.equals("")) {
+ //Only add error if there is one, this way we have a nice empty array instead of [""]
+ jsonResponse.addKeyValues("error", error);
+ }
return jsonResponse.toString();
} catch (IOException e) {
- jsonResponse.addKeyValues("error", "Problems reading stdout and stderr from " + cmd + "\n" + e.toString());
+ jsonResponse.addKeyValues("error", "Problems reading stdout and stderr from " + cmd + "\n" + e
+ .toString());
return jsonResponse.toString();
} finally {
process.destroy();
}
}
public static String inputStreamToString(InputStream is) throws IOException {
StringBuilder result = new StringBuilder();
int in;
while ((in = is.read()) != -1) {
result.append((char) in);
}
is.close();
return result.toString();
}
}
| false | true | public static String execRuntime(String cmd, boolean waitToFinish) {
System.out.println("Starting to execute - " + cmd);
JsonResponseBuilder jsonResponse = new JsonResponseBuilder();
jsonResponse.addKeyValues("exit_code", 1);
jsonResponse.addKeyValues("out", "");
jsonResponse.addKeyValues("error", "");
Process process;
try {
process = Runtime.getRuntime().exec(cmd);
} catch (IOException e) {
jsonResponse.addKeyValues("error", "Problems in running " + cmd + "\n" + e.toString());
return jsonResponse.toString();
}
int exitCode;
if (waitToFinish) {
try {
System.out.println("Waiting to finish");
exitCode = process.waitFor();
System.out.println("Command Finished");
} catch (InterruptedException e) {
jsonResponse.addKeyValues("error", "Interrupted running " + cmd + "\n" + e.toString());
return jsonResponse.toString();
}
} else {
System.out.println("Not waiting for finish");
jsonResponse.addKeyValues("exit_code", 0);
jsonResponse.addKeyValues("out", "Background process started");
return jsonResponse.toString();
}
try {
String output = inputStreamToString(process.getInputStream());
String error = inputStreamToString(process.getErrorStream());
jsonResponse.addKeyValues("exit_code", exitCode);
jsonResponse.addKeyValues("out", output);
jsonResponse.addKeyValues("error", error);
return jsonResponse.toString();
} catch (IOException e) {
jsonResponse.addKeyValues("error", "Problems reading stdout and stderr from " + cmd + "\n" + e.toString());
return jsonResponse.toString();
} finally {
process.destroy();
}
}
| public static String execRuntime(String cmd, boolean waitToFinish) {
System.out.println("Starting to execute - " + cmd);
JsonResponseBuilder jsonResponse = new JsonResponseBuilder();
Process process;
try {
process = Runtime.getRuntime().exec(cmd);
} catch (IOException e) {
jsonResponse.addKeyValues("error", "Problems in running " + cmd + "\n" + e.toString());
return jsonResponse.toString();
}
int exitCode;
if (waitToFinish) {
try {
System.out.println("Waiting to finish");
exitCode = process.waitFor();
System.out.println("Command Finished");
} catch (InterruptedException e) {
jsonResponse.addKeyValues("error", "Interrupted running " + cmd + "\n" + e.toString());
return jsonResponse.toString();
}
} else {
System.out.println("Not waiting for finish");
jsonResponse.addKeyValues("out", "Background process started");
return jsonResponse.toString();
}
try {
String output = inputStreamToString(process.getInputStream());
String error = inputStreamToString(process.getErrorStream());
jsonResponse.addKeyValues("exit_code", exitCode);
jsonResponse.addKeyValues("out", output);
if (!error.equals("")) {
//Only add error if there is one, this way we have a nice empty array instead of [""]
jsonResponse.addKeyValues("error", error);
}
return jsonResponse.toString();
} catch (IOException e) {
jsonResponse.addKeyValues("error", "Problems reading stdout and stderr from " + cmd + "\n" + e
.toString());
return jsonResponse.toString();
} finally {
process.destroy();
}
}
|
diff --git a/java/uk/ltd/getahead/dwr/create/PageFlowCreator.java b/java/uk/ltd/getahead/dwr/create/PageFlowCreator.java
index 13301c58..ea1283ee 100644
--- a/java/uk/ltd/getahead/dwr/create/PageFlowCreator.java
+++ b/java/uk/ltd/getahead/dwr/create/PageFlowCreator.java
@@ -1,130 +1,130 @@
package uk.ltd.getahead.dwr.create;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import javax.servlet.http.HttpServletRequest;
import uk.ltd.getahead.dwr.Creator;
import uk.ltd.getahead.dwr.WebContextFactory;
import uk.ltd.getahead.dwr.util.Logger;
/**
* Page Flow Creator
* The name Creator is a little misleading in that implies that a PageFlow is
* being created. This class merely returns the current PageFlowController from
* the Request
* @author Kevin Conaway
* @author Joe Walker [joe at getahead dot ltd dot uk]
*/
public class PageFlowCreator extends AbstractCreator implements Creator
{
/**
* Test to see what implementations of PageFlow are available.
* @throws ClassNotFoundException If neither Beehive or Weblogic are around.
*/
public PageFlowCreator() throws ClassNotFoundException
{
try
{
bhFlowClass = Class.forName("org.apache.beehive.netui.pageflow.PageFlowController"); //$NON-NLS-1$
Class bhUtilClass = Class.forName("org.apache.beehive.netui.pageflow.PageFlowUtils"); //$NON-NLS-1$
bhGetter = bhUtilClass.getMethod("getCurrentPageFlow", new Class[] { HttpServletRequest.class }); //$NON-NLS-1$
}
catch (Exception ex)
{
}
try
{
wlFlowClass = Class.forName("com.bea.wlw.netui.pageflow.PageFlowController"); //$NON-NLS-1$
Class wlUtilClass = Class.forName("com.bea.wlw.netui.pageflow.PageFlowUtils"); //$NON-NLS-1$
wlGetter = wlUtilClass.getMethod("getCurrentPageFlow", new Class[] { HttpServletRequest.class }); //$NON-NLS-1$
}
catch (Exception ex)
{
}
if ((bhGetter == null && wlGetter == null) ||
(bhFlowClass == null && wlFlowClass == null))
{
- throw new ClassNotFoundException("Beehive/Weblogic Creator not available."); //$NON-NLS-1$
+ throw new ClassNotFoundException("Beehive/Weblogic jar file not available."); //$NON-NLS-1$
}
}
/**
* What do we do if both Weblogic and Beehive are available.
* The default is to use Beehive, but this allows us to alter that.
* @param forceWebLogic Do we use Weblogic if both are available.
*/
public void setForceWebLogic(boolean forceWebLogic)
{
if (forceWebLogic)
{
bhGetter = null;
bhFlowClass = null;
}
}
/* (non-Javadoc)
* @see uk.ltd.getahead.dwr.Creator#getInstance()
*/
public Object getInstance() throws InstantiationException
{
if (getter == null)
{
getter = (bhGetter != null) ? bhGetter : wlGetter;
}
try
{
HttpServletRequest request = WebContextFactory.get().getHttpServletRequest();
return getter.invoke(null, new Object[] { request });
}
catch (InvocationTargetException ex)
{
throw new InstantiationException(ex.getTargetException().toString());
}
catch (Exception ex)
{
throw new InstantiationException(ex.toString());
}
}
/**
* @return The PageFlowController that we are using (Beehive/Weblogic)
*/
public Class getType()
{
if (instanceType == null)
{
try
{
instanceType = getInstance().getClass();
}
catch (InstantiationException ex)
{
log.error("Failed to instansiate object to detect type.", ex); //$NON-NLS-1$
return Object.class;
}
}
return instanceType;
}
/**
* The log stream
*/
private static final Logger log = Logger.getLogger(PageFlowCreator.class);
private Class instanceType;
private Method getter;
private Method bhGetter;
private Method wlGetter;
private Class bhFlowClass;
private Class wlFlowClass;
}
| true | true | public PageFlowCreator() throws ClassNotFoundException
{
try
{
bhFlowClass = Class.forName("org.apache.beehive.netui.pageflow.PageFlowController"); //$NON-NLS-1$
Class bhUtilClass = Class.forName("org.apache.beehive.netui.pageflow.PageFlowUtils"); //$NON-NLS-1$
bhGetter = bhUtilClass.getMethod("getCurrentPageFlow", new Class[] { HttpServletRequest.class }); //$NON-NLS-1$
}
catch (Exception ex)
{
}
try
{
wlFlowClass = Class.forName("com.bea.wlw.netui.pageflow.PageFlowController"); //$NON-NLS-1$
Class wlUtilClass = Class.forName("com.bea.wlw.netui.pageflow.PageFlowUtils"); //$NON-NLS-1$
wlGetter = wlUtilClass.getMethod("getCurrentPageFlow", new Class[] { HttpServletRequest.class }); //$NON-NLS-1$
}
catch (Exception ex)
{
}
if ((bhGetter == null && wlGetter == null) ||
(bhFlowClass == null && wlFlowClass == null))
{
throw new ClassNotFoundException("Beehive/Weblogic Creator not available."); //$NON-NLS-1$
}
}
| public PageFlowCreator() throws ClassNotFoundException
{
try
{
bhFlowClass = Class.forName("org.apache.beehive.netui.pageflow.PageFlowController"); //$NON-NLS-1$
Class bhUtilClass = Class.forName("org.apache.beehive.netui.pageflow.PageFlowUtils"); //$NON-NLS-1$
bhGetter = bhUtilClass.getMethod("getCurrentPageFlow", new Class[] { HttpServletRequest.class }); //$NON-NLS-1$
}
catch (Exception ex)
{
}
try
{
wlFlowClass = Class.forName("com.bea.wlw.netui.pageflow.PageFlowController"); //$NON-NLS-1$
Class wlUtilClass = Class.forName("com.bea.wlw.netui.pageflow.PageFlowUtils"); //$NON-NLS-1$
wlGetter = wlUtilClass.getMethod("getCurrentPageFlow", new Class[] { HttpServletRequest.class }); //$NON-NLS-1$
}
catch (Exception ex)
{
}
if ((bhGetter == null && wlGetter == null) ||
(bhFlowClass == null && wlFlowClass == null))
{
throw new ClassNotFoundException("Beehive/Weblogic jar file not available."); //$NON-NLS-1$
}
}
|
diff --git a/src/com/dmdirc/parser/ProcessJoin.java b/src/com/dmdirc/parser/ProcessJoin.java
index 22d177bf6..e0df3625a 100644
--- a/src/com/dmdirc/parser/ProcessJoin.java
+++ b/src/com/dmdirc/parser/ProcessJoin.java
@@ -1,141 +1,150 @@
/*
* Copyright (c) 2006-2008 Chris Smith, Shane Mc Cormack, Gregory Holmes
*
* 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.
*
* SVN: $Id$
*/
package com.dmdirc.parser;
import com.dmdirc.parser.callbacks.CallbackOnChannelJoin;
import com.dmdirc.parser.callbacks.CallbackOnChannelSelfJoin;
/**
* Process a channel join.
*/
public class ProcessJoin extends IRCProcessor {
/**
* Process a channel join.
*
* @param sParam Type of line to process ("JOIN")
* @param token IRCTokenised line to process
*/
public void process(final String sParam, final String[] token) {
if (sParam.equals("329")) {
if (token.length < 5) { return; }
ChannelInfo iChannel = myParser.getChannelInfo(token[3]);
if (iChannel != null) {
try {
iChannel.setCreateTime(Integer.parseInt(token[4]));
} catch (NumberFormatException nfe) { /* Oh well, not a normal ircd I guess */ }
}
} else {
// :nick!ident@host JOIN (:)#Channel
Byte nTemp;
if (token.length < 3) { return; }
ClientInfo iClient;
ChannelInfo iChannel;
ChannelClientInfo iChannelClient;
iClient = myParser.getClientInfo(token[0]);
iChannel = myParser.getChannelInfo(token[token.length-1]);
if (iClient == null) {
iClient = new ClientInfo(myParser, token[0]);
myParser.addClient(iClient);
}
// Check to see if we know the host/ident for this client to facilitate dmdirc Formatter
if (iClient.getHost().isEmpty()) { iClient.setUserBits(token[0],false); }
if (iChannel != null) {
if (iClient == myParser.getMyself()) {
try {
- myParser.getProcessingManager().process("PART", token);
+ if (iChannel.getUser(iClient) != null) {
+ // If we are joining a channel we are already on, fake a part from
+ // the channel internally, and rejoin.
+ myParser.getProcessingManager().process("PART", token);
+ } else {
+ // Otherwise we have a channel known, that we are not in?
+ myParser.callErrorInfo(new ParserError(ParserError.ERROR_FATAL, "Joined known channel that we wern't already on..", myParser.getLastLine()));
+ }
} catch (ProcessorNotFoundException e) { }
} else if (iChannel.getUser(iClient) != null) {
// Client joined channel that we already know of.
return;
} else {
// This is only done if we are already the channel, and it isn't us that
// joined.
iChannelClient = iChannel.addClient(iClient);
callChannelJoin(iChannel, iChannelClient);
return;
}
}
if (iClient != myParser.getMyself()) {
// callErrorInfo(new ParserError(ParserError.ERROR_WARNING, "Got join for channel ("+token[token.length-1]+") that I am not on. [Me: "+myParser.getMyself()+"]", myParser.getLastLine()));
}
iChannel = new ChannelInfo(myParser, token[token.length-1]);
+ // Add ourself to the channel, this will be overridden by the NAMES reply
+ iChannel.addClient(iClient);
myParser.addChannel(iChannel);
sendString("MODE "+iChannel.getName());
callChannelSelfJoin(iChannel);
}
}
/**
* Callback to all objects implementing the ChannelJoin Callback.
*
* @see IChannelJoin
* @param cChannel Channel Object
* @param cChannelClient ChannelClient object for new person
* @return true if a method was called, false otherwise
*/
protected boolean callChannelJoin(ChannelInfo cChannel, ChannelClientInfo cChannelClient) {
CallbackOnChannelJoin cb = (CallbackOnChannelJoin)getCallbackManager().getCallbackType("OnChannelJoin");
if (cb != null) { return cb.call(cChannel, cChannelClient); }
return false;
}
/**
* Callback to all objects implementing the ChannelSelfJoin Callback.
*
* @see IChannelSelfJoin
* @param cChannel Channel Object
* @return true if a method was called, false otherwise
*/
protected boolean callChannelSelfJoin(ChannelInfo cChannel) {
CallbackOnChannelSelfJoin cb = (CallbackOnChannelSelfJoin)getCallbackManager().getCallbackType("OnChannelSelfJoin");
if (cb != null) { return cb.call(cChannel); }
return false;
}
/**
* What does this IRCProcessor handle.
*
* @return String[] with the names of the tokens we handle.
*/
public String[] handles() {
String[] iHandle = new String[2];
iHandle[0] = "JOIN";
iHandle[1] = "329";
return iHandle;
}
/**
* Create a new instance of the IRCProcessor Object.
*
* @param parser IRCParser That owns this IRCProcessor
* @param manager ProcessingManager that is in charge of this IRCProcessor
*/
protected ProcessJoin (IRCParser parser, ProcessingManager manager) { super(parser, manager); }
}
| false | true | public void process(final String sParam, final String[] token) {
if (sParam.equals("329")) {
if (token.length < 5) { return; }
ChannelInfo iChannel = myParser.getChannelInfo(token[3]);
if (iChannel != null) {
try {
iChannel.setCreateTime(Integer.parseInt(token[4]));
} catch (NumberFormatException nfe) { /* Oh well, not a normal ircd I guess */ }
}
} else {
// :nick!ident@host JOIN (:)#Channel
Byte nTemp;
if (token.length < 3) { return; }
ClientInfo iClient;
ChannelInfo iChannel;
ChannelClientInfo iChannelClient;
iClient = myParser.getClientInfo(token[0]);
iChannel = myParser.getChannelInfo(token[token.length-1]);
if (iClient == null) {
iClient = new ClientInfo(myParser, token[0]);
myParser.addClient(iClient);
}
// Check to see if we know the host/ident for this client to facilitate dmdirc Formatter
if (iClient.getHost().isEmpty()) { iClient.setUserBits(token[0],false); }
if (iChannel != null) {
if (iClient == myParser.getMyself()) {
try {
myParser.getProcessingManager().process("PART", token);
} catch (ProcessorNotFoundException e) { }
} else if (iChannel.getUser(iClient) != null) {
// Client joined channel that we already know of.
return;
} else {
// This is only done if we are already the channel, and it isn't us that
// joined.
iChannelClient = iChannel.addClient(iClient);
callChannelJoin(iChannel, iChannelClient);
return;
}
}
if (iClient != myParser.getMyself()) {
// callErrorInfo(new ParserError(ParserError.ERROR_WARNING, "Got join for channel ("+token[token.length-1]+") that I am not on. [Me: "+myParser.getMyself()+"]", myParser.getLastLine()));
}
iChannel = new ChannelInfo(myParser, token[token.length-1]);
myParser.addChannel(iChannel);
sendString("MODE "+iChannel.getName());
callChannelSelfJoin(iChannel);
}
}
| public void process(final String sParam, final String[] token) {
if (sParam.equals("329")) {
if (token.length < 5) { return; }
ChannelInfo iChannel = myParser.getChannelInfo(token[3]);
if (iChannel != null) {
try {
iChannel.setCreateTime(Integer.parseInt(token[4]));
} catch (NumberFormatException nfe) { /* Oh well, not a normal ircd I guess */ }
}
} else {
// :nick!ident@host JOIN (:)#Channel
Byte nTemp;
if (token.length < 3) { return; }
ClientInfo iClient;
ChannelInfo iChannel;
ChannelClientInfo iChannelClient;
iClient = myParser.getClientInfo(token[0]);
iChannel = myParser.getChannelInfo(token[token.length-1]);
if (iClient == null) {
iClient = new ClientInfo(myParser, token[0]);
myParser.addClient(iClient);
}
// Check to see if we know the host/ident for this client to facilitate dmdirc Formatter
if (iClient.getHost().isEmpty()) { iClient.setUserBits(token[0],false); }
if (iChannel != null) {
if (iClient == myParser.getMyself()) {
try {
if (iChannel.getUser(iClient) != null) {
// If we are joining a channel we are already on, fake a part from
// the channel internally, and rejoin.
myParser.getProcessingManager().process("PART", token);
} else {
// Otherwise we have a channel known, that we are not in?
myParser.callErrorInfo(new ParserError(ParserError.ERROR_FATAL, "Joined known channel that we wern't already on..", myParser.getLastLine()));
}
} catch (ProcessorNotFoundException e) { }
} else if (iChannel.getUser(iClient) != null) {
// Client joined channel that we already know of.
return;
} else {
// This is only done if we are already the channel, and it isn't us that
// joined.
iChannelClient = iChannel.addClient(iClient);
callChannelJoin(iChannel, iChannelClient);
return;
}
}
if (iClient != myParser.getMyself()) {
// callErrorInfo(new ParserError(ParserError.ERROR_WARNING, "Got join for channel ("+token[token.length-1]+") that I am not on. [Me: "+myParser.getMyself()+"]", myParser.getLastLine()));
}
iChannel = new ChannelInfo(myParser, token[token.length-1]);
// Add ourself to the channel, this will be overridden by the NAMES reply
iChannel.addClient(iClient);
myParser.addChannel(iChannel);
sendString("MODE "+iChannel.getName());
callChannelSelfJoin(iChannel);
}
}
|
diff --git a/src/main/java/graphbuilder/twitter/TestTwokenizer.java b/src/main/java/graphbuilder/twitter/TestTwokenizer.java
index a008639..473729e 100644
--- a/src/main/java/graphbuilder/twitter/TestTwokenizer.java
+++ b/src/main/java/graphbuilder/twitter/TestTwokenizer.java
@@ -1,36 +1,44 @@
package graphbuilder.twitter;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.zip.GZIPInputStream;
public class TestTwokenizer {
public static void main (String[] args) throws FileNotFoundException, IOException {
File inputpath = new File(args[0]);
int parsedcount = 0;
for (File file : inputpath.listFiles()) {
System.out.println("Parsing " + file.getName());
InputStream in = new GZIPInputStream(new FileInputStream(file));
Reader decoder = new InputStreamReader(in);
BufferedReader buffered = new BufferedReader(decoder);
String line = null;
while((line = buffered.readLine()) != null) {
try {
TweetsJSParser parser = new TweetsJSParser(line);
+ System.out.println (parser.getText());
parser.tokenize();
parsedcount++;
} catch (Exception e) {
e.printStackTrace();
}
if (parsedcount % 10000 == 0)
System.out.println("Parsed " + parsedcount + "Tweets");
}
}
+ /*
+ String test = "7h... nh? a nh�u th?t nh�u ^^~...............................................";
+ test = test.toLowerCase().replaceAll("\\.{3,}", "\\.");
+ System.out.println(test);
+ Twokenize.tokenize(test);
+ System.out.println("done");
+ */
}
}
| false | true | public static void main (String[] args) throws FileNotFoundException, IOException {
File inputpath = new File(args[0]);
int parsedcount = 0;
for (File file : inputpath.listFiles()) {
System.out.println("Parsing " + file.getName());
InputStream in = new GZIPInputStream(new FileInputStream(file));
Reader decoder = new InputStreamReader(in);
BufferedReader buffered = new BufferedReader(decoder);
String line = null;
while((line = buffered.readLine()) != null) {
try {
TweetsJSParser parser = new TweetsJSParser(line);
parser.tokenize();
parsedcount++;
} catch (Exception e) {
e.printStackTrace();
}
if (parsedcount % 10000 == 0)
System.out.println("Parsed " + parsedcount + "Tweets");
}
}
}
| public static void main (String[] args) throws FileNotFoundException, IOException {
File inputpath = new File(args[0]);
int parsedcount = 0;
for (File file : inputpath.listFiles()) {
System.out.println("Parsing " + file.getName());
InputStream in = new GZIPInputStream(new FileInputStream(file));
Reader decoder = new InputStreamReader(in);
BufferedReader buffered = new BufferedReader(decoder);
String line = null;
while((line = buffered.readLine()) != null) {
try {
TweetsJSParser parser = new TweetsJSParser(line);
System.out.println (parser.getText());
parser.tokenize();
parsedcount++;
} catch (Exception e) {
e.printStackTrace();
}
if (parsedcount % 10000 == 0)
System.out.println("Parsed " + parsedcount + "Tweets");
}
}
/*
String test = "7h... nh? a nh�u th?t nh�u ^^~...............................................";
test = test.toLowerCase().replaceAll("\\.{3,}", "\\.");
System.out.println(test);
Twokenize.tokenize(test);
System.out.println("done");
*/
}
|
diff --git a/Capture/src/main/java/org/flightofstairs/honours/capture/agent/Tracer.java b/Capture/src/main/java/org/flightofstairs/honours/capture/agent/Tracer.java
index f46f8d4..efc8774 100644
--- a/Capture/src/main/java/org/flightofstairs/honours/capture/agent/Tracer.java
+++ b/Capture/src/main/java/org/flightofstairs/honours/capture/agent/Tracer.java
@@ -1,100 +1,101 @@
package org.flightofstairs.honours.capture.agent;
import java.rmi.ConnectException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.*;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.flightofstairs.honours.capture.recorder.RemoteRecorder;
import org.flightofstairs.honours.common.Call;
public enum Tracer {
INSTANCE;
/**
* Time between trace submits in ms.
*/
public static final int SUBMIT_DELAY = 200;
private final Queue<Call> toSend = new ConcurrentLinkedQueue<Call>();
private final RemoteRecorder recorder;
private Tracer() throws ExceptionInInitializerError {
try {
int port = Integer.parseInt(System.getProperty("org.flightofstairs.honours.capture.port"));
Registry registry = LocateRegistry.getRegistry(port);
recorder = (RemoteRecorder) registry.lookup("Recorder");
} catch (NumberFormatException ex) {
throw new ExceptionInInitializerError("Can't instantiate Tracer.");
} catch (RemoteException ex) {
throw new ExceptionInInitializerError("Can't instantiate Tracer.");
} catch (NotBoundException ex) {
throw new ExceptionInInitializerError("Can't instantiate Tracer.");
}
initSubmit();
initShutdown();
}
public void traceCall(Call call) {
toSend.add(call);
}
private void initShutdown() {
Thread thread = new Thread() {
@Override
public void run() {
try {
List<Call> toSendCopy = new LinkedList<Call>();
Call polled;
while((polled = toSend.poll()) != null) {
toSendCopy.add(polled);
}
recorder.addCalls(toSendCopy);
recorder.end();
} catch (RemoteException ex) {
}
}
};
Runtime.getRuntime().addShutdownHook(thread);
}
private void initSubmit() {
final Timer timer = new Timer();
final TimerTask task = new TimerTask() {
@Override
public void run() {
List<Call> toSendCopy;
synchronized(toSend) {
toSendCopy = new LinkedList<Call>(toSend);
+ toSend.clear();
}
try {
recorder.addCalls(toSendCopy);
toSend.clear();
} catch (ConnectException ex) {
Logger.getLogger(Tracer.class.getName()).log(Level.SEVERE, null, ex);
} catch (RemoteException ex) {
Logger.getLogger(Tracer.class.getName()).log(Level.SEVERE, null, ex);
}
}
};
timer.schedule(task, SUBMIT_DELAY, SUBMIT_DELAY);
}
}
| true | true | private void initSubmit() {
final Timer timer = new Timer();
final TimerTask task = new TimerTask() {
@Override
public void run() {
List<Call> toSendCopy;
synchronized(toSend) {
toSendCopy = new LinkedList<Call>(toSend);
}
try {
recorder.addCalls(toSendCopy);
toSend.clear();
} catch (ConnectException ex) {
Logger.getLogger(Tracer.class.getName()).log(Level.SEVERE, null, ex);
} catch (RemoteException ex) {
Logger.getLogger(Tracer.class.getName()).log(Level.SEVERE, null, ex);
}
}
};
timer.schedule(task, SUBMIT_DELAY, SUBMIT_DELAY);
}
| private void initSubmit() {
final Timer timer = new Timer();
final TimerTask task = new TimerTask() {
@Override
public void run() {
List<Call> toSendCopy;
synchronized(toSend) {
toSendCopy = new LinkedList<Call>(toSend);
toSend.clear();
}
try {
recorder.addCalls(toSendCopy);
toSend.clear();
} catch (ConnectException ex) {
Logger.getLogger(Tracer.class.getName()).log(Level.SEVERE, null, ex);
} catch (RemoteException ex) {
Logger.getLogger(Tracer.class.getName()).log(Level.SEVERE, null, ex);
}
}
};
timer.schedule(task, SUBMIT_DELAY, SUBMIT_DELAY);
}
|
diff --git a/baksmali/src/main/java/org/jf/baksmali/Renderers/LongRenderer.java b/baksmali/src/main/java/org/jf/baksmali/Renderers/LongRenderer.java
index 7dbe26b..70f46ed 100644
--- a/baksmali/src/main/java/org/jf/baksmali/Renderers/LongRenderer.java
+++ b/baksmali/src/main/java/org/jf/baksmali/Renderers/LongRenderer.java
@@ -1,45 +1,45 @@
/*
* [The "BSD licence"]
* Copyright (c) 2009 Ben Gruver
* 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. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 org.jf.baksmali.Renderers;
import org.antlr.stringtemplate.AttributeRenderer;
public class LongRenderer implements AttributeRenderer {
public String toString(Object o) {
Long l = (Long)o;
if (l < 0) {
- return "-0x" + Long.toHexString(-1 * l);
+ return "-0x" + Long.toHexString(-1 * l) + "L";
}
- return "0x" + Long.toHexString((Long)o);
+ return "0x" + Long.toHexString((Long)o) + "L";
}
public String toString(Object o, String s) {
return toString(o);
}
}
| false | true | public String toString(Object o) {
Long l = (Long)o;
if (l < 0) {
return "-0x" + Long.toHexString(-1 * l);
}
return "0x" + Long.toHexString((Long)o);
}
| public String toString(Object o) {
Long l = (Long)o;
if (l < 0) {
return "-0x" + Long.toHexString(-1 * l) + "L";
}
return "0x" + Long.toHexString((Long)o) + "L";
}
|
diff --git a/CSipSimple/src/com/csipsimple/utils/bluetooth/BluetoothWrapper.java b/CSipSimple/src/com/csipsimple/utils/bluetooth/BluetoothWrapper.java
index b3974e35..fba9fec3 100644
--- a/CSipSimple/src/com/csipsimple/utils/bluetooth/BluetoothWrapper.java
+++ b/CSipSimple/src/com/csipsimple/utils/bluetooth/BluetoothWrapper.java
@@ -1,60 +1,60 @@
/**
* Copyright (C) 2010-2012 Regis Montoya (aka r3gis - www.r3gis.fr)
* This file is part of CSipSimple.
*
* CSipSimple 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.
* If you own a pjsip commercial license you can also redistribute it
* and/or modify it under the terms of the GNU Lesser General Public License
* as an android library.
*
* CSipSimple 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.
*
* You should have received a copy of the GNU General Public License
* along with CSipSimple. If not, see <http://www.gnu.org/licenses/>.
*/
package com.csipsimple.utils.bluetooth;
import android.content.Context;
import com.csipsimple.service.MediaManager;
import com.csipsimple.utils.Compatibility;
public abstract class BluetoothWrapper {
private static BluetoothWrapper instance;
public static BluetoothWrapper getInstance(Context context) {
if(instance == null) {
- if(Compatibility.isCompatible(11)) {
+ if(Compatibility.isCompatible(14)) {
instance = new com.csipsimple.utils.bluetooth.BluetoothUtils14();
}else if(Compatibility.isCompatible(8)) {
instance = new com.csipsimple.utils.bluetooth.BluetoothUtils8();
}else {
instance = new com.csipsimple.utils.bluetooth.BluetoothUtils3();
}
if(instance != null) {
instance.setContext(context);
}
}
return instance;
}
protected BluetoothWrapper() {}
public abstract void setContext(Context context);
public abstract void setMediaManager(MediaManager manager);
public abstract boolean canBluetooth();
public abstract void setBluetoothOn(boolean on);
public abstract boolean isBluetoothOn();
public abstract void register();
public abstract void unregister();
public abstract boolean isBTHeadsetConnected();
}
| true | true | public static BluetoothWrapper getInstance(Context context) {
if(instance == null) {
if(Compatibility.isCompatible(11)) {
instance = new com.csipsimple.utils.bluetooth.BluetoothUtils14();
}else if(Compatibility.isCompatible(8)) {
instance = new com.csipsimple.utils.bluetooth.BluetoothUtils8();
}else {
instance = new com.csipsimple.utils.bluetooth.BluetoothUtils3();
}
if(instance != null) {
instance.setContext(context);
}
}
return instance;
}
| public static BluetoothWrapper getInstance(Context context) {
if(instance == null) {
if(Compatibility.isCompatible(14)) {
instance = new com.csipsimple.utils.bluetooth.BluetoothUtils14();
}else if(Compatibility.isCompatible(8)) {
instance = new com.csipsimple.utils.bluetooth.BluetoothUtils8();
}else {
instance = new com.csipsimple.utils.bluetooth.BluetoothUtils3();
}
if(instance != null) {
instance.setContext(context);
}
}
return instance;
}
|
diff --git a/source/com/mucommander/ui/theme/ThemeWriter.java b/source/com/mucommander/ui/theme/ThemeWriter.java
index 5c57a254..9a95513f 100644
--- a/source/com/mucommander/ui/theme/ThemeWriter.java
+++ b/source/com/mucommander/ui/theme/ThemeWriter.java
@@ -1,298 +1,298 @@
package com.mucommander.ui.theme;
import com.mucommander.xml.writer.*;
import java.awt.Color;
import java.awt.Font;
import java.io.*;
/**
* Class used to save themes in XML format.
* @author Nicolas Rinaudo
*/
class ThemeWriter implements ThemeXmlConstants {
// - Initialisation ------------------------------------------------------------------
// -----------------------------------------------------------------------------------
/**
* Prevents instanciation of the class.
*/
private ThemeWriter() {}
// - XML output ----------------------------------------------------------------------
// -----------------------------------------------------------------------------------
/**
* Saves the specified theme to the specified output stream.
* @param theme theme to save.
* @param stream where to write the theme to.
* @throws IOException thrown if any IO related error occurs.
*/
public static void write(ThemeData theme, OutputStream stream) throws IOException {
XmlWriter out;
Font font;
Color color;
out = new XmlWriter(stream);
out.startElement(ELEMENT_ROOT);
out.println();
// - File table description ------------------------------------------------------
// -------------------------------------------------------------------------------
out.startElement(ELEMENT_TABLE);
out.println();
if((font = theme.getFont(Theme.FILE_TABLE)) != null)
out.writeStandAloneElement(ELEMENT_FONT, getFontAttributes(font));
if((color = theme.getColor(Theme.FILE_TABLE_BORDER)) != null)
out.writeStandAloneElement(ELEMENT_BORDER, getColorAttributes(color));
// Normal colors.
out.startElement(ELEMENT_NORMAL);
out.println();
if((color = theme.getColor(Theme.FILE_BACKGROUND)) != null)
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(color));
if((color = theme.getColor(Theme.FILE_UNFOCUSED_BACKGROUND)) != null)
out.writeStandAloneElement(ELEMENT_UNFOCUSED_BACKGROUND, getColorAttributes(color));
if((color = theme.getColor(Theme.HIDDEN_FILE)) != null)
out.writeStandAloneElement(ELEMENT_HIDDEN, getColorAttributes(color));
if((color = theme.getColor(Theme.FOLDER)) != null)
out.writeStandAloneElement(ELEMENT_FOLDER, getColorAttributes(color));
if((color = theme.getColor(Theme.ARCHIVE)) != null)
out.writeStandAloneElement(ELEMENT_ARCHIVE, getColorAttributes(color));
if((color = theme.getColor(Theme.SYMLINK)) != null)
out.writeStandAloneElement(ELEMENT_SYMLINK, getColorAttributes(color));
if((color = theme.getColor(Theme.MARKED)) != null)
out.writeStandAloneElement(ELEMENT_MARKED, getColorAttributes(color));
if((color = theme.getColor(Theme.FILE)) != null)
out.writeStandAloneElement(ELEMENT_FILE, getColorAttributes(color));
out.endElement(ELEMENT_NORMAL);
// Selected colors.
out.startElement(ELEMENT_SELECTION);
out.println();
if((color = theme.getColor(Theme.FILE_BACKGROUND_SELECTED)) != null)
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(color));
if((color = theme.getColor(Theme.FILE_UNFOCUSED_BACKGROUND_SELECTED)) != null)
out.writeStandAloneElement(ELEMENT_UNFOCUSED_BACKGROUND, getColorAttributes(color));
if((color = theme.getColor(Theme.HIDDEN_FILE_SELECTED)) != null)
out.writeStandAloneElement(ELEMENT_HIDDEN, getColorAttributes(color));
if((color = theme.getColor(Theme.FOLDER_SELECTED)) != null)
out.writeStandAloneElement(ELEMENT_FOLDER, getColorAttributes(color));
if((color = theme.getColor(Theme.ARCHIVE_SELECTED)) != null)
out.writeStandAloneElement(ELEMENT_ARCHIVE, getColorAttributes(color));
if((color = theme.getColor(Theme.SYMLINK_SELECTED)) != null)
out.writeStandAloneElement(ELEMENT_SYMLINK, getColorAttributes(color));
if((color = theme.getColor(Theme.MARKED_SELECTED)) != null)
out.writeStandAloneElement(ELEMENT_MARKED, getColorAttributes(color));
if((color = theme.getColor(Theme.FILE_SELECTED)) != null)
out.writeStandAloneElement(ELEMENT_FILE, getColorAttributes(color));
out.endElement(ELEMENT_SELECTION);
out.endElement(ELEMENT_TABLE);
// - Shell description ----------------------------------------------------------
// -------------------------------------------------------------------------------
out.startElement(ELEMENT_SHELL);
out.println();
if((font = theme.getFont(Theme.SHELL)) != null)
out.writeStandAloneElement(ELEMENT_FONT, getFontAttributes(font));
// Normal colors.
out.startElement(ELEMENT_NORMAL);
out.println();
if((color = theme.getColor(Theme.SHELL_BACKGROUND)) != null)
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(color));
if((color = theme.getColor(Theme.SHELL_TEXT)) != null)
out.writeStandAloneElement(ELEMENT_TEXT, getColorAttributes(color));
out.endElement(ELEMENT_NORMAL);
// Selected colors.
out.startElement(ELEMENT_SELECTION);
out.println();
if((color = theme.getColor(Theme.SHELL_BACKGROUND_SELECTED)) != null)
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(color));
if((color = theme.getColor(Theme.SHELL_TEXT_SELECTED)) != null)
out.writeStandAloneElement(ELEMENT_TEXT, getColorAttributes(color));
out.endElement(ELEMENT_SELECTION);
out.endElement(ELEMENT_SHELL);
// - Shell history description ---------------------------------------------------
// -------------------------------------------------------------------------------
out.startElement(ELEMENT_SHELL_HISTORY);
out.println();
if((font = theme.getFont(Theme.SHELL_HISTORY)) != null)
out.writeStandAloneElement(ELEMENT_FONT, getFontAttributes(font));
// Normal colors.
out.startElement(ELEMENT_NORMAL);
out.println();
if((color = theme.getColor(Theme.SHELL_HISTORY_BACKGROUND)) != null)
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(color));
if((color = theme.getColor(Theme.SHELL_HISTORY_TEXT)) != null)
out.writeStandAloneElement(ELEMENT_TEXT, getColorAttributes(color));
out.endElement(ELEMENT_NORMAL);
// Selected colors.
out.startElement(ELEMENT_SELECTION);
out.println();
if((color = theme.getColor(Theme.SHELL_HISTORY_BACKGROUND_SELECTED)) != null)
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(color));
if((color = theme.getColor(Theme.SHELL_HISTORY_TEXT_SELECTED)) != null)
out.writeStandAloneElement(ELEMENT_TEXT, getColorAttributes(color));
out.endElement(ELEMENT_SELECTION);
- out.endElement(ELEMENT_SHELL);
+ out.endElement(ELEMENT_SHELL_HISTORY);
// - Editor description ----------------------------------------------------------
// -------------------------------------------------------------------------------
out.startElement(ELEMENT_EDITOR);
out.println();
if((font = theme.getFont(Theme.EDITOR)) != null)
out.writeStandAloneElement(ELEMENT_FONT, getFontAttributes(font));
// Normal colors.
out.startElement(ELEMENT_NORMAL);
out.println();
if((color = theme.getColor(Theme.EDITOR_BACKGROUND)) != null)
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(color));
if((color = theme.getColor(Theme.EDITOR_TEXT)) != null)
out.writeStandAloneElement(ELEMENT_TEXT, getColorAttributes(color));
out.endElement(ELEMENT_NORMAL);
// Selected colors.
out.startElement(ELEMENT_SELECTION);
out.println();
if((color = theme.getColor(Theme.EDITOR_BACKGROUND_SELECTED)) != null)
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(color));
if((color = theme.getColor(Theme.EDITOR_TEXT_SELECTED)) != null)
out.writeStandAloneElement(ELEMENT_TEXT, getColorAttributes(color));
out.endElement(ELEMENT_SELECTION);
out.endElement(ELEMENT_EDITOR);
// - Location bar description ----------------------------------------------------
// -------------------------------------------------------------------------------
out.startElement(ELEMENT_LOCATION_BAR);
out.println();
if((font = theme.getFont(Theme.LOCATION_BAR)) != null)
out.writeStandAloneElement(ELEMENT_FONT, getFontAttributes(font));
// Normal colors.
out.startElement(ELEMENT_NORMAL);
out.println();
if((color = theme.getColor(Theme.LOCATION_BAR_BACKGROUND)) != null)
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(color));
if((color = theme.getColor(Theme.LOCATION_BAR_TEXT)) != null)
out.writeStandAloneElement(ELEMENT_TEXT, getColorAttributes(color));
out.endElement(ELEMENT_NORMAL);
// Selected colors.
out.startElement(ELEMENT_SELECTION);
out.println();
if((color = theme.getColor(Theme.LOCATION_BAR_BACKGROUND_SELECTED)) != null)
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(color));
if((color = theme.getColor(Theme.LOCATION_BAR_TEXT_SELECTED)) != null)
out.writeStandAloneElement(ELEMENT_TEXT, getColorAttributes(color));
out.endElement(ELEMENT_SELECTION);
out.endElement(ELEMENT_EDITOR);
// - Volume label description ----------------------------------------------------
// -------------------------------------------------------------------------------
out.startElement(ELEMENT_STATUS_BAR);
out.println();
// Font.
if((font = theme.getFont(Theme.STATUS_BAR)) != null)
out.writeStandAloneElement(ELEMENT_FONT, getFontAttributes(font));
// Colors.
if((color = theme.getColor(Theme.STATUS_BAR_BACKGROUND)) != null)
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(color));
if((color = theme.getColor(Theme.STATUS_BAR_TEXT)) != null)
out.writeStandAloneElement(ELEMENT_TEXT, getColorAttributes(color));
if((color = theme.getColor(Theme.STATUS_BAR_BORDER)) != null)
out.writeStandAloneElement(ELEMENT_BORDER, getColorAttributes(color));
if((color = theme.getColor(Theme.STATUS_BAR_OK)) != null)
out.writeStandAloneElement(ELEMENT_OK, getColorAttributes(color));
if((color = theme.getColor(Theme.STATUS_BAR_WARNING)) != null)
out.writeStandAloneElement(ELEMENT_WARNING, getColorAttributes(color));
if((color = theme.getColor(Theme.STATUS_BAR_CRITICAL)) != null)
out.writeStandAloneElement(ELEMENT_CRITICAL, getColorAttributes(color));
out.endElement(ELEMENT_STATUS_BAR);
out.endElement(ELEMENT_ROOT);
}
// - Helper methods ------------------------------------------------------------------
// -----------------------------------------------------------------------------------
/**
* Returns the XML attributes describing the specified font.
* @param font font to described as XML attributes.
* @return the XML attributes describing the specified font.
*/
private static XmlAttributes getFontAttributes(Font font) {
XmlAttributes attributes; // Stores the font's description.
attributes = new XmlAttributes();
// Font family and size.
attributes.add(ATTRIBUTE_FAMILY, font.getFamily());
attributes.add(ATTRIBUTE_SIZE, Integer.toString(font.getSize()));
// Font style.
if(font.isBold())
attributes.add(ATTRIBUTE_BOLD, VALUE_TRUE);
if(font.isItalic())
attributes.add(ATTRIBUTE_ITALIC, VALUE_TRUE);
return attributes;
}
/**
* Returns the XML attributes describing the specified color.
* @param color color to described as XML attributes.
* @return the XML attributes describing the specified color.
*/
private static XmlAttributes getColorAttributes(Color color) {
XmlAttributes attributes; // Stores the color's description.
StringBuffer buffer; // Used to build the color's string representation.
buffer = new StringBuffer();
// Red component.
if(color.getRed() < 16)
buffer.append('0');
buffer.append(Integer.toString(color.getRed(), 16));
// Green component.
if(color.getGreen() < 16)
buffer.append('0');
buffer.append(Integer.toString(color.getGreen(), 16));
// Blue component.
if(color.getBlue() < 16)
buffer.append('0');
buffer.append(Integer.toString(color.getBlue(), 16));
// Builds the XML attributes.
attributes = new XmlAttributes();
attributes.add(ATTRIBUTE_COLOR, buffer.toString());
if(color.getAlpha() != 255) {
buffer.setLength(0);
if(color.getAlpha() < 16)
buffer.append('0');
buffer.append(Integer.toString(color.getAlpha(), 16));
attributes.add(ATTRIBUTE_ALPHA, buffer.toString());
}
return attributes;
}
}
| true | true | public static void write(ThemeData theme, OutputStream stream) throws IOException {
XmlWriter out;
Font font;
Color color;
out = new XmlWriter(stream);
out.startElement(ELEMENT_ROOT);
out.println();
// - File table description ------------------------------------------------------
// -------------------------------------------------------------------------------
out.startElement(ELEMENT_TABLE);
out.println();
if((font = theme.getFont(Theme.FILE_TABLE)) != null)
out.writeStandAloneElement(ELEMENT_FONT, getFontAttributes(font));
if((color = theme.getColor(Theme.FILE_TABLE_BORDER)) != null)
out.writeStandAloneElement(ELEMENT_BORDER, getColorAttributes(color));
// Normal colors.
out.startElement(ELEMENT_NORMAL);
out.println();
if((color = theme.getColor(Theme.FILE_BACKGROUND)) != null)
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(color));
if((color = theme.getColor(Theme.FILE_UNFOCUSED_BACKGROUND)) != null)
out.writeStandAloneElement(ELEMENT_UNFOCUSED_BACKGROUND, getColorAttributes(color));
if((color = theme.getColor(Theme.HIDDEN_FILE)) != null)
out.writeStandAloneElement(ELEMENT_HIDDEN, getColorAttributes(color));
if((color = theme.getColor(Theme.FOLDER)) != null)
out.writeStandAloneElement(ELEMENT_FOLDER, getColorAttributes(color));
if((color = theme.getColor(Theme.ARCHIVE)) != null)
out.writeStandAloneElement(ELEMENT_ARCHIVE, getColorAttributes(color));
if((color = theme.getColor(Theme.SYMLINK)) != null)
out.writeStandAloneElement(ELEMENT_SYMLINK, getColorAttributes(color));
if((color = theme.getColor(Theme.MARKED)) != null)
out.writeStandAloneElement(ELEMENT_MARKED, getColorAttributes(color));
if((color = theme.getColor(Theme.FILE)) != null)
out.writeStandAloneElement(ELEMENT_FILE, getColorAttributes(color));
out.endElement(ELEMENT_NORMAL);
// Selected colors.
out.startElement(ELEMENT_SELECTION);
out.println();
if((color = theme.getColor(Theme.FILE_BACKGROUND_SELECTED)) != null)
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(color));
if((color = theme.getColor(Theme.FILE_UNFOCUSED_BACKGROUND_SELECTED)) != null)
out.writeStandAloneElement(ELEMENT_UNFOCUSED_BACKGROUND, getColorAttributes(color));
if((color = theme.getColor(Theme.HIDDEN_FILE_SELECTED)) != null)
out.writeStandAloneElement(ELEMENT_HIDDEN, getColorAttributes(color));
if((color = theme.getColor(Theme.FOLDER_SELECTED)) != null)
out.writeStandAloneElement(ELEMENT_FOLDER, getColorAttributes(color));
if((color = theme.getColor(Theme.ARCHIVE_SELECTED)) != null)
out.writeStandAloneElement(ELEMENT_ARCHIVE, getColorAttributes(color));
if((color = theme.getColor(Theme.SYMLINK_SELECTED)) != null)
out.writeStandAloneElement(ELEMENT_SYMLINK, getColorAttributes(color));
if((color = theme.getColor(Theme.MARKED_SELECTED)) != null)
out.writeStandAloneElement(ELEMENT_MARKED, getColorAttributes(color));
if((color = theme.getColor(Theme.FILE_SELECTED)) != null)
out.writeStandAloneElement(ELEMENT_FILE, getColorAttributes(color));
out.endElement(ELEMENT_SELECTION);
out.endElement(ELEMENT_TABLE);
// - Shell description ----------------------------------------------------------
// -------------------------------------------------------------------------------
out.startElement(ELEMENT_SHELL);
out.println();
if((font = theme.getFont(Theme.SHELL)) != null)
out.writeStandAloneElement(ELEMENT_FONT, getFontAttributes(font));
// Normal colors.
out.startElement(ELEMENT_NORMAL);
out.println();
if((color = theme.getColor(Theme.SHELL_BACKGROUND)) != null)
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(color));
if((color = theme.getColor(Theme.SHELL_TEXT)) != null)
out.writeStandAloneElement(ELEMENT_TEXT, getColorAttributes(color));
out.endElement(ELEMENT_NORMAL);
// Selected colors.
out.startElement(ELEMENT_SELECTION);
out.println();
if((color = theme.getColor(Theme.SHELL_BACKGROUND_SELECTED)) != null)
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(color));
if((color = theme.getColor(Theme.SHELL_TEXT_SELECTED)) != null)
out.writeStandAloneElement(ELEMENT_TEXT, getColorAttributes(color));
out.endElement(ELEMENT_SELECTION);
out.endElement(ELEMENT_SHELL);
// - Shell history description ---------------------------------------------------
// -------------------------------------------------------------------------------
out.startElement(ELEMENT_SHELL_HISTORY);
out.println();
if((font = theme.getFont(Theme.SHELL_HISTORY)) != null)
out.writeStandAloneElement(ELEMENT_FONT, getFontAttributes(font));
// Normal colors.
out.startElement(ELEMENT_NORMAL);
out.println();
if((color = theme.getColor(Theme.SHELL_HISTORY_BACKGROUND)) != null)
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(color));
if((color = theme.getColor(Theme.SHELL_HISTORY_TEXT)) != null)
out.writeStandAloneElement(ELEMENT_TEXT, getColorAttributes(color));
out.endElement(ELEMENT_NORMAL);
// Selected colors.
out.startElement(ELEMENT_SELECTION);
out.println();
if((color = theme.getColor(Theme.SHELL_HISTORY_BACKGROUND_SELECTED)) != null)
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(color));
if((color = theme.getColor(Theme.SHELL_HISTORY_TEXT_SELECTED)) != null)
out.writeStandAloneElement(ELEMENT_TEXT, getColorAttributes(color));
out.endElement(ELEMENT_SELECTION);
out.endElement(ELEMENT_SHELL);
// - Editor description ----------------------------------------------------------
// -------------------------------------------------------------------------------
out.startElement(ELEMENT_EDITOR);
out.println();
if((font = theme.getFont(Theme.EDITOR)) != null)
out.writeStandAloneElement(ELEMENT_FONT, getFontAttributes(font));
// Normal colors.
out.startElement(ELEMENT_NORMAL);
out.println();
if((color = theme.getColor(Theme.EDITOR_BACKGROUND)) != null)
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(color));
if((color = theme.getColor(Theme.EDITOR_TEXT)) != null)
out.writeStandAloneElement(ELEMENT_TEXT, getColorAttributes(color));
out.endElement(ELEMENT_NORMAL);
// Selected colors.
out.startElement(ELEMENT_SELECTION);
out.println();
if((color = theme.getColor(Theme.EDITOR_BACKGROUND_SELECTED)) != null)
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(color));
if((color = theme.getColor(Theme.EDITOR_TEXT_SELECTED)) != null)
out.writeStandAloneElement(ELEMENT_TEXT, getColorAttributes(color));
out.endElement(ELEMENT_SELECTION);
out.endElement(ELEMENT_EDITOR);
// - Location bar description ----------------------------------------------------
// -------------------------------------------------------------------------------
out.startElement(ELEMENT_LOCATION_BAR);
out.println();
if((font = theme.getFont(Theme.LOCATION_BAR)) != null)
out.writeStandAloneElement(ELEMENT_FONT, getFontAttributes(font));
// Normal colors.
out.startElement(ELEMENT_NORMAL);
out.println();
if((color = theme.getColor(Theme.LOCATION_BAR_BACKGROUND)) != null)
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(color));
if((color = theme.getColor(Theme.LOCATION_BAR_TEXT)) != null)
out.writeStandAloneElement(ELEMENT_TEXT, getColorAttributes(color));
out.endElement(ELEMENT_NORMAL);
// Selected colors.
out.startElement(ELEMENT_SELECTION);
out.println();
if((color = theme.getColor(Theme.LOCATION_BAR_BACKGROUND_SELECTED)) != null)
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(color));
if((color = theme.getColor(Theme.LOCATION_BAR_TEXT_SELECTED)) != null)
out.writeStandAloneElement(ELEMENT_TEXT, getColorAttributes(color));
out.endElement(ELEMENT_SELECTION);
out.endElement(ELEMENT_EDITOR);
// - Volume label description ----------------------------------------------------
// -------------------------------------------------------------------------------
out.startElement(ELEMENT_STATUS_BAR);
out.println();
// Font.
if((font = theme.getFont(Theme.STATUS_BAR)) != null)
out.writeStandAloneElement(ELEMENT_FONT, getFontAttributes(font));
// Colors.
if((color = theme.getColor(Theme.STATUS_BAR_BACKGROUND)) != null)
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(color));
if((color = theme.getColor(Theme.STATUS_BAR_TEXT)) != null)
out.writeStandAloneElement(ELEMENT_TEXT, getColorAttributes(color));
if((color = theme.getColor(Theme.STATUS_BAR_BORDER)) != null)
out.writeStandAloneElement(ELEMENT_BORDER, getColorAttributes(color));
if((color = theme.getColor(Theme.STATUS_BAR_OK)) != null)
out.writeStandAloneElement(ELEMENT_OK, getColorAttributes(color));
if((color = theme.getColor(Theme.STATUS_BAR_WARNING)) != null)
out.writeStandAloneElement(ELEMENT_WARNING, getColorAttributes(color));
if((color = theme.getColor(Theme.STATUS_BAR_CRITICAL)) != null)
out.writeStandAloneElement(ELEMENT_CRITICAL, getColorAttributes(color));
out.endElement(ELEMENT_STATUS_BAR);
out.endElement(ELEMENT_ROOT);
}
| public static void write(ThemeData theme, OutputStream stream) throws IOException {
XmlWriter out;
Font font;
Color color;
out = new XmlWriter(stream);
out.startElement(ELEMENT_ROOT);
out.println();
// - File table description ------------------------------------------------------
// -------------------------------------------------------------------------------
out.startElement(ELEMENT_TABLE);
out.println();
if((font = theme.getFont(Theme.FILE_TABLE)) != null)
out.writeStandAloneElement(ELEMENT_FONT, getFontAttributes(font));
if((color = theme.getColor(Theme.FILE_TABLE_BORDER)) != null)
out.writeStandAloneElement(ELEMENT_BORDER, getColorAttributes(color));
// Normal colors.
out.startElement(ELEMENT_NORMAL);
out.println();
if((color = theme.getColor(Theme.FILE_BACKGROUND)) != null)
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(color));
if((color = theme.getColor(Theme.FILE_UNFOCUSED_BACKGROUND)) != null)
out.writeStandAloneElement(ELEMENT_UNFOCUSED_BACKGROUND, getColorAttributes(color));
if((color = theme.getColor(Theme.HIDDEN_FILE)) != null)
out.writeStandAloneElement(ELEMENT_HIDDEN, getColorAttributes(color));
if((color = theme.getColor(Theme.FOLDER)) != null)
out.writeStandAloneElement(ELEMENT_FOLDER, getColorAttributes(color));
if((color = theme.getColor(Theme.ARCHIVE)) != null)
out.writeStandAloneElement(ELEMENT_ARCHIVE, getColorAttributes(color));
if((color = theme.getColor(Theme.SYMLINK)) != null)
out.writeStandAloneElement(ELEMENT_SYMLINK, getColorAttributes(color));
if((color = theme.getColor(Theme.MARKED)) != null)
out.writeStandAloneElement(ELEMENT_MARKED, getColorAttributes(color));
if((color = theme.getColor(Theme.FILE)) != null)
out.writeStandAloneElement(ELEMENT_FILE, getColorAttributes(color));
out.endElement(ELEMENT_NORMAL);
// Selected colors.
out.startElement(ELEMENT_SELECTION);
out.println();
if((color = theme.getColor(Theme.FILE_BACKGROUND_SELECTED)) != null)
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(color));
if((color = theme.getColor(Theme.FILE_UNFOCUSED_BACKGROUND_SELECTED)) != null)
out.writeStandAloneElement(ELEMENT_UNFOCUSED_BACKGROUND, getColorAttributes(color));
if((color = theme.getColor(Theme.HIDDEN_FILE_SELECTED)) != null)
out.writeStandAloneElement(ELEMENT_HIDDEN, getColorAttributes(color));
if((color = theme.getColor(Theme.FOLDER_SELECTED)) != null)
out.writeStandAloneElement(ELEMENT_FOLDER, getColorAttributes(color));
if((color = theme.getColor(Theme.ARCHIVE_SELECTED)) != null)
out.writeStandAloneElement(ELEMENT_ARCHIVE, getColorAttributes(color));
if((color = theme.getColor(Theme.SYMLINK_SELECTED)) != null)
out.writeStandAloneElement(ELEMENT_SYMLINK, getColorAttributes(color));
if((color = theme.getColor(Theme.MARKED_SELECTED)) != null)
out.writeStandAloneElement(ELEMENT_MARKED, getColorAttributes(color));
if((color = theme.getColor(Theme.FILE_SELECTED)) != null)
out.writeStandAloneElement(ELEMENT_FILE, getColorAttributes(color));
out.endElement(ELEMENT_SELECTION);
out.endElement(ELEMENT_TABLE);
// - Shell description ----------------------------------------------------------
// -------------------------------------------------------------------------------
out.startElement(ELEMENT_SHELL);
out.println();
if((font = theme.getFont(Theme.SHELL)) != null)
out.writeStandAloneElement(ELEMENT_FONT, getFontAttributes(font));
// Normal colors.
out.startElement(ELEMENT_NORMAL);
out.println();
if((color = theme.getColor(Theme.SHELL_BACKGROUND)) != null)
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(color));
if((color = theme.getColor(Theme.SHELL_TEXT)) != null)
out.writeStandAloneElement(ELEMENT_TEXT, getColorAttributes(color));
out.endElement(ELEMENT_NORMAL);
// Selected colors.
out.startElement(ELEMENT_SELECTION);
out.println();
if((color = theme.getColor(Theme.SHELL_BACKGROUND_SELECTED)) != null)
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(color));
if((color = theme.getColor(Theme.SHELL_TEXT_SELECTED)) != null)
out.writeStandAloneElement(ELEMENT_TEXT, getColorAttributes(color));
out.endElement(ELEMENT_SELECTION);
out.endElement(ELEMENT_SHELL);
// - Shell history description ---------------------------------------------------
// -------------------------------------------------------------------------------
out.startElement(ELEMENT_SHELL_HISTORY);
out.println();
if((font = theme.getFont(Theme.SHELL_HISTORY)) != null)
out.writeStandAloneElement(ELEMENT_FONT, getFontAttributes(font));
// Normal colors.
out.startElement(ELEMENT_NORMAL);
out.println();
if((color = theme.getColor(Theme.SHELL_HISTORY_BACKGROUND)) != null)
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(color));
if((color = theme.getColor(Theme.SHELL_HISTORY_TEXT)) != null)
out.writeStandAloneElement(ELEMENT_TEXT, getColorAttributes(color));
out.endElement(ELEMENT_NORMAL);
// Selected colors.
out.startElement(ELEMENT_SELECTION);
out.println();
if((color = theme.getColor(Theme.SHELL_HISTORY_BACKGROUND_SELECTED)) != null)
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(color));
if((color = theme.getColor(Theme.SHELL_HISTORY_TEXT_SELECTED)) != null)
out.writeStandAloneElement(ELEMENT_TEXT, getColorAttributes(color));
out.endElement(ELEMENT_SELECTION);
out.endElement(ELEMENT_SHELL_HISTORY);
// - Editor description ----------------------------------------------------------
// -------------------------------------------------------------------------------
out.startElement(ELEMENT_EDITOR);
out.println();
if((font = theme.getFont(Theme.EDITOR)) != null)
out.writeStandAloneElement(ELEMENT_FONT, getFontAttributes(font));
// Normal colors.
out.startElement(ELEMENT_NORMAL);
out.println();
if((color = theme.getColor(Theme.EDITOR_BACKGROUND)) != null)
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(color));
if((color = theme.getColor(Theme.EDITOR_TEXT)) != null)
out.writeStandAloneElement(ELEMENT_TEXT, getColorAttributes(color));
out.endElement(ELEMENT_NORMAL);
// Selected colors.
out.startElement(ELEMENT_SELECTION);
out.println();
if((color = theme.getColor(Theme.EDITOR_BACKGROUND_SELECTED)) != null)
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(color));
if((color = theme.getColor(Theme.EDITOR_TEXT_SELECTED)) != null)
out.writeStandAloneElement(ELEMENT_TEXT, getColorAttributes(color));
out.endElement(ELEMENT_SELECTION);
out.endElement(ELEMENT_EDITOR);
// - Location bar description ----------------------------------------------------
// -------------------------------------------------------------------------------
out.startElement(ELEMENT_LOCATION_BAR);
out.println();
if((font = theme.getFont(Theme.LOCATION_BAR)) != null)
out.writeStandAloneElement(ELEMENT_FONT, getFontAttributes(font));
// Normal colors.
out.startElement(ELEMENT_NORMAL);
out.println();
if((color = theme.getColor(Theme.LOCATION_BAR_BACKGROUND)) != null)
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(color));
if((color = theme.getColor(Theme.LOCATION_BAR_TEXT)) != null)
out.writeStandAloneElement(ELEMENT_TEXT, getColorAttributes(color));
out.endElement(ELEMENT_NORMAL);
// Selected colors.
out.startElement(ELEMENT_SELECTION);
out.println();
if((color = theme.getColor(Theme.LOCATION_BAR_BACKGROUND_SELECTED)) != null)
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(color));
if((color = theme.getColor(Theme.LOCATION_BAR_TEXT_SELECTED)) != null)
out.writeStandAloneElement(ELEMENT_TEXT, getColorAttributes(color));
out.endElement(ELEMENT_SELECTION);
out.endElement(ELEMENT_EDITOR);
// - Volume label description ----------------------------------------------------
// -------------------------------------------------------------------------------
out.startElement(ELEMENT_STATUS_BAR);
out.println();
// Font.
if((font = theme.getFont(Theme.STATUS_BAR)) != null)
out.writeStandAloneElement(ELEMENT_FONT, getFontAttributes(font));
// Colors.
if((color = theme.getColor(Theme.STATUS_BAR_BACKGROUND)) != null)
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(color));
if((color = theme.getColor(Theme.STATUS_BAR_TEXT)) != null)
out.writeStandAloneElement(ELEMENT_TEXT, getColorAttributes(color));
if((color = theme.getColor(Theme.STATUS_BAR_BORDER)) != null)
out.writeStandAloneElement(ELEMENT_BORDER, getColorAttributes(color));
if((color = theme.getColor(Theme.STATUS_BAR_OK)) != null)
out.writeStandAloneElement(ELEMENT_OK, getColorAttributes(color));
if((color = theme.getColor(Theme.STATUS_BAR_WARNING)) != null)
out.writeStandAloneElement(ELEMENT_WARNING, getColorAttributes(color));
if((color = theme.getColor(Theme.STATUS_BAR_CRITICAL)) != null)
out.writeStandAloneElement(ELEMENT_CRITICAL, getColorAttributes(color));
out.endElement(ELEMENT_STATUS_BAR);
out.endElement(ELEMENT_ROOT);
}
|
diff --git a/java/modules/core/src/main/java/org/apache/synapse/core/axis2/SynapseModule.java b/java/modules/core/src/main/java/org/apache/synapse/core/axis2/SynapseModule.java
index f5f81d4f8..38fcd965e 100644
--- a/java/modules/core/src/main/java/org/apache/synapse/core/axis2/SynapseModule.java
+++ b/java/modules/core/src/main/java/org/apache/synapse/core/axis2/SynapseModule.java
@@ -1,181 +1,183 @@
/*
* 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.synapse.core.axis2;
import org.apache.axis2.AxisFault;
import org.apache.axis2.addressing.AddressingConstants;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.description.*;
import org.apache.axis2.engine.AxisConfiguration;
import org.apache.axis2.modules.Module;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.MDC;
import org.apache.neethi.Assertion;
import org.apache.neethi.Policy;
import org.apache.synapse.Constants;
import org.apache.synapse.SynapseException;
import org.apache.synapse.config.SynapseConfiguration;
import org.apache.synapse.config.SynapseConfigurationBuilder;
import javax.xml.namespace.QName;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;
/**
* This is the Synapse Module implementation class, which would initialize Synapse when it is
* deployed onto an Axis2 configuration.
*/
public class SynapseModule implements Module {
private static final Log log = LogFactory.getLog(SynapseModule.class);
private static final String SYNAPSE_SERVICE_NAME = "synapse";
private static final QName MEDIATE_OPERATION_Q_NAME = new QName("mediate");
public void init(ConfigurationContext configurationContext,
AxisModule axisModule) throws AxisFault {
try {
InetAddress addr = InetAddress.getLocalHost();
if (addr != null) {
// Get IP Address
String ipAddr = addr.getHostAddress();
if (ipAddr != null) {
MDC.put("ip", ipAddr);
}
// Get hostname
String hostname = addr.getHostName();
if (hostname == null) {
hostname = ipAddr;
}
MDC.put("host", hostname);
}
} catch (UnknownHostException e) {
log.warn("Unable to report hostname or IP address for tracing", e);
}
// Initializing the SynapseEnvironment and SynapseConfiguration
log.info("Initializing the Synapse configuration ...");
SynapseConfiguration synCfg = initializeSynapse(configurationContext);
log.info("Deploying the Synapse service..");
// Dynamically initialize the Synapse Service and deploy it into Axis2
AxisConfiguration axisCfg = configurationContext.getAxisConfiguration();
AxisService synapseService = new AxisService(SYNAPSE_SERVICE_NAME);
AxisOperation mediateOperation = new InOutAxisOperation(MEDIATE_OPERATION_Q_NAME);
mediateOperation.setMessageReceiver(new SynapseMessageReceiver());
synapseService.addOperation(mediateOperation);
List transports = new ArrayList();
transports.add(org.apache.axis2.Constants.TRANSPORT_HTTP);
transports.add("https");
synapseService.setExposedTransports(transports);
axisCfg.addService(synapseService);
log.info("Initializing Sandesha 2...");
AxisModule sandeshaAxisModule = configurationContext.getAxisConfiguration().
getModule(Constants.SANDESHA2_MODULE_NAME);
- Module sandesha2 = sandeshaAxisModule.getModule();
- sandesha2.init(configurationContext, sandeshaAxisModule);
+ if (sandeshaAxisModule != null) {
+ Module sandesha2 = sandeshaAxisModule.getModule();
+ sandesha2.init(configurationContext, sandeshaAxisModule);
+ }
log.info("Deploying Proxy services...");
Iterator iter = synCfg.getProxyServices().iterator();
while (iter.hasNext()) {
ProxyService proxy = (ProxyService) iter.next();
proxy.buildAxisService(synCfg, axisCfg);
log.debug("Deployed Proxy service : " + proxy.getName());
if (!proxy.isStartOnLoad()) {
proxy.stop(synCfg);
}
}
log.info("Synapse initialized successfully...!");
}
private static SynapseConfiguration initializeSynapse(
ConfigurationContext cfgCtx) {
cfgCtx.setProperty("addressing.validateAction", Boolean.FALSE);
AxisConfiguration axisConfiguration = cfgCtx.getAxisConfiguration();
SynapseConfiguration synapseConfiguration;
String config = System.getProperty(Constants.SYNAPSE_XML);
if (config != null) {
log.debug("System property '" + Constants.SYNAPSE_XML +
"' specifies synapse configuration as " + config);
synapseConfiguration = SynapseConfigurationBuilder.getConfiguration(config);
} else {
log.warn("System property '" + Constants.SYNAPSE_XML +
"' is not specified. Using default configuration..");
synapseConfiguration = SynapseConfigurationBuilder.getDefaultConfiguration();
}
// Set the Axis2 ConfigurationContext to the SynapseConfiguration
synapseConfiguration.setAxisConfiguration(cfgCtx.getAxisConfiguration());
// set the Synapse configuration and environment into the Axis2 configuration
Parameter synapseCtxParam = new Parameter(Constants.SYNAPSE_CONFIG, null);
synapseCtxParam.setValue(synapseConfiguration);
MessageContextCreatorForAxis2.setSynConfig(synapseConfiguration);
Parameter synapseEnvParam = new Parameter(Constants.SYNAPSE_ENV, null);
Axis2SynapseEnvironment synEnv = new Axis2SynapseEnvironment(cfgCtx, synapseConfiguration);
synapseEnvParam.setValue(synEnv);
MessageContextCreatorForAxis2.setSynEnv(synEnv);
try {
axisConfiguration.addParameter(synapseCtxParam);
axisConfiguration.addParameter(synapseEnvParam);
} catch (AxisFault e) {
String msg =
"Could not set parameters '" + Constants.SYNAPSE_CONFIG +
"' and/or '" + Constants.SYNAPSE_ENV +
"'to the Axis2 configuration : " + e.getMessage();
log.fatal(msg, e);
throw new SynapseException(msg, e);
}
return synapseConfiguration;
}
public void engageNotify(AxisDescription axisDescription) throws AxisFault {
// ignore
}
public boolean canSupportAssertion(Assertion assertion) {
return false;
}
public void applyPolicy(Policy policy, AxisDescription axisDescription) throws AxisFault {
// no implementation
}
public void shutdown(ConfigurationContext configurationContext)
throws AxisFault {
// ignore
}
}
| true | true | public void init(ConfigurationContext configurationContext,
AxisModule axisModule) throws AxisFault {
try {
InetAddress addr = InetAddress.getLocalHost();
if (addr != null) {
// Get IP Address
String ipAddr = addr.getHostAddress();
if (ipAddr != null) {
MDC.put("ip", ipAddr);
}
// Get hostname
String hostname = addr.getHostName();
if (hostname == null) {
hostname = ipAddr;
}
MDC.put("host", hostname);
}
} catch (UnknownHostException e) {
log.warn("Unable to report hostname or IP address for tracing", e);
}
// Initializing the SynapseEnvironment and SynapseConfiguration
log.info("Initializing the Synapse configuration ...");
SynapseConfiguration synCfg = initializeSynapse(configurationContext);
log.info("Deploying the Synapse service..");
// Dynamically initialize the Synapse Service and deploy it into Axis2
AxisConfiguration axisCfg = configurationContext.getAxisConfiguration();
AxisService synapseService = new AxisService(SYNAPSE_SERVICE_NAME);
AxisOperation mediateOperation = new InOutAxisOperation(MEDIATE_OPERATION_Q_NAME);
mediateOperation.setMessageReceiver(new SynapseMessageReceiver());
synapseService.addOperation(mediateOperation);
List transports = new ArrayList();
transports.add(org.apache.axis2.Constants.TRANSPORT_HTTP);
transports.add("https");
synapseService.setExposedTransports(transports);
axisCfg.addService(synapseService);
log.info("Initializing Sandesha 2...");
AxisModule sandeshaAxisModule = configurationContext.getAxisConfiguration().
getModule(Constants.SANDESHA2_MODULE_NAME);
Module sandesha2 = sandeshaAxisModule.getModule();
sandesha2.init(configurationContext, sandeshaAxisModule);
log.info("Deploying Proxy services...");
Iterator iter = synCfg.getProxyServices().iterator();
while (iter.hasNext()) {
ProxyService proxy = (ProxyService) iter.next();
proxy.buildAxisService(synCfg, axisCfg);
log.debug("Deployed Proxy service : " + proxy.getName());
if (!proxy.isStartOnLoad()) {
proxy.stop(synCfg);
}
}
log.info("Synapse initialized successfully...!");
}
| public void init(ConfigurationContext configurationContext,
AxisModule axisModule) throws AxisFault {
try {
InetAddress addr = InetAddress.getLocalHost();
if (addr != null) {
// Get IP Address
String ipAddr = addr.getHostAddress();
if (ipAddr != null) {
MDC.put("ip", ipAddr);
}
// Get hostname
String hostname = addr.getHostName();
if (hostname == null) {
hostname = ipAddr;
}
MDC.put("host", hostname);
}
} catch (UnknownHostException e) {
log.warn("Unable to report hostname or IP address for tracing", e);
}
// Initializing the SynapseEnvironment and SynapseConfiguration
log.info("Initializing the Synapse configuration ...");
SynapseConfiguration synCfg = initializeSynapse(configurationContext);
log.info("Deploying the Synapse service..");
// Dynamically initialize the Synapse Service and deploy it into Axis2
AxisConfiguration axisCfg = configurationContext.getAxisConfiguration();
AxisService synapseService = new AxisService(SYNAPSE_SERVICE_NAME);
AxisOperation mediateOperation = new InOutAxisOperation(MEDIATE_OPERATION_Q_NAME);
mediateOperation.setMessageReceiver(new SynapseMessageReceiver());
synapseService.addOperation(mediateOperation);
List transports = new ArrayList();
transports.add(org.apache.axis2.Constants.TRANSPORT_HTTP);
transports.add("https");
synapseService.setExposedTransports(transports);
axisCfg.addService(synapseService);
log.info("Initializing Sandesha 2...");
AxisModule sandeshaAxisModule = configurationContext.getAxisConfiguration().
getModule(Constants.SANDESHA2_MODULE_NAME);
if (sandeshaAxisModule != null) {
Module sandesha2 = sandeshaAxisModule.getModule();
sandesha2.init(configurationContext, sandeshaAxisModule);
}
log.info("Deploying Proxy services...");
Iterator iter = synCfg.getProxyServices().iterator();
while (iter.hasNext()) {
ProxyService proxy = (ProxyService) iter.next();
proxy.buildAxisService(synCfg, axisCfg);
log.debug("Deployed Proxy service : " + proxy.getName());
if (!proxy.isStartOnLoad()) {
proxy.stop(synCfg);
}
}
log.info("Synapse initialized successfully...!");
}
|
diff --git a/src/main/java/com/treasure_data/bulk_import/writer/JSONFileWriter.java b/src/main/java/com/treasure_data/bulk_import/writer/JSONFileWriter.java
index 78b7d4a..4aa3f39 100644
--- a/src/main/java/com/treasure_data/bulk_import/writer/JSONFileWriter.java
+++ b/src/main/java/com/treasure_data/bulk_import/writer/JSONFileWriter.java
@@ -1,147 +1,146 @@
//
// Treasure Data Bulk-Import Tool in Java
//
// Copyright (C) 2012 - 2013 Muga Nishizawa
//
// 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.treasure_data.bulk_import.writer;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.simple.JSONValue;
import com.treasure_data.bulk_import.model.DoubleColumnValue;
import com.treasure_data.bulk_import.model.IntColumnValue;
import com.treasure_data.bulk_import.model.LongColumnValue;
import com.treasure_data.bulk_import.model.StringColumnValue;
import com.treasure_data.bulk_import.model.TimeColumnValue;
import com.treasure_data.bulk_import.prepare_parts.PrepareConfiguration;
import com.treasure_data.bulk_import.prepare_parts.PreparePartsException;
import com.treasure_data.bulk_import.prepare_parts.PrepareProcessor;
public class JSONFileWriter extends FileWriter {
private Map<String, Object> record;
private List<Object> recordElements;
public JSONFileWriter(PrepareConfiguration conf) {
super(conf);
}
@Override
public void configure(PrepareProcessor.Task task) throws PreparePartsException {
}
@Override
public void writeBeginRow(int size) throws PreparePartsException {
if (record != null || recordElements != null) {
throw new IllegalStateException("record must be null");
}
record = new HashMap<String, Object>();
recordElements = new ArrayList<Object>();
}
@Override
public void write(String v) throws PreparePartsException {
recordElements.add(v);
}
@Override
public void write(int v) throws PreparePartsException {
recordElements.add(v);
}
@Override
public void write(long v) throws PreparePartsException {
recordElements.add(v);
}
@Override
public void write(double v) throws PreparePartsException {
recordElements.add(v);
}
@Override
public void write(TimeColumnValue filter, StringColumnValue v) throws PreparePartsException {
String timeString = v.getString();
long time = 0;
try {
time = Long.parseLong(timeString);
} catch (Throwable t) {
- throw new PreparePartsException(String.format(
- "'%s' could not be parsed as long type", timeString));
+ // ignore
}
if (time == 0 && filter.getTimeFormat() != null) {
time = filter.getTimeFormat().getTime(timeString);
}
write(time);
}
@Override
public void write(TimeColumnValue filter, IntColumnValue v) throws PreparePartsException {
v.write(this);
}
@Override
public void write(TimeColumnValue filter, LongColumnValue v) throws PreparePartsException {
v.write(this);
}
@Override
public void write(TimeColumnValue filter, DoubleColumnValue v) throws PreparePartsException {
throw new PreparePartsException("not implemented method");
}
@Override
public void writeNil() throws PreparePartsException {
recordElements.add(null);
}
@Override
public void writeEndRow() throws PreparePartsException {
int size = recordElements.size() / 2;
for (int i = 0; i < size; i++) {
String key = (String) recordElements.get(2 * i);
Object val = recordElements.get(2 * i + 1);
record.put(key, val);
}
}
public String toJSONString() {
return JSONValue.toJSONString(getRecord());
}
private Map<String, Object> getRecord() {
return record;
}
@Override
public void close() throws IOException {
if (record != null) {
record.clear();
record = null;
}
if (recordElements != null) {
recordElements.clear();
recordElements = null;
}
}
}
| true | true | public void write(TimeColumnValue filter, StringColumnValue v) throws PreparePartsException {
String timeString = v.getString();
long time = 0;
try {
time = Long.parseLong(timeString);
} catch (Throwable t) {
throw new PreparePartsException(String.format(
"'%s' could not be parsed as long type", timeString));
}
if (time == 0 && filter.getTimeFormat() != null) {
time = filter.getTimeFormat().getTime(timeString);
}
write(time);
}
| public void write(TimeColumnValue filter, StringColumnValue v) throws PreparePartsException {
String timeString = v.getString();
long time = 0;
try {
time = Long.parseLong(timeString);
} catch (Throwable t) {
// ignore
}
if (time == 0 && filter.getTimeFormat() != null) {
time = filter.getTimeFormat().getTime(timeString);
}
write(time);
}
|
diff --git a/src/main/java/be/redlab/jaxb/swagger/SwaggerAnnotationsJaxbPlugin.java b/src/main/java/be/redlab/jaxb/swagger/SwaggerAnnotationsJaxbPlugin.java
index 4da559e..cdebb37 100644
--- a/src/main/java/be/redlab/jaxb/swagger/SwaggerAnnotationsJaxbPlugin.java
+++ b/src/main/java/be/redlab/jaxb/swagger/SwaggerAnnotationsJaxbPlugin.java
@@ -1,136 +1,136 @@
/*
* Copyright 2013 Balder Van Camp
*
* 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 be.redlab.jaxb.swagger;
import java.io.StringWriter;
import java.util.Collection;
import java.util.Map;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import com.sun.codemodel.JAnnotationUse;
import com.sun.codemodel.JAnnotationValue;
import com.sun.codemodel.JFormatter;
import com.sun.codemodel.JMethod;
import com.sun.tools.xjc.Options;
import com.sun.tools.xjc.Plugin;
import com.sun.tools.xjc.outline.ClassOutline;
import com.sun.tools.xjc.outline.Outline;
import com.wordnik.swagger.annotations.ApiClass;
import com.wordnik.swagger.annotations.ApiProperty;
/**
* @author redlab
*
*/
public class SwaggerAnnotationsJaxbPlugin extends Plugin {
private static final String SWAGGERIFY = "swaggerify";
private static final String USAGE = "Add this plugin to the JAXB classes generator classpath and provide the argument '-swaggerify'.";
/*
* (non-Javadoc)
*
* @see com.sun.tools.xjc.Plugin#getOptionName()
*/
@Override
public String getOptionName() {
return SWAGGERIFY;
}
/*
* (non-Javadoc)
*
* @see com.sun.tools.xjc.Plugin#getUsage()
*/
@Override
public String getUsage() {
return USAGE;
}
/*
* (non-Javadoc)
*
* @see com.sun.tools.xjc.Plugin#run(com.sun.tools.xjc.outline.Outline, com.sun.tools.xjc.Options,
* org.xml.sax.ErrorHandler)
*
* Api Annotations Info
* String value() default "";
* String allowableValues() default "";endIndex
* String access() default "";
* String notes() default "";
* String dataType() default "";
* boolean required() default false;
*/
@Override
public boolean run(final Outline outline, final Options opt, final ErrorHandler errorHandler) throws SAXException {
Collection<? extends ClassOutline> classes = outline.getClasses();
for (ClassOutline o : classes) {
if (o.implClass.isClass() && !o.implClass.isAbstract() && !o.implClass.isInterface()
&& !o.implClass.isAnnotationTypeDeclaration()) {
JAnnotationUse annotate2 = o.implClass.annotate(ApiClass.class);
annotate2.param("value", o.ref.name());
annotate2.param("description", new StringBuilder(o.ref.fullName())
.append(" description generated by jaxb-swagger, hence no class description yet.").toString());
for (JMethod m : o.implClass.methods()) {
if (m.name().startsWith("get") && m.name().length() > 3) {
JAnnotationUse annotate = m.annotate(ApiProperty.class);
- String name = m.name();
- annotate.param("value", prepareNameFromGetter(name));
+ String name = prepareNameFromGetter(m.name());
+ annotate.param("value", name);
String dataType = DataTypeDeterminationUtil.determineDataType(m.type());
if (dataType != null) {
annotate.param("dataType", dataType);
}
Collection<JAnnotationUse> fieldAnnotations = o.implClass.fields()
.get(name.substring(0, 1).toLowerCase() + name.substring(1)).annotations();
for (JAnnotationUse jau : fieldAnnotations) {
if (jau.getAnnotationClass().name().equals("XmlElement")) {
Map<String, JAnnotationValue> members = jau.getAnnotationMembers();
JAnnotationValue value = members.get("defaultValue");
if (null != value) {
StringWriter w2 = new StringWriter();
JFormatter f = new JFormatter(w2);
value.generate(f);
annotate.param("notes", w2.toString());
}
value = members.get("required");
if (null != value) {
annotate.param("required", true);
} else {
annotate.param("required", false);
}
}
}
}
}
} else {
errorHandler.warning(new SAXParseException(String.format("Skipping %s as it is not an implementation or class",
o), null));
}
}
return true;
}
protected String prepareNameFromGetter(final String getterName) {
String name = getterName.substring(3);
StringBuilder b = new StringBuilder();
b.append(Character.toLowerCase(name.charAt(0)));
if (name.length() > 1) {
b.append(name.substring(1));
}
return b.toString();
}
}
| true | true | public boolean run(final Outline outline, final Options opt, final ErrorHandler errorHandler) throws SAXException {
Collection<? extends ClassOutline> classes = outline.getClasses();
for (ClassOutline o : classes) {
if (o.implClass.isClass() && !o.implClass.isAbstract() && !o.implClass.isInterface()
&& !o.implClass.isAnnotationTypeDeclaration()) {
JAnnotationUse annotate2 = o.implClass.annotate(ApiClass.class);
annotate2.param("value", o.ref.name());
annotate2.param("description", new StringBuilder(o.ref.fullName())
.append(" description generated by jaxb-swagger, hence no class description yet.").toString());
for (JMethod m : o.implClass.methods()) {
if (m.name().startsWith("get") && m.name().length() > 3) {
JAnnotationUse annotate = m.annotate(ApiProperty.class);
String name = m.name();
annotate.param("value", prepareNameFromGetter(name));
String dataType = DataTypeDeterminationUtil.determineDataType(m.type());
if (dataType != null) {
annotate.param("dataType", dataType);
}
Collection<JAnnotationUse> fieldAnnotations = o.implClass.fields()
.get(name.substring(0, 1).toLowerCase() + name.substring(1)).annotations();
for (JAnnotationUse jau : fieldAnnotations) {
if (jau.getAnnotationClass().name().equals("XmlElement")) {
Map<String, JAnnotationValue> members = jau.getAnnotationMembers();
JAnnotationValue value = members.get("defaultValue");
if (null != value) {
StringWriter w2 = new StringWriter();
JFormatter f = new JFormatter(w2);
value.generate(f);
annotate.param("notes", w2.toString());
}
value = members.get("required");
if (null != value) {
annotate.param("required", true);
} else {
annotate.param("required", false);
}
}
}
}
}
} else {
errorHandler.warning(new SAXParseException(String.format("Skipping %s as it is not an implementation or class",
o), null));
}
}
return true;
}
| public boolean run(final Outline outline, final Options opt, final ErrorHandler errorHandler) throws SAXException {
Collection<? extends ClassOutline> classes = outline.getClasses();
for (ClassOutline o : classes) {
if (o.implClass.isClass() && !o.implClass.isAbstract() && !o.implClass.isInterface()
&& !o.implClass.isAnnotationTypeDeclaration()) {
JAnnotationUse annotate2 = o.implClass.annotate(ApiClass.class);
annotate2.param("value", o.ref.name());
annotate2.param("description", new StringBuilder(o.ref.fullName())
.append(" description generated by jaxb-swagger, hence no class description yet.").toString());
for (JMethod m : o.implClass.methods()) {
if (m.name().startsWith("get") && m.name().length() > 3) {
JAnnotationUse annotate = m.annotate(ApiProperty.class);
String name = prepareNameFromGetter(m.name());
annotate.param("value", name);
String dataType = DataTypeDeterminationUtil.determineDataType(m.type());
if (dataType != null) {
annotate.param("dataType", dataType);
}
Collection<JAnnotationUse> fieldAnnotations = o.implClass.fields()
.get(name.substring(0, 1).toLowerCase() + name.substring(1)).annotations();
for (JAnnotationUse jau : fieldAnnotations) {
if (jau.getAnnotationClass().name().equals("XmlElement")) {
Map<String, JAnnotationValue> members = jau.getAnnotationMembers();
JAnnotationValue value = members.get("defaultValue");
if (null != value) {
StringWriter w2 = new StringWriter();
JFormatter f = new JFormatter(w2);
value.generate(f);
annotate.param("notes", w2.toString());
}
value = members.get("required");
if (null != value) {
annotate.param("required", true);
} else {
annotate.param("required", false);
}
}
}
}
}
} else {
errorHandler.warning(new SAXParseException(String.format("Skipping %s as it is not an implementation or class",
o), null));
}
}
return true;
}
|
diff --git a/src/test/org/jdesktop/swingx/InteractiveTestCase.java b/src/test/org/jdesktop/swingx/InteractiveTestCase.java
index 0dbf6ba0..22101a62 100644
--- a/src/test/org/jdesktop/swingx/InteractiveTestCase.java
+++ b/src/test/org/jdesktop/swingx/InteractiveTestCase.java
@@ -1,255 +1,255 @@
/*
*
* Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle,
* Santa Clara, California 95054, U.S.A. All rights reserved.
*/
package org.jdesktop.swingx;
import java.awt.BorderLayout;
import java.awt.Point;
import java.lang.reflect.Method;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.AbstractButton;
import javax.swing.Action;
import javax.swing.Box;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JToolBar;
import javax.swing.UIManager;
/**
* Base class for supporting inclusion of interactive tests into a JUnit test case.
* Note that the interactive tests are NOT executed by the JUnit framework and
* are not automated. They are typically used for visual inspection of features
* during development. It is convenient to include the interactive tests along with
* the automated JUnit tests since they may share resources and it keeps tests
* focused in a single place.
* <p>
* All interactive test methods should be prefixed with "interactive",
* e.g. interactiveTestTableSorting().</p>
* <p>
* The test class's <code>main</code> method should be used to control which
* interactive tests should run. Use <code>runInteractiveTests()</code> method
* to run all interactive tests in the class.</p>
* <p>
* Ultimately we need to investigate moving to a mechanism which can help automate
* interactive tests. JFCUnit is being investigated. In the meantime, this
* is quick and dirty and cheap.
* </p>
* @author Amy Fowler
* @version 1.0
*/
public abstract class InteractiveTestCase extends junit.framework.TestCase {
private static final Logger LOG = Logger
.getLogger(InteractiveTestCase.class.getName());
protected Point frameLocation = new Point(0,0);
public InteractiveTestCase() {
super();
String className = getClass().getName();
int lastDot = className.lastIndexOf(".");
String lastElement = className.substring(lastDot + 1);
setName(lastElement);
}
public InteractiveTestCase(String testTitle) {
super(testTitle);
}
/**
* Creates and returns a JXFrame with the specified title, containing
* the component wrapped into a JScrollPane.
*
* @param component the JComponent to wrap
* @param title the title to show in the frame
* @return a configured, packed and located JXFrame.
*/
public JXFrame wrapWithScrollingInFrame(JComponent component, String title) {
JScrollPane scroller = new JScrollPane(component);
return wrapInFrame(scroller, title);
}
/**
* Creates and returns a JXFrame with the specified title, containing
* two components individually wrapped into a JScrollPane.
*
* @param leftComp the left JComponent to wrap
* @param rightComp the right JComponent to wrap
* @param title the title to show in the frame
* @return a configured, packed and located JXFrame
*/
public JXFrame wrapWithScrollingInFrame(JComponent leftComp, JComponent rightComp, String title) {
JComponent comp = Box.createHorizontalBox();
comp.add(new JScrollPane(leftComp));
comp.add(new JScrollPane(rightComp));
JXFrame frame = wrapInFrame(comp, title);
return frame;
}
/**
* Creates and returns a JXFrame with the specified title, containing
* the component.
*
* @param component the JComponent to wrap
* @param title the title to show in the frame
* @return a configured, packed and located JXFrame.
*/
public JXFrame wrapInFrame(JComponent component, String title) {
JXFrame frame = new JXFrame(title, false);
JToolBar toolbar = new JToolBar();
frame.getRootPaneExt().setToolBar(toolbar);
frame.getContentPane().add(BorderLayout.CENTER, component);
// frame.getContentPane().add(BorderLayout.NORTH, toolbar);
frame.pack();
frame.setLocation(frameLocation);
if (frameLocation.x == 0) {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle(title+" [close me and all tests will close]");
}
frameLocation.x += 30;
frameLocation.y += 30;
return frame;
}
/**
* Creates, shows and returns a JXFrame with the specified title, containing
* the component wrapped into a JScrollPane.
*
* @param component the JComponent to wrap
* @param title the title to show in the frame
* @return a configured, packed and located JXFrame.
* @see #wrapWithScrollingInFrame(JComponent, String)
*/
public JXFrame showWithScrollingInFrame(JComponent component, String title) {
JXFrame frame = wrapWithScrollingInFrame(component, title);
frame.setVisible(true);
return frame;
}
/**
* Creates and returns a JXFrame with the specified title, containing
* two components individually wrapped into a JScrollPane.
*
* @param leftComp the left JComponent to wrap
* @param rightComp the right JComponent to wrap
* @param title the title to show in the frame
* @return a configured, packed and located JXFrame
*/
public JXFrame showWithScrollingInFrame(JComponent leftComp, JComponent rightComp, String title) {
JXFrame frame = wrapWithScrollingInFrame(leftComp, rightComp, title);
frame.setVisible(true);
return frame;
}
/**
* Creates, shows and returns a JXFrame with the specified title, containing
* the component.
*
* @param component the JComponent to wrap
* @param title the title to show in the frame
* @return a configured, packed and located JXFrame.
*/
public JXFrame showInFrame(JComponent component, String title) {
JXFrame frame = wrapInFrame(component, title);
frame.setVisible(true);
return frame;
}
/**
* Runs all tests whose method names match the specified regex pattern.
* @param regexPattern regular expression pattern used to match test method names
* @throws java.lang.Exception
*/
public void runInteractiveTests(String regexPattern) throws java.lang.Exception {
setUp();
Class testClass = getClass();
Method methods[] = testClass.getMethods();
for (int i = 0; i < methods.length; i++) {
if (methods[i].getName().matches(regexPattern)) {
try {
- methods[i].invoke(this, null);
+ methods[i].invoke(this);
}
catch (Exception e) {
System.out.println("could not run interactive test: " +
methods[i].getName());
e.printStackTrace();
}
}
}
if (methods.length == 0) {
System.out.println("no test methods found matching the pattern: "+
regexPattern);
}
tearDown();
}
/**
* Runs all test methods which are prefixed with "interactive".
* @throws java.lang.Exception
*/
public void runInteractiveTests() throws java.lang.Exception {
runInteractiveTests("interactive.*");
}
public void addAction(JXFrame frame, Action action) {
JToolBar toolbar = frame.getRootPaneExt().getToolBar();
if (toolbar != null) {
AbstractButton button = toolbar.add(action);
button.setFocusable(false);
}
}
public void addMessage(JXFrame frame, String message) {
JXStatusBar statusBar = getStatusBar(frame);
statusBar.add(new JLabel(message), JXStatusBar.Constraint.ResizeBehavior.FILL);
}
/**
* Returns the <code>JXFrame</code>'s status bar. Lazily creates and
* sets an instance if necessary.
* @param frame the target frame
* @return the frame's statusbar
*/
public JXStatusBar getStatusBar(JXFrame frame) {
JXStatusBar statusBar = frame.getRootPaneExt().getStatusBar();
if (statusBar == null) {
statusBar = new JXStatusBar();
frame.getRootPaneExt().setStatusBar(statusBar);
}
return statusBar;
}
/**
* @param frame
* @param string
*/
public void addStatusMessage(JXFrame frame, String message) {
JXStatusBar bar = getStatusBar(frame);
bar.add(new JLabel(message));
}
/**
* PENDING: JW - this is about toggling the LF, does nothing to
* update the UI. Check all tests using this method to see if they
* make sense!
*
*
* @param system
*/
public static void setSystemLF(boolean system) {
String lfName = system ? UIManager.getSystemLookAndFeelClassName() :
UIManager.getCrossPlatformLookAndFeelClassName();
try {
UIManager.setLookAndFeel(lfName);
} catch (Exception e1) {
LOG.info("exception when setting LF to " + lfName);
LOG.log(Level.FINE, "caused by ", e1);
}
}
}
| true | true | public void runInteractiveTests(String regexPattern) throws java.lang.Exception {
setUp();
Class testClass = getClass();
Method methods[] = testClass.getMethods();
for (int i = 0; i < methods.length; i++) {
if (methods[i].getName().matches(regexPattern)) {
try {
methods[i].invoke(this, null);
}
catch (Exception e) {
System.out.println("could not run interactive test: " +
methods[i].getName());
e.printStackTrace();
}
}
}
if (methods.length == 0) {
System.out.println("no test methods found matching the pattern: "+
regexPattern);
}
tearDown();
}
| public void runInteractiveTests(String regexPattern) throws java.lang.Exception {
setUp();
Class testClass = getClass();
Method methods[] = testClass.getMethods();
for (int i = 0; i < methods.length; i++) {
if (methods[i].getName().matches(regexPattern)) {
try {
methods[i].invoke(this);
}
catch (Exception e) {
System.out.println("could not run interactive test: " +
methods[i].getName());
e.printStackTrace();
}
}
}
if (methods.length == 0) {
System.out.println("no test methods found matching the pattern: "+
regexPattern);
}
tearDown();
}
|
diff --git a/CS110/src/assignments/chap4/PE419.java b/CS110/src/assignments/chap4/PE419.java
index 96f75a6..2ec8cd0 100644
--- a/CS110/src/assignments/chap4/PE419.java
+++ b/CS110/src/assignments/chap4/PE419.java
@@ -1,33 +1,33 @@
package assignments.chap4;
public class PE419 {
public static void main(String[] args) {
int i;
for (i=1; i<9; i++) {
for (int j = 8; j>=i; j--){
- System.out.print(" ");
+ System.out.print(" ");
}
int pwr = 0;
for (int k = 0; k < i; k++){
- System.out.print(" " + (int)Math.pow(2, pwr));
+ System.out.printf("%4s", (int)Math.pow(2, pwr));
pwr++;
}
int pwr1 = pwr - 1;
for (int l = 0; l < i; l++){
pwr1--;
if ((int)Math.pow(2, pwr1) != 0)
- System.out.print(" " + (int)Math.pow(2, pwr1));
+ System.out.printf("%4s", (int)Math.pow(2, pwr1));
}
System.out.println();
}
}
}
| false | true | public static void main(String[] args) {
int i;
for (i=1; i<9; i++) {
for (int j = 8; j>=i; j--){
System.out.print(" ");
}
int pwr = 0;
for (int k = 0; k < i; k++){
System.out.print(" " + (int)Math.pow(2, pwr));
pwr++;
}
int pwr1 = pwr - 1;
for (int l = 0; l < i; l++){
pwr1--;
if ((int)Math.pow(2, pwr1) != 0)
System.out.print(" " + (int)Math.pow(2, pwr1));
}
System.out.println();
}
}
| public static void main(String[] args) {
int i;
for (i=1; i<9; i++) {
for (int j = 8; j>=i; j--){
System.out.print(" ");
}
int pwr = 0;
for (int k = 0; k < i; k++){
System.out.printf("%4s", (int)Math.pow(2, pwr));
pwr++;
}
int pwr1 = pwr - 1;
for (int l = 0; l < i; l++){
pwr1--;
if ((int)Math.pow(2, pwr1) != 0)
System.out.printf("%4s", (int)Math.pow(2, pwr1));
}
System.out.println();
}
}
|
diff --git a/svnkit/src/main/java/org/tmatesoft/svn/core/internal/wc2/remote/SvnRemoteRemoteDelete.java b/svnkit/src/main/java/org/tmatesoft/svn/core/internal/wc2/remote/SvnRemoteRemoteDelete.java
index 321160cb9..f97fb00c7 100644
--- a/svnkit/src/main/java/org/tmatesoft/svn/core/internal/wc2/remote/SvnRemoteRemoteDelete.java
+++ b/svnkit/src/main/java/org/tmatesoft/svn/core/internal/wc2/remote/SvnRemoteRemoteDelete.java
@@ -1,150 +1,151 @@
package org.tmatesoft.svn.core.internal.wc2.remote;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.tmatesoft.svn.core.SVNCommitInfo;
import org.tmatesoft.svn.core.SVNErrorCode;
import org.tmatesoft.svn.core.SVNErrorMessage;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.SVNNodeKind;
import org.tmatesoft.svn.core.SVNURL;
import org.tmatesoft.svn.core.internal.util.SVNHashMap;
import org.tmatesoft.svn.core.internal.util.SVNPathUtil;
import org.tmatesoft.svn.core.internal.wc.ISVNCommitPathHandler;
import org.tmatesoft.svn.core.internal.wc.SVNCommitUtil;
import org.tmatesoft.svn.core.internal.wc.SVNErrorManager;
import org.tmatesoft.svn.core.internal.wc.SVNEventFactory;
import org.tmatesoft.svn.core.internal.wc.SVNPropertiesManager;
import org.tmatesoft.svn.core.internal.wc17.SVNWCUtils;
import org.tmatesoft.svn.core.internal.wc2.SvnRemoteOperationRunner;
import org.tmatesoft.svn.core.io.ISVNEditor;
import org.tmatesoft.svn.core.io.SVNRepository;
import org.tmatesoft.svn.core.wc.ISVNEventHandler;
import org.tmatesoft.svn.core.wc.SVNEventAction;
import org.tmatesoft.svn.core.wc2.SvnCommitItem;
import org.tmatesoft.svn.core.wc2.SvnRemoteDelete;
import org.tmatesoft.svn.core.wc2.SvnTarget;
import org.tmatesoft.svn.util.SVNLogType;
public class SvnRemoteRemoteDelete extends SvnRemoteOperationRunner<SVNCommitInfo, SvnRemoteDelete> {
@Override
protected SVNCommitInfo run() throws SVNException {
if (getOperation().getTargets().size() == 0) {
return SVNCommitInfo.NULL;
}
SVNHashMap reposInfo = new SVNHashMap();
SVNHashMap relPathInfo = new SVNHashMap();
for (SvnTarget target : getOperation().getTargets()) {
SVNURL url = target.getURL();
SVNRepository repository = null;
SVNURL reposRoot = null;
String reposRelPath = null;
ArrayList<String> relPaths;
SVNNodeKind kind;
for (Iterator rootUrls = reposInfo.keySet().iterator(); rootUrls.hasNext();) {
reposRoot = (SVNURL) rootUrls.next();
reposRelPath = SVNWCUtils.isChild(reposRoot, url);
if (reposRelPath != null) {
repository = (SVNRepository)reposInfo.get(reposRoot);
relPaths = (ArrayList<String>)relPathInfo.get(reposRoot);
relPaths.add(reposRelPath);
+ break; //appropriate SVNRepository/root was found, stop searching
}
}
if (repository == null) {
repository = getRepositoryAccess().createRepository(url, null, false);
reposRoot = repository.getRepositoryRoot(true);
repository.setLocation(reposRoot, false);
reposInfo.put(reposRoot, repository);
reposRelPath = SVNWCUtils.isChild(reposRoot, url);
relPaths = new ArrayList<String>();
relPathInfo.put(reposRoot, relPaths);
relPaths.add(reposRelPath);
}
if (reposRelPath == null) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.RA_ILLEGAL_URL, "URL ''{0}'' not within a repository", url);
SVNErrorManager.error(err, SVNLogType.WC);
}
kind = repository.checkPath(reposRelPath, -1);
if (kind == SVNNodeKind.NONE) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.FS_NOT_FOUND, "URL ''{0}'' does not exist", url);
SVNErrorManager.error(err, SVNLogType.WC);
}
}
SVNPropertiesManager.validateRevisionProperties(getOperation().getRevisionProperties());
SVNCommitInfo info = null;
for (Iterator rootUrls = reposInfo.keySet().iterator(); rootUrls.hasNext();) {
SVNURL reposRoot = (SVNURL) rootUrls.next();
SVNRepository repository = (SVNRepository) reposInfo.get(reposRoot);
List<String> paths = (List<String>) relPathInfo.get(reposRoot);
info = singleRepositoryDelete(repository, reposRoot, paths);
if (info != null) {
getOperation().receive(SvnTarget.fromURL(reposRoot), info);
}
}
return info != null ? info : SVNCommitInfo.NULL;
}
private SVNCommitInfo singleRepositoryDelete(SVNRepository repository, SVNURL rootURL, List<String> paths) throws SVNException {
if (paths.isEmpty()) {
paths.add(SVNPathUtil.tail(rootURL.getURIEncodedPath()));
rootURL = rootURL.removePathTail();
}
String commitMessage;
if (getOperation().getCommitHandler() != null) {
SvnCommitItem[] commitItems = new SvnCommitItem[paths.size()];
for (int i = 0; i < commitItems.length; i++) {
String path = (String) paths.get(i);
SvnCommitItem item = new SvnCommitItem();
item.setKind(SVNNodeKind.NONE);
item.setUrl(rootURL.appendPath(path, true));
item.setFlags(SvnCommitItem.DELETE);
commitItems[i] = item;
}
commitMessage = getOperation().getCommitHandler().getCommitMessage(getOperation().getCommitMessage(), commitItems);
if (commitMessage == null) {
return SVNCommitInfo.NULL;
}
commitMessage = SVNCommitUtil.validateCommitMessage(commitMessage);
}
else {
commitMessage = "";
}
ISVNEditor commitEditor = repository.getCommitEditor(commitMessage, null, false, getOperation().getRevisionProperties(), null);
ISVNCommitPathHandler deleter = new ISVNCommitPathHandler() {
public boolean handleCommitPath(String commitPath, ISVNEditor commitEditor) throws SVNException {
commitEditor.deleteEntry(commitPath, -1);
return false;
}
};
SVNCommitInfo info;
try {
SVNCommitUtil.driveCommitEditor(deleter, paths, commitEditor, -1);
info = commitEditor.closeEdit();
} catch (SVNException e) {
try {
commitEditor.abortEdit();
} catch (SVNException inner) {
}
throw e;
}
if (info != null && info.getNewRevision() >= 0) {
handleEvent(SVNEventFactory.createSVNEvent(null, SVNNodeKind.NONE, null, info.getNewRevision(), SVNEventAction.COMMIT_COMPLETED, null, null, null), ISVNEventHandler.UNKNOWN);
}
return info != null ? info : SVNCommitInfo.NULL;
}
}
| true | true | protected SVNCommitInfo run() throws SVNException {
if (getOperation().getTargets().size() == 0) {
return SVNCommitInfo.NULL;
}
SVNHashMap reposInfo = new SVNHashMap();
SVNHashMap relPathInfo = new SVNHashMap();
for (SvnTarget target : getOperation().getTargets()) {
SVNURL url = target.getURL();
SVNRepository repository = null;
SVNURL reposRoot = null;
String reposRelPath = null;
ArrayList<String> relPaths;
SVNNodeKind kind;
for (Iterator rootUrls = reposInfo.keySet().iterator(); rootUrls.hasNext();) {
reposRoot = (SVNURL) rootUrls.next();
reposRelPath = SVNWCUtils.isChild(reposRoot, url);
if (reposRelPath != null) {
repository = (SVNRepository)reposInfo.get(reposRoot);
relPaths = (ArrayList<String>)relPathInfo.get(reposRoot);
relPaths.add(reposRelPath);
}
}
if (repository == null) {
repository = getRepositoryAccess().createRepository(url, null, false);
reposRoot = repository.getRepositoryRoot(true);
repository.setLocation(reposRoot, false);
reposInfo.put(reposRoot, repository);
reposRelPath = SVNWCUtils.isChild(reposRoot, url);
relPaths = new ArrayList<String>();
relPathInfo.put(reposRoot, relPaths);
relPaths.add(reposRelPath);
}
if (reposRelPath == null) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.RA_ILLEGAL_URL, "URL ''{0}'' not within a repository", url);
SVNErrorManager.error(err, SVNLogType.WC);
}
kind = repository.checkPath(reposRelPath, -1);
if (kind == SVNNodeKind.NONE) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.FS_NOT_FOUND, "URL ''{0}'' does not exist", url);
SVNErrorManager.error(err, SVNLogType.WC);
}
}
SVNPropertiesManager.validateRevisionProperties(getOperation().getRevisionProperties());
SVNCommitInfo info = null;
for (Iterator rootUrls = reposInfo.keySet().iterator(); rootUrls.hasNext();) {
SVNURL reposRoot = (SVNURL) rootUrls.next();
SVNRepository repository = (SVNRepository) reposInfo.get(reposRoot);
List<String> paths = (List<String>) relPathInfo.get(reposRoot);
info = singleRepositoryDelete(repository, reposRoot, paths);
if (info != null) {
getOperation().receive(SvnTarget.fromURL(reposRoot), info);
}
}
return info != null ? info : SVNCommitInfo.NULL;
}
| protected SVNCommitInfo run() throws SVNException {
if (getOperation().getTargets().size() == 0) {
return SVNCommitInfo.NULL;
}
SVNHashMap reposInfo = new SVNHashMap();
SVNHashMap relPathInfo = new SVNHashMap();
for (SvnTarget target : getOperation().getTargets()) {
SVNURL url = target.getURL();
SVNRepository repository = null;
SVNURL reposRoot = null;
String reposRelPath = null;
ArrayList<String> relPaths;
SVNNodeKind kind;
for (Iterator rootUrls = reposInfo.keySet().iterator(); rootUrls.hasNext();) {
reposRoot = (SVNURL) rootUrls.next();
reposRelPath = SVNWCUtils.isChild(reposRoot, url);
if (reposRelPath != null) {
repository = (SVNRepository)reposInfo.get(reposRoot);
relPaths = (ArrayList<String>)relPathInfo.get(reposRoot);
relPaths.add(reposRelPath);
break; //appropriate SVNRepository/root was found, stop searching
}
}
if (repository == null) {
repository = getRepositoryAccess().createRepository(url, null, false);
reposRoot = repository.getRepositoryRoot(true);
repository.setLocation(reposRoot, false);
reposInfo.put(reposRoot, repository);
reposRelPath = SVNWCUtils.isChild(reposRoot, url);
relPaths = new ArrayList<String>();
relPathInfo.put(reposRoot, relPaths);
relPaths.add(reposRelPath);
}
if (reposRelPath == null) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.RA_ILLEGAL_URL, "URL ''{0}'' not within a repository", url);
SVNErrorManager.error(err, SVNLogType.WC);
}
kind = repository.checkPath(reposRelPath, -1);
if (kind == SVNNodeKind.NONE) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.FS_NOT_FOUND, "URL ''{0}'' does not exist", url);
SVNErrorManager.error(err, SVNLogType.WC);
}
}
SVNPropertiesManager.validateRevisionProperties(getOperation().getRevisionProperties());
SVNCommitInfo info = null;
for (Iterator rootUrls = reposInfo.keySet().iterator(); rootUrls.hasNext();) {
SVNURL reposRoot = (SVNURL) rootUrls.next();
SVNRepository repository = (SVNRepository) reposInfo.get(reposRoot);
List<String> paths = (List<String>) relPathInfo.get(reposRoot);
info = singleRepositoryDelete(repository, reposRoot, paths);
if (info != null) {
getOperation().receive(SvnTarget.fromURL(reposRoot), info);
}
}
return info != null ? info : SVNCommitInfo.NULL;
}
|
diff --git a/org.eclipse.m2e.core/src/org/eclipse/m2e/core/internal/archetype/ArchetypeManager.java b/org.eclipse.m2e.core/src/org/eclipse/m2e/core/internal/archetype/ArchetypeManager.java
index c600ee29..cdd6b7bf 100644
--- a/org.eclipse.m2e.core/src/org/eclipse/m2e/core/internal/archetype/ArchetypeManager.java
+++ b/org.eclipse.m2e.core/src/org/eclipse/m2e/core/internal/archetype/ArchetypeManager.java
@@ -1,220 +1,219 @@
/*******************************************************************************
* Copyright (c) 2008-2010 Sonatype, Inc.
* 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
*
* Contributors:
* Sonatype, Inc. - initial API and implementation
*******************************************************************************/
package org.eclipse.m2e.core.internal.archetype;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.codehaus.plexus.util.IOUtil;
import org.apache.maven.archetype.catalog.Archetype;
import org.apache.maven.archetype.common.ArchetypeArtifactManager;
import org.apache.maven.archetype.exception.UnknownArchetype;
import org.apache.maven.archetype.metadata.ArchetypeDescriptor;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.execution.MavenSession;
import org.eclipse.m2e.core.MavenPlugin;
import org.eclipse.m2e.core.embedder.IMaven;
import org.eclipse.m2e.core.internal.MavenPluginActivator;
import org.eclipse.m2e.core.internal.archetype.ArchetypeCatalogFactory.RemoteCatalogFactory;
/**
* Archetype Manager
*
* @author Eugene Kuleshov
*/
public class ArchetypeManager {
private final Map<String, ArchetypeCatalogFactory> catalogs = new LinkedHashMap<String, ArchetypeCatalogFactory>();
private final File configFile;
private final ArchetypeCatalogsWriter writer;
public ArchetypeManager(File configFile) {
this.configFile = configFile;
this.writer = new ArchetypeCatalogsWriter();
}
/**
* @return Collection of ArchetypeCatalogFactory
*/
public Collection<ArchetypeCatalogFactory> getArchetypeCatalogs() {
return new ArrayList<ArchetypeCatalogFactory>(catalogs.values());
}
public void addArchetypeCatalogFactory(ArchetypeCatalogFactory factory) {
if(factory != null) {
catalogs.put(factory.getId(), factory);
}
}
public void removeArchetypeCatalogFactory(String catalogId) {
catalogs.remove(catalogId);
}
public ArchetypeCatalogFactory getArchetypeCatalogFactory(String catalogId) {
return catalogs.get(catalogId);
}
public void readCatalogs() throws IOException {
if(configFile.exists()) {
InputStream is = null;
try {
is = new FileInputStream(configFile);
Collection<ArchetypeCatalogFactory> catalogs = writer.readArchetypeCatalogs(is);
for(Iterator<ArchetypeCatalogFactory> it = catalogs.iterator(); it.hasNext();) {
addArchetypeCatalogFactory(it.next());
}
} finally {
IOUtil.close(is);
}
}
}
public void saveCatalogs() throws IOException {
OutputStream os = null;
try {
os = new FileOutputStream(configFile);
writer.writeArchetypeCatalogs(getArchetypeCatalogs(), os);
} finally {
IOUtil.close(os);
}
}
/**
* @return the archetypeCatalogFactory containing the archetype parameter, null if none was found.
*/
public <T extends ArchetypeCatalogFactory> T findParentCatalogFactory(Archetype a, Class<T> type) throws CoreException {
if (a!=null){
for (ArchetypeCatalogFactory factory : getArchetypeCatalogs()) {
if ((type.isAssignableFrom(factory.getClass()))
//temporary hack to get around https://issues.sonatype.org/browse/MNGECLIPSE-1792
//cf. MavenProjectWizardArchetypePage.getAllArchetypes
&& !(factory.getDescription() != null && factory.getDescription().startsWith("Test")) //$NON-NLS-1$
&& factory.getArchetypeCatalog().getArchetypes().contains(a)) {
return (T)factory;
}
}
}
return null;
}
/**
* Gets the remote {@link ArtifactRepository} of the given {@link Archetype}, or null if none is found.
* The repository url is extracted from {@link Archetype#getRepository()}, or, if it has none, the remote catalog the archetype is found in.
* The {@link ArtifactRepository} id is set to <strong>archetypeId+"-repo"</strong>, to enable authentication on that repository.
*
* @see <a href="http://maven.apache.org/archetype/maven-archetype-plugin/faq.html">http://maven.apache.org/archetype/maven-archetype-plugin/faq.html</a>
* @param archetype
* @return the remote {@link ArtifactRepository} of the given {@link Archetype}, or null if none is found.
* @throws CoreException
*/
public ArtifactRepository getArchetypeRepository(Archetype archetype) throws CoreException {
String repoUrl = archetype.getRepository();
if (repoUrl == null) {
RemoteCatalogFactory catalogFactory = findParentCatalogFactory(archetype, RemoteCatalogFactory.class);
if (catalogFactory != null ) {
repoUrl = catalogFactory.getRepositoryUrl();
}
}
return repoUrl == null?null:MavenPlugin.getMaven().createArtifactRepository(archetype.getArtifactId()+"-repo", repoUrl); //$NON-NLS-1$
}
/**
* Gets the required properties of an {@link Archetype}.
*
* @param archetype the archetype possibly declaring required properties
* @param remoteArchetypeRepository the remote archetype repository, can be null.
* @param monitor the progress monitor, can be null.
* @return the required properties of the archetypes, null if none is found.
* @throws UnknownArchetype thrown if no archetype is can be resolved
* @throws CoreException
*/
public List<?> getRequiredProperties(Archetype archetype, ArtifactRepository remoteArchetypeRepository, IProgressMonitor monitor) throws UnknownArchetype, CoreException {
Assert.isNotNull(archetype, "Archetype can not be null");
if (monitor == null) {
monitor = new NullProgressMonitor();
}
final String groupId = archetype.getGroupId();
final String artifactId = archetype.getArtifactId();
final String version = archetype.getVersion();
//XXX I'm not fond of that dependencies to MavenPlugin / MavenPluginActivator
IMaven maven = MavenPlugin.getMaven();
ArtifactRepository localRepository = maven.getLocalRepository();
List<ArtifactRepository> repositories;
if (remoteArchetypeRepository == null) {
repositories = maven.getArtifactRepositories();
} else {
repositories = Collections.singletonList(remoteArchetypeRepository);
}
- repositories = maven.getArtifactRepositories();
MavenSession session = maven.createSession(maven.createExecutionRequest(monitor), null);
MavenSession oldSession = MavenPluginActivator.getDefault().setSession(session);
ArchetypeArtifactManager aaMgr = MavenPluginActivator.getDefault().getArchetypeArtifactManager();
List<?> properties = null;
try {
if(aaMgr.isFileSetArchetype(groupId,
artifactId,
version,
null,
localRepository,
repositories)) {
ArchetypeDescriptor descriptor = aaMgr.getFileSetArchetypeDescriptor(groupId,
artifactId,
version,
null,
localRepository,
repositories);
properties = descriptor.getRequiredProperties();
}
} finally {
MavenPluginActivator.getDefault().setSession(oldSession);
}
return properties;
}
}
| true | true | public List<?> getRequiredProperties(Archetype archetype, ArtifactRepository remoteArchetypeRepository, IProgressMonitor monitor) throws UnknownArchetype, CoreException {
Assert.isNotNull(archetype, "Archetype can not be null");
if (monitor == null) {
monitor = new NullProgressMonitor();
}
final String groupId = archetype.getGroupId();
final String artifactId = archetype.getArtifactId();
final String version = archetype.getVersion();
//XXX I'm not fond of that dependencies to MavenPlugin / MavenPluginActivator
IMaven maven = MavenPlugin.getMaven();
ArtifactRepository localRepository = maven.getLocalRepository();
List<ArtifactRepository> repositories;
if (remoteArchetypeRepository == null) {
repositories = maven.getArtifactRepositories();
} else {
repositories = Collections.singletonList(remoteArchetypeRepository);
}
repositories = maven.getArtifactRepositories();
MavenSession session = maven.createSession(maven.createExecutionRequest(monitor), null);
MavenSession oldSession = MavenPluginActivator.getDefault().setSession(session);
ArchetypeArtifactManager aaMgr = MavenPluginActivator.getDefault().getArchetypeArtifactManager();
List<?> properties = null;
try {
if(aaMgr.isFileSetArchetype(groupId,
artifactId,
version,
null,
localRepository,
repositories)) {
ArchetypeDescriptor descriptor = aaMgr.getFileSetArchetypeDescriptor(groupId,
artifactId,
version,
null,
localRepository,
repositories);
properties = descriptor.getRequiredProperties();
}
} finally {
MavenPluginActivator.getDefault().setSession(oldSession);
}
return properties;
}
| public List<?> getRequiredProperties(Archetype archetype, ArtifactRepository remoteArchetypeRepository, IProgressMonitor monitor) throws UnknownArchetype, CoreException {
Assert.isNotNull(archetype, "Archetype can not be null");
if (monitor == null) {
monitor = new NullProgressMonitor();
}
final String groupId = archetype.getGroupId();
final String artifactId = archetype.getArtifactId();
final String version = archetype.getVersion();
//XXX I'm not fond of that dependencies to MavenPlugin / MavenPluginActivator
IMaven maven = MavenPlugin.getMaven();
ArtifactRepository localRepository = maven.getLocalRepository();
List<ArtifactRepository> repositories;
if (remoteArchetypeRepository == null) {
repositories = maven.getArtifactRepositories();
} else {
repositories = Collections.singletonList(remoteArchetypeRepository);
}
MavenSession session = maven.createSession(maven.createExecutionRequest(monitor), null);
MavenSession oldSession = MavenPluginActivator.getDefault().setSession(session);
ArchetypeArtifactManager aaMgr = MavenPluginActivator.getDefault().getArchetypeArtifactManager();
List<?> properties = null;
try {
if(aaMgr.isFileSetArchetype(groupId,
artifactId,
version,
null,
localRepository,
repositories)) {
ArchetypeDescriptor descriptor = aaMgr.getFileSetArchetypeDescriptor(groupId,
artifactId,
version,
null,
localRepository,
repositories);
properties = descriptor.getRequiredProperties();
}
} finally {
MavenPluginActivator.getDefault().setSession(oldSession);
}
return properties;
}
|
diff --git a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasklist/ui/TaskReminderMenuContributor.java b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasklist/ui/TaskReminderMenuContributor.java
index 38b86f5af..8e76dfd39 100644
--- a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasklist/ui/TaskReminderMenuContributor.java
+++ b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasklist/ui/TaskReminderMenuContributor.java
@@ -1,200 +1,200 @@
/*******************************************************************************
* Copyright (c) 2004 - 2006 University Of British Columbia 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
*
* Contributors:
* University Of British Columbia - initial API and implementation
*******************************************************************************/
package org.eclipse.mylar.internal.tasklist.ui;
import java.util.Calendar;
import java.util.GregorianCalendar;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.window.Window;
import org.eclipse.mylar.internal.tasklist.planner.ui.DateSelectionDialog;
import org.eclipse.mylar.internal.tasklist.planner.ui.ReminderCellEditor;
import org.eclipse.mylar.internal.tasklist.ui.views.TaskListView;
import org.eclipse.mylar.provisional.tasklist.AbstractQueryHit;
import org.eclipse.mylar.provisional.tasklist.ITask;
import org.eclipse.mylar.provisional.tasklist.ITaskListElement;
import org.eclipse.mylar.provisional.tasklist.MylarTaskListPlugin;
/**
* @author Rob Elves
*/
public class TaskReminderMenuContributor implements IDynamicSubMenuContributor {
private static final String LABEL_REMINDER = "Schedule for";
private static final String LABEL_TODAY = "Today";
private static final String LABEL_NEXT_WEEK = "Next Week";
private static final String LABEL_FUTURE = "Later";
private static final String LABEL_CALENDAR = "Choose Date...";
private static final String LABEL_CLEAR = "Clear";
private ITask task = null;
@SuppressWarnings("deprecation")
public MenuManager getSubMenuManager(TaskListView view, ITaskListElement selection) {
final ITaskListElement selectedElement = selection;
final TaskListView taskListView = view;
final MenuManager subMenuManager = new MenuManager(LABEL_REMINDER);
if (selectedElement instanceof ITask) {
task = (ITask) selectedElement;
} else if (selectedElement instanceof AbstractQueryHit) {
if (((AbstractQueryHit) selectedElement).getCorrespondingTask() != null) {
task = ((AbstractQueryHit) selectedElement).getCorrespondingTask();
}
}
Action action = new Action() {
@Override
public void run() {
Calendar reminderCalendar = GregorianCalendar.getInstance();
MylarTaskListPlugin.getTaskListManager().setScheduledToday(reminderCalendar);
MylarTaskListPlugin.getTaskListManager().setReminder(task, reminderCalendar.getTime());
}
};
action.setText(LABEL_TODAY);
action.setEnabled(canSchedule());
subMenuManager.add(action);
if (MylarTaskListPlugin.getTaskListManager().isReminderToday(task)) {
action.setChecked(true);
}
subMenuManager.add(new Separator());
final int today = Calendar.getInstance().get(Calendar.DAY_OF_WEEK);
boolean reachedEndOfWeek = false;
for (int i = today+1; i <= 8 && !reachedEndOfWeek; i++) {
final int day = i;
action = new Action() {
@Override
public void run() {
Calendar reminderCalendar = GregorianCalendar.getInstance();
int dueIn = day-today;
MylarTaskListPlugin.getTaskListManager().setSecheduledIn(reminderCalendar, dueIn);
MylarTaskListPlugin.getTaskListManager().setReminder(task, reminderCalendar.getTime());
}
};
getDayLabel(i, action);
- if (task != null) {
+ if (task != null && task.getReminderDate() != null) {
int tasksCheduledOn = task.getReminderDate().getDay();
if (MylarTaskListPlugin.getTaskListManager().isReminderThisWeek(task)) {
if (tasksCheduledOn+1 == day) {
action.setChecked(true);
} else if (tasksCheduledOn ==0 && day == 8) {
action.setChecked(true);
}
}
}
action.setEnabled(canSchedule());
subMenuManager.add(action);
}
subMenuManager.add(new Separator());
action = new Action() {
@Override
public void run() {
MylarTaskListPlugin.getTaskListManager().setReminder(task,
MylarTaskListPlugin.getTaskListManager().getActivityNextWeek().getStart().getTime());
}
};
action.setText(LABEL_NEXT_WEEK);
action.setEnabled(canSchedule());
if (MylarTaskListPlugin.getTaskListManager().isReminderAfterThisWeek(task) &&
!MylarTaskListPlugin.getTaskListManager().isReminderLater(task)) {
action.setChecked(true);
}
subMenuManager.add(action);
action = new Action() {
@Override
public void run() {
MylarTaskListPlugin.getTaskListManager().setReminder(task,
MylarTaskListPlugin.getTaskListManager().getActivityFuture().getStart().getTime());
}
};
action.setText(LABEL_FUTURE);
action.setEnabled(canSchedule());
if (MylarTaskListPlugin.getTaskListManager().isReminderLater(task)) {
action.setChecked(true);
}
subMenuManager.add(action);
subMenuManager.add(new Separator());
action = new Action() {
@Override
public void run() {
Calendar theCalendar = GregorianCalendar.getInstance();
if(task.getReminderDate() != null) {
theCalendar.setTime(task.getReminderDate());
}
DateSelectionDialog reminderDialog = new DateSelectionDialog(taskListView.getSite().getShell(), theCalendar, ReminderCellEditor.REMINDER_DIALOG_TITLE);
int result = reminderDialog.open();
if (result == Window.OK) {
MylarTaskListPlugin.getTaskListManager().setReminder(task, reminderDialog.getDate());
}
}
};
action.setText(LABEL_CALENDAR);
action.setEnabled(canSchedule());
subMenuManager.add(action);
action = new Action() {
@Override
public void run() {
MylarTaskListPlugin.getTaskListManager().setReminder(task, null);
}
};
action.setText(LABEL_CLEAR);
action.setEnabled(task != null);
subMenuManager.add(action);
return subMenuManager;
}
private void getDayLabel(int i, Action action) {
switch (i) {
case Calendar.MONDAY:
action.setText("Monday");
break;
case Calendar.TUESDAY:
action.setText("Tuesday");
break;
case Calendar.WEDNESDAY:
action.setText("Wednesday");
break;
case Calendar.THURSDAY:
action.setText("Thursday");
break;
case Calendar.FRIDAY:
action.setText("Friday");
break;
case Calendar.SATURDAY:
action.setText("Saturday");
break;
case 8:
action.setText("Sunday");
break;
default:
break;
}
}
private boolean canSchedule() {
return task != null && !task.isCompleted();
}
}
| true | true | public MenuManager getSubMenuManager(TaskListView view, ITaskListElement selection) {
final ITaskListElement selectedElement = selection;
final TaskListView taskListView = view;
final MenuManager subMenuManager = new MenuManager(LABEL_REMINDER);
if (selectedElement instanceof ITask) {
task = (ITask) selectedElement;
} else if (selectedElement instanceof AbstractQueryHit) {
if (((AbstractQueryHit) selectedElement).getCorrespondingTask() != null) {
task = ((AbstractQueryHit) selectedElement).getCorrespondingTask();
}
}
Action action = new Action() {
@Override
public void run() {
Calendar reminderCalendar = GregorianCalendar.getInstance();
MylarTaskListPlugin.getTaskListManager().setScheduledToday(reminderCalendar);
MylarTaskListPlugin.getTaskListManager().setReminder(task, reminderCalendar.getTime());
}
};
action.setText(LABEL_TODAY);
action.setEnabled(canSchedule());
subMenuManager.add(action);
if (MylarTaskListPlugin.getTaskListManager().isReminderToday(task)) {
action.setChecked(true);
}
subMenuManager.add(new Separator());
final int today = Calendar.getInstance().get(Calendar.DAY_OF_WEEK);
boolean reachedEndOfWeek = false;
for (int i = today+1; i <= 8 && !reachedEndOfWeek; i++) {
final int day = i;
action = new Action() {
@Override
public void run() {
Calendar reminderCalendar = GregorianCalendar.getInstance();
int dueIn = day-today;
MylarTaskListPlugin.getTaskListManager().setSecheduledIn(reminderCalendar, dueIn);
MylarTaskListPlugin.getTaskListManager().setReminder(task, reminderCalendar.getTime());
}
};
getDayLabel(i, action);
if (task != null) {
int tasksCheduledOn = task.getReminderDate().getDay();
if (MylarTaskListPlugin.getTaskListManager().isReminderThisWeek(task)) {
if (tasksCheduledOn+1 == day) {
action.setChecked(true);
} else if (tasksCheduledOn ==0 && day == 8) {
action.setChecked(true);
}
}
}
action.setEnabled(canSchedule());
subMenuManager.add(action);
}
subMenuManager.add(new Separator());
action = new Action() {
@Override
public void run() {
MylarTaskListPlugin.getTaskListManager().setReminder(task,
MylarTaskListPlugin.getTaskListManager().getActivityNextWeek().getStart().getTime());
}
};
action.setText(LABEL_NEXT_WEEK);
action.setEnabled(canSchedule());
if (MylarTaskListPlugin.getTaskListManager().isReminderAfterThisWeek(task) &&
!MylarTaskListPlugin.getTaskListManager().isReminderLater(task)) {
action.setChecked(true);
}
subMenuManager.add(action);
action = new Action() {
@Override
public void run() {
MylarTaskListPlugin.getTaskListManager().setReminder(task,
MylarTaskListPlugin.getTaskListManager().getActivityFuture().getStart().getTime());
}
};
action.setText(LABEL_FUTURE);
action.setEnabled(canSchedule());
if (MylarTaskListPlugin.getTaskListManager().isReminderLater(task)) {
action.setChecked(true);
}
subMenuManager.add(action);
subMenuManager.add(new Separator());
action = new Action() {
@Override
public void run() {
Calendar theCalendar = GregorianCalendar.getInstance();
if(task.getReminderDate() != null) {
theCalendar.setTime(task.getReminderDate());
}
DateSelectionDialog reminderDialog = new DateSelectionDialog(taskListView.getSite().getShell(), theCalendar, ReminderCellEditor.REMINDER_DIALOG_TITLE);
int result = reminderDialog.open();
if (result == Window.OK) {
MylarTaskListPlugin.getTaskListManager().setReminder(task, reminderDialog.getDate());
}
}
};
action.setText(LABEL_CALENDAR);
action.setEnabled(canSchedule());
subMenuManager.add(action);
action = new Action() {
@Override
public void run() {
MylarTaskListPlugin.getTaskListManager().setReminder(task, null);
}
};
action.setText(LABEL_CLEAR);
action.setEnabled(task != null);
subMenuManager.add(action);
return subMenuManager;
}
| public MenuManager getSubMenuManager(TaskListView view, ITaskListElement selection) {
final ITaskListElement selectedElement = selection;
final TaskListView taskListView = view;
final MenuManager subMenuManager = new MenuManager(LABEL_REMINDER);
if (selectedElement instanceof ITask) {
task = (ITask) selectedElement;
} else if (selectedElement instanceof AbstractQueryHit) {
if (((AbstractQueryHit) selectedElement).getCorrespondingTask() != null) {
task = ((AbstractQueryHit) selectedElement).getCorrespondingTask();
}
}
Action action = new Action() {
@Override
public void run() {
Calendar reminderCalendar = GregorianCalendar.getInstance();
MylarTaskListPlugin.getTaskListManager().setScheduledToday(reminderCalendar);
MylarTaskListPlugin.getTaskListManager().setReminder(task, reminderCalendar.getTime());
}
};
action.setText(LABEL_TODAY);
action.setEnabled(canSchedule());
subMenuManager.add(action);
if (MylarTaskListPlugin.getTaskListManager().isReminderToday(task)) {
action.setChecked(true);
}
subMenuManager.add(new Separator());
final int today = Calendar.getInstance().get(Calendar.DAY_OF_WEEK);
boolean reachedEndOfWeek = false;
for (int i = today+1; i <= 8 && !reachedEndOfWeek; i++) {
final int day = i;
action = new Action() {
@Override
public void run() {
Calendar reminderCalendar = GregorianCalendar.getInstance();
int dueIn = day-today;
MylarTaskListPlugin.getTaskListManager().setSecheduledIn(reminderCalendar, dueIn);
MylarTaskListPlugin.getTaskListManager().setReminder(task, reminderCalendar.getTime());
}
};
getDayLabel(i, action);
if (task != null && task.getReminderDate() != null) {
int tasksCheduledOn = task.getReminderDate().getDay();
if (MylarTaskListPlugin.getTaskListManager().isReminderThisWeek(task)) {
if (tasksCheduledOn+1 == day) {
action.setChecked(true);
} else if (tasksCheduledOn ==0 && day == 8) {
action.setChecked(true);
}
}
}
action.setEnabled(canSchedule());
subMenuManager.add(action);
}
subMenuManager.add(new Separator());
action = new Action() {
@Override
public void run() {
MylarTaskListPlugin.getTaskListManager().setReminder(task,
MylarTaskListPlugin.getTaskListManager().getActivityNextWeek().getStart().getTime());
}
};
action.setText(LABEL_NEXT_WEEK);
action.setEnabled(canSchedule());
if (MylarTaskListPlugin.getTaskListManager().isReminderAfterThisWeek(task) &&
!MylarTaskListPlugin.getTaskListManager().isReminderLater(task)) {
action.setChecked(true);
}
subMenuManager.add(action);
action = new Action() {
@Override
public void run() {
MylarTaskListPlugin.getTaskListManager().setReminder(task,
MylarTaskListPlugin.getTaskListManager().getActivityFuture().getStart().getTime());
}
};
action.setText(LABEL_FUTURE);
action.setEnabled(canSchedule());
if (MylarTaskListPlugin.getTaskListManager().isReminderLater(task)) {
action.setChecked(true);
}
subMenuManager.add(action);
subMenuManager.add(new Separator());
action = new Action() {
@Override
public void run() {
Calendar theCalendar = GregorianCalendar.getInstance();
if(task.getReminderDate() != null) {
theCalendar.setTime(task.getReminderDate());
}
DateSelectionDialog reminderDialog = new DateSelectionDialog(taskListView.getSite().getShell(), theCalendar, ReminderCellEditor.REMINDER_DIALOG_TITLE);
int result = reminderDialog.open();
if (result == Window.OK) {
MylarTaskListPlugin.getTaskListManager().setReminder(task, reminderDialog.getDate());
}
}
};
action.setText(LABEL_CALENDAR);
action.setEnabled(canSchedule());
subMenuManager.add(action);
action = new Action() {
@Override
public void run() {
MylarTaskListPlugin.getTaskListManager().setReminder(task, null);
}
};
action.setText(LABEL_CLEAR);
action.setEnabled(task != null);
subMenuManager.add(action);
return subMenuManager;
}
|
diff --git a/tr2-client/src/tr2/client/series/CalculatorManager.java b/tr2-client/src/tr2/client/series/CalculatorManager.java
index 49a98ad..4c7b3a6 100644
--- a/tr2-client/src/tr2/client/series/CalculatorManager.java
+++ b/tr2-client/src/tr2/client/series/CalculatorManager.java
@@ -1,67 +1,66 @@
package tr2.client.series;
import java.io.IOException;
import tr2.client.http.Proxy;
import tr2.client.http.RequestType;
import tr2.server.common.entity.Interval;
import tr2.server.common.series.protocol.Messages;
import tr2.server.common.series.protocol.SeriesRequest;
import tr2.server.common.util.JSONHelper;
public class CalculatorManager implements Runnable {
@Override
public void run() {
while (true) {
/*
* Here we're using just one thread to calculate, but it can be
* easily extended to use more
*/
Calculator c = new Calculator();
Interval i = c.calculate(getSeriesInterval());
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
sendResultsToServer(i);
}
}
private void sendResultsToServer(Interval interval) {
try {
if (interval == null)
return;
Proxy proxy = Proxy.instance();
SeriesRequest s = new SeriesRequest();
String request = s.prepare(Messages.INTERVAL_CALCULATED,
interval.toJSON());
System.out
- .println("[CALCULATOR MANAGER] Sending request to server: ");
- System.out.println("\t" + request);
+ .println("[CALCULATOR MANAGER] Sending request to server: " + request);
proxy.request(request, RequestType.SERIES);
} catch (IOException e) {
//e.printStackTrace();
}
}
private Interval getSeriesInterval() {
Proxy proxy = null;
String response = null;
try {
SeriesRequest s = new SeriesRequest();
String request = s.prepare(Messages.GET_INTERVAL, null);
proxy = Proxy.instance();
response = proxy.request(request, RequestType.SERIES);
/* Parses JSON String to Interval object. */
} catch (IOException e) {
//e.printStackTrace();
}
return JSONHelper.fromJSON(response, Interval.class);
}
}
| true | true | private void sendResultsToServer(Interval interval) {
try {
if (interval == null)
return;
Proxy proxy = Proxy.instance();
SeriesRequest s = new SeriesRequest();
String request = s.prepare(Messages.INTERVAL_CALCULATED,
interval.toJSON());
System.out
.println("[CALCULATOR MANAGER] Sending request to server: ");
System.out.println("\t" + request);
proxy.request(request, RequestType.SERIES);
} catch (IOException e) {
//e.printStackTrace();
}
}
| private void sendResultsToServer(Interval interval) {
try {
if (interval == null)
return;
Proxy proxy = Proxy.instance();
SeriesRequest s = new SeriesRequest();
String request = s.prepare(Messages.INTERVAL_CALCULATED,
interval.toJSON());
System.out
.println("[CALCULATOR MANAGER] Sending request to server: " + request);
proxy.request(request, RequestType.SERIES);
} catch (IOException e) {
//e.printStackTrace();
}
}
|
diff --git a/phresco-service-web/src/main/java/com/photon/phresco/service/rest/api/LoginService.java b/phresco-service-web/src/main/java/com/photon/phresco/service/rest/api/LoginService.java
index de0b3bdf..1abab243 100644
--- a/phresco-service-web/src/main/java/com/photon/phresco/service/rest/api/LoginService.java
+++ b/phresco-service-web/src/main/java/com/photon/phresco/service/rest/api/LoginService.java
@@ -1,113 +1,114 @@
/*
* ###
* Service Web Archive
*
* Copyright (C) 1999 - 2012 Photon Infotech 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.photon.phresco.service.rest.api;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import com.photon.phresco.commons.model.User;
import com.photon.phresco.exception.PhrescoException;
import com.photon.phresco.service.api.DbService;
import com.photon.phresco.service.api.PhrescoServerFactory;
import com.photon.phresco.service.api.RepositoryManager;
import com.photon.phresco.service.util.AuthenticationUtil;
import com.photon.phresco.service.util.ServerConstants;
import com.photon.phresco.util.Credentials;
import com.photon.phresco.util.ServiceConstants;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.GenericType;
import com.sun.jersey.api.client.WebResource;
@Path(ServiceConstants.REST_API_LOGIN)
public class LoginService extends DbService {
public LoginService() {
super();
}
// @POST
// @Produces(MediaType.APPLICATION_JSON)
// @Consumes(MediaType.APPLICATION_JSON)
// public User login(Credentials credentials) throws PhrescoException {
// System.out.println("In Login Service");
// User user = new User();
// user.setLoginId("demo_user");
// user.setEmail("[email protected]");
// user.setFirstName("Demo");
// user.setLastName("User");
// user.setDisplayName("Demo User");
//
// AuthenticationUtil authTokenUtil = AuthenticationUtil.getInstance();
// user.setToken(authTokenUtil.generateToken(credentials.getUsername()));
// user.setPhrescoEnabled(true);
// return user;
// }
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public User login(Credentials credentials) throws PhrescoException {
Client client = Client.create();
PhrescoServerFactory.initialize();
RepositoryManager repoMgr = PhrescoServerFactory.getRepositoryManager();
WebResource resource = client.resource(repoMgr.getAuthServiceURL() + ServerConstants.AUTHENTICATE);
resource.accept(MediaType.APPLICATION_JSON_TYPE);
ClientResponse response = resource.type(MediaType.APPLICATION_JSON_TYPE).post(ClientResponse.class, credentials);
GenericType<User> genericType = new GenericType<User>() {};
User user = response.getEntity(genericType);
AuthenticationUtil authTokenUtil = AuthenticationUtil.getInstance();
user.setToken(authTokenUtil.generateToken(credentials.getUsername()));
user.setPhrescoEnabled(true);
+ user.setValidLogin(true);
return user;
// UserDAO userDao = mongoOperation.findOne(ServiceConstants.USERDAO_COLLECTION_NAME,
// new Query(Criteria.whereId().is(user.getName())), UserDAO.class);
// user.setId(user.getName());
// Converter<UserDAO, User> converter = (Converter<UserDAO, User>) ConvertersFactory.getConverter(UserDAO.class);
// User convertedUser = new User();
// if(userDao != null) {
// convertedUser = converter.convertDAOToObject(userDao, mongoOperation);
// }
//// List<Customer> customers = mongoOperation.getCollection(ServiceConstants.CUSTOMERS_COLLECTION_NAME , Customer.class);
//// List<Customer> customers = new ArrayList<Customer>();
//// Converter<CustomerDAO, Customer> customerConverter =
//// (Converter<CustomerDAO, Customer>) ConvertersFactory.getConverter(CustomerDAO.class);
//// List<CustomerDAO> customerDAOs = mongoOperation.getCollection(ServiceConstants.CUSTOMERDAO_COLLECTION_NAME , CustomerDAO.class);
//// for (CustomerDAO customerDAO : customerDAOs) {
//// customers.add(customerConverter.convertDAOToObject(customerDAO, mongoOperation));
//// }
//
// AuthenticationUtil authTokenUtil = AuthenticationUtil.getInstance();
// convertedUser.setLoginId(credentials.getUsername());
// convertedUser.setToken(authTokenUtil.generateToken(credentials.getUsername()));
// convertedUser.setDisplayName(user.getDisplayName());
// convertedUser.setPhrescoEnabled(user.isPhrescoEnabled());
// convertedUser.setCustomers(customers);
// return convertedUser;
}
}
| true | true | public User login(Credentials credentials) throws PhrescoException {
Client client = Client.create();
PhrescoServerFactory.initialize();
RepositoryManager repoMgr = PhrescoServerFactory.getRepositoryManager();
WebResource resource = client.resource(repoMgr.getAuthServiceURL() + ServerConstants.AUTHENTICATE);
resource.accept(MediaType.APPLICATION_JSON_TYPE);
ClientResponse response = resource.type(MediaType.APPLICATION_JSON_TYPE).post(ClientResponse.class, credentials);
GenericType<User> genericType = new GenericType<User>() {};
User user = response.getEntity(genericType);
AuthenticationUtil authTokenUtil = AuthenticationUtil.getInstance();
user.setToken(authTokenUtil.generateToken(credentials.getUsername()));
user.setPhrescoEnabled(true);
return user;
// UserDAO userDao = mongoOperation.findOne(ServiceConstants.USERDAO_COLLECTION_NAME,
// new Query(Criteria.whereId().is(user.getName())), UserDAO.class);
// user.setId(user.getName());
// Converter<UserDAO, User> converter = (Converter<UserDAO, User>) ConvertersFactory.getConverter(UserDAO.class);
// User convertedUser = new User();
// if(userDao != null) {
// convertedUser = converter.convertDAOToObject(userDao, mongoOperation);
// }
//// List<Customer> customers = mongoOperation.getCollection(ServiceConstants.CUSTOMERS_COLLECTION_NAME , Customer.class);
//// List<Customer> customers = new ArrayList<Customer>();
//// Converter<CustomerDAO, Customer> customerConverter =
//// (Converter<CustomerDAO, Customer>) ConvertersFactory.getConverter(CustomerDAO.class);
//// List<CustomerDAO> customerDAOs = mongoOperation.getCollection(ServiceConstants.CUSTOMERDAO_COLLECTION_NAME , CustomerDAO.class);
//// for (CustomerDAO customerDAO : customerDAOs) {
//// customers.add(customerConverter.convertDAOToObject(customerDAO, mongoOperation));
//// }
//
// AuthenticationUtil authTokenUtil = AuthenticationUtil.getInstance();
// convertedUser.setLoginId(credentials.getUsername());
// convertedUser.setToken(authTokenUtil.generateToken(credentials.getUsername()));
// convertedUser.setDisplayName(user.getDisplayName());
// convertedUser.setPhrescoEnabled(user.isPhrescoEnabled());
// convertedUser.setCustomers(customers);
// return convertedUser;
}
| public User login(Credentials credentials) throws PhrescoException {
Client client = Client.create();
PhrescoServerFactory.initialize();
RepositoryManager repoMgr = PhrescoServerFactory.getRepositoryManager();
WebResource resource = client.resource(repoMgr.getAuthServiceURL() + ServerConstants.AUTHENTICATE);
resource.accept(MediaType.APPLICATION_JSON_TYPE);
ClientResponse response = resource.type(MediaType.APPLICATION_JSON_TYPE).post(ClientResponse.class, credentials);
GenericType<User> genericType = new GenericType<User>() {};
User user = response.getEntity(genericType);
AuthenticationUtil authTokenUtil = AuthenticationUtil.getInstance();
user.setToken(authTokenUtil.generateToken(credentials.getUsername()));
user.setPhrescoEnabled(true);
user.setValidLogin(true);
return user;
// UserDAO userDao = mongoOperation.findOne(ServiceConstants.USERDAO_COLLECTION_NAME,
// new Query(Criteria.whereId().is(user.getName())), UserDAO.class);
// user.setId(user.getName());
// Converter<UserDAO, User> converter = (Converter<UserDAO, User>) ConvertersFactory.getConverter(UserDAO.class);
// User convertedUser = new User();
// if(userDao != null) {
// convertedUser = converter.convertDAOToObject(userDao, mongoOperation);
// }
//// List<Customer> customers = mongoOperation.getCollection(ServiceConstants.CUSTOMERS_COLLECTION_NAME , Customer.class);
//// List<Customer> customers = new ArrayList<Customer>();
//// Converter<CustomerDAO, Customer> customerConverter =
//// (Converter<CustomerDAO, Customer>) ConvertersFactory.getConverter(CustomerDAO.class);
//// List<CustomerDAO> customerDAOs = mongoOperation.getCollection(ServiceConstants.CUSTOMERDAO_COLLECTION_NAME , CustomerDAO.class);
//// for (CustomerDAO customerDAO : customerDAOs) {
//// customers.add(customerConverter.convertDAOToObject(customerDAO, mongoOperation));
//// }
//
// AuthenticationUtil authTokenUtil = AuthenticationUtil.getInstance();
// convertedUser.setLoginId(credentials.getUsername());
// convertedUser.setToken(authTokenUtil.generateToken(credentials.getUsername()));
// convertedUser.setDisplayName(user.getDisplayName());
// convertedUser.setPhrescoEnabled(user.isPhrescoEnabled());
// convertedUser.setCustomers(customers);
// return convertedUser;
}
|
diff --git a/org.eclipse.mylyn.tasks.tests/src/org/eclipse/mylyn/tasklist/tests/TaskDataImportTest.java b/org.eclipse.mylyn.tasks.tests/src/org/eclipse/mylyn/tasklist/tests/TaskDataImportTest.java
index 463953020..c549beb17 100644
--- a/org.eclipse.mylyn.tasks.tests/src/org/eclipse/mylyn/tasklist/tests/TaskDataImportTest.java
+++ b/org.eclipse.mylyn.tasks.tests/src/org/eclipse/mylyn/tasklist/tests/TaskDataImportTest.java
@@ -1,123 +1,123 @@
/*******************************************************************************
* Copyright (c) 2004 - 2006 University Of British Columbia 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
*
* Contributors:
* University Of British Columbia - initial API and implementation
*******************************************************************************/
package org.eclipse.mylar.tasklist.tests;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.List;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.mylar.core.MylarPlugin;
import org.eclipse.mylar.core.tests.AbstractContextTest;
import org.eclipse.mylar.internal.tasklist.ITask;
import org.eclipse.mylar.internal.tasklist.MylarTaskListPlugin;
import org.eclipse.mylar.internal.tasklist.TaskList;
import org.eclipse.mylar.internal.tasklist.TaskListManager;
import org.eclipse.mylar.internal.tasklist.ui.wizards.TaskDataImportWizard;
import org.eclipse.mylar.internal.tasklist.ui.wizards.TaskDataImportWizardPage;
import org.eclipse.swt.widgets.Shell;
/**
* Test case for the Task Import Wizard
*
* @author Rob Elves
*/
public class TaskDataImportTest extends AbstractContextTest {
private TaskDataImportWizard wizard = null;
private TaskDataImportWizardPage wizardPage = null;
private String sourceDir = "taskdataimporttest";
private File sourceDirFile = null;
private String sourceZipPath = "taskdataimporttest/mylardata-2006-02-16.zip";
private File sourceZipFile = null;
private TaskListManager manager = MylarTaskListPlugin.getTaskListManager();
protected void setUp() throws Exception {
super.setUp();
// Create the import wizard
wizard = new TaskDataImportWizard();
wizard.addPages();
wizard.createPageControls(new Shell());
wizardPage = (TaskDataImportWizardPage) wizard.getPage(TaskDataImportWizardPage.PAGE_NAME);
assertNotNull(wizardPage);
manager.createNewTaskList();
- assertTrue(manager.getTaskList().getRoots().size() == 0);
+ assertTrue(manager.getTaskList().getRoots().size() == 1);
sourceDirFile = getLocalFile(sourceDir);
assertTrue(sourceDirFile.exists());
sourceZipFile = getLocalFile(sourceZipPath);
assertTrue(sourceZipFile.exists());
// make sure no tasks and categories exist prior to import tests
- assertEquals(manager.getTaskList().getTaskCategories().size(), 0);
+ assertEquals(manager.getTaskList().getTaskCategories().size(), 1);
}
protected void tearDown() throws Exception {
super.tearDown();
}
/**
* Tests the wizard when it has been asked to import all task data from a
* zip file
*/
public void testImportFromAllFromZip() {
wizardPage.setParameters(true, true, true, true, true, "", sourceZipFile.getPath());
wizard.performFinish();
TaskList taskList = MylarTaskListPlugin.getTaskListManager().getTaskList();
assertNotNull(taskList);
List<ITask> tasks = taskList.getRootTasks();
assertNotNull(tasks);
assertTrue(tasks.size() > 0);
for (ITask task : tasks) {
assertTrue(MylarPlugin.getContextManager().hasContext(task.getHandleIdentifier()));
}
}
/** Tests the wizard when it has been asked to import task data from folder */
public void testImportFromAllFromFolder() {
wizardPage.setParameters(true, true, true, true, false, sourceDirFile.getPath(), "");
wizard.performFinish();
TaskList taskList = MylarTaskListPlugin.getTaskListManager().getTaskList();
assertNotNull(taskList);
List<ITask> tasks = taskList.getRootTasks();
assertNotNull(tasks);
assertTrue(tasks.size() > 0);
for (ITask task : tasks) {
assertTrue(MylarPlugin.getContextManager().hasContext(task.getHandleIdentifier()));
}
}
private File getLocalFile(String path) {
try {
URL installURL = MylarTasksTestsPlugin.getDefault().getBundle().getEntry(path);
URL localURL = FileLocator.toFileURL(installURL);
return new File(localURL.getFile());
} catch (IOException e) {
return null;
}
}
}
| false | true | protected void setUp() throws Exception {
super.setUp();
// Create the import wizard
wizard = new TaskDataImportWizard();
wizard.addPages();
wizard.createPageControls(new Shell());
wizardPage = (TaskDataImportWizardPage) wizard.getPage(TaskDataImportWizardPage.PAGE_NAME);
assertNotNull(wizardPage);
manager.createNewTaskList();
assertTrue(manager.getTaskList().getRoots().size() == 0);
sourceDirFile = getLocalFile(sourceDir);
assertTrue(sourceDirFile.exists());
sourceZipFile = getLocalFile(sourceZipPath);
assertTrue(sourceZipFile.exists());
// make sure no tasks and categories exist prior to import tests
assertEquals(manager.getTaskList().getTaskCategories().size(), 0);
}
| protected void setUp() throws Exception {
super.setUp();
// Create the import wizard
wizard = new TaskDataImportWizard();
wizard.addPages();
wizard.createPageControls(new Shell());
wizardPage = (TaskDataImportWizardPage) wizard.getPage(TaskDataImportWizardPage.PAGE_NAME);
assertNotNull(wizardPage);
manager.createNewTaskList();
assertTrue(manager.getTaskList().getRoots().size() == 1);
sourceDirFile = getLocalFile(sourceDir);
assertTrue(sourceDirFile.exists());
sourceZipFile = getLocalFile(sourceZipPath);
assertTrue(sourceZipFile.exists());
// make sure no tasks and categories exist prior to import tests
assertEquals(manager.getTaskList().getTaskCategories().size(), 1);
}
|
diff --git a/geoserver/wcs/src/main/java/org/vfny/geoserver/wcs/responses/CoverageResponseDelegateFactory.java b/geoserver/wcs/src/main/java/org/vfny/geoserver/wcs/responses/CoverageResponseDelegateFactory.java
index 2b12604e10..5f69df942d 100644
--- a/geoserver/wcs/src/main/java/org/vfny/geoserver/wcs/responses/CoverageResponseDelegateFactory.java
+++ b/geoserver/wcs/src/main/java/org/vfny/geoserver/wcs/responses/CoverageResponseDelegateFactory.java
@@ -1,81 +1,80 @@
/* Copyright (c) 2001 - 2007 TOPP - www.openplans.org. All rights reserved.
* This code is licensed under the GPL 2.0 license, availible at the root
* application directory.
*/
package org.vfny.geoserver.wcs.responses;
import org.vfny.geoserver.wcs.responses.coverage.AscCoverageResponseDelegate;
import org.vfny.geoserver.wcs.responses.coverage.GTopo30CoverageResponseDelegate;
import org.vfny.geoserver.wcs.responses.coverage.GeoTIFFCoverageResponseDelegate;
import org.vfny.geoserver.wcs.responses.coverage.IMGCoverageResponseDelegate;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.NoSuchElementException;
/**
* DOCUMENT ME!
*
* @author $Author: Alessio Fabiani ([email protected]) $ (last
* modification)
* @author $Author: Simone Giannecchini ([email protected]) $ (last
* modification)
*/
public class CoverageResponseDelegateFactory {
/** DOCUMENT ME! */
private static final List encoders = new LinkedList();
static {
encoders.add(new AscCoverageResponseDelegate());
encoders.add(new IMGCoverageResponseDelegate());
encoders.add(new GTopo30CoverageResponseDelegate());
encoders.add(new GeoTIFFCoverageResponseDelegate());
}
private CoverageResponseDelegateFactory() {
}
/**
* Creates an encoder for a specific getfeature results output format
*
* @param outputFormat
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*
* @throws NoSuchElementException
* DOCUMENT ME!
*/
public static CoverageResponseDelegate encoderFor(String outputFormat)
throws NoSuchElementException {
CoverageResponseDelegate encoder = null;
for (Iterator it = encoders.iterator(); it.hasNext();) {
encoder = (CoverageResponseDelegate) it.next();
if (encoder.canProduce(outputFormat)) {
try {
if (encoder != null) {
return (CoverageResponseDelegate) encoder.getClass().newInstance();
}
} catch (IllegalAccessException ex) {
final NoSuchElementException e = new NoSuchElementException(new StringBuffer(
"Can't create the encoder ").append(encoder.getClass().getName())
.toString());
e.initCause(ex);
throw e;
} catch (InstantiationException ex) {
final NoSuchElementException e = new NoSuchElementException(new StringBuffer(
"Can't create the encoder ").append(encoder.getClass().getName())
.toString());
e.initCause(ex);
throw e;
}
}
}
- throw new NoSuchElementException(new StringBuffer("Can't create the encoder ").append(
- encoder.getClass().getName()).toString());
+ throw new NoSuchElementException("Can't create the encoder for format " + outputFormat);
}
}
| true | true | public static CoverageResponseDelegate encoderFor(String outputFormat)
throws NoSuchElementException {
CoverageResponseDelegate encoder = null;
for (Iterator it = encoders.iterator(); it.hasNext();) {
encoder = (CoverageResponseDelegate) it.next();
if (encoder.canProduce(outputFormat)) {
try {
if (encoder != null) {
return (CoverageResponseDelegate) encoder.getClass().newInstance();
}
} catch (IllegalAccessException ex) {
final NoSuchElementException e = new NoSuchElementException(new StringBuffer(
"Can't create the encoder ").append(encoder.getClass().getName())
.toString());
e.initCause(ex);
throw e;
} catch (InstantiationException ex) {
final NoSuchElementException e = new NoSuchElementException(new StringBuffer(
"Can't create the encoder ").append(encoder.getClass().getName())
.toString());
e.initCause(ex);
throw e;
}
}
}
throw new NoSuchElementException(new StringBuffer("Can't create the encoder ").append(
encoder.getClass().getName()).toString());
}
| public static CoverageResponseDelegate encoderFor(String outputFormat)
throws NoSuchElementException {
CoverageResponseDelegate encoder = null;
for (Iterator it = encoders.iterator(); it.hasNext();) {
encoder = (CoverageResponseDelegate) it.next();
if (encoder.canProduce(outputFormat)) {
try {
if (encoder != null) {
return (CoverageResponseDelegate) encoder.getClass().newInstance();
}
} catch (IllegalAccessException ex) {
final NoSuchElementException e = new NoSuchElementException(new StringBuffer(
"Can't create the encoder ").append(encoder.getClass().getName())
.toString());
e.initCause(ex);
throw e;
} catch (InstantiationException ex) {
final NoSuchElementException e = new NoSuchElementException(new StringBuffer(
"Can't create the encoder ").append(encoder.getClass().getName())
.toString());
e.initCause(ex);
throw e;
}
}
}
throw new NoSuchElementException("Can't create the encoder for format " + outputFormat);
}
|
diff --git a/src/ash/parser/Parser.java b/src/ash/parser/Parser.java
index c06c166..2b51853 100644
--- a/src/ash/parser/Parser.java
+++ b/src/ash/parser/Parser.java
@@ -1,72 +1,72 @@
package ash.parser;
import java.io.Serializable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import bruce.common.utils.CommonUtils;
public final class Parser {
private static final Pattern getFirstPlainTextPattern = Pattern.compile("(\\S+)\\s*");
private static final char ESCAPE_CHAR = '\\';
private static final char STRING_WRAPPING_CHAR = '\"';
private static final char QUOTE_CHAR = '\'';
private Parser() {}
protected static Serializable createAst(String readIn) {
if (readIn.charAt(0) == '(') {
String unWrapped = unWrapped(readIn);
return CommonUtils.isStringNullOrWriteSpace(unWrapped) ? Node.NIL : split(unWrapped);
} else
return readIn;
}
private static String unWrapped(String exp) {
if (exp.charAt(0) == '(' && exp.charAt(exp.length() - 1) == ')')
return exp.substring(1, exp.length() - 1);
throw new UnsupportedOperationException("Can not Unwrap:" + exp);
}
public static Node split(String str) {
String trim = str.trim();
boolean quoteSugar = trim.charAt(0) == QUOTE_CHAR;
String first = quoteSugar ? getFirst(trim.substring(1)) : getFirst(trim);
String rest = getRest(trim, quoteSugar ? first.length() + 1 : first.length());
- Serializable ast = quoteSugar ? new Node("quote", new Node(createAst(first))) : createAst(first);
+ Serializable ast = quoteSugar ? new Node("quote", split(first)) : createAst(first);
if (CommonUtils.isStringNullOrWriteSpace(rest))
return new Node(ast);
else
return new Node(ast, split(rest));
}
private static String getRest(String str, int firstStrLen) {
return str.substring(firstStrLen);
}
private static String getFirst(String str) {
char headCh = str.charAt(0);
return headCh == '(' || headCh == STRING_WRAPPING_CHAR
? str.substring(0, getFirstElemLen(str, 0, 0, '\0'))
: getHeadPlainText(str);
}
protected static String getHeadPlainText(String str) {
Matcher m = getFirstPlainTextPattern.matcher(str);
m.find();
return m.group(1);
}
private static int getFirstElemLen(String src, int balance, int elemLen, char spanChar) {
if (elemLen != 0 && balance == 0 && spanChar == '\0') return elemLen;
final char c = src.charAt(elemLen);
return getFirstElemLen(src,
spanChar == STRING_WRAPPING_CHAR
? balance
: balance + (c == '(' ? 1 : (c == ')' ? -1 : 0)),
elemLen + (c == ESCAPE_CHAR ? 2 : 1),
STRING_WRAPPING_CHAR == c ? (spanChar == c ? '\0' : c) : spanChar);
}
}
| true | true | public static Node split(String str) {
String trim = str.trim();
boolean quoteSugar = trim.charAt(0) == QUOTE_CHAR;
String first = quoteSugar ? getFirst(trim.substring(1)) : getFirst(trim);
String rest = getRest(trim, quoteSugar ? first.length() + 1 : first.length());
Serializable ast = quoteSugar ? new Node("quote", new Node(createAst(first))) : createAst(first);
if (CommonUtils.isStringNullOrWriteSpace(rest))
return new Node(ast);
else
return new Node(ast, split(rest));
}
| public static Node split(String str) {
String trim = str.trim();
boolean quoteSugar = trim.charAt(0) == QUOTE_CHAR;
String first = quoteSugar ? getFirst(trim.substring(1)) : getFirst(trim);
String rest = getRest(trim, quoteSugar ? first.length() + 1 : first.length());
Serializable ast = quoteSugar ? new Node("quote", split(first)) : createAst(first);
if (CommonUtils.isStringNullOrWriteSpace(rest))
return new Node(ast);
else
return new Node(ast, split(rest));
}
|
diff --git a/test/mnj/lua/BaseLibTest.java b/test/mnj/lua/BaseLibTest.java
index d40a4b6..205c8b0 100644
--- a/test/mnj/lua/BaseLibTest.java
+++ b/test/mnj/lua/BaseLibTest.java
@@ -1,297 +1,298 @@
// $Header$
package mnj.lua;
// For j2meunit see http://j2meunit.sourceforge.net/
import j2meunit.framework.Test;
import j2meunit.framework.TestSuite;
// Auxiliary files
// BaseLibTestLoadfile.luc
// return 99
// BaseLibTest.lua - contains functions that test each of base library
// functions. It is important (for testing "error") that this file is
// not stripped if it is loaded in binary form.
// :todo: test radix conversion for tonumber.
// :todo: test unpack with non-default arguments.
// :todo: test rawequal for things with metamethods.
// :todo: test rawget for tables with metamethods.
// :todo: test rawset for tables with metamethods.
// :todo: (when string library is available) test the strings returned
// by assert.
/**
* J2MEUnit tests for Jili's BaseLib (base library). DO NOT SUBCLASS.
* public access granted only because j2meunit makes it necessary.
*/
public class BaseLibTest extends JiliTestCase
{
/** void constructor, necessary for running using
* <code>java j2meunit.textui.TestRunner BaseLibTest</code>
*/
public BaseLibTest() { }
/** Clones constructor from superclass. */
private BaseLibTest(String name)
{
super(name);
}
/**
* Tests BaseLib.
*/
public void testBaseLib()
{
System.out.println("BaseLibTest.testBaseLib()");
Lua L = new Lua();
BaseLib.open(L);
// Test that each global name is defined as expected.
String[] name =
{
"_VERSION",
"_G", "ipairs", "pairs", "print", "rawequal", "rawget", "rawset",
"select", "tonumber", "tostring", "type", "unpack"
};
for (int i=0; i<name.length; ++i)
{
Object o = L.getGlobal(name[i]);
assertTrue(name[i] + " exists", !L.isNil(o));
}
}
/**
* Opens the base library into a fresh Lua state, calls a global
* function, and returns the Lua state.
* @param name name of function to call.
* @param n number of results expected from function.
*/
private Lua luaGlobal(String name, int n)
{
Lua L = new Lua();
BaseLib.open(L);
loadFile(L, "BaseLibTest");
L.call(0, 0);
System.out.println(name);
L.push(L.getGlobal(name));
L.call(0, n);
return L;
}
/**
* Calls a global lua function and checks that <var>n</var> results
* are all true.
*/
private void nTrue(String name, int n)
{
Lua L = luaGlobal(name, n);
for (int i=1; i<=n; ++i)
{
assertTrue("Result " + i + " is true",
L.valueOfBoolean(true).equals(L.value(i)));
}
}
/**
* Sometimes overridden by anon subclass.
*/
public void runTest()
{
nTrue(getName(), 1);
}
/**
* Tests print. Not much we can reasonably do here apart from call
* it. We can't automatically check that the output appears anywhere
* or is correct. This also tests tostring to some extent; print
* calls tostring internally, so this tests that it can be called
* without error, for example.
*/
public void testPrint()
{
luaGlobal("testprint", 0);
}
public void testTostring()
{
nTrue("testtostring", 5);
}
public void testTonumber()
{
nTrue("testtonumber", 5);
}
public void testType()
{
nTrue("testtype", 6);
}
public void testSelect()
{
nTrue("testselect", 2);
}
public void testPairs()
{
nTrue("testpairs", 4);
}
public void testNext()
{
nTrue("testnext", 4);
}
public void testIpairs()
{
nTrue("testipairs", 4);
}
public void testRawequal()
{
nTrue("testrawequal", 7);
}
public void testRawget()
{
nTrue("testrawget", 2);
}
public void testRawset()
{
nTrue("testrawset", 2);
}
public void testPcall()
{
nTrue("testpcall", 2);
}
public void testError()
{
nTrue("testerror", 2);
}
public void testMetatable()
{
nTrue("testmetatable", 2);
}
public void test__metatable()
{
nTrue("test__metatable", 2);
}
/** Tests _VERSION */
public void testVersion()
{
Lua L = new Lua();
BaseLib.open(L);
Object o = L.getGlobal("_VERSION");
assertTrue("_VERSION exists", o != null);
assertTrue("_VERSION is a string", L.isString(o));
}
public void testErrormore()
{
nTrue("testerrormore", 2);
}
public void testpcall2()
{
nTrue("testpcall2", 4);
}
public void testpcall3()
{
nTrue("testpcall3", 2);
}
public Test suite()
{
TestSuite suite = new TestSuite();
suite.addTest(new BaseLibTest("testBaseLib")
{
public void runTest() { testBaseLib(); } });
suite.addTest(new BaseLibTest("testPrint")
{
public void runTest() { testPrint(); } });
suite.addTest(new BaseLibTest("testTostring")
{
public void runTest() { testTostring(); } });
suite.addTest(new BaseLibTest("testTonumber")
{
public void runTest() { testTonumber(); } });
suite.addTest(new BaseLibTest("testType")
{
public void runTest() { testType(); } });
suite.addTest(new BaseLibTest("testSelect")
{
public void runTest() { testSelect(); } });
suite.addTest(new BaseLibTest("testunpack"));
suite.addTest(new BaseLibTest("testPairs")
{
public void runTest() { testPairs(); } });
suite.addTest(new BaseLibTest("testIpairs")
{
public void runTest() { testIpairs(); } });
suite.addTest(new BaseLibTest("testRawequal")
{
public void runTest() { testRawequal(); } });
suite.addTest(new BaseLibTest("testRawget")
{
public void runTest() { testRawget(); } });
suite.addTest(new BaseLibTest("testRawset")
{
public void runTest() { testRawset(); } });
suite.addTest(new BaseLibTest("testgetfenv"));
suite.addTest(new BaseLibTest("testsetfenv"));
suite.addTest(new BaseLibTest("testNext")
{
public void runTest() { testNext(); } });
suite.addTest(new BaseLibTest("testPcall")
{
public void runTest() { testPcall(); } });
suite.addTest(new BaseLibTest("testError")
{
public void runTest() { testError(); } });
suite.addTest(new BaseLibTest("testMetatable")
{
public void runTest() { testMetatable(); } });
suite.addTest(new BaseLibTest("test__metatable")
{
public void runTest() { test__metatable(); } });
suite.addTest(new BaseLibTest("test__tostring"));
suite.addTest(new BaseLibTest("testcollectgarbage"));
suite.addTest(new BaseLibTest("testassert"));
suite.addTest(new BaseLibTest("testloadstring"));
suite.addTest(new BaseLibTest("testloadfile"));
suite.addTest(new BaseLibTest("testload"));
suite.addTest(new BaseLibTest("testdofile"));
suite.addTest(new BaseLibTest("testversion")
{
public void runTest() { testVersion(); } });
suite.addTest(new BaseLibTest("testxpcall"));
suite.addTest(new BaseLibTest("testerrormore")
{
public void runTest() { testErrormore(); } });
suite.addTest(new BaseLibTest("testpcall2")
{
public void runTest() { testpcall2(); }
});
suite.addTest(new BaseLibTest("testpcall3")
{
public void runTest() { testpcall3(); }
});
suite.addTest(new BaseLibTest("testpcall4"));
suite.addTest(new BaseLibTest("testpcall5"));
suite.addTest(new BaseLibTest("testunpackbig"));
suite.addTest(new BaseLibTest("testloaderr"));
suite.addTest(new BaseLibTest("testnanindex"));
+ suite.addTest(new BaseLibTest("testhexerror"));
return suite;
}
}
| true | true | public Test suite()
{
TestSuite suite = new TestSuite();
suite.addTest(new BaseLibTest("testBaseLib")
{
public void runTest() { testBaseLib(); } });
suite.addTest(new BaseLibTest("testPrint")
{
public void runTest() { testPrint(); } });
suite.addTest(new BaseLibTest("testTostring")
{
public void runTest() { testTostring(); } });
suite.addTest(new BaseLibTest("testTonumber")
{
public void runTest() { testTonumber(); } });
suite.addTest(new BaseLibTest("testType")
{
public void runTest() { testType(); } });
suite.addTest(new BaseLibTest("testSelect")
{
public void runTest() { testSelect(); } });
suite.addTest(new BaseLibTest("testunpack"));
suite.addTest(new BaseLibTest("testPairs")
{
public void runTest() { testPairs(); } });
suite.addTest(new BaseLibTest("testIpairs")
{
public void runTest() { testIpairs(); } });
suite.addTest(new BaseLibTest("testRawequal")
{
public void runTest() { testRawequal(); } });
suite.addTest(new BaseLibTest("testRawget")
{
public void runTest() { testRawget(); } });
suite.addTest(new BaseLibTest("testRawset")
{
public void runTest() { testRawset(); } });
suite.addTest(new BaseLibTest("testgetfenv"));
suite.addTest(new BaseLibTest("testsetfenv"));
suite.addTest(new BaseLibTest("testNext")
{
public void runTest() { testNext(); } });
suite.addTest(new BaseLibTest("testPcall")
{
public void runTest() { testPcall(); } });
suite.addTest(new BaseLibTest("testError")
{
public void runTest() { testError(); } });
suite.addTest(new BaseLibTest("testMetatable")
{
public void runTest() { testMetatable(); } });
suite.addTest(new BaseLibTest("test__metatable")
{
public void runTest() { test__metatable(); } });
suite.addTest(new BaseLibTest("test__tostring"));
suite.addTest(new BaseLibTest("testcollectgarbage"));
suite.addTest(new BaseLibTest("testassert"));
suite.addTest(new BaseLibTest("testloadstring"));
suite.addTest(new BaseLibTest("testloadfile"));
suite.addTest(new BaseLibTest("testload"));
suite.addTest(new BaseLibTest("testdofile"));
suite.addTest(new BaseLibTest("testversion")
{
public void runTest() { testVersion(); } });
suite.addTest(new BaseLibTest("testxpcall"));
suite.addTest(new BaseLibTest("testerrormore")
{
public void runTest() { testErrormore(); } });
suite.addTest(new BaseLibTest("testpcall2")
{
public void runTest() { testpcall2(); }
});
suite.addTest(new BaseLibTest("testpcall3")
{
public void runTest() { testpcall3(); }
});
suite.addTest(new BaseLibTest("testpcall4"));
suite.addTest(new BaseLibTest("testpcall5"));
suite.addTest(new BaseLibTest("testunpackbig"));
suite.addTest(new BaseLibTest("testloaderr"));
suite.addTest(new BaseLibTest("testnanindex"));
return suite;
}
| public Test suite()
{
TestSuite suite = new TestSuite();
suite.addTest(new BaseLibTest("testBaseLib")
{
public void runTest() { testBaseLib(); } });
suite.addTest(new BaseLibTest("testPrint")
{
public void runTest() { testPrint(); } });
suite.addTest(new BaseLibTest("testTostring")
{
public void runTest() { testTostring(); } });
suite.addTest(new BaseLibTest("testTonumber")
{
public void runTest() { testTonumber(); } });
suite.addTest(new BaseLibTest("testType")
{
public void runTest() { testType(); } });
suite.addTest(new BaseLibTest("testSelect")
{
public void runTest() { testSelect(); } });
suite.addTest(new BaseLibTest("testunpack"));
suite.addTest(new BaseLibTest("testPairs")
{
public void runTest() { testPairs(); } });
suite.addTest(new BaseLibTest("testIpairs")
{
public void runTest() { testIpairs(); } });
suite.addTest(new BaseLibTest("testRawequal")
{
public void runTest() { testRawequal(); } });
suite.addTest(new BaseLibTest("testRawget")
{
public void runTest() { testRawget(); } });
suite.addTest(new BaseLibTest("testRawset")
{
public void runTest() { testRawset(); } });
suite.addTest(new BaseLibTest("testgetfenv"));
suite.addTest(new BaseLibTest("testsetfenv"));
suite.addTest(new BaseLibTest("testNext")
{
public void runTest() { testNext(); } });
suite.addTest(new BaseLibTest("testPcall")
{
public void runTest() { testPcall(); } });
suite.addTest(new BaseLibTest("testError")
{
public void runTest() { testError(); } });
suite.addTest(new BaseLibTest("testMetatable")
{
public void runTest() { testMetatable(); } });
suite.addTest(new BaseLibTest("test__metatable")
{
public void runTest() { test__metatable(); } });
suite.addTest(new BaseLibTest("test__tostring"));
suite.addTest(new BaseLibTest("testcollectgarbage"));
suite.addTest(new BaseLibTest("testassert"));
suite.addTest(new BaseLibTest("testloadstring"));
suite.addTest(new BaseLibTest("testloadfile"));
suite.addTest(new BaseLibTest("testload"));
suite.addTest(new BaseLibTest("testdofile"));
suite.addTest(new BaseLibTest("testversion")
{
public void runTest() { testVersion(); } });
suite.addTest(new BaseLibTest("testxpcall"));
suite.addTest(new BaseLibTest("testerrormore")
{
public void runTest() { testErrormore(); } });
suite.addTest(new BaseLibTest("testpcall2")
{
public void runTest() { testpcall2(); }
});
suite.addTest(new BaseLibTest("testpcall3")
{
public void runTest() { testpcall3(); }
});
suite.addTest(new BaseLibTest("testpcall4"));
suite.addTest(new BaseLibTest("testpcall5"));
suite.addTest(new BaseLibTest("testunpackbig"));
suite.addTest(new BaseLibTest("testloaderr"));
suite.addTest(new BaseLibTest("testnanindex"));
suite.addTest(new BaseLibTest("testhexerror"));
return suite;
}
|
diff --git a/web/src/org/openmrs/module/dataintegrity/web/controller/TransferCheckListController.java b/web/src/org/openmrs/module/dataintegrity/web/controller/TransferCheckListController.java
index 4c1d367..261be28 100644
--- a/web/src/org/openmrs/module/dataintegrity/web/controller/TransferCheckListController.java
+++ b/web/src/org/openmrs/module/dataintegrity/web/controller/TransferCheckListController.java
@@ -1,213 +1,212 @@
package org.openmrs.module.dataintegrity.web.controller;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.openmrs.api.context.Context;
import org.openmrs.module.Module;
import org.openmrs.module.ModuleException;
import org.openmrs.module.ModuleFactory;
import org.openmrs.module.ModuleUtil;
import org.openmrs.module.dataintegrity.DataIntegrityCheckTemplate;
import org.openmrs.module.dataintegrity.DataIntegrityService;
import org.openmrs.module.dataintegrity.DataIntegrityXmlFileParser;
import org.openmrs.module.dataintegrity.IDataIntegrityCheckUpload;
import org.openmrs.module.dataintegrity.IntegrityCheckUtil;
import org.openmrs.web.WebConstants;
import org.openmrs.web.WebUtil;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.view.RedirectView;
public class TransferCheckListController extends SimpleFormController {
private DataIntegrityService getDataIntegrityService() {
return (DataIntegrityService)Context.getService(DataIntegrityService.class);
}
protected Object formBackingObject(HttpServletRequest request) throws ServletException {
return "not used";
}
@Override
protected Map referenceData(HttpServletRequest request, Object command, Errors errors) throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
if (Context.isAuthenticated()) {
map.put("existingChecks", getDataIntegrityService().getAllDataIntegrityCheckTemplates());
}
return map; //return all existing integrity checks
}
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object obj,
BindException errors) throws Exception {
HttpSession httpSession = request.getSession();
MessageSourceAccessor msa = getMessageSourceAccessor();
String success = "";
String error = "";
String view = getFormView();
String[] checkList = request.getParameterValues("integrityCheckId"); //Get the list of integrity check IDs
if (checkList == null) { //when uploading checkList = null
if (Context.isAuthenticated() && request instanceof MultipartHttpServletRequest) {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
MultipartFile multipartCheckFile = multipartRequest.getFile("checkFile");
if (multipartCheckFile != null && !multipartCheckFile.isEmpty()) {
String filename = WebUtil.stripFilename(multipartCheckFile.getOriginalFilename());
if (filename.toLowerCase().endsWith("xml")) {
InputStream inputStream = null;
File checkFile = null;
try {
inputStream = multipartCheckFile.getInputStream();
checkFile = IntegrityCheckUtil.uploadIntegrityCheckFile(inputStream, filename);
DataIntegrityXmlFileParser fileParser = new DataIntegrityXmlFileParser(checkFile);
List<IDataIntegrityCheckUpload> checksToUpload = fileParser.getChecksToAdd();
for (int i=0; i<checksToUpload.size(); i++) {
IDataIntegrityCheckUpload check = checksToUpload.get(i);
DataIntegrityCheckTemplate template = new DataIntegrityCheckTemplate();
template.setIntegrityCheckType(check.getCheckType());
template.setIntegrityCheckCode(check.getCheckCode());
template.setIntegrityCheckFailDirective(check.getCheckFailDirective());
template.setIntegrityCheckFailDirectiveOperator(check.getCheckFailDirectiveOperator());
template.setIntegrityCheckName(check.getCheckName());
template.setIntegrityCheckRepairDirective(check.getCheckRepairDirective());
template.setIntegrityCheckResultType(check.getCheckResultType());
template.setIntegrityCheckRepairType(check.getCheckRepairType());
template.setIntegrityCheckParameters(check.getCheckParameters());
getDataIntegrityService().saveDataIntegrityCheckTemplate(template);
success += check.getCheckName() + " " + msa.getMessage("dataintegrity.upload.success") + "<br />";
}
}
catch (Exception e) {
error = msa.getMessage("dataintegrity.upload.fail") + ". Message: " + e.getMessage();
if (checkFile != null) {
checkFile.delete();
}
}
finally {
// clean up the check repository folder
try {
if (inputStream != null)
inputStream.close();
}
catch (IOException io) {
}
}
} else {
error = msa.getMessage("dataintegrity.upload.xml");
}
}
}
} else {
//exporting integrity checks to a XML file
try {
DataIntegrityService service = getDataIntegrityService();
File exportFile = IntegrityCheckUtil.getExportIntegrityCheckFile();
FileWriter fstream = new FileWriter(exportFile);
BufferedWriter out = new BufferedWriter(fstream);
StringBuffer exportString = new StringBuffer();
exportString.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<checks>\r\n");
for (String checkId : checkList) {
DataIntegrityCheckTemplate template = service.getDataIntegrityCheckTemplate(Integer.valueOf(checkId));
exportString.append("\t<check type=\"" + template.getIntegrityCheckType() + "\">\r\n");
- exportString.append("\t\t<id>" + template.getIntegrityCheckId() + "</id>\r\n");
exportString.append("\t\t<name>" + template.getIntegrityCheckName() + "</name>\r\n");
exportString.append("\t\t<code>" + template.getIntegrityCheckCode() + "</code>\r\n");
exportString.append("\t\t<resultType>" + template.getIntegrityCheckResultType() + "</resultType>\r\n");
exportString.append("\t\t<fail operator=\"" + template.getIntegrityCheckFailDirectiveOperator() + "\">" + template.getIntegrityCheckFailDirective() + "</fail>\r\n");
if (!template.getIntegrityCheckRepairType().equals("none")) {
exportString.append("\t\t<repair type=\"" + template.getIntegrityCheckRepairType() + "\">" + template.getIntegrityCheckRepairDirective() + "</repair>\r\n");
}
if (!template.getIntegrityCheckParameters().equals("")) {
exportString.append("\t\t<parameters>" + template.getIntegrityCheckParameters() + "</parameters>\r\n");
}
exportString.append("\t</check>\r\n");
}
exportString.append("</checks>\r\n");
out.write(exportString.toString());
out.close();
//Zip the file
File zipFile = zipExportFile(exportFile);
//Downloading the file
FileInputStream fileToDownload = new FileInputStream(zipFile);
ServletOutputStream output = response.getOutputStream();
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=IntegrityChecks.zip");
response.setContentLength(fileToDownload.available());
int c;
while ((c = fileToDownload.read()) != -1)
{
output.write(c);
}
output.flush();
output.close();
fileToDownload.close();
zipFile.delete();
exportFile.delete();
} catch (Exception e) {
error = msa.getMessage("dataintegrity.upload.export.error") + ". Message: " + e.getMessage();
}
}
view = getSuccessView();
if (!success.equals(""))
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, success);
if (!error.equals(""))
httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, error);
return new ModelAndView(new RedirectView(view));
}
private File zipExportFile(File file) throws Exception {
byte[] buf = new byte[1024];
try {
File zipFile = IntegrityCheckUtil.getZippedExportIntegrityCheckFile();
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile));
// Compress the files
FileInputStream in = new FileInputStream(file);
// Add ZIP entry to output stream.
out.putNextEntry(new ZipEntry(file.getName()));
// Transfer bytes from the file to the ZIP file
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
// Complete the entry
out.closeEntry();
in.close();
// Complete the ZIP file
out.close();
return zipFile;
} catch (Exception e) {
throw new Exception("Failed to zip file. " + e.getMessage());
}
}
}
| true | true | protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object obj,
BindException errors) throws Exception {
HttpSession httpSession = request.getSession();
MessageSourceAccessor msa = getMessageSourceAccessor();
String success = "";
String error = "";
String view = getFormView();
String[] checkList = request.getParameterValues("integrityCheckId"); //Get the list of integrity check IDs
if (checkList == null) { //when uploading checkList = null
if (Context.isAuthenticated() && request instanceof MultipartHttpServletRequest) {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
MultipartFile multipartCheckFile = multipartRequest.getFile("checkFile");
if (multipartCheckFile != null && !multipartCheckFile.isEmpty()) {
String filename = WebUtil.stripFilename(multipartCheckFile.getOriginalFilename());
if (filename.toLowerCase().endsWith("xml")) {
InputStream inputStream = null;
File checkFile = null;
try {
inputStream = multipartCheckFile.getInputStream();
checkFile = IntegrityCheckUtil.uploadIntegrityCheckFile(inputStream, filename);
DataIntegrityXmlFileParser fileParser = new DataIntegrityXmlFileParser(checkFile);
List<IDataIntegrityCheckUpload> checksToUpload = fileParser.getChecksToAdd();
for (int i=0; i<checksToUpload.size(); i++) {
IDataIntegrityCheckUpload check = checksToUpload.get(i);
DataIntegrityCheckTemplate template = new DataIntegrityCheckTemplate();
template.setIntegrityCheckType(check.getCheckType());
template.setIntegrityCheckCode(check.getCheckCode());
template.setIntegrityCheckFailDirective(check.getCheckFailDirective());
template.setIntegrityCheckFailDirectiveOperator(check.getCheckFailDirectiveOperator());
template.setIntegrityCheckName(check.getCheckName());
template.setIntegrityCheckRepairDirective(check.getCheckRepairDirective());
template.setIntegrityCheckResultType(check.getCheckResultType());
template.setIntegrityCheckRepairType(check.getCheckRepairType());
template.setIntegrityCheckParameters(check.getCheckParameters());
getDataIntegrityService().saveDataIntegrityCheckTemplate(template);
success += check.getCheckName() + " " + msa.getMessage("dataintegrity.upload.success") + "<br />";
}
}
catch (Exception e) {
error = msa.getMessage("dataintegrity.upload.fail") + ". Message: " + e.getMessage();
if (checkFile != null) {
checkFile.delete();
}
}
finally {
// clean up the check repository folder
try {
if (inputStream != null)
inputStream.close();
}
catch (IOException io) {
}
}
} else {
error = msa.getMessage("dataintegrity.upload.xml");
}
}
}
} else {
//exporting integrity checks to a XML file
try {
DataIntegrityService service = getDataIntegrityService();
File exportFile = IntegrityCheckUtil.getExportIntegrityCheckFile();
FileWriter fstream = new FileWriter(exportFile);
BufferedWriter out = new BufferedWriter(fstream);
StringBuffer exportString = new StringBuffer();
exportString.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<checks>\r\n");
for (String checkId : checkList) {
DataIntegrityCheckTemplate template = service.getDataIntegrityCheckTemplate(Integer.valueOf(checkId));
exportString.append("\t<check type=\"" + template.getIntegrityCheckType() + "\">\r\n");
exportString.append("\t\t<id>" + template.getIntegrityCheckId() + "</id>\r\n");
exportString.append("\t\t<name>" + template.getIntegrityCheckName() + "</name>\r\n");
exportString.append("\t\t<code>" + template.getIntegrityCheckCode() + "</code>\r\n");
exportString.append("\t\t<resultType>" + template.getIntegrityCheckResultType() + "</resultType>\r\n");
exportString.append("\t\t<fail operator=\"" + template.getIntegrityCheckFailDirectiveOperator() + "\">" + template.getIntegrityCheckFailDirective() + "</fail>\r\n");
if (!template.getIntegrityCheckRepairType().equals("none")) {
exportString.append("\t\t<repair type=\"" + template.getIntegrityCheckRepairType() + "\">" + template.getIntegrityCheckRepairDirective() + "</repair>\r\n");
}
if (!template.getIntegrityCheckParameters().equals("")) {
exportString.append("\t\t<parameters>" + template.getIntegrityCheckParameters() + "</parameters>\r\n");
}
exportString.append("\t</check>\r\n");
}
exportString.append("</checks>\r\n");
out.write(exportString.toString());
out.close();
//Zip the file
File zipFile = zipExportFile(exportFile);
//Downloading the file
FileInputStream fileToDownload = new FileInputStream(zipFile);
ServletOutputStream output = response.getOutputStream();
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=IntegrityChecks.zip");
response.setContentLength(fileToDownload.available());
int c;
while ((c = fileToDownload.read()) != -1)
{
output.write(c);
}
output.flush();
output.close();
fileToDownload.close();
zipFile.delete();
exportFile.delete();
} catch (Exception e) {
error = msa.getMessage("dataintegrity.upload.export.error") + ". Message: " + e.getMessage();
}
}
view = getSuccessView();
if (!success.equals(""))
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, success);
if (!error.equals(""))
httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, error);
return new ModelAndView(new RedirectView(view));
}
| protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object obj,
BindException errors) throws Exception {
HttpSession httpSession = request.getSession();
MessageSourceAccessor msa = getMessageSourceAccessor();
String success = "";
String error = "";
String view = getFormView();
String[] checkList = request.getParameterValues("integrityCheckId"); //Get the list of integrity check IDs
if (checkList == null) { //when uploading checkList = null
if (Context.isAuthenticated() && request instanceof MultipartHttpServletRequest) {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
MultipartFile multipartCheckFile = multipartRequest.getFile("checkFile");
if (multipartCheckFile != null && !multipartCheckFile.isEmpty()) {
String filename = WebUtil.stripFilename(multipartCheckFile.getOriginalFilename());
if (filename.toLowerCase().endsWith("xml")) {
InputStream inputStream = null;
File checkFile = null;
try {
inputStream = multipartCheckFile.getInputStream();
checkFile = IntegrityCheckUtil.uploadIntegrityCheckFile(inputStream, filename);
DataIntegrityXmlFileParser fileParser = new DataIntegrityXmlFileParser(checkFile);
List<IDataIntegrityCheckUpload> checksToUpload = fileParser.getChecksToAdd();
for (int i=0; i<checksToUpload.size(); i++) {
IDataIntegrityCheckUpload check = checksToUpload.get(i);
DataIntegrityCheckTemplate template = new DataIntegrityCheckTemplate();
template.setIntegrityCheckType(check.getCheckType());
template.setIntegrityCheckCode(check.getCheckCode());
template.setIntegrityCheckFailDirective(check.getCheckFailDirective());
template.setIntegrityCheckFailDirectiveOperator(check.getCheckFailDirectiveOperator());
template.setIntegrityCheckName(check.getCheckName());
template.setIntegrityCheckRepairDirective(check.getCheckRepairDirective());
template.setIntegrityCheckResultType(check.getCheckResultType());
template.setIntegrityCheckRepairType(check.getCheckRepairType());
template.setIntegrityCheckParameters(check.getCheckParameters());
getDataIntegrityService().saveDataIntegrityCheckTemplate(template);
success += check.getCheckName() + " " + msa.getMessage("dataintegrity.upload.success") + "<br />";
}
}
catch (Exception e) {
error = msa.getMessage("dataintegrity.upload.fail") + ". Message: " + e.getMessage();
if (checkFile != null) {
checkFile.delete();
}
}
finally {
// clean up the check repository folder
try {
if (inputStream != null)
inputStream.close();
}
catch (IOException io) {
}
}
} else {
error = msa.getMessage("dataintegrity.upload.xml");
}
}
}
} else {
//exporting integrity checks to a XML file
try {
DataIntegrityService service = getDataIntegrityService();
File exportFile = IntegrityCheckUtil.getExportIntegrityCheckFile();
FileWriter fstream = new FileWriter(exportFile);
BufferedWriter out = new BufferedWriter(fstream);
StringBuffer exportString = new StringBuffer();
exportString.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<checks>\r\n");
for (String checkId : checkList) {
DataIntegrityCheckTemplate template = service.getDataIntegrityCheckTemplate(Integer.valueOf(checkId));
exportString.append("\t<check type=\"" + template.getIntegrityCheckType() + "\">\r\n");
exportString.append("\t\t<name>" + template.getIntegrityCheckName() + "</name>\r\n");
exportString.append("\t\t<code>" + template.getIntegrityCheckCode() + "</code>\r\n");
exportString.append("\t\t<resultType>" + template.getIntegrityCheckResultType() + "</resultType>\r\n");
exportString.append("\t\t<fail operator=\"" + template.getIntegrityCheckFailDirectiveOperator() + "\">" + template.getIntegrityCheckFailDirective() + "</fail>\r\n");
if (!template.getIntegrityCheckRepairType().equals("none")) {
exportString.append("\t\t<repair type=\"" + template.getIntegrityCheckRepairType() + "\">" + template.getIntegrityCheckRepairDirective() + "</repair>\r\n");
}
if (!template.getIntegrityCheckParameters().equals("")) {
exportString.append("\t\t<parameters>" + template.getIntegrityCheckParameters() + "</parameters>\r\n");
}
exportString.append("\t</check>\r\n");
}
exportString.append("</checks>\r\n");
out.write(exportString.toString());
out.close();
//Zip the file
File zipFile = zipExportFile(exportFile);
//Downloading the file
FileInputStream fileToDownload = new FileInputStream(zipFile);
ServletOutputStream output = response.getOutputStream();
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=IntegrityChecks.zip");
response.setContentLength(fileToDownload.available());
int c;
while ((c = fileToDownload.read()) != -1)
{
output.write(c);
}
output.flush();
output.close();
fileToDownload.close();
zipFile.delete();
exportFile.delete();
} catch (Exception e) {
error = msa.getMessage("dataintegrity.upload.export.error") + ". Message: " + e.getMessage();
}
}
view = getSuccessView();
if (!success.equals(""))
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, success);
if (!error.equals(""))
httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, error);
return new ModelAndView(new RedirectView(view));
}
|
diff --git a/MultiDraw/src/gui/ToolPalette.java b/MultiDraw/src/gui/ToolPalette.java
index 8999db9..bcc5a2a 100644
--- a/MultiDraw/src/gui/ToolPalette.java
+++ b/MultiDraw/src/gui/ToolPalette.java
@@ -1,120 +1,122 @@
package gui;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Enumeration;
import javax.imageio.ImageIO;
import javax.swing.AbstractButton;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JToggleButton;
import tools.ClientToolProperties;
public class ToolPalette extends JPanel {
private ButtonGroup btnGroup;
private ClientToolProperties tp;
// Command sent when corresponding button is pressed: PEN, BRUSH, BUCKET,
// ERASER, TEXT, SHAPE_LINE, SHAPE_RECTANGLE, SHAPE_ELLIPSE
public ToolPalette(ClientToolProperties tp) {
btnGroup = new ButtonGroup();
this.tp = tp;
this.setOpaque(false);
BtnListener btnListener = new BtnListener();
this.setLayout(new GridLayout(4, 2, 5, 5));
try {
// pen button
JButton penButton = new JButton();
Image img = ImageIO.read(getClass().getResource("/res/icons/pen.png"));
penButton.setIcon(new ImageIcon(img));
penButton.setActionCommand(ClientToolProperties.PEN_TOOL + "");
btnGroup.add(penButton);
// brush button
JButton brushButton = new JButton();
img = ImageIO.read(getClass().getResource("/res/icons/paintbrush.png"));
brushButton.setIcon(new ImageIcon(img));
brushButton.setActionCommand(ClientToolProperties.BRUSH_TOOL + "");
btnGroup.add(brushButton);
// colorPicker button
JButton colorPicker = new JButton();
img = ImageIO.read(getClass().getResource("/res/icons/pipette.png"));
colorPicker.setIcon(new ImageIcon(img));
colorPicker.setActionCommand(ClientToolProperties.COLORPICKER_TOOL + "");
btnGroup.add(colorPicker);
// eraser button
JButton eraserButton = new JButton();
img = ImageIO.read(getClass().getResource("/res/icons/erase.png"));
eraserButton.setIcon(new ImageIcon(img));
eraserButton.setActionCommand(ClientToolProperties.ERASER_TOOL + "");
btnGroup.add(eraserButton);
// text button
JButton textButton = new JButton();
img = ImageIO.read(getClass().getResource("/res/icons/text.png"));
textButton.setIcon(new ImageIcon(img));
textButton.setActionCommand(ClientToolProperties.TEXT_TOOL + "");
btnGroup.add(textButton);
// line button
JButton lineButton = new JButton();
img = ImageIO.read(getClass().getResource("/res/icons/line.png"));
lineButton.setIcon(new ImageIcon(img));
lineButton.setActionCommand(ClientToolProperties.LINE_TOOL + "");
btnGroup.add(lineButton);
// rectangle button
JButton rectangleButton = new JButton();
img = ImageIO.read(getClass().getResource("/res/icons/rectangle.png"));
rectangleButton.setIcon(new ImageIcon(img));
rectangleButton.setActionCommand(ClientToolProperties.RECTANGLE_TOOL + "");
btnGroup.add(rectangleButton);
// ellipse button
JButton ellipseButton = new JButton();
img = ImageIO.read(getClass().getResource("/res/icons/ellipse.png"));
ellipseButton.setIcon(new ImageIcon(img));
ellipseButton.setActionCommand(ClientToolProperties.ELLIPSE_TOOL + "");
btnGroup.add(ellipseButton);
Enumeration<AbstractButton> buttons = btnGroup.getElements();
while (buttons.hasMoreElements()) {
JButton b = (JButton) buttons.nextElement();
b.setPreferredSize(new Dimension(30, 30));
b.addActionListener(btnListener);
b.setFocusPainted(false);
+ b.setBackground(new Color(255, 255, 255));
this.add(b);
}
+ brushButton.setBackground(new Color(200, 200, 200));
} catch (Exception ex) {
System.out.println("Exception: " + ex.getMessage());
}
}
private class BtnListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
Enumeration<AbstractButton> buttons = btnGroup.getElements();
while (buttons.hasMoreElements()) {
JButton b = (JButton) buttons.nextElement();
b.setBackground(new Color(255, 255, 255));
}
JButton pressedButton = ((JButton) e.getSource());
pressedButton.setBackground(new Color(200, 200, 200));
int tool = Integer.parseInt(e.getActionCommand());
tp.changeTool(tool);
}
}
}
| false | true | public ToolPalette(ClientToolProperties tp) {
btnGroup = new ButtonGroup();
this.tp = tp;
this.setOpaque(false);
BtnListener btnListener = new BtnListener();
this.setLayout(new GridLayout(4, 2, 5, 5));
try {
// pen button
JButton penButton = new JButton();
Image img = ImageIO.read(getClass().getResource("/res/icons/pen.png"));
penButton.setIcon(new ImageIcon(img));
penButton.setActionCommand(ClientToolProperties.PEN_TOOL + "");
btnGroup.add(penButton);
// brush button
JButton brushButton = new JButton();
img = ImageIO.read(getClass().getResource("/res/icons/paintbrush.png"));
brushButton.setIcon(new ImageIcon(img));
brushButton.setActionCommand(ClientToolProperties.BRUSH_TOOL + "");
btnGroup.add(brushButton);
// colorPicker button
JButton colorPicker = new JButton();
img = ImageIO.read(getClass().getResource("/res/icons/pipette.png"));
colorPicker.setIcon(new ImageIcon(img));
colorPicker.setActionCommand(ClientToolProperties.COLORPICKER_TOOL + "");
btnGroup.add(colorPicker);
// eraser button
JButton eraserButton = new JButton();
img = ImageIO.read(getClass().getResource("/res/icons/erase.png"));
eraserButton.setIcon(new ImageIcon(img));
eraserButton.setActionCommand(ClientToolProperties.ERASER_TOOL + "");
btnGroup.add(eraserButton);
// text button
JButton textButton = new JButton();
img = ImageIO.read(getClass().getResource("/res/icons/text.png"));
textButton.setIcon(new ImageIcon(img));
textButton.setActionCommand(ClientToolProperties.TEXT_TOOL + "");
btnGroup.add(textButton);
// line button
JButton lineButton = new JButton();
img = ImageIO.read(getClass().getResource("/res/icons/line.png"));
lineButton.setIcon(new ImageIcon(img));
lineButton.setActionCommand(ClientToolProperties.LINE_TOOL + "");
btnGroup.add(lineButton);
// rectangle button
JButton rectangleButton = new JButton();
img = ImageIO.read(getClass().getResource("/res/icons/rectangle.png"));
rectangleButton.setIcon(new ImageIcon(img));
rectangleButton.setActionCommand(ClientToolProperties.RECTANGLE_TOOL + "");
btnGroup.add(rectangleButton);
// ellipse button
JButton ellipseButton = new JButton();
img = ImageIO.read(getClass().getResource("/res/icons/ellipse.png"));
ellipseButton.setIcon(new ImageIcon(img));
ellipseButton.setActionCommand(ClientToolProperties.ELLIPSE_TOOL + "");
btnGroup.add(ellipseButton);
Enumeration<AbstractButton> buttons = btnGroup.getElements();
while (buttons.hasMoreElements()) {
JButton b = (JButton) buttons.nextElement();
b.setPreferredSize(new Dimension(30, 30));
b.addActionListener(btnListener);
b.setFocusPainted(false);
this.add(b);
}
} catch (Exception ex) {
System.out.println("Exception: " + ex.getMessage());
}
}
| public ToolPalette(ClientToolProperties tp) {
btnGroup = new ButtonGroup();
this.tp = tp;
this.setOpaque(false);
BtnListener btnListener = new BtnListener();
this.setLayout(new GridLayout(4, 2, 5, 5));
try {
// pen button
JButton penButton = new JButton();
Image img = ImageIO.read(getClass().getResource("/res/icons/pen.png"));
penButton.setIcon(new ImageIcon(img));
penButton.setActionCommand(ClientToolProperties.PEN_TOOL + "");
btnGroup.add(penButton);
// brush button
JButton brushButton = new JButton();
img = ImageIO.read(getClass().getResource("/res/icons/paintbrush.png"));
brushButton.setIcon(new ImageIcon(img));
brushButton.setActionCommand(ClientToolProperties.BRUSH_TOOL + "");
btnGroup.add(brushButton);
// colorPicker button
JButton colorPicker = new JButton();
img = ImageIO.read(getClass().getResource("/res/icons/pipette.png"));
colorPicker.setIcon(new ImageIcon(img));
colorPicker.setActionCommand(ClientToolProperties.COLORPICKER_TOOL + "");
btnGroup.add(colorPicker);
// eraser button
JButton eraserButton = new JButton();
img = ImageIO.read(getClass().getResource("/res/icons/erase.png"));
eraserButton.setIcon(new ImageIcon(img));
eraserButton.setActionCommand(ClientToolProperties.ERASER_TOOL + "");
btnGroup.add(eraserButton);
// text button
JButton textButton = new JButton();
img = ImageIO.read(getClass().getResource("/res/icons/text.png"));
textButton.setIcon(new ImageIcon(img));
textButton.setActionCommand(ClientToolProperties.TEXT_TOOL + "");
btnGroup.add(textButton);
// line button
JButton lineButton = new JButton();
img = ImageIO.read(getClass().getResource("/res/icons/line.png"));
lineButton.setIcon(new ImageIcon(img));
lineButton.setActionCommand(ClientToolProperties.LINE_TOOL + "");
btnGroup.add(lineButton);
// rectangle button
JButton rectangleButton = new JButton();
img = ImageIO.read(getClass().getResource("/res/icons/rectangle.png"));
rectangleButton.setIcon(new ImageIcon(img));
rectangleButton.setActionCommand(ClientToolProperties.RECTANGLE_TOOL + "");
btnGroup.add(rectangleButton);
// ellipse button
JButton ellipseButton = new JButton();
img = ImageIO.read(getClass().getResource("/res/icons/ellipse.png"));
ellipseButton.setIcon(new ImageIcon(img));
ellipseButton.setActionCommand(ClientToolProperties.ELLIPSE_TOOL + "");
btnGroup.add(ellipseButton);
Enumeration<AbstractButton> buttons = btnGroup.getElements();
while (buttons.hasMoreElements()) {
JButton b = (JButton) buttons.nextElement();
b.setPreferredSize(new Dimension(30, 30));
b.addActionListener(btnListener);
b.setFocusPainted(false);
b.setBackground(new Color(255, 255, 255));
this.add(b);
}
brushButton.setBackground(new Color(200, 200, 200));
} catch (Exception ex) {
System.out.println("Exception: " + ex.getMessage());
}
}
|
diff --git a/liquibase.eclipse.plugin/src/liquibase/eclipse/plugin/controller/ReleaseJob.java b/liquibase.eclipse.plugin/src/liquibase/eclipse/plugin/controller/ReleaseJob.java
index 8422492..918e413 100644
--- a/liquibase.eclipse.plugin/src/liquibase/eclipse/plugin/controller/ReleaseJob.java
+++ b/liquibase.eclipse.plugin/src/liquibase/eclipse/plugin/controller/ReleaseJob.java
@@ -1,108 +1,111 @@
package liquibase.eclipse.plugin.controller;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import liquibase.Liquibase;
import liquibase.eclipse.plugin.model.ChangeSet;
import liquibase.eclipse.plugin.model.ChangeSetContentProvider;
import liquibase.eclipse.plugin.model.ChangeSetStatus;
import liquibase.eclipse.plugin.model.DatabaseConfiguration;
import liquibase.exception.LiquibaseException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
/**
* Handles the multiple threads started by a liquibase release.
*
* @author afinke
*
*/
public class ReleaseJob extends Job {
private Liquibase liquibase;
private DatabaseConfiguration databaseConfiguration;
private Button releaseButton;
private Shell shell;
public ReleaseJob(String name,
DatabaseConfiguration databaseConfiguration,
Liquibase liquibase,
Button releaseButton,
Shell shell) {
super(name);
this.liquibase = liquibase;
this.databaseConfiguration = databaseConfiguration;
this.releaseButton = releaseButton;
this.shell = shell;
}
@Override
protected IStatus run(IProgressMonitor progressMonitor) {
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
// disable release button to avoid multiple releases
releaseButton.setEnabled(false);
}
});
ExecutorService executor = Executors.newCachedThreadPool();
DatabaseChangelogPoller databaseChangelogPoller =
new DatabaseChangelogPoller(databaseConfiguration);
// start polling 'databasechangelog'
executor.execute(databaseChangelogPoller);
// start updating the database
try {
liquibase.update(null);
} catch (LiquibaseException e) {
databaseChangelogPoller.stop();
executor.shutdown();
+ String errorMessage = e.getMessage();
+ // changelog path, id, author
+ String[] splittedErrorMessage = errorMessage.split("::");
List<ChangeSet> changeSets = ChangeSetContentProvider.getInstance().getChangeSets();
for (ChangeSet changeSet : changeSets) {
- if(changeSet.getStatus().equals(ChangeSetStatus.RUNNING)) {
+ if(changeSet.getId().equals(splittedErrorMessage[1])) {
changeSet.setStatus(ChangeSetStatus.ERROR);
break;
}
}
reportError(e.getMessage());
return Status.CANCEL_STATUS;
}
databaseChangelogPoller.stop();
executor.shutdown();
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
// enable release button after everything finished
releaseButton.setEnabled(true);
}
});
reportSuccess();
return Status.OK_STATUS;
}
private void reportSuccess() {
Display.getDefault().asyncExec(new Runnable() {
public void run() {
MessageDialog.openInformation(shell, "Success", "Database updates were successfull.");
}
});
}
private void reportError(final String error) {
Display.getDefault().asyncExec(new Runnable() {
public void run() {
MessageDialog.openError(shell, "Error", error);
}
});
}
}
| false | true | protected IStatus run(IProgressMonitor progressMonitor) {
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
// disable release button to avoid multiple releases
releaseButton.setEnabled(false);
}
});
ExecutorService executor = Executors.newCachedThreadPool();
DatabaseChangelogPoller databaseChangelogPoller =
new DatabaseChangelogPoller(databaseConfiguration);
// start polling 'databasechangelog'
executor.execute(databaseChangelogPoller);
// start updating the database
try {
liquibase.update(null);
} catch (LiquibaseException e) {
databaseChangelogPoller.stop();
executor.shutdown();
List<ChangeSet> changeSets = ChangeSetContentProvider.getInstance().getChangeSets();
for (ChangeSet changeSet : changeSets) {
if(changeSet.getStatus().equals(ChangeSetStatus.RUNNING)) {
changeSet.setStatus(ChangeSetStatus.ERROR);
break;
}
}
reportError(e.getMessage());
return Status.CANCEL_STATUS;
}
databaseChangelogPoller.stop();
executor.shutdown();
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
// enable release button after everything finished
releaseButton.setEnabled(true);
}
});
reportSuccess();
return Status.OK_STATUS;
}
| protected IStatus run(IProgressMonitor progressMonitor) {
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
// disable release button to avoid multiple releases
releaseButton.setEnabled(false);
}
});
ExecutorService executor = Executors.newCachedThreadPool();
DatabaseChangelogPoller databaseChangelogPoller =
new DatabaseChangelogPoller(databaseConfiguration);
// start polling 'databasechangelog'
executor.execute(databaseChangelogPoller);
// start updating the database
try {
liquibase.update(null);
} catch (LiquibaseException e) {
databaseChangelogPoller.stop();
executor.shutdown();
String errorMessage = e.getMessage();
// changelog path, id, author
String[] splittedErrorMessage = errorMessage.split("::");
List<ChangeSet> changeSets = ChangeSetContentProvider.getInstance().getChangeSets();
for (ChangeSet changeSet : changeSets) {
if(changeSet.getId().equals(splittedErrorMessage[1])) {
changeSet.setStatus(ChangeSetStatus.ERROR);
break;
}
}
reportError(e.getMessage());
return Status.CANCEL_STATUS;
}
databaseChangelogPoller.stop();
executor.shutdown();
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
// enable release button after everything finished
releaseButton.setEnabled(true);
}
});
reportSuccess();
return Status.OK_STATUS;
}
|
diff --git a/src/main/java/org/jvnet/hudson/plugins/VariableReplacerUtil.java b/src/main/java/org/jvnet/hudson/plugins/VariableReplacerUtil.java
index a5c4729..b900414 100644
--- a/src/main/java/org/jvnet/hudson/plugins/VariableReplacerUtil.java
+++ b/src/main/java/org/jvnet/hudson/plugins/VariableReplacerUtil.java
@@ -1,21 +1,21 @@
package org.jvnet.hudson.plugins;
import java.util.Map;
public class VariableReplacerUtil {
public static String replace(String originalCommand, Map<String, String> vars) {
if(originalCommand == null){
return null;
}
vars.remove("_"); //why _ as key for build tool?
StringBuilder sb = new StringBuilder();
for (String variable : vars.keySet()) {
if (originalCommand.contains(variable) ) {
- sb.append("export " + variable + "=\"" + vars.get(variable) + "\"\n");
+ sb.append(variable + "=\"" + vars.get(variable) + "\"\n");
}
}
sb.append("\n");
sb.append(originalCommand);
return sb.toString();
}
}
| true | true | public static String replace(String originalCommand, Map<String, String> vars) {
if(originalCommand == null){
return null;
}
vars.remove("_"); //why _ as key for build tool?
StringBuilder sb = new StringBuilder();
for (String variable : vars.keySet()) {
if (originalCommand.contains(variable) ) {
sb.append("export " + variable + "=\"" + vars.get(variable) + "\"\n");
}
}
sb.append("\n");
sb.append(originalCommand);
return sb.toString();
}
| public static String replace(String originalCommand, Map<String, String> vars) {
if(originalCommand == null){
return null;
}
vars.remove("_"); //why _ as key for build tool?
StringBuilder sb = new StringBuilder();
for (String variable : vars.keySet()) {
if (originalCommand.contains(variable) ) {
sb.append(variable + "=\"" + vars.get(variable) + "\"\n");
}
}
sb.append("\n");
sb.append(originalCommand);
return sb.toString();
}
|
diff --git a/jOOQ/src/main/java/org/jooq/impl/LoaderImpl.java b/jOOQ/src/main/java/org/jooq/impl/LoaderImpl.java
index 252e27386..16edbc83b 100644
--- a/jOOQ/src/main/java/org/jooq/impl/LoaderImpl.java
+++ b/jOOQ/src/main/java/org/jooq/impl/LoaderImpl.java
@@ -1,567 +1,567 @@
/**
* Copyright (c) 2009-2013, Data Geekery GmbH (http://www.datageekery.com)
* All rights reserved.
*
* This work is dual-licensed
* - under the Apache Software License 2.0 (the "ASL")
* - under the jOOQ License and Maintenance Agreement (the "jOOQ License")
* =============================================================================
* You may choose which license applies to you:
*
* - If you're using this work with Open Source databases, you may choose
* either ASL or jOOQ License.
* - If you're using this work with at least one commercial database, you must
* choose jOOQ License
*
* For more information, please visit http://www.jooq.org/licenses
*
* Apache Software License 2.0:
* -----------------------------------------------------------------------------
* 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.
*
* jOOQ License and Maintenance Agreement:
* -----------------------------------------------------------------------------
* Data Geekery grants the Customer the non-exclusive, timely limited and
* non-transferable license to install and use the Software under the terms of
* the jOOQ License and Maintenance Agreement.
*
* This library is distributed with a LIMITED WARRANTY. See the jOOQ License
* and Maintenance Agreement for more details: http://www.jooq.org/licensing
*/
package org.jooq.impl;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import org.jooq.Condition;
import org.jooq.Configuration;
import org.jooq.DSLContext;
import org.jooq.Field;
import org.jooq.InsertQuery;
import org.jooq.Loader;
import org.jooq.LoaderCSVOptionsStep;
import org.jooq.LoaderCSVStep;
import org.jooq.LoaderError;
import org.jooq.LoaderJSONOptionsStep;
import org.jooq.LoaderJSONStep;
import org.jooq.LoaderOptionsStep;
import org.jooq.LoaderXMLStep;
import org.jooq.SelectQuery;
import org.jooq.Table;
import org.jooq.TableRecord;
import org.jooq.exception.DataAccessException;
import org.jooq.tools.StringUtils;
import org.jooq.tools.csv.CSVParser;
import org.jooq.tools.csv.CSVReader;
import org.xml.sax.InputSource;
/**
* @author Lukas Eder
* @author Johannes Bühler
*/
class LoaderImpl<R extends TableRecord<R>> implements
// Cascading interface implementations for Loader behaviour
LoaderOptionsStep<R>,
LoaderXMLStep<R>,
LoaderCSVStep<R>,
LoaderCSVOptionsStep<R>,
LoaderJSONStep<R>,
LoaderJSONOptionsStep<R>,
Loader<R> {
// Configuration constants
// -----------------------
private static final int ON_DUPLICATE_KEY_ERROR = 0;
private static final int ON_DUPLICATE_KEY_IGNORE = 1;
private static final int ON_DUPLICATE_KEY_UPDATE = 2;
private static final int ON_ERROR_ABORT = 0;
private static final int ON_ERROR_IGNORE = 1;
private static final int COMMIT_NONE = 0;
private static final int COMMIT_AFTER = 1;
private static final int COMMIT_ALL = 2;
private static final int CONTENT_CSV = 0;
private static final int CONTENT_XML = 1;
private static final int CONTENT_JSON = 2;
// Configuration data
// ------------------
private final DSLContext create;
private final Configuration configuration;
private final Table<R> table;
private int onDuplicate = ON_DUPLICATE_KEY_ERROR;
private int onError = ON_ERROR_ABORT;
private int commit = COMMIT_NONE;
private int commitAfter = 1;
private int content = CONTENT_CSV;
private BufferedReader data;
// CSV configuration data
// ----------------------
private int ignoreRows = 1;
private char quote = CSVParser.DEFAULT_QUOTE_CHARACTER;
private char separator = CSVParser.DEFAULT_SEPARATOR;
private String nullString = null;
private Field<?>[] fields;
private boolean[] primaryKey;
// Result data
// -----------
private int ignored;
private int processed;
private int stored;
private final List<LoaderError> errors;
LoaderImpl(Configuration configuration, Table<R> table) {
this.create = DSL.using(configuration);
this.configuration = configuration;
this.table = table;
this.errors = new ArrayList<LoaderError>();
}
// -------------------------------------------------------------------------
// Configuration setup
// -------------------------------------------------------------------------
@Override
public final LoaderImpl<R> onDuplicateKeyError() {
onDuplicate = ON_DUPLICATE_KEY_ERROR;
return this;
}
@Override
public final LoaderImpl<R> onDuplicateKeyIgnore() {
if (table.getPrimaryKey() == null) {
throw new IllegalStateException("ON DUPLICATE KEY IGNORE only works on tables with explicit primary keys. Table is not updatable : " + table);
}
onDuplicate = ON_DUPLICATE_KEY_IGNORE;
return this;
}
@Override
public final LoaderImpl<R> onDuplicateKeyUpdate() {
if (table.getPrimaryKey() == null) {
throw new IllegalStateException("ON DUPLICATE KEY UPDATE only works on tables with explicit primary keys. Table is not updatable : " + table);
}
onDuplicate = ON_DUPLICATE_KEY_UPDATE;
return this;
}
@Override
public final LoaderImpl<R> onErrorIgnore() {
onError = ON_ERROR_IGNORE;
return this;
}
@Override
public final LoaderImpl<R> onErrorAbort() {
onError = ON_ERROR_ABORT;
return this;
}
@Override
public final LoaderImpl<R> commitEach() {
commit = COMMIT_AFTER;
return this;
}
@Override
public final LoaderImpl<R> commitAfter(int number) {
commit = COMMIT_AFTER;
commitAfter = number;
return this;
}
@Override
public final LoaderImpl<R> commitAll() {
commit = COMMIT_ALL;
return this;
}
@Override
public final LoaderImpl<R> commitNone() {
commit = COMMIT_NONE;
return this;
}
@Override
public final LoaderImpl<R> loadCSV(File file) throws FileNotFoundException {
content = CONTENT_CSV;
data = new BufferedReader(new FileReader(file));
return this;
}
@Override
public final LoaderImpl<R> loadCSV(String csv) {
content = CONTENT_CSV;
data = new BufferedReader(new StringReader(csv));
return this;
}
@Override
public final LoaderImpl<R> loadCSV(InputStream stream) {
content = CONTENT_CSV;
data = new BufferedReader(new InputStreamReader(stream));
return this;
}
@Override
public final LoaderImpl<R> loadCSV(Reader reader) {
content = CONTENT_CSV;
data = new BufferedReader(reader);
return this;
}
@Override
public final LoaderImpl<R> loadXML(File file) throws FileNotFoundException {
content = CONTENT_XML;
throw new UnsupportedOperationException("This is not yet implemented");
}
@Override
public final LoaderImpl<R> loadXML(String xml) {
content = CONTENT_XML;
throw new UnsupportedOperationException("This is not yet implemented");
}
@Override
public final LoaderImpl<R> loadXML(InputStream stream) {
content = CONTENT_XML;
throw new UnsupportedOperationException("This is not yet implemented");
}
@Override
public final LoaderImpl<R> loadXML(Reader reader) {
content = CONTENT_XML;
throw new UnsupportedOperationException("This is not yet implemented");
}
@Override
public final LoaderImpl<R> loadXML(InputSource source) {
content = CONTENT_XML;
throw new UnsupportedOperationException("This is not yet implemented");
}
// -------------------------------------------------------------------------
// CSV configuration
// -------------------------------------------------------------------------
@Override
public final LoaderImpl<R> fields(Field<?>... f) {
this.fields = f;
this.primaryKey = new boolean[f.length];
if (table.getPrimaryKey() != null) {
for (int i = 0; i < fields.length; i++) {
if (fields[i] != null) {
if (table.getPrimaryKey().getFields().contains(fields[i])) {
primaryKey[i] = true;
}
}
}
}
return this;
}
@Override
public final LoaderImpl<R> fields(Collection<? extends Field<?>> f) {
return fields(f.toArray(new Field[f.size()]));
}
@Override
public final LoaderImpl<R> ignoreRows(int number) {
ignoreRows = number;
return this;
}
@Override
public final LoaderImpl<R> quote(char q) {
this.quote = q;
return this;
}
@Override
public final LoaderImpl<R> separator(char s) {
this.separator = s;
return this;
}
@Override
public final LoaderImpl<R> nullString(String n) {
this.nullString = n;
return this;
}
@Override
public final LoaderJSONStep<R> loadJSON(File file) throws FileNotFoundException {
content = CONTENT_JSON;
data = new BufferedReader(new FileReader(file));
return this;
}
@Override
public final LoaderJSONStep<R> loadJSON(String json) {
content = CONTENT_JSON;
data = new BufferedReader(new StringReader(json));
return this;
}
@Override
public final LoaderJSONStep<R> loadJSON(InputStream stream) {
content = CONTENT_JSON;
data = new BufferedReader(new InputStreamReader(stream));
return this;
}
@Override
public final LoaderJSONStep<R> loadJSON(Reader reader) {
content = CONTENT_JSON;
data = new BufferedReader(reader);
return this;
}
// -------------------------------------------------------------------------
// XML configuration
// -------------------------------------------------------------------------
// [...] to be specified
// -------------------------------------------------------------------------
// Execution
// -------------------------------------------------------------------------
@Override
public final LoaderImpl<R> execute() throws IOException {
if (content == CONTENT_CSV) {
executeCSV();
}
else if (content == CONTENT_XML) {
throw new UnsupportedOperationException();
}
else if (content == CONTENT_JSON) {
executeJSON();
}
else {
throw new IllegalStateException();
}
return this;
}
private void executeJSON() throws IOException {
JSONReader reader = new JSONReader(data);
try {
// The current json format is not designed for streaming. Thats why
// all records are loaded at once.
List<String[]> allRecords = reader.readAll();
executeSQL(allRecords.iterator());
}
// SQLExceptions originating from rollbacks or commits are always fatal
// They are propagated, and not swallowed
catch (SQLException e) {
throw Utils.translate(null, e);
}
finally {
reader.close();
}
}
private final void executeCSV() throws IOException {
CSVReader reader = new CSVReader(data, separator, quote, ignoreRows);
try {
executeSQL(reader);
}
// SQLExceptions originating from rollbacks or commits are always fatal
// They are propagated, and not swallowed
catch (SQLException e) {
throw Utils.translate(null, e);
}
finally {
reader.close();
}
}
- private void executeSQL(Iterator<String[]> reader) throws IOException, SQLException {
+ private void executeSQL(Iterator<String[]> reader) throws SQLException {
String[] row;
// TODO: When running in COMMIT_AFTER > 1 or COMMIT_ALL mode, then
// it might be better to bulk load / merge n records
rowloop: while (reader.hasNext() && ((row = reader.next()) != null)) {
// [#1627] Handle NULL values
for (int i = 0; i < row.length; i++) {
if (StringUtils.equals(nullString, row[i])) {
row[i] = null;
}
}
processed++;
InsertQuery<R> insert = create.insertQuery(table);
for (int i = 0; i < row.length; i++) {
if (i < fields.length && fields[i] != null) {
addValue0(insert, fields[i], row[i]);
}
}
// TODO: This is only supported by some dialects. Let other
// dialects execute a SELECT and then either an INSERT or UPDATE
if (onDuplicate == ON_DUPLICATE_KEY_UPDATE) {
insert.onDuplicateKeyUpdate(true);
for (int i = 0; i < row.length; i++) {
if (i < fields.length && fields[i] != null && !primaryKey[i]) {
addValueForUpdate0(insert, fields[i], row[i]);
}
}
}
// TODO: This can be implemented faster using a MERGE statement
// in some dialects
else if (onDuplicate == ON_DUPLICATE_KEY_IGNORE) {
SelectQuery<R> select = create.selectQuery(table);
for (int i = 0; i < row.length; i++) {
if (i < fields.length && primaryKey[i]) {
select.addConditions(getCondition(fields[i], row[i]));
}
}
try {
if (select.execute() > 0) {
ignored++;
continue rowloop;
}
}
catch (DataAccessException e) {
errors.add(new LoaderErrorImpl(e, row, processed - 1, select));
}
}
// Don't do anything. Let the execution fail
else if (onDuplicate == ON_DUPLICATE_KEY_ERROR) {}
try {
insert.execute();
stored++;
if (commit == COMMIT_AFTER) {
if (processed % commitAfter == 0) {
configuration.connectionProvider().acquire().commit();
}
}
}
catch (DataAccessException e) {
errors.add(new LoaderErrorImpl(e, row, processed - 1, insert));
ignored++;
if (onError == ON_ERROR_ABORT) {
break rowloop;
}
}
}
// Rollback on errors in COMMIT_ALL mode
try {
if (commit == COMMIT_ALL) {
if (!errors.isEmpty()) {
stored = 0;
configuration.connectionProvider().acquire().rollback();
}
else {
configuration.connectionProvider().acquire().commit();
}
}
// Commit remaining elements in COMMIT_AFTER mode
else if (commit == COMMIT_AFTER) {
if (processed % commitAfter != 0) {
configuration.connectionProvider().acquire().commit();
}
}
}
catch (DataAccessException e) {
errors.add(new LoaderErrorImpl(e, null, processed - 1, null));
}
}
/**
* Type-safety...
*/
private <T> void addValue0(InsertQuery<R> insert, Field<T> field, String row) {
insert.addValue(field, field.getDataType().convert(row));
}
/**
* Type-safety...
*/
private <T> void addValueForUpdate0(InsertQuery<R> insert, Field<T> field, String row) {
insert.addValueForUpdate(field, field.getDataType().convert(row));
}
/**
* Get a type-safe condition
*/
private <T> Condition getCondition(Field<T> field, String string) {
return field.equal(field.getDataType().convert(string));
}
// -------------------------------------------------------------------------
// Outcome
// -------------------------------------------------------------------------
@Override
public final List<LoaderError> errors() {
return errors;
}
@Override
public final int processed() {
return processed;
}
@Override
public final int ignored() {
return ignored;
}
@Override
public final int stored() {
return stored;
}
}
| true | true | private void executeSQL(Iterator<String[]> reader) throws IOException, SQLException {
String[] row;
// TODO: When running in COMMIT_AFTER > 1 or COMMIT_ALL mode, then
// it might be better to bulk load / merge n records
rowloop: while (reader.hasNext() && ((row = reader.next()) != null)) {
// [#1627] Handle NULL values
for (int i = 0; i < row.length; i++) {
if (StringUtils.equals(nullString, row[i])) {
row[i] = null;
}
}
processed++;
InsertQuery<R> insert = create.insertQuery(table);
for (int i = 0; i < row.length; i++) {
if (i < fields.length && fields[i] != null) {
addValue0(insert, fields[i], row[i]);
}
}
// TODO: This is only supported by some dialects. Let other
// dialects execute a SELECT and then either an INSERT or UPDATE
if (onDuplicate == ON_DUPLICATE_KEY_UPDATE) {
insert.onDuplicateKeyUpdate(true);
for (int i = 0; i < row.length; i++) {
if (i < fields.length && fields[i] != null && !primaryKey[i]) {
addValueForUpdate0(insert, fields[i], row[i]);
}
}
}
// TODO: This can be implemented faster using a MERGE statement
// in some dialects
else if (onDuplicate == ON_DUPLICATE_KEY_IGNORE) {
SelectQuery<R> select = create.selectQuery(table);
for (int i = 0; i < row.length; i++) {
if (i < fields.length && primaryKey[i]) {
select.addConditions(getCondition(fields[i], row[i]));
}
}
try {
if (select.execute() > 0) {
ignored++;
continue rowloop;
}
}
catch (DataAccessException e) {
errors.add(new LoaderErrorImpl(e, row, processed - 1, select));
}
}
// Don't do anything. Let the execution fail
else if (onDuplicate == ON_DUPLICATE_KEY_ERROR) {}
try {
insert.execute();
stored++;
if (commit == COMMIT_AFTER) {
if (processed % commitAfter == 0) {
configuration.connectionProvider().acquire().commit();
}
}
}
catch (DataAccessException e) {
errors.add(new LoaderErrorImpl(e, row, processed - 1, insert));
ignored++;
if (onError == ON_ERROR_ABORT) {
break rowloop;
}
}
}
// Rollback on errors in COMMIT_ALL mode
try {
if (commit == COMMIT_ALL) {
if (!errors.isEmpty()) {
stored = 0;
configuration.connectionProvider().acquire().rollback();
}
else {
configuration.connectionProvider().acquire().commit();
}
}
// Commit remaining elements in COMMIT_AFTER mode
else if (commit == COMMIT_AFTER) {
if (processed % commitAfter != 0) {
configuration.connectionProvider().acquire().commit();
}
}
}
catch (DataAccessException e) {
errors.add(new LoaderErrorImpl(e, null, processed - 1, null));
}
}
| private void executeSQL(Iterator<String[]> reader) throws SQLException {
String[] row;
// TODO: When running in COMMIT_AFTER > 1 or COMMIT_ALL mode, then
// it might be better to bulk load / merge n records
rowloop: while (reader.hasNext() && ((row = reader.next()) != null)) {
// [#1627] Handle NULL values
for (int i = 0; i < row.length; i++) {
if (StringUtils.equals(nullString, row[i])) {
row[i] = null;
}
}
processed++;
InsertQuery<R> insert = create.insertQuery(table);
for (int i = 0; i < row.length; i++) {
if (i < fields.length && fields[i] != null) {
addValue0(insert, fields[i], row[i]);
}
}
// TODO: This is only supported by some dialects. Let other
// dialects execute a SELECT and then either an INSERT or UPDATE
if (onDuplicate == ON_DUPLICATE_KEY_UPDATE) {
insert.onDuplicateKeyUpdate(true);
for (int i = 0; i < row.length; i++) {
if (i < fields.length && fields[i] != null && !primaryKey[i]) {
addValueForUpdate0(insert, fields[i], row[i]);
}
}
}
// TODO: This can be implemented faster using a MERGE statement
// in some dialects
else if (onDuplicate == ON_DUPLICATE_KEY_IGNORE) {
SelectQuery<R> select = create.selectQuery(table);
for (int i = 0; i < row.length; i++) {
if (i < fields.length && primaryKey[i]) {
select.addConditions(getCondition(fields[i], row[i]));
}
}
try {
if (select.execute() > 0) {
ignored++;
continue rowloop;
}
}
catch (DataAccessException e) {
errors.add(new LoaderErrorImpl(e, row, processed - 1, select));
}
}
// Don't do anything. Let the execution fail
else if (onDuplicate == ON_DUPLICATE_KEY_ERROR) {}
try {
insert.execute();
stored++;
if (commit == COMMIT_AFTER) {
if (processed % commitAfter == 0) {
configuration.connectionProvider().acquire().commit();
}
}
}
catch (DataAccessException e) {
errors.add(new LoaderErrorImpl(e, row, processed - 1, insert));
ignored++;
if (onError == ON_ERROR_ABORT) {
break rowloop;
}
}
}
// Rollback on errors in COMMIT_ALL mode
try {
if (commit == COMMIT_ALL) {
if (!errors.isEmpty()) {
stored = 0;
configuration.connectionProvider().acquire().rollback();
}
else {
configuration.connectionProvider().acquire().commit();
}
}
// Commit remaining elements in COMMIT_AFTER mode
else if (commit == COMMIT_AFTER) {
if (processed % commitAfter != 0) {
configuration.connectionProvider().acquire().commit();
}
}
}
catch (DataAccessException e) {
errors.add(new LoaderErrorImpl(e, null, processed - 1, null));
}
}
|
diff --git a/src/soot/baf/JasminClass.java b/src/soot/baf/JasminClass.java
index 1d4b739a..61332b49 100644
--- a/src/soot/baf/JasminClass.java
+++ b/src/soot/baf/JasminClass.java
@@ -1,2242 +1,2242 @@
/* Soot - a J*va Optimization Framework
* Copyright (C) 1999 Patrick Lam, Patrick Pominville and Raja Vallee-Rai
*
* 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.
*/
/*
* Modified by the Sable Research Group and others 1997-1999.
* See the 'credits' file distributed with Soot for the complete list of
* contributors. (Soot is distributed at http://www.sable.mcgill.ca/soot)
*/
package soot.baf;
import soot.options.*;
import soot.tagkit.*;
import soot.*;
import soot.jimple.*;
import soot.toolkits.graph.*;
import soot.util.*;
import java.util.*;
import java.io.*;
public class JasminClass
{
Map instToLabel;
Map localToSlot;
Map subroutineToReturnAddressSlot;
List code;
boolean isEmittingMethodCode;
int labelCount;
boolean isNextGotoAJsr;
int returnAddressSlot;
int currentStackHeight = 0;
int maxStackHeight = 0;
Map localToGroup;
Map groupToColorCount;
Map localToColor;
Map blockToStackHeight = new HashMap(); // maps a block to the stack height upon entering it
Map blockToLogicalStackHeight = new HashMap(); // maps a block to the logical stack height upon entering it
String slashify(String s)
{
return s.replace('.', '/');
}
public static int sizeOfType(Type t)
{
if(t instanceof DoubleWordType || t instanceof LongType || t instanceof DoubleType)
return 2;
else if(t instanceof VoidType)
return 0;
else
return 1;
}
int argCountOf(SootMethod m)
{
int argCount = 0;
Iterator typeIt = m.getParameterTypes().iterator();
while(typeIt.hasNext())
{
Type t = (Type) typeIt.next();
argCount += sizeOfType(t);
}
return argCount;
}
String jasminDescriptorOf(Type type)
{
TypeSwitch sw;
type.apply(sw = new TypeSwitch()
{
public void caseBooleanType(BooleanType t)
{
setResult("Z");
}
public void caseByteType(ByteType t)
{
setResult("B");
}
public void caseCharType(CharType t)
{
setResult("C");
}
public void caseDoubleType(DoubleType t)
{
setResult("D");
}
public void caseFloatType(FloatType t)
{
setResult("F");
}
public void caseIntType(IntType t)
{
setResult("I");
}
public void caseLongType(LongType t)
{
setResult("J");
}
public void caseShortType(ShortType t)
{
setResult("S");
}
public void defaultCase(Type t)
{
throw new RuntimeException("Invalid type: " + t);
}
public void caseArrayType(ArrayType t)
{
StringBuffer buffer = new StringBuffer();
for(int i = 0; i < t.numDimensions; i++)
buffer.append("[");
setResult(buffer.toString() + jasminDescriptorOf(t.baseType));
}
public void caseRefType(RefType t)
{
setResult("L" + t.getClassName().replace('.', '/') + ";");
}
public void caseVoidType(VoidType t)
{
setResult("V");
}
});
return (String) sw.getResult();
}
String jasminDescriptorOf(SootMethod m)
{
StringBuffer buffer = new StringBuffer();
buffer.append("(");
// Add methods parameters
{
Iterator typeIt = m.getParameterTypes().iterator();
while(typeIt.hasNext())
{
Type t = (Type) typeIt.next();
buffer.append(jasminDescriptorOf(t));
}
}
buffer.append(")");
buffer.append(jasminDescriptorOf(m.getReturnType()));
return buffer.toString();
}
void emit(String s)
{
okayEmit(s);
}
void okayEmit(String s)
{
if(isEmittingMethodCode && !s.endsWith(":"))
code.add(" " + s);
else
code.add(s);
}
public JasminClass(SootClass sootClass)
{
if(Options.v().time())
Timers.v().buildJasminTimer.start();
if(Options.v().verbose())
G.v().out.println("[" + sootClass.getName() + "] Constructing baf.JasminClass...");
code = new LinkedList();
// Emit the header
{
int modifiers = sootClass.getModifiers();
if(Modifier.isInterface(modifiers))
{
modifiers -= Modifier.INTERFACE;
emit(".interface " + Modifier.toString(modifiers) + " " + slashify(sootClass.getName()));
}
else
emit(".class " + Modifier.toString(modifiers) + " " + slashify(sootClass.getName()));
if(sootClass.hasSuperclass())
emit(".super " + slashify(sootClass.getSuperclass().getName()));
else
emit(".super " + slashify(sootClass.getName()));
emit("");
}
// Emit the interfaces
{
Iterator interfaceIt = sootClass.getInterfaces().iterator();
while(interfaceIt.hasNext())
{
SootClass inter = (SootClass) interfaceIt.next();
emit(".implements " + slashify(inter.getName()));
}
if(sootClass.getInterfaceCount() != 0)
emit("");
}
// emit class attributes.
Iterator it = sootClass.getTags().iterator();
while(it.hasNext()) {
Tag tag = (Tag) it.next();
if(tag instanceof Attribute)
emit(".class_attribute " + tag.getName() + " \"" + new String(Base64.encode(((Attribute)tag).getValue()))+"\"");
}
// Emit the fields
{
Iterator fieldIt = sootClass.getFields().iterator();
while(fieldIt.hasNext())
{
SootField field = (SootField) fieldIt.next();
emit(".field " + Modifier.toString(field.getModifiers()) + " " +
"\"" + field.getName() + "\"" + " " + jasminDescriptorOf(field.getType()));
Iterator attributeIt = field.getTags().iterator();
while(attributeIt.hasNext()) {
Tag tag = (Tag) attributeIt.next();
if(tag instanceof Attribute)
emit(".field_attribute " + tag.getName() + " \"" + new String(Base64.encode(((Attribute)tag).getValue())) +"\"");
}
}
if(sootClass.getFieldCount() != 0)
emit("");
}
// Emit the methods
{
Iterator methodIt = sootClass.methodIterator();
while(methodIt.hasNext())
{
emitMethod((SootMethod) methodIt.next());
emit("");
}
}
if(Options.v().time())
Timers.v().buildJasminTimer.end();
}
void assignColorsToLocals(BafBody body)
{
if(Options.v().verbose())
G.v().out.println("[" + body.getMethod().getName() +
"] Assigning colors to locals...");
if(Options.v().time())
Timers.v().packTimer.start();
localToGroup = new HashMap(body.getLocalCount() * 2 + 1, 0.7f);
groupToColorCount = new HashMap(body.getLocalCount() * 2 + 1, 0.7f);
localToColor = new HashMap(body.getLocalCount() * 2 + 1, 0.7f);
// Assign each local to a group, and set that group's color count to 0.
{
Iterator localIt = body.getLocals().iterator();
while(localIt.hasNext())
{
Local l = (Local) localIt.next();
Object g;
if(sizeOfType(l.getType()) == 1)
g = IntType.v();
else
g = LongType.v();
localToGroup.put(l, g);
if(!groupToColorCount.containsKey(g))
{
groupToColorCount.put(g, new Integer(0));
}
}
}
// Assign colors to the parameter locals.
{
Iterator codeIt = body.getUnits().iterator();
while(codeIt.hasNext())
{
Stmt s = (Stmt) codeIt.next();
if(s instanceof IdentityStmt &&
((IdentityStmt) s).getLeftOp() instanceof Local)
{
Local l = (Local) ((IdentityStmt) s).getLeftOp();
Object group = localToGroup.get(l);
int count = ((Integer) groupToColorCount.get(group)).intValue();
localToColor.put(l, new Integer(count));
count++;
groupToColorCount.put(group, new Integer(count));
}
}
}
// Call the graph colorer.
// FastColorer.assignColorsToLocals(body, localToGroup,
// localToColor, groupToColorCount);
if(Options.v().time())
Timers.v().packTimer.end();
}
void emitMethod(SootMethod method)
{
if (method.isPhantom())
return;
// Emit prologue
emit(".method " + Modifier.toString(method.getModifiers()) + " " +
method.getName() + jasminDescriptorOf(method));
if(method.isConcrete())
{
if(!method.hasActiveBody())
throw new RuntimeException("method: " + method.getName() + " has no active body!");
else
emitMethodBody(method);
}
// Emit epilogue
emit(".end method");
Iterator it = method.getTags().iterator();
while(it.hasNext()) {
Tag tag = (Tag) it.next();
if(tag instanceof Attribute)
emit(".method_attribute " + tag.getName() + " \"" + new String(Base64.encode(tag.getValue())) +"\"");
}
}
void emitMethodBody(SootMethod method)
{
if(Options.v().time())
Timers.v().buildJasminTimer.end();
Body activeBody = method.getActiveBody();
if(!(activeBody instanceof BafBody))
throw new RuntimeException("method: " + method.getName() + " has an invalid active body!");
BafBody body = (BafBody) activeBody;
if(body == null)
throw new RuntimeException("method: " + method.getName() + " has no active body!");
if(Options.v().time())
Timers.v().buildJasminTimer.start();
Chain instList = body.getUnits();
int stackLimitIndex = -1;
subroutineToReturnAddressSlot = new HashMap(10, 0.7f);
// Determine the instToLabel map
{
Iterator boxIt = body.getUnitBoxes(true).iterator();
instToLabel = new HashMap(instList.size() * 2 + 1, 0.7f);
labelCount = 0;
while(boxIt.hasNext())
{
// Assign a label for each statement reference
{
InstBox box = (InstBox) boxIt.next();
if(!instToLabel.containsKey(box.getUnit()))
instToLabel.put(box.getUnit(), "label" + labelCount++);
}
}
}
// Emit the exceptions, recording the Units at the beginning
// of handlers so that later on we can recognize blocks that
// begin with an exception on the stack.
Set handlerUnits = new ArraySet(body.getTraps().size());
{
Iterator trapIt = body.getTraps().iterator();
while(trapIt.hasNext())
{
Trap trap = (Trap) trapIt.next();
if(trap.getBeginUnit() != trap.getEndUnit()) {
emit(".catch " + slashify(trap.getException().getName()) + " from " +
instToLabel.get(trap.getBeginUnit()) + " to " + instToLabel.get(trap.getEndUnit()) +
" using " + instToLabel.get(trap.getHandlerUnit()));
handlerUnits.add(trap.getHandlerUnit());
}
}
}
// Determine where the locals go
{
int localCount = 0;
int[] paramSlots = new int[method.getParameterCount()];
int thisSlot = 0;
Set assignedLocals = new HashSet();
Map groupColorPairToSlot = new HashMap(body.getLocalCount() * 2 + 1, 0.7f);
localToSlot = new HashMap(body.getLocalCount() * 2 + 1, 0.7f);
//assignColorsToLocals(body);
// Determine slots for 'this' and parameters
{
List paramTypes = method.getParameterTypes();
if(!method.isStatic())
{
thisSlot = 0;
localCount++;
}
for(int i = 0; i < paramTypes.size(); i++)
{
paramSlots[i] = localCount;
localCount += sizeOfType((Type) paramTypes.get(i));
}
}
// Handle identity statements
{
Iterator instIt = instList.iterator();
while(instIt.hasNext())
{
Inst s = (Inst) instIt.next();
if(s instanceof IdentityInst && ((IdentityInst) s).getLeftOp() instanceof Local)
{
Local l = (Local) ((IdentityInst) s).getLeftOp();
IdentityRef identity = (IdentityRef) ((IdentityInst) s).getRightOp();
int slot = 0;
if(identity instanceof ThisRef)
{
if(method.isStatic())
throw new RuntimeException("Attempting to use 'this' in static method");
slot = thisSlot;
}
else if(identity instanceof ParameterRef)
slot = paramSlots[((ParameterRef) identity).getIndex()];
else {
// Exception ref. Skip over this
continue;
}
localToSlot.put(l, new Integer(slot));
assignedLocals.add(l);
}
}
}
// Assign the rest of the locals
{
Iterator localIt = body.getLocals().iterator();
while(localIt.hasNext())
{
Local local = (Local) localIt.next();
if(!assignedLocals.contains(local))
{
localToSlot.put(local, new Integer(localCount));
localCount += sizeOfType((Type)local.getType());
assignedLocals.add(local);
}
}
if (!Modifier.isNative(method.getModifiers())
&& !Modifier.isAbstract(method.getModifiers()))
{
emit(" .limit stack ?");
stackLimitIndex = code.size() - 1;
emit(" .limit locals " + localCount);
}
}
}
// Emit code in one pass
{
Iterator codeIt = instList.iterator();
isEmittingMethodCode = true;
maxStackHeight = 0;
isNextGotoAJsr = false;
while(codeIt.hasNext())
{
Inst s = (Inst) codeIt.next();
if(instToLabel.containsKey(s))
emit(instToLabel.get(s) + ":");
// emit this statement
{
emitInst(s);
}
}
isEmittingMethodCode = false;
// calculate max stack height
{
maxStackHeight = 0;
if(activeBody.getUnits().size() != 0 ) {
BlockGraph blockGraph = new BriefBlockGraph(activeBody);
List blocks = blockGraph.getBlocks();
if(blocks.size() != 0) {
// set the stack height of the entry points
List entryPoints = ((DirectedGraph)blockGraph).getHeads();
Iterator entryIt = entryPoints.iterator();
while(entryIt.hasNext()) {
Block entryBlock = (Block) entryIt.next();
Integer initialHeight;
if(handlerUnits.contains(entryBlock.getHead())) {
initialHeight = new Integer(1);
} else {
initialHeight = new Integer(0);
}
blockToStackHeight.put(entryBlock, initialHeight);
blockToLogicalStackHeight.put(entryBlock, initialHeight);
}
// dfs the block graph using the blocks in the entryPoints list as roots
entryIt = entryPoints.iterator();
while(entryIt.hasNext()) {
Block nextBlock = (Block) entryIt.next();
calculateStackHeight(nextBlock);
calculateLogicalStackHeightCheck(nextBlock);
}
}
}
}
if (!Modifier.isNative(method.getModifiers())
&& !Modifier.isAbstract(method.getModifiers()))
code.set(stackLimitIndex, " .limit stack " + maxStackHeight);
}
// emit code attributes
{
Iterator it = body.getTags().iterator();
while(it.hasNext()) {
Tag t = (Tag) it.next();
if(t instanceof JasminAttribute) {
emit(".code_attribute " + t.getName() +" \"" + ((JasminAttribute) t).getJasminValue(instToLabel) +"\"");
}
}
}
}
public void print(PrintWriter out)
{
Iterator it = code.iterator();
while(it.hasNext())
out.println(it.next());
}
void emitInst(Inst inst)
{
inst.apply(new InstSwitch()
{
public void caseReturnVoidInst(ReturnVoidInst i)
{
emit("return");
}
public void caseReturnInst(ReturnInst i)
{
i.getOpType().apply(new TypeSwitch()
{
public void defaultCase(Type t)
{
throw new RuntimeException("invalid return type " + t.toString());
}
public void caseDoubleType(DoubleType t)
{
emit("dreturn");
}
public void caseFloatType(FloatType t)
{
emit("freturn");
}
public void caseIntType(IntType t)
{
emit("ireturn");
}
public void caseByteType(ByteType t)
{
emit("ireturn");
}
public void caseShortType(ShortType t)
{
emit("ireturn");
}
public void caseCharType(CharType t)
{
emit("ireturn");
}
public void caseBooleanType(BooleanType t)
{
emit("ireturn");
}
public void caseLongType(LongType t)
{
emit("lreturn");
}
public void caseArrayType(ArrayType t)
{
emit("areturn");
}
public void caseRefType(RefType t)
{
emit("areturn");
}
public void caseNullType(NullType t)
{
emit("areturn");
}
});
}
public void caseNopInst(NopInst i) { emit ("nop"); }
public void caseEnterMonitorInst(EnterMonitorInst i)
{
emit ("monitorenter");
}
public void casePopInst(PopInst i)
{
if(i.getWordCount() == 2) {
emit("pop2");
}
else
emit("pop");
}
public void caseExitMonitorInst(ExitMonitorInst i)
{
emit ("monitorexit");
}
public void caseGotoInst(GotoInst i)
{
emit("goto " + instToLabel.get(i.getTarget()));
}
public void casePushInst(PushInst i)
{
if (i.getConstant() instanceof IntConstant)
{
IntConstant v = (IntConstant)(i.getConstant());
if(v.value == -1)
emit("iconst_m1");
else if(v.value >= 0 && v.value <= 5)
emit("iconst_" + v.value);
else if(v.value >= Byte.MIN_VALUE &&
v.value <= Byte.MAX_VALUE)
emit("bipush " + v.value);
else if(v.value >= Short.MIN_VALUE &&
v.value <= Short.MAX_VALUE)
emit("sipush " + v.value);
else
emit("ldc " + v.toString());
}
else if (i.getConstant() instanceof StringConstant)
{
emit("ldc " + i.getConstant().toString());
}
else if (i.getConstant() instanceof DoubleConstant)
{
DoubleConstant v = (DoubleConstant)(i.getConstant());
if(v.value == 0)
emit("dconst_0");
else if(v.value == 1)
emit("dconst_1");
else {
String s = v.toString();
if(s.equals("#Infinity"))
s="+DoubleInfinity";
if(s.equals("#-Infinity"))
s="-DoubleInfinity";
if(s.equals("#NaN"))
s="+DoubleNaN";
emit("ldc2_w " + s);
}
}
else if (i.getConstant() instanceof FloatConstant)
{
FloatConstant v = (FloatConstant)(i.getConstant());
if(v.value == 0)
emit("fconst_0");
else if(v.value == 1)
emit("fconst_1");
else if(v.value == 2)
emit("fconst_2");
else {
String s = v.toString();
if(s.equals("#InfinityF"))
s="+FloatInfinity";
if(s.equals("#-InfinityF"))
s="-FloatInfinity";
if(s.equals("#NaNF"))
s="+FloatNaN";
emit("ldc " + s);
}
}
else if (i.getConstant() instanceof LongConstant)
{
LongConstant v = (LongConstant)(i.getConstant());
if(v.value == 0)
emit("lconst_0");
else if(v.value == 1)
emit("lconst_1");
else
emit("ldc2_w " + v.toString());
}
else if (i.getConstant() instanceof NullConstant)
emit("aconst_null");
else
throw new RuntimeException("unsupported opcode");
}
public void caseIdentityInst(IdentityInst i)
{
if(i.getRightOp() instanceof CaughtExceptionRef &&
i.getLeftOp() instanceof Local)
{
int slot = ((Integer) localToSlot.get(i.getLeftOp())).intValue();
if(slot >= 0 && slot <= 3)
emit("astore_" + slot);
else
emit("astore " + slot);
}
}
public void caseStoreInst(StoreInst i)
{
final int slot =
((Integer) localToSlot.get(i.getLocal())).intValue();
i.getOpType().apply(new TypeSwitch()
{
public void caseArrayType(ArrayType t)
{
if(slot >= 0 && slot <= 3)
emit("astore_" + slot);
else
emit("astore " + slot);
}
public void caseDoubleType(DoubleType t)
{
if(slot >= 0 && slot <= 3)
emit("dstore_" + slot);
else
emit("dstore " + slot);
}
public void caseFloatType(FloatType t)
{
if(slot >= 0 && slot <= 3)
emit("fstore_" + slot);
else
emit("fstore " + slot);
}
public void caseIntType(IntType t)
{
if(slot >= 0 && slot <= 3)
emit("istore_" + slot);
else
emit("istore " + slot);
}
public void caseByteType(ByteType t)
{
if(slot >= 0 && slot <= 3)
emit("istore_" + slot);
else
emit("istore " + slot);
}
public void caseShortType(ShortType t)
{
if(slot >= 0 && slot <= 3)
emit("istore_" + slot);
else
emit("istore " + slot);
}
public void caseCharType(CharType t)
{
if(slot >= 0 && slot <= 3)
emit("istore_" + slot);
else
emit("istore " + slot);
}
public void caseBooleanType(BooleanType t)
{
if(slot >= 0 && slot <= 3)
emit("istore_" + slot);
else
emit("istore " + slot);
}
public void caseLongType(LongType t)
{
if(slot >= 0 && slot <= 3)
emit("lstore_" + slot);
else
emit("lstore " + slot);
}
public void caseRefType(RefType t)
{
if(slot >= 0 && slot <= 3)
emit("astore_" + slot);
else
emit("astore " + slot);
}
public void caseStmtAddressType(StmtAddressType t)
{
isNextGotoAJsr = true;
returnAddressSlot = slot;
/*
if ( slot >= 0 && slot <= 3)
emit("astore_" + slot, );
else
emit("astore " + slot, );
*/
}
public void caseNullType(NullType t)
{
if(slot >= 0 && slot <= 3)
emit("astore_" + slot);
else
emit("astore " + slot);
}
public void defaultCase(Type t)
{
throw new RuntimeException("Invalid local type:"
+ t);
}
});
}
public void caseLoadInst(LoadInst i)
{
final int slot =
((Integer) localToSlot.get(i.getLocal())).intValue();
i.getOpType().apply(new TypeSwitch()
{
public void caseArrayType(ArrayType t)
{
if(slot >= 0 && slot <= 3)
emit("aload_" + slot);
else
emit("aload " + slot);
}
public void defaultCase(Type t)
{
throw new
RuntimeException("invalid local type to load" + t);
}
public void caseDoubleType(DoubleType t)
{
if(slot >= 0 && slot <= 3)
emit("dload_" + slot);
else
emit("dload " + slot);
}
public void caseFloatType(FloatType t)
{
if(slot >= 0 && slot <= 3)
emit("fload_" + slot);
else
emit("fload " + slot);
}
public void caseIntType(IntType t)
{
if(slot >= 0 && slot <= 3)
emit("iload_" + slot);
else
emit("iload " + slot);
}
public void caseByteType(ByteType t)
{
if(slot >= 0 && slot <= 3)
emit("iload_" + slot);
else
emit("iload " + slot);
}
public void caseShortType(ShortType t)
{
if(slot >= 0 && slot <= 3)
emit("iload_" + slot);
else
emit("iload " + slot);
}
public void caseCharType(CharType t)
{
if(slot >= 0 && slot <= 3)
emit("iload_" + slot);
else
emit("iload " + slot);
}
public void caseBooleanType(BooleanType t)
{
if(slot >= 0 && slot <= 3)
emit("iload_" + slot);
else
emit("iload " + slot);
}
public void caseLongType(LongType t)
{
if(slot >= 0 && slot <= 3)
emit("lload_" + slot);
else
emit("lload " + slot);
}
public void caseRefType(RefType t)
{
if(slot >= 0 && slot <= 3)
emit("aload_" + slot);
else
emit("aload " + slot);
}
public void caseNullType(NullType t)
{
if(slot >= 0 && slot <= 3)
emit("aload_" + slot);
else
emit("aload " + slot);
}
});
}
public void caseArrayWriteInst(ArrayWriteInst i)
{
i.getOpType().apply(new TypeSwitch()
{
public void caseArrayType(ArrayType t)
{
emit("aastore");
}
public void caseDoubleType(DoubleType t)
{
emit("dastore");
}
public void caseFloatType(FloatType t)
{
emit("fastore");
}
public void caseIntType(IntType t)
{
emit("iastore");
}
public void caseLongType(LongType t)
{
emit("lastore");
}
public void caseRefType(RefType t)
{
emit("aastore");
}
public void caseByteType(ByteType t)
{
emit("bastore");
}
public void caseBooleanType(BooleanType t)
{
emit("bastore");
}
public void caseCharType(CharType t)
{
emit("castore");
}
public void caseShortType(ShortType t)
{
emit("sastore");
}
public void defaultCase(Type t)
{
throw new RuntimeException("Invalid type: " + t);
}});
}
public void caseArrayReadInst(ArrayReadInst i)
{
i.getOpType().apply(new TypeSwitch()
{
public void caseArrayType(ArrayType ty)
{
emit("aaload");
}
public void caseBooleanType(BooleanType ty)
{
emit("baload");
}
public void caseByteType(ByteType ty)
{
emit("baload");
}
public void caseCharType(CharType ty)
{
emit("caload");
}
public void defaultCase(Type ty)
{
throw new RuntimeException("invalid base type");
}
public void caseDoubleType(DoubleType ty)
{
emit("daload");
}
public void caseFloatType(FloatType ty)
{
emit("faload");
}
public void caseIntType(IntType ty)
{
emit("iaload");
}
public void caseLongType(LongType ty)
{
emit("laload");
}
public void caseNullType(NullType ty)
{
emit("aaload");
}
public void caseRefType(RefType ty)
{
emit("aaload");
}
public void caseShortType(ShortType ty)
{
emit("saload");
}
});
}
public void caseIfNullInst(IfNullInst i)
{
emit("ifnull " + instToLabel.get(i.getTarget()));
}
public void caseIfNonNullInst(IfNonNullInst i)
{
emit("ifnonnull " + instToLabel.get(i.getTarget()));
}
public void caseIfEqInst(IfEqInst i)
{
emit("ifeq " + instToLabel.get(i.getTarget()));
}
public void caseIfNeInst(IfNeInst i)
{
emit("ifne " + instToLabel.get(i.getTarget()));
}
public void caseIfGtInst(IfGtInst i)
{
emit("ifgt " + instToLabel.get(i.getTarget()));
}
public void caseIfGeInst(IfGeInst i)
{
emit("ifge " + instToLabel.get(i.getTarget()));
}
public void caseIfLtInst(IfLtInst i)
{
emit("iflt " + instToLabel.get(i.getTarget()));
}
public void caseIfLeInst(IfLeInst i)
{
emit("ifle " + instToLabel.get(i.getTarget()));
}
public void caseIfCmpEqInst(final IfCmpEqInst i)
{
i.getOpType().apply(new TypeSwitch()
{
public void caseIntType(IntType t)
{
emit("if_icmpeq " +
instToLabel.get(i.getTarget()));
}
public void caseBooleanType(BooleanType t)
{
emit("if_icmpeq " +
instToLabel.get(i.getTarget()));
}
public void caseShortType(ShortType t)
{
emit("if_icmpeq " +
instToLabel.get(i.getTarget()));
}
public void caseCharType(CharType t)
{
emit("if_icmpeq " +
instToLabel.get(i.getTarget()));
}
public void caseByteType(ByteType t)
{
emit("if_icmpeq " +
instToLabel.get(i.getTarget()));
}
public void caseDoubleType(DoubleType t)
{
emit("dcmpg");
emit("ifeq " +
instToLabel.get(i.getTarget()));
}
public void caseLongType(LongType t)
{
emit("lcmp");
emit("ifeq " +
instToLabel.get(i.getTarget()));
}
public void caseFloatType(FloatType t)
{
emit("fcmpg");
emit("ifeq " +
instToLabel.get(i.getTarget()));
}
public void caseArrayType(ArrayType t)
{
emit("if_acmpeq " +
instToLabel.get(i.getTarget()));
}
public void caseRefType(RefType t)
{
emit("if_acmpeq " +
instToLabel.get(i.getTarget()));
}
public void caseNullType(NullType t)
{
emit("if_acmpeq " +
instToLabel.get(i.getTarget()));
}
public void defaultCase(Type t)
{
throw new RuntimeException("invalid type");
}
});
}
public void caseIfCmpNeInst(final IfCmpNeInst i)
{
i.getOpType().apply(new TypeSwitch()
{
public void caseIntType(IntType t)
{
emit("if_icmpne " +
instToLabel.get(i.getTarget()));
}
public void caseBooleanType(BooleanType t)
{
emit("if_icmpne " +
instToLabel.get(i.getTarget()));
}
public void caseShortType(ShortType t)
{
emit("if_icmpne " +
instToLabel.get(i.getTarget()));
}
public void caseCharType(CharType t)
{
emit("if_icmpne " +
instToLabel.get(i.getTarget()));
}
public void caseByteType(ByteType t)
{
emit("if_icmpne " +
instToLabel.get(i.getTarget()));
}
public void caseDoubleType(DoubleType t)
{
emit("dcmpg");
emit("ifne " +
instToLabel.get(i.getTarget()));
}
public void caseLongType(LongType t)
{
emit("lcmp");
emit("ifne " +
instToLabel.get(i.getTarget()));
}
public void caseFloatType(FloatType t)
{
emit("fcmpg");
emit("ifne " +
instToLabel.get(i.getTarget()));
}
public void caseArrayType(ArrayType t)
{
emit("if_acmpne " +
instToLabel.get(i.getTarget()));
}
public void caseRefType(RefType t)
{
emit("if_acmpne " +
instToLabel.get(i.getTarget()));
}
public void caseNullType(NullType t)
{
emit("if_acmpne " +
instToLabel.get(i.getTarget()));
}
public void defaultCase(Type t)
{
throw new RuntimeException("invalid type");
}
});
}
public void caseIfCmpGtInst(final IfCmpGtInst i)
{
i.getOpType().apply(new TypeSwitch()
{
public void caseIntType(IntType t)
{
emit("if_icmpgt " +
instToLabel.get(i.getTarget()));
}
public void caseBooleanType(BooleanType t)
{
emit("if_icmpgt " +
instToLabel.get(i.getTarget()));
}
public void caseShortType(ShortType t)
{
emit("if_icmpgt " +
instToLabel.get(i.getTarget()));
}
public void caseCharType(CharType t)
{
emit("if_icmpgt " +
instToLabel.get(i.getTarget()));
}
public void caseByteType(ByteType t)
{
emit("if_icmpgt " +
instToLabel.get(i.getTarget()));
}
public void caseDoubleType(DoubleType t)
{
emit("dcmpg");
emit("ifgt " +
instToLabel.get(i.getTarget()));
}
public void caseLongType(LongType t)
{
emit("lcmp");
emit("ifgt " +
instToLabel.get(i.getTarget()));
}
public void caseFloatType(FloatType t)
{
emit("fcmpg");
emit("ifgt " +
instToLabel.get(i.getTarget()));
}
public void caseArrayType(ArrayType t)
{
emit("if_acmpgt " +
instToLabel.get(i.getTarget()));
}
public void caseRefType(RefType t)
{
emit("if_acmpgt " +
instToLabel.get(i.getTarget()));
}
public void caseNullType(NullType t)
{
emit("if_acmpgt " +
instToLabel.get(i.getTarget()));
}
public void defaultCase(Type t)
{
throw new RuntimeException("invalid type");
}
});
}
public void caseIfCmpGeInst(final IfCmpGeInst i)
{
i.getOpType().apply(new TypeSwitch()
{
public void caseIntType(IntType t)
{
emit("if_icmpge " +
instToLabel.get(i.getTarget()));
}
public void caseBooleanType(BooleanType t)
{
emit("if_icmpge " +
instToLabel.get(i.getTarget()));
}
public void caseShortType(ShortType t)
{
emit("if_icmpge " +
instToLabel.get(i.getTarget()));
}
public void caseCharType(CharType t)
{
emit("if_icmpge " +
instToLabel.get(i.getTarget()));
}
public void caseByteType(ByteType t)
{
emit("if_icmpge " +
instToLabel.get(i.getTarget()));
}
public void caseDoubleType(DoubleType t)
{
emit("dcmpg");
emit("ifge " +
instToLabel.get(i.getTarget()));
}
public void caseLongType(LongType t)
{
emit("lcmp");
emit("ifge " +
instToLabel.get(i.getTarget()));
}
public void caseFloatType(FloatType t)
{
emit("fcmpg");
emit("ifge " +
instToLabel.get(i.getTarget()));
}
public void caseArrayType(ArrayType t)
{
emit("if_acmpge " +
instToLabel.get(i.getTarget()));
}
public void caseRefType(RefType t)
{
emit("if_acmpge " +
instToLabel.get(i.getTarget()));
}
public void caseNullType(NullType t)
{
emit("if_acmpge " +
instToLabel.get(i.getTarget()));
}
public void defaultCase(Type t)
{
throw new RuntimeException("invalid type");
}
});
}
public void caseIfCmpLtInst(final IfCmpLtInst i)
{
i.getOpType().apply(new TypeSwitch()
{
public void caseIntType(IntType t)
{
emit("if_icmplt " +
instToLabel.get(i.getTarget()));
}
public void caseBooleanType(BooleanType t)
{
emit("if_icmplt " +
instToLabel.get(i.getTarget()));
}
public void caseShortType(ShortType t)
{
emit("if_icmplt " +
instToLabel.get(i.getTarget()));
}
public void caseCharType(CharType t)
{
emit("if_icmplt " +
instToLabel.get(i.getTarget()));
}
public void caseByteType(ByteType t)
{
emit("if_icmplt " +
instToLabel.get(i.getTarget()));
}
public void caseDoubleType(DoubleType t)
{
emit("dcmpg");
emit("iflt " +
instToLabel.get(i.getTarget()));
}
public void caseLongType(LongType t)
{
emit("lcmp");
emit("iflt " +
instToLabel.get(i.getTarget()));
}
public void caseFloatType(FloatType t)
{
emit("fcmpg");
emit("iflt " +
instToLabel.get(i.getTarget()));
}
public void caseArrayType(ArrayType t)
{
emit("if_acmplt " +
instToLabel.get(i.getTarget()));
}
public void caseRefType(RefType t)
{
emit("if_acmplt " +
instToLabel.get(i.getTarget()));
}
public void caseNullType(NullType t)
{
emit("if_acmplt " +
instToLabel.get(i.getTarget()));
}
public void defaultCase(Type t)
{
throw new RuntimeException("invalid type");
}
});
}
public void caseIfCmpLeInst(final IfCmpLeInst i)
{
i.getOpType().apply(new TypeSwitch()
{
public void caseIntType(IntType t)
{
emit("if_icmple " +
instToLabel.get(i.getTarget()));
}
public void caseBooleanType(BooleanType t)
{
emit("if_icmple " +
instToLabel.get(i.getTarget()));
}
public void caseShortType(ShortType t)
{
emit("if_icmple " +
instToLabel.get(i.getTarget()));
}
public void caseCharType(CharType t)
{
emit("if_icmple " +
instToLabel.get(i.getTarget()));
}
public void caseByteType(ByteType t)
{
emit("if_icmple " +
instToLabel.get(i.getTarget()));
}
public void caseDoubleType(DoubleType t)
{
emit("dcmpg");
emit("ifle " +
instToLabel.get(i.getTarget()));
}
public void caseLongType(LongType t)
{
emit("lcmp");
emit("ifle " +
instToLabel.get(i.getTarget()));
}
public void caseFloatType(FloatType t)
{
emit("fcmpg");
emit("ifle " +
instToLabel.get(i.getTarget()));
}
public void caseArrayType(ArrayType t)
{
emit("if_acmple " +
instToLabel.get(i.getTarget()));
}
public void caseRefType(RefType t)
{
emit("if_acmple " +
instToLabel.get(i.getTarget()));
}
public void caseNullType(NullType t)
{
emit("if_acmple " +
instToLabel.get(i.getTarget()));
}
public void defaultCase(Type t)
{
throw new RuntimeException("invalid type");
}
});
}
public void caseStaticGetInst(StaticGetInst i)
{
SootField field = i.getField();
emit("getstatic " +
slashify(field.getDeclaringClass().getName()) + "/" +
field.getName() + " " +
jasminDescriptorOf(field.getType()));
}
public void caseStaticPutInst(StaticPutInst i)
{
emit("putstatic " +
slashify(i.getField().getDeclaringClass().getName()) +
"/" + i.getField().getName() + " " +
jasminDescriptorOf(i.getField().getType()));
}
public void caseFieldGetInst(FieldGetInst i)
{
emit("getfield " +
slashify(i.getField().getDeclaringClass().getName()) +
"/" + i.getField().getName() + " " +
jasminDescriptorOf(i.getField().getType()));
}
public void caseFieldPutInst(FieldPutInst i)
{
emit("putfield " +
slashify(i.getField().getDeclaringClass().getName()) +
"/" + i.getField().getName() + " " +
jasminDescriptorOf(i.getField().getType()));
}
public void caseInstanceCastInst(InstanceCastInst i)
{
Type castType = i.getCastType();
if(castType instanceof RefType)
emit("checkcast " + slashify(castType.toString()));
else if(castType instanceof ArrayType)
emit("checkcast " + jasminDescriptorOf(castType));
}
public void caseInstanceOfInst(InstanceOfInst i)
{
Type checkType = i.getCheckType();
if(checkType instanceof RefType)
emit("instanceof " + slashify(checkType.toString()));
else if(checkType instanceof ArrayType)
emit("instanceof " + jasminDescriptorOf(checkType));
}
public void caseNewInst(NewInst i)
{
emit("new "+slashify(i.getBaseType().toString()));
}
public void casePrimitiveCastInst(PrimitiveCastInst i)
{
emit(i.toString());
}
public void caseStaticInvokeInst(StaticInvokeInst i)
{
SootMethod m = i.getMethod();
emit("invokestatic " + slashify(m.getDeclaringClass().getName()) + "/" +
m.getName() + jasminDescriptorOf(m));
}
public void caseVirtualInvokeInst(VirtualInvokeInst i)
{
SootMethod m = i.getMethod();
emit("invokevirtual " + slashify(m.getDeclaringClass().getName()) + "/" +
m.getName() + jasminDescriptorOf(m));
}
public void caseInterfaceInvokeInst(InterfaceInvokeInst i)
{
SootMethod m = i.getMethod();
emit("invokeinterface " + slashify(m.getDeclaringClass().getName()) + "/" +
m.getName() + jasminDescriptorOf(m) + " " + (argCountOf(m) + 1));
}
public void caseSpecialInvokeInst(SpecialInvokeInst i)
{
SootMethod m = i.getMethod();
emit("invokespecial " + slashify(m.getDeclaringClass().getName()) + "/" +
m.getName() + jasminDescriptorOf(m));
}
public void caseThrowInst(ThrowInst i)
{
emit("athrow");
}
public void caseCmpInst(CmpInst i)
{
emit("lcmp");
}
public void caseCmplInst(CmplInst i)
{
if(i.getOpType().equals(FloatType.v()))
emit("fcmpl");
else
emit("dcmpl");
}
public void caseCmpgInst(CmpgInst i)
{
if(i.getOpType().equals(FloatType.v()))
emit("fcmpg");
else
emit("dcmpg");
}
private void emitOpTypeInst(final String s, final OpTypeArgInst i)
{
i.getOpType().apply(new TypeSwitch()
{
private void handleIntCase()
{
emit("i"+s);
}
public void caseIntType(IntType t) { handleIntCase(); }
public void caseBooleanType(BooleanType t) { handleIntCase(); }
public void caseShortType(ShortType t) { handleIntCase(); }
public void caseCharType(CharType t) { handleIntCase(); }
public void caseByteType(ByteType t) { handleIntCase(); }
public void caseLongType(LongType t)
{
emit("l"+s);
}
public void caseDoubleType(DoubleType t)
{
emit("d"+s);
}
public void caseFloatType(FloatType t)
{
emit("f"+s);
}
public void defaultCase(Type t)
{
throw new RuntimeException("Invalid argument type for div");
}
});
}
public void caseAddInst(AddInst i)
{
emitOpTypeInst("add", i);
}
public void caseDivInst(DivInst i)
{
emitOpTypeInst("div", i);
}
public void caseSubInst(SubInst i)
{
emitOpTypeInst("sub", i);
}
public void caseMulInst(MulInst i)
{
emitOpTypeInst("mul", i);
}
public void caseRemInst(RemInst i)
{
emitOpTypeInst("rem", i);
}
public void caseShlInst(ShlInst i)
{
emitOpTypeInst("shl", i);
}
public void caseAndInst(AndInst i)
{
emitOpTypeInst("and", i);
}
public void caseOrInst(OrInst i)
{
emitOpTypeInst("or", i);
}
public void caseXorInst(XorInst i)
{
emitOpTypeInst("xor", i);
}
public void caseShrInst(ShrInst i)
{
emitOpTypeInst("shr", i);
}
public void caseUshrInst(UshrInst i)
{
emitOpTypeInst("ushr", i);
}
public void caseIncInst(IncInst i)
{
if(((ValueBox) i.getUseBoxes().get(0)).getValue() != ((ValueBox) i.getDefBoxes().get(0)).getValue())
throw new RuntimeException("iinc def and use boxes don't match");
emit("iinc " + ((Integer) localToSlot.get(i.getLocal())) + " " + i.getConstant());
}
public void caseArrayLengthInst(ArrayLengthInst i)
{
emit("arraylength");
}
public void caseNegInst(NegInst i)
{
emitOpTypeInst("neg", i);
}
public void caseNewArrayInst(NewArrayInst i)
{
if(i.getBaseType() instanceof RefType)
emit("anewarray " + slashify(i.getBaseType().toString()));
else if(i.getBaseType() instanceof ArrayType)
emit("anewarray " + jasminDescriptorOf(i.getBaseType()));
else
emit("newarray " + i.getBaseType().toString());
}
public void caseNewMultiArrayInst(NewMultiArrayInst i)
{
emit("multianewarray " + jasminDescriptorOf(i.getBaseType()) + " " +
i.getDimensionCount());
}
public void caseLookupSwitchInst(LookupSwitchInst i)
{
emit("lookupswitch");
List lookupValues = i.getLookupValues();
List targets = i.getTargets();
for(int j = 0; j < lookupValues.size(); j++)
emit(" " + lookupValues.get(j) + " : " +
instToLabel.get(targets.get(j)));
emit(" default : " + instToLabel.get(i.getDefaultTarget()));
}
public void caseTableSwitchInst(TableSwitchInst i)
{
emit("tableswitch " + i.getLowIndex() + " ; high = " + i.getHighIndex());
List targets = i.getTargets();
for(int j = 0; j < targets.size(); j++)
emit(" " + instToLabel.get(targets.get(j)));
emit("default : " + instToLabel.get(i.getDefaultTarget()));
}
private boolean isDwordType(Type t)
{
return t instanceof LongType || t instanceof DoubleType
|| t instanceof DoubleWordType;
}
public void caseDup1Inst(Dup1Inst i)
{
Type firstOpType = i.getOp1Type();
if (isDwordType(firstOpType))
emit("dup2"); // (form 2)
else
emit("dup");
}
public void caseDup2Inst(Dup2Inst i)
{
Type firstOpType = i.getOp1Type();
Type secondOpType = i.getOp2Type();
// The first two cases have no real bytecode equivalents.
// Use a pair of insts to simulate them.
if(isDwordType(firstOpType)) {
emit("dup2"); // (form 2)
if(isDwordType(secondOpType)) {
emit("dup2"); // (form 2 -- by simulation)
} else
emit("dup"); // also a simulation
} else if(isDwordType(secondOpType)) {
if(isDwordType(firstOpType)) {
emit("dup2"); // (form 2)
} else
emit("dup");
emit("dup2"); // (form 2 -- complete the simulation)
} else {
//delme[
G.v().out.println("3000:(JasminClass): dup2 created");
//delme
emit("dup2"); // form 1
}
}
public void caseDup1_x1Inst(Dup1_x1Inst i)
{
Type opType = i.getOp1Type();
Type underType = i.getUnder1Type();
if(isDwordType(opType)) {
if(isDwordType(underType)) {
emit("dup2_x2"); // (form 4)
} else
emit("dup2_x1"); // (form 2)
} else {
if(isDwordType(underType))
emit("dup_x2"); // (form 2)
else
emit("dup_x1"); // (only one form)
}
}
public void caseDup1_x2Inst(Dup1_x2Inst i)
{
- Type opType = i.getOpType();
+ Type opType = i.getOp1Type();
Type under1Type = i.getUnder1Type();
Type under2Type = i.getUnder2Type();
if (isDwordType(opType)) {
if (!isDwordType(under1Type) && !isDwordType(under2Type))
emit("dup2_x2"); // (form 2)
else
throw new RuntimeException("magic not implemented yet");
} else {
if (isDwordType(under1Type) || isDwordType(under2Type))
throw new RuntimeException("magic not implemented yet");
}
emit("dup_x2"); // (form 1)
}
public void caseDup2_x1Inst(Dup2_x1Inst i)
{
Type op1Type = i.getOp1Type();
Type op2Type = i.getOp2Type();
Type under1Type = i.getUnder1Type();
if (isDwordType(under1Type)) {
- if (!isDwordType(op1Type) && !isDwordType(under2Type))
+ if (!isDwordType(op1Type) && !isDwordType(op2Type))
throw new RuntimeException("magic not implemented yet");
else
emit("dup2_x2"); // (form 3)
} else {
if (isDwordType(op1Type) || isDwordType(op2Type))
throw new RuntimeException("magic not implemented yet");
}
emit("dup2_x1"); // (form 1)
}
public void caseDup2_x2Inst(Dup2_x2Inst i)
{
Type op1Type = i.getOp1Type();
Type op2Type = i.getOp2Type();
Type under1Type = i.getUnder1Type();
Type under2Type = i.getUnder2Type();
if (isDwordType(op1Type) || isDwordType(op2Type) ||
isDwordType(under1Type) || isDwordType(under1Type))
throw new RuntimeException("magic not implemented yet");
emit("dup2_x2"); // (form 1)
}
public void caseSwapInst(SwapInst i)
{
emit("swap");
}
});
}
private void calculateStackHeight(Block aBlock)
{
Iterator it = aBlock.iterator();
int blockHeight = ((Integer)blockToStackHeight.get(aBlock)).intValue();
while(it.hasNext()) {
Inst nInst = (Inst) it.next();
blockHeight -= nInst.getInMachineCount();
if(blockHeight < 0 ){
throw new RuntimeException("Negative Stack height has been attained: \n" +
"StackHeight: " + blockHeight + "\n" +
"At instruction:" + nInst + "\n" +
"Block:\n" + aBlock +
"\n\nMethod: " + aBlock.getBody().getMethod().getName()
+ "\n" + aBlock.getBody().getMethod()
);
}
blockHeight += nInst.getOutMachineCount();
if( blockHeight > maxStackHeight) {
maxStackHeight = blockHeight;
}
//G.v().out.println(">>> " + nInst + " " + blockHeight);
}
Iterator succs = aBlock.getSuccs().iterator();
while(succs.hasNext()) {
Block b = (Block) succs.next();
Integer i = (Integer) blockToStackHeight.get(b);
if(i != null) {
if(i.intValue() != blockHeight) {
throw new RuntimeException("incoherent stack height at block merge point " + b + aBlock + "\ncomputed blockHeight == " + blockHeight + " recorded blockHeight = " + i.intValue());
}
} else {
blockToStackHeight.put(b, new Integer(blockHeight));
calculateStackHeight(b);
}
}
}
private void calculateLogicalStackHeightCheck(Block aBlock)
{
Iterator it = aBlock.iterator();
int blockHeight = ((Integer)blockToLogicalStackHeight.get(aBlock)).intValue();
while(it.hasNext()) {
Inst nInst = (Inst) it.next();
blockHeight -= nInst.getInCount();
if(blockHeight < 0 ){
throw new RuntimeException("Negative Stack Logical height has been attained: \n" +
"StackHeight: " + blockHeight +
"\nAt instruction:" + nInst +
"\nBlock:\n" + aBlock +
"\n\nMethod: " + aBlock.getBody().getMethod().getName()
+ "\n" + aBlock.getBody().getMethod()
);
}
blockHeight += nInst.getOutCount();
//G.v().out.println(">>> " + nInst + " " + blockHeight);
}
Iterator succs = aBlock.getSuccs().iterator();
while(succs.hasNext()) {
Block b = (Block) succs.next();
Integer i = (Integer) blockToLogicalStackHeight.get(b);
if(i != null) {
if(i.intValue() != blockHeight) {
throw new RuntimeException("incoherent logical stack height at block merge point " + b + aBlock);
}
} else {
blockToLogicalStackHeight.put(b, new Integer(blockHeight));
calculateLogicalStackHeightCheck(b);
}
}
}
}
class GroupIntPair
{
Object group;
int x;
GroupIntPair(Object group, int x)
{
this.group = group;
this.x = x;
}
public boolean equals(Object other)
{
if(other instanceof GroupIntPair)
return ((GroupIntPair) other).group.equals(this.group) &&
((GroupIntPair) other).x == this.x;
else
return false;
}
public int hashCode()
{
return group.hashCode() + 1013 * x;
}
}
| false | true | void emitInst(Inst inst)
{
inst.apply(new InstSwitch()
{
public void caseReturnVoidInst(ReturnVoidInst i)
{
emit("return");
}
public void caseReturnInst(ReturnInst i)
{
i.getOpType().apply(new TypeSwitch()
{
public void defaultCase(Type t)
{
throw new RuntimeException("invalid return type " + t.toString());
}
public void caseDoubleType(DoubleType t)
{
emit("dreturn");
}
public void caseFloatType(FloatType t)
{
emit("freturn");
}
public void caseIntType(IntType t)
{
emit("ireturn");
}
public void caseByteType(ByteType t)
{
emit("ireturn");
}
public void caseShortType(ShortType t)
{
emit("ireturn");
}
public void caseCharType(CharType t)
{
emit("ireturn");
}
public void caseBooleanType(BooleanType t)
{
emit("ireturn");
}
public void caseLongType(LongType t)
{
emit("lreturn");
}
public void caseArrayType(ArrayType t)
{
emit("areturn");
}
public void caseRefType(RefType t)
{
emit("areturn");
}
public void caseNullType(NullType t)
{
emit("areturn");
}
});
}
public void caseNopInst(NopInst i) { emit ("nop"); }
public void caseEnterMonitorInst(EnterMonitorInst i)
{
emit ("monitorenter");
}
public void casePopInst(PopInst i)
{
if(i.getWordCount() == 2) {
emit("pop2");
}
else
emit("pop");
}
public void caseExitMonitorInst(ExitMonitorInst i)
{
emit ("monitorexit");
}
public void caseGotoInst(GotoInst i)
{
emit("goto " + instToLabel.get(i.getTarget()));
}
public void casePushInst(PushInst i)
{
if (i.getConstant() instanceof IntConstant)
{
IntConstant v = (IntConstant)(i.getConstant());
if(v.value == -1)
emit("iconst_m1");
else if(v.value >= 0 && v.value <= 5)
emit("iconst_" + v.value);
else if(v.value >= Byte.MIN_VALUE &&
v.value <= Byte.MAX_VALUE)
emit("bipush " + v.value);
else if(v.value >= Short.MIN_VALUE &&
v.value <= Short.MAX_VALUE)
emit("sipush " + v.value);
else
emit("ldc " + v.toString());
}
else if (i.getConstant() instanceof StringConstant)
{
emit("ldc " + i.getConstant().toString());
}
else if (i.getConstant() instanceof DoubleConstant)
{
DoubleConstant v = (DoubleConstant)(i.getConstant());
if(v.value == 0)
emit("dconst_0");
else if(v.value == 1)
emit("dconst_1");
else {
String s = v.toString();
if(s.equals("#Infinity"))
s="+DoubleInfinity";
if(s.equals("#-Infinity"))
s="-DoubleInfinity";
if(s.equals("#NaN"))
s="+DoubleNaN";
emit("ldc2_w " + s);
}
}
else if (i.getConstant() instanceof FloatConstant)
{
FloatConstant v = (FloatConstant)(i.getConstant());
if(v.value == 0)
emit("fconst_0");
else if(v.value == 1)
emit("fconst_1");
else if(v.value == 2)
emit("fconst_2");
else {
String s = v.toString();
if(s.equals("#InfinityF"))
s="+FloatInfinity";
if(s.equals("#-InfinityF"))
s="-FloatInfinity";
if(s.equals("#NaNF"))
s="+FloatNaN";
emit("ldc " + s);
}
}
else if (i.getConstant() instanceof LongConstant)
{
LongConstant v = (LongConstant)(i.getConstant());
if(v.value == 0)
emit("lconst_0");
else if(v.value == 1)
emit("lconst_1");
else
emit("ldc2_w " + v.toString());
}
else if (i.getConstant() instanceof NullConstant)
emit("aconst_null");
else
throw new RuntimeException("unsupported opcode");
}
public void caseIdentityInst(IdentityInst i)
{
if(i.getRightOp() instanceof CaughtExceptionRef &&
i.getLeftOp() instanceof Local)
{
int slot = ((Integer) localToSlot.get(i.getLeftOp())).intValue();
if(slot >= 0 && slot <= 3)
emit("astore_" + slot);
else
emit("astore " + slot);
}
}
public void caseStoreInst(StoreInst i)
{
final int slot =
((Integer) localToSlot.get(i.getLocal())).intValue();
i.getOpType().apply(new TypeSwitch()
{
public void caseArrayType(ArrayType t)
{
if(slot >= 0 && slot <= 3)
emit("astore_" + slot);
else
emit("astore " + slot);
}
public void caseDoubleType(DoubleType t)
{
if(slot >= 0 && slot <= 3)
emit("dstore_" + slot);
else
emit("dstore " + slot);
}
public void caseFloatType(FloatType t)
{
if(slot >= 0 && slot <= 3)
emit("fstore_" + slot);
else
emit("fstore " + slot);
}
public void caseIntType(IntType t)
{
if(slot >= 0 && slot <= 3)
emit("istore_" + slot);
else
emit("istore " + slot);
}
public void caseByteType(ByteType t)
{
if(slot >= 0 && slot <= 3)
emit("istore_" + slot);
else
emit("istore " + slot);
}
public void caseShortType(ShortType t)
{
if(slot >= 0 && slot <= 3)
emit("istore_" + slot);
else
emit("istore " + slot);
}
public void caseCharType(CharType t)
{
if(slot >= 0 && slot <= 3)
emit("istore_" + slot);
else
emit("istore " + slot);
}
public void caseBooleanType(BooleanType t)
{
if(slot >= 0 && slot <= 3)
emit("istore_" + slot);
else
emit("istore " + slot);
}
public void caseLongType(LongType t)
{
if(slot >= 0 && slot <= 3)
emit("lstore_" + slot);
else
emit("lstore " + slot);
}
public void caseRefType(RefType t)
{
if(slot >= 0 && slot <= 3)
emit("astore_" + slot);
else
emit("astore " + slot);
}
public void caseStmtAddressType(StmtAddressType t)
{
isNextGotoAJsr = true;
returnAddressSlot = slot;
/*
if ( slot >= 0 && slot <= 3)
emit("astore_" + slot, );
else
emit("astore " + slot, );
*/
}
public void caseNullType(NullType t)
{
if(slot >= 0 && slot <= 3)
emit("astore_" + slot);
else
emit("astore " + slot);
}
public void defaultCase(Type t)
{
throw new RuntimeException("Invalid local type:"
+ t);
}
});
}
public void caseLoadInst(LoadInst i)
{
final int slot =
((Integer) localToSlot.get(i.getLocal())).intValue();
i.getOpType().apply(new TypeSwitch()
{
public void caseArrayType(ArrayType t)
{
if(slot >= 0 && slot <= 3)
emit("aload_" + slot);
else
emit("aload " + slot);
}
public void defaultCase(Type t)
{
throw new
RuntimeException("invalid local type to load" + t);
}
public void caseDoubleType(DoubleType t)
{
if(slot >= 0 && slot <= 3)
emit("dload_" + slot);
else
emit("dload " + slot);
}
public void caseFloatType(FloatType t)
{
if(slot >= 0 && slot <= 3)
emit("fload_" + slot);
else
emit("fload " + slot);
}
public void caseIntType(IntType t)
{
if(slot >= 0 && slot <= 3)
emit("iload_" + slot);
else
emit("iload " + slot);
}
public void caseByteType(ByteType t)
{
if(slot >= 0 && slot <= 3)
emit("iload_" + slot);
else
emit("iload " + slot);
}
public void caseShortType(ShortType t)
{
if(slot >= 0 && slot <= 3)
emit("iload_" + slot);
else
emit("iload " + slot);
}
public void caseCharType(CharType t)
{
if(slot >= 0 && slot <= 3)
emit("iload_" + slot);
else
emit("iload " + slot);
}
public void caseBooleanType(BooleanType t)
{
if(slot >= 0 && slot <= 3)
emit("iload_" + slot);
else
emit("iload " + slot);
}
public void caseLongType(LongType t)
{
if(slot >= 0 && slot <= 3)
emit("lload_" + slot);
else
emit("lload " + slot);
}
public void caseRefType(RefType t)
{
if(slot >= 0 && slot <= 3)
emit("aload_" + slot);
else
emit("aload " + slot);
}
public void caseNullType(NullType t)
{
if(slot >= 0 && slot <= 3)
emit("aload_" + slot);
else
emit("aload " + slot);
}
});
}
public void caseArrayWriteInst(ArrayWriteInst i)
{
i.getOpType().apply(new TypeSwitch()
{
public void caseArrayType(ArrayType t)
{
emit("aastore");
}
public void caseDoubleType(DoubleType t)
{
emit("dastore");
}
public void caseFloatType(FloatType t)
{
emit("fastore");
}
public void caseIntType(IntType t)
{
emit("iastore");
}
public void caseLongType(LongType t)
{
emit("lastore");
}
public void caseRefType(RefType t)
{
emit("aastore");
}
public void caseByteType(ByteType t)
{
emit("bastore");
}
public void caseBooleanType(BooleanType t)
{
emit("bastore");
}
public void caseCharType(CharType t)
{
emit("castore");
}
public void caseShortType(ShortType t)
{
emit("sastore");
}
public void defaultCase(Type t)
{
throw new RuntimeException("Invalid type: " + t);
}});
}
public void caseArrayReadInst(ArrayReadInst i)
{
i.getOpType().apply(new TypeSwitch()
{
public void caseArrayType(ArrayType ty)
{
emit("aaload");
}
public void caseBooleanType(BooleanType ty)
{
emit("baload");
}
public void caseByteType(ByteType ty)
{
emit("baload");
}
public void caseCharType(CharType ty)
{
emit("caload");
}
public void defaultCase(Type ty)
{
throw new RuntimeException("invalid base type");
}
public void caseDoubleType(DoubleType ty)
{
emit("daload");
}
public void caseFloatType(FloatType ty)
{
emit("faload");
}
public void caseIntType(IntType ty)
{
emit("iaload");
}
public void caseLongType(LongType ty)
{
emit("laload");
}
public void caseNullType(NullType ty)
{
emit("aaload");
}
public void caseRefType(RefType ty)
{
emit("aaload");
}
public void caseShortType(ShortType ty)
{
emit("saload");
}
});
}
public void caseIfNullInst(IfNullInst i)
{
emit("ifnull " + instToLabel.get(i.getTarget()));
}
public void caseIfNonNullInst(IfNonNullInst i)
{
emit("ifnonnull " + instToLabel.get(i.getTarget()));
}
public void caseIfEqInst(IfEqInst i)
{
emit("ifeq " + instToLabel.get(i.getTarget()));
}
public void caseIfNeInst(IfNeInst i)
{
emit("ifne " + instToLabel.get(i.getTarget()));
}
public void caseIfGtInst(IfGtInst i)
{
emit("ifgt " + instToLabel.get(i.getTarget()));
}
public void caseIfGeInst(IfGeInst i)
{
emit("ifge " + instToLabel.get(i.getTarget()));
}
public void caseIfLtInst(IfLtInst i)
{
emit("iflt " + instToLabel.get(i.getTarget()));
}
public void caseIfLeInst(IfLeInst i)
{
emit("ifle " + instToLabel.get(i.getTarget()));
}
public void caseIfCmpEqInst(final IfCmpEqInst i)
{
i.getOpType().apply(new TypeSwitch()
{
public void caseIntType(IntType t)
{
emit("if_icmpeq " +
instToLabel.get(i.getTarget()));
}
public void caseBooleanType(BooleanType t)
{
emit("if_icmpeq " +
instToLabel.get(i.getTarget()));
}
public void caseShortType(ShortType t)
{
emit("if_icmpeq " +
instToLabel.get(i.getTarget()));
}
public void caseCharType(CharType t)
{
emit("if_icmpeq " +
instToLabel.get(i.getTarget()));
}
public void caseByteType(ByteType t)
{
emit("if_icmpeq " +
instToLabel.get(i.getTarget()));
}
public void caseDoubleType(DoubleType t)
{
emit("dcmpg");
emit("ifeq " +
instToLabel.get(i.getTarget()));
}
public void caseLongType(LongType t)
{
emit("lcmp");
emit("ifeq " +
instToLabel.get(i.getTarget()));
}
public void caseFloatType(FloatType t)
{
emit("fcmpg");
emit("ifeq " +
instToLabel.get(i.getTarget()));
}
public void caseArrayType(ArrayType t)
{
emit("if_acmpeq " +
instToLabel.get(i.getTarget()));
}
public void caseRefType(RefType t)
{
emit("if_acmpeq " +
instToLabel.get(i.getTarget()));
}
public void caseNullType(NullType t)
{
emit("if_acmpeq " +
instToLabel.get(i.getTarget()));
}
public void defaultCase(Type t)
{
throw new RuntimeException("invalid type");
}
});
}
public void caseIfCmpNeInst(final IfCmpNeInst i)
{
i.getOpType().apply(new TypeSwitch()
{
public void caseIntType(IntType t)
{
emit("if_icmpne " +
instToLabel.get(i.getTarget()));
}
public void caseBooleanType(BooleanType t)
{
emit("if_icmpne " +
instToLabel.get(i.getTarget()));
}
public void caseShortType(ShortType t)
{
emit("if_icmpne " +
instToLabel.get(i.getTarget()));
}
public void caseCharType(CharType t)
{
emit("if_icmpne " +
instToLabel.get(i.getTarget()));
}
public void caseByteType(ByteType t)
{
emit("if_icmpne " +
instToLabel.get(i.getTarget()));
}
public void caseDoubleType(DoubleType t)
{
emit("dcmpg");
emit("ifne " +
instToLabel.get(i.getTarget()));
}
public void caseLongType(LongType t)
{
emit("lcmp");
emit("ifne " +
instToLabel.get(i.getTarget()));
}
public void caseFloatType(FloatType t)
{
emit("fcmpg");
emit("ifne " +
instToLabel.get(i.getTarget()));
}
public void caseArrayType(ArrayType t)
{
emit("if_acmpne " +
instToLabel.get(i.getTarget()));
}
public void caseRefType(RefType t)
{
emit("if_acmpne " +
instToLabel.get(i.getTarget()));
}
public void caseNullType(NullType t)
{
emit("if_acmpne " +
instToLabel.get(i.getTarget()));
}
public void defaultCase(Type t)
{
throw new RuntimeException("invalid type");
}
});
}
public void caseIfCmpGtInst(final IfCmpGtInst i)
{
i.getOpType().apply(new TypeSwitch()
{
public void caseIntType(IntType t)
{
emit("if_icmpgt " +
instToLabel.get(i.getTarget()));
}
public void caseBooleanType(BooleanType t)
{
emit("if_icmpgt " +
instToLabel.get(i.getTarget()));
}
public void caseShortType(ShortType t)
{
emit("if_icmpgt " +
instToLabel.get(i.getTarget()));
}
public void caseCharType(CharType t)
{
emit("if_icmpgt " +
instToLabel.get(i.getTarget()));
}
public void caseByteType(ByteType t)
{
emit("if_icmpgt " +
instToLabel.get(i.getTarget()));
}
public void caseDoubleType(DoubleType t)
{
emit("dcmpg");
emit("ifgt " +
instToLabel.get(i.getTarget()));
}
public void caseLongType(LongType t)
{
emit("lcmp");
emit("ifgt " +
instToLabel.get(i.getTarget()));
}
public void caseFloatType(FloatType t)
{
emit("fcmpg");
emit("ifgt " +
instToLabel.get(i.getTarget()));
}
public void caseArrayType(ArrayType t)
{
emit("if_acmpgt " +
instToLabel.get(i.getTarget()));
}
public void caseRefType(RefType t)
{
emit("if_acmpgt " +
instToLabel.get(i.getTarget()));
}
public void caseNullType(NullType t)
{
emit("if_acmpgt " +
instToLabel.get(i.getTarget()));
}
public void defaultCase(Type t)
{
throw new RuntimeException("invalid type");
}
});
}
public void caseIfCmpGeInst(final IfCmpGeInst i)
{
i.getOpType().apply(new TypeSwitch()
{
public void caseIntType(IntType t)
{
emit("if_icmpge " +
instToLabel.get(i.getTarget()));
}
public void caseBooleanType(BooleanType t)
{
emit("if_icmpge " +
instToLabel.get(i.getTarget()));
}
public void caseShortType(ShortType t)
{
emit("if_icmpge " +
instToLabel.get(i.getTarget()));
}
public void caseCharType(CharType t)
{
emit("if_icmpge " +
instToLabel.get(i.getTarget()));
}
public void caseByteType(ByteType t)
{
emit("if_icmpge " +
instToLabel.get(i.getTarget()));
}
public void caseDoubleType(DoubleType t)
{
emit("dcmpg");
emit("ifge " +
instToLabel.get(i.getTarget()));
}
public void caseLongType(LongType t)
{
emit("lcmp");
emit("ifge " +
instToLabel.get(i.getTarget()));
}
public void caseFloatType(FloatType t)
{
emit("fcmpg");
emit("ifge " +
instToLabel.get(i.getTarget()));
}
public void caseArrayType(ArrayType t)
{
emit("if_acmpge " +
instToLabel.get(i.getTarget()));
}
public void caseRefType(RefType t)
{
emit("if_acmpge " +
instToLabel.get(i.getTarget()));
}
public void caseNullType(NullType t)
{
emit("if_acmpge " +
instToLabel.get(i.getTarget()));
}
public void defaultCase(Type t)
{
throw new RuntimeException("invalid type");
}
});
}
public void caseIfCmpLtInst(final IfCmpLtInst i)
{
i.getOpType().apply(new TypeSwitch()
{
public void caseIntType(IntType t)
{
emit("if_icmplt " +
instToLabel.get(i.getTarget()));
}
public void caseBooleanType(BooleanType t)
{
emit("if_icmplt " +
instToLabel.get(i.getTarget()));
}
public void caseShortType(ShortType t)
{
emit("if_icmplt " +
instToLabel.get(i.getTarget()));
}
public void caseCharType(CharType t)
{
emit("if_icmplt " +
instToLabel.get(i.getTarget()));
}
public void caseByteType(ByteType t)
{
emit("if_icmplt " +
instToLabel.get(i.getTarget()));
}
public void caseDoubleType(DoubleType t)
{
emit("dcmpg");
emit("iflt " +
instToLabel.get(i.getTarget()));
}
public void caseLongType(LongType t)
{
emit("lcmp");
emit("iflt " +
instToLabel.get(i.getTarget()));
}
public void caseFloatType(FloatType t)
{
emit("fcmpg");
emit("iflt " +
instToLabel.get(i.getTarget()));
}
public void caseArrayType(ArrayType t)
{
emit("if_acmplt " +
instToLabel.get(i.getTarget()));
}
public void caseRefType(RefType t)
{
emit("if_acmplt " +
instToLabel.get(i.getTarget()));
}
public void caseNullType(NullType t)
{
emit("if_acmplt " +
instToLabel.get(i.getTarget()));
}
public void defaultCase(Type t)
{
throw new RuntimeException("invalid type");
}
});
}
public void caseIfCmpLeInst(final IfCmpLeInst i)
{
i.getOpType().apply(new TypeSwitch()
{
public void caseIntType(IntType t)
{
emit("if_icmple " +
instToLabel.get(i.getTarget()));
}
public void caseBooleanType(BooleanType t)
{
emit("if_icmple " +
instToLabel.get(i.getTarget()));
}
public void caseShortType(ShortType t)
{
emit("if_icmple " +
instToLabel.get(i.getTarget()));
}
public void caseCharType(CharType t)
{
emit("if_icmple " +
instToLabel.get(i.getTarget()));
}
public void caseByteType(ByteType t)
{
emit("if_icmple " +
instToLabel.get(i.getTarget()));
}
public void caseDoubleType(DoubleType t)
{
emit("dcmpg");
emit("ifle " +
instToLabel.get(i.getTarget()));
}
public void caseLongType(LongType t)
{
emit("lcmp");
emit("ifle " +
instToLabel.get(i.getTarget()));
}
public void caseFloatType(FloatType t)
{
emit("fcmpg");
emit("ifle " +
instToLabel.get(i.getTarget()));
}
public void caseArrayType(ArrayType t)
{
emit("if_acmple " +
instToLabel.get(i.getTarget()));
}
public void caseRefType(RefType t)
{
emit("if_acmple " +
instToLabel.get(i.getTarget()));
}
public void caseNullType(NullType t)
{
emit("if_acmple " +
instToLabel.get(i.getTarget()));
}
public void defaultCase(Type t)
{
throw new RuntimeException("invalid type");
}
});
}
public void caseStaticGetInst(StaticGetInst i)
{
SootField field = i.getField();
emit("getstatic " +
slashify(field.getDeclaringClass().getName()) + "/" +
field.getName() + " " +
jasminDescriptorOf(field.getType()));
}
public void caseStaticPutInst(StaticPutInst i)
{
emit("putstatic " +
slashify(i.getField().getDeclaringClass().getName()) +
"/" + i.getField().getName() + " " +
jasminDescriptorOf(i.getField().getType()));
}
public void caseFieldGetInst(FieldGetInst i)
{
emit("getfield " +
slashify(i.getField().getDeclaringClass().getName()) +
"/" + i.getField().getName() + " " +
jasminDescriptorOf(i.getField().getType()));
}
public void caseFieldPutInst(FieldPutInst i)
{
emit("putfield " +
slashify(i.getField().getDeclaringClass().getName()) +
"/" + i.getField().getName() + " " +
jasminDescriptorOf(i.getField().getType()));
}
public void caseInstanceCastInst(InstanceCastInst i)
{
Type castType = i.getCastType();
if(castType instanceof RefType)
emit("checkcast " + slashify(castType.toString()));
else if(castType instanceof ArrayType)
emit("checkcast " + jasminDescriptorOf(castType));
}
public void caseInstanceOfInst(InstanceOfInst i)
{
Type checkType = i.getCheckType();
if(checkType instanceof RefType)
emit("instanceof " + slashify(checkType.toString()));
else if(checkType instanceof ArrayType)
emit("instanceof " + jasminDescriptorOf(checkType));
}
public void caseNewInst(NewInst i)
{
emit("new "+slashify(i.getBaseType().toString()));
}
public void casePrimitiveCastInst(PrimitiveCastInst i)
{
emit(i.toString());
}
public void caseStaticInvokeInst(StaticInvokeInst i)
{
SootMethod m = i.getMethod();
emit("invokestatic " + slashify(m.getDeclaringClass().getName()) + "/" +
m.getName() + jasminDescriptorOf(m));
}
public void caseVirtualInvokeInst(VirtualInvokeInst i)
{
SootMethod m = i.getMethod();
emit("invokevirtual " + slashify(m.getDeclaringClass().getName()) + "/" +
m.getName() + jasminDescriptorOf(m));
}
public void caseInterfaceInvokeInst(InterfaceInvokeInst i)
{
SootMethod m = i.getMethod();
emit("invokeinterface " + slashify(m.getDeclaringClass().getName()) + "/" +
m.getName() + jasminDescriptorOf(m) + " " + (argCountOf(m) + 1));
}
public void caseSpecialInvokeInst(SpecialInvokeInst i)
{
SootMethod m = i.getMethod();
emit("invokespecial " + slashify(m.getDeclaringClass().getName()) + "/" +
m.getName() + jasminDescriptorOf(m));
}
public void caseThrowInst(ThrowInst i)
{
emit("athrow");
}
public void caseCmpInst(CmpInst i)
{
emit("lcmp");
}
public void caseCmplInst(CmplInst i)
{
if(i.getOpType().equals(FloatType.v()))
emit("fcmpl");
else
emit("dcmpl");
}
public void caseCmpgInst(CmpgInst i)
{
if(i.getOpType().equals(FloatType.v()))
emit("fcmpg");
else
emit("dcmpg");
}
private void emitOpTypeInst(final String s, final OpTypeArgInst i)
{
i.getOpType().apply(new TypeSwitch()
{
private void handleIntCase()
{
emit("i"+s);
}
public void caseIntType(IntType t) { handleIntCase(); }
public void caseBooleanType(BooleanType t) { handleIntCase(); }
public void caseShortType(ShortType t) { handleIntCase(); }
public void caseCharType(CharType t) { handleIntCase(); }
public void caseByteType(ByteType t) { handleIntCase(); }
public void caseLongType(LongType t)
{
emit("l"+s);
}
public void caseDoubleType(DoubleType t)
{
emit("d"+s);
}
public void caseFloatType(FloatType t)
{
emit("f"+s);
}
public void defaultCase(Type t)
{
throw new RuntimeException("Invalid argument type for div");
}
});
}
public void caseAddInst(AddInst i)
{
emitOpTypeInst("add", i);
}
public void caseDivInst(DivInst i)
{
emitOpTypeInst("div", i);
}
public void caseSubInst(SubInst i)
{
emitOpTypeInst("sub", i);
}
public void caseMulInst(MulInst i)
{
emitOpTypeInst("mul", i);
}
public void caseRemInst(RemInst i)
{
emitOpTypeInst("rem", i);
}
public void caseShlInst(ShlInst i)
{
emitOpTypeInst("shl", i);
}
public void caseAndInst(AndInst i)
{
emitOpTypeInst("and", i);
}
public void caseOrInst(OrInst i)
{
emitOpTypeInst("or", i);
}
public void caseXorInst(XorInst i)
{
emitOpTypeInst("xor", i);
}
public void caseShrInst(ShrInst i)
{
emitOpTypeInst("shr", i);
}
public void caseUshrInst(UshrInst i)
{
emitOpTypeInst("ushr", i);
}
public void caseIncInst(IncInst i)
{
if(((ValueBox) i.getUseBoxes().get(0)).getValue() != ((ValueBox) i.getDefBoxes().get(0)).getValue())
throw new RuntimeException("iinc def and use boxes don't match");
emit("iinc " + ((Integer) localToSlot.get(i.getLocal())) + " " + i.getConstant());
}
public void caseArrayLengthInst(ArrayLengthInst i)
{
emit("arraylength");
}
public void caseNegInst(NegInst i)
{
emitOpTypeInst("neg", i);
}
public void caseNewArrayInst(NewArrayInst i)
{
if(i.getBaseType() instanceof RefType)
emit("anewarray " + slashify(i.getBaseType().toString()));
else if(i.getBaseType() instanceof ArrayType)
emit("anewarray " + jasminDescriptorOf(i.getBaseType()));
else
emit("newarray " + i.getBaseType().toString());
}
public void caseNewMultiArrayInst(NewMultiArrayInst i)
{
emit("multianewarray " + jasminDescriptorOf(i.getBaseType()) + " " +
i.getDimensionCount());
}
public void caseLookupSwitchInst(LookupSwitchInst i)
{
emit("lookupswitch");
List lookupValues = i.getLookupValues();
List targets = i.getTargets();
for(int j = 0; j < lookupValues.size(); j++)
emit(" " + lookupValues.get(j) + " : " +
instToLabel.get(targets.get(j)));
emit(" default : " + instToLabel.get(i.getDefaultTarget()));
}
public void caseTableSwitchInst(TableSwitchInst i)
{
emit("tableswitch " + i.getLowIndex() + " ; high = " + i.getHighIndex());
List targets = i.getTargets();
for(int j = 0; j < targets.size(); j++)
emit(" " + instToLabel.get(targets.get(j)));
emit("default : " + instToLabel.get(i.getDefaultTarget()));
}
private boolean isDwordType(Type t)
{
return t instanceof LongType || t instanceof DoubleType
|| t instanceof DoubleWordType;
}
public void caseDup1Inst(Dup1Inst i)
{
Type firstOpType = i.getOp1Type();
if (isDwordType(firstOpType))
emit("dup2"); // (form 2)
else
emit("dup");
}
public void caseDup2Inst(Dup2Inst i)
{
Type firstOpType = i.getOp1Type();
Type secondOpType = i.getOp2Type();
// The first two cases have no real bytecode equivalents.
// Use a pair of insts to simulate them.
if(isDwordType(firstOpType)) {
emit("dup2"); // (form 2)
if(isDwordType(secondOpType)) {
emit("dup2"); // (form 2 -- by simulation)
} else
emit("dup"); // also a simulation
} else if(isDwordType(secondOpType)) {
if(isDwordType(firstOpType)) {
emit("dup2"); // (form 2)
} else
emit("dup");
emit("dup2"); // (form 2 -- complete the simulation)
} else {
//delme[
G.v().out.println("3000:(JasminClass): dup2 created");
//delme
emit("dup2"); // form 1
}
}
public void caseDup1_x1Inst(Dup1_x1Inst i)
{
Type opType = i.getOp1Type();
Type underType = i.getUnder1Type();
if(isDwordType(opType)) {
if(isDwordType(underType)) {
emit("dup2_x2"); // (form 4)
} else
emit("dup2_x1"); // (form 2)
} else {
if(isDwordType(underType))
emit("dup_x2"); // (form 2)
else
emit("dup_x1"); // (only one form)
}
}
public void caseDup1_x2Inst(Dup1_x2Inst i)
{
Type opType = i.getOpType();
Type under1Type = i.getUnder1Type();
Type under2Type = i.getUnder2Type();
if (isDwordType(opType)) {
if (!isDwordType(under1Type) && !isDwordType(under2Type))
emit("dup2_x2"); // (form 2)
else
throw new RuntimeException("magic not implemented yet");
} else {
if (isDwordType(under1Type) || isDwordType(under2Type))
throw new RuntimeException("magic not implemented yet");
}
emit("dup_x2"); // (form 1)
}
public void caseDup2_x1Inst(Dup2_x1Inst i)
{
Type op1Type = i.getOp1Type();
Type op2Type = i.getOp2Type();
Type under1Type = i.getUnder1Type();
if (isDwordType(under1Type)) {
if (!isDwordType(op1Type) && !isDwordType(under2Type))
throw new RuntimeException("magic not implemented yet");
else
emit("dup2_x2"); // (form 3)
} else {
if (isDwordType(op1Type) || isDwordType(op2Type))
throw new RuntimeException("magic not implemented yet");
}
emit("dup2_x1"); // (form 1)
}
public void caseDup2_x2Inst(Dup2_x2Inst i)
{
Type op1Type = i.getOp1Type();
Type op2Type = i.getOp2Type();
Type under1Type = i.getUnder1Type();
Type under2Type = i.getUnder2Type();
if (isDwordType(op1Type) || isDwordType(op2Type) ||
isDwordType(under1Type) || isDwordType(under1Type))
throw new RuntimeException("magic not implemented yet");
emit("dup2_x2"); // (form 1)
}
public void caseSwapInst(SwapInst i)
{
emit("swap");
}
});
}
| void emitInst(Inst inst)
{
inst.apply(new InstSwitch()
{
public void caseReturnVoidInst(ReturnVoidInst i)
{
emit("return");
}
public void caseReturnInst(ReturnInst i)
{
i.getOpType().apply(new TypeSwitch()
{
public void defaultCase(Type t)
{
throw new RuntimeException("invalid return type " + t.toString());
}
public void caseDoubleType(DoubleType t)
{
emit("dreturn");
}
public void caseFloatType(FloatType t)
{
emit("freturn");
}
public void caseIntType(IntType t)
{
emit("ireturn");
}
public void caseByteType(ByteType t)
{
emit("ireturn");
}
public void caseShortType(ShortType t)
{
emit("ireturn");
}
public void caseCharType(CharType t)
{
emit("ireturn");
}
public void caseBooleanType(BooleanType t)
{
emit("ireturn");
}
public void caseLongType(LongType t)
{
emit("lreturn");
}
public void caseArrayType(ArrayType t)
{
emit("areturn");
}
public void caseRefType(RefType t)
{
emit("areturn");
}
public void caseNullType(NullType t)
{
emit("areturn");
}
});
}
public void caseNopInst(NopInst i) { emit ("nop"); }
public void caseEnterMonitorInst(EnterMonitorInst i)
{
emit ("monitorenter");
}
public void casePopInst(PopInst i)
{
if(i.getWordCount() == 2) {
emit("pop2");
}
else
emit("pop");
}
public void caseExitMonitorInst(ExitMonitorInst i)
{
emit ("monitorexit");
}
public void caseGotoInst(GotoInst i)
{
emit("goto " + instToLabel.get(i.getTarget()));
}
public void casePushInst(PushInst i)
{
if (i.getConstant() instanceof IntConstant)
{
IntConstant v = (IntConstant)(i.getConstant());
if(v.value == -1)
emit("iconst_m1");
else if(v.value >= 0 && v.value <= 5)
emit("iconst_" + v.value);
else if(v.value >= Byte.MIN_VALUE &&
v.value <= Byte.MAX_VALUE)
emit("bipush " + v.value);
else if(v.value >= Short.MIN_VALUE &&
v.value <= Short.MAX_VALUE)
emit("sipush " + v.value);
else
emit("ldc " + v.toString());
}
else if (i.getConstant() instanceof StringConstant)
{
emit("ldc " + i.getConstant().toString());
}
else if (i.getConstant() instanceof DoubleConstant)
{
DoubleConstant v = (DoubleConstant)(i.getConstant());
if(v.value == 0)
emit("dconst_0");
else if(v.value == 1)
emit("dconst_1");
else {
String s = v.toString();
if(s.equals("#Infinity"))
s="+DoubleInfinity";
if(s.equals("#-Infinity"))
s="-DoubleInfinity";
if(s.equals("#NaN"))
s="+DoubleNaN";
emit("ldc2_w " + s);
}
}
else if (i.getConstant() instanceof FloatConstant)
{
FloatConstant v = (FloatConstant)(i.getConstant());
if(v.value == 0)
emit("fconst_0");
else if(v.value == 1)
emit("fconst_1");
else if(v.value == 2)
emit("fconst_2");
else {
String s = v.toString();
if(s.equals("#InfinityF"))
s="+FloatInfinity";
if(s.equals("#-InfinityF"))
s="-FloatInfinity";
if(s.equals("#NaNF"))
s="+FloatNaN";
emit("ldc " + s);
}
}
else if (i.getConstant() instanceof LongConstant)
{
LongConstant v = (LongConstant)(i.getConstant());
if(v.value == 0)
emit("lconst_0");
else if(v.value == 1)
emit("lconst_1");
else
emit("ldc2_w " + v.toString());
}
else if (i.getConstant() instanceof NullConstant)
emit("aconst_null");
else
throw new RuntimeException("unsupported opcode");
}
public void caseIdentityInst(IdentityInst i)
{
if(i.getRightOp() instanceof CaughtExceptionRef &&
i.getLeftOp() instanceof Local)
{
int slot = ((Integer) localToSlot.get(i.getLeftOp())).intValue();
if(slot >= 0 && slot <= 3)
emit("astore_" + slot);
else
emit("astore " + slot);
}
}
public void caseStoreInst(StoreInst i)
{
final int slot =
((Integer) localToSlot.get(i.getLocal())).intValue();
i.getOpType().apply(new TypeSwitch()
{
public void caseArrayType(ArrayType t)
{
if(slot >= 0 && slot <= 3)
emit("astore_" + slot);
else
emit("astore " + slot);
}
public void caseDoubleType(DoubleType t)
{
if(slot >= 0 && slot <= 3)
emit("dstore_" + slot);
else
emit("dstore " + slot);
}
public void caseFloatType(FloatType t)
{
if(slot >= 0 && slot <= 3)
emit("fstore_" + slot);
else
emit("fstore " + slot);
}
public void caseIntType(IntType t)
{
if(slot >= 0 && slot <= 3)
emit("istore_" + slot);
else
emit("istore " + slot);
}
public void caseByteType(ByteType t)
{
if(slot >= 0 && slot <= 3)
emit("istore_" + slot);
else
emit("istore " + slot);
}
public void caseShortType(ShortType t)
{
if(slot >= 0 && slot <= 3)
emit("istore_" + slot);
else
emit("istore " + slot);
}
public void caseCharType(CharType t)
{
if(slot >= 0 && slot <= 3)
emit("istore_" + slot);
else
emit("istore " + slot);
}
public void caseBooleanType(BooleanType t)
{
if(slot >= 0 && slot <= 3)
emit("istore_" + slot);
else
emit("istore " + slot);
}
public void caseLongType(LongType t)
{
if(slot >= 0 && slot <= 3)
emit("lstore_" + slot);
else
emit("lstore " + slot);
}
public void caseRefType(RefType t)
{
if(slot >= 0 && slot <= 3)
emit("astore_" + slot);
else
emit("astore " + slot);
}
public void caseStmtAddressType(StmtAddressType t)
{
isNextGotoAJsr = true;
returnAddressSlot = slot;
/*
if ( slot >= 0 && slot <= 3)
emit("astore_" + slot, );
else
emit("astore " + slot, );
*/
}
public void caseNullType(NullType t)
{
if(slot >= 0 && slot <= 3)
emit("astore_" + slot);
else
emit("astore " + slot);
}
public void defaultCase(Type t)
{
throw new RuntimeException("Invalid local type:"
+ t);
}
});
}
public void caseLoadInst(LoadInst i)
{
final int slot =
((Integer) localToSlot.get(i.getLocal())).intValue();
i.getOpType().apply(new TypeSwitch()
{
public void caseArrayType(ArrayType t)
{
if(slot >= 0 && slot <= 3)
emit("aload_" + slot);
else
emit("aload " + slot);
}
public void defaultCase(Type t)
{
throw new
RuntimeException("invalid local type to load" + t);
}
public void caseDoubleType(DoubleType t)
{
if(slot >= 0 && slot <= 3)
emit("dload_" + slot);
else
emit("dload " + slot);
}
public void caseFloatType(FloatType t)
{
if(slot >= 0 && slot <= 3)
emit("fload_" + slot);
else
emit("fload " + slot);
}
public void caseIntType(IntType t)
{
if(slot >= 0 && slot <= 3)
emit("iload_" + slot);
else
emit("iload " + slot);
}
public void caseByteType(ByteType t)
{
if(slot >= 0 && slot <= 3)
emit("iload_" + slot);
else
emit("iload " + slot);
}
public void caseShortType(ShortType t)
{
if(slot >= 0 && slot <= 3)
emit("iload_" + slot);
else
emit("iload " + slot);
}
public void caseCharType(CharType t)
{
if(slot >= 0 && slot <= 3)
emit("iload_" + slot);
else
emit("iload " + slot);
}
public void caseBooleanType(BooleanType t)
{
if(slot >= 0 && slot <= 3)
emit("iload_" + slot);
else
emit("iload " + slot);
}
public void caseLongType(LongType t)
{
if(slot >= 0 && slot <= 3)
emit("lload_" + slot);
else
emit("lload " + slot);
}
public void caseRefType(RefType t)
{
if(slot >= 0 && slot <= 3)
emit("aload_" + slot);
else
emit("aload " + slot);
}
public void caseNullType(NullType t)
{
if(slot >= 0 && slot <= 3)
emit("aload_" + slot);
else
emit("aload " + slot);
}
});
}
public void caseArrayWriteInst(ArrayWriteInst i)
{
i.getOpType().apply(new TypeSwitch()
{
public void caseArrayType(ArrayType t)
{
emit("aastore");
}
public void caseDoubleType(DoubleType t)
{
emit("dastore");
}
public void caseFloatType(FloatType t)
{
emit("fastore");
}
public void caseIntType(IntType t)
{
emit("iastore");
}
public void caseLongType(LongType t)
{
emit("lastore");
}
public void caseRefType(RefType t)
{
emit("aastore");
}
public void caseByteType(ByteType t)
{
emit("bastore");
}
public void caseBooleanType(BooleanType t)
{
emit("bastore");
}
public void caseCharType(CharType t)
{
emit("castore");
}
public void caseShortType(ShortType t)
{
emit("sastore");
}
public void defaultCase(Type t)
{
throw new RuntimeException("Invalid type: " + t);
}});
}
public void caseArrayReadInst(ArrayReadInst i)
{
i.getOpType().apply(new TypeSwitch()
{
public void caseArrayType(ArrayType ty)
{
emit("aaload");
}
public void caseBooleanType(BooleanType ty)
{
emit("baload");
}
public void caseByteType(ByteType ty)
{
emit("baload");
}
public void caseCharType(CharType ty)
{
emit("caload");
}
public void defaultCase(Type ty)
{
throw new RuntimeException("invalid base type");
}
public void caseDoubleType(DoubleType ty)
{
emit("daload");
}
public void caseFloatType(FloatType ty)
{
emit("faload");
}
public void caseIntType(IntType ty)
{
emit("iaload");
}
public void caseLongType(LongType ty)
{
emit("laload");
}
public void caseNullType(NullType ty)
{
emit("aaload");
}
public void caseRefType(RefType ty)
{
emit("aaload");
}
public void caseShortType(ShortType ty)
{
emit("saload");
}
});
}
public void caseIfNullInst(IfNullInst i)
{
emit("ifnull " + instToLabel.get(i.getTarget()));
}
public void caseIfNonNullInst(IfNonNullInst i)
{
emit("ifnonnull " + instToLabel.get(i.getTarget()));
}
public void caseIfEqInst(IfEqInst i)
{
emit("ifeq " + instToLabel.get(i.getTarget()));
}
public void caseIfNeInst(IfNeInst i)
{
emit("ifne " + instToLabel.get(i.getTarget()));
}
public void caseIfGtInst(IfGtInst i)
{
emit("ifgt " + instToLabel.get(i.getTarget()));
}
public void caseIfGeInst(IfGeInst i)
{
emit("ifge " + instToLabel.get(i.getTarget()));
}
public void caseIfLtInst(IfLtInst i)
{
emit("iflt " + instToLabel.get(i.getTarget()));
}
public void caseIfLeInst(IfLeInst i)
{
emit("ifle " + instToLabel.get(i.getTarget()));
}
public void caseIfCmpEqInst(final IfCmpEqInst i)
{
i.getOpType().apply(new TypeSwitch()
{
public void caseIntType(IntType t)
{
emit("if_icmpeq " +
instToLabel.get(i.getTarget()));
}
public void caseBooleanType(BooleanType t)
{
emit("if_icmpeq " +
instToLabel.get(i.getTarget()));
}
public void caseShortType(ShortType t)
{
emit("if_icmpeq " +
instToLabel.get(i.getTarget()));
}
public void caseCharType(CharType t)
{
emit("if_icmpeq " +
instToLabel.get(i.getTarget()));
}
public void caseByteType(ByteType t)
{
emit("if_icmpeq " +
instToLabel.get(i.getTarget()));
}
public void caseDoubleType(DoubleType t)
{
emit("dcmpg");
emit("ifeq " +
instToLabel.get(i.getTarget()));
}
public void caseLongType(LongType t)
{
emit("lcmp");
emit("ifeq " +
instToLabel.get(i.getTarget()));
}
public void caseFloatType(FloatType t)
{
emit("fcmpg");
emit("ifeq " +
instToLabel.get(i.getTarget()));
}
public void caseArrayType(ArrayType t)
{
emit("if_acmpeq " +
instToLabel.get(i.getTarget()));
}
public void caseRefType(RefType t)
{
emit("if_acmpeq " +
instToLabel.get(i.getTarget()));
}
public void caseNullType(NullType t)
{
emit("if_acmpeq " +
instToLabel.get(i.getTarget()));
}
public void defaultCase(Type t)
{
throw new RuntimeException("invalid type");
}
});
}
public void caseIfCmpNeInst(final IfCmpNeInst i)
{
i.getOpType().apply(new TypeSwitch()
{
public void caseIntType(IntType t)
{
emit("if_icmpne " +
instToLabel.get(i.getTarget()));
}
public void caseBooleanType(BooleanType t)
{
emit("if_icmpne " +
instToLabel.get(i.getTarget()));
}
public void caseShortType(ShortType t)
{
emit("if_icmpne " +
instToLabel.get(i.getTarget()));
}
public void caseCharType(CharType t)
{
emit("if_icmpne " +
instToLabel.get(i.getTarget()));
}
public void caseByteType(ByteType t)
{
emit("if_icmpne " +
instToLabel.get(i.getTarget()));
}
public void caseDoubleType(DoubleType t)
{
emit("dcmpg");
emit("ifne " +
instToLabel.get(i.getTarget()));
}
public void caseLongType(LongType t)
{
emit("lcmp");
emit("ifne " +
instToLabel.get(i.getTarget()));
}
public void caseFloatType(FloatType t)
{
emit("fcmpg");
emit("ifne " +
instToLabel.get(i.getTarget()));
}
public void caseArrayType(ArrayType t)
{
emit("if_acmpne " +
instToLabel.get(i.getTarget()));
}
public void caseRefType(RefType t)
{
emit("if_acmpne " +
instToLabel.get(i.getTarget()));
}
public void caseNullType(NullType t)
{
emit("if_acmpne " +
instToLabel.get(i.getTarget()));
}
public void defaultCase(Type t)
{
throw new RuntimeException("invalid type");
}
});
}
public void caseIfCmpGtInst(final IfCmpGtInst i)
{
i.getOpType().apply(new TypeSwitch()
{
public void caseIntType(IntType t)
{
emit("if_icmpgt " +
instToLabel.get(i.getTarget()));
}
public void caseBooleanType(BooleanType t)
{
emit("if_icmpgt " +
instToLabel.get(i.getTarget()));
}
public void caseShortType(ShortType t)
{
emit("if_icmpgt " +
instToLabel.get(i.getTarget()));
}
public void caseCharType(CharType t)
{
emit("if_icmpgt " +
instToLabel.get(i.getTarget()));
}
public void caseByteType(ByteType t)
{
emit("if_icmpgt " +
instToLabel.get(i.getTarget()));
}
public void caseDoubleType(DoubleType t)
{
emit("dcmpg");
emit("ifgt " +
instToLabel.get(i.getTarget()));
}
public void caseLongType(LongType t)
{
emit("lcmp");
emit("ifgt " +
instToLabel.get(i.getTarget()));
}
public void caseFloatType(FloatType t)
{
emit("fcmpg");
emit("ifgt " +
instToLabel.get(i.getTarget()));
}
public void caseArrayType(ArrayType t)
{
emit("if_acmpgt " +
instToLabel.get(i.getTarget()));
}
public void caseRefType(RefType t)
{
emit("if_acmpgt " +
instToLabel.get(i.getTarget()));
}
public void caseNullType(NullType t)
{
emit("if_acmpgt " +
instToLabel.get(i.getTarget()));
}
public void defaultCase(Type t)
{
throw new RuntimeException("invalid type");
}
});
}
public void caseIfCmpGeInst(final IfCmpGeInst i)
{
i.getOpType().apply(new TypeSwitch()
{
public void caseIntType(IntType t)
{
emit("if_icmpge " +
instToLabel.get(i.getTarget()));
}
public void caseBooleanType(BooleanType t)
{
emit("if_icmpge " +
instToLabel.get(i.getTarget()));
}
public void caseShortType(ShortType t)
{
emit("if_icmpge " +
instToLabel.get(i.getTarget()));
}
public void caseCharType(CharType t)
{
emit("if_icmpge " +
instToLabel.get(i.getTarget()));
}
public void caseByteType(ByteType t)
{
emit("if_icmpge " +
instToLabel.get(i.getTarget()));
}
public void caseDoubleType(DoubleType t)
{
emit("dcmpg");
emit("ifge " +
instToLabel.get(i.getTarget()));
}
public void caseLongType(LongType t)
{
emit("lcmp");
emit("ifge " +
instToLabel.get(i.getTarget()));
}
public void caseFloatType(FloatType t)
{
emit("fcmpg");
emit("ifge " +
instToLabel.get(i.getTarget()));
}
public void caseArrayType(ArrayType t)
{
emit("if_acmpge " +
instToLabel.get(i.getTarget()));
}
public void caseRefType(RefType t)
{
emit("if_acmpge " +
instToLabel.get(i.getTarget()));
}
public void caseNullType(NullType t)
{
emit("if_acmpge " +
instToLabel.get(i.getTarget()));
}
public void defaultCase(Type t)
{
throw new RuntimeException("invalid type");
}
});
}
public void caseIfCmpLtInst(final IfCmpLtInst i)
{
i.getOpType().apply(new TypeSwitch()
{
public void caseIntType(IntType t)
{
emit("if_icmplt " +
instToLabel.get(i.getTarget()));
}
public void caseBooleanType(BooleanType t)
{
emit("if_icmplt " +
instToLabel.get(i.getTarget()));
}
public void caseShortType(ShortType t)
{
emit("if_icmplt " +
instToLabel.get(i.getTarget()));
}
public void caseCharType(CharType t)
{
emit("if_icmplt " +
instToLabel.get(i.getTarget()));
}
public void caseByteType(ByteType t)
{
emit("if_icmplt " +
instToLabel.get(i.getTarget()));
}
public void caseDoubleType(DoubleType t)
{
emit("dcmpg");
emit("iflt " +
instToLabel.get(i.getTarget()));
}
public void caseLongType(LongType t)
{
emit("lcmp");
emit("iflt " +
instToLabel.get(i.getTarget()));
}
public void caseFloatType(FloatType t)
{
emit("fcmpg");
emit("iflt " +
instToLabel.get(i.getTarget()));
}
public void caseArrayType(ArrayType t)
{
emit("if_acmplt " +
instToLabel.get(i.getTarget()));
}
public void caseRefType(RefType t)
{
emit("if_acmplt " +
instToLabel.get(i.getTarget()));
}
public void caseNullType(NullType t)
{
emit("if_acmplt " +
instToLabel.get(i.getTarget()));
}
public void defaultCase(Type t)
{
throw new RuntimeException("invalid type");
}
});
}
public void caseIfCmpLeInst(final IfCmpLeInst i)
{
i.getOpType().apply(new TypeSwitch()
{
public void caseIntType(IntType t)
{
emit("if_icmple " +
instToLabel.get(i.getTarget()));
}
public void caseBooleanType(BooleanType t)
{
emit("if_icmple " +
instToLabel.get(i.getTarget()));
}
public void caseShortType(ShortType t)
{
emit("if_icmple " +
instToLabel.get(i.getTarget()));
}
public void caseCharType(CharType t)
{
emit("if_icmple " +
instToLabel.get(i.getTarget()));
}
public void caseByteType(ByteType t)
{
emit("if_icmple " +
instToLabel.get(i.getTarget()));
}
public void caseDoubleType(DoubleType t)
{
emit("dcmpg");
emit("ifle " +
instToLabel.get(i.getTarget()));
}
public void caseLongType(LongType t)
{
emit("lcmp");
emit("ifle " +
instToLabel.get(i.getTarget()));
}
public void caseFloatType(FloatType t)
{
emit("fcmpg");
emit("ifle " +
instToLabel.get(i.getTarget()));
}
public void caseArrayType(ArrayType t)
{
emit("if_acmple " +
instToLabel.get(i.getTarget()));
}
public void caseRefType(RefType t)
{
emit("if_acmple " +
instToLabel.get(i.getTarget()));
}
public void caseNullType(NullType t)
{
emit("if_acmple " +
instToLabel.get(i.getTarget()));
}
public void defaultCase(Type t)
{
throw new RuntimeException("invalid type");
}
});
}
public void caseStaticGetInst(StaticGetInst i)
{
SootField field = i.getField();
emit("getstatic " +
slashify(field.getDeclaringClass().getName()) + "/" +
field.getName() + " " +
jasminDescriptorOf(field.getType()));
}
public void caseStaticPutInst(StaticPutInst i)
{
emit("putstatic " +
slashify(i.getField().getDeclaringClass().getName()) +
"/" + i.getField().getName() + " " +
jasminDescriptorOf(i.getField().getType()));
}
public void caseFieldGetInst(FieldGetInst i)
{
emit("getfield " +
slashify(i.getField().getDeclaringClass().getName()) +
"/" + i.getField().getName() + " " +
jasminDescriptorOf(i.getField().getType()));
}
public void caseFieldPutInst(FieldPutInst i)
{
emit("putfield " +
slashify(i.getField().getDeclaringClass().getName()) +
"/" + i.getField().getName() + " " +
jasminDescriptorOf(i.getField().getType()));
}
public void caseInstanceCastInst(InstanceCastInst i)
{
Type castType = i.getCastType();
if(castType instanceof RefType)
emit("checkcast " + slashify(castType.toString()));
else if(castType instanceof ArrayType)
emit("checkcast " + jasminDescriptorOf(castType));
}
public void caseInstanceOfInst(InstanceOfInst i)
{
Type checkType = i.getCheckType();
if(checkType instanceof RefType)
emit("instanceof " + slashify(checkType.toString()));
else if(checkType instanceof ArrayType)
emit("instanceof " + jasminDescriptorOf(checkType));
}
public void caseNewInst(NewInst i)
{
emit("new "+slashify(i.getBaseType().toString()));
}
public void casePrimitiveCastInst(PrimitiveCastInst i)
{
emit(i.toString());
}
public void caseStaticInvokeInst(StaticInvokeInst i)
{
SootMethod m = i.getMethod();
emit("invokestatic " + slashify(m.getDeclaringClass().getName()) + "/" +
m.getName() + jasminDescriptorOf(m));
}
public void caseVirtualInvokeInst(VirtualInvokeInst i)
{
SootMethod m = i.getMethod();
emit("invokevirtual " + slashify(m.getDeclaringClass().getName()) + "/" +
m.getName() + jasminDescriptorOf(m));
}
public void caseInterfaceInvokeInst(InterfaceInvokeInst i)
{
SootMethod m = i.getMethod();
emit("invokeinterface " + slashify(m.getDeclaringClass().getName()) + "/" +
m.getName() + jasminDescriptorOf(m) + " " + (argCountOf(m) + 1));
}
public void caseSpecialInvokeInst(SpecialInvokeInst i)
{
SootMethod m = i.getMethod();
emit("invokespecial " + slashify(m.getDeclaringClass().getName()) + "/" +
m.getName() + jasminDescriptorOf(m));
}
public void caseThrowInst(ThrowInst i)
{
emit("athrow");
}
public void caseCmpInst(CmpInst i)
{
emit("lcmp");
}
public void caseCmplInst(CmplInst i)
{
if(i.getOpType().equals(FloatType.v()))
emit("fcmpl");
else
emit("dcmpl");
}
public void caseCmpgInst(CmpgInst i)
{
if(i.getOpType().equals(FloatType.v()))
emit("fcmpg");
else
emit("dcmpg");
}
private void emitOpTypeInst(final String s, final OpTypeArgInst i)
{
i.getOpType().apply(new TypeSwitch()
{
private void handleIntCase()
{
emit("i"+s);
}
public void caseIntType(IntType t) { handleIntCase(); }
public void caseBooleanType(BooleanType t) { handleIntCase(); }
public void caseShortType(ShortType t) { handleIntCase(); }
public void caseCharType(CharType t) { handleIntCase(); }
public void caseByteType(ByteType t) { handleIntCase(); }
public void caseLongType(LongType t)
{
emit("l"+s);
}
public void caseDoubleType(DoubleType t)
{
emit("d"+s);
}
public void caseFloatType(FloatType t)
{
emit("f"+s);
}
public void defaultCase(Type t)
{
throw new RuntimeException("Invalid argument type for div");
}
});
}
public void caseAddInst(AddInst i)
{
emitOpTypeInst("add", i);
}
public void caseDivInst(DivInst i)
{
emitOpTypeInst("div", i);
}
public void caseSubInst(SubInst i)
{
emitOpTypeInst("sub", i);
}
public void caseMulInst(MulInst i)
{
emitOpTypeInst("mul", i);
}
public void caseRemInst(RemInst i)
{
emitOpTypeInst("rem", i);
}
public void caseShlInst(ShlInst i)
{
emitOpTypeInst("shl", i);
}
public void caseAndInst(AndInst i)
{
emitOpTypeInst("and", i);
}
public void caseOrInst(OrInst i)
{
emitOpTypeInst("or", i);
}
public void caseXorInst(XorInst i)
{
emitOpTypeInst("xor", i);
}
public void caseShrInst(ShrInst i)
{
emitOpTypeInst("shr", i);
}
public void caseUshrInst(UshrInst i)
{
emitOpTypeInst("ushr", i);
}
public void caseIncInst(IncInst i)
{
if(((ValueBox) i.getUseBoxes().get(0)).getValue() != ((ValueBox) i.getDefBoxes().get(0)).getValue())
throw new RuntimeException("iinc def and use boxes don't match");
emit("iinc " + ((Integer) localToSlot.get(i.getLocal())) + " " + i.getConstant());
}
public void caseArrayLengthInst(ArrayLengthInst i)
{
emit("arraylength");
}
public void caseNegInst(NegInst i)
{
emitOpTypeInst("neg", i);
}
public void caseNewArrayInst(NewArrayInst i)
{
if(i.getBaseType() instanceof RefType)
emit("anewarray " + slashify(i.getBaseType().toString()));
else if(i.getBaseType() instanceof ArrayType)
emit("anewarray " + jasminDescriptorOf(i.getBaseType()));
else
emit("newarray " + i.getBaseType().toString());
}
public void caseNewMultiArrayInst(NewMultiArrayInst i)
{
emit("multianewarray " + jasminDescriptorOf(i.getBaseType()) + " " +
i.getDimensionCount());
}
public void caseLookupSwitchInst(LookupSwitchInst i)
{
emit("lookupswitch");
List lookupValues = i.getLookupValues();
List targets = i.getTargets();
for(int j = 0; j < lookupValues.size(); j++)
emit(" " + lookupValues.get(j) + " : " +
instToLabel.get(targets.get(j)));
emit(" default : " + instToLabel.get(i.getDefaultTarget()));
}
public void caseTableSwitchInst(TableSwitchInst i)
{
emit("tableswitch " + i.getLowIndex() + " ; high = " + i.getHighIndex());
List targets = i.getTargets();
for(int j = 0; j < targets.size(); j++)
emit(" " + instToLabel.get(targets.get(j)));
emit("default : " + instToLabel.get(i.getDefaultTarget()));
}
private boolean isDwordType(Type t)
{
return t instanceof LongType || t instanceof DoubleType
|| t instanceof DoubleWordType;
}
public void caseDup1Inst(Dup1Inst i)
{
Type firstOpType = i.getOp1Type();
if (isDwordType(firstOpType))
emit("dup2"); // (form 2)
else
emit("dup");
}
public void caseDup2Inst(Dup2Inst i)
{
Type firstOpType = i.getOp1Type();
Type secondOpType = i.getOp2Type();
// The first two cases have no real bytecode equivalents.
// Use a pair of insts to simulate them.
if(isDwordType(firstOpType)) {
emit("dup2"); // (form 2)
if(isDwordType(secondOpType)) {
emit("dup2"); // (form 2 -- by simulation)
} else
emit("dup"); // also a simulation
} else if(isDwordType(secondOpType)) {
if(isDwordType(firstOpType)) {
emit("dup2"); // (form 2)
} else
emit("dup");
emit("dup2"); // (form 2 -- complete the simulation)
} else {
//delme[
G.v().out.println("3000:(JasminClass): dup2 created");
//delme
emit("dup2"); // form 1
}
}
public void caseDup1_x1Inst(Dup1_x1Inst i)
{
Type opType = i.getOp1Type();
Type underType = i.getUnder1Type();
if(isDwordType(opType)) {
if(isDwordType(underType)) {
emit("dup2_x2"); // (form 4)
} else
emit("dup2_x1"); // (form 2)
} else {
if(isDwordType(underType))
emit("dup_x2"); // (form 2)
else
emit("dup_x1"); // (only one form)
}
}
public void caseDup1_x2Inst(Dup1_x2Inst i)
{
Type opType = i.getOp1Type();
Type under1Type = i.getUnder1Type();
Type under2Type = i.getUnder2Type();
if (isDwordType(opType)) {
if (!isDwordType(under1Type) && !isDwordType(under2Type))
emit("dup2_x2"); // (form 2)
else
throw new RuntimeException("magic not implemented yet");
} else {
if (isDwordType(under1Type) || isDwordType(under2Type))
throw new RuntimeException("magic not implemented yet");
}
emit("dup_x2"); // (form 1)
}
public void caseDup2_x1Inst(Dup2_x1Inst i)
{
Type op1Type = i.getOp1Type();
Type op2Type = i.getOp2Type();
Type under1Type = i.getUnder1Type();
if (isDwordType(under1Type)) {
if (!isDwordType(op1Type) && !isDwordType(op2Type))
throw new RuntimeException("magic not implemented yet");
else
emit("dup2_x2"); // (form 3)
} else {
if (isDwordType(op1Type) || isDwordType(op2Type))
throw new RuntimeException("magic not implemented yet");
}
emit("dup2_x1"); // (form 1)
}
public void caseDup2_x2Inst(Dup2_x2Inst i)
{
Type op1Type = i.getOp1Type();
Type op2Type = i.getOp2Type();
Type under1Type = i.getUnder1Type();
Type under2Type = i.getUnder2Type();
if (isDwordType(op1Type) || isDwordType(op2Type) ||
isDwordType(under1Type) || isDwordType(under1Type))
throw new RuntimeException("magic not implemented yet");
emit("dup2_x2"); // (form 1)
}
public void caseSwapInst(SwapInst i)
{
emit("swap");
}
});
}
|
diff --git a/src/main/java/fr/xebia/management/config/ManagedCachingConnectionFactoryDefinitionParser.java b/src/main/java/fr/xebia/management/config/ManagedCachingConnectionFactoryDefinitionParser.java
index 4feaf63..8a181b1 100644
--- a/src/main/java/fr/xebia/management/config/ManagedCachingConnectionFactoryDefinitionParser.java
+++ b/src/main/java/fr/xebia/management/config/ManagedCachingConnectionFactoryDefinitionParser.java
@@ -1,52 +1,52 @@
/*
* Copyright 2008-2010 Xebia and 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 fr.xebia.management.config;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.AbstractBeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.w3c.dom.Element;
import fr.xebia.springframework.jms.ManagedCachingConnectionFactory;
public class ManagedCachingConnectionFactoryDefinitionParser extends AbstractBeanDefinitionParser {
private static final String CONNECTION_FACTORY_ATTRIBUTE = "connection-factory";
private static final String CACHE_CONSUMERS_ATTRIBUTE = "cache-consumers";
private static final String CACHE_PRODUCERS_ATTRIBUTE = "cache-producers";
private static final String SESSION_CACHE_SIZE_ATTRIBUTE = "session-cache-size";
private static final String RECONNECT_ON_EXCEPTION = "reconnect-on-exception";
@Override
protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) {
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(ManagedCachingConnectionFactory.class);
builder.setRole(BeanDefinition.ROLE_APPLICATION);
builder.getRawBeanDefinition().setSource(parserContext.extractSource(element));
- builder.addPropertyReference("connectionFactory", element.getAttribute(CONNECTION_FACTORY_ATTRIBUTE));
+ builder.addPropertyReference("targetConnectionFactory", element.getAttribute(CONNECTION_FACTORY_ATTRIBUTE));
builder.addPropertyValue("cacheConsumers", element.getAttribute(CACHE_CONSUMERS_ATTRIBUTE));
builder.addPropertyValue("cacheProducers", element.getAttribute(CACHE_PRODUCERS_ATTRIBUTE));
builder.addPropertyValue("sessionCacheSize", element.getAttribute(SESSION_CACHE_SIZE_ATTRIBUTE));
builder.addPropertyValue("reconnectOnException", element.getAttribute(RECONNECT_ON_EXCEPTION));
return builder.getBeanDefinition();
}
}
| true | true | protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) {
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(ManagedCachingConnectionFactory.class);
builder.setRole(BeanDefinition.ROLE_APPLICATION);
builder.getRawBeanDefinition().setSource(parserContext.extractSource(element));
builder.addPropertyReference("connectionFactory", element.getAttribute(CONNECTION_FACTORY_ATTRIBUTE));
builder.addPropertyValue("cacheConsumers", element.getAttribute(CACHE_CONSUMERS_ATTRIBUTE));
builder.addPropertyValue("cacheProducers", element.getAttribute(CACHE_PRODUCERS_ATTRIBUTE));
builder.addPropertyValue("sessionCacheSize", element.getAttribute(SESSION_CACHE_SIZE_ATTRIBUTE));
builder.addPropertyValue("reconnectOnException", element.getAttribute(RECONNECT_ON_EXCEPTION));
return builder.getBeanDefinition();
}
| protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) {
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(ManagedCachingConnectionFactory.class);
builder.setRole(BeanDefinition.ROLE_APPLICATION);
builder.getRawBeanDefinition().setSource(parserContext.extractSource(element));
builder.addPropertyReference("targetConnectionFactory", element.getAttribute(CONNECTION_FACTORY_ATTRIBUTE));
builder.addPropertyValue("cacheConsumers", element.getAttribute(CACHE_CONSUMERS_ATTRIBUTE));
builder.addPropertyValue("cacheProducers", element.getAttribute(CACHE_PRODUCERS_ATTRIBUTE));
builder.addPropertyValue("sessionCacheSize", element.getAttribute(SESSION_CACHE_SIZE_ATTRIBUTE));
builder.addPropertyValue("reconnectOnException", element.getAttribute(RECONNECT_ON_EXCEPTION));
return builder.getBeanDefinition();
}
|
diff --git a/src/openblocks/utils/InventoryUtils.java b/src/openblocks/utils/InventoryUtils.java
index b9fabd28..bd45a05b 100644
--- a/src/openblocks/utils/InventoryUtils.java
+++ b/src/openblocks/utils/InventoryUtils.java
@@ -1,80 +1,80 @@
package openblocks.utils;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
public class InventoryUtils {
public static void tryMergeStacks(IInventory targetInventory, int slot, ItemStack stack) {
- if (targetInventory.isStackValidForSlot(slot, stack)) {
+ if (targetInventory.isItemValidForSlot(slot, stack)) {
ItemStack targetStack = targetInventory.getStackInSlot(slot);
if (targetStack == null) {
targetInventory.setInventorySlotContents(slot, stack.copy());
stack.stackSize = 0;
} else {
- boolean valid = targetInventory.isStackValidForSlot(slot, stack);
+ boolean valid = targetInventory.isItemValidForSlot(slot, stack);
if (valid
&& stack.itemID == targetStack.itemID
&& (!stack.getHasSubtypes() || stack.getItemDamage() == targetStack.getItemDamage())
&& ItemStack.areItemStackTagsEqual(stack, targetStack)
&& targetStack.stackSize < targetStack.getMaxStackSize()) {
int space = targetStack.getMaxStackSize()
- targetStack.stackSize;
int mergeAmount = Math.min(space, stack.stackSize);
ItemStack copy = targetStack.copy();
copy.stackSize += mergeAmount;
targetInventory.setInventorySlotContents(slot, copy);
stack.stackSize -= mergeAmount;
}
}
}
}
public static void insertItemIntoInventory(IInventory inventory, ItemStack stack) {
int i = 0;
while (stack.stackSize > 0 && i < inventory.getSizeInventory()) {
tryMergeStacks(inventory, i, stack);
i++;
}
}
public static int moveItemInto(IInventory fromInventory, int slot, IInventory targetInventory, int intoSlot, int maxAmount) {
int merged = 0;
ItemStack stack = fromInventory.getStackInSlot(slot);
if (stack == null) { return merged; }
ItemStack clonedStack = stack.copy();
clonedStack.stackSize = Math.min(clonedStack.stackSize, maxAmount);
int amountToMerge = clonedStack.stackSize;
InventoryUtils.tryMergeStacks(targetInventory, intoSlot, clonedStack);
merged = (amountToMerge - clonedStack.stackSize);
fromInventory.decrStackSize(slot, merged);
return merged;
}
public static int moveItem(IInventory fromInventory, int slot, IInventory targetInventory, int maxAmount) {
int merged = 0;
ItemStack stack = fromInventory.getStackInSlot(slot);
if (stack == null) { return 0; }
ItemStack clonedStack = stack.copy();
clonedStack.stackSize = Math.min(clonedStack.stackSize, maxAmount);
int amountToMerge = clonedStack.stackSize;
InventoryUtils.insertItemIntoInventory(targetInventory, clonedStack);
merged = (amountToMerge - clonedStack.stackSize);
fromInventory.decrStackSize(slot, merged);
return merged;
}
public static boolean consumeInventoryItem(IInventory inventory, ItemStack stack) {
for (int i = 0; i < inventory.getSizeInventory(); i++) {
ItemStack stackInSlot = inventory.getStackInSlot(i);
if (stackInSlot != null && stackInSlot.isItemEqual(stack)) {
stackInSlot.stackSize--;
if (stackInSlot.stackSize == 0) {
inventory.setInventorySlotContents(i, null);
}
return true;
}
}
return false;
}
}
| false | true | public static void tryMergeStacks(IInventory targetInventory, int slot, ItemStack stack) {
if (targetInventory.isStackValidForSlot(slot, stack)) {
ItemStack targetStack = targetInventory.getStackInSlot(slot);
if (targetStack == null) {
targetInventory.setInventorySlotContents(slot, stack.copy());
stack.stackSize = 0;
} else {
boolean valid = targetInventory.isStackValidForSlot(slot, stack);
if (valid
&& stack.itemID == targetStack.itemID
&& (!stack.getHasSubtypes() || stack.getItemDamage() == targetStack.getItemDamage())
&& ItemStack.areItemStackTagsEqual(stack, targetStack)
&& targetStack.stackSize < targetStack.getMaxStackSize()) {
int space = targetStack.getMaxStackSize()
- targetStack.stackSize;
int mergeAmount = Math.min(space, stack.stackSize);
ItemStack copy = targetStack.copy();
copy.stackSize += mergeAmount;
targetInventory.setInventorySlotContents(slot, copy);
stack.stackSize -= mergeAmount;
}
}
}
}
| public static void tryMergeStacks(IInventory targetInventory, int slot, ItemStack stack) {
if (targetInventory.isItemValidForSlot(slot, stack)) {
ItemStack targetStack = targetInventory.getStackInSlot(slot);
if (targetStack == null) {
targetInventory.setInventorySlotContents(slot, stack.copy());
stack.stackSize = 0;
} else {
boolean valid = targetInventory.isItemValidForSlot(slot, stack);
if (valid
&& stack.itemID == targetStack.itemID
&& (!stack.getHasSubtypes() || stack.getItemDamage() == targetStack.getItemDamage())
&& ItemStack.areItemStackTagsEqual(stack, targetStack)
&& targetStack.stackSize < targetStack.getMaxStackSize()) {
int space = targetStack.getMaxStackSize()
- targetStack.stackSize;
int mergeAmount = Math.min(space, stack.stackSize);
ItemStack copy = targetStack.copy();
copy.stackSize += mergeAmount;
targetInventory.setInventorySlotContents(slot, copy);
stack.stackSize -= mergeAmount;
}
}
}
}
|
diff --git a/webapp/src/org/intermine/bio/web/widget/PwStatURLQuery.java b/webapp/src/org/intermine/bio/web/widget/PwStatURLQuery.java
index 28d8148..a76766e 100644
--- a/webapp/src/org/intermine/bio/web/widget/PwStatURLQuery.java
+++ b/webapp/src/org/intermine/bio/web/widget/PwStatURLQuery.java
@@ -1,82 +1,82 @@
package org.intermine.bio.web.widget;
/*
* Copyright (C) 2002-2009 FlyMine
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. See the LICENSE file for more
* information or http://www.gnu.org/copyleft/lesser.html.
*
*/
import org.intermine.objectstore.ObjectStore;
import org.intermine.pathquery.Constraints;
import org.intermine.pathquery.PathQuery;
import org.intermine.web.logic.bag.InterMineBag;
import org.intermine.web.logic.widget.WidgetURLQuery;
/**
* {@inheritDoc}
* @author Julie Sullivan
*/
public class PwStatURLQuery implements WidgetURLQuery
{
//private static final Logger LOG = Logger.getLogger(GoStatURLQuery.class);
private ObjectStore os;
private InterMineBag bag;
private String key;
/**
* @param os object store
* @param key go terms user selected
* @param bag bag page they were on
*/
public PwStatURLQuery(ObjectStore os, InterMineBag bag, String key) {
this.bag = bag;
this.key = key;
this.os = os;
}
/**
* {@inheritDoc}
*/
public PathQuery generatePathQuery() {
PathQuery q = new PathQuery(os.getModel());
String bagType = bag.getType();
String pathStrings = "";
String prefix = (bagType.equals("Protein") ? "Protein.genes" : "Gene");
if (bagType.equals("Protein")) {
pathStrings = "Protein.primaryAccession,";
}
pathStrings += prefix + ".primaryIdentifier,"
+ prefix + ".symbol,"
+ prefix + ".organism.name,"
- + prefix + ".pwAnnotation.PWTerm.identifier,"
- + prefix + ".pwAnnotation.PWTerm.name,"
- + prefix + ".pwAnnotation.PWTerm.relations.parentTerm.identifier,"
- + prefix + ".pwAnnotation.PWTerm.relations.parentTerm.name";
+ + prefix + ".pwAnnotation.ontologyTerm.identifier,"
+ + prefix + ".pwAnnotation.ontologyTerm.name,"
+ + prefix + ".pwAnnotation.ontologyTerm.relations.parentTerm.identifier,"
+ + prefix + ".pwAnnotation.ontologyTerm.relations.parentTerm.name";
q.setView(pathStrings);
q.setOrderBy(pathStrings);
q.addConstraint(bagType, Constraints.in(bag.getName()));
// can't be a NOT relationship!
String pathString = prefix + ".pwAnnotation.qualifier";
q.addConstraint(pathString, Constraints.isNull());
// go term
- pathString = prefix + ".pwAnnotation.PWTerm.relations.parentTerm";
+ pathString = prefix + ".pwAnnotation.ontologyTerm.relations.parentTerm";
q.addConstraint(pathString, Constraints.lookup(key), "C", "PWTerm");
q.setConstraintLogic("A and B and C");
q.syncLogicExpression("and");
return q;
}
}
| false | true | public PathQuery generatePathQuery() {
PathQuery q = new PathQuery(os.getModel());
String bagType = bag.getType();
String pathStrings = "";
String prefix = (bagType.equals("Protein") ? "Protein.genes" : "Gene");
if (bagType.equals("Protein")) {
pathStrings = "Protein.primaryAccession,";
}
pathStrings += prefix + ".primaryIdentifier,"
+ prefix + ".symbol,"
+ prefix + ".organism.name,"
+ prefix + ".pwAnnotation.PWTerm.identifier,"
+ prefix + ".pwAnnotation.PWTerm.name,"
+ prefix + ".pwAnnotation.PWTerm.relations.parentTerm.identifier,"
+ prefix + ".pwAnnotation.PWTerm.relations.parentTerm.name";
q.setView(pathStrings);
q.setOrderBy(pathStrings);
q.addConstraint(bagType, Constraints.in(bag.getName()));
// can't be a NOT relationship!
String pathString = prefix + ".pwAnnotation.qualifier";
q.addConstraint(pathString, Constraints.isNull());
// go term
pathString = prefix + ".pwAnnotation.PWTerm.relations.parentTerm";
q.addConstraint(pathString, Constraints.lookup(key), "C", "PWTerm");
q.setConstraintLogic("A and B and C");
q.syncLogicExpression("and");
return q;
}
| public PathQuery generatePathQuery() {
PathQuery q = new PathQuery(os.getModel());
String bagType = bag.getType();
String pathStrings = "";
String prefix = (bagType.equals("Protein") ? "Protein.genes" : "Gene");
if (bagType.equals("Protein")) {
pathStrings = "Protein.primaryAccession,";
}
pathStrings += prefix + ".primaryIdentifier,"
+ prefix + ".symbol,"
+ prefix + ".organism.name,"
+ prefix + ".pwAnnotation.ontologyTerm.identifier,"
+ prefix + ".pwAnnotation.ontologyTerm.name,"
+ prefix + ".pwAnnotation.ontologyTerm.relations.parentTerm.identifier,"
+ prefix + ".pwAnnotation.ontologyTerm.relations.parentTerm.name";
q.setView(pathStrings);
q.setOrderBy(pathStrings);
q.addConstraint(bagType, Constraints.in(bag.getName()));
// can't be a NOT relationship!
String pathString = prefix + ".pwAnnotation.qualifier";
q.addConstraint(pathString, Constraints.isNull());
// go term
pathString = prefix + ".pwAnnotation.ontologyTerm.relations.parentTerm";
q.addConstraint(pathString, Constraints.lookup(key), "C", "PWTerm");
q.setConstraintLogic("A and B and C");
q.syncLogicExpression("and");
return q;
}
|
diff --git a/drools-analytics/src/test/java/org/drools/analytics/redundancy/NotesTest.java b/drools-analytics/src/test/java/org/drools/analytics/redundancy/NotesTest.java
index 5e83d7f51d..1fa48ea421 100644
--- a/drools-analytics/src/test/java/org/drools/analytics/redundancy/NotesTest.java
+++ b/drools-analytics/src/test/java/org/drools/analytics/redundancy/NotesTest.java
@@ -1,58 +1,59 @@
package org.drools.analytics.redundancy;
import java.util.ArrayList;
import java.util.Collection;
import org.drools.StatelessSession;
import org.drools.analytics.TestBase;
import org.drools.analytics.components.LiteralRestriction;
import org.drools.analytics.components.PatternPossibility;
import org.drools.analytics.dao.AnalyticsDataFactory;
import org.drools.analytics.dao.AnalyticsResult;
import org.drools.analytics.report.components.AnalyticsMessage;
import org.drools.analytics.report.components.AnalyticsMessageBase;
import org.drools.analytics.report.components.Redundancy;
import org.drools.base.RuleNameMatchesAgendaFilter;
public class NotesTest extends TestBase {
public void testRedundantRestrictionsInPatternPossibilities()
throws Exception {
StatelessSession session = getStatelessSession(this.getClass()
.getResourceAsStream("Notes.drl"));
session.setAgendaFilter(new RuleNameMatchesAgendaFilter(
"Find redundant restrictions from pattern possibilities"));
Collection<Object> objects = new ArrayList<Object>();
LiteralRestriction left = new LiteralRestriction();
LiteralRestriction right = new LiteralRestriction();
Redundancy redundancy = new Redundancy(
Redundancy.RedundancyType.STRONG, left, right);
PatternPossibility possibility = new PatternPossibility();
possibility.add(left);
possibility.add(right);
objects.add(left);
objects.add(right);
objects.add(redundancy);
objects.add(possibility);
+ AnalyticsDataFactory.clearAnalyticsResult();
AnalyticsResult result = AnalyticsDataFactory.getAnalyticsResult();
session.setGlobal("result", result);
session.executeWithResults(objects);
Collection<AnalyticsMessageBase> notes = result
.getBySeverity(AnalyticsMessage.Severity.NOTE);
// Has at least one item.
assertEquals(1, notes.size());
AnalyticsMessageBase note = notes.iterator().next();
assertTrue(note.getFaulty().equals(redundancy));
}
}
| true | true | public void testRedundantRestrictionsInPatternPossibilities()
throws Exception {
StatelessSession session = getStatelessSession(this.getClass()
.getResourceAsStream("Notes.drl"));
session.setAgendaFilter(new RuleNameMatchesAgendaFilter(
"Find redundant restrictions from pattern possibilities"));
Collection<Object> objects = new ArrayList<Object>();
LiteralRestriction left = new LiteralRestriction();
LiteralRestriction right = new LiteralRestriction();
Redundancy redundancy = new Redundancy(
Redundancy.RedundancyType.STRONG, left, right);
PatternPossibility possibility = new PatternPossibility();
possibility.add(left);
possibility.add(right);
objects.add(left);
objects.add(right);
objects.add(redundancy);
objects.add(possibility);
AnalyticsResult result = AnalyticsDataFactory.getAnalyticsResult();
session.setGlobal("result", result);
session.executeWithResults(objects);
Collection<AnalyticsMessageBase> notes = result
.getBySeverity(AnalyticsMessage.Severity.NOTE);
// Has at least one item.
assertEquals(1, notes.size());
AnalyticsMessageBase note = notes.iterator().next();
assertTrue(note.getFaulty().equals(redundancy));
}
| public void testRedundantRestrictionsInPatternPossibilities()
throws Exception {
StatelessSession session = getStatelessSession(this.getClass()
.getResourceAsStream("Notes.drl"));
session.setAgendaFilter(new RuleNameMatchesAgendaFilter(
"Find redundant restrictions from pattern possibilities"));
Collection<Object> objects = new ArrayList<Object>();
LiteralRestriction left = new LiteralRestriction();
LiteralRestriction right = new LiteralRestriction();
Redundancy redundancy = new Redundancy(
Redundancy.RedundancyType.STRONG, left, right);
PatternPossibility possibility = new PatternPossibility();
possibility.add(left);
possibility.add(right);
objects.add(left);
objects.add(right);
objects.add(redundancy);
objects.add(possibility);
AnalyticsDataFactory.clearAnalyticsResult();
AnalyticsResult result = AnalyticsDataFactory.getAnalyticsResult();
session.setGlobal("result", result);
session.executeWithResults(objects);
Collection<AnalyticsMessageBase> notes = result
.getBySeverity(AnalyticsMessage.Severity.NOTE);
// Has at least one item.
assertEquals(1, notes.size());
AnalyticsMessageBase note = notes.iterator().next();
assertTrue(note.getFaulty().equals(redundancy));
}
|
diff --git a/contrib/Quote.java b/contrib/Quote.java
index 750deca..288bcf9 100644
--- a/contrib/Quote.java
+++ b/contrib/Quote.java
@@ -1,1158 +1,1158 @@
import uk.co.uwcs.choob.*;
import uk.co.uwcs.choob.modules.*;
import uk.co.uwcs.choob.support.*;
import uk.co.uwcs.choob.support.events.*;
import java.sql.*;
import java.util.*;
import java.util.regex.*;
import java.text.*;
public class QuoteObject
{
public int id;
public String quoter;
public String hostmask;
public int lines;
public int score;
public int up;
public int down;
public long time;
}
public class QuoteLine
{
public int id;
public int quoteID;
public int lineNumber;
public String nick;
public String message;
public boolean isAction;
}
public class RecentQuote
{
public QuoteObject quote;
// No sense in caching the lines here.
public long time;
/*
* 0 = displayed
* 1 = quoted
*/
public int type;
}
public class Quote
{
private static int MINLENGTH = 7; // Minimum length of a line to be quotable using simple syntax.
private static int MINWORDS = 2; // Minimum words in a line to be quotable using simple syntax.
private static int HISTORY = 100; // Lines of history to search.
private static int EXCERPT = 40; // Maximum length of excerpt text in replies to create.
private static int MAXLINES = 10; // Maximum allowed lines in a quote.
private static int MAXCLAUSES = 20; // Maximum allowed lines in a quote.
private static int MAXJOINS = 6; // Maximum allowed lines in a quote.
private static int RECENTLENGTH = 20; // Maximum length of "recent quotes" list for a context.
private static String IGNORE = "quoteme|quote|quoten|quote.create"; // Ignore these when searching for regex quotes.
private static int THRESHOLD = -3; // Lowest karma of displayed quote.
private HashMap<String,List<RecentQuote>> recentQuotes;
private Modules mods;
private IRCInterface irc;
private Pattern ignorePattern;
public Quote( Modules mods, IRCInterface irc )
{
this.mods = mods;
this.irc = irc;
this.ignorePattern = Pattern.compile(
"^(?:" + irc.getTriggerRegex() + ")" +
"(?:" + IGNORE + ")", Pattern.CASE_INSENSITIVE);
recentQuotes = new HashMap<String,List<RecentQuote>>();
}
public String[] helpTopics = { "UsingCreate", "CreateExamples", "UsingGet" };
public String[] helpUsingCreate = {
"There's 4 ways of calling Quote.Create.",
"If you pass no parameters (or action: or privmsg:), the most recent line (or action) that's long enough will be quoted.",
"With just a nickname (or privmsg:<Nick>), the most recent line from that nick will be quoted.",
"With action:<Nick>, the most recent action from that nick will be quoted.",
"Finally, you can specify one or 2 regular expression searches. If"
+ " you specify just one, the most recent matching line will be quoted."
+ " With 2, the first one matches the start of the quote, and the"
+ " second matches the end. Previous quote commands are skipped when doing"
+ " any regex matching.",
"'Long enough' in this context means at least " + MINLENGTH
+ " characters, and at least " + MINWORDS + " words.",
"Note that nicknames are always made into their short form: 'privmsg:fred|bed' will quote people called 'fred', 'fred|busy', etc.",
"See CreateExamples for some examples."
};
public String[] helpCreateExamples = {
"'Quote.Create action:Fred' will quote the most recent action from Fred, regardless of length.",
"'Quote.Create privmsg:' will quote the most recent line that's long enough.",
"'Quote.Create fred:/blizzard/ /suck/' will quote the most recent possible quote starting with fred saying 'Blizzard', ending with the first line containing 'suck'."
};
public String[] helpUsingGet = {
"There are several clauses you can use to select quotes.",
"You can specify a number, which will be used as a quote ID.",
"A clause '<Selector>:<Relation><Number>', where <Selector> is one of 'score' or 'length', <Relation> is '>', '<' or '=' and <Number> is some number.",
"You can use 'quoter:<Nick>' to get quotes made by <Nick>.",
"Finally, you can use '<Nick>', '/<Regex>/' or '<Nick>:/<Regex>/' to match only quotes from <Nick>, quotes matching <Regex> or quotes where <Nick> said something matching <Regex>."
};
public String[] helpCommandCreate = {
"Create a new quote. See Quote.UsingCreate for more info.",
"[ [privmsg:][<Nick>] | action:[<Nick>] | [<Nick>:]/<Regex>/ [[<Nick>:]/<Regex>] ]",
"<Nick> is a nickname to quote",
"<Regex> is a regular expression to use to match lines"
};
public void commandCreate( Message mes ) throws ChoobException
{
if (!(mes instanceof ChannelEvent))
{
irc.sendContextReply( mes, "Sorry, this command can only be used in a channel" );
return;
}
String chan = ((ChannelEvent)mes).getChannel();
List<Message> history = mods.history.getLastMessages( mes, HISTORY );
- String param = mods.util.getParamString(mes);
+ String param = mods.util.getParamString(mes).trim();
// Default is privmsg
- if ( param.equals("") || ((param.charAt(0) < '0' || param.charAt(0) > '9') && param.charAt(0) != '/' && param.indexOf(':') == -1) )
+ if ( param.equals("") || ((param.charAt(0) < '0' || param.charAt(0) > '9') && param.charAt(0) != '/' && param.indexOf(':') == -1 && param.indexOf(' ') == -1) )
param = "privmsg:" + param;
final List<Message> lines = new ArrayList<Message>();
if (param.charAt(0) >= '0' && param.charAt(0) <= '9')
{
// First digit is a number. That means the rest are, too! (Or at least, we assume so.)
String bits[] = param.split(" +");
int offset = 0;
int size;
if (bits.length > 2)
{
irc.sendContextReply(mes, "When quoting by offset, you must supply only 1 or 2 parameters.");
return;
}
else if (bits.length == 2)
{
try
{
offset = Integer.parseInt(bits[1]);
}
catch (NumberFormatException e)
{
irc.sendContextReply(mes, "Numeric offset " + bits[1] + " was not a valid integer...");
return;
}
}
try
{
size = Integer.parseInt(bits[0]);
}
catch (NumberFormatException e)
{
irc.sendContextReply(mes, "Numeric size " + bits[0] + " was not a valid integer...");
return;
}
if (offset < 0)
{
irc.sendContextReply(mes, "Can't quote things that haven't happened yet!");
return;
}
else if (size < 1)
{
irc.sendContextReply(mes, "Can't quote an empty quote!");
return;
}
else if (offset + size > history.size())
{
irc.sendContextReply(mes, "Can't quote -- memory like a seive!");
return;
}
// Must do this backwards
for(int i=offset + size - 1; i>=offset; i--)
lines.add(history.get(i));
}
- else if (param.charAt(0) != '/' && param.indexOf(':') == -1)
+ else if (param.charAt(0) != '/' && param.indexOf(':') == -1 && param.indexOf(' ') == -1)
{
// It's a nickname.
String bits[] = param.split("\\s+");
if (bits.length > 2)
{
irc.sendContextReply(mes, "When quoting by nickname, you must supply only 1 parameter.");
return;
}
String findNick = mods.nick.getBestPrimaryNick( bits[0] ).toLowerCase();
for(int i=0; i<history.size(); i++)
{
Message line = history.get(i);
String text = line.getMessage();
// if (text.length() < MINLENGTH || text.split(" +").length < MINWORDS)
// continue;
String guessNick = mods.nick.getBestPrimaryNick( line.getNick() );
if ( guessNick.toLowerCase().equals(findNick) )
{
lines.add(line);
break;
}
}
if (lines.size() == 0)
{
irc.sendContextReply(mes, "No quote found for nickname " + findNick + ".");
return;
}
}
else if (param.toLowerCase().startsWith("action:") || param.toLowerCase().startsWith("privmsg:"))
{
Class thing;
if (param.toLowerCase().startsWith("action:"))
thing = ChannelAction.class;
else
thing = ChannelMessage.class;
// It's an action from a nickname
String bits[] = param.split("\\s+");
if (bits.length > 2)
{
irc.sendContextReply(mes, "When quoting by type, you must supply only 1 parameter.");
return;
}
bits = bits[0].split(":");
String findNick;
if (bits.length == 2)
findNick = mods.nick.getBestPrimaryNick( bits[1] ).toLowerCase();
else
findNick = null;
for(int i=0; i<history.size(); i++)
{
Message line = history.get(i);
String text = line.getMessage();
if (!thing.isInstance(line))
continue;
if (findNick != null)
{
String guessNick = mods.nick.getBestPrimaryNick( line.getNick() );
if ( guessNick.toLowerCase().equals(findNick) )
{
lines.add(line);
break;
}
}
else
{
// Check length etc.
if (text.length() < MINLENGTH || text.split(" +").length < MINWORDS)
continue;
lines.add(line);
break;
}
}
if (lines.size() == 0)
{
if (findNick != null)
irc.sendContextReply(mes, "No quotes found for nickname " + findNick + ".");
else
irc.sendContextReply(mes, "No recent quotes of that type!");
return;
}
}
else
{
// Final case: Regex quoting.
- // Matches anything of the form [NICK:]/REGEX/ [[NICK:]/REGEX/]
- Matcher ma = Pattern.compile("(?:([^\\s:]+):)?/((?:\\\\.|[^\\\\/])+)/(?:\\s+(?:([^\\s:]+):)?/((?:\\\\.|[^\\\\/])+)/)?").matcher(param);
+ // Matches anything of the form [NICK{:| }]/REGEX/ [[NICK{:| }]/REGEX/]
+ Matcher ma = Pattern.compile("(?:([^\\s:]+)[:\\s])?/((?:\\\\.|[^\\\\/])+)/(?:\\s+(?:([^\\s:]+)[:\\s])?/((?:\\\\.|[^\\\\/])+)/)?").matcher(param);
if (!ma.matches())
{
irc.sendContextReply(mes, "Sorry, your string looked like a regex quote but I couldn't decipher it.");
return;
}
String startNick, startRegex, endNick, endRegex;
if (ma.group(4) != null)
{
// The second parameter exists ==> multiline quote
startNick = ma.group(1);
startRegex = ".*" + ma.group(2) + ".*";
endNick = ma.group(3);
endRegex = ".*" + ma.group(4) + ".*";
}
else
{
startNick = null;
startRegex = null;
endNick = ma.group(1);
endRegex = ".*" + ma.group(2) + ".*";
}
if (startNick != null)
startNick = mods.nick.getBestPrimaryNick( startNick ).toLowerCase();
if (endNick != null)
endNick = mods.nick.getBestPrimaryNick( endNick ).toLowerCase();
// OK, do the match!
int endIndex = -1, startIndex = -1;
for(int i=0; i<history.size(); i++)
{
Message line = history.get(i);
String nick = mods.nick.getBestPrimaryNick( line.getNick() ).toLowerCase();
if ( endRegex != null )
{
// Not matched the end yet
// For this one, we must avoid triggering on quote commands.
if (ignorePattern.matcher(line.getMessage()).find())
continue;
if ((endNick == null || endNick.equals(nick))
&& line.getMessage().matches(endRegex))
{
// But have now...
endRegex = null;
endIndex = i;
if ( startRegex == null )
{
startIndex = i;
break;
}
}
}
else
{
// Matched the end; looking for the start.
if ((startNick == null || startNick.equals(nick))
&& line.getMessage().matches(startRegex))
{
startIndex = i;
break;
}
}
}
if (startIndex == -1 || endIndex == -1)
{
irc.sendContextReply(mes, "Sorry, no quote found!");
return;
}
for(int i=startIndex; i>=endIndex; i--)
lines.add(history.get(i));
}
// Have some lines.
// Is it a sensible size?
if (lines.size() > MAXLINES)
{
irc.sendContextReply(mes, "Sorry, this quote is longer than the maximum size of " + MAXLINES + " lines.");
return;
}
// Check for people suspiciously quoting themselves.
// For now, that's just if they are the final line in the quote.
Message last = lines.get(lines.size() - 1);
//*/ Remove the first slash to comment me out.
if (last.getLogin().compareToIgnoreCase(mes.getLogin()) == 0
&& last.getHostname().compareToIgnoreCase(mes.getHostname()) == 0)
{
// Suspicious!
irc.sendContextReply(mes, "Sorry, no quoting yourself!");
return;
} //*/
// OK, build a QuoteObject...
final QuoteObject quote = new QuoteObject();
quote.quoter = mods.nick.getBestPrimaryNick(mes.getNick());
quote.hostmask = (mes.getLogin() + "@" + mes.getHostname()).toLowerCase();
quote.lines = lines.size();
quote.score = 0;
quote.up = 0;
quote.down = 0;
quote.time = System.currentTimeMillis();
// QuoteLine object; quoteID will be filled in later.
final List quoteLines = new ArrayList(lines.size());
mods.odb.runTransaction( new ObjectDBTransaction() {
public void run()
{
quote.id = 0;
save(quote);
// Now have a quote ID!
quoteLines.clear();
for(int i=0; i<lines.size(); i++)
{
QuoteLine quoteLine = new QuoteLine();
quoteLine.quoteID = quote.id;
quoteLine.id = 0;
quoteLine.lineNumber = i;
quoteLine.nick = mods.nick.getBestPrimaryNick(lines.get(i).getNick());
quoteLine.message = lines.get(i).getMessage();
quoteLine.isAction = (lines.get(i) instanceof ChannelAction);
save(quoteLine);
quoteLines.add(quoteLine);
}
}});
// Remember this quote for later...
addLastQuote(mes.getContext(), quote, 1);
- irc.sendContextReply( mes, "OK, added quote " + quote.id + ": " + formatPreview(quoteLines) );
+ irc.sendContextReply( mes, "OK, added quote " + quote.lines + " line quote #" + quote.id + ": " + formatPreview(quoteLines) );
}
public String[] helpCommandAdd = {
"Add a quote to the database.",
"<Nick> <Text> [ ||| <Nick> <Text> ... ]",
"the nickname of the person who said the text (of the form '<nick>' or '* nick' or just simply 'nick')",
"the text that was actually said"
};
public java.security.Permission permissionCommandAdd = new ChoobPermission("plugins.quote.add");
public void commandAdd(Message mes)
{
mods.security.checkNickPerm(permissionCommandAdd, mes.getNick());
String params = mods.util.getParamString( mes );
String[] lines = params.split("\\s+\\|\\|\\|\\s+");
final QuoteLine[] content = new QuoteLine[lines.length];
for(int i=0; i<lines.length; i++)
{
String line = lines[i];
String nick, text;
boolean action = false;
if (line.charAt(0) == '*')
{
int spacePos1 = line.indexOf(' ');
if (spacePos1 == -1)
{
irc.sendContextReply(mes, "Line " + i + " was invalid!");
return;
}
int spacePos2 = line.indexOf(' ', spacePos1 + 1);
if (spacePos2 == -1)
{
irc.sendContextReply(mes, "Line " + i + " was invalid!");
return;
}
nick = line.substring(spacePos1 + 1, spacePos2);
text = line.substring(spacePos2 + 1);
action = true;
}
else if (line.charAt(0) == '<')
{
int spacePos = line.indexOf(' ');
if (spacePos == -1)
{
irc.sendContextReply(mes, "Line " + i + " was invalid!");
return;
}
else if (line.charAt(spacePos - 1) != '>')
{
irc.sendContextReply(mes, "Line " + i + " was invalid!");
return;
}
nick = line.substring(1, spacePos - 1);
text = line.substring(spacePos + 1);
}
else
{
int spacePos = line.indexOf(' ');
if (spacePos == -1)
{
irc.sendContextReply(mes, "Line " + i + " was invalid!");
return;
}
nick = line.substring(0, spacePos);
text = line.substring(spacePos + 1);
}
QuoteLine quoteLine = new QuoteLine();
quoteLine.lineNumber = i;
quoteLine.nick = mods.nick.getBestPrimaryNick(nick);
quoteLine.message = text;
quoteLine.isAction = action;
content[i] = quoteLine;
}
final QuoteObject quote = new QuoteObject();
quote.quoter = mods.nick.getBestPrimaryNick(mes.getNick());
quote.hostmask = (mes.getLogin() + "@" + mes.getHostname()).toLowerCase();
quote.lines = lines.length;
quote.score = 0;
quote.up = 0;
quote.down = 0;
quote.time = System.currentTimeMillis();
// QuoteLine object; quoteID will be filled in later.
final List quoteLines = new ArrayList(lines.length);
mods.odb.runTransaction( new ObjectDBTransaction() {
public void run()
{
// Have to set ID etc. here in case transaction blows up.
quote.id = 0;
save(quote);
// Now have a quote ID!
quoteLines.clear();
for(int i=0; i<content.length; i++)
{
QuoteLine quoteLine = content[i];
quoteLine.quoteID = quote.id;
quoteLine.id = 0;
save(quoteLine);
quoteLines.add(quoteLine);
}
}});
addLastQuote(mes.getContext(), quote, 1);
irc.sendContextReply( mes, "OK, added quote " + quote.id + ": " + formatPreview(quoteLines) );
}
private String formatPreview(List<QuoteLine> lines)
{
if (lines.size() == 1)
{
QuoteLine line = lines.get(0);
String text;
if (line.message.length() > EXCERPT)
text = line.message.substring(0, 27) + "...";
else
text = line.message;
String prefix;
if (line.isAction)
prefix = "* " + line.nick;
else
prefix = "<" + line.nick + ">";
return prefix + " " + text;
}
else
{
// last is initalised above
QuoteLine first = lines.get(0);
String firstText;
if (first.isAction)
firstText = "* " + first.nick;
else
firstText = "<" + first.nick + ">";
if (first.message.length() > EXCERPT)
firstText += " " + first.message.substring(0, 27) + "...";
else
firstText += " " + first.message;
QuoteLine last = lines.get(lines.size() - 1);
String lastText;
if (last.isAction)
lastText = "* " + last.nick;
else
lastText = "<" + last.nick + ">";
if (last.message.length() > EXCERPT)
lastText += " " + last.message.substring(0, 27) + "...";
else
lastText += " " + last.message;
return firstText + " -> " + lastText;
}
}
public String[] helpCommandGet = {
"Get a random quote from the database.",
"[ <Clause> [ <Clause> ... ]]",
"<Clause> is a clause to select quotes with (see Quote.UsingGet)"
};
public void commandGet( Message mes ) throws ChoobException
{
String whereClause = getClause( mods.util.getParamString( mes ) );
List quotes = mods.odb.retrieve( QuoteObject.class, "SORT BY RANDOM LIMIT (1) " + whereClause );
if (quotes.size() == 0)
{
irc.sendContextReply( mes, "No quotes found!" );
return;
}
QuoteObject quote = (QuoteObject)quotes.get(0);
List lines = mods.odb.retrieve( QuoteLine.class, "WHERE quoteID = " + quote.id );
Iterator l = lines.iterator();
if (!l.hasNext())
{
irc.sendContextReply( mes, "Found quote " + quote.id + " but it was empty!" );
return;
}
while(l.hasNext())
{
QuoteLine line = (QuoteLine)l.next();
if (line.isAction)
irc.sendContextMessage( mes, "* " + line.nick + " " + line.message );
else
irc.sendContextMessage( mes, "<" + line.nick + "> " + line.message );
}
// Remember this quote for later...
addLastQuote(mes.getContext(), quote, 0);
}
public String[] helpApiSingleLineQuote = {
"Get a single line quote from the specified nickname, optionally adding it to the recent quotes list for the passed context.",
"Either the single line quote, or null if there was none.",
"<nick> [<context>]",
"the nickname to get a quote from",
"the optional context in which the quote will be displayed"
};
public String apiSingleLineQuote(String nick)
{
return apiSingleLineQuote(nick, null);
}
public String apiSingleLineQuote(String nick, String context)
{
String whereClause = getClause(nick + " length:=1");
List quotes = mods.odb.retrieve( QuoteObject.class, "SORT BY RANDOM LIMIT (1) " + whereClause );
if (quotes.size() == 0)
return null;
QuoteObject quote = (QuoteObject)quotes.get(0);
List <QuoteLine>lines = mods.odb.retrieve( QuoteLine.class, "WHERE quoteID = " + quote.id );
if (lines.size() == 0)
{
System.err.println("Found quote " + quote.id + " but it was empty!" );
return null;
}
if (context != null)
addLastQuote(context, quote, 0);
QuoteLine line = lines.get(0);
if (line.isAction)
return "/me " + line.message;
else
return line.message;
}
private void addLastQuote(String context, QuoteObject quote, int type)
{
synchronized(recentQuotes)
{
List<RecentQuote> recent = recentQuotes.get(context);
if (recent == null)
{
recent = new LinkedList<RecentQuote>();
recentQuotes.put( context, recent );
}
RecentQuote info = new RecentQuote();
info.quote = quote;
info.time = System.currentTimeMillis();
info.type = type;
recent.add(0, info);
while (recent.size() > RECENTLENGTH)
recent.remove( RECENTLENGTH );
}
}
public String[] helpCommandCount = {
"Get the number of matching quotes.",
"[ <Clause> [ <Clause> ... ]]",
"<Clause> is a clause to select quotes with (see Quote.UsingGet)"
};
public void commandCount( Message mes ) throws ChoobException
{
String whereClause = getClause( mods.util.getParamString( mes ) );
List<Integer> quoteCounts = mods.odb.retrieveInt( QuoteObject.class, whereClause );
int count = quoteCounts.size();
if (count == 0)
irc.sendContextReply( mes, "Sorry, no quotes match!" );
else if (count == 1)
irc.sendContextReply( mes, "There's just the one quote..." );
else
irc.sendContextReply( mes, "There are " + count + " quotes!" );
}
// quotekarma, quoteinfo
public String[] helpCommandInfo = {
"Get a summary of matching quotes.",
"[ <Clause> [ <Clause> ... ]]",
"<Clause> is a clause to select quotes with (see Quote.UsingGet)"
};
public void commandInfo( Message mes ) throws ChoobException
{
String whereClause = getClause( mods.util.getParamString(mes) );
List<Integer> quoteKarmas = mods.odb.retrieveInt( QuoteObject.class, "SELECT score " + whereClause );
int count = quoteKarmas.size();
int nonZeroCount = 0;
int total = 0;
int max = 0, min = 0;
for(Integer i: quoteKarmas)
{
total += i;
if (i != 0)
{
nonZeroCount++;
if (i < min)
min = i;
else if (i > max)
max = i;
}
}
DecimalFormat format = new DecimalFormat("##0.00");
String avKarma = format.format((double) total / (double) count);
String avNonZeroKarma = format.format((double) total / (double) nonZeroCount);
if (count == 0)
irc.sendContextReply( mes, "Sorry, no quotes found!" );
else if (count == 1)
irc.sendContextReply( mes, "I only found one quote; karma is " + total + "." );
else
irc.sendContextReply( mes, "Found " + count + " quotes. The total karma is " + total + ", average " + avKarma + ". " + nonZeroCount + " quotes had a karma; average for these is " + avNonZeroKarma + ". Min karma is " + min + " and max is " + max + "." );
}
public String[] helpCommandRemove = {
"Remove your most recently added quote.",
};
public void commandRemove( Message mes ) throws ChoobException
{
// Quotes are stored by context...
synchronized(recentQuotes)
{
String context = mes.getContext();
List<RecentQuote> recent = recentQuotes.get(context);
if (recent == null || recent.size() == 0)
{
irc.sendContextReply( mes, "Sorry, no quotes seen from here!" );
return;
}
String nick = mods.nick.getBestPrimaryNick(mes.getNick()).toLowerCase();
String hostmask = (mes.getLogin() + "@" + mes.getHostname()).toLowerCase();
Iterator<RecentQuote> iter = recent.iterator();
QuoteObject quote = null;
RecentQuote info = null;
while(iter.hasNext())
{
info = iter.next();
if (info.type == 1 && info.quote.quoter.toLowerCase().equals(nick)
&& info.quote.hostmask.equals(hostmask))
{
quote = info.quote;
break;
}
}
if (quote == null)
{
irc.sendContextReply( mes, "Sorry, you haven't quoted anything recently here!" );
return;
}
final QuoteObject theQuote = quote;
final List<QuoteLine> quoteLines = mods.odb.retrieve( QuoteLine.class, "WHERE quoteID = " + quote.id );
mods.odb.runTransaction( new ObjectDBTransaction() {
public void run()
{
delete(theQuote);
// Now have a quote ID!
for(QuoteLine line: quoteLines)
{
delete(line);
}
}});
recent.remove(info); // So the next unquote doesn't hit it
irc.sendContextReply( mes, "OK, unquoted quote " + quote.id + " (" + formatPreview(quoteLines) + ")." );
}
}
public String[] helpCommandLast = {
"Get a list of recent quote IDs.",
"[<Count>]",
"<Count> is the maximum number to return (default is 1)"
};
public void commandLast( Message mes ) throws ChoobException
{
// Get a count...
int count = 1;
String param = mods.util.getParamString(mes);
try
{
if ( param.length() > 0 )
count = Integer.parseInt( param );
}
catch ( NumberFormatException e )
{
irc.sendContextReply( mes, "'" + param + "' is not a valid integer!" );
return;
}
synchronized(recentQuotes)
{
String context = mes.getContext();
List<RecentQuote> recent = recentQuotes.get(context);
if (recent == null || recent.size() == 0)
{
irc.sendContextReply( mes, "Sorry, no quotes seen from here!" );
return;
}
// Ugly hack to avoid lack of last()...
ListIterator<RecentQuote> iter = recent.listIterator();
RecentQuote info = null;
QuoteObject quote = null;
boolean first = true;
String output = null;
int remain = count;
while(iter.hasNext() && remain-- > 0)
{
info = iter.next();
if (!first)
output = output + ", " + info.quote.id;
else
output = "" + info.quote.id;
first = false;
}
if (count == 1)
irc.sendContextReply( mes, "Most recent quote ID: " + output + "." );
else
irc.sendContextReply( mes, "Most recent quote IDs: " + output + "." );
}
}
public String[] helpCommandKarmaMod = {
"Increase or decrease the karma of a quote.",
"<Direction> [<ID>]",
"<Direction> is 'up' or 'down'",
"<ID> is an optional quote ID (default is to use the most recent)"
};
public void commandKarmaMod( Message mes ) throws ChoobException
{
int quoteID = -1;
boolean up = true;
List<String> params = mods.util.getParams(mes);
if (params.size() == 1 || params.size() > 3)
{
irc.sendContextReply( mes, "Syntax: quote.KarmaMod {up|down} [number]" );
return;
}
// Check input
try
{
if ( params.size() == 3 )
quoteID = Integer.parseInt( params.get(2) );
}
catch ( NumberFormatException e )
{
// History dictates that this be ignored.
}
if ( params.get(1).toLowerCase().equals("down") )
up = false;
else if ( params.get(1).toLowerCase().equals("up") )
up = true;
else
{
irc.sendContextReply( mes, "Syntax: quote.KarmaMod {up|down} [number]" );
return;
}
String leet;
if (up)
leet = "l33t";
else
leet = "lame";
if (quoteID == -1)
{
synchronized(recentQuotes)
{
String context = mes.getContext();
List<RecentQuote> recent = recentQuotes.get(context);
if (recent == null || recent.size() == 0)
{
irc.sendContextReply( mes, "Sorry, no quotes seen from here!" );
return;
}
quoteID = recent.get(0).quote.id;
}
}
List quotes = mods.odb.retrieve( QuoteObject.class, "WHERE id = " + quoteID );
if (quotes.size() == 0)
{
irc.sendContextReply( mes, "No such quote to " + leet + "!" );
return;
}
QuoteObject quote = (QuoteObject)quotes.get(0);
if (up)
{
if (quote.score == THRESHOLD - 1)
{
if (mods.security.hasNickPerm( new ChoobPermission( "quote.delete" ), mes.getNick() ))
{
quote.score++;
quote.up++;
irc.sendContextReply( mes, "OK, quote " + quoteID + " is now leet enough to be seen! Current karma is " + quote.score + "." );
}
else
{
irc.sendContextReply( mes, "Sorry, that quote is on the karma threshold. Only an admin can make it more leet!" );
return;
}
}
else
{
quote.score++;
quote.up++;
irc.sendContextReply( mes, "OK, quote " + quoteID + " is now more leet! Current karma is " + quote.score + "." );
}
}
else if (quote.score == THRESHOLD)
{
if (mods.security.hasNickPerm( new ChoobPermission( "quote.delete" ), mes.getNick() ))
{
quote.score--;
quote.down++;
irc.sendContextReply( mes, "OK, quote " + quoteID + " is now too lame to be seen! Current karma is " + quote.score + "." );
}
else
{
irc.sendContextReply( mes, "Sorry, that quote is on the karma threshold. Only an admin can make it more lame!" );
return;
}
}
else
{
quote.score--;
quote.down++;
irc.sendContextReply( mes, "OK, quote " + quoteID + " is now more lame! Current karma is " + quote.score + "." );
}
mods.odb.update(quote);
}
/**
* Simple parser for quote searches...
*/
private String getClause(String text)
{
List<String> clauses = new ArrayList<String>();
boolean score = false; // True if score clause added.
int pos = text.equals("") ? -1 : 0;
int joins = 0;
while(pos != -1)
{
// Avoid problems with initial zero value...
if (pos != 0)
pos++;
// Initially, cut at space
int endPos = text.indexOf(' ', pos);
if (endPos == -1)
endPos = text.length();
String param = text.substring(pos, endPos);
String user = null; // User for regexes. Used later.
int colon = param.indexOf(':');
boolean fiddled = false; // Set to true if param already parsed
if (colon != -1)
{
String first = param.substring(0, colon).toLowerCase();
param = param.substring(colon + 1);
if (param.charAt(0) == '/')
{
// This must be a regex with a user parameter. Save for later.
user = mods.nick.getBestPrimaryNick( first );
pos = pos + colon + 1;
}
// OK, not a regex. What else might it be?
else if (first.equals("length"))
{
// Length modifier.
if (param.length() <= 1)
throw new ChoobError("Invalid/empty length selector.");
char op = param.charAt(0);
if (op != '>' && op != '<' && op != '=')
throw new ChoobError("Invalid length selector: " + param);
int length;
try
{
length = Integer.parseInt(param.substring(1));
}
catch (NumberFormatException e)
{
throw new ChoobError("Invalid length selector: " + param);
}
clauses.add("lines " + op + " " + length);
fiddled = true;
}
else if (first.equals("quoter"))
{
if (param.length() < 1)
throw new ChoobError("Empty quoter nickname.");
clauses.add("quoter = \"" + param.replaceAll("(\\W)", "\\\\1") + "\"");
fiddled = true;
}
else if (first.equals("score"))
{
if (param.length() <= 1)
throw new ChoobError("Invalid/empty score selector.");
char op = param.charAt(0);
if (op != '>' && op != '<' && op != '=')
throw new ChoobError("Invalid score selector: " + param);
int value;
try
{
value = Integer.parseInt(param.substring(1));
}
catch (NumberFormatException e)
{
throw new ChoobError("Invalid score selector: " + param);
}
clauses.add("score " + op + " " + value);
score = true;
fiddled = true;
}
// That's all the special cases out of the way. If we're still
// here, were's screwed...
else
{
throw new ChoobError("Unknown selector type: " + first);
}
}
if (fiddled)
{ } // Do nothing
// Right. We know that we either have a quoted nickname or a regex...
else if (param.charAt(0) == '/')
{
// This is a regex, then.
// Get a matcher on th region from here to the end of the string...
Matcher ma = Pattern.compile("^(?:\\\\.|[^\\\\/])*?/").matcher(text).region(pos+1,text.length());
if (!ma.find())
throw new ChoobError("Regular expression has no end!");
int end = ma.end();
String regex = text.substring(pos + 1, end - 1);
clauses.add("join"+joins+".message RLIKE \"" + regex.replaceAll("(\\W)", "$1") + "\"");
if (user != null)
clauses.add("join"+joins+".nick = \"" + user.replaceAll("(\\W)", "$1") + "\"");
clauses.add("join"+joins+".quoteID = id");
joins++;
pos = end-1; // In case there's a space, this is the /
}
else if (param.charAt(0) >= '0' && param.charAt(0) <= '9')
{
// Number -> Quote-by-ID
int value;
try
{
value = Integer.parseInt(param);
}
catch (NumberFormatException e)
{
throw new ChoobError("Invalid quote number: " + param);
}
clauses.add("id = " + value);
}
else
{
// This is a name
user = mods.nick.getBestPrimaryNick( param );
clauses.add("join"+joins+".nick = \"" + user.replaceAll("(\\W)", "\\\\1") + "\"");
clauses.add("join"+joins+".quoteID = id");
joins++;
}
// Make sure we skip any double spaces...
pos = text.indexOf(' ', pos + 1);
while( pos < text.length() - 1 && text.charAt(pos + 1) == ' ')
{
pos++;
}
// And that we haven't hopped off the end...
if (pos == text.length() - 1)
pos = -1;
}
// All those joins hate MySQL.
if (joins > MAXJOINS)
throw new ChoobError("Sorry, due to MySQL being whorish, only " + MAXJOINS + " nickname or line clause(s) allowed for now.");
else if (clauses.size() > MAXCLAUSES)
throw new ChoobError("Sorry, due to MySQL being whorish, only " + MAXCLAUSES + " clause(s) allowed for now.");
if (!score)
clauses.add("score > " + (THRESHOLD - 1));
StringBuffer search = new StringBuffer();
for(int i=0; i<joins; i++)
search.append("WITH " + QuoteLine.class.getName() + " AS join" + i + " ");
if (clauses.size() > 0)
{
search.append("WHERE ");
for(int i=0; i<clauses.size(); i++)
{
if (i != 0)
search.append(" AND ");
search.append(clauses.get(i));
}
}
return search.toString();
}
public void onJoin( ChannelJoin ev, Modules mods, IRCInterface irc )
{
if (ev.getLogin().equals("Choob"))
return;
boolean joinMessage = true;
boolean joinQuote = true;
try
{
String mesVal = (String)mods.plugin.callAPI("Options", "GetUserOption", ev.getNick(), "joinmessage");
joinMessage = (mesVal == null) || (mesVal.equals("1"));
System.out.println("mesVal: " + mesVal);
String quoteVal = (String)mods.plugin.callAPI("Options", "GetUserOption", ev.getNick(), "joinquote");
joinQuote = (quoteVal == null) || (quoteVal.equals("1"));
System.out.println("quoteVal: " + quoteVal);
}
catch (ChoobNoSuchCallException e)
{
}
String quote = null;
if ( joinQuote && joinMessage )
quote = apiSingleLineQuote( ev.getNick(), ev.getContext() );
if ( joinMessage )
{
if (quote == null)
irc.sendContextMessage( ev, "Hello, " + ev.getNick() + "!");
else
irc.sendContextMessage( ev, "Hello, " + ev.getNick() + ": \"" + quote + "\"");
}
}
}
| false | true | public void commandCreate( Message mes ) throws ChoobException
{
if (!(mes instanceof ChannelEvent))
{
irc.sendContextReply( mes, "Sorry, this command can only be used in a channel" );
return;
}
String chan = ((ChannelEvent)mes).getChannel();
List<Message> history = mods.history.getLastMessages( mes, HISTORY );
String param = mods.util.getParamString(mes);
// Default is privmsg
if ( param.equals("") || ((param.charAt(0) < '0' || param.charAt(0) > '9') && param.charAt(0) != '/' && param.indexOf(':') == -1) )
param = "privmsg:" + param;
final List<Message> lines = new ArrayList<Message>();
if (param.charAt(0) >= '0' && param.charAt(0) <= '9')
{
// First digit is a number. That means the rest are, too! (Or at least, we assume so.)
String bits[] = param.split(" +");
int offset = 0;
int size;
if (bits.length > 2)
{
irc.sendContextReply(mes, "When quoting by offset, you must supply only 1 or 2 parameters.");
return;
}
else if (bits.length == 2)
{
try
{
offset = Integer.parseInt(bits[1]);
}
catch (NumberFormatException e)
{
irc.sendContextReply(mes, "Numeric offset " + bits[1] + " was not a valid integer...");
return;
}
}
try
{
size = Integer.parseInt(bits[0]);
}
catch (NumberFormatException e)
{
irc.sendContextReply(mes, "Numeric size " + bits[0] + " was not a valid integer...");
return;
}
if (offset < 0)
{
irc.sendContextReply(mes, "Can't quote things that haven't happened yet!");
return;
}
else if (size < 1)
{
irc.sendContextReply(mes, "Can't quote an empty quote!");
return;
}
else if (offset + size > history.size())
{
irc.sendContextReply(mes, "Can't quote -- memory like a seive!");
return;
}
// Must do this backwards
for(int i=offset + size - 1; i>=offset; i--)
lines.add(history.get(i));
}
else if (param.charAt(0) != '/' && param.indexOf(':') == -1)
{
// It's a nickname.
String bits[] = param.split("\\s+");
if (bits.length > 2)
{
irc.sendContextReply(mes, "When quoting by nickname, you must supply only 1 parameter.");
return;
}
String findNick = mods.nick.getBestPrimaryNick( bits[0] ).toLowerCase();
for(int i=0; i<history.size(); i++)
{
Message line = history.get(i);
String text = line.getMessage();
// if (text.length() < MINLENGTH || text.split(" +").length < MINWORDS)
// continue;
String guessNick = mods.nick.getBestPrimaryNick( line.getNick() );
if ( guessNick.toLowerCase().equals(findNick) )
{
lines.add(line);
break;
}
}
if (lines.size() == 0)
{
irc.sendContextReply(mes, "No quote found for nickname " + findNick + ".");
return;
}
}
else if (param.toLowerCase().startsWith("action:") || param.toLowerCase().startsWith("privmsg:"))
{
Class thing;
if (param.toLowerCase().startsWith("action:"))
thing = ChannelAction.class;
else
thing = ChannelMessage.class;
// It's an action from a nickname
String bits[] = param.split("\\s+");
if (bits.length > 2)
{
irc.sendContextReply(mes, "When quoting by type, you must supply only 1 parameter.");
return;
}
bits = bits[0].split(":");
String findNick;
if (bits.length == 2)
findNick = mods.nick.getBestPrimaryNick( bits[1] ).toLowerCase();
else
findNick = null;
for(int i=0; i<history.size(); i++)
{
Message line = history.get(i);
String text = line.getMessage();
if (!thing.isInstance(line))
continue;
if (findNick != null)
{
String guessNick = mods.nick.getBestPrimaryNick( line.getNick() );
if ( guessNick.toLowerCase().equals(findNick) )
{
lines.add(line);
break;
}
}
else
{
// Check length etc.
if (text.length() < MINLENGTH || text.split(" +").length < MINWORDS)
continue;
lines.add(line);
break;
}
}
if (lines.size() == 0)
{
if (findNick != null)
irc.sendContextReply(mes, "No quotes found for nickname " + findNick + ".");
else
irc.sendContextReply(mes, "No recent quotes of that type!");
return;
}
}
else
{
// Final case: Regex quoting.
// Matches anything of the form [NICK:]/REGEX/ [[NICK:]/REGEX/]
Matcher ma = Pattern.compile("(?:([^\\s:]+):)?/((?:\\\\.|[^\\\\/])+)/(?:\\s+(?:([^\\s:]+):)?/((?:\\\\.|[^\\\\/])+)/)?").matcher(param);
if (!ma.matches())
{
irc.sendContextReply(mes, "Sorry, your string looked like a regex quote but I couldn't decipher it.");
return;
}
String startNick, startRegex, endNick, endRegex;
if (ma.group(4) != null)
{
// The second parameter exists ==> multiline quote
startNick = ma.group(1);
startRegex = ".*" + ma.group(2) + ".*";
endNick = ma.group(3);
endRegex = ".*" + ma.group(4) + ".*";
}
else
{
startNick = null;
startRegex = null;
endNick = ma.group(1);
endRegex = ".*" + ma.group(2) + ".*";
}
if (startNick != null)
startNick = mods.nick.getBestPrimaryNick( startNick ).toLowerCase();
if (endNick != null)
endNick = mods.nick.getBestPrimaryNick( endNick ).toLowerCase();
// OK, do the match!
int endIndex = -1, startIndex = -1;
for(int i=0; i<history.size(); i++)
{
Message line = history.get(i);
String nick = mods.nick.getBestPrimaryNick( line.getNick() ).toLowerCase();
if ( endRegex != null )
{
// Not matched the end yet
// For this one, we must avoid triggering on quote commands.
if (ignorePattern.matcher(line.getMessage()).find())
continue;
if ((endNick == null || endNick.equals(nick))
&& line.getMessage().matches(endRegex))
{
// But have now...
endRegex = null;
endIndex = i;
if ( startRegex == null )
{
startIndex = i;
break;
}
}
}
else
{
// Matched the end; looking for the start.
if ((startNick == null || startNick.equals(nick))
&& line.getMessage().matches(startRegex))
{
startIndex = i;
break;
}
}
}
if (startIndex == -1 || endIndex == -1)
{
irc.sendContextReply(mes, "Sorry, no quote found!");
return;
}
for(int i=startIndex; i>=endIndex; i--)
lines.add(history.get(i));
}
// Have some lines.
// Is it a sensible size?
if (lines.size() > MAXLINES)
{
irc.sendContextReply(mes, "Sorry, this quote is longer than the maximum size of " + MAXLINES + " lines.");
return;
}
// Check for people suspiciously quoting themselves.
// For now, that's just if they are the final line in the quote.
Message last = lines.get(lines.size() - 1);
//*/ Remove the first slash to comment me out.
if (last.getLogin().compareToIgnoreCase(mes.getLogin()) == 0
&& last.getHostname().compareToIgnoreCase(mes.getHostname()) == 0)
{
// Suspicious!
irc.sendContextReply(mes, "Sorry, no quoting yourself!");
return;
} //*/
// OK, build a QuoteObject...
final QuoteObject quote = new QuoteObject();
quote.quoter = mods.nick.getBestPrimaryNick(mes.getNick());
quote.hostmask = (mes.getLogin() + "@" + mes.getHostname()).toLowerCase();
quote.lines = lines.size();
quote.score = 0;
quote.up = 0;
quote.down = 0;
quote.time = System.currentTimeMillis();
// QuoteLine object; quoteID will be filled in later.
final List quoteLines = new ArrayList(lines.size());
mods.odb.runTransaction( new ObjectDBTransaction() {
public void run()
{
quote.id = 0;
save(quote);
// Now have a quote ID!
quoteLines.clear();
for(int i=0; i<lines.size(); i++)
{
QuoteLine quoteLine = new QuoteLine();
quoteLine.quoteID = quote.id;
quoteLine.id = 0;
quoteLine.lineNumber = i;
quoteLine.nick = mods.nick.getBestPrimaryNick(lines.get(i).getNick());
quoteLine.message = lines.get(i).getMessage();
quoteLine.isAction = (lines.get(i) instanceof ChannelAction);
save(quoteLine);
quoteLines.add(quoteLine);
}
}});
// Remember this quote for later...
addLastQuote(mes.getContext(), quote, 1);
irc.sendContextReply( mes, "OK, added quote " + quote.id + ": " + formatPreview(quoteLines) );
}
| public void commandCreate( Message mes ) throws ChoobException
{
if (!(mes instanceof ChannelEvent))
{
irc.sendContextReply( mes, "Sorry, this command can only be used in a channel" );
return;
}
String chan = ((ChannelEvent)mes).getChannel();
List<Message> history = mods.history.getLastMessages( mes, HISTORY );
String param = mods.util.getParamString(mes).trim();
// Default is privmsg
if ( param.equals("") || ((param.charAt(0) < '0' || param.charAt(0) > '9') && param.charAt(0) != '/' && param.indexOf(':') == -1 && param.indexOf(' ') == -1) )
param = "privmsg:" + param;
final List<Message> lines = new ArrayList<Message>();
if (param.charAt(0) >= '0' && param.charAt(0) <= '9')
{
// First digit is a number. That means the rest are, too! (Or at least, we assume so.)
String bits[] = param.split(" +");
int offset = 0;
int size;
if (bits.length > 2)
{
irc.sendContextReply(mes, "When quoting by offset, you must supply only 1 or 2 parameters.");
return;
}
else if (bits.length == 2)
{
try
{
offset = Integer.parseInt(bits[1]);
}
catch (NumberFormatException e)
{
irc.sendContextReply(mes, "Numeric offset " + bits[1] + " was not a valid integer...");
return;
}
}
try
{
size = Integer.parseInt(bits[0]);
}
catch (NumberFormatException e)
{
irc.sendContextReply(mes, "Numeric size " + bits[0] + " was not a valid integer...");
return;
}
if (offset < 0)
{
irc.sendContextReply(mes, "Can't quote things that haven't happened yet!");
return;
}
else if (size < 1)
{
irc.sendContextReply(mes, "Can't quote an empty quote!");
return;
}
else if (offset + size > history.size())
{
irc.sendContextReply(mes, "Can't quote -- memory like a seive!");
return;
}
// Must do this backwards
for(int i=offset + size - 1; i>=offset; i--)
lines.add(history.get(i));
}
else if (param.charAt(0) != '/' && param.indexOf(':') == -1 && param.indexOf(' ') == -1)
{
// It's a nickname.
String bits[] = param.split("\\s+");
if (bits.length > 2)
{
irc.sendContextReply(mes, "When quoting by nickname, you must supply only 1 parameter.");
return;
}
String findNick = mods.nick.getBestPrimaryNick( bits[0] ).toLowerCase();
for(int i=0; i<history.size(); i++)
{
Message line = history.get(i);
String text = line.getMessage();
// if (text.length() < MINLENGTH || text.split(" +").length < MINWORDS)
// continue;
String guessNick = mods.nick.getBestPrimaryNick( line.getNick() );
if ( guessNick.toLowerCase().equals(findNick) )
{
lines.add(line);
break;
}
}
if (lines.size() == 0)
{
irc.sendContextReply(mes, "No quote found for nickname " + findNick + ".");
return;
}
}
else if (param.toLowerCase().startsWith("action:") || param.toLowerCase().startsWith("privmsg:"))
{
Class thing;
if (param.toLowerCase().startsWith("action:"))
thing = ChannelAction.class;
else
thing = ChannelMessage.class;
// It's an action from a nickname
String bits[] = param.split("\\s+");
if (bits.length > 2)
{
irc.sendContextReply(mes, "When quoting by type, you must supply only 1 parameter.");
return;
}
bits = bits[0].split(":");
String findNick;
if (bits.length == 2)
findNick = mods.nick.getBestPrimaryNick( bits[1] ).toLowerCase();
else
findNick = null;
for(int i=0; i<history.size(); i++)
{
Message line = history.get(i);
String text = line.getMessage();
if (!thing.isInstance(line))
continue;
if (findNick != null)
{
String guessNick = mods.nick.getBestPrimaryNick( line.getNick() );
if ( guessNick.toLowerCase().equals(findNick) )
{
lines.add(line);
break;
}
}
else
{
// Check length etc.
if (text.length() < MINLENGTH || text.split(" +").length < MINWORDS)
continue;
lines.add(line);
break;
}
}
if (lines.size() == 0)
{
if (findNick != null)
irc.sendContextReply(mes, "No quotes found for nickname " + findNick + ".");
else
irc.sendContextReply(mes, "No recent quotes of that type!");
return;
}
}
else
{
// Final case: Regex quoting.
// Matches anything of the form [NICK{:| }]/REGEX/ [[NICK{:| }]/REGEX/]
Matcher ma = Pattern.compile("(?:([^\\s:]+)[:\\s])?/((?:\\\\.|[^\\\\/])+)/(?:\\s+(?:([^\\s:]+)[:\\s])?/((?:\\\\.|[^\\\\/])+)/)?").matcher(param);
if (!ma.matches())
{
irc.sendContextReply(mes, "Sorry, your string looked like a regex quote but I couldn't decipher it.");
return;
}
String startNick, startRegex, endNick, endRegex;
if (ma.group(4) != null)
{
// The second parameter exists ==> multiline quote
startNick = ma.group(1);
startRegex = ".*" + ma.group(2) + ".*";
endNick = ma.group(3);
endRegex = ".*" + ma.group(4) + ".*";
}
else
{
startNick = null;
startRegex = null;
endNick = ma.group(1);
endRegex = ".*" + ma.group(2) + ".*";
}
if (startNick != null)
startNick = mods.nick.getBestPrimaryNick( startNick ).toLowerCase();
if (endNick != null)
endNick = mods.nick.getBestPrimaryNick( endNick ).toLowerCase();
// OK, do the match!
int endIndex = -1, startIndex = -1;
for(int i=0; i<history.size(); i++)
{
Message line = history.get(i);
String nick = mods.nick.getBestPrimaryNick( line.getNick() ).toLowerCase();
if ( endRegex != null )
{
// Not matched the end yet
// For this one, we must avoid triggering on quote commands.
if (ignorePattern.matcher(line.getMessage()).find())
continue;
if ((endNick == null || endNick.equals(nick))
&& line.getMessage().matches(endRegex))
{
// But have now...
endRegex = null;
endIndex = i;
if ( startRegex == null )
{
startIndex = i;
break;
}
}
}
else
{
// Matched the end; looking for the start.
if ((startNick == null || startNick.equals(nick))
&& line.getMessage().matches(startRegex))
{
startIndex = i;
break;
}
}
}
if (startIndex == -1 || endIndex == -1)
{
irc.sendContextReply(mes, "Sorry, no quote found!");
return;
}
for(int i=startIndex; i>=endIndex; i--)
lines.add(history.get(i));
}
// Have some lines.
// Is it a sensible size?
if (lines.size() > MAXLINES)
{
irc.sendContextReply(mes, "Sorry, this quote is longer than the maximum size of " + MAXLINES + " lines.");
return;
}
// Check for people suspiciously quoting themselves.
// For now, that's just if they are the final line in the quote.
Message last = lines.get(lines.size() - 1);
//*/ Remove the first slash to comment me out.
if (last.getLogin().compareToIgnoreCase(mes.getLogin()) == 0
&& last.getHostname().compareToIgnoreCase(mes.getHostname()) == 0)
{
// Suspicious!
irc.sendContextReply(mes, "Sorry, no quoting yourself!");
return;
} //*/
// OK, build a QuoteObject...
final QuoteObject quote = new QuoteObject();
quote.quoter = mods.nick.getBestPrimaryNick(mes.getNick());
quote.hostmask = (mes.getLogin() + "@" + mes.getHostname()).toLowerCase();
quote.lines = lines.size();
quote.score = 0;
quote.up = 0;
quote.down = 0;
quote.time = System.currentTimeMillis();
// QuoteLine object; quoteID will be filled in later.
final List quoteLines = new ArrayList(lines.size());
mods.odb.runTransaction( new ObjectDBTransaction() {
public void run()
{
quote.id = 0;
save(quote);
// Now have a quote ID!
quoteLines.clear();
for(int i=0; i<lines.size(); i++)
{
QuoteLine quoteLine = new QuoteLine();
quoteLine.quoteID = quote.id;
quoteLine.id = 0;
quoteLine.lineNumber = i;
quoteLine.nick = mods.nick.getBestPrimaryNick(lines.get(i).getNick());
quoteLine.message = lines.get(i).getMessage();
quoteLine.isAction = (lines.get(i) instanceof ChannelAction);
save(quoteLine);
quoteLines.add(quoteLine);
}
}});
// Remember this quote for later...
addLastQuote(mes.getContext(), quote, 1);
irc.sendContextReply( mes, "OK, added quote " + quote.lines + " line quote #" + quote.id + ": " + formatPreview(quoteLines) );
}
|
diff --git a/bad-vibes-game/src/com/mobi/badvibes/model/world/TutorialWorld.java b/bad-vibes-game/src/com/mobi/badvibes/model/world/TutorialWorld.java
index ee9c2f3..25ed9d0 100644
--- a/bad-vibes-game/src/com/mobi/badvibes/model/world/TutorialWorld.java
+++ b/bad-vibes-game/src/com/mobi/badvibes/model/world/TutorialWorld.java
@@ -1,230 +1,229 @@
package com.mobi.badvibes.model.world;
import java.util.ArrayList;
import java.util.Random;
import com.mobi.badvibes.Point;
import com.mobi.badvibes.controller.GameMaster;
import com.mobi.badvibes.model.localstorage.LocalStorage;
import com.mobi.badvibes.model.people.NormanTheNormal;
import com.mobi.badvibes.model.people.Person;
import com.mobi.badvibes.model.people.logic.ExploreLogic;
import com.mobi.badvibes.model.people.logic.HappyLogic;
import com.mobi.badvibes.model.people.logic.LeavingTrainLogic;
import com.mobi.badvibes.model.people.logic.PauseLogic;
import com.mobi.badvibes.model.people.logic.PersonLogic;
import com.mobi.badvibes.model.people.logic.RushLogic;
import com.mobi.badvibes.util.GameUtil;
import com.mobi.badvibes.util.MathHelper;
import com.mobi.badvibes.util.MediaPlayer;
import com.mobi.badvibes.view.PersonView;
import com.mobi.badvibes.view.TrainView.TrainState;
import com.mobi.badvibes.view.WorldRenderer;
public class TutorialWorld extends World
{
/**
* This dictates the number of seconds before the train arrives.
*/
private static final float ArrivalTime = 12;
/**
* This dictates how much time is allocated for boarding, including the
* opening and closing of doors.
*/
private static final float BoardingTime = 12;
/**
* The delay before the next train arrives.
*/
private static final float NextTrainTime = 10;
/**
* It takes 5 seconds to go back to the main menu screen.
*/
private static final float BackToMenuDelay = 7;
/**
* There is 2 second delay per bucket when people will board.
*/
private static final float BoardDelayPerBucket = 1;
private float Timer = 0;
private int BucketIndex = 0;
private static final float totalWait = 26f;
@Override
public void initialize()
{
super.initialize();
}
public ArrayList<Person> createPeople()
{
ArrayList<Person> list = new ArrayList<Person>();
for (int i = 0; i < trainRidersCount; i++)
{
Person n = new NormanTheNormal();
list.add(n);
}
return list;
}
public ArrayList<Person> createPeopleInTrain()
{
ArrayList<Person> list = new ArrayList<Person>();
for (int i = 0; i < trainLeaversCount; i++)
list.add(new NormanTheNormal());
return list;
}
@Override
public void runEvent(EventType type)
{
switch (type)
{
case RUSH:
// TODO: change this to per-bucket rush
for (PersonView p : WorldRenderer.Instance.masterBucket.get(BucketIndex))
{
Person px = p.getPerson();
if (this.peopleList.contains(px) == false)
continue;
PersonLogic logic = px.getLogic();
if (logic instanceof PauseLogic)
continue;
if (logic instanceof LeavingTrainLogic)
continue;
if (logic instanceof HappyLogic)
continue;
if (peopleList.contains(px))
{
px.setLogic(new RushLogic(px));
}
}
break;
case ALIGHT:
for (Person p : peopleInTrainList)
{
Random r = new Random();
Point newPoint = (r.nextBoolean()) ? new Point(9, 0) : new Point(10, 0);
p.getView().setPosition(GameUtil.getPlatformVectorCentered(newPoint));
p.setLogic(new LeavingTrainLogic(p));
}
break;
case EXPLORE:
for (Person p : peopleList)
{
p.setLogic(new ExploreLogic(p));
}
break;
}
}
@Override
public void update(float delta)
{
Timer += delta;
currentWait += delta;
totalTimer += delta;
trainProgress = MathHelper.ClampF(currentWait / totalWait, 0, 1f);
if (peopleInTrainList.size() == 0)
{
if (peopleList.size() == 0)
{
// TODO This doesn't show.
setInfoText("Level success!", 2);
currentState = WorldState.END_GAME;
}
}
switch (currentState)
{
case ENTERING:
if (Timer >= ArrivalTime)
{
- MediaPlayer.sfx("");
Timer = 0;
train.trainView.arriveTrain();
currentState = WorldState.ARRIVAL;
setInfoText("!!!", 3);
setPeopleInTrainList(createPeopleInTrain());
}
break;
case ARRIVAL:
if (train.trainView.currentState == TrainState.BOARDING)
{
Timer = 0;
// TODO: manually let the player switch to this state, ie:
// showing the button, etc.
currentState = WorldState.BOARDING;
// we immediately do the first rushing, para less wait :3
runEvent(EventType.RUSH);
BucketIndex++;
}
break;
case BOARDING:
// TODO: trigger per-bucket rush in runEvent, when all buckets are
// iterated
// then change state to DEPARTURE
if (Timer >= BoardDelayPerBucket)
{
Timer = 0;
runEvent(EventType.RUSH);
BucketIndex++;
if (BucketIndex >= WorldRenderer.Instance.masterBucket.size())
{
BucketIndex = 0;
currentState = WorldState.DEPARTURE;
train.trainView.departTrain();
}
}
break;
case DEPARTURE:
if (Timer >= NextTrainTime)
{
currentWait = Timer = 0;
currentState = WorldState.ENTERING;
}
break;
case END_GAME:
if (Timer >= BackToMenuDelay)
{
float boundedHappiness = MathHelper.ClampF(happiness, 0, 1f);
GameMaster.data.happiness = boundedHappiness;
GameMaster.data.totalTime = totalTimer;
float timeFactor = (totalTimer > 45) ? totalTimer / 120f : 0;
GameMaster.data.score = MathHelper.ClampF(boundedHappiness - timeFactor, 0, 1f);
LocalStorage.Write(GameMaster.data);
GameMaster.endGame();
}
break;
default:
break;
}
}
}
| true | true | public void update(float delta)
{
Timer += delta;
currentWait += delta;
totalTimer += delta;
trainProgress = MathHelper.ClampF(currentWait / totalWait, 0, 1f);
if (peopleInTrainList.size() == 0)
{
if (peopleList.size() == 0)
{
// TODO This doesn't show.
setInfoText("Level success!", 2);
currentState = WorldState.END_GAME;
}
}
switch (currentState)
{
case ENTERING:
if (Timer >= ArrivalTime)
{
MediaPlayer.sfx("");
Timer = 0;
train.trainView.arriveTrain();
currentState = WorldState.ARRIVAL;
setInfoText("!!!", 3);
setPeopleInTrainList(createPeopleInTrain());
}
break;
case ARRIVAL:
if (train.trainView.currentState == TrainState.BOARDING)
{
Timer = 0;
// TODO: manually let the player switch to this state, ie:
// showing the button, etc.
currentState = WorldState.BOARDING;
// we immediately do the first rushing, para less wait :3
runEvent(EventType.RUSH);
BucketIndex++;
}
break;
case BOARDING:
// TODO: trigger per-bucket rush in runEvent, when all buckets are
// iterated
// then change state to DEPARTURE
if (Timer >= BoardDelayPerBucket)
{
Timer = 0;
runEvent(EventType.RUSH);
BucketIndex++;
if (BucketIndex >= WorldRenderer.Instance.masterBucket.size())
{
BucketIndex = 0;
currentState = WorldState.DEPARTURE;
train.trainView.departTrain();
}
}
break;
case DEPARTURE:
if (Timer >= NextTrainTime)
{
currentWait = Timer = 0;
currentState = WorldState.ENTERING;
}
break;
case END_GAME:
if (Timer >= BackToMenuDelay)
{
float boundedHappiness = MathHelper.ClampF(happiness, 0, 1f);
GameMaster.data.happiness = boundedHappiness;
GameMaster.data.totalTime = totalTimer;
float timeFactor = (totalTimer > 45) ? totalTimer / 120f : 0;
GameMaster.data.score = MathHelper.ClampF(boundedHappiness - timeFactor, 0, 1f);
LocalStorage.Write(GameMaster.data);
GameMaster.endGame();
}
break;
default:
break;
}
}
| public void update(float delta)
{
Timer += delta;
currentWait += delta;
totalTimer += delta;
trainProgress = MathHelper.ClampF(currentWait / totalWait, 0, 1f);
if (peopleInTrainList.size() == 0)
{
if (peopleList.size() == 0)
{
// TODO This doesn't show.
setInfoText("Level success!", 2);
currentState = WorldState.END_GAME;
}
}
switch (currentState)
{
case ENTERING:
if (Timer >= ArrivalTime)
{
Timer = 0;
train.trainView.arriveTrain();
currentState = WorldState.ARRIVAL;
setInfoText("!!!", 3);
setPeopleInTrainList(createPeopleInTrain());
}
break;
case ARRIVAL:
if (train.trainView.currentState == TrainState.BOARDING)
{
Timer = 0;
// TODO: manually let the player switch to this state, ie:
// showing the button, etc.
currentState = WorldState.BOARDING;
// we immediately do the first rushing, para less wait :3
runEvent(EventType.RUSH);
BucketIndex++;
}
break;
case BOARDING:
// TODO: trigger per-bucket rush in runEvent, when all buckets are
// iterated
// then change state to DEPARTURE
if (Timer >= BoardDelayPerBucket)
{
Timer = 0;
runEvent(EventType.RUSH);
BucketIndex++;
if (BucketIndex >= WorldRenderer.Instance.masterBucket.size())
{
BucketIndex = 0;
currentState = WorldState.DEPARTURE;
train.trainView.departTrain();
}
}
break;
case DEPARTURE:
if (Timer >= NextTrainTime)
{
currentWait = Timer = 0;
currentState = WorldState.ENTERING;
}
break;
case END_GAME:
if (Timer >= BackToMenuDelay)
{
float boundedHappiness = MathHelper.ClampF(happiness, 0, 1f);
GameMaster.data.happiness = boundedHappiness;
GameMaster.data.totalTime = totalTimer;
float timeFactor = (totalTimer > 45) ? totalTimer / 120f : 0;
GameMaster.data.score = MathHelper.ClampF(boundedHappiness - timeFactor, 0, 1f);
LocalStorage.Write(GameMaster.data);
GameMaster.endGame();
}
break;
default:
break;
}
}
|
diff --git a/src/eu/cloudtm/autonomicManager/simulator/SimulatorConfGlobal.java b/src/eu/cloudtm/autonomicManager/simulator/SimulatorConfGlobal.java
index ce3bb53..dd3861a 100644
--- a/src/eu/cloudtm/autonomicManager/simulator/SimulatorConfGlobal.java
+++ b/src/eu/cloudtm/autonomicManager/simulator/SimulatorConfGlobal.java
@@ -1,56 +1,56 @@
package eu.cloudtm.autonomicManager.simulator;
import eu.cloudtm.autonomicManager.commons.EvaluatedParam;
import eu.cloudtm.autonomicManager.commons.ForecastParam;
import eu.cloudtm.autonomicManager.commons.Param;
import eu.cloudtm.autonomicManager.oracles.InputOracle;
/**
* @author Sebastiano Peluso
*/
class SimulatorConfGlobal {
private Integer cacheObjects;
private Integer numServers;
private Integer numClients;
private Integer objectReplicationDegree;
private Long startStatTime;
private Long averageServerToServerNetDelay; //TODO Chiedere a Pierangelo
private Long averageClientToServerNetDelay; //TODO Chiedere a Pierangelo
SimulatorConfGlobal(InputOracle inputOracle){
cacheObjects = (Integer) inputOracle.getParam(Param.NumberOfEntries);
numServers = (Integer) inputOracle.getForecastParam(ForecastParam.NumNodes);
- numClients = (Integer) inputOracle.getEvaluatedParam(EvaluatedParam.MAX_ACTIVE_THREADS);
+ numClients = (Integer) inputOracle.getEvaluatedParam(EvaluatedParam.MAX_ACTIVE_THREADS) * numServers;
objectReplicationDegree = (Integer) inputOracle.getForecastParam(ForecastParam.ReplicationDegree);
startStatTime = 0L;
averageServerToServerNetDelay = 0L;
averageClientToServerNetDelay = 0L;
}
int getNumberOfClients(){
return numClients;
}
@Override
public String toString() {
return "[Global]\n\n"+
"cache_objects = "+cacheObjects+"\n"+
"num_servers = "+numServers+"\n"+
"num_clients = "+numClients+"\n"+
"object_replication_degree = "+objectReplicationDegree+"\n"+
"start_stat_time = "+startStatTime+"\n"+
"average_server_to_server_net_delay = "+averageServerToServerNetDelay+"\n"+
"average_client_to_server_net_delay = "+averageClientToServerNetDelay;
}
}
| true | true | SimulatorConfGlobal(InputOracle inputOracle){
cacheObjects = (Integer) inputOracle.getParam(Param.NumberOfEntries);
numServers = (Integer) inputOracle.getForecastParam(ForecastParam.NumNodes);
numClients = (Integer) inputOracle.getEvaluatedParam(EvaluatedParam.MAX_ACTIVE_THREADS);
objectReplicationDegree = (Integer) inputOracle.getForecastParam(ForecastParam.ReplicationDegree);
startStatTime = 0L;
averageServerToServerNetDelay = 0L;
averageClientToServerNetDelay = 0L;
}
| SimulatorConfGlobal(InputOracle inputOracle){
cacheObjects = (Integer) inputOracle.getParam(Param.NumberOfEntries);
numServers = (Integer) inputOracle.getForecastParam(ForecastParam.NumNodes);
numClients = (Integer) inputOracle.getEvaluatedParam(EvaluatedParam.MAX_ACTIVE_THREADS) * numServers;
objectReplicationDegree = (Integer) inputOracle.getForecastParam(ForecastParam.ReplicationDegree);
startStatTime = 0L;
averageServerToServerNetDelay = 0L;
averageClientToServerNetDelay = 0L;
}
|
diff --git a/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/startup/SipProtocolHandler.java b/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/startup/SipProtocolHandler.java
index 3eb699f6a..e5f23eae0 100644
--- a/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/startup/SipProtocolHandler.java
+++ b/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/startup/SipProtocolHandler.java
@@ -1,572 +1,572 @@
/*
* This 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 software 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 software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.mobicents.servlet.sip.startup;
import gov.nist.javax.sip.SipStackImpl;
import java.io.File;
import java.io.FileInputStream;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.URI;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import javax.management.MBeanRegistration;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.sip.ListeningPoint;
import javax.sip.SipProvider;
import javax.sip.SipStack;
import net.java.stun4j.StunAddress;
import net.java.stun4j.client.NetworkConfigurationDiscoveryProcess;
import net.java.stun4j.client.StunDiscoveryReport;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.coyote.Adapter;
import org.apache.coyote.ProtocolHandler;
import org.apache.tomcat.util.modeler.Registry;
import org.mobicents.servlet.sip.JainSipUtils;
import org.mobicents.servlet.sip.SipFactories;
import org.mobicents.servlet.sip.core.DNSAddressResolver;
import org.mobicents.servlet.sip.core.ExtendedListeningPoint;
import org.mobicents.servlet.sip.core.SipApplicationDispatcher;
/**
* This is the sip protocol handler that will get called upon creation of the
* tomcat connector defined in the server.xml.<br/> To use a sip connector, one
* need to specify a new connector in server.xml with
* org.mobicents.servlet.sip.startup.SipProtocolHandler as the value for the
* protocol attribute.<br/>
*
* Some of the fields (representing the sip stack propeties) get populated
* automatically by the container.<br/>
*
* @author Jean Deruelle
*
*/
public class SipProtocolHandler implements ProtocolHandler, MBeanRegistration {
// the logger
private static transient Log logger = LogFactory.getLog(SipProtocolHandler.class.getName());
// *
protected ObjectName tpOname = null;
// *
protected ObjectName rgOname = null;
/**
* The random port number generator that we use in getRandomPortNumer()
*/
private static Random portNumberGenerator = new Random();
private Adapter adapter = null;
private Map<String, Object> attributes = new HashMap<String, Object>();
private SipStack sipStack;
/*
* the extended listening point with global ip address and port for it
*/
public ExtendedListeningPoint extendedListeningPoint;
// sip stack attributes defined by the server.xml
private String sipStackPropertiesFile;
// defining sip stack properties
private Properties sipStackProperties;
/**
* the sip stack signaling transport
*/
private String signalingTransport;
/**
* the sip stack listening port
*/
private int port;
/*
* IP address for this protocol handler.
*/
private String ipAddress;
/*
* use Stun
*/
private boolean useStun;
/*
* Stun Server Address
*/
private String stunServerAddress;
/*
* Stun Server Port
*/
private int stunServerPort;
/**
* {@inheritDoc}
*/
public void destroy() throws Exception {
if(logger.isDebugEnabled()) {
logger.debug("Stopping a sip protocol handler");
}
//Jboss specific unloading case
SipApplicationDispatcher sipApplicationDispatcher = (SipApplicationDispatcher)
getAttribute(SipApplicationDispatcher.class.getSimpleName());
if(sipApplicationDispatcher != null) {
if(logger.isDebugEnabled()) {
logger.debug("Removing the Sip Application Dispatcher as a sip listener for listening point " + extendedListeningPoint);
}
extendedListeningPoint.getSipProvider().removeSipListener(sipApplicationDispatcher);
sipApplicationDispatcher.getSipNetworkInterfaceManager().removeExtendedListeningPoint(extendedListeningPoint);
}
// removing listening point and sip provider
if(logger.isDebugEnabled()) {
logger.debug("Removing the following Listening Point " + extendedListeningPoint);
}
sipStack.deleteSipProvider(extendedListeningPoint.getSipProvider());
if(logger.isDebugEnabled()) {
logger.debug("Removing the sip provider");
}
sipStack.deleteListeningPoint(extendedListeningPoint.getListeningPoint());
extendedListeningPoint = null;
// stopping the sip stack
if(!sipStack.getListeningPoints().hasNext() && !sipStack.getSipProviders().hasNext()) {
sipStack.stop();
sipStack = null;
logger.info("Sip stack stopped");
}
if (tpOname!=null)
Registry.getRegistry(null, null).unregisterComponent(tpOname);
if (rgOname != null)
Registry.getRegistry(null, null).unregisterComponent(rgOname);
}
public Adapter getAdapter() {
return adapter;
}
/**
* {@inheritDoc}
*/
public Object getAttribute(String attribute) {
return attributes.get(attribute);
}
/**
* {@inheritDoc}
*/
public Iterator getAttributeNames() {
return attributes.keySet().iterator();
}
/**
* {@inheritDoc}
*/
public void init() throws Exception {
SipFactories.initialize("gov.nist");
setAttribute("isSipConnector",Boolean.TRUE);
}
public void pause() throws Exception {
//This is optionnal, no implementation there
}
public void resume() throws Exception {
// This is optionnal, no implementation there
}
public void setAdapter(Adapter adapter) {
this.adapter = adapter;
}
/**
* {@inheritDoc}
*/
public void setAttribute(String arg0, Object arg1) {
attributes.put(arg0, arg1);
}
public void start() throws Exception {
try {
if(logger.isDebugEnabled()) {
logger.debug("Starting a sip protocol handler");
}
String catalinaHome = System.getProperty("catalina.home");
if (catalinaHome == null) {
catalinaHome = System.getProperty("catalina.base");
}
if(catalinaHome == null) {
catalinaHome = ".";
}
if(sipStackPropertiesFile != null && !sipStackPropertiesFile.startsWith("file:///")) {
sipStackPropertiesFile = "file:///" + catalinaHome.replace(File.separatorChar, '/') + "/" + sipStackPropertiesFile;
}
sipStackProperties = new Properties();
boolean isPropsLoaded = false;
try {
if (logger.isDebugEnabled()) {
logger.debug("Loading SIP stack properties from following file : " + sipStackPropertiesFile);
}
if(sipStackPropertiesFile != null) {
FileInputStream sipStackPropertiesInputStream = new FileInputStream(new File(new URI(sipStackPropertiesFile)));
sipStackProperties.load(sipStackPropertiesInputStream);
String debugLog = sipStackProperties.getProperty("gov.nist.javax.sip.DEBUG_LOG");
if(debugLog != null && debugLog.length() > 0 && !debugLog.startsWith("file:///")) {
sipStackProperties.setProperty("gov.nist.javax.sip.DEBUG_LOG",
- catalinaHome + "/" + debugLog);
+ "file:///" + catalinaHome + "/" + debugLog);
}
String serverLog = sipStackProperties.getProperty("gov.nist.javax.sip.SERVER_LOG");
if(serverLog != null && serverLog.length() > 0 && !serverLog.startsWith("file:///")) {
sipStackProperties.setProperty("gov.nist.javax.sip.SERVER_LOG",
- catalinaHome + "/" + serverLog);
+ "file:///" + catalinaHome + "/" + serverLog);
}
isPropsLoaded = true;
} else {
logger.warn("no sip stack properties file defined ");
}
} catch (Exception e) {
logger.warn("Could not find or problem when loading the sip stack properties file : " + sipStackPropertiesFile, e);
}
if(!isPropsLoaded) {
logger.warn("loading default Mobicents Sip Servlets sip stack properties");
// Silently set default values
sipStackProperties.setProperty("gov.nist.javax.sip.LOG_MESSAGE_CONTENT",
"true");
sipStackProperties.setProperty("gov.nist.javax.sip.TRACE_LEVEL",
"32");
sipStackProperties.setProperty("gov.nist.javax.sip.DEBUG_LOG",
- catalinaHome + "/" + "mss-jsip-" + ipAddress + "-" + port+"-debug.txt");
+ "file:///" + catalinaHome + "/" + "mss-jsip-" + ipAddress + "-" + port+"-debug.txt");
sipStackProperties.setProperty("gov.nist.javax.sip.SERVER_LOG",
- catalinaHome + "/" + "mss-jsip-" + ipAddress + "-" + port+"-messages.xml");
+ "file:///" + catalinaHome + "/" + "mss-jsip-" + ipAddress + "-" + port+"-messages.xml");
sipStackProperties.setProperty("javax.sip.STACK_NAME", "mss-" + ipAddress + "-" + port);
sipStackProperties.setProperty("javax.sip.AUTOMATIC_DIALOG_SUPPORT", "off");
sipStackProperties.setProperty("gov.nist.javax.sip.DELIVER_UNSOLICITED_NOTIFY", "true");
sipStackProperties.setProperty("gov.nist.javax.sip.THREAD_POOL_SIZE", "64");
sipStackProperties.setProperty("gov.nist.javax.sip.REENTRANT_LISTENER", "true");
}
//checking the external ip address if stun enabled
String globalIpAddress = null;
int globalPort = -1;
if (useStun) {
if(InetAddress.getByName(ipAddress).isLoopbackAddress()) {
logger.warn("The Ip address provided is the loopback address, stun won't be enabled for it");
} else {
//chooses stun port randomly
DatagramSocket randomSocket = initRandomPortSocket();
int randomPort = randomSocket.getLocalPort();
randomSocket.disconnect();
randomSocket.close();
randomSocket = null;
StunAddress localStunAddress = new StunAddress(ipAddress,
randomPort);
StunAddress serverStunAddress = new StunAddress(
stunServerAddress, stunServerPort);
NetworkConfigurationDiscoveryProcess addressDiscovery = new NetworkConfigurationDiscoveryProcess(
localStunAddress, serverStunAddress);
addressDiscovery.start();
StunDiscoveryReport report = addressDiscovery
.determineAddress();
if(report.getPublicAddress() != null) {
globalIpAddress = report.getPublicAddress().getSocketAddress().getAddress().getHostAddress();
globalPort = report.getPublicAddress().getPort();
//TODO set a timer to retry the binding and provide a callback to update the global ip address and port
} else {
useStun = false;
logger.error("Stun discovery failed to find a valid public ip address, disabling stun !");
}
logger.info("Stun report = " + report);
addressDiscovery.shutDown();
}
}
if(logger.isInfoEnabled()) {
logger.info("Mobicents Sip Servlets sip stack properties : " + sipStackProperties);
}
// Create SipStack object
sipStack = SipFactories.sipFactory.createSipStack(sipStackProperties);
ListeningPoint listeningPoint = sipStack.createListeningPoint(ipAddress,
port, signalingTransport);
if(useStun) {
// listeningPoint.setSentBy(globalIpAddress + ":" + globalPort);
listeningPoint.setSentBy(globalIpAddress + ":" + port);
}
SipProvider sipProvider = sipStack.createSipProvider(listeningPoint);
sipStack.start();
//creating the extended listening point
extendedListeningPoint = new ExtendedListeningPoint(sipProvider, listeningPoint);
extendedListeningPoint.setGlobalIpAddress(globalIpAddress);
extendedListeningPoint.setGlobalPort(globalPort);
//TODO add it as a listener for global ip address changes if STUN rediscover a new addess at some point
//made the sip stack and the extended listening Point available to the service implementation
setAttribute(SipStack.class.getSimpleName(), sipStack);
setAttribute(ExtendedListeningPoint.class.getSimpleName(), extendedListeningPoint);
//Jboss specific loading case
SipApplicationDispatcher sipApplicationDispatcher = (SipApplicationDispatcher)
getAttribute(SipApplicationDispatcher.class.getSimpleName());
if(sipApplicationDispatcher != null) {
if(logger.isDebugEnabled()) {
logger.debug("Adding the Sip Application Dispatcher as a sip listener for connector listening on port " + port);
}
sipProvider.addSipListener(sipApplicationDispatcher);
sipApplicationDispatcher.getSipNetworkInterfaceManager().addExtendedListeningPoint(extendedListeningPoint);
// for nist sip stack set the DNS Address resolver allowing to make DNS SRV lookups
if(sipStack instanceof SipStackImpl) {
if(logger.isDebugEnabled()) {
logger.debug(sipStack.getStackName() +" will be using DNS SRV lookups as AddressResolver");
}
((SipStackImpl) sipStack).setAddressResolver(new DNSAddressResolver(sipApplicationDispatcher));
}
}
logger.info("Sip Connector started on ip address : " + ipAddress
+ ",port " + port + ", useStun " + useStun + ", stunAddress " + stunServerAddress + ", stunPort : " + stunServerPort);
if (this.domain != null) {
// try {
// tpOname = new ObjectName
// (domain + ":" + "type=ThreadPool,name=" + getName());
// Registry.getRegistry(null, null)
// .registerComponent(endpoint, tpOname, null );
// } catch (Exception e) {
// logger.error("Can't register endpoint");
// }
rgOname=new ObjectName
(domain + ":type=GlobalRequestProcessor,name=" + getName());
Registry.getRegistry(null, null).registerComponent
( sipStack, rgOname, null );
}
} catch (Exception ex) {
logger.fatal(
"Bad shit happened -- check server.xml for tomcat. ", ex);
throw ex;
}
}
/**
* Initializes and binds a socket that on a random port number. The method
* would try to bind on a random port and retry 5 times until a free port
* is found.
*
* @return the socket that we have initialized on a randomport number.
*/
private DatagramSocket initRandomPortSocket() {
int bindRetries = 5;
int currentlyTriedPort =
getRandomPortNumber(JainSipUtils.MIN_PORT_NUMBER, JainSipUtils.MAX_PORT_NUMBER);
DatagramSocket resultSocket = null;
//we'll first try to bind to a random port. if this fails we'll try
//again (bindRetries times in all) until we find a free local port.
for (int i = 0; i < bindRetries; i++) {
try {
resultSocket = new DatagramSocket(currentlyTriedPort);
//we succeeded - break so that we don't try to bind again
break;
}
catch (SocketException exc) {
if (exc.getMessage().indexOf("Address already in use") == -1) {
logger.fatal("An exception occurred while trying to create"
+ "a local host discovery socket.", exc);
return null;
}
//port seems to be taken. try another one.
logger.debug("Port " + currentlyTriedPort + " seems in use.");
currentlyTriedPort =
getRandomPortNumber(JainSipUtils.MIN_PORT_NUMBER, JainSipUtils.MAX_PORT_NUMBER);
logger.debug("Retrying bind on port " + currentlyTriedPort);
}
}
return resultSocket;
}
/**
* Returns a random local port number, greater than min and lower than max.
*
* @param min the minimum allowed value for the returned port number.
* @param max the maximum allowed value for the returned port number.
*
* @return a random int located between greater than min and lower than max.
*/
public static int getRandomPortNumber(int min, int max) {
return portNumberGenerator.nextInt(max - min) + min;
}
/**
* @return the signalingTransport
*/
public String getSignalingTransport() {
return signalingTransport;
}
/**
* @param signalingTransport
* the signalingTransport to set
*/
public void setSignalingTransport(String transport) {
this.signalingTransport = transport;
}
/**
* @return the port
*/
public int getPort() {
return port;
}
/**
* @param port
* the port to set
*/
public void setPort(int port) {
this.port = port;
}
public void setIpAddress(String ipAddress) {
this.ipAddress = ipAddress;
}
public String getIpAddress() {
return ipAddress;
}
/**
* @return the stunServerAddress
*/
public String getStunServerAddress() {
return stunServerAddress;
}
/**
* @param stunServerAddress the stunServerAddress to set
*/
public void setStunServerAddress(String stunServerAddress) {
this.stunServerAddress = stunServerAddress;
}
/**
* @return the stunServerPort
*/
public int getStunServerPort() {
return stunServerPort;
}
/**
* @param stunServerPort the stunServerPort to set
*/
public void setStunServerPort(int stunServerPort) {
this.stunServerPort = stunServerPort;
}
/**
* @return the useStun
*/
public boolean isUseStun() {
return useStun;
}
/**
* @param useStun the useStun to set
*/
public void setUseStun(boolean useStun) {
this.useStun = useStun;
}
public InetAddress getAddress() {
try {
return InetAddress.getByName(ipAddress);
} catch (UnknownHostException e) {
logger.error("unexpected exception while getting the ipaddress of the sip protocol handler", e);
return null;
}
}
public void setAddress(InetAddress ia) { ipAddress = ia.getHostAddress(); }
public String getName() {
String encodedAddr = "";
if (getAddress() != null) {
encodedAddr = "" + getAddress();
if (encodedAddr.startsWith("/"))
encodedAddr = encodedAddr.substring(1);
encodedAddr = URLEncoder.encode(encodedAddr) + "-";
}
return ("sip-" + encodedAddr + getPort());
}
/**
* @param sipStackPropertiesFile the sipStackPropertiesFile to set
*/
public void setSipStackPropertiesFile(String sipStackPropertiesFile) {
this.sipStackPropertiesFile = sipStackPropertiesFile;
}
/**
* @return the sipStackPropertiesFile
*/
public String getSipStackPropertiesFile() {
return sipStackPropertiesFile;
}
// -------------------- JMX related methods --------------------
// *
protected String domain;
protected ObjectName oname;
protected MBeanServer mserver;
public ObjectName getObjectName() {
return oname;
}
public String getDomain() {
return domain;
}
public ObjectName preRegister(MBeanServer server,
ObjectName name) throws Exception {
oname=name;
mserver=server;
domain=name.getDomain();
return name;
}
public void postRegister(Boolean registrationDone) {
}
public void preDeregister() throws Exception {
}
public void postDeregister() {
}
}
| false | true | public void start() throws Exception {
try {
if(logger.isDebugEnabled()) {
logger.debug("Starting a sip protocol handler");
}
String catalinaHome = System.getProperty("catalina.home");
if (catalinaHome == null) {
catalinaHome = System.getProperty("catalina.base");
}
if(catalinaHome == null) {
catalinaHome = ".";
}
if(sipStackPropertiesFile != null && !sipStackPropertiesFile.startsWith("file:///")) {
sipStackPropertiesFile = "file:///" + catalinaHome.replace(File.separatorChar, '/') + "/" + sipStackPropertiesFile;
}
sipStackProperties = new Properties();
boolean isPropsLoaded = false;
try {
if (logger.isDebugEnabled()) {
logger.debug("Loading SIP stack properties from following file : " + sipStackPropertiesFile);
}
if(sipStackPropertiesFile != null) {
FileInputStream sipStackPropertiesInputStream = new FileInputStream(new File(new URI(sipStackPropertiesFile)));
sipStackProperties.load(sipStackPropertiesInputStream);
String debugLog = sipStackProperties.getProperty("gov.nist.javax.sip.DEBUG_LOG");
if(debugLog != null && debugLog.length() > 0 && !debugLog.startsWith("file:///")) {
sipStackProperties.setProperty("gov.nist.javax.sip.DEBUG_LOG",
catalinaHome + "/" + debugLog);
}
String serverLog = sipStackProperties.getProperty("gov.nist.javax.sip.SERVER_LOG");
if(serverLog != null && serverLog.length() > 0 && !serverLog.startsWith("file:///")) {
sipStackProperties.setProperty("gov.nist.javax.sip.SERVER_LOG",
catalinaHome + "/" + serverLog);
}
isPropsLoaded = true;
} else {
logger.warn("no sip stack properties file defined ");
}
} catch (Exception e) {
logger.warn("Could not find or problem when loading the sip stack properties file : " + sipStackPropertiesFile, e);
}
if(!isPropsLoaded) {
logger.warn("loading default Mobicents Sip Servlets sip stack properties");
// Silently set default values
sipStackProperties.setProperty("gov.nist.javax.sip.LOG_MESSAGE_CONTENT",
"true");
sipStackProperties.setProperty("gov.nist.javax.sip.TRACE_LEVEL",
"32");
sipStackProperties.setProperty("gov.nist.javax.sip.DEBUG_LOG",
catalinaHome + "/" + "mss-jsip-" + ipAddress + "-" + port+"-debug.txt");
sipStackProperties.setProperty("gov.nist.javax.sip.SERVER_LOG",
catalinaHome + "/" + "mss-jsip-" + ipAddress + "-" + port+"-messages.xml");
sipStackProperties.setProperty("javax.sip.STACK_NAME", "mss-" + ipAddress + "-" + port);
sipStackProperties.setProperty("javax.sip.AUTOMATIC_DIALOG_SUPPORT", "off");
sipStackProperties.setProperty("gov.nist.javax.sip.DELIVER_UNSOLICITED_NOTIFY", "true");
sipStackProperties.setProperty("gov.nist.javax.sip.THREAD_POOL_SIZE", "64");
sipStackProperties.setProperty("gov.nist.javax.sip.REENTRANT_LISTENER", "true");
}
//checking the external ip address if stun enabled
String globalIpAddress = null;
int globalPort = -1;
if (useStun) {
if(InetAddress.getByName(ipAddress).isLoopbackAddress()) {
logger.warn("The Ip address provided is the loopback address, stun won't be enabled for it");
} else {
//chooses stun port randomly
DatagramSocket randomSocket = initRandomPortSocket();
int randomPort = randomSocket.getLocalPort();
randomSocket.disconnect();
randomSocket.close();
randomSocket = null;
StunAddress localStunAddress = new StunAddress(ipAddress,
randomPort);
StunAddress serverStunAddress = new StunAddress(
stunServerAddress, stunServerPort);
NetworkConfigurationDiscoveryProcess addressDiscovery = new NetworkConfigurationDiscoveryProcess(
localStunAddress, serverStunAddress);
addressDiscovery.start();
StunDiscoveryReport report = addressDiscovery
.determineAddress();
if(report.getPublicAddress() != null) {
globalIpAddress = report.getPublicAddress().getSocketAddress().getAddress().getHostAddress();
globalPort = report.getPublicAddress().getPort();
//TODO set a timer to retry the binding and provide a callback to update the global ip address and port
} else {
useStun = false;
logger.error("Stun discovery failed to find a valid public ip address, disabling stun !");
}
logger.info("Stun report = " + report);
addressDiscovery.shutDown();
}
}
if(logger.isInfoEnabled()) {
logger.info("Mobicents Sip Servlets sip stack properties : " + sipStackProperties);
}
// Create SipStack object
sipStack = SipFactories.sipFactory.createSipStack(sipStackProperties);
ListeningPoint listeningPoint = sipStack.createListeningPoint(ipAddress,
port, signalingTransport);
if(useStun) {
// listeningPoint.setSentBy(globalIpAddress + ":" + globalPort);
listeningPoint.setSentBy(globalIpAddress + ":" + port);
}
SipProvider sipProvider = sipStack.createSipProvider(listeningPoint);
sipStack.start();
//creating the extended listening point
extendedListeningPoint = new ExtendedListeningPoint(sipProvider, listeningPoint);
extendedListeningPoint.setGlobalIpAddress(globalIpAddress);
extendedListeningPoint.setGlobalPort(globalPort);
//TODO add it as a listener for global ip address changes if STUN rediscover a new addess at some point
//made the sip stack and the extended listening Point available to the service implementation
setAttribute(SipStack.class.getSimpleName(), sipStack);
setAttribute(ExtendedListeningPoint.class.getSimpleName(), extendedListeningPoint);
//Jboss specific loading case
SipApplicationDispatcher sipApplicationDispatcher = (SipApplicationDispatcher)
getAttribute(SipApplicationDispatcher.class.getSimpleName());
if(sipApplicationDispatcher != null) {
if(logger.isDebugEnabled()) {
logger.debug("Adding the Sip Application Dispatcher as a sip listener for connector listening on port " + port);
}
sipProvider.addSipListener(sipApplicationDispatcher);
sipApplicationDispatcher.getSipNetworkInterfaceManager().addExtendedListeningPoint(extendedListeningPoint);
// for nist sip stack set the DNS Address resolver allowing to make DNS SRV lookups
if(sipStack instanceof SipStackImpl) {
if(logger.isDebugEnabled()) {
logger.debug(sipStack.getStackName() +" will be using DNS SRV lookups as AddressResolver");
}
((SipStackImpl) sipStack).setAddressResolver(new DNSAddressResolver(sipApplicationDispatcher));
}
}
logger.info("Sip Connector started on ip address : " + ipAddress
+ ",port " + port + ", useStun " + useStun + ", stunAddress " + stunServerAddress + ", stunPort : " + stunServerPort);
if (this.domain != null) {
// try {
// tpOname = new ObjectName
// (domain + ":" + "type=ThreadPool,name=" + getName());
// Registry.getRegistry(null, null)
// .registerComponent(endpoint, tpOname, null );
// } catch (Exception e) {
// logger.error("Can't register endpoint");
// }
rgOname=new ObjectName
(domain + ":type=GlobalRequestProcessor,name=" + getName());
Registry.getRegistry(null, null).registerComponent
( sipStack, rgOname, null );
}
} catch (Exception ex) {
logger.fatal(
"Bad shit happened -- check server.xml for tomcat. ", ex);
throw ex;
}
}
| public void start() throws Exception {
try {
if(logger.isDebugEnabled()) {
logger.debug("Starting a sip protocol handler");
}
String catalinaHome = System.getProperty("catalina.home");
if (catalinaHome == null) {
catalinaHome = System.getProperty("catalina.base");
}
if(catalinaHome == null) {
catalinaHome = ".";
}
if(sipStackPropertiesFile != null && !sipStackPropertiesFile.startsWith("file:///")) {
sipStackPropertiesFile = "file:///" + catalinaHome.replace(File.separatorChar, '/') + "/" + sipStackPropertiesFile;
}
sipStackProperties = new Properties();
boolean isPropsLoaded = false;
try {
if (logger.isDebugEnabled()) {
logger.debug("Loading SIP stack properties from following file : " + sipStackPropertiesFile);
}
if(sipStackPropertiesFile != null) {
FileInputStream sipStackPropertiesInputStream = new FileInputStream(new File(new URI(sipStackPropertiesFile)));
sipStackProperties.load(sipStackPropertiesInputStream);
String debugLog = sipStackProperties.getProperty("gov.nist.javax.sip.DEBUG_LOG");
if(debugLog != null && debugLog.length() > 0 && !debugLog.startsWith("file:///")) {
sipStackProperties.setProperty("gov.nist.javax.sip.DEBUG_LOG",
"file:///" + catalinaHome + "/" + debugLog);
}
String serverLog = sipStackProperties.getProperty("gov.nist.javax.sip.SERVER_LOG");
if(serverLog != null && serverLog.length() > 0 && !serverLog.startsWith("file:///")) {
sipStackProperties.setProperty("gov.nist.javax.sip.SERVER_LOG",
"file:///" + catalinaHome + "/" + serverLog);
}
isPropsLoaded = true;
} else {
logger.warn("no sip stack properties file defined ");
}
} catch (Exception e) {
logger.warn("Could not find or problem when loading the sip stack properties file : " + sipStackPropertiesFile, e);
}
if(!isPropsLoaded) {
logger.warn("loading default Mobicents Sip Servlets sip stack properties");
// Silently set default values
sipStackProperties.setProperty("gov.nist.javax.sip.LOG_MESSAGE_CONTENT",
"true");
sipStackProperties.setProperty("gov.nist.javax.sip.TRACE_LEVEL",
"32");
sipStackProperties.setProperty("gov.nist.javax.sip.DEBUG_LOG",
"file:///" + catalinaHome + "/" + "mss-jsip-" + ipAddress + "-" + port+"-debug.txt");
sipStackProperties.setProperty("gov.nist.javax.sip.SERVER_LOG",
"file:///" + catalinaHome + "/" + "mss-jsip-" + ipAddress + "-" + port+"-messages.xml");
sipStackProperties.setProperty("javax.sip.STACK_NAME", "mss-" + ipAddress + "-" + port);
sipStackProperties.setProperty("javax.sip.AUTOMATIC_DIALOG_SUPPORT", "off");
sipStackProperties.setProperty("gov.nist.javax.sip.DELIVER_UNSOLICITED_NOTIFY", "true");
sipStackProperties.setProperty("gov.nist.javax.sip.THREAD_POOL_SIZE", "64");
sipStackProperties.setProperty("gov.nist.javax.sip.REENTRANT_LISTENER", "true");
}
//checking the external ip address if stun enabled
String globalIpAddress = null;
int globalPort = -1;
if (useStun) {
if(InetAddress.getByName(ipAddress).isLoopbackAddress()) {
logger.warn("The Ip address provided is the loopback address, stun won't be enabled for it");
} else {
//chooses stun port randomly
DatagramSocket randomSocket = initRandomPortSocket();
int randomPort = randomSocket.getLocalPort();
randomSocket.disconnect();
randomSocket.close();
randomSocket = null;
StunAddress localStunAddress = new StunAddress(ipAddress,
randomPort);
StunAddress serverStunAddress = new StunAddress(
stunServerAddress, stunServerPort);
NetworkConfigurationDiscoveryProcess addressDiscovery = new NetworkConfigurationDiscoveryProcess(
localStunAddress, serverStunAddress);
addressDiscovery.start();
StunDiscoveryReport report = addressDiscovery
.determineAddress();
if(report.getPublicAddress() != null) {
globalIpAddress = report.getPublicAddress().getSocketAddress().getAddress().getHostAddress();
globalPort = report.getPublicAddress().getPort();
//TODO set a timer to retry the binding and provide a callback to update the global ip address and port
} else {
useStun = false;
logger.error("Stun discovery failed to find a valid public ip address, disabling stun !");
}
logger.info("Stun report = " + report);
addressDiscovery.shutDown();
}
}
if(logger.isInfoEnabled()) {
logger.info("Mobicents Sip Servlets sip stack properties : " + sipStackProperties);
}
// Create SipStack object
sipStack = SipFactories.sipFactory.createSipStack(sipStackProperties);
ListeningPoint listeningPoint = sipStack.createListeningPoint(ipAddress,
port, signalingTransport);
if(useStun) {
// listeningPoint.setSentBy(globalIpAddress + ":" + globalPort);
listeningPoint.setSentBy(globalIpAddress + ":" + port);
}
SipProvider sipProvider = sipStack.createSipProvider(listeningPoint);
sipStack.start();
//creating the extended listening point
extendedListeningPoint = new ExtendedListeningPoint(sipProvider, listeningPoint);
extendedListeningPoint.setGlobalIpAddress(globalIpAddress);
extendedListeningPoint.setGlobalPort(globalPort);
//TODO add it as a listener for global ip address changes if STUN rediscover a new addess at some point
//made the sip stack and the extended listening Point available to the service implementation
setAttribute(SipStack.class.getSimpleName(), sipStack);
setAttribute(ExtendedListeningPoint.class.getSimpleName(), extendedListeningPoint);
//Jboss specific loading case
SipApplicationDispatcher sipApplicationDispatcher = (SipApplicationDispatcher)
getAttribute(SipApplicationDispatcher.class.getSimpleName());
if(sipApplicationDispatcher != null) {
if(logger.isDebugEnabled()) {
logger.debug("Adding the Sip Application Dispatcher as a sip listener for connector listening on port " + port);
}
sipProvider.addSipListener(sipApplicationDispatcher);
sipApplicationDispatcher.getSipNetworkInterfaceManager().addExtendedListeningPoint(extendedListeningPoint);
// for nist sip stack set the DNS Address resolver allowing to make DNS SRV lookups
if(sipStack instanceof SipStackImpl) {
if(logger.isDebugEnabled()) {
logger.debug(sipStack.getStackName() +" will be using DNS SRV lookups as AddressResolver");
}
((SipStackImpl) sipStack).setAddressResolver(new DNSAddressResolver(sipApplicationDispatcher));
}
}
logger.info("Sip Connector started on ip address : " + ipAddress
+ ",port " + port + ", useStun " + useStun + ", stunAddress " + stunServerAddress + ", stunPort : " + stunServerPort);
if (this.domain != null) {
// try {
// tpOname = new ObjectName
// (domain + ":" + "type=ThreadPool,name=" + getName());
// Registry.getRegistry(null, null)
// .registerComponent(endpoint, tpOname, null );
// } catch (Exception e) {
// logger.error("Can't register endpoint");
// }
rgOname=new ObjectName
(domain + ":type=GlobalRequestProcessor,name=" + getName());
Registry.getRegistry(null, null).registerComponent
( sipStack, rgOname, null );
}
} catch (Exception ex) {
logger.fatal(
"Bad shit happened -- check server.xml for tomcat. ", ex);
throw ex;
}
}
|
diff --git a/source/RMG/jing/rxn/PDepIsomer.java b/source/RMG/jing/rxn/PDepIsomer.java
index b1ebbaac..0aba7919 100644
--- a/source/RMG/jing/rxn/PDepIsomer.java
+++ b/source/RMG/jing/rxn/PDepIsomer.java
@@ -1,347 +1,347 @@
////////////////////////////////////////////////////////////////////////////////
//
// RMG - Reaction Mechanism Generator
//
// Copyright (c) 2002-2009 Prof. William H. Green ([email protected]) and the
// RMG Team ([email protected])
//
// 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 jing.rxn;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.ListIterator;
import jing.chem.ChemGraph;
import jing.chem.Species;
import jing.chem.SpeciesDictionary;
import jing.param.Temperature;
import jing.rxnSys.CoreEdgeReactionModel;
import jing.rxnSys.ReactionSystem;
/**
* Represents a single isomer (unimolecular or multimolecular) of a pressure-
* dependent network. In this context an isomer refers to one or more
* species wherein the total number of each element in all species matches
* the total number of that species in every other isomer of the network.
* @author jwallen
*/
public class PDepIsomer {
//==========================================================================
//
// Data members
//
/**
* A linked list containing the species that make up the isomer.
*/
private LinkedList<Species> speciesList;
/**
* Set to true if the pathways from this isomer is included in the network.
*/
private boolean included;
//==========================================================================
//
// Constructors
//
/**
* Constructor for unimolecular isomers.
* @param species The species the isomer represents.
*/
public PDepIsomer(Species species) {
speciesList = new LinkedList<Species>();
speciesList.add(species);
included = false;
}
/**
* Constructor for bimolecular isomers.
* @param species1 The first species the isomer represents.
* @param species2 The second species the isomer represents.
*/
public PDepIsomer(Species species1, Species species2) {
speciesList = new LinkedList<Species>();
speciesList.add(species1);
speciesList.add(species2);
included = true;
}
/**
* Constructor for generic isomers.
* @param speList A list of species the isomer represents.
*/
public PDepIsomer(LinkedList speList) {
speciesList = new LinkedList<Species>();
for (int i = 0; i < speList.size(); i++) {
Object obj = speList.get(i);
if (obj instanceof Species)
speciesList.add((Species) obj);
else if (obj instanceof ChemGraph)
speciesList.add(SpeciesDictionary.getSpecies((ChemGraph) obj));
}
included = (speList.size() > 1);
}
//==========================================================================
//
// Accessors
//
/**
* Returns the ith species of the isomer.
* @param i The index of the species to return
* @return The species corresponding to index i
*/
public Species getSpecies(int i) {
return speciesList.get(i);
}
/**
* Returns the entire list of species in the isomer.
* @return The list of species in the isomer
*/
public LinkedList<Species> getSpeciesList() {
return speciesList;
}
/**
* Returns an iterator to the first species in the isomer
* @return An iterator to the first species in the isomer
*/
public ListIterator<Species> getSpeciesListIterator() {
return speciesList.listIterator();
}
/**
* Returns the number of species in the isomer.
* @return The number of species in the isomer.
*/
public int getNumSpecies() {
return speciesList.size();
}
/**
* Returns a string containing the names and IDs of each species in the
* isomer in the form "A(1) + B(2) + ...".
* @return The names and IDs of each species in the isomer
*/
public String getSpeciesNames() {
String str = speciesList.get(0).getName() + "(" +
Integer.toString(speciesList.get(0).getID()) + ")";
for (int i = 1; i < speciesList.size(); i++) {
str += " + " + ((Species) speciesList.get(i)).getName() + "(" +
Integer.toString(speciesList.get(i).getID()) + ")";
}
return str;
}
/**
* Returns a string containing the names and IDs of each species in the
* isomer in the form "A(1) + B(2) + ...".
* @return The names and IDs of each species in the isomer
*/
@Override
public String toString() {
return getSpeciesNames();
}
/**
* Returns the included status the isomer.
* @return The included status the isomer.
*/
public boolean getIncluded() {
return included;
}
/**
* Sets the included status the isomer.
* @param incl The new included status the isomer.
*/
public void setIncluded(boolean incl) {
included = incl;
}
//==========================================================================
//
// Other methods
//
/**
* Returns true if the isomer is unimolecular and false otherwise.
* @return True if the isomer is unimolecular and false otherwise
*/
public boolean isUnimolecular() {
if (speciesList == null) return false;
return speciesList.size() == 1;
}
/**
* Returns true if the isomer is multimolecular and false otherwise.
* @return True if the isomer is multimolecular and false otherwise
*/
public boolean isMultimolecular() {
if (speciesList == null) return false;
return speciesList.size() > 1;
}
/**
* Calculates the total Gibbs free energy of the isomer at the specified
* temperature.
* @param temperature The temperature at which to do the calculation
* @return The total Gibbs free energy of the isomer
*/
public double calculateG(Temperature temperature) {
double G = 0;
for (int i = 0; i < speciesList.size(); i++) {
G += speciesList.get(i).calculateG(temperature);
}
return G;
}
/**
* Calculates the Gibbs free energy of the ith species of the isomer at the
* specified temperature.
* @param species The index of the species
* @param temperature The temperature at which to do the calculation
* @return The Gibbs free energy of the ith species
*/
public double calculateG(int species, Temperature temperature) {
return speciesList.get(species).calculateG(temperature);
}
/**
* Calculates the total enthalpy of the isomer at the specified
* temperature.
* @param temperature The temperature at which to do the calculation
* @return The total enthalpy of the isomer
*/
public double calculateH(Temperature temperature) {
double H = 0;
for (int i = 0; i < speciesList.size(); i++) {
H += speciesList.get(i).calculateH(temperature);
}
return H;
}
/**
* Calculates the enthalpy of the ith species of the isomer at the
* specified temperature.
* @param species The index of the species
* @param temperature The temperature at which to do the calculation
* @return The enthalpy of the ith species
*/
public double calculateH(int species, Temperature temperature) {
return speciesList.get(species).calculateH(temperature);
}
/**
* Returns the total molecular weight of the isomer.
* @return The total molecular weight of the isomer
*/
public double getMolecularWeight() {
double molWt = 0;
for (int i = 0; i < speciesList.size(); i++) {
molWt += speciesList.get(i).getMolecularWeight();
}
return molWt;
}
/**
* Returns the molecular weight of the ith species of the isomer.
* @param species The index of the species
* @return The molecular weight of the ith species
*/
public double getMolecularWeight(int species) {
return speciesList.get(species).getMolecularWeight();
}
/**
* Implements the equals method common to all Java objects. This method
* calls other versions of equals() based on the type of the object passed.
* @param object An object to compare the isomer to.
* @return True if the isomer and the object are equal, false if not
*/
@Override
public boolean equals(Object object) {
if (object instanceof PDepIsomer)
return equals((PDepIsomer) object);
else
return false;
}
/**
* Returns true if the current object and isomer have all of the same
* species, no matter what order the species are stored in each object's
* species list.
* @param isomer The isomer to compare the current isomer to
* @return True if the two isomers have all of the same species, false if not
*/
public boolean equals(PDepIsomer isomer) {
if (getNumSpecies() != isomer.getNumSpecies())
return false;
else {
for (int i = 0; i < getNumSpecies(); i++) {
Species speciesI = speciesList.get(i);
boolean found = false;
for (int j = 0; j < isomer.getNumSpecies(); j++) {
- Species speciesJ = isomer.speciesList.get(i);
+ Species speciesJ = isomer.speciesList.get(j);
if (speciesI.equals(speciesJ))
found = true;
}
if (!found)
return false;
}
return true;
}
}
/**
* Returns all of the pressure-dependent pathways involving the current isomer.
* @param rxnSystem A reaction system to use to access the template and library reaction generators.
* @return A hash set of the pressure-dependent pathways involving the current isomer
*/
public LinkedHashSet generatePaths(ReactionSystem rxnSystem) {
if (!isUnimolecular())
return new LinkedHashSet();
LinkedHashSet reactionSet = ((TemplateReactionGenerator) rxnSystem.getReactionGenerator()).generatePdepReactions(getSpecies(0));
reactionSet.addAll(((LibraryReactionGenerator) rxnSystem.getLibraryReactionGenerator()).generatePdepReactions(getSpecies(0)));
return reactionSet;
}
/**
* Checks to see if the isomer is in the model core (i.e. all of the
* species in the isomer are core species).
* @param cerm The current core-edge reaction model
* @return True if all species are in the model core, false if not
*/
public boolean isCore(CoreEdgeReactionModel cerm) {
for (int i = 0; i < speciesList.size(); i++) {
if (!cerm.containsAsReactedSpecies(speciesList.get(i)))
return false;
}
return true;
}
}
| true | true | public boolean equals(PDepIsomer isomer) {
if (getNumSpecies() != isomer.getNumSpecies())
return false;
else {
for (int i = 0; i < getNumSpecies(); i++) {
Species speciesI = speciesList.get(i);
boolean found = false;
for (int j = 0; j < isomer.getNumSpecies(); j++) {
Species speciesJ = isomer.speciesList.get(i);
if (speciesI.equals(speciesJ))
found = true;
}
if (!found)
return false;
}
return true;
}
}
| public boolean equals(PDepIsomer isomer) {
if (getNumSpecies() != isomer.getNumSpecies())
return false;
else {
for (int i = 0; i < getNumSpecies(); i++) {
Species speciesI = speciesList.get(i);
boolean found = false;
for (int j = 0; j < isomer.getNumSpecies(); j++) {
Species speciesJ = isomer.speciesList.get(j);
if (speciesI.equals(speciesJ))
found = true;
}
if (!found)
return false;
}
return true;
}
}
|
diff --git a/structure/src/main/java/org/biojava/bio/structure/align/StructureAlignmentFactory.java b/structure/src/main/java/org/biojava/bio/structure/align/StructureAlignmentFactory.java
index 7849ae4b1..ea365adb2 100644
--- a/structure/src/main/java/org/biojava/bio/structure/align/StructureAlignmentFactory.java
+++ b/structure/src/main/java/org/biojava/bio/structure/align/StructureAlignmentFactory.java
@@ -1,45 +1,45 @@
package org.biojava.bio.structure.align;
import java.util.ArrayList;
import java.util.List;
import org.biojava.bio.structure.StructureException;
import org.biojava.bio.structure.align.ce.CeMain;
import org.biojava.bio.structure.align.ce.CeSideChainMain;
import org.biojava.bio.structure.align.seq.SmithWaterman3Daligner;
public class StructureAlignmentFactory {
public static StructureAlignment[] getAllAlgorithms(){
- StructureAlignment[] algorithms = new StructureAlignment[5];
+ StructureAlignment[] algorithms = new StructureAlignment[3];
algorithms[0] = new CeMain();
algorithms[1] = new CeSideChainMain();
algorithms[2] = new SmithWaterman3Daligner();
//algorithms[3] = new BioJavaStructureAlignment();
return algorithms;
}
public static StructureAlignment getAlgorithm(String name) throws StructureException{
StructureAlignment[] algorithms = getAllAlgorithms();
for ( StructureAlignment algo : algorithms){
if (algo.getAlgorithmName().equalsIgnoreCase(name))
return algo;
}
throw new StructureException("Unknown alignment algorithm: " + name);
}
public static String[] getAllAlgorithmNames(){
StructureAlignment[] algos = getAllAlgorithms();
List<String> names = new ArrayList<String>();
for (StructureAlignment alg : algos){
names.add(alg.getAlgorithmName());
}
return (String[])names.toArray(new String[names.size()]);
}
}
| true | true | public static StructureAlignment[] getAllAlgorithms(){
StructureAlignment[] algorithms = new StructureAlignment[5];
algorithms[0] = new CeMain();
algorithms[1] = new CeSideChainMain();
algorithms[2] = new SmithWaterman3Daligner();
//algorithms[3] = new BioJavaStructureAlignment();
return algorithms;
}
| public static StructureAlignment[] getAllAlgorithms(){
StructureAlignment[] algorithms = new StructureAlignment[3];
algorithms[0] = new CeMain();
algorithms[1] = new CeSideChainMain();
algorithms[2] = new SmithWaterman3Daligner();
//algorithms[3] = new BioJavaStructureAlignment();
return algorithms;
}
|
diff --git a/src/main/java/org/gearman/impl/client/GearmanJobReturnImpl.java b/src/main/java/org/gearman/impl/client/GearmanJobReturnImpl.java
index 49d6f04..9480f00 100644
--- a/src/main/java/org/gearman/impl/client/GearmanJobReturnImpl.java
+++ b/src/main/java/org/gearman/impl/client/GearmanJobReturnImpl.java
@@ -1,104 +1,104 @@
/*
* Copyright (c) 2012, Isaiah van der Elst ([email protected])
* 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 org.gearman.impl.client;
import java.util.Deque;
import java.util.LinkedList;
import java.util.concurrent.TimeUnit;
import org.gearman.GearmanJobEvent;
import org.gearman.GearmanJobReturn;
public class GearmanJobReturnImpl implements GearmanJobReturn, BackendJobReturn {
private boolean isEOF = false;
private final Deque<GearmanJobEvent> eventList = new LinkedList<>();
@Override
public synchronized GearmanJobEvent poll() throws InterruptedException {
while(eventList.isEmpty() && !this.isEOF) {
this.wait();
}
if(this.isEOF())
return GearmanJobEventImmutable.GEARMAN_EOF;
return eventList.pollFirst();
}
@Override
public synchronized GearmanJobEvent poll(long timeout, TimeUnit unit) throws InterruptedException {
if(timeout==0) return poll();
timeout = TimeUnit.MILLISECONDS.convert(timeout, unit);
while(eventList.isEmpty() && !this.isEOF && timeout>0) {
long startTime = System.currentTimeMillis();
this.wait(timeout);
- timeout = timeout - (startTime - System.currentTimeMillis());
+ timeout = timeout - (System.currentTimeMillis()-startTime);
}
if(this.isEOF())
return GearmanJobEventImmutable.GEARMAN_EOF;
return eventList.pollFirst();
}
@Override
public synchronized GearmanJobEvent pollNow() {
if(this.isEOF())
return GearmanJobEventImmutable.GEARMAN_EOF;
return this.eventList.pollFirst();
}
@Override
public synchronized void put(GearmanJobEvent event) {
if(this.isEOF)
throw new IllegalStateException();
this.eventList.addLast(event);
this.notifyAll();
}
@Override
public synchronized void eof(GearmanJobEvent lastevent) {
if(this.isEOF)
throw new IllegalStateException();
this.isEOF = true;
this.eventList.addLast(lastevent);
this.notifyAll();
}
@Override
public boolean isEOF() {
return this.isEOF && eventList.isEmpty();
}
}
| true | true | public synchronized GearmanJobEvent poll(long timeout, TimeUnit unit) throws InterruptedException {
if(timeout==0) return poll();
timeout = TimeUnit.MILLISECONDS.convert(timeout, unit);
while(eventList.isEmpty() && !this.isEOF && timeout>0) {
long startTime = System.currentTimeMillis();
this.wait(timeout);
timeout = timeout - (startTime - System.currentTimeMillis());
}
if(this.isEOF())
return GearmanJobEventImmutable.GEARMAN_EOF;
return eventList.pollFirst();
}
| public synchronized GearmanJobEvent poll(long timeout, TimeUnit unit) throws InterruptedException {
if(timeout==0) return poll();
timeout = TimeUnit.MILLISECONDS.convert(timeout, unit);
while(eventList.isEmpty() && !this.isEOF && timeout>0) {
long startTime = System.currentTimeMillis();
this.wait(timeout);
timeout = timeout - (System.currentTimeMillis()-startTime);
}
if(this.isEOF())
return GearmanJobEventImmutable.GEARMAN_EOF;
return eventList.pollFirst();
}
|
diff --git a/src/java/com/idega/user/data/GroupBMPBean.java b/src/java/com/idega/user/data/GroupBMPBean.java
index cfb565031..c9f1170bd 100644
--- a/src/java/com/idega/user/data/GroupBMPBean.java
+++ b/src/java/com/idega/user/data/GroupBMPBean.java
@@ -1,1853 +1,1852 @@
package com.idega.user.data;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.ejb.CreateException;
import javax.ejb.EJBException;
import javax.ejb.FinderException;
import javax.ejb.RemoveException;
import com.idega.core.builder.data.ICDomain;
import com.idega.core.builder.data.ICPage;
import com.idega.core.contact.data.Email;
import com.idega.core.contact.data.Phone;
import com.idega.core.contact.data.PhoneBMPBean;
import com.idega.core.data.ICTreeNode;
import com.idega.core.file.data.ICFile;
import com.idega.core.location.data.Address;
import com.idega.core.location.data.AddressType;
import com.idega.core.net.data.ICNetwork;
import com.idega.core.net.data.ICProtocol;
import com.idega.data.GenericEntity;
import com.idega.data.IDOAddRelationshipException;
import com.idega.data.IDOCompositePrimaryKeyException;
import com.idega.data.IDOEntityDefinition;
import com.idega.data.IDOException;
import com.idega.data.IDOLookup;
import com.idega.data.IDOLookupException;
import com.idega.data.IDOQuery;
import com.idega.data.IDORelationshipException;
import com.idega.data.IDOUtil;
import com.idega.data.MetaDataCapable;
import com.idega.data.UniqueIDCapable;
import com.idega.data.query.AND;
import com.idega.data.query.Column;
import com.idega.data.query.Criteria;
import com.idega.data.query.InCriteria;
import com.idega.data.query.MatchCriteria;
import com.idega.data.query.OR;
import com.idega.data.query.SelectQuery;
import com.idega.data.query.Table;
import com.idega.data.query.WildCardColumn;
import com.idega.idegaweb.IWApplicationContext;
import com.idega.util.IWTimestamp;
import com.idega.util.ListUtil;
/**
* Title: IW Core
* Description:
* Copyright: Copyright (c) 2001-2003 idega software
* Company: idega.is
* @author <a href="mailto:[email protected]">Gu�mundur �g�st S�mundsson</a>,
* @version 1.0
*/
public class GroupBMPBean extends com.idega.core.data.GenericGroupBMPBean implements Group, ICTreeNode, MetaDataCapable,UniqueIDCapable {
private static final int PREFETCH_SIZE = 100;
public static final int GROUP_ID_EVERYONE = -7913;
public static final int GROUP_ID_USERS = -1906;
private static final String RELATION_TYPE_GROUP_PARENT = "GROUP_PARENT";
private static final String SQL_RELATION_ADDRESS = "IC_GROUP_ADDRESS";
public final static String SQL_RELATION_EMAIL = "IC_GROUP_EMAIL";
public final static String SQL_RELATION_PHONE = "IC_GROUP_PHONE";
private static final String ENTITY_NAME = "ic_group";
static final String COLUMN_GROUP_ID = "IC_GROUP_ID";
static final String COLUMN_NAME = "NAME";
static final String COLUMN_GROUP_TYPE = "GROUP_TYPE";
static final String COLUMN_DESCRIPTION = "DESCRIPTION";
static final String COLUMN_EXTRA_INFO = "EXTRA_INFO";
static final String COLUMN_CREATED = "CREATED";
static final String COLUMN_HOME_PAGE_ID = "HOME_PAGE_ID";
static final String COLUMN_HOME_FOLDER_ID = "HOME_FOLDER_ID";
static final String COLUMN_ALIAS_TO_GROUP = "ALIAS_ID";
static final String COLUMN_PERMISSION_CONTROLLING_GROUP = "PERM_GROUP_ID";
static final String COLUMN_IS_PERMISSION_CONTROLLING_GROUP = "IS_PERM_CONTROLLING";
static final String COLUMN_SHORT_NAME = "SHORT_NAME";
static final String COLUMN_ABBREVATION = "ABBR";
static final String META_DATA_HOME_PAGE = "homepage";
private static List userGroupTypeSingletonList;
private List userRepresentativeGroupTypeList;
public final void initializeAttributes() {
addAttribute(getIDColumnName());
addAttribute(getNameColumnName(), "Group name", true, true, "java.lang.String");
- addAttribute(getGroupTypeColumnName(), "Group type", true, true, String.class, 30, "many-to-one", GroupType.class);
addAttribute(getGroupDescriptionColumnName(), "Description", true, true, "java.lang.String");
addAttribute(getExtraInfoColumnName(), "Extra information", true, true, "java.lang.String");
addAttribute(COLUMN_CREATED, "Created when", Timestamp.class);
addAttribute(getColumnNameHomePageID(), "Home page ID", true, true, Integer.class, "many-to-one", ICPage.class);
setNullable(getColumnNameHomePageID(), true);
addAttribute(COLUMN_SHORT_NAME, "Short name", true, true, String.class);
addAttribute(COLUMN_ABBREVATION, "Abbrevation", true, true, String.class);
//adds a unique id string column to this entity that is set when the entity is first stored.
addUniqueIDColumn();
this.addManyToManyRelationShip(ICNetwork.class, "ic_group_network");
this.addManyToManyRelationShip(ICProtocol.class, "ic_group_protocol");
this.addManyToManyRelationShip(Phone.class, SQL_RELATION_PHONE);
this.addManyToManyRelationShip(Email.class, SQL_RELATION_EMAIL);
this.addManyToManyRelationShip(Address.class, SQL_RELATION_ADDRESS);
addMetaDataRelationship();
//can have extra info in the ic_metadata table
// id of the group that has the permissions for this group. If this is not null then this group has inherited permissions.
addManyToOneRelationship(COLUMN_PERMISSION_CONTROLLING_GROUP, Group.class);
addManyToOneRelationship(getGroupTypeColumnName(), GroupType.class);
addAttribute(COLUMN_IS_PERMISSION_CONTROLLING_GROUP, "Do children of this group get same permissions", true, true, Boolean.class);
addManyToOneRelationship(COLUMN_ALIAS_TO_GROUP, Group.class);
setNullable(COLUMN_ALIAS_TO_GROUP, true);
addManyToOneRelationship(COLUMN_HOME_FOLDER_ID,ICFile.class);
//indexes
addIndex("IDX_IC_GROUP_1", new String[]{ COLUMN_GROUP_TYPE, COLUMN_GROUP_ID});
addIndex("IDX_IC_GROUP_2", COLUMN_NAME);
addIndex("IDX_IC_GROUP_3", COLUMN_GROUP_ID);
addIndex("IDX_IC_GROUP_4", COLUMN_GROUP_TYPE);
addIndex("IDX_IC_GROUP_5", new String[]{ COLUMN_GROUP_ID, COLUMN_GROUP_TYPE});
addIndex("IDX_IC_GROUP_6", COLUMN_HOME_PAGE_ID);
addIndex("IDX_IC_GROUP_7", COLUMN_ABBREVATION);
addIndex("IDX_IC_GROUP_8", new String[]{ COLUMN_GROUP_ID, COLUMN_NAME, COLUMN_GROUP_TYPE});
addIndex("IDX_IC_GROUP_9", UNIQUE_ID_COLUMN_NAME);
addIndex("IDX_IC_GROUP_10", new String[]{ COLUMN_GROUP_TYPE, COLUMN_NAME});
}
public final String getEntityName() {
return ENTITY_NAME;
}
// public String getNameOfMiddleTable(IDOLegacyEntity entity1,IDOLegacyEntity entity2){
// return "ic_group_user";
// }
public void setDefaultValues() {
//DO NOT USE setColumn
initializeColumnValue(COLUMN_GROUP_TYPE, getGroupTypeValue());
initializeColumnValue(COLUMN_CREATED,IWTimestamp.getTimestampRightNow());
}
// public void insertStartData(){
// try {
// GroupTypeHome tghome = (GroupTypeHome)IDOLookup.getHome(GroupType.class);
// try{
// GroupType type = tghome.findByPrimaryKey(getGroupTypeKey());
// } catch(FinderException e){
// e.printStackTrace();
// try {
// GroupType type = tghome.create();
// type.setType(getGroupTypeKey());
// type.setDescription(getGroupTypeDescription());
// type.store();
// }
// catch (Exception ex) {
// ex.printStackTrace();
// }
// }
// }
// catch (RemoteException rmi){
// throw new EJBException(rmi);
// }
// }
// protected boolean doInsertInCreate(){
// return true;
// }
/**
* overwrite in extended classes
*/
public String getGroupTypeValue() {
return getGroupTypeHome().getGeneralGroupTypeString();
}
public String getGroupTypeKey() {
return getGroupTypeValue();
}
public String getGroupTypeDescription() {
return "";
}
/* ColumNames begin */
public static String getColumnNameGroupID() {
return COLUMN_GROUP_ID;
}
public static String getNameColumnName() {
return COLUMN_NAME;
}
public static String getGroupTypeColumnName() {
return COLUMN_GROUP_TYPE;
}
public static String getGroupDescriptionColumnName() {
return COLUMN_DESCRIPTION;
}
public static String getExtraInfoColumnName() {
return COLUMN_EXTRA_INFO;
}
public static String getColumnNameHomePageID() {
return COLUMN_HOME_PAGE_ID;
}
public static String getColumnNameShortName() {
return COLUMN_SHORT_NAME;
}
public static String getColumnNameAbbrevation() {
return COLUMN_ABBREVATION;
}
/* ColumNames end */
/* functions begin */
public String getName() {
return (String)getColumnValue(getNameColumnName());
}
public void setName(String name) {
setColumn(getNameColumnName(), name);
}
public String getGroupType() {
//try {
//was going to the database everytime!! I kill you tryggvi/gummi (eiki)
//return (String) ((GroupType) getColumnValue(getGroupTypeColumnName())).getPrimaryKey();
return getStringColumnValue(getGroupTypeColumnName());
//} catch (RemoteException ex) {
// throw new EJBException(ex);
//}
}
public void setGroupType(String groupType) {
setColumn(getGroupTypeColumnName(), groupType);
}
public void setGroupType(GroupType groupType) {
setColumn(getGroupTypeColumnName(), groupType);
}
public void setAliasID(int id) {
setColumn(COLUMN_ALIAS_TO_GROUP, id);
}
public void setAlias(Group alias) {
setColumn(COLUMN_ALIAS_TO_GROUP, alias);
}
public int getAliasID() {
return getIntColumnValue(COLUMN_ALIAS_TO_GROUP);
}
public Group getAlias() {
return (Group)getColumnValue(COLUMN_ALIAS_TO_GROUP);
}
/**
* This only returns true if the group is of the type alias and the id is bigger than 0
*/
public boolean isAlias() {
return ("alias".equals(getGroupType()) && ( getAliasID()>0 ));
}
public void setPermissionControllingGroupID(int id) {
setColumn(COLUMN_PERMISSION_CONTROLLING_GROUP, id);
}
public void setPermissionControllingGroup(Group controllingGroup) {
setColumn(COLUMN_PERMISSION_CONTROLLING_GROUP, controllingGroup);
}
public int getPermissionControllingGroupID() {
return getIntColumnValue(COLUMN_PERMISSION_CONTROLLING_GROUP);
}
public Group getPermissionControllingGroup() {
return (Group)getColumnValue(COLUMN_PERMISSION_CONTROLLING_GROUP);
}
public void setShortName(String shortName) {
setColumn(COLUMN_SHORT_NAME, shortName);
}
public void setAbbrevation(String abbr) {
setColumn(COLUMN_ABBREVATION, abbr);
}
public String getDescription() {
return (String)getColumnValue(getGroupDescriptionColumnName());
}
public void setDescription(String description) {
setColumn(getGroupDescriptionColumnName(), description);
}
public String getExtraInfo() {
return (String)getColumnValue(getExtraInfoColumnName());
}
public void setExtraInfo(String extraInfo) {
setColumn(getExtraInfoColumnName(), extraInfo);
}
public Timestamp getCreated() {
return ((Timestamp)getColumnValue(COLUMN_CREATED));
}
public void setCreated(Timestamp created) {
setColumn(this.COLUMN_CREATED, created);
}
public int getHomePageID() {
return getIntColumnValue(getColumnNameHomePageID());
}
public ICPage getHomePage() {
return (ICPage)getColumnValue(getColumnNameHomePageID());
}
public void setHomePageID(int pageID) {
setColumn(getColumnNameHomePageID(), pageID);
}
public void setHomePageID(Integer pageID) {
setColumn(getColumnNameHomePageID(), pageID);
}
public void setHomePage(ICPage page) {
setColumn(getColumnNameHomePageID(), page);
}
public int getHomeFolderID() {
return getIntColumnValue(COLUMN_HOME_FOLDER_ID);
}
public ICFile getHomeFolder() {
return (ICFile)getColumnValue(COLUMN_HOME_FOLDER_ID);
}
public void setHomeFolderID(int fileID) {
setColumn(COLUMN_HOME_FOLDER_ID, fileID);
}
public void setHomeFolderID(Integer fileID) {
setColumn(COLUMN_HOME_FOLDER_ID, fileID);
}
public void setHomeFolder(ICFile file) {
setHomeFolderID((Integer)file.getPrimaryKey());
}
public String getShortName() {
return getStringColumnValue(COLUMN_SHORT_NAME);
}
public String getAbbrevation() {
return getStringColumnValue(COLUMN_ABBREVATION);
}
public String getHomePageURL() {
return getMetaData(META_DATA_HOME_PAGE);
}
public void setHomePageURL(String homePage) {
setMetaData(META_DATA_HOME_PAGE, homePage );
}
public void setIsPermissionControllingGroup(boolean isControlling){
setColumn(COLUMN_IS_PERMISSION_CONTROLLING_GROUP,isControlling);
}
public boolean isPermissionControllingGroup(){
return getBooleanColumnValue(COLUMN_IS_PERMISSION_CONTROLLING_GROUP,false);
}
/**
* Gets a list of all the groups that this "group" is directly member of.
* @see com.idega.user.data.Group#getListOfAllGroupsContainingThis()
*/
public List getParentGroups() throws EJBException {
return getParentGroups(null, null);
}
/**
* Optimized version of getParentGroups() by Sigtryggur 22.06.2004
* Database access is minimized by passing a Map of cached groupParents and Map of cached groups to the method
*/
public List getParentGroups(Map cachedParents, Map cachedGroups) throws EJBException {
List theReturn = new ArrayList();
try {
Group parent = null;
Collection parents = getCollectionOfParents(cachedParents, cachedGroups);
Iterator parIter = parents.iterator();
while (parIter.hasNext()) {
parent = (Group)parIter.next();
if (parent != null && !theReturn.contains(parent)) {
theReturn.add(parent);
}
}
if (isUser()) {
try {
User user = getUserForGroup();
Group usersPrimaryGroup = null;
String key = String.valueOf(user.getPrimaryGroupID());
if (cachedGroups != null) {
if (cachedGroups.containsKey(key))
usersPrimaryGroup = (Group)cachedGroups.get(key);
else
{
usersPrimaryGroup = user.getPrimaryGroup();
cachedGroups.put(key, usersPrimaryGroup);
}
}
else {
usersPrimaryGroup = user.getPrimaryGroup();;
}
if (usersPrimaryGroup!=null && !theReturn.contains(usersPrimaryGroup)) {
theReturn.add(usersPrimaryGroup);
}
} catch (FinderException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
catch (Exception e) {
e.printStackTrace();
throw new EJBException(e.getMessage());
}
return theReturn;
}
private Collection getCollectionOfParents() throws FinderException {
return getCollectionOfParents(null, null);
}
private Collection getCollectionOfParents(Map cachedParents, Map cachedGroups) throws FinderException {
Collection col = null;
String key = this.getPrimaryKey().toString();
if (cachedParents!=null) {
if (cachedParents.containsKey(key))
col = (Collection)cachedParents.get(key);
else
{
col = ejbFindParentGroups(this.getID());
cachedParents.put(key, col);
}
}
else {
col = ejbFindParentGroups(this.getID());
}
Collection returnCol = new ArrayList();
Group parent = null;
Integer parentID = null;
Iterator iter = col.iterator();
while (iter.hasNext()) {
parentID = (Integer)iter.next();
key = parentID.toString();
if (cachedGroups != null) {
if (cachedGroups.containsKey(key))
parent = (Group)cachedGroups.get(key);
else
{
parent = getGroupHome().findByPrimaryKey(parentID);
cachedGroups.put(key, parent);
}
}
else {
parent = getGroupHome().findByPrimaryKey(parentID);
}
returnCol.add(parent);
}
return returnCol;
}
protected Collection getChildGroupRelationships() throws FinderException {
//null type is included as relation type for backwards compatability.
return this.getGroupRelationHome().findGroupsRelationshipsByRelatedGroup(this.getID(), RELATION_TYPE_GROUP_PARENT, null);
}
/**
* Returns the User instance representing the Group if the Group is of type UserGroupRepresentative
* @throws IDOLookupException
* @throws FinderException
**/
private User getUserForGroup() throws IDOLookupException, FinderException {
UserHome uHome = (UserHome)IDOLookup.getHome(User.class);
return uHome.findUserForUserGroup(this);
}
/**
* Finds all the GroupRelations that point to groups that "this" group is a direct parent for
* @return Collection of GroupRelations
*/
protected Collection getParentalGroupRelationships() throws FinderException {
//null type is included as relation type for backwards compatability.
return this.getGroupRelationHome().findGroupsRelationshipsContaining(this.getID(), RELATION_TYPE_GROUP_PARENT, null);
}
/**
* @deprecated
*/
protected List getListOfAllGroupsContaining(int group_id) throws EJBException {
try {
Group group = this.getGroupHome().findByPrimaryKey(new Integer(group_id));
return group.getParentGroups();
}
catch (Exception e) {
throw new EJBException(e.getMessage());
}
}
public Integer ejbCreateGroup() throws CreateException {
return (Integer)this.ejbCreate();
}
public void ejbPostCreateGroup() throws CreateException {
}
public Collection ejbFindGroupsByName(String name) throws FinderException {
return this.idoFindPKsBySQL("select * from " + this.getEntityName() + " where " + this.getNameColumnName() + " = '" + name + "'");
}
public Collection ejbFindGroupsByNameAndGroupTypes(String name, Collection groupTypes, boolean onlyReturnTypesInCollection) throws FinderException {
//String groupTypeValue = null;
String notString = null;
IDOQuery query = idoQuery();
query.append("select * from " + this.getEntityName() + " where " + this.getNameColumnName() + " = '" + name + "' and "+ this.getGroupTypeColumnName());
if (groupTypes != null && groupTypes.size() == 1) {
notString = onlyReturnTypesInCollection?" ":" !";
query.append(notString + "= '" + groupTypes.iterator().next() + "'");
} else {
notString = onlyReturnTypesInCollection?" ":" not ";
query.append(notString + "in (");
query.appendCommaDelimitedWithinSingleQuotes(groupTypes).append(")");
}
return this.idoFindPKsByQuery(query);
}
public Collection ejbFindGroupsByGroupTypeAndLikeName(String groupType, String partOfGroupName) throws FinderException {
return this.idoFindPKsBySQL("select * from " + this.getEntityName() + " where " + this.getGroupTypeColumnName() + " = '" + groupType + "' and "+ this.getNameColumnName() + " like '" + partOfGroupName + "' order by "+this.getNameColumnName());
}
public Collection ejbFindGroupsByAbbreviation(String abbreviation) throws FinderException {
return this.idoFindPKsBySQL("select * from " + this.getEntityName() + " where " + COLUMN_ABBREVATION + " = '" + abbreviation + "'");
}
public Collection ejbFindGroupsByNameAndDescription(String name, String description) throws FinderException {
Table table = new Table(this);
Column nameCol = new Column(table, getNameColumnName());
Column desc = new Column(table, getGroupDescriptionColumnName());
SelectQuery query = new SelectQuery(table);
query.addColumn(new WildCardColumn(table));
query.addCriteria(new MatchCriteria(nameCol, MatchCriteria.EQUALS, name));
query.addCriteria(new MatchCriteria(desc, MatchCriteria.EQUALS, description));
return this.idoFindPKsByQuery(query);
}
public Integer ejbFindGroupByPrimaryKey(Object primaryKey) throws FinderException {
return (Integer)this.ejbFindByPrimaryKey(primaryKey);
}
// private List getListOfAllGroupsContainingLegacy(int group_id)throws EJBException{
// String tableToSelectFrom = "IC_GROUP_TREE";
// StringBuffer buffer=new StringBuffer();
// buffer.append("select * from ");
// buffer.append(tableToSelectFrom);
// buffer.append(" where ");
// buffer.append("CHILD_IC_GROUP_ID");
// buffer.append("=");
// buffer.append(group_id);
// String SQLString=buffer.toString();
// Connection conn= null;
// Statement Stmt= null;
// Vector vector = new Vector();
// try
// {
// conn = getConnection(getDatasource());
// Stmt = conn.createStatement();
// ResultSet RS = Stmt.executeQuery(SQLString);
// while (RS.next()){
// IDOLegacyEntity tempobj=null;
// try{
// tempobj = (IDOLegacyEntity)Class.forName(this.getClass().getName()).newInstance();
// tempobj.findByPrimaryKey(RS.getInt(this.getIDColumnName()));
// }
// catch(Exception ex){
// System.err.println("There was an error in " + this.getClass().getName() +".getAllGroupsContainingThis(): "+ex.getMessage());
// }
// vector.addElement(tempobj);
// }
//
// RS.close();
//
// }
// catch(Exception e){
// throw new EJBException(e.getMessage());
// }
// finally{
// if(Stmt != null){
// try{
// Stmt.close();
// }
// catch(SQLException e){}
// }
// if (conn != null){
// freeConnection(getDatasource(),conn);
// }
// }
//
// if (vector != null){
// vector.trimToSize();
// return vector;
// //return (Group[]) vector.toArray((Object[])java.lang.reflect.Array.newInstance(this.getClass(),0));
// }
// else{
// return null;
// }
// }
//
//??
// public Group[] getAllGroupsContained()throws SQLException{
//
// List vector = this.getListOfAllGroupsContained();
//
// if(vector != null){
//
// return (Group[]) vector.toArray((Object[])java.lang.reflect.Array.newInstance(this.getClass(),0));
//
// }else{
//
// return new Group[0];
//
// }
//
// }
/**
* @return A list of groups (not users) under this group
*/
public List getChildGroups() throws EJBException {
List theReturn = new ArrayList();
try {
theReturn.addAll(ListUtil.convertCollectionToList(getGroupHome().findGroupsContained(this, getUserGroupTypeList(), false)));
return theReturn;
}
catch (FinderException e) {
e.printStackTrace();
return theReturn;
}
}
/**
* Gets the children of the containingGroup
* @param containingGroup
* @param groupTypes
* @param returnTypes
* @return
* @throws FinderException
*/
public Collection ejbFindGroupsContainedTemp(Group containingGroup, Collection groupTypes, boolean returnTypes) throws FinderException {
Table groupTable = new Table(ENTITY_NAME, "g");
Table groupRelTable = new Table(GroupRelationBMPBean.TABLE_NAME, "gr");
SelectQuery query = new SelectQuery(groupTable);
query.addColumn(new WildCardColumn(groupTable));
query.addJoin(groupTable, COLUMN_GROUP_ID, groupRelTable,GroupRelationBMPBean.RELATED_GROUP_ID_COLUMN);
if (groupTypes != null && !groupTypes.isEmpty()) {
if (groupTypes.size() == 1){
query.addCriteria(new MatchCriteria(groupTable, COLUMN_GROUP_TYPE, MatchCriteria.NOTEQUALS, groupTypes.iterator().next().toString()));
} else {
query.addCriteria(new InCriteria(groupTable, COLUMN_GROUP_TYPE, groupTypes, !returnTypes));
}
}
query.addCriteria(new MatchCriteria(groupRelTable, GroupRelationBMPBean.GROUP_ID_COLUMN, MatchCriteria.EQUALS, containingGroup.getPrimaryKey()));
query.addCriteria(new MatchCriteria(groupRelTable, GroupRelationBMPBean.RELATIONSHIP_TYPE_COLUMN, MatchCriteria.EQUALS, RELATION_TYPE_GROUP_PARENT));
String[] statuses = {GroupRelationBMPBean.STATUS_ACTIVE, GroupRelationBMPBean.STATUS_PASSIVE_PENDING};
query.addCriteria(new InCriteria(groupRelTable, GroupRelationBMPBean.STATUS_COLUMN, statuses));
query.addOrder(groupTable, COLUMN_NAME, true);
return idoFindPKsByQueryUsingLoadBalance(query, PREFETCH_SIZE);
//return idoFindPKsBySQL(query.toString());
}
public Collection ejbFindGroupsContained(Group containingGroup, Collection groupTypes, boolean returnTypes) throws FinderException {
String findGroupRelationsSQL = getGroupRelationHome().getFindRelatedGroupIdsInGroupRelationshipsContainingSQL(((Integer)containingGroup.getPrimaryKey()).intValue(), RELATION_TYPE_GROUP_PARENT);
SelectQuery query = idoSelectQuery();
Criteria theCriteria = null;
if (groupTypes != null && !groupTypes.isEmpty()) {
theCriteria = new InCriteria(idoQueryTable(),COLUMN_GROUP_TYPE,groupTypes,!returnTypes);
}
Criteria inCr = new InCriteria(idoQueryTable(),COLUMN_GROUP_ID,findGroupRelationsSQL);
if(theCriteria==null){
theCriteria = inCr;
} else {
theCriteria = new AND(theCriteria,inCr);
}
query.addCriteria(theCriteria);
query.addOrder(idoQueryTable(),this.COLUMN_NAME,true);
return idoFindPKsByQueryUsingLoadBalance(query, PREFETCH_SIZE);
//return idoFindPKsBySQL(query.toString());
}
/**
* Gets the children of the containingGroup
* @param containingGroup
* @param groupTypeProxy group type to return
* @param returnTypes
* @return
* @throws FinderException
*/
public Collection ejbFindGroupsContained(Group containingGroup, Group groupTypeProxy) throws FinderException {
String findGroupRelationsSQL = getGroupRelationHome().getFindRelatedGroupIdsInGroupRelationshipsContainingSQL(((Integer)containingGroup.getPrimaryKey()).intValue(), RELATION_TYPE_GROUP_PARENT);
SelectQuery query = idoSelectQuery();
query.addCriteria( new MatchCriteria(idoQueryTable(),COLUMN_GROUP_TYPE,MatchCriteria.LIKE,groupTypeProxy.getGroupTypeKey()));
query.addCriteria(new InCriteria(idoQueryTable(),COLUMN_GROUP_ID,findGroupRelationsSQL));
query.addOrder(idoQueryTable(),COLUMN_NAME,true);
return idoFindPKsByQueryIgnoringCacheAndUsingLoadBalance(query, (GenericEntity)groupTypeProxy, groupTypeProxy.getSelectQueryConstraints(), PREFETCH_SIZE);
//return idoFindPKsBySQL(query.toString());
}
public int ejbHomeGetNumberOfGroupsContained(Group containingGroup, Collection groupTypes, boolean returnTypes) throws FinderException, IDOException {
String relatedSQL = getGroupRelationHome().getFindRelatedGroupIdsInGroupRelationshipsContainingSQL(((Integer)containingGroup.getPrimaryKey()).intValue(), RELATION_TYPE_GROUP_PARENT);
if (groupTypes != null && !groupTypes.isEmpty()) {
IDOQuery query = idoQuery();
query.appendSelectCountIDFrom(this.getEntityName(), getIDColumnName());
query.appendWhere(this.COLUMN_GROUP_TYPE);
IDOQuery subQuery = idoQuery();
subQuery.appendCommaDelimitedWithinSingleQuotes(groupTypes);
if (returnTypes) {
query.appendIn(subQuery);
}
else {
query.appendNotIn(subQuery);
}
query.appendAnd();
query.append(this.COLUMN_GROUP_ID);
query.appendIn(relatedSQL);
return this.idoGetNumberOfRecords(query.toString());
}
else {
System.err.println("ejbHomeGetNumberOfGroupsContained :NO GROUP TYPES SUPPLIED!");
return 0;
}
}
public int ejbHomeGetNumberOfVisibleGroupsContained(Group containingGroup) throws FinderException, IDOException {
String relatedSQL = getGroupRelationHome().getFindRelatedGroupIdsInGroupRelationshipsContainingSQL(((Integer)containingGroup.getPrimaryKey()).intValue(), RELATION_TYPE_GROUP_PARENT);
String visibleGroupTypes = getGroupTypeHome().getVisibleGroupTypesSQLString();
IDOQuery query = idoQuery();
query.appendSelectCountIDFrom(this.getEntityName(), getIDColumnName());
query.appendWhere(this.COLUMN_GROUP_TYPE);
query.appendIn(visibleGroupTypes);
query.appendAnd();
query.append(this.COLUMN_GROUP_ID);
query.appendIn(relatedSQL);
return this.idoGetNumberOfRecords(query.toString());
}
public Collection ejbFindTopNodeGroupsContained(ICDomain containingDomain, Collection groupTypes, boolean returnTypes) throws FinderException {
String relationsSQL = this.getGroupDomainRelationHome().getFindRelatedGroupIdsInGroupDomainRelationshipsContainingSQL(((Integer)containingDomain.getPrimaryKey()).intValue(), getGroupDomainRelationTypeHome().getTopNodeRelationTypeString());
if (groupTypes != null && !groupTypes.isEmpty()) {
IDOQuery query = idoQuery();
query.appendSelectAllFrom(this.getEntityName());
query.appendWhere(this.COLUMN_GROUP_TYPE);
IDOQuery subQuery = idoQuery();
subQuery.appendCommaDelimitedWithinSingleQuotes(groupTypes);
if (returnTypes) {
query.appendIn(subQuery);
}
else {
query.appendNotIn(subQuery);
}
query.appendAnd();
query.append(this.COLUMN_GROUP_ID);
query.appendIn(relationsSQL);
query.appendOrderBy(this.COLUMN_NAME);
// System.out.println("[GroupBMPBean](ejbFindGroupsContained): "+query.toString());
return this.idoFindPKsBySQL(query.toString());
}
else {
return ListUtil.getEmptyList();
}
}
public int ejbHomeGetNumberOfTopNodeGroupsContained(ICDomain containingDomain, Collection groupTypes, boolean returnTypes) throws FinderException, IDOException {
String relationsSQL = getGroupDomainRelationHome().getFindRelatedGroupIdsInGroupDomainRelationshipsContainingSQL(((Integer)containingDomain.getPrimaryKey()).intValue(), getGroupDomainRelationTypeHome().getTopNodeRelationTypeString());
if (groupTypes != null && !groupTypes.isEmpty()) {
IDOQuery query = idoQuery();
query.appendSelectCountIDFrom(this.getEntityName(), getIDColumnName());
query.appendWhere(this.COLUMN_GROUP_TYPE);
IDOQuery subQuery = idoQuery();
subQuery.appendCommaDelimitedWithinSingleQuotes(groupTypes);
if (returnTypes) {
query.appendIn(subQuery);
}
else {
query.appendNotIn(subQuery);
}
query.appendAnd();
query.append(this.COLUMN_GROUP_ID);
query.appendIn(relationsSQL);
// System.out.println("[GroupBMPBean](ejbHomeGetNumberOfGroupsContained): "+query.toString());
return this.idoGetNumberOfRecords(query.toString());
}
else {
System.err.println("ejbHomeGetNumberOfTopNodeGroupsContained :NO GROUP TYPES SUPPLIED!");
return 0;
}
}
public int ejbHomeGetNumberOfTopNodeVisibleGroupsContained(ICDomain containingDomain) throws FinderException, IDOException {
String relatedSQL = getGroupDomainRelationHome().getFindRelatedGroupIdsInGroupDomainRelationshipsContainingSQL(((Integer)containingDomain.getPrimaryKey()).intValue(), getGroupDomainRelationTypeHome().getTopNodeRelationTypeString());
String visibleGroupTypes = getGroupTypeHome().getVisibleGroupTypesSQLString();
IDOQuery query = idoQuery();
query.appendSelectCountIDFrom(this.getEntityName(), getIDColumnName());
query.appendWhere(this.COLUMN_GROUP_TYPE);
query.appendIn(visibleGroupTypes);
query.appendAnd();
query.append(this.COLUMN_GROUP_ID);
query.appendIn(relatedSQL);
return this.idoGetNumberOfRecords(query.toString());
}
public Collection ejbFindTopNodeVisibleGroupsContained(ICDomain containingDomain) throws FinderException {
String relationsSQL = this.getGroupDomainRelationHome().getFindRelatedGroupIdsInGroupDomainRelationshipsContainingSQL(((Integer)containingDomain.getPrimaryKey()).intValue(), getGroupDomainRelationTypeHome().getTopNodeRelationTypeString());
String visibleGroupTypes = getGroupTypeHome().getVisibleGroupTypesSQLString();
IDOQuery query = idoQuery();
query.appendSelectAllFrom(this.getEntityName());
query.appendWhere(this.COLUMN_GROUP_TYPE);
query.appendIn(visibleGroupTypes);
query.appendAnd();
query.append(this.COLUMN_GROUP_ID);
query.appendIn(relationsSQL);
query.appendOrderBy(this.COLUMN_NAME);
return this.idoFindPKsBySQL(query.toString());
}
/**
* @todo change name to getGroupsContained();
*/
// private List getListOfAllGroupsContainedLegacy()throws EJBException{
// String tableToSelectFrom = "IC_GROUP_TREE";
// StringBuffer buffer=new StringBuffer();
// buffer.append("select CHILD_IC_GROUP_ID from ");
// buffer.append(tableToSelectFrom);
// buffer.append(" where ");
// buffer.append("IC_GROUP_ID");
// buffer.append("=");
// buffer.append(this.getID());
// String SQLString=buffer.toString();
// Connection conn= null;
// Statement Stmt= null;
// Vector vector = new Vector();
// try
// {
// conn = getConnection(getDatasource());
// Stmt = conn.createStatement();
// ResultSet RS = Stmt.executeQuery(SQLString);
// while (RS.next()){
//
// IDOLegacyEntity tempobj=null;
// try{
// tempobj = (IDOLegacyEntity)Class.forName(this.getClass().getName()).newInstance();
// tempobj.findByPrimaryKey(RS.getInt("CHILD_IC_GROUP_ID"));
// }
// catch(Exception ex){
// System.err.println("There was an error in " + this.getClass().getName() +".getAllGroupsContainingThis(): "+ex.getMessage());
//
// }
//
// vector.addElement(tempobj);
//
// }
// RS.close();
//
// }
// catch(Exception e){
// throw new EJBException(e.getMessage());
// }
// finally{
// if(Stmt != null){
// try{
// Stmt.close();
// }
// catch(SQLException sqle){}
// }
// if (conn != null){
// freeConnection(getDatasource(),conn);
// }
// }
//
// if (vector != null){
// vector.trimToSize();
// return vector;
// //return (Group[]) vector.toArray((Object[])java.lang.reflect.Array.newInstance(this.getClass(),0));
// }
// else{
// return null;
// }
//
//
// //return (Group[])this.findReverseRelated(this);
//
// }
/**
* @todo change implementation: let the database handle the filtering
*/
public List getChildGroups(String[] groupTypes, boolean returnSpecifiedGroupTypes) throws EJBException {
List theReturn = new ArrayList();
List types = null;
if (groupTypes != null && groupTypes.length > 0) {
types = ListUtil.convertStringArrayToList(groupTypes);
}
try {
return ListUtil.convertCollectionToList(getGroupHome().findGroupsContained(this, types, returnSpecifiedGroupTypes));
}
catch (FinderException e) {
e.printStackTrace();
return theReturn;
}
}
public List getChildGroupsIDs(String[] groupTypes, boolean returnSpecifiedGroupTypes) throws EJBException {
List theReturn = new ArrayList();
List types = null;
if (groupTypes != null && groupTypes.length > 0) {
types = ListUtil.convertStringArrayToList(groupTypes);
}
try {
return ListUtil.convertCollectionToList(getGroupHome().findGroupsContainedIDs(this, types, returnSpecifiedGroupTypes));
}
catch (FinderException e) {
e.printStackTrace();
return theReturn;
}
}
/**
* Returns collection of Childs that match the type of 'groupTypeProxy' and according to groupTypeProxy.getSelectQueryConstrains().
* The objects in the collection will be of the same class as 'groupTypeProxy' i.e. if groupTypeProxy implements User then it will be collection of User elements
*/
public Collection getChildGroups(Group groupTypeProxy) throws EJBException {
try {
return getGroupHome().findGroupsContained(this, groupTypeProxy);
}
catch (FinderException e) {
e.printStackTrace();
return ListUtil.getEmptyList();
}
}
public Collection getAllGroupsContainingUser(User user) throws EJBException {
return this.getListOfAllGroupsContaining(user.getGroupID());
}
/**
* Adds the group by id groupToAdd under this group
* @see com.idega.user.data.Group#addGroup(Group)
*/
public void addGroup(Group groupToAdd) throws EJBException {
this.addGroup(this.getGroupIDFromGroup(groupToAdd));
}
/**
* Adds the user by id under this group and changes his deleted status to false if needed.
* Also sets his primary group to this group if it is not set
* @see com.idega.user.data.Group#addGroup(User)
*/
public void addGroup(User userToAdd) throws EJBException {
this.addGroup(this.getGroupIDFromGroup(userToAdd));
boolean needsToStore= false;
if(userToAdd.getDeleted()){
needsToStore = true;
userToAdd.setDeleted(false);
}
if(userToAdd.getPrimaryGroupID()<0){
needsToStore = true;
userToAdd.setPrimaryGroup(this);
}
if(needsToStore){
userToAdd.store();
}
}
/**
* Adds the group by id groupToAdd under this group
* @see com.idega.user.data.Group#addGroup(Group)
*/
public void addGroup(Group groupToAdd, Timestamp time) throws EJBException {
this.addGroup(this.getGroupIDFromGroup(groupToAdd), time);
}
/**
* Adds the group by id groupId under this group
* @see com.idega.core.data.GenericGroup#addGroup(int,time)
*/
public void addGroup(int groupId,Timestamp time) throws EJBException {
try {
//GroupRelation rel = this.getGroupRelationHome().create();
//rel.setGroup(this);
//rel.setRelatedGroup(groupId);
//rel.store();
if(time!=null){
addUniqueRelation(groupId, RELATION_TYPE_GROUP_PARENT,time);
}
else{
addUniqueRelation(groupId, RELATION_TYPE_GROUP_PARENT);
}
}
catch (Exception e) {
throw new EJBException(e.getMessage());
}
}
/**
* Adds the group by id groupId under this group
* @see com.idega.core.data.GenericGroup#addGroup(int)
*/
public void addGroup(int groupId) throws EJBException {
addGroup(groupId,null);
}
public void addRelation(Group groupToAdd, String relationType) throws CreateException {
this.addRelation(this.getGroupIDFromGroup(groupToAdd), relationType);
}
public void addRelation(Group groupToAdd, GroupRelationType relationType) throws CreateException {
this.addRelation(this.getGroupIDFromGroup(groupToAdd), relationType);
}
public void addRelation(int relatedGroupId, GroupRelationType relationType) throws CreateException {
this.addRelation(relatedGroupId, relationType.getType());
}
public void addRelation(int relatedGroupId, String relationType) throws CreateException {
//try{
GroupRelation rel = this.getGroupRelationHome().create();
rel.setGroup(this);
rel.setRelatedGroup(relatedGroupId);
rel.setRelationshipType(relationType);
rel.setRelatedGroupType(rel.getRelatedGroup().getGroupType());
rel.store();
//}
//catch(Exception e){
// throw new EJBException(e.getMessage());
//}
}
/**
* Only adds a relation if one does not exist already
* @param relatedGroupId
* @param relationType
* @throws CreateException
* @throws RemoteException
*/
public void addUniqueRelation(int relatedGroupId, String relationType, Timestamp time) throws CreateException {
//try{
if (!hasRelationTo(relatedGroupId, relationType)) {
//System.out.println("hasRelationTo("+relatedGroupId+","+relationType+") IS FALSE");
GroupRelation rel = this.getGroupRelationHome().create();
rel.setGroup(this);
rel.setRelatedGroup(relatedGroupId);
rel.setRelationshipType(relationType);
if(time == null){
time = IWTimestamp.getTimestampRightNow();
}
rel.setInitiationDate(time);
rel.setRelatedGroupType(rel.getRelatedGroup().getGroupType());
rel.store();
}
//}
//catch(Exception e){
// throw new EJBException(e.getMessage());
//}
}
public void addUniqueRelation(int relatedGroupId, String relationType) throws CreateException {
addUniqueRelation(relatedGroupId, relationType, null);
}
/**
* Only adds a relation if one does not exist already
* @param relatedGroup
* @param relationType
* @throws CreateException
* @throws RemoteException
*/
public void addUniqueRelation(Group relatedGroup, String relationType) throws CreateException {
addUniqueRelation(((Integer) (relatedGroup.getPrimaryKey())).intValue(), relationType);
}
/**
* @deprecated use removeRelation(int relatedGroupId, String relationType, User performer)
*/
public void removeRelation(Group relatedGroup, String relationType) throws RemoveException {
int groupId = this.getGroupIDFromGroup(relatedGroup);
this.removeRelation(groupId, relationType);
}
/**
* @deprecated use removeRelation(int relatedGroupId, String relationType, User performer)
*/
public void removeRelation(int relatedGroupId, String relationType) throws RemoveException {
removeRelation(relatedGroupId, relationType,null);
}
/**
* @deprecated use removeRelation(int relatedGroupId, String relationType, User performer)
*/
public void removeRelation(Group relatedGroup, String relationType, User performer) throws RemoveException {
int groupId = this.getGroupIDFromGroup(relatedGroup);
this.removeRelation(groupId, relationType, performer);
}
public void removeRelation(int relatedGroupId, String relationType, User performer) throws RemoveException {
GroupRelation rel = null;
try {
//Group group = this.getGroupHome().findByPrimaryKey(relatedGroupId);
Collection rels;
rels = this.getGroupRelationHome().findGroupsRelationshipsContaining(this.getID(), relatedGroupId, relationType);
Iterator iter = rels.iterator();
while (iter.hasNext()) {
rel = (GroupRelation)iter.next();
if (performer == null) {
rel.remove();
} else {
rel.removeBy(performer);
}
}
}
catch (FinderException e) {
throw new RemoveException(e.getMessage());
}
}
/**
* Returns a collection of Group objects that are related by the relation type relationType with this Group
*/
public Collection getRelatedBy(GroupRelationType relationType) throws FinderException {
return getRelatedBy(relationType.getType());
}
/**
* Returns a collection of Group objects that are related by the relation type relationType with this Group
*/
public Collection getRelatedBy(String relationType) throws FinderException {
GroupRelation rel = null;
Collection theReturn = new ArrayList();
Collection rels = null;
rels = this.getGroupRelationHome().findGroupsRelationshipsContaining(this.getID(), relationType);
Iterator iter = rels.iterator();
while (iter.hasNext()) {
rel = (GroupRelation)iter.next();
Group g = rel.getRelatedGroup();
theReturn.add(g);
}
return theReturn;
}
/**
* Returns a collection of Group objects that are reverse related by the
* relation type relationType with this Group
*/
public Collection getReverseRelatedBy(String relationType) throws FinderException {
GroupRelation rel = null;
Collection theReturn = new ArrayList();
Collection rels = null;
rels = this.getGroupRelationHome().findGroupsRelationshipsByRelatedGroup(this.getID(), relationType);
Iterator iter = rels.iterator();
while (iter.hasNext()) {
rel = (GroupRelation)iter.next();
Group g = rel.getGroup();
theReturn.add(g);
}
return theReturn;
}
// private void addGroupLegacy(int groupId)throws EJBException{
// Connection conn= null;
// Statement Stmt= null;
// try{
// conn = getConnection(getDatasource());
// Stmt = conn.createStatement();
// String sql = "insert into IC_GROUP_TREE ("+getIDColumnName()+", CHILD_IC_GROUP_ID) values("+getID()+","+groupId+")";
// //System.err.println(sql);
// int i = Stmt.executeUpdate(sql);
// //System.err.println(sql);
// }catch (Exception ex) {
// ex.printStackTrace(System.out);
// }finally{
// if(Stmt != null){
// try{
// Stmt.close();
// }
// catch(SQLException sqle){}
// }
// if (conn != null){
// freeConnection(getDatasource(),conn);
// }
// }
// }
// private void removeGroupLegacy(int groupId, boolean AllEntries)throws EJBException{
// Connection conn= null;
// Statement Stmt= null;
// try{
// conn = getConnection(getDatasource());
// Stmt = conn.createStatement();
// String qry;
// if(AllEntries)//removing all in middle table
// qry = "delete from IC_GROUP_TREE where "+this.getIDColumnName()+"='"+this.getID()+"' OR CHILD_IC_GROUP_ID ='"+this.getID()+"'";
// else// just removing this particular one
// qry = "delete from IC_GROUP_TREE where "+this.getIDColumnName()+"='"+this.getID()+"' AND CHILD_IC_GROUP_ID ='"+groupId+"'";
// int i = Stmt.executeUpdate(qry);
// }catch (Exception ex) {
// ex.printStackTrace(System.out);
// }finally{
// if(Stmt != null){
// try{
// Stmt.close();
// }
// catch(SQLException sqle){}
// }
// if (conn != null){
// freeConnection(getDatasource(),conn);
// }
// }
// }
//
// /**
// * @deprecated moved to UserGroupBusiness
// */
// public static void addUserOld(int groupId, User user){
// //((com.idega.user.data.GroupHome)com.idega.data.IDOLookup.getHomeLegacy(Group.class)).findByPrimaryKeyLegacy(groupId).addGroup(user.getGroupID());
// throw new java.lang.UnsupportedOperationException("Method adduser moved to UserBusiness");
// }
// public void addUser(User user)throws RemoteException{
// this.addGroup(user.getGroupID());
// }
public void removeUser(User user, User currentUser) throws RemoveException{
// former: user.getGroupId() but this method is deprecated therefore: user.getId()
try {
this.removeGroup(user.getID(), currentUser, false);
}
catch (EJBException e) {
throw new RemoveException(e.getMessage());
}
}
public void removeUser(User user, User currentUser, Timestamp time) throws RemoveException{
// former: user.getGroupId() but this method is deprecated therefore: user.getId()
try{
this.removeGroup(user.getID(), currentUser, false, time);
}
catch (EJBException e) {
throw new RemoveException(e.getMessage());
}
}
// public Group findGroup(String groupName) throws SQLException{
//
// List group = EntityFinder.findAllByColumn(com.idega.data.GenericEntity.getStaticInstance(this.getClass().getName()),getNameColumnName(),groupName,getGroupTypeColumnName(),this.getGroupTypeValue());
//
// if(group != null){
//
// return (Group)group.get(0);
//
// }else{
//
// return null;
//
// }
//
// }
/**
* This finder returns a collection of all groups of the grouptype(s) that are defined in the groupTypes parameter
* It also returns the groups that are defined as topnodes in the ic_domain_group_relation table
* It excludes groups that have been deleted and don't have any active relations to parent groups
* If returnSpecifiedGroupTypes is set as false then it excludes the grouptype(s) defined in the groupTypes paremeter
* excluding user representative groups
* @return all groups of certain type(s) that have not been deleted
* @throws FinderException
*/
public Collection ejbFindAllGroups(String[] groupTypes, boolean returnSpecifiedGroupTypes) throws FinderException {
Table groupTable = new Table(this, "g");
Column idCol = new Column(groupTable, getColumnNameGroupID());
Table groupRelSubTable = new Table(GroupRelationBMPBean.TABLE_NAME, "gr");
Column relatedGroupIDSubCol = new Column(groupRelSubTable, GroupRelationBMPBean.RELATED_GROUP_ID_COLUMN);
//Column relationshipTypeSubCol = new Column(groupRelSubTable, GroupRelationBMPBean.RELATIONSHIP_TYPE_COLUMN);
Column groupRelationstatusSubCol = new Column(groupRelSubTable, GroupRelationBMPBean.STATUS_COLUMN);
SelectQuery firstSubQuery = new SelectQuery(groupRelSubTable);
firstSubQuery.addColumn(relatedGroupIDSubCol);
//subQuery.addCriteria(new MatchCriteria(relationshipTypeSubCol, MatchCriteria.EQUALS, RELATION_TYPE_GROUP_PARENT));
firstSubQuery.addCriteria(new InCriteria(groupRelationstatusSubCol, new String[]{GroupRelation.STATUS_ACTIVE, GroupRelation.STATUS_PASSIVE_PENDING}));
Table groupDomainRelSubTable = new Table(GroupDomainRelationBMPBean.TABLE_NAME, "gdr");
Column gdr_RelatedGroupIDSubCol = new Column(groupDomainRelSubTable, GroupDomainRelationBMPBean.RELATED_GROUP_ID_COLUMN);
Column gdr_relationshipTypeSubCol = new Column(groupDomainRelSubTable, GroupDomainRelationBMPBean.RELATIONSHIP_TYPE_COLUMN);
Column gdr_groupRelationstatusSubCol = new Column(groupDomainRelSubTable, GroupDomainRelationBMPBean.STATUS_COLUMN);
SelectQuery secondSubQuery = new SelectQuery(groupDomainRelSubTable);
secondSubQuery.addColumn(gdr_RelatedGroupIDSubCol);
secondSubQuery.addCriteria(new MatchCriteria(gdr_relationshipTypeSubCol, MatchCriteria.EQUALS, GroupDomainRelationTypeBMPBean.RELATION_TYPE_TOP_NODE));
secondSubQuery.addCriteria(new MatchCriteria(gdr_groupRelationstatusSubCol, MatchCriteria.IS, MatchCriteria.NULL));
InCriteria firstInCriteria = new InCriteria(idCol, firstSubQuery);
InCriteria secondInCriteria = new InCriteria(idCol, secondSubQuery);
SelectQuery query = new SelectQuery(groupTable);
query.addColumn(new WildCardColumn(groupTable));
if (groupTypes != null && groupTypes.length != 0) {
Column typeCol = new Column(groupTable, getGroupTypeColumnName());
if (groupTypes.length == 1){
query.addCriteria(new MatchCriteria(typeCol, returnSpecifiedGroupTypes?MatchCriteria.EQUALS:MatchCriteria.NOTEQUALS, groupTypes[0]));
} else {
query.addCriteria(new InCriteria(typeCol, groupTypes, !returnSpecifiedGroupTypes));
}
}
query.addCriteria(new OR(firstInCriteria, secondInCriteria));
query.addOrder(groupTable, getNameColumnName(), true);
return this.idoFindPKsByQuery(query);
}
// public Collection ejbFindAllGroups(String[] groupTypes, boolean returnSepcifiedGroupTypes) throws FinderException {
// if (groupTypes != null && groupTypes.length > 0) {
// String typeList = IDOUtil.getInstance().convertArrayToCommaseparatedString(groupTypes, true);
// return super.idoFindIDsBySQL("select * from " + getEntityName() + " where " + getGroupTypeColumnName() + ((returnSepcifiedGroupTypes) ? " in (" : " not in (") + typeList + ") order by " + getNameColumnName());
// }
// return super.idoFindAllIDsOrderedBySQL(getNameColumnName());
// }
/**
*
* @return all groups excluding user representative groups
* @throws FinderException
*/
public Collection ejbFindAll() throws FinderException {
// String[] types = {this.getGroupTypeValue()};
// return ejbFindAllGroups(types,true);
String theUserType = "ic_user_representative";
SelectQuery query = idoSelectQuery();
query.addCriteria(new MatchCriteria(idoQueryTable(),getGroupTypeColumnName(),MatchCriteria.NOTEQUALS,theUserType,true));
int prefetchSize = 10000;
return super.idoFindPKsByQueryUsingLoadBalance(query,prefetchSize);
}
/**
* @deprecated replaced with ejbFindAllGroups
*/
public static List getAllGroupsOld(String[] groupTypes, boolean returnSepcifiedGroupTypes) throws SQLException {
/*String typeList = "";
if (groupTypes != null && groupTypes.length > 0){
for(int g = 0; g < groupTypes.length; g++){
if(g>0){ typeList += ", "; }
typeList += "'"+groupTypes[g]+"'";
}
Group gr = (Group)com.idega.user.data.GroupBMPBean.getStaticInstance();
return EntityFinder.findAll(gr,"select * from "+gr.getEntityName()+" where "+com.idega.user.data.GroupBMPBean.getGroupTypeColumnName()+((returnSepcifiedGroupTypes)?" in (":" not in (")+typeList+") order by "+com.idega.user.data.GroupBMPBean.getNameColumnName());
}
return EntityFinder.findAllOrdered(com.idega.user.data.GroupBMPBean.getStaticInstance(),com.idega.user.data.GroupBMPBean.getNameColumnName());
*/
return null;
}
protected boolean identicalGroupExistsInDatabase() throws Exception {
// return SimpleQuerier.executeStringQuery("select * from "+this.getEntityName()+" where "+this.getGroupTypeColumnName()+" = '"+this.getGroupType()+"' and "+this.getNameColumnName()+" = '"+this.getName()+"'",this.getDatasource()).length > 0;
return false;
}
public void insert() throws SQLException {
try {
// if(!this.getName().equals("")){
if (identicalGroupExistsInDatabase()) {
throw new SQLException("group with same name and type already in database");
}
// }
super.insert();
}
catch (Exception ex) {
if (ex instanceof SQLException) {
throw (SQLException)ex;
}
else {
System.err.println(ex.getMessage());
ex.printStackTrace();
throw new SQLException(ex.getMessage());
}
}
}
// public boolean equals(IDOLegacyEntity entity){
// if(entity != null){
// if(entity instanceof Group){
// return this.equals((Group)entity);
// } else {
// return super.equals(entity);
// }
// }
// return false;
// }
protected boolean equals(Group group) {
if (group != null) {
try {
if (group.getPrimaryKey().equals(this.getPrimaryKey())) {
return true;
}
}
catch (Exception e) {
return false;
}
return false;
}
return false;
}
private GroupHome getGroupHome() {
return ((GroupHome)this.getEJBLocalHome());
}
private GroupDomainRelationHome getGroupDomainRelationHome() {
try {
return ((GroupDomainRelationHome)IDOLookup.getHome(GroupDomainRelation.class));
}
catch (IDOLookupException e) {
e.printStackTrace();
}
return null;
}
private GroupDomainRelationTypeHome getGroupDomainRelationTypeHome() {
try {
return ((GroupDomainRelationTypeHome)IDOLookup.getHome(GroupDomainRelationType.class));
}
catch (IDOLookupException e) {
e.printStackTrace();
}
return null;
}
public String ejbHomeGetGroupType() {
return this.getGroupTypeValue();
}
public String ejbHomeGetRelationTypeGroupParent() {
return RELATION_TYPE_GROUP_PARENT;
}
public Collection ejbFindGroups(String[] groupIDs) throws FinderException {
Collection toReturn = new ArrayList(0);
String sGroupList = "";
/* if (groupIDs != null && groupIDs.length > 0){
for(int g = 0; g < groupIDs.length; g++){
if(g>0){ sGroupList += ", "; }
sGroupList += groupIDs[g];
}
}*/
sGroupList = IDOUtil.getInstance().convertArrayToCommaseparatedString(groupIDs);
if (!sGroupList.equals("")) {
String sql = "SELECT * FROM " + getTableName() + " WHERE " + getIDColumnName() + " in (" + sGroupList + ")";
toReturn = super.idoFindPKsBySQL(sql);
}
return toReturn;
}
public Collection ejbFindGroupsByType(String type) throws FinderException {
StringBuffer sql = new StringBuffer("select ").append(getIDColumnName()).append(" from ");
sql.append(getEntityName());
sql.append(" where ");
sql.append(COLUMN_GROUP_TYPE);
sql.append(" = '");
sql.append(type);
sql.append("'");
return super.idoFindPKsBySQL(sql.toString());
}
public Collection ejbFindGroupsByMetaData(String key, String value) throws FinderException {
return super.idoFindPKsByMetaData(key, value);
}
public Integer ejbFindSystemUsersGroup() throws FinderException {
return new Integer(this.GROUP_ID_USERS);
}
private GroupTypeHome getGroupTypeHome() {
try {
return ((GroupTypeHome)IDOLookup.getHome(GroupType.class));
}
catch (IDOLookupException e) {
e.printStackTrace();
}
return null;
}
public Collection ejbFindGroupsRelationshipsByRelatedGroup(int groupID,String relationType,String orRelationType)throws FinderException{
String firstRelationTypeClause = GroupRelationBMPBean.getRelationTypeWhereClause(relationType);
String secondRelationTypeClause = GroupRelationBMPBean.getRelationTypeWhereClause(orRelationType);
String sql = "select * from "+GroupRelationBMPBean.TABLE_NAME+" where "+GroupRelationBMPBean.RELATED_GROUP_ID_COLUMN+"="+groupID
+" and ("+firstRelationTypeClause+" OR "+secondRelationTypeClause+") and ( "+GroupRelationBMPBean.STATUS_COLUMN+"='"+GroupRelation.STATUS_ACTIVE+"' OR "+GroupRelationBMPBean.STATUS_COLUMN+"='"+GroupRelation.STATUS_PASSIVE_PENDING+"' ) ";
return this.idoFindPKsBySQL(sql);
}
public Collection ejbFindParentGroups(int groupID)throws FinderException{
String sql = "select " + getIDColumnName() + " from "+GroupRelationBMPBean.TABLE_NAME+" where "+GroupRelationBMPBean.RELATED_GROUP_ID_COLUMN+"="+groupID
+" and ("+GroupRelationBMPBean.RELATIONSHIP_TYPE_COLUMN+"='GROUP_PARENT' OR "+ GroupRelationBMPBean.RELATIONSHIP_TYPE_COLUMN+" is null) and ( "+GroupRelationBMPBean.STATUS_COLUMN+"='"+GroupRelation.STATUS_ACTIVE+"' OR "+GroupRelationBMPBean.STATUS_COLUMN+"='"+GroupRelation.STATUS_PASSIVE_PENDING+"' ) ";
return this.idoFindPKsBySQL(sql);
}
private UserHome getUserHome() {
try {
return (UserHome)IDOLookup.getHome(User.class);
}
catch (IDOLookupException e) {
e.printStackTrace();
}
return null;
}
private List getUserGroupTypeList() {
if (userGroupTypeSingletonList == null) {
userGroupTypeSingletonList = new ArrayList();
userGroupTypeSingletonList.add(getUserHome().getGroupType());
}
return userGroupTypeSingletonList;
}
/**
* Method hasRelationTo.
* @param group
* @return boolean
* @throws RemoteException
*/
public boolean hasRelationTo(Group group) {
return hasRelationTo(((Integer)group.getPrimaryKey()).intValue());
}
/**
* This is bidirectional
*/
public boolean hasRelationTo(int groupId) {
int myId = ((Integer)this.getPrimaryKey()).intValue();
Collection relations = new ArrayList();
try {
relations = this.getGroupRelationHome().findGroupsRelationshipsContainingBiDirectional(myId, groupId);
}
catch (FinderException ex) {
ex.printStackTrace();
}
return !relations.isEmpty();
}
/**
* This is bidirectional
*/
public boolean hasRelationTo(int groupId, String relationType) {
int myId = ((Integer)this.getPrimaryKey()).intValue();
Collection relations = new ArrayList();
try {
relations = this.getGroupRelationHome().findGroupsRelationshipsContainingBiDirectional(myId, groupId, relationType);
}
catch (FinderException ex) {
ex.printStackTrace();
}
return !relations.isEmpty();
}
public Iterator getChildrenIterator() {
Iterator it = null;
Collection children = getChildren();
if (children != null) {
it = children.iterator();
}
return it;
}
public Collection getChildren() {
/**
* @todo: Change implementation this first part may not be needed. (Eiki,gummi)
*
*/
if (this.getID() == this.GROUP_ID_USERS) {
// String[] groupTypes = {"ic_user_representative"};
try {
String[] groupTypes = new String[1];
groupTypes[0] = ((GroupHome)IDOLookup.getHome(User.class)).getGroupType();
return this.getGroupHome().findGroups(groupTypes);
}
catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
else {
return getChildGroups(); //only returns groups not users
}
}
public boolean getAllowsChildren() {
return true;
}
public ICTreeNode getChildAtIndex(int childIndex) {
try {
return ((GroupHome)this.getEJBLocalHome()).findByPrimaryKey(new Integer(childIndex));
}
catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
public int getChildCount() {
if (this.getID() == this.GROUP_ID_USERS) {
try {
String[] groupTypes = new String[1];
groupTypes[0] = ((GroupHome)IDOLookup.getHome(User.class)).getGroupType();
return this.getGroupHome().findGroups(groupTypes).size();
}
catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
else {
try {
// Collection types = this.getGroupTypeHome().findVisibleGroupTypes();//TODO optimize or cache
return this.getGroupHome().getNumberOfVisibleGroupsContained(this);
}
catch (FinderException e) {
throw new EJBException(e);
}
catch (IDOException idoex) {
throw new EJBException(idoex);
}
}
}
public int getIndex(ICTreeNode node) {
return node.getNodeID();
}
/**
* @todo reimplement
*/
public ICTreeNode getParentNode() {
ICTreeNode parent = null;
try {
parent = (ICTreeNode)this.getParentGroups().iterator().next();
}
catch (Exception e) {
}
return parent;
}
public boolean isLeaf() {
/**
* @todo reimplement
*/
return getChildCount() > 0;
}
public String getNodeName() {
return this.getName();
}
public String getNodeName(Locale locale) {
return this.getNodeName();
}
public String getNodeName(Locale locale, IWApplicationContext iwac){
return getNodeName(locale);
}
public int getNodeID() {
return ((Integer)this.getPrimaryKey()).intValue();
}
public int getSiblingCount() {
ICTreeNode parent = getParentNode();
if (parent != null) {
return parent.getChildCount();
}
else {
return 0;
}
}
/**
* @see com.idega.core.ICTreeNode#getNodeType()
*/
public int getNodeType(){
return -1;
}
public void store() {
super.store();
}
/**
* Gets if the group is of type "UserGroupRepresentative"
**/
public boolean isUser() {
return UserBMPBean.USER_GROUP_TYPE.equals(this.getGroupType());
}
public void addAddress(Address address) throws IDOAddRelationshipException {
this.idoAddTo(address);
}
public Collection getAddresses(AddressType addressType) throws IDOLookupException, IDOCompositePrimaryKeyException, IDORelationshipException {
String addressTypePrimaryKeyColumn = addressType.getEntityDefinition().getPrimaryKeyDefinition().getField().getSQLFieldName();
IDOEntityDefinition addressDefinition = IDOLookup.getEntityDefinitionForClass(Address.class);
String addressTableName = addressDefinition.getSQLTableName();
String addressPrimaryKeyColumn = addressDefinition.getPrimaryKeyDefinition().getField().getSQLFieldName();
String groupAddressMiddleTableName = addressDefinition.getMiddleTableNameForRelation(getEntityName());
IDOQuery query = idoQuery();
query.appendSelect().append("a.").append(addressPrimaryKeyColumn).appendFrom().append(addressTableName).append(" a, ");
query.append(groupAddressMiddleTableName).append(" iua ").appendWhere();
query.append("a.").append(addressPrimaryKeyColumn).appendEqualSign();
query.append("iua.").append(addressPrimaryKeyColumn);
query.appendAnd().append("a.");
query.append(addressTypePrimaryKeyColumn).appendEqualSign();
query.append(addressType.getPrimaryKey());
query.appendAnd().append("iua.");
query.append(COLUMN_GROUP_ID).appendEqualSign().append(getPrimaryKey());
return idoGetRelatedEntitiesBySQL(Address.class, query.toString());
}
public Collection getPhones() {
try {
return super.idoGetRelatedEntities(Phone.class);
}
catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Error in getPhones() : " + e.getMessage());
}
}
public Collection getPhones(String phoneTypeID) {
try {
return super.idoGetRelatedEntities(Phone.class, PhoneBMPBean.getColumnNamePhoneTypeId(), phoneTypeID);
}
catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Error in getPhones() : " + e.getMessage());
}
}
public Collection getEmails() {
try {
return super.idoGetRelatedEntities(Email.class);
}
catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Error in getEmails() : " + e.getMessage());
}
}
public void addEmail(Email email) throws IDOAddRelationshipException {
this.idoAddTo(email);
}
public void addPhone(Phone phone) throws IDOAddRelationshipException {
this.idoAddTo(phone);
}
public void removeGroup(Group entityToRemoveFrom, User currentUser) throws EJBException {
int groupId = this.getGroupIDFromGroup(entityToRemoveFrom);
if ((groupId == -1) || (groupId == 0)) //removing all in middle table
this.removeGroup(groupId, currentUser, true);
else // just removing this particular one
this.removeGroup(groupId, currentUser, false);
}
protected int getGroupIDFromGroup(Group group) {
Integer groupID = ((Integer)group.getPrimaryKey());
if (groupID != null)
return groupID.intValue();
else
return -1;
}
public void removeGroup(User currentUser) throws EJBException {
this.removeGroup(-1, currentUser, true);
}
public void removeGroup(int relatedGroupId, User currentUser, boolean AllEntries, Timestamp time) throws EJBException {
try {
Collection rels = null;
if (AllEntries) {
rels = this.getGroupRelationHome().findGroupsRelationshipsUnder(this);
}
else {
rels = this.getGroupRelationHome().findGroupsRelationshipsContaining(this.getID(), relatedGroupId);
}
Iterator iter = rels.iterator();
while (iter.hasNext()) {
GroupRelation item = (GroupRelation)iter.next();
item.removeBy(currentUser,time);
}
}
catch (Exception e) {
throw new EJBException(e.getMessage());
}
}
public void removeGroup(int relatedGroupId, User currentUser, boolean AllEntries) throws EJBException {
removeGroup(relatedGroupId,currentUser,AllEntries,IWTimestamp.getTimestampRightNow());
}
protected GroupRelationHome getGroupRelationHome() {
try {
return ((GroupRelationHome)IDOLookup.getHome(GroupRelation.class));
}
catch (IDOLookupException e) {
e.printStackTrace();
}
return null;
}
public Object ejbFindByHomePageID(int pageID) throws FinderException {
return idoFindOnePKByQuery(idoQueryGetSelect().appendWhereEquals(getColumnNameHomePageID(),pageID));
}
public Integer ejbFindGroupByUniqueId(String uniqueIdString) throws FinderException {
return (Integer) idoFindOnePKByUniqueId(uniqueIdString);
}
public Integer ejbFindBoardGroupByClubIDAndLeagueID(Integer clubID, Integer leagueID) throws FinderException {
String sql = "select m.metadata_value as ic_group_id from ic_group_relation rel, ic_group div, ic_group_ic_metadata mg, ic_metadata m, ic_group_ic_metadata mg2, ic_metadata m2 "
+"where rel.IC_GROUP_ID = "+clubID
+"and rel.RELATIONSHIP_TYPE='GROUP_PARENT' "
+"and ( rel.GROUP_RELATION_STATUS='ST_ACTIVE' or rel.GROUP_RELATION_STATUS='PASS_PEND' ) "
+"and div.IC_GROUP_ID=rel.related_IC_GROUP_ID "
+"and div.group_type='iwme_club_division' "
+"and div.ic_group_id=mg.ic_group_id "
+"and mg.ic_metadata_id=m.ic_metadata_id "
+"and m.metadata_name='CLUBDIV_BOARD' "
+"and div.ic_group_id=mg2.ic_group_id "
+"and mg2.ic_metadata_id=m2.ic_metadata_id "
+"and m2.metadata_name='CLUBDIV_CONN' "
+"and m2.metadata_value in ('"+leagueID+"')";
return (Integer) this.idoFindOnePKBySQL(sql);
}
public SelectQuery getSelectQueryConstraints(){
return null;
}
} // Class Group
| true | true | public final void initializeAttributes() {
addAttribute(getIDColumnName());
addAttribute(getNameColumnName(), "Group name", true, true, "java.lang.String");
addAttribute(getGroupTypeColumnName(), "Group type", true, true, String.class, 30, "many-to-one", GroupType.class);
addAttribute(getGroupDescriptionColumnName(), "Description", true, true, "java.lang.String");
addAttribute(getExtraInfoColumnName(), "Extra information", true, true, "java.lang.String");
addAttribute(COLUMN_CREATED, "Created when", Timestamp.class);
addAttribute(getColumnNameHomePageID(), "Home page ID", true, true, Integer.class, "many-to-one", ICPage.class);
setNullable(getColumnNameHomePageID(), true);
addAttribute(COLUMN_SHORT_NAME, "Short name", true, true, String.class);
addAttribute(COLUMN_ABBREVATION, "Abbrevation", true, true, String.class);
//adds a unique id string column to this entity that is set when the entity is first stored.
addUniqueIDColumn();
this.addManyToManyRelationShip(ICNetwork.class, "ic_group_network");
this.addManyToManyRelationShip(ICProtocol.class, "ic_group_protocol");
this.addManyToManyRelationShip(Phone.class, SQL_RELATION_PHONE);
this.addManyToManyRelationShip(Email.class, SQL_RELATION_EMAIL);
this.addManyToManyRelationShip(Address.class, SQL_RELATION_ADDRESS);
addMetaDataRelationship();
//can have extra info in the ic_metadata table
// id of the group that has the permissions for this group. If this is not null then this group has inherited permissions.
addManyToOneRelationship(COLUMN_PERMISSION_CONTROLLING_GROUP, Group.class);
addManyToOneRelationship(getGroupTypeColumnName(), GroupType.class);
addAttribute(COLUMN_IS_PERMISSION_CONTROLLING_GROUP, "Do children of this group get same permissions", true, true, Boolean.class);
addManyToOneRelationship(COLUMN_ALIAS_TO_GROUP, Group.class);
setNullable(COLUMN_ALIAS_TO_GROUP, true);
addManyToOneRelationship(COLUMN_HOME_FOLDER_ID,ICFile.class);
//indexes
addIndex("IDX_IC_GROUP_1", new String[]{ COLUMN_GROUP_TYPE, COLUMN_GROUP_ID});
addIndex("IDX_IC_GROUP_2", COLUMN_NAME);
addIndex("IDX_IC_GROUP_3", COLUMN_GROUP_ID);
addIndex("IDX_IC_GROUP_4", COLUMN_GROUP_TYPE);
addIndex("IDX_IC_GROUP_5", new String[]{ COLUMN_GROUP_ID, COLUMN_GROUP_TYPE});
addIndex("IDX_IC_GROUP_6", COLUMN_HOME_PAGE_ID);
addIndex("IDX_IC_GROUP_7", COLUMN_ABBREVATION);
addIndex("IDX_IC_GROUP_8", new String[]{ COLUMN_GROUP_ID, COLUMN_NAME, COLUMN_GROUP_TYPE});
addIndex("IDX_IC_GROUP_9", UNIQUE_ID_COLUMN_NAME);
addIndex("IDX_IC_GROUP_10", new String[]{ COLUMN_GROUP_TYPE, COLUMN_NAME});
}
| public final void initializeAttributes() {
addAttribute(getIDColumnName());
addAttribute(getNameColumnName(), "Group name", true, true, "java.lang.String");
addAttribute(getGroupDescriptionColumnName(), "Description", true, true, "java.lang.String");
addAttribute(getExtraInfoColumnName(), "Extra information", true, true, "java.lang.String");
addAttribute(COLUMN_CREATED, "Created when", Timestamp.class);
addAttribute(getColumnNameHomePageID(), "Home page ID", true, true, Integer.class, "many-to-one", ICPage.class);
setNullable(getColumnNameHomePageID(), true);
addAttribute(COLUMN_SHORT_NAME, "Short name", true, true, String.class);
addAttribute(COLUMN_ABBREVATION, "Abbrevation", true, true, String.class);
//adds a unique id string column to this entity that is set when the entity is first stored.
addUniqueIDColumn();
this.addManyToManyRelationShip(ICNetwork.class, "ic_group_network");
this.addManyToManyRelationShip(ICProtocol.class, "ic_group_protocol");
this.addManyToManyRelationShip(Phone.class, SQL_RELATION_PHONE);
this.addManyToManyRelationShip(Email.class, SQL_RELATION_EMAIL);
this.addManyToManyRelationShip(Address.class, SQL_RELATION_ADDRESS);
addMetaDataRelationship();
//can have extra info in the ic_metadata table
// id of the group that has the permissions for this group. If this is not null then this group has inherited permissions.
addManyToOneRelationship(COLUMN_PERMISSION_CONTROLLING_GROUP, Group.class);
addManyToOneRelationship(getGroupTypeColumnName(), GroupType.class);
addAttribute(COLUMN_IS_PERMISSION_CONTROLLING_GROUP, "Do children of this group get same permissions", true, true, Boolean.class);
addManyToOneRelationship(COLUMN_ALIAS_TO_GROUP, Group.class);
setNullable(COLUMN_ALIAS_TO_GROUP, true);
addManyToOneRelationship(COLUMN_HOME_FOLDER_ID,ICFile.class);
//indexes
addIndex("IDX_IC_GROUP_1", new String[]{ COLUMN_GROUP_TYPE, COLUMN_GROUP_ID});
addIndex("IDX_IC_GROUP_2", COLUMN_NAME);
addIndex("IDX_IC_GROUP_3", COLUMN_GROUP_ID);
addIndex("IDX_IC_GROUP_4", COLUMN_GROUP_TYPE);
addIndex("IDX_IC_GROUP_5", new String[]{ COLUMN_GROUP_ID, COLUMN_GROUP_TYPE});
addIndex("IDX_IC_GROUP_6", COLUMN_HOME_PAGE_ID);
addIndex("IDX_IC_GROUP_7", COLUMN_ABBREVATION);
addIndex("IDX_IC_GROUP_8", new String[]{ COLUMN_GROUP_ID, COLUMN_NAME, COLUMN_GROUP_TYPE});
addIndex("IDX_IC_GROUP_9", UNIQUE_ID_COLUMN_NAME);
addIndex("IDX_IC_GROUP_10", new String[]{ COLUMN_GROUP_TYPE, COLUMN_NAME});
}
|
diff --git a/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/adaptor/PluginConverterImpl.java b/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/adaptor/PluginConverterImpl.java
index e4721ccd..041d6f38 100644
--- a/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/adaptor/PluginConverterImpl.java
+++ b/bundles/org.eclipse.osgi/eclipseAdaptor/src/org/eclipse/core/runtime/adaptor/PluginConverterImpl.java
@@ -1,715 +1,718 @@
/*******************************************************************************
* Copyright (c) 2003, 2005 IBM Corporation 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
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.core.runtime.adaptor;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import org.eclipse.osgi.framework.adaptor.FrameworkAdaptor;
import org.eclipse.osgi.framework.internal.core.Constants;
import org.eclipse.osgi.framework.internal.defaultadaptor.DevClassPathHelper;
import org.eclipse.osgi.framework.log.FrameworkLogEntry;
import org.eclipse.osgi.service.pluginconversion.PluginConversionException;
import org.eclipse.osgi.service.pluginconversion.PluginConverter;
import org.eclipse.osgi.service.resolver.VersionRange;
import org.eclipse.osgi.util.ManifestElement;
import org.eclipse.osgi.util.NLS;
import org.osgi.framework.*;
/**
* Internal class.
*/
public class PluginConverterImpl implements PluginConverter {
public static boolean DEBUG = false;
private static final String SEMICOLON = "; "; //$NON-NLS-1$
private static final String UTF_8 = "UTF-8"; //$NON-NLS-1$
private static final String LIST_SEPARATOR = ",\n "; //$NON-NLS-1$
private static final String DOT = "."; //$NON-NLS-1$
private BundleContext context;
private BufferedWriter out;
private IPluginInfo pluginInfo;
private File pluginManifestLocation;
private Dictionary generatedManifest;
private byte manifestType;
private String target;
private Dictionary devProperties;
static final String TARGET31 = "3.1"; //$NON-NLS-1$
private static final String MANIFEST_VERSION = "Manifest-Version"; //$NON-NLS-1$
private static final String PLUGIN_PROPERTIES_FILENAME = "plugin"; //$NON-NLS-1$
private static PluginConverterImpl instance;
private static final String[] ARCH_LIST = {org.eclipse.osgi.service.environment.Constants.ARCH_PA_RISC, org.eclipse.osgi.service.environment.Constants.ARCH_PPC, org.eclipse.osgi.service.environment.Constants.ARCH_SPARC, org.eclipse.osgi.service.environment.Constants.ARCH_X86, org.eclipse.osgi.service.environment.Constants.ARCH_AMD64, org.eclipse.osgi.service.environment.Constants.ARCH_IA64};
protected static final String FRAGMENT_MANIFEST = "fragment.xml"; //$NON-NLS-1$
protected static final String GENERATED_FROM = "Generated-from"; //$NON-NLS-1$
protected static final String MANIFEST_TYPE_ATTRIBUTE = "type"; //$NON-NLS-1$
private static final String[] OS_LIST = {org.eclipse.osgi.service.environment.Constants.OS_AIX, org.eclipse.osgi.service.environment.Constants.OS_HPUX, org.eclipse.osgi.service.environment.Constants.OS_LINUX, org.eclipse.osgi.service.environment.Constants.OS_MACOSX, org.eclipse.osgi.service.environment.Constants.OS_QNX, org.eclipse.osgi.service.environment.Constants.OS_SOLARIS, org.eclipse.osgi.service.environment.Constants.OS_WIN32};
protected static final String PI_RUNTIME = "org.eclipse.core.runtime"; //$NON-NLS-1$
protected static final String PI_BOOT = "org.eclipse.core.boot"; //$NON-NLS-1$
protected static final String PI_RUNTIME_COMPATIBILITY = "org.eclipse.core.runtime.compatibility"; //$NON-NLS-1$
protected static final String PLUGIN_MANIFEST = "plugin.xml"; //$NON-NLS-1$
private static final String COMPATIBILITY_ACTIVATOR = "org.eclipse.core.internal.compatibility.PluginActivator"; //$NON-NLS-1$
private static final String[] WS_LIST = {org.eclipse.osgi.service.environment.Constants.WS_CARBON, org.eclipse.osgi.service.environment.Constants.WS_GTK, org.eclipse.osgi.service.environment.Constants.WS_MOTIF, org.eclipse.osgi.service.environment.Constants.WS_PHOTON, org.eclipse.osgi.service.environment.Constants.WS_WIN32};
public static PluginConverterImpl getDefault() {
return instance;
}
PluginConverterImpl(BundleContext context) {
this.context = context;
instance = this;
}
private void init() {
// need to make sure these fields are cleared out for each conversion.
out = null;
pluginInfo = null;
pluginManifestLocation = null;
generatedManifest = new Hashtable(10);
manifestType = EclipseBundleData.MANIFEST_TYPE_UNKNOWN;
target = null;
devProperties = null;
}
private void fillPluginInfo(File pluginBaseLocation) throws PluginConversionException {
pluginManifestLocation = pluginBaseLocation;
if (pluginManifestLocation == null)
throw new IllegalArgumentException();
URL pluginFile = findPluginManifest(pluginBaseLocation);
if (pluginFile == null)
throw new PluginConversionException(NLS.bind(EclipseAdaptorMsg.ECLIPSE_CONVERTER_FILENOTFOUND, pluginBaseLocation.getAbsolutePath()));
pluginInfo = parsePluginInfo(pluginFile);
String validation = pluginInfo.validateForm();
if (validation != null)
throw new PluginConversionException(validation);
}
private Set filterExport(Collection exportToFilter, Collection filter) {
if (filter == null || filter.contains("*")) //$NON-NLS-1$
return (Set) exportToFilter;
Set filteredExport = new HashSet(exportToFilter.size());
for (Iterator iter = exportToFilter.iterator(); iter.hasNext();) {
String anExport = (String) iter.next();
for (Iterator iter2 = filter.iterator(); iter2.hasNext();) {
String aFilter = (String) iter2.next();
int dotStar = aFilter.indexOf(".*"); //$NON-NLS-1$
if (dotStar != -1)
aFilter = aFilter.substring(0, dotStar);
if (anExport.equals(aFilter)) {
filteredExport.add(anExport);
break;
}
}
}
return filteredExport;
}
private ArrayList findOSJars(File pluginRoot, String path, boolean filter) {
path = path.substring(4);
ArrayList found = new ArrayList(0);
for (int i = 0; i < OS_LIST.length; i++) {
//look for os/osname/path
String searchedPath = "os/" + OS_LIST[i] + "/" + path; //$NON-NLS-1$ //$NON-NLS-2$
if (new File(pluginRoot, searchedPath).exists())
found.add(searchedPath + (filter ? ";(os=" + WS_LIST[i] + ")" : "")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
//look for os/osname/archname/path
for (int j = 0; j < ARCH_LIST.length; j++) {
searchedPath = "os/" + OS_LIST[i] + "/" + ARCH_LIST[j] + "/" + path; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
if (new File(pluginRoot, searchedPath).exists()) {
found.add(searchedPath + (filter ? ";(& (os=" + WS_LIST[i] + ") (arch=" + ARCH_LIST[j] + ")" : "")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
}
}
}
return found;
}
private URL findPluginManifest(File baseLocation) {
//Here, we can not use the bundlefile because it may explode the jar and returns a location from which we will not be able to derive the jars location
URL xmlFileLocation;
InputStream stream = null;
URL baseURL = null;
try {
if (baseLocation.getName().endsWith(".jar")) { //$NON-NLS-1$
baseURL = new URL("jar:file:" + baseLocation.toString() + "!/"); //$NON-NLS-1$ //$NON-NLS-2$
manifestType |= EclipseBundleData.MANIFEST_TYPE_JAR;
} else {
baseURL = baseLocation.toURL();
}
} catch (MalformedURLException e1) {
//this can't happen since we are building the urls ourselves from a file
}
try {
xmlFileLocation = new URL(baseURL, PLUGIN_MANIFEST);
stream = xmlFileLocation.openStream();
manifestType |= EclipseBundleData.MANIFEST_TYPE_PLUGIN;
return xmlFileLocation;
} catch (MalformedURLException e) {
FrameworkLogEntry entry = new FrameworkLogEntry(FrameworkAdaptor.FRAMEWORK_SYMBOLICNAME, e.getMessage(), 0, e, null);
EclipseAdaptor.getDefault().getFrameworkLog().log(entry);
return null;
} catch (IOException ioe) {
//ignore
} finally {
try {
if (stream != null)
stream.close();
} catch (IOException e) {
//ignore
}
}
try {
xmlFileLocation = new URL(baseURL, FRAGMENT_MANIFEST);
stream = xmlFileLocation.openStream();
manifestType |= EclipseBundleData.MANIFEST_TYPE_FRAGMENT;
return xmlFileLocation;
} catch (MalformedURLException e) {
FrameworkLogEntry entry = new FrameworkLogEntry(FrameworkAdaptor.FRAMEWORK_SYMBOLICNAME, e.getMessage(), 0, e, null);
EclipseAdaptor.getDefault().getFrameworkLog().log(entry);
return null;
} catch (IOException ioe) {
// Ignore
} finally {
try {
if (stream != null)
stream.close();
} catch (IOException e) {
//ignore
}
}
return null;
}
private ArrayList findWSJars(File pluginRoot, String path, boolean filter) {
path = path.substring(4);
ArrayList found = new ArrayList(0);
for (int i = 0; i < WS_LIST.length; i++) {
String searchedPath = "ws/" + WS_LIST[i] + path; //$NON-NLS-1$
if (new File(pluginRoot, searchedPath).exists()) {
found.add(searchedPath + (filter ? ";(ws=" + WS_LIST[i] + ")" : "")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
}
return found;
}
protected void fillManifest(boolean compatibilityManifest, boolean analyseJars) {
generateManifestVersion();
generateHeaders();
generateClasspath();
generateActivator();
generatePluginClass();
if (analyseJars)
generateProvidePackage();
generateRequireBundle();
generateLocalizationEntry();
generateEclipseHeaders();
if (compatibilityManifest) {
generateTimestamp();
}
}
public void writeManifest(File generationLocation, Dictionary manifestToWrite, boolean compatibilityManifest) throws PluginConversionException {
try {
File parentFile = new File(generationLocation.getParent());
parentFile.mkdirs();
generationLocation.createNewFile();
if (!generationLocation.isFile()) {
String message = NLS.bind(EclipseAdaptorMsg.ECLIPSE_CONVERTER_ERROR_CREATING_BUNDLE_MANIFEST, this.pluginInfo.getUniqueId(), generationLocation);
throw new PluginConversionException(message);
}
// replaces any eventual existing file
manifestToWrite = new Hashtable((Map) manifestToWrite);
// MANIFEST.MF files must be written using UTF-8
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(generationLocation), UTF_8));
writeEntry(MANIFEST_VERSION, (String) manifestToWrite.remove(MANIFEST_VERSION));
writeEntry(GENERATED_FROM, (String) manifestToWrite.remove(GENERATED_FROM)); //Need to do this first uptoDate check expect the generated-from tag to be in the first line
if (TARGET31.equals(target))
writeEntry(Constants.BUNDLE_MANIFESTVERSION, (String) manifestToWrite.remove(Constants.BUNDLE_MANIFESTVERSION));
writeEntry(Constants.BUNDLE_NAME, (String) manifestToWrite.remove(Constants.BUNDLE_NAME));
writeEntry(Constants.BUNDLE_SYMBOLICNAME, (String) manifestToWrite.remove(Constants.BUNDLE_SYMBOLICNAME));
writeEntry(Constants.BUNDLE_VERSION, (String) manifestToWrite.remove(Constants.BUNDLE_VERSION));
writeEntry(Constants.BUNDLE_CLASSPATH, (String) manifestToWrite.remove(Constants.BUNDLE_CLASSPATH));
writeEntry(Constants.BUNDLE_ACTIVATOR, (String) manifestToWrite.remove(Constants.BUNDLE_ACTIVATOR));
writeEntry(Constants.BUNDLE_VENDOR, (String) manifestToWrite.remove(Constants.BUNDLE_VENDOR));
writeEntry(Constants.FRAGMENT_HOST, (String) manifestToWrite.remove(Constants.FRAGMENT_HOST));
writeEntry(Constants.BUNDLE_LOCALIZATION, (String) manifestToWrite.remove(Constants.BUNDLE_LOCALIZATION));
if (TARGET31.equals(target))
writeEntry(Constants.EXPORT_PACKAGE, (String) manifestToWrite.remove(Constants.EXPORT_PACKAGE));
else
writeEntry(Constants.PROVIDE_PACKAGE, (String) manifestToWrite.remove(Constants.PROVIDE_PACKAGE));
writeEntry(Constants.REQUIRE_BUNDLE, (String) manifestToWrite.remove(Constants.REQUIRE_BUNDLE));
Enumeration keys = manifestToWrite.keys();
while (keys.hasMoreElements()) {
String key = (String) keys.nextElement();
writeEntry(key, (String) manifestToWrite.get(key));
}
out.flush();
} catch (IOException e) {
String message = NLS.bind(EclipseAdaptorMsg.ECLIPSE_CONVERTER_ERROR_CREATING_BUNDLE_MANIFEST, this.pluginInfo.getUniqueId(), generationLocation); //$NON-NLS-1$
throw new PluginConversionException(message, e);
} finally {
if (out != null)
try {
out.close();
} catch (IOException e) {
// only report problems writing to/flushing the file
}
}
}
private void generateLocalizationEntry() {
generatedManifest.put(Constants.BUNDLE_LOCALIZATION, PLUGIN_PROPERTIES_FILENAME);
}
private void generateManifestVersion() {
generatedManifest.put(MANIFEST_VERSION, "1.0"); //$NON-NLS-1$ //$NON-NLS-2$
}
private boolean requireRuntimeCompatibility() {
ArrayList requireList = pluginInfo.getRequires();
for (Iterator iter = requireList.iterator(); iter.hasNext();) {
if (((PluginParser.Prerequisite) iter.next()).getName().equalsIgnoreCase(PI_RUNTIME_COMPATIBILITY))
return true;
}
return false;
}
private void generateActivator() {
if (!pluginInfo.isFragment())
if (!requireRuntimeCompatibility()) {
String pluginClass = pluginInfo.getPluginClass();
if (pluginClass != null && !pluginClass.trim().equals("")) //$NON-NLS-1$
generatedManifest.put(Constants.BUNDLE_ACTIVATOR, pluginClass);
} else {
generatedManifest.put(Constants.BUNDLE_ACTIVATOR, COMPATIBILITY_ACTIVATOR);
}
}
private void generateClasspath() {
String[] classpath = pluginInfo.getLibrariesName();
if (classpath.length != 0)
generatedManifest.put(Constants.BUNDLE_CLASSPATH, getStringFromArray(classpath, LIST_SEPARATOR));
}
private void generateHeaders() {
if (TARGET31.equals(target))
generatedManifest.put(Constants.BUNDLE_MANIFESTVERSION, "2"); //$NON-NLS-1$
generatedManifest.put(Constants.BUNDLE_NAME, pluginInfo.getPluginName());
generatedManifest.put(Constants.BUNDLE_VERSION, pluginInfo.getVersion());
generatedManifest.put(Constants.BUNDLE_SYMBOLICNAME, getSymbolicNameEntry());
String provider = pluginInfo.getProviderName();
if (provider != null)
generatedManifest.put(Constants.BUNDLE_VENDOR, provider);
if (pluginInfo.isFragment()) {
StringBuffer hostBundle = new StringBuffer();
hostBundle.append(pluginInfo.getMasterId());
String versionRange = getVersionRange(pluginInfo.getMasterVersion(), pluginInfo.getMasterMatch()); // TODO need to get match rule here!
if (versionRange != null)
hostBundle.append(versionRange);
generatedManifest.put(Constants.FRAGMENT_HOST, hostBundle.toString());
}
}
/*
* Generates an entry in the form:
* <symbolic-name>[; singleton=true]
*/
private String getSymbolicNameEntry() {
// false is the default, so don't bother adding anything
if (!pluginInfo.isSingleton())
return pluginInfo.getUniqueId();
StringBuffer result = new StringBuffer(pluginInfo.getUniqueId());
result.append(SEMICOLON); //$NON-NLS-1$
result.append(Constants.SINGLETON_DIRECTIVE);
String assignment = TARGET31.equals(target) ? ":=" : "="; //$NON-NLS-1$ //$NON-NLS-2$
result.append(assignment).append("true"); //$NON-NLS-1$
return result.toString();
}
private void generatePluginClass() {
if (requireRuntimeCompatibility()) {
String pluginClass = pluginInfo.getPluginClass();
if (pluginClass != null)
generatedManifest.put(EclipseAdaptor.PLUGIN_CLASS, pluginClass);
}
}
private void generateProvidePackage() {
Set exports = getExports();
if (exports != null && exports.size() != 0) {
generatedManifest.put(TARGET31.equals(target) ? Constants.EXPORT_PACKAGE : Constants.PROVIDE_PACKAGE, getStringFromCollection(exports, LIST_SEPARATOR));
}
}
private void generateRequireBundle() {
ArrayList requiredBundles = pluginInfo.getRequires();
if (requiredBundles.size() == 0)
return;
StringBuffer bundleRequire = new StringBuffer();
for (Iterator iter = requiredBundles.iterator(); iter.hasNext();) {
PluginParser.Prerequisite element = (PluginParser.Prerequisite) iter.next();
StringBuffer modImport = new StringBuffer(element.getName());
String versionRange = getVersionRange(element.getVersion(), element.getMatch());
if (versionRange != null)
modImport.append(versionRange);
if (element.isExported()) {
if (TARGET31.equals(target))
modImport.append(';').append(Constants.VISIBILITY_DIRECTIVE).append(":=").append(Constants.VISIBILITY_REEXPORT);//$NON-NLS-1$
else
modImport.append(';').append(Constants.REPROVIDE_ATTRIBUTE).append("=true");//$NON-NLS-1$
}
if (element.isOptional()) {
if (TARGET31.equals(target))
modImport.append(';').append(Constants.RESOLUTION_DIRECTIVE).append(":=").append(Constants.RESOLUTION_OPTIONAL);//$NON-NLS-1$
else
modImport.append(';').append(Constants.OPTIONAL_ATTRIBUTE).append("=true");//$NON-NLS-1$
}
bundleRequire.append(modImport.toString());
if (iter.hasNext())
bundleRequire.append(LIST_SEPARATOR);
}
generatedManifest.put(Constants.REQUIRE_BUNDLE, bundleRequire.toString());
}
private void generateTimestamp() {
// so it is easy to tell which ones are generated
generatedManifest.put(GENERATED_FROM, Long.toString(getTimeStamp(pluginManifestLocation, manifestType)) + ";" + MANIFEST_TYPE_ATTRIBUTE + "=" + manifestType); //$NON-NLS-1$ //$NON-NLS-2$
}
private void generateEclipseHeaders() {
if (!pluginInfo.isFragment())
generatedManifest.put(EclipseAdaptor.ECLIPSE_AUTOSTART, "true"); //$NON-NLS-1$
}
private Set getExports() {
Map libs = pluginInfo.getLibraries();
if (libs == null)
return null;
//If we are in dev mode, then add the binary folders on the list libs with the export clause set to be the cumulation of the export clause of the real libs
if (devProperties != null || DevClassPathHelper.inDevelopmentMode()) {
String[] devClassPath = DevClassPathHelper.getDevClassPath(pluginInfo.getUniqueId(), devProperties);
// collect export clauses
List allExportClauses = new ArrayList(libs.size());
Set libEntries = libs.entrySet();
for (Iterator iter = libEntries.iterator(); iter.hasNext();) {
Map.Entry element = (Map.Entry) iter.next();
allExportClauses.addAll((List) element.getValue());
}
if (devClassPath != null) {
for (int i = 0; i < devClassPath.length; i++)
libs.put(devClassPath[i], allExportClauses);
}
}
Set result = new TreeSet();
Set libEntries = libs.entrySet();
for (Iterator iter = libEntries.iterator(); iter.hasNext();) {
Map.Entry element = (Map.Entry) iter.next();
List filter = (List) element.getValue();
if (filter.size() == 0) //If the library is not exported, then ignore it
continue;
String libEntryText = (String) element.getKey();
File libraryLocation;
if (devProperties != null || DevClassPathHelper.inDevelopmentMode()) {
// in development time, libEntries may contain absolute locations (linked folders)
File libEntryAsPath = new File(libEntryText);
libraryLocation = libEntryAsPath.isAbsolute() ? libEntryAsPath : new File(pluginManifestLocation, libEntryText);
} else
- libraryLocation = new File(pluginManifestLocation, libEntryText);
+ if (!libEntryText.equals(".")) //$NON-NLS-1$
+ libraryLocation = new File(pluginManifestLocation, libEntryText);
+ else
+ libraryLocation = pluginManifestLocation;
Set exports = null;
if (libraryLocation.exists()) {
if (libraryLocation.isFile())
exports = filterExport(getExportsFromJAR(libraryLocation), filter); //TODO Need to handle $xx$ variables
else if (libraryLocation.isDirectory())
exports = filterExport(getExportsFromDir(libraryLocation), filter);
} else {
ArrayList expandedLibs = getLibrariesExpandingVariables((String) element.getKey(), false);
exports = new HashSet();
for (Iterator iterator = expandedLibs.iterator(); iterator.hasNext();) {
String libName = (String) iterator.next();
File libFile = new File(pluginManifestLocation, libName);
if (libFile.isFile()) {
exports.addAll(filterExport(getExportsFromJAR(libFile), filter));
}
}
}
if (exports != null)
result.addAll(exports);
}
return result;
}
private Set getExportsFromDir(File location) {
return getExportsFromDir(location, ""); //$NON-NLS-1$
}
private Set getExportsFromDir(File location, String packageName) {
String prefix = (packageName.length() > 0) ? (packageName + '.') : ""; //$NON-NLS-1$
String[] files = location.list();
Set exportedPaths = new HashSet();
boolean containsFile = false;
if (files != null)
for (int i = 0; i < files.length; i++) {
if (!isValidPackageName(files[i]))
continue;
File pkgFile = new File(location, files[i]);
if (pkgFile.isDirectory())
exportedPaths.addAll(getExportsFromDir(pkgFile, prefix + files[i]));
else
containsFile = true;
}
if (containsFile)
// Allow the default package to be provided. If the default package
// contains a File then use "." as the package name to provide for default.
if (packageName.length() > 0)
exportedPaths.add(packageName);
else
exportedPaths.add(DOT);
return exportedPaths;
}
private Set getExportsFromJAR(File jarFile) {
Set names = new HashSet();
JarFile file = null;
try {
file = new JarFile(jarFile);
} catch (IOException e) {
String message = NLS.bind(EclipseAdaptorMsg.ECLIPSE_CONVERTER_PLUGIN_LIBRARY_IGNORED, jarFile, pluginInfo.getUniqueId());
EclipseAdaptor.getDefault().getFrameworkLog().log(new FrameworkLogEntry(FrameworkAdaptor.FRAMEWORK_SYMBOLICNAME, message, 0, e, null));
return names;
}
//Run through the entries
for (Enumeration entriesEnum = file.entries(); entriesEnum.hasMoreElements();) {
JarEntry entry = (JarEntry) entriesEnum.nextElement();
String name = entry.getName();
if (!isValidPackageName(name))
continue;
int lastSlash = name.lastIndexOf("/"); //$NON-NLS-1$
//Ignore folders that do not contain files
if (lastSlash != -1) {
if (lastSlash != name.length() - 1 && name.lastIndexOf(' ') == -1)
names.add(name.substring(0, lastSlash).replace('/', '.'));
} else {
// Allow the default package to be provided. If the default package
// contains a File then use "." as the package name to provide for default.
names.add(DOT);
}
}
try {
file.close();
} catch (IOException e) {
// Nothing to do
}
return names;
}
private ArrayList getLibrariesExpandingVariables(String libraryPath, boolean filter) {
String var = hasPrefix(libraryPath);
if (var == null) {
ArrayList returnValue = new ArrayList(1);
returnValue.add(libraryPath);
return returnValue;
}
if (var.equals("ws")) { //$NON-NLS-1$
return findWSJars(pluginManifestLocation, libraryPath, filter);
}
if (var.equals("os")) { //$NON-NLS-1$
return findOSJars(pluginManifestLocation, libraryPath, filter);
}
return new ArrayList(0);
}
//return a String representing the string found between the $s
private String hasPrefix(String libPath) {
if (libPath.startsWith("$ws$")) //$NON-NLS-1$
return "ws"; //$NON-NLS-1$
if (libPath.startsWith("$os$")) //$NON-NLS-1$
return "os"; //$NON-NLS-1$
if (libPath.startsWith("$nl$")) //$NON-NLS-1$
return "nl"; //$NON-NLS-1$
return null;
}
private boolean isValidPackageName(String name) {
if (name.indexOf(' ') > 0 || name.equalsIgnoreCase("META-INF") || name.startsWith("META-INF/")) //$NON-NLS-1$ //$NON-NLS-2$
return false;
return true;
}
/**
* Parses the plugin manifest to find out: - the plug-in unique identifier -
* the plug-in version - runtime/libraries entries - the plug-in class -
* the master plugin (for a fragment)
*/
private IPluginInfo parsePluginInfo(URL pluginLocation) throws PluginConversionException {
InputStream input = null;
try {
input = new BufferedInputStream(pluginLocation.openStream());
return new PluginParser(context, target).parsePlugin(input);
} catch (Exception e) {
String message = NLS.bind(EclipseAdaptorMsg.ECLIPSE_CONVERTER_ERROR_PARSING_PLUGIN_MANIFEST, pluginManifestLocation);
throw new PluginConversionException(message, e);
} finally {
if (input != null)
try {
input.close();
} catch (IOException e) {
//ignore exception
}
}
}
public static boolean upToDate(File generationLocation, File pluginLocation, byte manifestType) {
if (!generationLocation.isFile())
return false;
String secondLine = null;
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(new FileInputStream(generationLocation)));
reader.readLine();
secondLine = reader.readLine();
} catch (IOException e) {
// not a big deal - we could not read an existing manifest
return false;
} finally {
if (reader != null)
try {
reader.close();
} catch (IOException e) {
// ignore
}
}
String tag = GENERATED_FROM + ": "; //$NON-NLS-1$
if (secondLine == null || !secondLine.startsWith(tag))
return false;
secondLine = secondLine.substring(tag.length());
ManifestElement generatedFrom;
try {
generatedFrom = ManifestElement.parseHeader(PluginConverterImpl.GENERATED_FROM, secondLine)[0];
} catch (BundleException be) {
return false;
}
String timestampStr = generatedFrom.getValue();
try {
return Long.parseLong(timestampStr.trim()) == getTimeStamp(pluginLocation, manifestType);
} catch (NumberFormatException nfe) {
// not a big deal - just a bogus existing manifest that will be ignored
}
return false;
}
public static long getTimeStamp(File pluginLocation, byte manifestType) {
if ((manifestType & EclipseBundleData.MANIFEST_TYPE_JAR) != 0)
return pluginLocation.lastModified();
else if ((manifestType & EclipseBundleData.MANIFEST_TYPE_PLUGIN) != 0)
return new File(pluginLocation, PLUGIN_MANIFEST).lastModified();
else if ((manifestType & EclipseBundleData.MANIFEST_TYPE_FRAGMENT) != 0)
return new File(pluginLocation, FRAGMENT_MANIFEST).lastModified();
else if ((manifestType & EclipseBundleData.MANIFEST_TYPE_BUNDLE) != 0)
return new File(pluginLocation, Constants.OSGI_BUNDLE_MANIFEST).lastModified();
return -1;
}
private void writeEntry(String key, String value) throws IOException {
if (value != null && value.length() > 0) {
out.write(key + ": " + value); //$NON-NLS-1$
out.newLine();
}
}
private String getStringFromArray(String[] values, String separator) {
if (values == null)
return ""; //$NON-NLS-1$
StringBuffer result = new StringBuffer();
for (int i = 0; i < values.length; i++) {
if (i > 0)
result.append(separator);
result.append(values[i]);
}
return result.toString();
}
private String getStringFromCollection(Collection collection, String separator) {
StringBuffer result = new StringBuffer();
boolean first = true;
for (Iterator i = collection.iterator(); i.hasNext();) {
if (first)
first = false;
else
result.append(separator);
result.append(i.next());
}
return result.toString();
}
public synchronized Dictionary convertManifest(File pluginBaseLocation, boolean compatibility, String target, boolean analyseJars, Dictionary devProperties) throws PluginConversionException {
if (DEBUG)
System.out.println("Convert " + pluginBaseLocation); //$NON-NLS-1$
init();
this.target = target == null ? TARGET31 : target;
this.devProperties = devProperties;
fillPluginInfo(pluginBaseLocation);
fillManifest(compatibility, analyseJars);
return generatedManifest;
}
public synchronized Dictionary convertManifest(File pluginBaseLocation, boolean compatibility, String target, boolean analyseJars) throws PluginConversionException {
return convertManifest(pluginBaseLocation, compatibility, target, analyseJars, null);
}
public synchronized File convertManifest(File pluginBaseLocation, File bundleManifestLocation, boolean compatibilityManifest, String target, boolean analyseJars, Dictionary devProperties) throws PluginConversionException {
convertManifest(pluginBaseLocation, compatibilityManifest, target, analyseJars, devProperties);
if (bundleManifestLocation == null) {
String cacheLocation = (String) System.getProperties().get(LocationManager.PROP_MANIFEST_CACHE);
bundleManifestLocation = new File(cacheLocation, pluginInfo.getUniqueId() + '_' + pluginInfo.getVersion() + ".MF"); //$NON-NLS-1$
}
if (upToDate(bundleManifestLocation, pluginManifestLocation, manifestType))
return bundleManifestLocation;
writeManifest(bundleManifestLocation, generatedManifest, compatibilityManifest);
return bundleManifestLocation;
}
public synchronized File convertManifest(File pluginBaseLocation, File bundleManifestLocation, boolean compatibilityManifest, String target, boolean analyseJars) throws PluginConversionException {
return convertManifest(pluginBaseLocation, bundleManifestLocation, compatibilityManifest, target, analyseJars, null);
}
private String getVersionRange(String reqVersion, String matchRule) {
if (reqVersion == null)
return null;
Version minVersion = Version.parseVersion(reqVersion);
String versionRange;
if (matchRule != null) {
if (matchRule.equalsIgnoreCase(IModel.PLUGIN_REQUIRES_MATCH_PERFECT)) {
versionRange = new VersionRange(minVersion, true, minVersion, true).toString();
} else if (matchRule.equalsIgnoreCase(IModel.PLUGIN_REQUIRES_MATCH_EQUIVALENT)) {
versionRange = new VersionRange(minVersion, true, new Version(minVersion.getMajor(), minVersion.getMinor() + 1, 0, ""), false).toString(); //$NON-NLS-1$
} else if (matchRule.equalsIgnoreCase(IModel.PLUGIN_REQUIRES_MATCH_COMPATIBLE)) {
versionRange = new VersionRange(minVersion, true, new Version(minVersion.getMajor() + 1, 0, 0, ""), false).toString(); //$NON-NLS-1$
} else if (matchRule.equalsIgnoreCase(IModel.PLUGIN_REQUIRES_MATCH_GREATER_OR_EQUAL)) {
// just return the reqVersion here without any version range
versionRange = reqVersion;
} else {
versionRange = new VersionRange(minVersion, true, new Version(minVersion.getMajor() + 1, 0, 0, ""), false).toString(); //$NON-NLS-1$
}
} else {
versionRange = new VersionRange(minVersion, true, new Version(minVersion.getMajor() + 1, 0, 0, ""), false).toString(); //$NON-NLS-1$
}
StringBuffer result = new StringBuffer();
result.append(';').append(Constants.BUNDLE_VERSION_ATTRIBUTE).append('=');
result.append('\"').append(versionRange).append('\"');
return result.toString();
}
}
| true | true | private Set getExports() {
Map libs = pluginInfo.getLibraries();
if (libs == null)
return null;
//If we are in dev mode, then add the binary folders on the list libs with the export clause set to be the cumulation of the export clause of the real libs
if (devProperties != null || DevClassPathHelper.inDevelopmentMode()) {
String[] devClassPath = DevClassPathHelper.getDevClassPath(pluginInfo.getUniqueId(), devProperties);
// collect export clauses
List allExportClauses = new ArrayList(libs.size());
Set libEntries = libs.entrySet();
for (Iterator iter = libEntries.iterator(); iter.hasNext();) {
Map.Entry element = (Map.Entry) iter.next();
allExportClauses.addAll((List) element.getValue());
}
if (devClassPath != null) {
for (int i = 0; i < devClassPath.length; i++)
libs.put(devClassPath[i], allExportClauses);
}
}
Set result = new TreeSet();
Set libEntries = libs.entrySet();
for (Iterator iter = libEntries.iterator(); iter.hasNext();) {
Map.Entry element = (Map.Entry) iter.next();
List filter = (List) element.getValue();
if (filter.size() == 0) //If the library is not exported, then ignore it
continue;
String libEntryText = (String) element.getKey();
File libraryLocation;
if (devProperties != null || DevClassPathHelper.inDevelopmentMode()) {
// in development time, libEntries may contain absolute locations (linked folders)
File libEntryAsPath = new File(libEntryText);
libraryLocation = libEntryAsPath.isAbsolute() ? libEntryAsPath : new File(pluginManifestLocation, libEntryText);
} else
libraryLocation = new File(pluginManifestLocation, libEntryText);
Set exports = null;
if (libraryLocation.exists()) {
if (libraryLocation.isFile())
exports = filterExport(getExportsFromJAR(libraryLocation), filter); //TODO Need to handle $xx$ variables
else if (libraryLocation.isDirectory())
exports = filterExport(getExportsFromDir(libraryLocation), filter);
} else {
ArrayList expandedLibs = getLibrariesExpandingVariables((String) element.getKey(), false);
exports = new HashSet();
for (Iterator iterator = expandedLibs.iterator(); iterator.hasNext();) {
String libName = (String) iterator.next();
File libFile = new File(pluginManifestLocation, libName);
if (libFile.isFile()) {
exports.addAll(filterExport(getExportsFromJAR(libFile), filter));
}
}
}
if (exports != null)
result.addAll(exports);
}
return result;
}
| private Set getExports() {
Map libs = pluginInfo.getLibraries();
if (libs == null)
return null;
//If we are in dev mode, then add the binary folders on the list libs with the export clause set to be the cumulation of the export clause of the real libs
if (devProperties != null || DevClassPathHelper.inDevelopmentMode()) {
String[] devClassPath = DevClassPathHelper.getDevClassPath(pluginInfo.getUniqueId(), devProperties);
// collect export clauses
List allExportClauses = new ArrayList(libs.size());
Set libEntries = libs.entrySet();
for (Iterator iter = libEntries.iterator(); iter.hasNext();) {
Map.Entry element = (Map.Entry) iter.next();
allExportClauses.addAll((List) element.getValue());
}
if (devClassPath != null) {
for (int i = 0; i < devClassPath.length; i++)
libs.put(devClassPath[i], allExportClauses);
}
}
Set result = new TreeSet();
Set libEntries = libs.entrySet();
for (Iterator iter = libEntries.iterator(); iter.hasNext();) {
Map.Entry element = (Map.Entry) iter.next();
List filter = (List) element.getValue();
if (filter.size() == 0) //If the library is not exported, then ignore it
continue;
String libEntryText = (String) element.getKey();
File libraryLocation;
if (devProperties != null || DevClassPathHelper.inDevelopmentMode()) {
// in development time, libEntries may contain absolute locations (linked folders)
File libEntryAsPath = new File(libEntryText);
libraryLocation = libEntryAsPath.isAbsolute() ? libEntryAsPath : new File(pluginManifestLocation, libEntryText);
} else
if (!libEntryText.equals(".")) //$NON-NLS-1$
libraryLocation = new File(pluginManifestLocation, libEntryText);
else
libraryLocation = pluginManifestLocation;
Set exports = null;
if (libraryLocation.exists()) {
if (libraryLocation.isFile())
exports = filterExport(getExportsFromJAR(libraryLocation), filter); //TODO Need to handle $xx$ variables
else if (libraryLocation.isDirectory())
exports = filterExport(getExportsFromDir(libraryLocation), filter);
} else {
ArrayList expandedLibs = getLibrariesExpandingVariables((String) element.getKey(), false);
exports = new HashSet();
for (Iterator iterator = expandedLibs.iterator(); iterator.hasNext();) {
String libName = (String) iterator.next();
File libFile = new File(pluginManifestLocation, libName);
if (libFile.isFile()) {
exports.addAll(filterExport(getExportsFromJAR(libFile), filter));
}
}
}
if (exports != null)
result.addAll(exports);
}
return result;
}
|
diff --git a/src/de/ueller/midlet/gps/GuiWaypoint.java b/src/de/ueller/midlet/gps/GuiWaypoint.java
index 6a3bc4fa..66173083 100644
--- a/src/de/ueller/midlet/gps/GuiWaypoint.java
+++ b/src/de/ueller/midlet/gps/GuiWaypoint.java
@@ -1,158 +1,161 @@
package de.ueller.midlet.gps;
/*
* GpsMid - Copyright (c) 2008 Kai Krueger apm at users dot sourceforge dot net
* See Copying
*/
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.List;
import de.ueller.midlet.gps.data.MoreMath;
import de.ueller.midlet.gps.data.IntPoint;
import de.ueller.midlet.gps.data.Node;
import de.ueller.midlet.gps.data.PositionMark;
public class GuiWaypoint extends List implements CommandListener,
GpsMidDisplayable, UploadListener {
private final static Logger logger=Logger.getInstance(GuiWaypoint.class,Logger.DEBUG);
private final Command SEND_ALL_CMD = new Command("Send All", Command.ITEM, 1);
private final Command LOAD_CMD = new Command("Load Gpx", Command.ITEM, 2);
private final Command SEND_CMD = new Command("Send", Command.ITEM, 4);
private final Command DEL_CMD = new Command("delete", Command.ITEM, 2);
private final Command SALL_CMD = new Command("Select All", Command.ITEM, 2);
private final Command DSALL_CMD = new Command("Deselect All", Command.ITEM, 2);
private final Command BACK_CMD = new Command("Back", Command.BACK, 5);
private final Command GOTO_CMD = new Command("Display", Command.OK,6);
private PositionMark[] waypoints;
private final Trace parent;
public GuiWaypoint(Trace parent) throws Exception {
super("Waypoints", List.MULTIPLE);
this.parent = parent;
setCommandListener(this);
initWaypoints();
//addCommand(SEND_CMD);
addCommand(SEND_ALL_CMD);
addCommand(LOAD_CMD);
addCommand(DEL_CMD);
addCommand(SALL_CMD);
addCommand(DSALL_CMD);
addCommand(BACK_CMD);
addCommand(GOTO_CMD);
}
/**
* Read tracks from the GPX recordStore and display the names in the list on screen.
*/
private void initWaypoints() {
this.deleteAll();
waypoints = parent.gpx.listWayPt();
for (int i = 0; i < waypoints.length; i++) {
this.append(waypoints[i].displayName,null);
}
}
public void commandAction(Command c, Displayable d) {
logger.debug("got Command " + c);
if (c == SEND_CMD) {
/* TODO */
return;
}
if (c == DEL_CMD) {
boolean[] sel = new boolean[waypoints.length];
this.getSelectedFlags(sel);
for (int i = 0; i < sel.length; i++) {
if (sel[i]) {
parent.gpx.deleteWayPt(waypoints[i]);
}
}
initWaypoints();
return;
}
if ((c == SALL_CMD) || (c == DSALL_CMD)) {
boolean select = (c == SALL_CMD);
boolean[] sel = new boolean[waypoints.length];
for (int i = 0; i < waypoints.length; i++)
sel[i] = select;
this.setSelectedFlags(sel);
return;
}
if (c == BACK_CMD) {
parent.show();
return;
}
if (c == SEND_ALL_CMD) {
parent.gpx.sendWayPt(parent.getConfig().getGpxUrl(), this);
return;
}
if (c == LOAD_CMD) {
GuiGpxLoad ggl = new GuiGpxLoad(this);
ggl.show();
return;
}
if (c == GOTO_CMD) {
float w = 0, e = 0, n = 0, s = 0;
int idx = -1;
boolean[] sel = new boolean[waypoints.length];
this.getSelectedFlags(sel);
for (int i = 0; i < sel.length; i++) {
if (sel[i]) {
if (idx == -1) {
idx = i;
w = waypoints[i].lon;
e = waypoints[i].lon;
n = waypoints[i].lat;
s = waypoints[i].lat;
} else {
idx = -2;
if (waypoints[i].lon < w)
w = waypoints[i].lon;
if (waypoints[i].lon > e)
e = waypoints[i].lon;
if (waypoints[i].lat < s)
s = waypoints[i].lat;
if (waypoints[i].lat > n)
n = waypoints[i].lat;
}
}
}
- if (idx > -1) {
+ if (idx == -1) {
+ logger.error("No waypoint selected");
+ return;
+ } else if (idx > -1) {
parent.setTarget(waypoints[idx]);
} else {
IntPoint intPoint1 = new IntPoint(10,10);
IntPoint intPoint2 = new IntPoint(getWidth() - 10,getHeight() - 10);
Node n1 = new Node(n*MoreMath.FAC_RADTODEC,w*MoreMath.FAC_RADTODEC);
Node n2 = new Node(s*MoreMath.FAC_RADTODEC,e*MoreMath.FAC_RADTODEC);
float scale = parent.projection.getScale(n1, n2, intPoint1, intPoint2);
parent.receivePosItion((n-s)/2 + s, (e-w)/2 + w, scale*1.2f);
}
parent.show();
return;
}
}
public void completedUpload() {
Alert alert = new Alert("Information");
alert.setString("Completed GPX upload");
Display.getDisplay(parent.getParent()).setCurrent(alert);
}
public void show() {
Display.getDisplay(parent.getParent()).setCurrent(this);
}
}
| true | true | public void commandAction(Command c, Displayable d) {
logger.debug("got Command " + c);
if (c == SEND_CMD) {
/* TODO */
return;
}
if (c == DEL_CMD) {
boolean[] sel = new boolean[waypoints.length];
this.getSelectedFlags(sel);
for (int i = 0; i < sel.length; i++) {
if (sel[i]) {
parent.gpx.deleteWayPt(waypoints[i]);
}
}
initWaypoints();
return;
}
if ((c == SALL_CMD) || (c == DSALL_CMD)) {
boolean select = (c == SALL_CMD);
boolean[] sel = new boolean[waypoints.length];
for (int i = 0; i < waypoints.length; i++)
sel[i] = select;
this.setSelectedFlags(sel);
return;
}
if (c == BACK_CMD) {
parent.show();
return;
}
if (c == SEND_ALL_CMD) {
parent.gpx.sendWayPt(parent.getConfig().getGpxUrl(), this);
return;
}
if (c == LOAD_CMD) {
GuiGpxLoad ggl = new GuiGpxLoad(this);
ggl.show();
return;
}
if (c == GOTO_CMD) {
float w = 0, e = 0, n = 0, s = 0;
int idx = -1;
boolean[] sel = new boolean[waypoints.length];
this.getSelectedFlags(sel);
for (int i = 0; i < sel.length; i++) {
if (sel[i]) {
if (idx == -1) {
idx = i;
w = waypoints[i].lon;
e = waypoints[i].lon;
n = waypoints[i].lat;
s = waypoints[i].lat;
} else {
idx = -2;
if (waypoints[i].lon < w)
w = waypoints[i].lon;
if (waypoints[i].lon > e)
e = waypoints[i].lon;
if (waypoints[i].lat < s)
s = waypoints[i].lat;
if (waypoints[i].lat > n)
n = waypoints[i].lat;
}
}
}
if (idx > -1) {
parent.setTarget(waypoints[idx]);
} else {
IntPoint intPoint1 = new IntPoint(10,10);
IntPoint intPoint2 = new IntPoint(getWidth() - 10,getHeight() - 10);
Node n1 = new Node(n*MoreMath.FAC_RADTODEC,w*MoreMath.FAC_RADTODEC);
Node n2 = new Node(s*MoreMath.FAC_RADTODEC,e*MoreMath.FAC_RADTODEC);
float scale = parent.projection.getScale(n1, n2, intPoint1, intPoint2);
parent.receivePosItion((n-s)/2 + s, (e-w)/2 + w, scale*1.2f);
}
parent.show();
return;
}
}
| public void commandAction(Command c, Displayable d) {
logger.debug("got Command " + c);
if (c == SEND_CMD) {
/* TODO */
return;
}
if (c == DEL_CMD) {
boolean[] sel = new boolean[waypoints.length];
this.getSelectedFlags(sel);
for (int i = 0; i < sel.length; i++) {
if (sel[i]) {
parent.gpx.deleteWayPt(waypoints[i]);
}
}
initWaypoints();
return;
}
if ((c == SALL_CMD) || (c == DSALL_CMD)) {
boolean select = (c == SALL_CMD);
boolean[] sel = new boolean[waypoints.length];
for (int i = 0; i < waypoints.length; i++)
sel[i] = select;
this.setSelectedFlags(sel);
return;
}
if (c == BACK_CMD) {
parent.show();
return;
}
if (c == SEND_ALL_CMD) {
parent.gpx.sendWayPt(parent.getConfig().getGpxUrl(), this);
return;
}
if (c == LOAD_CMD) {
GuiGpxLoad ggl = new GuiGpxLoad(this);
ggl.show();
return;
}
if (c == GOTO_CMD) {
float w = 0, e = 0, n = 0, s = 0;
int idx = -1;
boolean[] sel = new boolean[waypoints.length];
this.getSelectedFlags(sel);
for (int i = 0; i < sel.length; i++) {
if (sel[i]) {
if (idx == -1) {
idx = i;
w = waypoints[i].lon;
e = waypoints[i].lon;
n = waypoints[i].lat;
s = waypoints[i].lat;
} else {
idx = -2;
if (waypoints[i].lon < w)
w = waypoints[i].lon;
if (waypoints[i].lon > e)
e = waypoints[i].lon;
if (waypoints[i].lat < s)
s = waypoints[i].lat;
if (waypoints[i].lat > n)
n = waypoints[i].lat;
}
}
}
if (idx == -1) {
logger.error("No waypoint selected");
return;
} else if (idx > -1) {
parent.setTarget(waypoints[idx]);
} else {
IntPoint intPoint1 = new IntPoint(10,10);
IntPoint intPoint2 = new IntPoint(getWidth() - 10,getHeight() - 10);
Node n1 = new Node(n*MoreMath.FAC_RADTODEC,w*MoreMath.FAC_RADTODEC);
Node n2 = new Node(s*MoreMath.FAC_RADTODEC,e*MoreMath.FAC_RADTODEC);
float scale = parent.projection.getScale(n1, n2, intPoint1, intPoint2);
parent.receivePosItion((n-s)/2 + s, (e-w)/2 + w, scale*1.2f);
}
parent.show();
return;
}
}
|
diff --git a/loci/visbio/help/HelpWindow.java b/loci/visbio/help/HelpWindow.java
index 1459c127a..1df2ddcb7 100644
--- a/loci/visbio/help/HelpWindow.java
+++ b/loci/visbio/help/HelpWindow.java
@@ -1,233 +1,233 @@
//
// HelpWindow.java
//
/*
VisBio application for visualization of multidimensional
biological image data. Copyright (C) 2002-2004 Curtis Rueden.
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.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package loci.visbio.help;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.io.*;
import java.util.Enumeration;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.html.HTMLFrameHyperlinkEvent;
import javax.swing.text.html.HTMLDocument;
import javax.swing.tree.*;
import loci.visbio.util.BrowserLauncher;
import loci.visbio.util.SwingUtil;
/** HelpWindow details basic VisBio program usage. */
public class HelpWindow extends JFrame
implements HyperlinkListener, TreeSelectionListener
{
// -- Constants --
/** Default width of help window in pixels. */
private static final int DEFAULT_WIDTH = 950;
/** Default height of help window in pixels. */
private static final int DEFAULT_HEIGHT = 700;
/** Minimum width of tree pane. */
private static final int MIN_TREE_WIDTH = 250;
// -- Fields --
/** Help topic tree root node. */
private HelpTopic root;
/** Tree of help topics. */
private JTree topics;
/** Pane containing the current help topic. */
private JEditorPane pane;
// -- Constructor --
/** Creates a VisBio help window. */
public HelpWindow() {
super("VisBio Help");
// create components
root = new HelpTopic("VisBio Help Topics", null);
topics = new JTree(root);
topics.setRootVisible(false);
topics.setShowsRootHandles(true);
topics.getSelectionModel().setSelectionMode(
TreeSelectionModel.SINGLE_TREE_SELECTION);
topics.addTreeSelectionListener(this);
pane = new JEditorPane("text/html", "");
pane.addHyperlinkListener(this);
pane.setEditable(false);
// lay out components
JScrollPane topicsScroll = new JScrollPane(topics);
topicsScroll.setMinimumSize(new Dimension(MIN_TREE_WIDTH, 0));
SwingUtil.configureScrollPane(topicsScroll);
JScrollPane paneScroll = new JScrollPane(pane);
SwingUtil.configureScrollPane(paneScroll);
JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
topicsScroll, paneScroll);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int width = screenSize.width - 25, height = screenSize.height - 50;
if (width > DEFAULT_WIDTH) width = DEFAULT_WIDTH;
- if (height > DEFAULT_HEIGHT) width = DEFAULT_HEIGHT;
+ if (height > DEFAULT_HEIGHT) height = DEFAULT_HEIGHT;
split.setPreferredSize(new Dimension(width, height));
setContentPane(split);
}
// -- HelpWindow API methods --
/** Adds the given topic to the list, from the given source file. */
public void addTopic(String topic, String source) {
addTopic(root, topic, source);
}
// -- JFrame API methods --
/** Expands tree fully before packing help window. */
public void pack() {
// HACK - Expanding nodes as they are added to the tree results in bizarre
// behavior (nodes permanently missing from the tree). Better to expand
// everything after the tree has been completely built.
Enumeration e = root.breadthFirstEnumeration();
topics.expandPath(new TreePath(root.getPath()));
while (e.hasMoreElements()) {
HelpTopic node = (HelpTopic) e.nextElement();
if (node.isLeaf()) continue;
topics.expandPath(new TreePath(node.getPath()));
}
// select first child node
HelpTopic firstChild = (HelpTopic) root.getChildAt(0);
topics.setSelectionPath(new TreePath(firstChild.getPath()));
super.pack();
}
// -- HyperlinkListener API methods --
/** Handles hyperlinks. */
public void hyperlinkUpdate(HyperlinkEvent e) {
if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
if (e instanceof HTMLFrameHyperlinkEvent) {
HTMLFrameHyperlinkEvent evt = (HTMLFrameHyperlinkEvent) e;
HTMLDocument doc = (HTMLDocument) pane.getDocument();
doc.processHTMLFrameHyperlinkEvent(evt);
}
else {
String source = e.getURL().toString();
HelpTopic node = findTopic(source);
if (node != null) {
TreePath path = new TreePath(node.getPath());
topics.setSelectionPath(path);
topics.scrollPathToVisible(path);
}
else {
// launch external browser to handle the link
try { BrowserLauncher.openURL(source); }
catch (IOException exc) { exc.printStackTrace(); }
}
}
}
}
// -- TreeSelectionListener API methods --
/** Updates help topic based on user selection. */
public void valueChanged(TreeSelectionEvent e) {
TreePath path = e.getNewLeadSelectionPath();
HelpTopic node = path == null ? null :
(HelpTopic) path.getLastPathComponent();
final String source = node == null ? null : node.getSource();
if (source == null) {
pane.setText(node == null ? "" : node.getName());
return;
}
pane.setText("<h2>" + node.getName() + "</h2>");
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try { pane.setPage(getClass().getResource(source)); }
catch (IOException exc) {
StringWriter sw = new StringWriter();
exc.printStackTrace(new PrintWriter(sw));
pane.setText(source + "<pre>" + sw.toString() + "</pre>");
}
// HACK - JEditorPane.setPage(URL) throws a RuntimeException
// ("Must insert new content into body element-")
// when editor pane is successively updated too rapidly.
// This 50ms delay seems sufficient to prevent the exception.
try { Thread.sleep(50); }
catch (InterruptedException exc) { }
}
});
}
// -- Helper methods --
/** Recursively adds the given topic to the tree at the given position. */
private void addTopic(HelpTopic parent, String topic, String source) {
//topics.expandPath(new TreePath(parent.getPath()));
int slash = topic.indexOf("/");
if (slash < 0) parent.add(new HelpTopic(topic, source));
else {
String pre = topic.substring(0, slash);
String post = topic.substring(slash + 1);
HelpTopic child = null;
Enumeration e = parent.children();
while (e.hasMoreElements()) {
HelpTopic node = (HelpTopic) e.nextElement();
if (node.getName().equals(pre)) {
child = node;
break;
}
}
if (child == null) {
child = new HelpTopic(pre, null);
parent.add(child);
}
addTopic(child, post, source);
}
}
/** Locates the first node with the given source. */
private HelpTopic findTopic(String source) {
Enumeration e = root.breadthFirstEnumeration();
while (e.hasMoreElements()) {
HelpTopic node = (HelpTopic) e.nextElement();
String nodeSource = node.getSource();
if (nodeSource == null) continue;
// HACK - since URL strings have multiple possible structures, this
// search just compares the end of the search string. If a link points to
// an external URL that happens to end with the same string as one of the
// help topics, this method will erroneously flag that topic anyway.
if (source.endsWith(nodeSource)) return node;
}
return null;
}
}
| true | true | public HelpWindow() {
super("VisBio Help");
// create components
root = new HelpTopic("VisBio Help Topics", null);
topics = new JTree(root);
topics.setRootVisible(false);
topics.setShowsRootHandles(true);
topics.getSelectionModel().setSelectionMode(
TreeSelectionModel.SINGLE_TREE_SELECTION);
topics.addTreeSelectionListener(this);
pane = new JEditorPane("text/html", "");
pane.addHyperlinkListener(this);
pane.setEditable(false);
// lay out components
JScrollPane topicsScroll = new JScrollPane(topics);
topicsScroll.setMinimumSize(new Dimension(MIN_TREE_WIDTH, 0));
SwingUtil.configureScrollPane(topicsScroll);
JScrollPane paneScroll = new JScrollPane(pane);
SwingUtil.configureScrollPane(paneScroll);
JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
topicsScroll, paneScroll);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int width = screenSize.width - 25, height = screenSize.height - 50;
if (width > DEFAULT_WIDTH) width = DEFAULT_WIDTH;
if (height > DEFAULT_HEIGHT) width = DEFAULT_HEIGHT;
split.setPreferredSize(new Dimension(width, height));
setContentPane(split);
}
| public HelpWindow() {
super("VisBio Help");
// create components
root = new HelpTopic("VisBio Help Topics", null);
topics = new JTree(root);
topics.setRootVisible(false);
topics.setShowsRootHandles(true);
topics.getSelectionModel().setSelectionMode(
TreeSelectionModel.SINGLE_TREE_SELECTION);
topics.addTreeSelectionListener(this);
pane = new JEditorPane("text/html", "");
pane.addHyperlinkListener(this);
pane.setEditable(false);
// lay out components
JScrollPane topicsScroll = new JScrollPane(topics);
topicsScroll.setMinimumSize(new Dimension(MIN_TREE_WIDTH, 0));
SwingUtil.configureScrollPane(topicsScroll);
JScrollPane paneScroll = new JScrollPane(pane);
SwingUtil.configureScrollPane(paneScroll);
JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
topicsScroll, paneScroll);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int width = screenSize.width - 25, height = screenSize.height - 50;
if (width > DEFAULT_WIDTH) width = DEFAULT_WIDTH;
if (height > DEFAULT_HEIGHT) height = DEFAULT_HEIGHT;
split.setPreferredSize(new Dimension(width, height));
setContentPane(split);
}
|
diff --git a/jOOQ-test/src/org/jooq/test/_/testcases/GroupByTests.java b/jOOQ-test/src/org/jooq/test/_/testcases/GroupByTests.java
index fd71f5bd0..753f519d2 100644
--- a/jOOQ-test/src/org/jooq/test/_/testcases/GroupByTests.java
+++ b/jOOQ-test/src/org/jooq/test/_/testcases/GroupByTests.java
@@ -1,330 +1,327 @@
/**
* Copyright (c) 2009-2013, Lukas Eder, [email protected]
* All rights reserved.
*
* This software is licensed to you under the Apache License, Version 2.0
* (the "License"); You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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.
*
* . Neither the name "jOOQ" 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 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 OWNER 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 org.jooq.test._.testcases;
import static java.util.Arrays.asList;
import static junit.framework.Assert.assertEquals;
import static org.jooq.SQLDialect.DB2;
import static org.jooq.SQLDialect.MARIADB;
import static org.jooq.SQLDialect.MYSQL;
import static org.jooq.SQLDialect.SYBASE;
import static org.jooq.impl.DSL.count;
import static org.jooq.impl.DSL.cube;
import static org.jooq.impl.DSL.grouping;
import static org.jooq.impl.DSL.groupingId;
import static org.jooq.impl.DSL.groupingSets;
import static org.jooq.impl.DSL.one;
import static org.jooq.impl.DSL.rollup;
import static org.jooq.impl.DSL.selectOne;
import java.sql.Date;
import java.util.Arrays;
import org.jooq.Field;
import org.jooq.Record1;
import org.jooq.Record2;
import org.jooq.Record3;
import org.jooq.Record4;
import org.jooq.Record6;
import org.jooq.Result;
import org.jooq.TableRecord;
import org.jooq.UpdatableRecord;
import org.jooq.exception.DataAccessException;
import org.jooq.test.BaseTest;
import org.jooq.test.jOOQAbstractTest;
import org.junit.Test;
public class GroupByTests<
A extends UpdatableRecord<A> & Record6<Integer, String, String, Date, Integer, ?>,
AP,
B extends UpdatableRecord<B>,
S extends UpdatableRecord<S> & Record1<String>,
B2S extends UpdatableRecord<B2S> & Record3<String, Integer, Integer>,
BS extends UpdatableRecord<BS>,
L extends TableRecord<L> & Record2<String, String>,
X extends TableRecord<X>,
DATE extends UpdatableRecord<DATE>,
BOOL extends UpdatableRecord<BOOL>,
D extends UpdatableRecord<D>,
T extends UpdatableRecord<T>,
U extends TableRecord<U>,
UU extends UpdatableRecord<UU>,
I extends TableRecord<I>,
IPK extends UpdatableRecord<IPK>,
T725 extends UpdatableRecord<T725>,
T639 extends UpdatableRecord<T639>,
T785 extends TableRecord<T785>>
extends BaseTest<A, AP, B, S, B2S, BS, L, X, DATE, BOOL, D, T, U, UU, I, IPK, T725, T639, T785> {
public GroupByTests(jOOQAbstractTest<A, AP, B, S, B2S, BS, L, X, DATE, BOOL, D, T, U, UU, I, IPK, T725, T639, T785> delegate) {
super(delegate);
}
@Test
public void testEmptyGrouping() throws Exception {
// [#1665] Test the empty GROUP BY clause
assertEquals(1, (int) create().selectOne()
.from(TBook())
.groupBy()
.fetchOne(0, Integer.class));
// [#1665] Test the empty GROUP BY clause
assertEquals(1, (int) create().selectOne()
.from(TBook())
.groupBy()
.having("1 = 1")
.fetchOne(0, Integer.class));
}
@Test
public void testGrouping() throws Exception {
// Test a simple group by query
Field<Integer> count = count().as("c");
Result<Record2<Integer, Integer>> result = create()
.select(TBook_AUTHOR_ID(), count)
.from(TBook())
.groupBy(TBook_AUTHOR_ID()).fetch();
assertEquals(2, result.size());
assertEquals(2, (int) result.get(0).getValue(count));
assertEquals(2, (int) result.get(1).getValue(count));
// Test a group by query with a single HAVING clause
Result<Record2<String, Integer>> result2 = create()
.select(TAuthor_LAST_NAME(), count)
.from(TBook())
.join(TAuthor()).on(TBook_AUTHOR_ID().equal(TAuthor_ID()))
.where(TBook_TITLE().notEqual("1984"))
.groupBy(TAuthor_LAST_NAME())
.having(count().equal(2))
.fetch();
assertEquals(1, result2.size());
assertEquals(2, (int) result2.getValue(0, count));
assertEquals("Coelho", result2.getValue(0, TAuthor_LAST_NAME()));
// Test a group by query with a combined HAVING clause
Result<Record2<String, Integer>> result3 = create()
.select(TAuthor_LAST_NAME(), count)
.from(TBook())
.join(TAuthor()).on(TBook_AUTHOR_ID().equal(TAuthor_ID()))
.where(TBook_TITLE().notEqual("1984"))
.groupBy(TAuthor_LAST_NAME())
.having(count().equal(2))
.or(count().greaterOrEqual(2))
.andExists(selectOne())
.fetch();
assertEquals(1, result3.size());
assertEquals(2, (int) result3.getValue(0, count));
assertEquals("Coelho", result3.getValue(0, TAuthor_LAST_NAME()));
// Test a group by query with a plain SQL having clause
Result<Record2<String, Integer>> result4 = create()
.select(VLibrary_AUTHOR(), count)
.from(VLibrary())
.where(VLibrary_TITLE().notEqual("1984"))
.groupBy(VLibrary_AUTHOR())
// MySQL seems to have a bug with fully qualified view names in the
// having clause. TODO: Fully analyse this issue
// https://sourceforge.net/apps/trac/jooq/ticket/277
.having("v_library.author like ?", "Paulo%")
.fetch();
assertEquals(1, result4.size());
assertEquals(2, (int) result4.getValue(0, count));
// SQLite loses type information when views select functions.
// In this case: concatenation. So as a workaround, SQLlite only selects
// FIRST_NAME in the view
assertEquals("Paulo", result4.getValue(0, VLibrary_AUTHOR()).substring(0, 5));
}
@Test
public void testGroupByCubeRollup() throws Exception {
switch (dialect()) {
case ASE:
case DERBY:
case FIREBIRD:
case H2:
case HSQLDB:
case INGRES:
case POSTGRES:
case SQLITE:
log.info("SKIPPING", "Group by CUBE / ROLLUP tests");
return;
}
// Simple ROLLUP clause
// --------------------
Result<Record2<Integer, Integer>> result = create()
.select(
TBook_ID(),
TBook_AUTHOR_ID())
.from(TBook())
.groupBy(rollup(
TBook_ID(),
TBook_AUTHOR_ID()))
+ .orderBy(
+ TBook_ID().asc().nullsLast(),
+ TBook_AUTHOR_ID().asc().nullsLast())
.fetch();
- if (dialect() == DB2) {
- assertEquals(Arrays.asList(null, 1, 2, 3, 4, 1, 2, 3, 4), result.getValues(0));
- assertEquals(Arrays.asList(null, null, null, null, null, 1, 1, 2, 2), result.getValues(1));
- }
- else {
- assertEquals(Arrays.asList(1, 1, 2, 2, 3, 3, 4, 4, null), result.getValues(0));
- assertEquals(Arrays.asList(1, null, 1, null, 2, null, 2, null, null), result.getValues(1));
- }
+ assertEquals(Arrays.asList(1, 1, 2, 2, 3, 3, 4, 4, null), result.getValues(0));
+ assertEquals(Arrays.asList(1, null, 1, null, 2, null, 2, null, null), result.getValues(1));
if (asList(MARIADB, MYSQL).contains(dialect())) {
log.info("SKIPPING", "CUBE and GROUPING SETS tests");
return;
}
// ROLLUP clause
// -------------
Field<Integer> groupingId = groupingId(TBook_ID(), TBook_AUTHOR_ID());
if (asList(DB2, SYBASE).contains(dialect()))
groupingId = one();
Result<Record4<Integer, Integer, Integer, Integer>> result2 = create()
.select(
TBook_ID(),
TBook_AUTHOR_ID(),
grouping(TBook_ID()),
groupingId)
.from(TBook())
.groupBy(rollup(
TBook_ID(),
TBook_AUTHOR_ID()))
.orderBy(
TBook_ID().asc().nullsFirst(),
TBook_AUTHOR_ID().asc().nullsFirst()).fetch();
assertEquals(9, result2.size());
assertEquals(Arrays.asList(null, 1, 1, 2, 2, 3, 3, 4, 4), result2.getValues(0));
assertEquals(Arrays.asList(null, null, 1, null, 1, null, 2, null, 2), result2.getValues(1));
assertEquals(Arrays.asList(1, 0, 0, 0, 0, 0, 0, 0, 0), result2.getValues(2));
if (!asList(DB2, SYBASE).contains(dialect()))
assertEquals(Arrays.asList(3, 1, 0, 1, 0, 1, 0, 1, 0), result2.getValues(3));
// CUBE clause
// -----------
Result<Record4<Integer, Integer, Integer, Integer>> result3 = create().select(
TBook_ID(),
TBook_AUTHOR_ID(),
grouping(TBook_ID()),
groupingId)
.from(TBook())
.groupBy(cube(
TBook_ID(),
TBook_AUTHOR_ID()))
.orderBy(
TBook_ID().asc().nullsFirst(),
TBook_AUTHOR_ID().asc().nullsFirst()).fetch();
assertEquals(11, result3.size());
assertEquals(Arrays.asList(null, null, null, 1, 1, 2, 2, 3, 3, 4, 4), result3.getValues(0));
assertEquals(Arrays.asList(null, 1, 2, null, 1, null, 1, null, 2, null, 2), result3.getValues(1));
assertEquals(Arrays.asList(1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0), result3.getValues(2));
if (!asList(DB2, SYBASE).contains(dialect()))
assertEquals(Arrays.asList(3, 2, 2, 1, 0, 1, 0, 1, 0, 1, 0), result3.getValues(3));
// GROUPING SETS clause
// --------------------
Result<Record4<Integer, Integer, Integer, Integer>> result4 = create().select(
TBook_ID(),
TBook_AUTHOR_ID(),
grouping(TBook_ID()),
groupingId)
.from(TBook())
.groupBy(groupingSets(
new Field<?>[] { TBook_AUTHOR_ID(), TBook_ID() },
new Field<?>[] { TBook_AUTHOR_ID(), TBook_LANGUAGE_ID() },
new Field<?>[0],
new Field<?>[0]))
.orderBy(
TBook_ID().asc().nullsFirst(),
TBook_AUTHOR_ID().asc().nullsFirst()).fetch();
assertEquals(9, result4.size());
assertEquals(Arrays.asList(null, null, null, null, null, 1, 2, 3, 4), result4.getValues(0));
assertEquals(Arrays.asList(null, null, 1, 2, 2, 1, 1, 2, 2), result4.getValues(1));
assertEquals(Arrays.asList(1, 1, 1, 1, 1, 0, 0, 0, 0), result4.getValues(2));
if (!asList(DB2, SYBASE).contains(dialect()))
assertEquals(Arrays.asList(3, 3, 2, 2, 2, 0, 0, 0, 0), result4.getValues(3));
}
@Test
public void testHavingWithoutGrouping() throws Exception {
try {
assertEquals(Integer.valueOf(1), create()
.selectOne()
.from(TBook())
.where(TBook_AUTHOR_ID().equal(1))
.having(count().greaterOrEqual(2))
.fetchOne(0));
assertEquals(null, create()
.selectOne()
.from(TBook())
.where(TBook_AUTHOR_ID().equal(1))
.having(count().greaterOrEqual(3))
.fetchOne(0));
}
catch (DataAccessException e) {
// HAVING without GROUP BY is not supported by some dialects,
// So this exception is OK
switch (dialect()) {
// [#1665] TODO: Add support for the empty GROUP BY () clause
case SQLITE:
log.info("SKIPPING", "HAVING without GROUP BY is not supported: " + e.getMessage());
break;
default:
throw e;
}
}
}
}
| false | true | public void testGroupByCubeRollup() throws Exception {
switch (dialect()) {
case ASE:
case DERBY:
case FIREBIRD:
case H2:
case HSQLDB:
case INGRES:
case POSTGRES:
case SQLITE:
log.info("SKIPPING", "Group by CUBE / ROLLUP tests");
return;
}
// Simple ROLLUP clause
// --------------------
Result<Record2<Integer, Integer>> result = create()
.select(
TBook_ID(),
TBook_AUTHOR_ID())
.from(TBook())
.groupBy(rollup(
TBook_ID(),
TBook_AUTHOR_ID()))
.fetch();
if (dialect() == DB2) {
assertEquals(Arrays.asList(null, 1, 2, 3, 4, 1, 2, 3, 4), result.getValues(0));
assertEquals(Arrays.asList(null, null, null, null, null, 1, 1, 2, 2), result.getValues(1));
}
else {
assertEquals(Arrays.asList(1, 1, 2, 2, 3, 3, 4, 4, null), result.getValues(0));
assertEquals(Arrays.asList(1, null, 1, null, 2, null, 2, null, null), result.getValues(1));
}
if (asList(MARIADB, MYSQL).contains(dialect())) {
log.info("SKIPPING", "CUBE and GROUPING SETS tests");
return;
}
// ROLLUP clause
// -------------
Field<Integer> groupingId = groupingId(TBook_ID(), TBook_AUTHOR_ID());
if (asList(DB2, SYBASE).contains(dialect()))
groupingId = one();
Result<Record4<Integer, Integer, Integer, Integer>> result2 = create()
.select(
TBook_ID(),
TBook_AUTHOR_ID(),
grouping(TBook_ID()),
groupingId)
.from(TBook())
.groupBy(rollup(
TBook_ID(),
TBook_AUTHOR_ID()))
.orderBy(
TBook_ID().asc().nullsFirst(),
TBook_AUTHOR_ID().asc().nullsFirst()).fetch();
assertEquals(9, result2.size());
assertEquals(Arrays.asList(null, 1, 1, 2, 2, 3, 3, 4, 4), result2.getValues(0));
assertEquals(Arrays.asList(null, null, 1, null, 1, null, 2, null, 2), result2.getValues(1));
assertEquals(Arrays.asList(1, 0, 0, 0, 0, 0, 0, 0, 0), result2.getValues(2));
if (!asList(DB2, SYBASE).contains(dialect()))
assertEquals(Arrays.asList(3, 1, 0, 1, 0, 1, 0, 1, 0), result2.getValues(3));
// CUBE clause
// -----------
Result<Record4<Integer, Integer, Integer, Integer>> result3 = create().select(
TBook_ID(),
TBook_AUTHOR_ID(),
grouping(TBook_ID()),
groupingId)
.from(TBook())
.groupBy(cube(
TBook_ID(),
TBook_AUTHOR_ID()))
.orderBy(
TBook_ID().asc().nullsFirst(),
TBook_AUTHOR_ID().asc().nullsFirst()).fetch();
assertEquals(11, result3.size());
assertEquals(Arrays.asList(null, null, null, 1, 1, 2, 2, 3, 3, 4, 4), result3.getValues(0));
assertEquals(Arrays.asList(null, 1, 2, null, 1, null, 1, null, 2, null, 2), result3.getValues(1));
assertEquals(Arrays.asList(1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0), result3.getValues(2));
if (!asList(DB2, SYBASE).contains(dialect()))
assertEquals(Arrays.asList(3, 2, 2, 1, 0, 1, 0, 1, 0, 1, 0), result3.getValues(3));
// GROUPING SETS clause
// --------------------
Result<Record4<Integer, Integer, Integer, Integer>> result4 = create().select(
TBook_ID(),
TBook_AUTHOR_ID(),
grouping(TBook_ID()),
groupingId)
.from(TBook())
.groupBy(groupingSets(
new Field<?>[] { TBook_AUTHOR_ID(), TBook_ID() },
new Field<?>[] { TBook_AUTHOR_ID(), TBook_LANGUAGE_ID() },
new Field<?>[0],
new Field<?>[0]))
.orderBy(
TBook_ID().asc().nullsFirst(),
TBook_AUTHOR_ID().asc().nullsFirst()).fetch();
assertEquals(9, result4.size());
assertEquals(Arrays.asList(null, null, null, null, null, 1, 2, 3, 4), result4.getValues(0));
assertEquals(Arrays.asList(null, null, 1, 2, 2, 1, 1, 2, 2), result4.getValues(1));
assertEquals(Arrays.asList(1, 1, 1, 1, 1, 0, 0, 0, 0), result4.getValues(2));
if (!asList(DB2, SYBASE).contains(dialect()))
assertEquals(Arrays.asList(3, 3, 2, 2, 2, 0, 0, 0, 0), result4.getValues(3));
}
| public void testGroupByCubeRollup() throws Exception {
switch (dialect()) {
case ASE:
case DERBY:
case FIREBIRD:
case H2:
case HSQLDB:
case INGRES:
case POSTGRES:
case SQLITE:
log.info("SKIPPING", "Group by CUBE / ROLLUP tests");
return;
}
// Simple ROLLUP clause
// --------------------
Result<Record2<Integer, Integer>> result = create()
.select(
TBook_ID(),
TBook_AUTHOR_ID())
.from(TBook())
.groupBy(rollup(
TBook_ID(),
TBook_AUTHOR_ID()))
.orderBy(
TBook_ID().asc().nullsLast(),
TBook_AUTHOR_ID().asc().nullsLast())
.fetch();
assertEquals(Arrays.asList(1, 1, 2, 2, 3, 3, 4, 4, null), result.getValues(0));
assertEquals(Arrays.asList(1, null, 1, null, 2, null, 2, null, null), result.getValues(1));
if (asList(MARIADB, MYSQL).contains(dialect())) {
log.info("SKIPPING", "CUBE and GROUPING SETS tests");
return;
}
// ROLLUP clause
// -------------
Field<Integer> groupingId = groupingId(TBook_ID(), TBook_AUTHOR_ID());
if (asList(DB2, SYBASE).contains(dialect()))
groupingId = one();
Result<Record4<Integer, Integer, Integer, Integer>> result2 = create()
.select(
TBook_ID(),
TBook_AUTHOR_ID(),
grouping(TBook_ID()),
groupingId)
.from(TBook())
.groupBy(rollup(
TBook_ID(),
TBook_AUTHOR_ID()))
.orderBy(
TBook_ID().asc().nullsFirst(),
TBook_AUTHOR_ID().asc().nullsFirst()).fetch();
assertEquals(9, result2.size());
assertEquals(Arrays.asList(null, 1, 1, 2, 2, 3, 3, 4, 4), result2.getValues(0));
assertEquals(Arrays.asList(null, null, 1, null, 1, null, 2, null, 2), result2.getValues(1));
assertEquals(Arrays.asList(1, 0, 0, 0, 0, 0, 0, 0, 0), result2.getValues(2));
if (!asList(DB2, SYBASE).contains(dialect()))
assertEquals(Arrays.asList(3, 1, 0, 1, 0, 1, 0, 1, 0), result2.getValues(3));
// CUBE clause
// -----------
Result<Record4<Integer, Integer, Integer, Integer>> result3 = create().select(
TBook_ID(),
TBook_AUTHOR_ID(),
grouping(TBook_ID()),
groupingId)
.from(TBook())
.groupBy(cube(
TBook_ID(),
TBook_AUTHOR_ID()))
.orderBy(
TBook_ID().asc().nullsFirst(),
TBook_AUTHOR_ID().asc().nullsFirst()).fetch();
assertEquals(11, result3.size());
assertEquals(Arrays.asList(null, null, null, 1, 1, 2, 2, 3, 3, 4, 4), result3.getValues(0));
assertEquals(Arrays.asList(null, 1, 2, null, 1, null, 1, null, 2, null, 2), result3.getValues(1));
assertEquals(Arrays.asList(1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0), result3.getValues(2));
if (!asList(DB2, SYBASE).contains(dialect()))
assertEquals(Arrays.asList(3, 2, 2, 1, 0, 1, 0, 1, 0, 1, 0), result3.getValues(3));
// GROUPING SETS clause
// --------------------
Result<Record4<Integer, Integer, Integer, Integer>> result4 = create().select(
TBook_ID(),
TBook_AUTHOR_ID(),
grouping(TBook_ID()),
groupingId)
.from(TBook())
.groupBy(groupingSets(
new Field<?>[] { TBook_AUTHOR_ID(), TBook_ID() },
new Field<?>[] { TBook_AUTHOR_ID(), TBook_LANGUAGE_ID() },
new Field<?>[0],
new Field<?>[0]))
.orderBy(
TBook_ID().asc().nullsFirst(),
TBook_AUTHOR_ID().asc().nullsFirst()).fetch();
assertEquals(9, result4.size());
assertEquals(Arrays.asList(null, null, null, null, null, 1, 2, 3, 4), result4.getValues(0));
assertEquals(Arrays.asList(null, null, 1, 2, 2, 1, 1, 2, 2), result4.getValues(1));
assertEquals(Arrays.asList(1, 1, 1, 1, 1, 0, 0, 0, 0), result4.getValues(2));
if (!asList(DB2, SYBASE).contains(dialect()))
assertEquals(Arrays.asList(3, 3, 2, 2, 2, 0, 0, 0, 0), result4.getValues(3));
}
|
diff --git a/common/plugins/org.jboss.tools.common.validation/src/org/jboss/tools/common/validation/PreferenceInfoManager.java b/common/plugins/org.jboss.tools.common.validation/src/org/jboss/tools/common/validation/PreferenceInfoManager.java
index cfbb407a7..a123da842 100644
--- a/common/plugins/org.jboss.tools.common.validation/src/org/jboss/tools/common/validation/PreferenceInfoManager.java
+++ b/common/plugins/org.jboss.tools.common.validation/src/org/jboss/tools/common/validation/PreferenceInfoManager.java
@@ -1,45 +1,48 @@
/*******************************************************************************
* Copyright (c) 2012 Red Hat, Inc.
* Distributed under license by Red Hat, Inc. All rights reserved.
* This program is 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
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
******************************************************************************/
package org.jboss.tools.common.validation;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* Preference Info Manager store info from validators and returns it to Quick fixes
* @author Daniel Azarov
*/
public class PreferenceInfoManager {
private static Map<String, IPreferenceInfo> infos = Collections.synchronizedMap(new HashMap<String, IPreferenceInfo>());
/*
* register IPreferenceInfo for problemType
* this method is designed to be called from validator
*/
public static void register(String problemType, IPreferenceInfo info){
if(!infos.containsKey(problemType)){
infos.put(problemType, info);
}
}
/*
* returns IPreferenceInfo for problemType
*/
public static IPreferenceInfo getPreferenceInfo(String problemType){
+ if(problemType == null){
+ problemType = ValidationErrorManager.DEFAULT_VALIDATION_MARKER;
+ }
IPreferenceInfo info = infos.get(problemType);
if(info == null){
ValidationContext.loadValidatorByProblemType(problemType);
info = infos.get(problemType);
}
return info;
}
}
| true | true | public static IPreferenceInfo getPreferenceInfo(String problemType){
IPreferenceInfo info = infos.get(problemType);
if(info == null){
ValidationContext.loadValidatorByProblemType(problemType);
info = infos.get(problemType);
}
return info;
}
| public static IPreferenceInfo getPreferenceInfo(String problemType){
if(problemType == null){
problemType = ValidationErrorManager.DEFAULT_VALIDATION_MARKER;
}
IPreferenceInfo info = infos.get(problemType);
if(info == null){
ValidationContext.loadValidatorByProblemType(problemType);
info = infos.get(problemType);
}
return info;
}
|
diff --git a/src/com/modcrafting/identify/commands/IdentifyCommand.java b/src/com/modcrafting/identify/commands/IdentifyCommand.java
index 05b291e..2ad737d 100644
--- a/src/com/modcrafting/identify/commands/IdentifyCommand.java
+++ b/src/com/modcrafting/identify/commands/IdentifyCommand.java
@@ -1,373 +1,374 @@
package com.modcrafting.identify.commands;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import com.modcrafting.diablodrops.items.Socket;
import com.modcrafting.identify.Identify;
/*
*
*/
public class IdentifyCommand implements CommandExecutor {
Identify plugin;
public IdentifyCommand(Identify identify) {
this.plugin = identify;
}
@SuppressWarnings("deprecation")
@Override
public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) {
if (!hasPerms(sender,command.getPermission()))
return true;
Player player = null;
if (sender instanceof Player){
player = (Player)sender;
}
if(args.length<1) return false;
if(args[0].equalsIgnoreCase("list")&&hasPerms(sender,"identify.list")){
if(args.length < 2){
showList(player);
return true;
}
if(args[1].equalsIgnoreCase("dd")&&plugin.getDiabloDrops()!=null){
//TODO: DD daily list.
//TODO: DD Tier list.
//TODO: DD Custom buy.
return true;
}
return true;
}
if(args[0].equalsIgnoreCase("buy")){
if (!hasPerms(sender,"identify.buy"))
return true;
double bal = plugin.economy.getBalance(sender.getName());
if(args.length<2){
if(plugin.getDiabloDrops()!=null){
sender.sendMessage(ChatColor.GRAY+" /identify buy <dd|tier|tome|gem|name|enchant|lore|random>");
return true;
}
return false;
}
if((args[1].equalsIgnoreCase("diablodrop")||args[1].equalsIgnoreCase("dd"))
&&plugin.getDiabloDrops()!=null){
if(!plugin.ddConfig.getBoolean("DiabloDrop.Random.Enabled",true)) return true;
double price = plugin.ddConfig.getDouble("DiabloDrop.Random.Price", 1000);
if(price > bal){
sender.sendMessage(ChatColor.DARK_AQUA + "Your don't have enough money!");
return true;
}else{
ItemStack item = plugin.getDiabloDrops().dropsAPI.getItem();
while(item==null)
item = plugin.getDiabloDrops().dropsAPI.getItem();
String name = null;
if(item.hasItemMeta()){
name = item.getItemMeta().getDisplayName();
}
player.getInventory().addItem(item);
player.updateInventory();
plugin.economy.withdrawPlayer(sender.getName(), Math.abs(price));
sender.sendMessage(ChatColor.DARK_AQUA + "You were charged: " + ChatColor.BLUE + String.valueOf(price));
sender.sendMessage(ChatColor.GOLD+"[DiabloDrops]"
+ChatColor.GRAY + "For: " + name);
return true;
}
}
if(args[1].equalsIgnoreCase("tier")&&plugin.getDiabloDrops()!=null){
for(com.modcrafting.diablodrops.tier.Tier tier:plugin.getDiabloDrops().tiers){
if(args[2].equalsIgnoreCase(tier.getName())&&plugin.ddConfig.getBoolean("DiabloDrop.Tier.Enabled",true)){
double price = plugin.ddConfig.getDouble("DiabloDrop."+tier.getName()+".Price", 1000);
if(price > bal){
sender.sendMessage(ChatColor.DARK_AQUA + "Your don't have enough money!");
return true;
}
ItemStack item = plugin.getDiabloDrops().dropsAPI.getItem();
while(item==null)
item = plugin.getDiabloDrops().dropsAPI.getItem();
String name = null;
if(item.hasItemMeta()){
name = item.getItemMeta().getDisplayName();
}
player.getInventory().addItem(item);
player.updateInventory();
plugin.economy.withdrawPlayer(sender.getName(), Math.abs(price));
sender.sendMessage(ChatColor.DARK_AQUA + "You were charged: " + ChatColor.BLUE + String.valueOf(price));
sender.sendMessage(ChatColor.GOLD+"[DiabloDrops]"
+ChatColor.GRAY + "For: " + name);
return true;
}
}
sender.sendMessage(ChatColor.GOLD+"[DiabloDrops]"
+ChatColor.GRAY+" Tier: "+args[2]+" not found.");
return true;
}
if(args[1].equalsIgnoreCase("tome")&&plugin.getDiabloDrops()!=null){
if(!plugin.ddConfig.getBoolean("DiabloDrop.Tome.Enabled",true)) return true;
double price = plugin.ddConfig.getDouble("DiabloDrop.Tome.Price", 1000);
if(price > bal){
sender.sendMessage(ChatColor.DARK_AQUA + "Your don't have enough money!");
return true;
}
com.modcrafting.diablodrops.items.IdentifyTome tome = new com.modcrafting.diablodrops.items.IdentifyTome();
player.getInventory().addItem(tome);
player.updateInventory();
plugin.economy.withdrawPlayer(sender.getName(), Math.abs(price));
sender.sendMessage(ChatColor.DARK_AQUA + "You were charged: " + ChatColor.BLUE + String.valueOf(price));
sender.sendMessage(ChatColor.GOLD+"[DiabloDrops]"
+ChatColor.GRAY + "For An Identification Tome. ");
return true;
}
if(args[1].equalsIgnoreCase("gem")&&plugin.getDiabloDrops()!=null){
if(!plugin.ddConfig.getBoolean("DiabloDrop.SocketGem.Enabled",true)) return true;
double price = plugin.ddConfig.getDouble("DiabloDrop.SocketGem.Price", 1000);
if(price > bal){
sender.sendMessage(ChatColor.DARK_AQUA + "Your don't have enough money!");
return true;
}
List<String> l = plugin.getDiabloDrops().config.getStringList("SocketItem.Items");
com.modcrafting.diablodrops.items.Socket tome = new Socket(Material.valueOf(l.get(
plugin.getDiabloDrops().gen.nextInt(l.size())).toUpperCase()));
player.getInventory().addItem(tome);
player.updateInventory();
plugin.economy.withdrawPlayer(sender.getName(), Math.abs(price));
sender.sendMessage(ChatColor.DARK_AQUA + "You were charged: " + ChatColor.BLUE + String.valueOf(price));
sender.sendMessage(ChatColor.GOLD+"[DiabloDrops]"
+ChatColor.GRAY + "For An Socket Gem. ");
return true;
}
if(args[1].equalsIgnoreCase("name")
&&plugin.getConfig().getBoolean("Name.Enabled",true)
&&hasPerms(sender,"identify.buy.name")){
double price = 1000;
String name = combineSplit(2, args, " ");
name = ChatColor.translateAlternateColorCodes('&', name);
ItemStack item = player.getItemInHand();
if (item==null||item.getType() == Material.AIR){
sender.sendMessage(ChatColor.DARK_AQUA + "Your Not Holding Anything.");
return true;
}
if(plugin.getConfig().getBoolean("Name.Flat",true)){
price = plugin.ddConfig.getDouble("Name.FlatRate", 1000);
if(price > bal){
sender.sendMessage(ChatColor.DARK_AQUA + "Your don't have enough money!");
sender.sendMessage(ChatColor.BLUE + "Name Cost: "+String.valueOf(price));
return true;
}
plugin.economy.withdrawPlayer(sender.getName(), Math.abs(price));
}else{
price = plugin.ddConfig.getDouble("Name.PerLetter", 10);
price = price*name.length();
if(price > bal){
sender.sendMessage(ChatColor.DARK_AQUA + "Your don't have enough money!");
sender.sendMessage(ChatColor.BLUE + "Name Cost: "+String.valueOf(price));
return true;
}
plugin.economy.withdrawPlayer(sender.getName(), Math.abs(price));
}
ItemMeta meta = item.getItemMeta();
meta.setDisplayName(name);
item.setItemMeta(meta);
sender.sendMessage(ChatColor.GRAY+" Name: "+name+ChatColor.GRAY+" was set for "+ChatColor.GOLD+String.valueOf(price));
return true;
}
if(args[1].equalsIgnoreCase("lore")
&&plugin.getConfig().getBoolean("Lore.Enabled",true)
&&hasPerms(sender,"identify.buy.lore")){
if(plugin.getDiabloDrops()!=null&&!sender.hasPermission("identify.override.lore")){
sender.sendMessage(ChatColor.GOLD+"[DiabloDrops]"+ChatColor.GRAY+"Option disabled.");
return true;
}
double price = 1000;
String lore = combineSplit(2, args, " ");
lore = ChatColor.translateAlternateColorCodes(
"&".toCharArray()[0], lore);
if(!plugin.ddConfig.getBoolean("Lore.PerLetterLine",false)){
price = plugin.ddConfig.getDouble("Lore.FlatRatePerLine", 1000);
price = lore.split(",").length*price;
if(price > bal){
sender.sendMessage(ChatColor.DARK_AQUA + "Your don't have enough money!");
sender.sendMessage(ChatColor.BLUE + "Lore Cost: "+String.valueOf(price));
return true;
}
plugin.economy.withdrawPlayer(sender.getName(), Math.abs(price));
}else{
price = plugin.ddConfig.getDouble("Lore.PerRate", 10);
price = lore.length()*price;
if(price > bal){
sender.sendMessage(ChatColor.DARK_AQUA + "Your don't have enough money!");
sender.sendMessage(ChatColor.BLUE + "Lore Cost: "+String.valueOf(price));
return true;
}
plugin.economy.withdrawPlayer(sender.getName(), Math.abs(price));
}
ItemStack item = player.getItemInHand();
List<String> list = new ArrayList<String>();
for (String s : lore.split(","))
{
if (s.length() > 0)
list.add(s);
}
ItemMeta m = item.getItemMeta();
m.setLore(list);
+ item.setItemMeta(m);
sender.sendMessage(ChatColor.DARK_AQUA + "You were charged: " + ChatColor.BLUE + String.valueOf(price));
for(String s:list){
if (s.length() > 0)
sender.sendMessage(s);
}
sender.sendMessage(ChatColor.DARK_AQUA + "Lore Set.");
return true;
}
if(args[1].equalsIgnoreCase("random")&&hasPerms(sender,"identify.buy.random")){
ItemStack item = player.getItemInHand();
if(item.hasItemMeta()){
ItemMeta meta = item.getItemMeta();
if(meta.getDisplayName().contains(new Character((char) 167).toString())
|| item.getEnchantments().size()>0){
sender.sendMessage(ChatColor.AQUA+"You are unable to enchant this.");
return true;
}
}
plugin.buy.buyRandom(player);
return true;
}
if(args[1].equalsIgnoreCase("enchant")&&args.length>2&&hasPerms(sender,"identify.buy.enchant")){
ItemStack item = player.getItemInHand();
if(item.hasItemMeta()){
ItemMeta meta = item.getItemMeta();
if(meta.getDisplayName()!=null
&&meta.getDisplayName().contains(new Character((char) 167).toString())){
sender.sendMessage(ChatColor.AQUA+"You are unable to enchant this.");
return true;
}
}
plugin.buy.buyList(player, args);
return true;
}
}
if(args[0].equalsIgnoreCase("repair")
&&plugin.getConfig().getBoolean("Repair.Enabled",true)
&&hasPerms(sender,"identify.repair")){
double bal = plugin.economy.getBalance(sender.getName());
double price = 1000;
ItemStack item = player.getItemInHand();
if (item==null||item.getType() == Material.AIR){
sender.sendMessage(ChatColor.DARK_AQUA + "Your Not Holding Anything.");
return true;
}
if(plugin.getConfig().getBoolean("Repair.Flat",true)){
price = plugin.ddConfig.getDouble("Repair.FlatRate", 1000);
if(price > bal){
sender.sendMessage(ChatColor.DARK_AQUA + "Your don't have enough money!");
sender.sendMessage(ChatColor.BLUE + "Repair Cost: "+String.valueOf(price));
return true;
}
plugin.economy.withdrawPlayer(sender.getName(), Math.abs(price));
}else{
price = plugin.ddConfig.getDouble("Repair.PriceVsDamage", 10);
price = price*item.getDurability();
if(price > bal){
sender.sendMessage(ChatColor.DARK_AQUA + "Your don't have enough money!");
sender.sendMessage(ChatColor.BLUE + "Repair Cost: "+String.valueOf(price));
return true;
}
plugin.economy.withdrawPlayer(sender.getName(), Math.abs(price));
}
item.setDurability((short)0);
sender.sendMessage(ChatColor.GRAY+" Your "+item.getType().toString()+ChatColor.GRAY+" was repaired for "+ChatColor.GOLD+String.valueOf(price));
return true;
}
if(args[0].equalsIgnoreCase("help")){
showHelp(player);
return true;
}
if(args[0].equalsIgnoreCase("reload")&&hasPerms(sender,"identify.reload")){
plugin.getServer().getPluginManager().disablePlugin(plugin);
plugin.getServer().getPluginManager().enablePlugin(plugin);
plugin.reloadConfig();
sender.sendMessage(ChatColor.GREEN+"Reloaded Identify.");
return true;
}
if(args[0].equalsIgnoreCase("clear")&&hasPerms(sender,"identify.clear")){
ItemStack it = player.getItemInHand();
Material mat = it.getType();
short dam = it.getDurability();
ItemStack its = new ItemStack(mat,1,dam);
player.setItemInHand(its);
sender.sendMessage(ChatColor.DARK_AQUA+"Item cleared");
return true;
}
return false;
}
public boolean showHelp(Player sender) {
sender.sendMessage(ChatColor.DARK_AQUA + "Identify Help");
sender.sendMessage(ChatColor.DARK_AQUA + "-----------------------------------------");
sender.sendMessage(ChatColor.DARK_AQUA + "/identify <Buy/List/Reload/Clear/Help>");
if(plugin.getDiabloDrops()!=null){
sender.sendMessage(ChatColor.DARK_AQUA + "/identify buy <DD/Tier/Name/Enchant/Lore/Random>");
}else{
sender.sendMessage(ChatColor.DARK_AQUA + "/identify buy <Name/Enchant/Lore/Random>");
}
sender.sendMessage(ChatColor.DARK_AQUA + "/Identify buy enchant {ID#/Name} (level/MAX)");
sender.sendMessage(ChatColor.DARK_AQUA + "/Identify buy name &7AwezomeSword");
sender.sendMessage(ChatColor.DARK_AQUA + "/Identify buy lore &7Enter text here,&bseperated by comma");
sender.sendMessage(ChatColor.DARK_AQUA + "/identify list");
sender.sendMessage(ChatColor.DARK_AQUA + "/identify reload");
return true;
}
public void showList(Player sender){
ItemStack item = sender.getItemInHand();
String itemName = item.getType().toString();
sender.sendMessage(ChatColor.DARK_AQUA + "Identify Shop {Current Item: " + itemName + " }");
sender.sendMessage(ChatColor.DARK_AQUA + "-----------------------------------------");
sender.sendMessage(ChatColor.GOLD + "For a random enchantment type /identify buy random");
sender.sendMessage(ChatColor.GOLD + "Use /identify buy enchant [id# or name] [lvl]");
for(int i=0;i<Enchantment.values().length;i++){
Enchantment e = Enchantment.values()[i];
if(e.canEnchantItem(item)){
sender.sendMessage(ChatColor.BLUE + "ID#"+String.valueOf(EnchantUtil.getID(e))+" "+e.getName()+" +1");
}
}
}
public boolean hasPerms(CommandSender sender,String string){
if (!sender.hasPermission(string)){
sender.sendMessage(ChatColor.RED + "You do not have the required permissions.");
return false;
}
return true;
}
public String combineSplit(int startIndex, String[] string, String seperator)
{
StringBuilder builder = new StringBuilder();
if (string.length >= 1)
{
for (int i = startIndex; i < string.length; i++)
{
builder.append(string[i]);
builder.append(seperator);
}
if (builder.length() > seperator.length())
{
builder.deleteCharAt(builder.length() - seperator.length()); // remove
return builder.toString();
}
}
return "";
}
}
| true | true | public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) {
if (!hasPerms(sender,command.getPermission()))
return true;
Player player = null;
if (sender instanceof Player){
player = (Player)sender;
}
if(args.length<1) return false;
if(args[0].equalsIgnoreCase("list")&&hasPerms(sender,"identify.list")){
if(args.length < 2){
showList(player);
return true;
}
if(args[1].equalsIgnoreCase("dd")&&plugin.getDiabloDrops()!=null){
//TODO: DD daily list.
//TODO: DD Tier list.
//TODO: DD Custom buy.
return true;
}
return true;
}
if(args[0].equalsIgnoreCase("buy")){
if (!hasPerms(sender,"identify.buy"))
return true;
double bal = plugin.economy.getBalance(sender.getName());
if(args.length<2){
if(plugin.getDiabloDrops()!=null){
sender.sendMessage(ChatColor.GRAY+" /identify buy <dd|tier|tome|gem|name|enchant|lore|random>");
return true;
}
return false;
}
if((args[1].equalsIgnoreCase("diablodrop")||args[1].equalsIgnoreCase("dd"))
&&plugin.getDiabloDrops()!=null){
if(!plugin.ddConfig.getBoolean("DiabloDrop.Random.Enabled",true)) return true;
double price = plugin.ddConfig.getDouble("DiabloDrop.Random.Price", 1000);
if(price > bal){
sender.sendMessage(ChatColor.DARK_AQUA + "Your don't have enough money!");
return true;
}else{
ItemStack item = plugin.getDiabloDrops().dropsAPI.getItem();
while(item==null)
item = plugin.getDiabloDrops().dropsAPI.getItem();
String name = null;
if(item.hasItemMeta()){
name = item.getItemMeta().getDisplayName();
}
player.getInventory().addItem(item);
player.updateInventory();
plugin.economy.withdrawPlayer(sender.getName(), Math.abs(price));
sender.sendMessage(ChatColor.DARK_AQUA + "You were charged: " + ChatColor.BLUE + String.valueOf(price));
sender.sendMessage(ChatColor.GOLD+"[DiabloDrops]"
+ChatColor.GRAY + "For: " + name);
return true;
}
}
if(args[1].equalsIgnoreCase("tier")&&plugin.getDiabloDrops()!=null){
for(com.modcrafting.diablodrops.tier.Tier tier:plugin.getDiabloDrops().tiers){
if(args[2].equalsIgnoreCase(tier.getName())&&plugin.ddConfig.getBoolean("DiabloDrop.Tier.Enabled",true)){
double price = plugin.ddConfig.getDouble("DiabloDrop."+tier.getName()+".Price", 1000);
if(price > bal){
sender.sendMessage(ChatColor.DARK_AQUA + "Your don't have enough money!");
return true;
}
ItemStack item = plugin.getDiabloDrops().dropsAPI.getItem();
while(item==null)
item = plugin.getDiabloDrops().dropsAPI.getItem();
String name = null;
if(item.hasItemMeta()){
name = item.getItemMeta().getDisplayName();
}
player.getInventory().addItem(item);
player.updateInventory();
plugin.economy.withdrawPlayer(sender.getName(), Math.abs(price));
sender.sendMessage(ChatColor.DARK_AQUA + "You were charged: " + ChatColor.BLUE + String.valueOf(price));
sender.sendMessage(ChatColor.GOLD+"[DiabloDrops]"
+ChatColor.GRAY + "For: " + name);
return true;
}
}
sender.sendMessage(ChatColor.GOLD+"[DiabloDrops]"
+ChatColor.GRAY+" Tier: "+args[2]+" not found.");
return true;
}
if(args[1].equalsIgnoreCase("tome")&&plugin.getDiabloDrops()!=null){
if(!plugin.ddConfig.getBoolean("DiabloDrop.Tome.Enabled",true)) return true;
double price = plugin.ddConfig.getDouble("DiabloDrop.Tome.Price", 1000);
if(price > bal){
sender.sendMessage(ChatColor.DARK_AQUA + "Your don't have enough money!");
return true;
}
com.modcrafting.diablodrops.items.IdentifyTome tome = new com.modcrafting.diablodrops.items.IdentifyTome();
player.getInventory().addItem(tome);
player.updateInventory();
plugin.economy.withdrawPlayer(sender.getName(), Math.abs(price));
sender.sendMessage(ChatColor.DARK_AQUA + "You were charged: " + ChatColor.BLUE + String.valueOf(price));
sender.sendMessage(ChatColor.GOLD+"[DiabloDrops]"
+ChatColor.GRAY + "For An Identification Tome. ");
return true;
}
if(args[1].equalsIgnoreCase("gem")&&plugin.getDiabloDrops()!=null){
if(!plugin.ddConfig.getBoolean("DiabloDrop.SocketGem.Enabled",true)) return true;
double price = plugin.ddConfig.getDouble("DiabloDrop.SocketGem.Price", 1000);
if(price > bal){
sender.sendMessage(ChatColor.DARK_AQUA + "Your don't have enough money!");
return true;
}
List<String> l = plugin.getDiabloDrops().config.getStringList("SocketItem.Items");
com.modcrafting.diablodrops.items.Socket tome = new Socket(Material.valueOf(l.get(
plugin.getDiabloDrops().gen.nextInt(l.size())).toUpperCase()));
player.getInventory().addItem(tome);
player.updateInventory();
plugin.economy.withdrawPlayer(sender.getName(), Math.abs(price));
sender.sendMessage(ChatColor.DARK_AQUA + "You were charged: " + ChatColor.BLUE + String.valueOf(price));
sender.sendMessage(ChatColor.GOLD+"[DiabloDrops]"
+ChatColor.GRAY + "For An Socket Gem. ");
return true;
}
if(args[1].equalsIgnoreCase("name")
&&plugin.getConfig().getBoolean("Name.Enabled",true)
&&hasPerms(sender,"identify.buy.name")){
double price = 1000;
String name = combineSplit(2, args, " ");
name = ChatColor.translateAlternateColorCodes('&', name);
ItemStack item = player.getItemInHand();
if (item==null||item.getType() == Material.AIR){
sender.sendMessage(ChatColor.DARK_AQUA + "Your Not Holding Anything.");
return true;
}
if(plugin.getConfig().getBoolean("Name.Flat",true)){
price = plugin.ddConfig.getDouble("Name.FlatRate", 1000);
if(price > bal){
sender.sendMessage(ChatColor.DARK_AQUA + "Your don't have enough money!");
sender.sendMessage(ChatColor.BLUE + "Name Cost: "+String.valueOf(price));
return true;
}
plugin.economy.withdrawPlayer(sender.getName(), Math.abs(price));
}else{
price = plugin.ddConfig.getDouble("Name.PerLetter", 10);
price = price*name.length();
if(price > bal){
sender.sendMessage(ChatColor.DARK_AQUA + "Your don't have enough money!");
sender.sendMessage(ChatColor.BLUE + "Name Cost: "+String.valueOf(price));
return true;
}
plugin.economy.withdrawPlayer(sender.getName(), Math.abs(price));
}
ItemMeta meta = item.getItemMeta();
meta.setDisplayName(name);
item.setItemMeta(meta);
sender.sendMessage(ChatColor.GRAY+" Name: "+name+ChatColor.GRAY+" was set for "+ChatColor.GOLD+String.valueOf(price));
return true;
}
if(args[1].equalsIgnoreCase("lore")
&&plugin.getConfig().getBoolean("Lore.Enabled",true)
&&hasPerms(sender,"identify.buy.lore")){
if(plugin.getDiabloDrops()!=null&&!sender.hasPermission("identify.override.lore")){
sender.sendMessage(ChatColor.GOLD+"[DiabloDrops]"+ChatColor.GRAY+"Option disabled.");
return true;
}
double price = 1000;
String lore = combineSplit(2, args, " ");
lore = ChatColor.translateAlternateColorCodes(
"&".toCharArray()[0], lore);
if(!plugin.ddConfig.getBoolean("Lore.PerLetterLine",false)){
price = plugin.ddConfig.getDouble("Lore.FlatRatePerLine", 1000);
price = lore.split(",").length*price;
if(price > bal){
sender.sendMessage(ChatColor.DARK_AQUA + "Your don't have enough money!");
sender.sendMessage(ChatColor.BLUE + "Lore Cost: "+String.valueOf(price));
return true;
}
plugin.economy.withdrawPlayer(sender.getName(), Math.abs(price));
}else{
price = plugin.ddConfig.getDouble("Lore.PerRate", 10);
price = lore.length()*price;
if(price > bal){
sender.sendMessage(ChatColor.DARK_AQUA + "Your don't have enough money!");
sender.sendMessage(ChatColor.BLUE + "Lore Cost: "+String.valueOf(price));
return true;
}
plugin.economy.withdrawPlayer(sender.getName(), Math.abs(price));
}
ItemStack item = player.getItemInHand();
List<String> list = new ArrayList<String>();
for (String s : lore.split(","))
{
if (s.length() > 0)
list.add(s);
}
ItemMeta m = item.getItemMeta();
m.setLore(list);
sender.sendMessage(ChatColor.DARK_AQUA + "You were charged: " + ChatColor.BLUE + String.valueOf(price));
for(String s:list){
if (s.length() > 0)
sender.sendMessage(s);
}
sender.sendMessage(ChatColor.DARK_AQUA + "Lore Set.");
return true;
}
if(args[1].equalsIgnoreCase("random")&&hasPerms(sender,"identify.buy.random")){
ItemStack item = player.getItemInHand();
if(item.hasItemMeta()){
ItemMeta meta = item.getItemMeta();
if(meta.getDisplayName().contains(new Character((char) 167).toString())
|| item.getEnchantments().size()>0){
sender.sendMessage(ChatColor.AQUA+"You are unable to enchant this.");
return true;
}
}
plugin.buy.buyRandom(player);
return true;
}
if(args[1].equalsIgnoreCase("enchant")&&args.length>2&&hasPerms(sender,"identify.buy.enchant")){
ItemStack item = player.getItemInHand();
if(item.hasItemMeta()){
ItemMeta meta = item.getItemMeta();
if(meta.getDisplayName()!=null
&&meta.getDisplayName().contains(new Character((char) 167).toString())){
sender.sendMessage(ChatColor.AQUA+"You are unable to enchant this.");
return true;
}
}
plugin.buy.buyList(player, args);
return true;
}
}
if(args[0].equalsIgnoreCase("repair")
&&plugin.getConfig().getBoolean("Repair.Enabled",true)
&&hasPerms(sender,"identify.repair")){
double bal = plugin.economy.getBalance(sender.getName());
double price = 1000;
ItemStack item = player.getItemInHand();
if (item==null||item.getType() == Material.AIR){
sender.sendMessage(ChatColor.DARK_AQUA + "Your Not Holding Anything.");
return true;
}
if(plugin.getConfig().getBoolean("Repair.Flat",true)){
price = plugin.ddConfig.getDouble("Repair.FlatRate", 1000);
if(price > bal){
sender.sendMessage(ChatColor.DARK_AQUA + "Your don't have enough money!");
sender.sendMessage(ChatColor.BLUE + "Repair Cost: "+String.valueOf(price));
return true;
}
plugin.economy.withdrawPlayer(sender.getName(), Math.abs(price));
}else{
price = plugin.ddConfig.getDouble("Repair.PriceVsDamage", 10);
price = price*item.getDurability();
if(price > bal){
sender.sendMessage(ChatColor.DARK_AQUA + "Your don't have enough money!");
sender.sendMessage(ChatColor.BLUE + "Repair Cost: "+String.valueOf(price));
return true;
}
plugin.economy.withdrawPlayer(sender.getName(), Math.abs(price));
}
item.setDurability((short)0);
sender.sendMessage(ChatColor.GRAY+" Your "+item.getType().toString()+ChatColor.GRAY+" was repaired for "+ChatColor.GOLD+String.valueOf(price));
return true;
}
if(args[0].equalsIgnoreCase("help")){
showHelp(player);
return true;
}
if(args[0].equalsIgnoreCase("reload")&&hasPerms(sender,"identify.reload")){
plugin.getServer().getPluginManager().disablePlugin(plugin);
plugin.getServer().getPluginManager().enablePlugin(plugin);
plugin.reloadConfig();
sender.sendMessage(ChatColor.GREEN+"Reloaded Identify.");
return true;
}
if(args[0].equalsIgnoreCase("clear")&&hasPerms(sender,"identify.clear")){
ItemStack it = player.getItemInHand();
Material mat = it.getType();
short dam = it.getDurability();
ItemStack its = new ItemStack(mat,1,dam);
player.setItemInHand(its);
sender.sendMessage(ChatColor.DARK_AQUA+"Item cleared");
return true;
}
return false;
}
| public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) {
if (!hasPerms(sender,command.getPermission()))
return true;
Player player = null;
if (sender instanceof Player){
player = (Player)sender;
}
if(args.length<1) return false;
if(args[0].equalsIgnoreCase("list")&&hasPerms(sender,"identify.list")){
if(args.length < 2){
showList(player);
return true;
}
if(args[1].equalsIgnoreCase("dd")&&plugin.getDiabloDrops()!=null){
//TODO: DD daily list.
//TODO: DD Tier list.
//TODO: DD Custom buy.
return true;
}
return true;
}
if(args[0].equalsIgnoreCase("buy")){
if (!hasPerms(sender,"identify.buy"))
return true;
double bal = plugin.economy.getBalance(sender.getName());
if(args.length<2){
if(plugin.getDiabloDrops()!=null){
sender.sendMessage(ChatColor.GRAY+" /identify buy <dd|tier|tome|gem|name|enchant|lore|random>");
return true;
}
return false;
}
if((args[1].equalsIgnoreCase("diablodrop")||args[1].equalsIgnoreCase("dd"))
&&plugin.getDiabloDrops()!=null){
if(!plugin.ddConfig.getBoolean("DiabloDrop.Random.Enabled",true)) return true;
double price = plugin.ddConfig.getDouble("DiabloDrop.Random.Price", 1000);
if(price > bal){
sender.sendMessage(ChatColor.DARK_AQUA + "Your don't have enough money!");
return true;
}else{
ItemStack item = plugin.getDiabloDrops().dropsAPI.getItem();
while(item==null)
item = plugin.getDiabloDrops().dropsAPI.getItem();
String name = null;
if(item.hasItemMeta()){
name = item.getItemMeta().getDisplayName();
}
player.getInventory().addItem(item);
player.updateInventory();
plugin.economy.withdrawPlayer(sender.getName(), Math.abs(price));
sender.sendMessage(ChatColor.DARK_AQUA + "You were charged: " + ChatColor.BLUE + String.valueOf(price));
sender.sendMessage(ChatColor.GOLD+"[DiabloDrops]"
+ChatColor.GRAY + "For: " + name);
return true;
}
}
if(args[1].equalsIgnoreCase("tier")&&plugin.getDiabloDrops()!=null){
for(com.modcrafting.diablodrops.tier.Tier tier:plugin.getDiabloDrops().tiers){
if(args[2].equalsIgnoreCase(tier.getName())&&plugin.ddConfig.getBoolean("DiabloDrop.Tier.Enabled",true)){
double price = plugin.ddConfig.getDouble("DiabloDrop."+tier.getName()+".Price", 1000);
if(price > bal){
sender.sendMessage(ChatColor.DARK_AQUA + "Your don't have enough money!");
return true;
}
ItemStack item = plugin.getDiabloDrops().dropsAPI.getItem();
while(item==null)
item = plugin.getDiabloDrops().dropsAPI.getItem();
String name = null;
if(item.hasItemMeta()){
name = item.getItemMeta().getDisplayName();
}
player.getInventory().addItem(item);
player.updateInventory();
plugin.economy.withdrawPlayer(sender.getName(), Math.abs(price));
sender.sendMessage(ChatColor.DARK_AQUA + "You were charged: " + ChatColor.BLUE + String.valueOf(price));
sender.sendMessage(ChatColor.GOLD+"[DiabloDrops]"
+ChatColor.GRAY + "For: " + name);
return true;
}
}
sender.sendMessage(ChatColor.GOLD+"[DiabloDrops]"
+ChatColor.GRAY+" Tier: "+args[2]+" not found.");
return true;
}
if(args[1].equalsIgnoreCase("tome")&&plugin.getDiabloDrops()!=null){
if(!plugin.ddConfig.getBoolean("DiabloDrop.Tome.Enabled",true)) return true;
double price = plugin.ddConfig.getDouble("DiabloDrop.Tome.Price", 1000);
if(price > bal){
sender.sendMessage(ChatColor.DARK_AQUA + "Your don't have enough money!");
return true;
}
com.modcrafting.diablodrops.items.IdentifyTome tome = new com.modcrafting.diablodrops.items.IdentifyTome();
player.getInventory().addItem(tome);
player.updateInventory();
plugin.economy.withdrawPlayer(sender.getName(), Math.abs(price));
sender.sendMessage(ChatColor.DARK_AQUA + "You were charged: " + ChatColor.BLUE + String.valueOf(price));
sender.sendMessage(ChatColor.GOLD+"[DiabloDrops]"
+ChatColor.GRAY + "For An Identification Tome. ");
return true;
}
if(args[1].equalsIgnoreCase("gem")&&plugin.getDiabloDrops()!=null){
if(!plugin.ddConfig.getBoolean("DiabloDrop.SocketGem.Enabled",true)) return true;
double price = plugin.ddConfig.getDouble("DiabloDrop.SocketGem.Price", 1000);
if(price > bal){
sender.sendMessage(ChatColor.DARK_AQUA + "Your don't have enough money!");
return true;
}
List<String> l = plugin.getDiabloDrops().config.getStringList("SocketItem.Items");
com.modcrafting.diablodrops.items.Socket tome = new Socket(Material.valueOf(l.get(
plugin.getDiabloDrops().gen.nextInt(l.size())).toUpperCase()));
player.getInventory().addItem(tome);
player.updateInventory();
plugin.economy.withdrawPlayer(sender.getName(), Math.abs(price));
sender.sendMessage(ChatColor.DARK_AQUA + "You were charged: " + ChatColor.BLUE + String.valueOf(price));
sender.sendMessage(ChatColor.GOLD+"[DiabloDrops]"
+ChatColor.GRAY + "For An Socket Gem. ");
return true;
}
if(args[1].equalsIgnoreCase("name")
&&plugin.getConfig().getBoolean("Name.Enabled",true)
&&hasPerms(sender,"identify.buy.name")){
double price = 1000;
String name = combineSplit(2, args, " ");
name = ChatColor.translateAlternateColorCodes('&', name);
ItemStack item = player.getItemInHand();
if (item==null||item.getType() == Material.AIR){
sender.sendMessage(ChatColor.DARK_AQUA + "Your Not Holding Anything.");
return true;
}
if(plugin.getConfig().getBoolean("Name.Flat",true)){
price = plugin.ddConfig.getDouble("Name.FlatRate", 1000);
if(price > bal){
sender.sendMessage(ChatColor.DARK_AQUA + "Your don't have enough money!");
sender.sendMessage(ChatColor.BLUE + "Name Cost: "+String.valueOf(price));
return true;
}
plugin.economy.withdrawPlayer(sender.getName(), Math.abs(price));
}else{
price = plugin.ddConfig.getDouble("Name.PerLetter", 10);
price = price*name.length();
if(price > bal){
sender.sendMessage(ChatColor.DARK_AQUA + "Your don't have enough money!");
sender.sendMessage(ChatColor.BLUE + "Name Cost: "+String.valueOf(price));
return true;
}
plugin.economy.withdrawPlayer(sender.getName(), Math.abs(price));
}
ItemMeta meta = item.getItemMeta();
meta.setDisplayName(name);
item.setItemMeta(meta);
sender.sendMessage(ChatColor.GRAY+" Name: "+name+ChatColor.GRAY+" was set for "+ChatColor.GOLD+String.valueOf(price));
return true;
}
if(args[1].equalsIgnoreCase("lore")
&&plugin.getConfig().getBoolean("Lore.Enabled",true)
&&hasPerms(sender,"identify.buy.lore")){
if(plugin.getDiabloDrops()!=null&&!sender.hasPermission("identify.override.lore")){
sender.sendMessage(ChatColor.GOLD+"[DiabloDrops]"+ChatColor.GRAY+"Option disabled.");
return true;
}
double price = 1000;
String lore = combineSplit(2, args, " ");
lore = ChatColor.translateAlternateColorCodes(
"&".toCharArray()[0], lore);
if(!plugin.ddConfig.getBoolean("Lore.PerLetterLine",false)){
price = plugin.ddConfig.getDouble("Lore.FlatRatePerLine", 1000);
price = lore.split(",").length*price;
if(price > bal){
sender.sendMessage(ChatColor.DARK_AQUA + "Your don't have enough money!");
sender.sendMessage(ChatColor.BLUE + "Lore Cost: "+String.valueOf(price));
return true;
}
plugin.economy.withdrawPlayer(sender.getName(), Math.abs(price));
}else{
price = plugin.ddConfig.getDouble("Lore.PerRate", 10);
price = lore.length()*price;
if(price > bal){
sender.sendMessage(ChatColor.DARK_AQUA + "Your don't have enough money!");
sender.sendMessage(ChatColor.BLUE + "Lore Cost: "+String.valueOf(price));
return true;
}
plugin.economy.withdrawPlayer(sender.getName(), Math.abs(price));
}
ItemStack item = player.getItemInHand();
List<String> list = new ArrayList<String>();
for (String s : lore.split(","))
{
if (s.length() > 0)
list.add(s);
}
ItemMeta m = item.getItemMeta();
m.setLore(list);
item.setItemMeta(m);
sender.sendMessage(ChatColor.DARK_AQUA + "You were charged: " + ChatColor.BLUE + String.valueOf(price));
for(String s:list){
if (s.length() > 0)
sender.sendMessage(s);
}
sender.sendMessage(ChatColor.DARK_AQUA + "Lore Set.");
return true;
}
if(args[1].equalsIgnoreCase("random")&&hasPerms(sender,"identify.buy.random")){
ItemStack item = player.getItemInHand();
if(item.hasItemMeta()){
ItemMeta meta = item.getItemMeta();
if(meta.getDisplayName().contains(new Character((char) 167).toString())
|| item.getEnchantments().size()>0){
sender.sendMessage(ChatColor.AQUA+"You are unable to enchant this.");
return true;
}
}
plugin.buy.buyRandom(player);
return true;
}
if(args[1].equalsIgnoreCase("enchant")&&args.length>2&&hasPerms(sender,"identify.buy.enchant")){
ItemStack item = player.getItemInHand();
if(item.hasItemMeta()){
ItemMeta meta = item.getItemMeta();
if(meta.getDisplayName()!=null
&&meta.getDisplayName().contains(new Character((char) 167).toString())){
sender.sendMessage(ChatColor.AQUA+"You are unable to enchant this.");
return true;
}
}
plugin.buy.buyList(player, args);
return true;
}
}
if(args[0].equalsIgnoreCase("repair")
&&plugin.getConfig().getBoolean("Repair.Enabled",true)
&&hasPerms(sender,"identify.repair")){
double bal = plugin.economy.getBalance(sender.getName());
double price = 1000;
ItemStack item = player.getItemInHand();
if (item==null||item.getType() == Material.AIR){
sender.sendMessage(ChatColor.DARK_AQUA + "Your Not Holding Anything.");
return true;
}
if(plugin.getConfig().getBoolean("Repair.Flat",true)){
price = plugin.ddConfig.getDouble("Repair.FlatRate", 1000);
if(price > bal){
sender.sendMessage(ChatColor.DARK_AQUA + "Your don't have enough money!");
sender.sendMessage(ChatColor.BLUE + "Repair Cost: "+String.valueOf(price));
return true;
}
plugin.economy.withdrawPlayer(sender.getName(), Math.abs(price));
}else{
price = plugin.ddConfig.getDouble("Repair.PriceVsDamage", 10);
price = price*item.getDurability();
if(price > bal){
sender.sendMessage(ChatColor.DARK_AQUA + "Your don't have enough money!");
sender.sendMessage(ChatColor.BLUE + "Repair Cost: "+String.valueOf(price));
return true;
}
plugin.economy.withdrawPlayer(sender.getName(), Math.abs(price));
}
item.setDurability((short)0);
sender.sendMessage(ChatColor.GRAY+" Your "+item.getType().toString()+ChatColor.GRAY+" was repaired for "+ChatColor.GOLD+String.valueOf(price));
return true;
}
if(args[0].equalsIgnoreCase("help")){
showHelp(player);
return true;
}
if(args[0].equalsIgnoreCase("reload")&&hasPerms(sender,"identify.reload")){
plugin.getServer().getPluginManager().disablePlugin(plugin);
plugin.getServer().getPluginManager().enablePlugin(plugin);
plugin.reloadConfig();
sender.sendMessage(ChatColor.GREEN+"Reloaded Identify.");
return true;
}
if(args[0].equalsIgnoreCase("clear")&&hasPerms(sender,"identify.clear")){
ItemStack it = player.getItemInHand();
Material mat = it.getType();
short dam = it.getDurability();
ItemStack its = new ItemStack(mat,1,dam);
player.setItemInHand(its);
sender.sendMessage(ChatColor.DARK_AQUA+"Item cleared");
return true;
}
return false;
}
|
diff --git a/src/main/java/de/cismet/cismap/commons/gui/piccolo/LinearReferencedPointPHandle.java b/src/main/java/de/cismet/cismap/commons/gui/piccolo/LinearReferencedPointPHandle.java
index 29e2edab..a01d0c63 100644
--- a/src/main/java/de/cismet/cismap/commons/gui/piccolo/LinearReferencedPointPHandle.java
+++ b/src/main/java/de/cismet/cismap/commons/gui/piccolo/LinearReferencedPointPHandle.java
@@ -1,190 +1,190 @@
/***************************************************
*
* cismet GmbH, Saarbruecken, Germany
*
* ... and it just works.
*
****************************************************/
package de.cismet.cismap.commons.gui.piccolo;
import com.vividsolutions.jts.geom.Coordinate;
import edu.umd.cs.piccolo.event.PInputEvent;
import edu.umd.cs.piccolo.util.PBounds;
import edu.umd.cs.piccolo.util.PDimension;
import edu.umd.cs.piccolox.util.PLocator;
import pswing.PSwing;
import pswing.PSwingCanvas;
import java.awt.geom.Point2D;
import java.text.Format;
import de.cismet.cismap.commons.WorldToScreenTransform;
import de.cismet.cismap.commons.gui.MappingComponent;
import de.cismet.cismap.commons.gui.piccolo.eventlistener.LinearReferencedPointFeature;
import de.cismet.cismap.commons.gui.piccolo.eventlistener.LinearReferencedPointFeatureListener;
import de.cismet.cismap.commons.gui.piccolo.eventlistener.SimpleMoveListener;
/**
* DOCUMENT ME!
*
* @author jruiz
* @version $Revision$, $Date$
*/
public class LinearReferencedPointPHandle extends PHandle {
//~ Static fields/initializers ---------------------------------------------
private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(
LinearReferencedPointPHandle.class);
//~ Instance fields --------------------------------------------------------
private PFeature pfeature;
private LinearReferencedPointInfoPanel infoPanel;
private PSwing pswingComp;
//~ Constructors -----------------------------------------------------------
/**
* Creates a new LinearReferencedPointPHandle object.
*
* @param pfeature DOCUMENT ME!
*/
public LinearReferencedPointPHandle(final PFeature pfeature) {
super(new PLocator() {
@Override
public double locateX() {
try {
- return pfeature.getYp(0, 0)[0];
+ return pfeature.getXp(0, 0)[0];
} catch (Exception ex) {
return -1;
}
}
@Override
public double locateY() {
try {
- return pfeature.getXp(0, 0)[0];
+ return pfeature.getYp(0, 0)[0];
} catch (Exception ex) {
return -1;
}
}
}, pfeature.getViewer());
this.pfeature = pfeature;
initPanel();
((LinearReferencedPointFeature)pfeature.getFeature()).addListener(new LinearReferencedPointFeatureListener() {
@Override
public void featureMoved(final LinearReferencedPointFeature pointFeature) {
relocateHandle();
}
@Override
public void featureMerged(final LinearReferencedPointFeature withPoint,
final LinearReferencedPointFeature mergePoint) {
}
});
}
//~ Methods ----------------------------------------------------------------
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public PFeature getPFeature() {
return pfeature;
}
/**
* DOCUMENT ME!
*/
private void initPanel() {
infoPanel = new LinearReferencedPointInfoPanel();
pswingComp = new PSwing((PSwingCanvas)pfeature.getViewer(), infoPanel);
infoPanel.setPNodeParent(pswingComp);
addChild(pswingComp);
}
@Override
public void dragHandle(final PDimension aLocalDimension, final PInputEvent pInputEvent) {
try {
final SimpleMoveListener moveListener = (SimpleMoveListener)pfeature.getViewer()
.getInputListener(MappingComponent.MOTION);
if (moveListener != null) {
moveListener.mouseMoved(pInputEvent);
} else {
LOG.warn("Movelistener zur Abstimmung der Mauszeiger nicht gefunden.");
}
if (pfeature.getViewer().getHandleInteractionMode().equals(MappingComponent.MOVE_HANDLE)) {
pfeature.getViewer().getCamera().localToView(aLocalDimension);
final WorldToScreenTransform wtst = pfeature.getViewer().getWtst();
final LinearReferencedPointFeature linref = (LinearReferencedPointFeature)pfeature.getFeature();
final Point2D dragPoint = pInputEvent.getPosition();
final Coordinate coord = new Coordinate(
wtst.getSourceX(dragPoint.getX()),
wtst.getSourceY(dragPoint.getY()));
linref.moveTo(coord);
relocateHandle();
}
} catch (Throwable t) {
if (LOG.isDebugEnabled()) {
LOG.debug("Error in dragHandle.", t);
}
}
}
@Override
public void endHandleDrag(final Point2D aLocalPoint, final PInputEvent aEvent) {
super.endHandleDrag(aLocalPoint, aEvent);
final LinearReferencedPointFeature linref = (LinearReferencedPointFeature)pfeature.getFeature();
linref.moveFinished();
}
@Override
public void relocateHandle() {
super.relocateHandle();
if (pfeature != null) {
final LinearReferencedPointFeature linref = (LinearReferencedPointFeature)pfeature.getFeature();
String info = "";
final Format infoFormat = ((LinearReferencedPointFeature)pfeature.getFeature()).getInfoFormat();
if (infoFormat != null) {
info = infoFormat.format(linref.getCurrentPosition());
} else {
info = String.valueOf(linref.getCurrentPosition());
}
infoPanel.setLengthInfo(info);
final PBounds b = getBoundsReference();
final Point2D aPoint = getLocator().locatePoint(null);
pfeature.getViewer().getCamera().viewToLocal(aPoint);
final double newCenterX = aPoint.getX();
final double newCenterY = aPoint.getY();
pswingComp.setOffset(newCenterX + DEFAULT_HANDLE_SIZE, newCenterY - (pswingComp.getHeight() / 2));
if ((newCenterX != b.getCenterX()) || (newCenterY != b.getCenterY())) {
this.setBounds(0, 0, DEFAULT_HANDLE_SIZE, DEFAULT_HANDLE_SIZE);
centerBoundsOnPoint(newCenterX, newCenterY);
}
}
}
}
| false | true | public LinearReferencedPointPHandle(final PFeature pfeature) {
super(new PLocator() {
@Override
public double locateX() {
try {
return pfeature.getYp(0, 0)[0];
} catch (Exception ex) {
return -1;
}
}
@Override
public double locateY() {
try {
return pfeature.getXp(0, 0)[0];
} catch (Exception ex) {
return -1;
}
}
}, pfeature.getViewer());
this.pfeature = pfeature;
initPanel();
((LinearReferencedPointFeature)pfeature.getFeature()).addListener(new LinearReferencedPointFeatureListener() {
@Override
public void featureMoved(final LinearReferencedPointFeature pointFeature) {
relocateHandle();
}
@Override
public void featureMerged(final LinearReferencedPointFeature withPoint,
final LinearReferencedPointFeature mergePoint) {
}
});
}
| public LinearReferencedPointPHandle(final PFeature pfeature) {
super(new PLocator() {
@Override
public double locateX() {
try {
return pfeature.getXp(0, 0)[0];
} catch (Exception ex) {
return -1;
}
}
@Override
public double locateY() {
try {
return pfeature.getYp(0, 0)[0];
} catch (Exception ex) {
return -1;
}
}
}, pfeature.getViewer());
this.pfeature = pfeature;
initPanel();
((LinearReferencedPointFeature)pfeature.getFeature()).addListener(new LinearReferencedPointFeatureListener() {
@Override
public void featureMoved(final LinearReferencedPointFeature pointFeature) {
relocateHandle();
}
@Override
public void featureMerged(final LinearReferencedPointFeature withPoint,
final LinearReferencedPointFeature mergePoint) {
}
});
}
|
diff --git a/msv/src/com/sun/msv/util/xml/DOMBuilder.java b/msv/src/com/sun/msv/util/xml/DOMBuilder.java
index b2a41982..7329143a 100644
--- a/msv/src/com/sun/msv/util/xml/DOMBuilder.java
+++ b/msv/src/com/sun/msv/util/xml/DOMBuilder.java
@@ -1,68 +1,68 @@
/*
* @(#)$Id$
*
* Copyright 2001 Sun Microsystems, Inc. All Rights Reserved.
*
* This software is the proprietary information of Sun Microsystems, Inc.
* Use is subject to license terms.
*
*/
package com.sun.msv.util.xml;
import org.xml.sax.ContentHandler;
import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
/**
* builds DOM from SAX2 event stream.
*
* @author
* <a href="mailto:[email protected]">Kohsuke KAWAGUCHI</a>
*/
public class DOMBuilder extends DefaultHandler {
private final Document dom;
private Node parent;
public DOMBuilder( Document document ) {
this.dom = document;
parent = dom;
}
public DOMBuilder() throws ParserConfigurationException {
this( DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument() );
}
/**
* returns DOM. This method should be called after the parsing was completed.
*/
public Document getDocument() {
return dom;
}
public void startElement( String ns, String local, String qname, Attributes atts ) {
- Element e = dom.createElementNS( ns, local );
+ Element e = dom.createElementNS( ns, qname );
parent.appendChild(e);
parent = e;
for( int i=0; i<atts.getLength(); i++ )
- e.setAttributeNS( atts.getURI(i), atts.getLocalName(i), atts.getValue(i) );
+ e.setAttributeNS( atts.getURI(i), atts.getQName(i), atts.getValue(i) );
}
public void endElement( String ns, String local, String qname ) {
parent = parent.getParentNode();
}
public void characters( char[] buf, int start, int len ) {
parent.appendChild( dom.createTextNode(new String(buf,start,len)) );
}
public void ignorableWhitespace( char[] buf, int start, int len ) {
parent.appendChild( dom.createTextNode(new String(buf,start,len)) );
}
}
| false | true | public void startElement( String ns, String local, String qname, Attributes atts ) {
Element e = dom.createElementNS( ns, local );
parent.appendChild(e);
parent = e;
for( int i=0; i<atts.getLength(); i++ )
e.setAttributeNS( atts.getURI(i), atts.getLocalName(i), atts.getValue(i) );
}
| public void startElement( String ns, String local, String qname, Attributes atts ) {
Element e = dom.createElementNS( ns, qname );
parent.appendChild(e);
parent = e;
for( int i=0; i<atts.getLength(); i++ )
e.setAttributeNS( atts.getURI(i), atts.getQName(i), atts.getValue(i) );
}
|
diff --git a/projects/de.skuzzle.polly.plugin.core/src/commands/WebInterfaceCommand.java b/projects/de.skuzzle.polly.plugin.core/src/commands/WebInterfaceCommand.java
index a76aacc7..59420f12 100644
--- a/projects/de.skuzzle.polly.plugin.core/src/commands/WebInterfaceCommand.java
+++ b/projects/de.skuzzle.polly.plugin.core/src/commands/WebInterfaceCommand.java
@@ -1,73 +1,73 @@
package commands;
import java.io.IOException;
import polly.core.MSG;
import de.skuzzle.polly.sdk.Command;
import de.skuzzle.polly.sdk.Configuration;
import de.skuzzle.polly.sdk.MyPolly;
import de.skuzzle.polly.sdk.Parameter;
import de.skuzzle.polly.sdk.Signature;
import de.skuzzle.polly.sdk.Types;
import de.skuzzle.polly.sdk.User;
import de.skuzzle.polly.sdk.exceptions.CommandException;
import de.skuzzle.polly.sdk.exceptions.DuplicatedSignatureException;
import de.skuzzle.polly.sdk.exceptions.InsufficientRightsException;
import de.skuzzle.polly.sdk.roles.RoleManager;
public class WebInterfaceCommand extends Command {
public WebInterfaceCommand(MyPolly polly) throws DuplicatedSignatureException {
super(polly, "web"); //$NON-NLS-1$
this.createSignature(MSG.webSig0Desc);
this.createSignature(MSG.webSig1Desc,
RoleManager.ADMIN_PERMISSION,
new Parameter(MSG.webSig1OnOff, Types.BOOLEAN));
this.setHelpText(MSG.webHelp);
}
@Override
protected boolean executeOnBoth(User executer, String channel,
Signature signature) throws CommandException, InsufficientRightsException {
boolean ssl = false;
try {
ssl = this.getMyPolly().configuration().open("http.cfg").readBoolean( //$NON-NLS-1$
Configuration.HTTP_USE_SSL);
} catch (Exception e1) {
e1.printStackTrace();
}
final int port = this.getMyPolly().webInterface().getPort();
boolean appendPort = ssl && port != 443 || !ssl && port != 80;
String url = "http" + (ssl ? "s" : ""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
url += "://" + this.getMyPolly().webInterface().getPublicHost(); //$NON-NLS-1$
- url += appendPort ? ":" + port : ""; //$NON-NLS-1$
+ url += appendPort ? ":" + port : ""; //$NON-NLS-1$ //$NON-NLS-2$
if (this.match(signature, 0)) {
if (this.getMyPolly().webInterface().getServer().isRunning()) {
this.reply(channel, MSG.bind(MSG.webShowUrl, url));
} else {
this.reply(channel, MSG.webOffline);
}
} else if (this.match(signature, 1)) {
boolean newState = signature.getBooleanValue(0);
if (this.getMyPolly().webInterface().getServer().isRunning() && !newState) {
this.getMyPolly().webInterface().getServer().shutdown(0);
this.reply(channel, MSG.webTurnedOff);
} else if (!this.getMyPolly().webInterface().getServer().isRunning() && newState) {
try {
this.getMyPolly().webInterface().getServer().start();
this.reply(channel, MSG.bind(MSG.webTurnedOn, url));
} catch (IOException e) {
throw new CommandException(e);
}
}
}
return false;
}
}
| true | true | protected boolean executeOnBoth(User executer, String channel,
Signature signature) throws CommandException, InsufficientRightsException {
boolean ssl = false;
try {
ssl = this.getMyPolly().configuration().open("http.cfg").readBoolean( //$NON-NLS-1$
Configuration.HTTP_USE_SSL);
} catch (Exception e1) {
e1.printStackTrace();
}
final int port = this.getMyPolly().webInterface().getPort();
boolean appendPort = ssl && port != 443 || !ssl && port != 80;
String url = "http" + (ssl ? "s" : ""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
url += "://" + this.getMyPolly().webInterface().getPublicHost(); //$NON-NLS-1$
url += appendPort ? ":" + port : ""; //$NON-NLS-1$
if (this.match(signature, 0)) {
if (this.getMyPolly().webInterface().getServer().isRunning()) {
this.reply(channel, MSG.bind(MSG.webShowUrl, url));
} else {
this.reply(channel, MSG.webOffline);
}
} else if (this.match(signature, 1)) {
boolean newState = signature.getBooleanValue(0);
if (this.getMyPolly().webInterface().getServer().isRunning() && !newState) {
this.getMyPolly().webInterface().getServer().shutdown(0);
this.reply(channel, MSG.webTurnedOff);
} else if (!this.getMyPolly().webInterface().getServer().isRunning() && newState) {
try {
this.getMyPolly().webInterface().getServer().start();
this.reply(channel, MSG.bind(MSG.webTurnedOn, url));
} catch (IOException e) {
throw new CommandException(e);
}
}
}
return false;
}
| protected boolean executeOnBoth(User executer, String channel,
Signature signature) throws CommandException, InsufficientRightsException {
boolean ssl = false;
try {
ssl = this.getMyPolly().configuration().open("http.cfg").readBoolean( //$NON-NLS-1$
Configuration.HTTP_USE_SSL);
} catch (Exception e1) {
e1.printStackTrace();
}
final int port = this.getMyPolly().webInterface().getPort();
boolean appendPort = ssl && port != 443 || !ssl && port != 80;
String url = "http" + (ssl ? "s" : ""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
url += "://" + this.getMyPolly().webInterface().getPublicHost(); //$NON-NLS-1$
url += appendPort ? ":" + port : ""; //$NON-NLS-1$ //$NON-NLS-2$
if (this.match(signature, 0)) {
if (this.getMyPolly().webInterface().getServer().isRunning()) {
this.reply(channel, MSG.bind(MSG.webShowUrl, url));
} else {
this.reply(channel, MSG.webOffline);
}
} else if (this.match(signature, 1)) {
boolean newState = signature.getBooleanValue(0);
if (this.getMyPolly().webInterface().getServer().isRunning() && !newState) {
this.getMyPolly().webInterface().getServer().shutdown(0);
this.reply(channel, MSG.webTurnedOff);
} else if (!this.getMyPolly().webInterface().getServer().isRunning() && newState) {
try {
this.getMyPolly().webInterface().getServer().start();
this.reply(channel, MSG.bind(MSG.webTurnedOn, url));
} catch (IOException e) {
throw new CommandException(e);
}
}
}
return false;
}
|
diff --git a/src/compiler/language/parser/LanguageTokenizer.java b/src/compiler/language/parser/LanguageTokenizer.java
index fc7dfb3..ba0a609 100644
--- a/src/compiler/language/parser/LanguageTokenizer.java
+++ b/src/compiler/language/parser/LanguageTokenizer.java
@@ -1,1362 +1,1362 @@
package compiler.language.parser;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;
import parser.ParseException;
import parser.Token;
import parser.Tokenizer;
import compiler.language.LexicalPhrase;
import compiler.language.ast.terminal.CharacterLiteralAST;
import compiler.language.ast.terminal.FloatingLiteralAST;
import compiler.language.ast.terminal.IntegerLiteralAST;
import compiler.language.ast.terminal.NameAST;
import compiler.language.ast.terminal.SinceSpecifierAST;
import compiler.language.ast.terminal.StringLiteralAST;
import compiler.language.ast.terminal.VersionNumberAST;
/*
* Created on 30 Jun 2010
*/
/**
* The tokenizer for the language. This contains everything necessary to parse and read tokens in order from a given Reader.
* @author Anthony Bryant
*/
public class LanguageTokenizer extends Tokenizer<ParseType>
{
private static final Map<String, ParseType> KEYWORDS = new HashMap<String, ParseType>();
static
{
KEYWORDS.put("abstract", ParseType.ABSTRACT_KEYWORD);
KEYWORDS.put("bool", ParseType.BOOLEAN_KEYWORD);
KEYWORDS.put("break", ParseType.BREAK_KEYWORD);
KEYWORDS.put("byte", ParseType.BYTE_KEYWORD);
KEYWORDS.put("case", ParseType.CASE_KEYWORD);
KEYWORDS.put("cast", ParseType.CAST_KEYWORD);
KEYWORDS.put("catch", ParseType.CATCH_KEYWORD);
KEYWORDS.put("char", ParseType.CHARACTER_KEYWORD);
KEYWORDS.put("class", ParseType.CLASS_KEYWORD);
KEYWORDS.put("closure", ParseType.CLOSURE_KEYWORD);
KEYWORDS.put("continue", ParseType.CONTINUE_KEYWORD);
KEYWORDS.put("default", ParseType.DEFAULT_KEYWORD);
KEYWORDS.put("do", ParseType.DO_KEYWORD);
KEYWORDS.put("double", ParseType.DOUBLE_KEYWORD);
KEYWORDS.put("else", ParseType.ELSE_KEYWORD);
KEYWORDS.put("enum", ParseType.ENUM_KEYWORD);
KEYWORDS.put("extends", ParseType.EXTENDS_KEYWORD);
KEYWORDS.put("fallthrough", ParseType.FALLTHROUGH_KEYWORD);
KEYWORDS.put("false", ParseType.FALSE_KEYWORD);
KEYWORDS.put("final", ParseType.FINAL_KEYWORD);
KEYWORDS.put("finally", ParseType.FINALLY_KEYWORD);
KEYWORDS.put("float", ParseType.FLOAT_KEYWORD);
KEYWORDS.put("for", ParseType.FOR_KEYWORD);
KEYWORDS.put("getter", ParseType.GETTER_KEYWORD);
KEYWORDS.put("if", ParseType.IF_KEYWORD);
KEYWORDS.put("immutable", ParseType.IMMUTABLE_KEYWORD);
KEYWORDS.put("implements", ParseType.IMPLEMENTS_KEYWORD);
KEYWORDS.put("import", ParseType.IMPORT_KEYWORD);
KEYWORDS.put("instanceof", ParseType.INSTANCEOF_KEYWORD);
KEYWORDS.put("int", ParseType.INT_KEYWORD);
KEYWORDS.put("interface", ParseType.INTERFACE_KEYWORD);
KEYWORDS.put("long", ParseType.LONG_KEYWORD);
KEYWORDS.put("mutable", ParseType.MUTABLE_KEYWORD);
KEYWORDS.put("native", ParseType.NATIVE_KEYWORD);
KEYWORDS.put("new", ParseType.NEW_KEYWORD);
KEYWORDS.put("nil", ParseType.NIL_KEYWORD);
KEYWORDS.put("package", ParseType.PACKAGE_KEYWORD);
KEYWORDS.put("private", ParseType.PRIVATE_KEYWORD);
KEYWORDS.put("property", ParseType.PROPERTY_KEYWORD);
KEYWORDS.put("protected", ParseType.PROTECTED_KEYWORD);
KEYWORDS.put("public", ParseType.PUBLIC_KEYWORD);
KEYWORDS.put("return", ParseType.RETURN_KEYWORD);
KEYWORDS.put("sealed", ParseType.SEALED_KEYWORD);
KEYWORDS.put("setter", ParseType.SETTER_KEYWORD);
KEYWORDS.put("short", ParseType.SHORT_KEYWORD);
KEYWORDS.put("signed", ParseType.SIGNED_KEYWORD);
// "since" is handled differently (the whole "since(1.2.3)" is parsed by the tokenizer)
KEYWORDS.put("static", ParseType.STATIC_KEYWORD);
KEYWORDS.put("super", ParseType.SUPER_KEYWORD);
KEYWORDS.put("switch", ParseType.SWITCH_KEYWORD);
KEYWORDS.put("synchronized", ParseType.SYNCHRONIZED_KEYWORD);
KEYWORDS.put("this", ParseType.THIS_KEYWORD);
KEYWORDS.put("throw", ParseType.THROW_KEYWORD);
KEYWORDS.put("throws", ParseType.THROWS_KEYWORD);
KEYWORDS.put("transient", ParseType.TRANSIENT_KEYWORD);
KEYWORDS.put("true", ParseType.TRUE_KEYWORD);
KEYWORDS.put("try", ParseType.TRY_KEYWORD);
KEYWORDS.put("unsigned", ParseType.UNSIGNED_KEYWORD);
KEYWORDS.put("void", ParseType.VOID_KEYWORD);
KEYWORDS.put("volatile", ParseType.VOLATILE_KEYWORD);
KEYWORDS.put("while", ParseType.WHILE_KEYWORD);
}
private RandomAccessReader reader;
private int currentLine;
private int currentColumn;
/**
* Creates a new LanguageTokenizer with the specified reader.
* @param reader - the reader to read the input from
*/
public LanguageTokenizer(Reader reader)
{
this.reader = new RandomAccessReader(reader);
currentLine = 1;
currentColumn = 1;
}
/**
* Skips all whitespace and comment characters at the start of the stream, while updating the current position in the file.
* @throws IOException - if an error occurs while reading
*/
private void skipWhitespaceAndComments() throws IOException, LanguageParseException
{
int index = 0;
while (true)
{
int nextChar = reader.read(index);
if (nextChar < 0)
{
reader.discard(index);
return;
}
else if (nextChar == '\r')
{
currentLine++;
currentColumn = 1;
// skip the line feed, since it is immediately following a carriage return
int secondChar = reader.read(index + 1);
if (secondChar == '\n')
{
index++;
}
index++;
continue;
}
else if (nextChar == '\n')
{
currentLine++;
currentColumn = 1;
index++;
continue;
}
else if (nextChar == '\t')
{
reader.discard(index); // discard so that getting the current line works
throw new LanguageParseException("Tabs are not permitted in this language.", new LexicalPhrase(currentLine, reader.getCurrentLine(), currentColumn));
}
else if (Character.isWhitespace(nextChar))
{
currentColumn++;
index++;
continue;
}
else if (nextChar == '/')
{
int secondChar = reader.read(index + 1);
if (secondChar == '*')
{
currentColumn += 2;
index += 2;
// skip to the end of the comment: "*/"
int commentChar = reader.read(index);
while (commentChar >= 0)
{
if (commentChar == '*')
{
int secondCommentChar = reader.read(index + 1);
if (secondCommentChar == '/')
{
currentColumn += 2;
index += 2;
break;
}
}
else if (commentChar == '\r')
{
currentLine++;
currentColumn = 1;
// skip the line feed, since it is immediately following a carriage return
int secondCommentChar = reader.read(index + 1);
if (secondCommentChar == '\n')
{
index++;
}
index++;
}
else if (commentChar == '\n')
{
currentLine++;
currentColumn = 1;
index++;
}
else if (commentChar == '\t')
{
reader.discard(index); // discard so that getting the current line works correctly
throw new LanguageParseException("Tabs are not permitted in this language.", new LexicalPhrase(currentLine, reader.getCurrentLine(), currentColumn));
}
else
{
currentColumn++;
index++;
}
commentChar = reader.read(index);
}
continue;
}
else if (secondChar == '/')
{
index += 2;
// skip to the end of the comment: "\n" or "\r"
int commentChar = reader.read(index);
while (commentChar >= 0)
{
if (commentChar == '\r')
{
currentLine++;
currentColumn = 1;
// skip the line feed, since it is immediately following a carriage return
int secondCommentChar = reader.read(index + 1);
if (secondCommentChar == '\n')
{
index++;
}
index++;
break;
}
else if (commentChar == '\n')
{
currentLine++;
currentColumn = 1;
index++;
break;
}
else if (commentChar == '\t')
{
reader.discard(index); // discard so that getting the current line works correctly
throw new LanguageParseException("Tabs are not permitted in this language.", new LexicalPhrase(currentLine, reader.getCurrentLine(), currentColumn));
}
else
{
currentColumn++;
index++;
}
commentChar = reader.read(index);
}
continue;
}
else
{
reader.discard(index);
return;
}
} // finished parsing comments
else
{
reader.discard(index);
return;
}
}
}
/**
* Reads a name or keyword token from the start of the reader.
* This method assumes that all whitespace and comments have just been discarded,
* and the currentLine and currentColumn are up to date.
* @return a Token read from the input stream, or null if no Token could be read
* @throws IOException - if an error occurs while reading from the stream
* @throws LanguageParseException - if an invalid character sequence is detected
*/
private Token<ParseType> readNameOrKeyword() throws IOException, LanguageParseException
{
int nextChar = reader.read(0);
if (nextChar < 0 || (!Character.isLetter(nextChar) && nextChar != '_'))
{
// there is no name here, so return null
return null;
}
// we have the start of a name or keyword, so allocate a buffer for it
StringBuffer buffer = new StringBuffer();
buffer.append((char) nextChar);
int index = 1;
nextChar = reader.read(index);
while (Character.isLetterOrDigit(nextChar) || nextChar == '_')
{
buffer.append((char) nextChar);
index++;
nextChar = reader.read(index);
}
// we will not be reading any more as part of the name, so discard the used characters
reader.discard(index);
// update the tokenizer's current location in the file
currentColumn += index;
// we have a full name or keyword, so compare it against a list of keywords to find out which
String name = buffer.toString();
ParseType keyword = KEYWORDS.get(name);
if (keyword != null)
{
return new Token<ParseType>(keyword, new LexicalPhrase(currentLine, reader.getCurrentLine(), currentColumn - index, currentColumn));
}
// check if the name is the start of a since specifier, and if it is then read the rest of it
if (name.equals("since"))
{
return readSinceSpecifier(new LexicalPhrase(currentLine, reader.getCurrentLine(), currentColumn - index, currentColumn));
}
// check if the name is an underscore, and if it is then return it
if (name.equals("_"))
{
return new Token<ParseType>(ParseType.UNDERSCORE, new LexicalPhrase(currentLine, reader.getCurrentLine(), currentColumn - index, currentColumn));
}
// we have a name, so return it
return new Token<ParseType>(ParseType.NAME, new NameAST(name, new LexicalPhrase(currentLine, reader.getCurrentLine(), currentColumn - index, currentColumn)));
}
/**
* Reads a since specifier from the stream.
* This method assumes that a "since" keyword has just been parsed, and will throw exceptions if invalid tokens are detected after it.
* @param sinceKeywordPhrase - the LexicalPhrase of the "since" keyword which has already been parsed
* @return a since specified Token
* @throws IOException - if an error occurs while reading from the stream
* @throws LanguageParseException - if an invalid token is detected in the since specifier
*/
private Token<ParseType> readSinceSpecifier(LexicalPhrase sinceKeywordPhrase) throws IOException, LanguageParseException
{
// skip whitespace between "since" and "("
skipWhitespaceAndComments();
// read the "("
int nextChar = reader.read(0);
if (nextChar != '(')
{
throw new LanguageParseException("Expected '(' after 'since'.", new LexicalPhrase(currentLine, reader.getCurrentLine(), currentColumn));
}
LexicalPhrase lparenPhrase = new LexicalPhrase(currentLine, reader.getCurrentLine(), currentColumn, currentColumn + 1);
currentColumn++;
reader.discard(1);
skipWhitespaceAndComments();
// read the first number
Token<ParseType> firstLiteralToken = readIntegerLiteral();
if (firstLiteralToken == null)
{
throw new LanguageParseException("Expected integer literal in since specifier.", new LexicalPhrase(currentLine, reader.getCurrentLine(), currentColumn));
}
IntegerLiteralAST firstLiteral = (IntegerLiteralAST) firstLiteralToken.getValue();
VersionNumberAST version = new VersionNumberAST(new IntegerLiteralAST[] {firstLiteral}, firstLiteral.getLexicalPhrase());
skipWhitespaceAndComments();
LexicalPhrase rparenPhrase;
while (true)
{
nextChar = reader.read(0);
if (nextChar == '.')
{
// read the dot
currentColumn++;
reader.discard(1);
LexicalPhrase dotPhrase = new LexicalPhrase(currentLine, reader.getCurrentLine(), currentColumn - 1, currentColumn);
skipWhitespaceAndComments();
// read the next version number part
Token<ParseType> literalToken = readIntegerLiteral();
if (literalToken == null)
{
throw new LanguageParseException("Expected integer literal in since specifier.", new LexicalPhrase(currentLine, reader.getCurrentLine(), currentColumn));
}
IntegerLiteralAST literal = (IntegerLiteralAST) literalToken.getValue();
IntegerLiteralAST[] oldList = version.getVersionParts();
IntegerLiteralAST[] newList = new IntegerLiteralAST[oldList.length + 1];
System.arraycopy(oldList, 0, newList, 0, oldList.length);
newList[oldList.length] = literal;
version = new VersionNumberAST(newList, LexicalPhrase.combine(version.getLexicalPhrase(), dotPhrase, literal.getLexicalPhrase()));
skipWhitespaceAndComments();
}
else if (nextChar == ')')
{
// read the RParen
currentColumn++;
reader.discard(1);
rparenPhrase = new LexicalPhrase(currentLine, reader.getCurrentLine(), currentColumn - 1, currentColumn);
break;
}
else
{
throw new LanguageParseException("Expected '.' or ')' after integer literal in since specifier.", new LexicalPhrase(currentLine, reader.getCurrentLine(), currentColumn));
}
}
SinceSpecifierAST sinceSpecifier = new SinceSpecifierAST(version, LexicalPhrase.combine(sinceKeywordPhrase, lparenPhrase, version.getLexicalPhrase(), rparenPhrase));
return new Token<ParseType>(ParseType.SINCE_SPECIFIER, sinceSpecifier);
}
/**
* Reads a floating literal from the start of the reader.
* This method assumes that all whitespace and comments have just been discarded,
* and the currentLine and currentColumn are up to date.
* @return a Token read from the input stream, or null if no Token could be read
* @throws IOException - if an error occurs while reading from the stream
*/
private Token<ParseType> readFloatingLiteral() throws IOException
{
int nextChar;
int index = 0;
StringBuffer buffer = new StringBuffer();
boolean hasInitialNumber = false;
while (true)
{
nextChar = reader.read(index);
int digitValue = Character.digit(nextChar, 10);
if (digitValue < 0)
{
// we do not have a digit in the range 0-9
break;
}
hasInitialNumber = true;
buffer.append((char) nextChar);
index++;
}
boolean hasFractionalPart = false;
if (nextChar == '.')
{
buffer.append('.');
index++;
while (true)
{
nextChar = reader.read(index);
int digitValue = Character.digit(nextChar, 10);
if (digitValue < 0)
{
// we do not have a digit in the range 0-9
if (!hasFractionalPart)
{
// there is no fractional part to this number, so it is not a valid floating point literal
return null;
}
break;
}
hasFractionalPart = true;
buffer.append((char) nextChar);
index++;
}
}
boolean hasExponent = false;
if (nextChar == 'e' || nextChar == 'E')
{
int indexBeforeExponent = index;
StringBuffer exponentialBuffer = new StringBuffer();
exponentialBuffer.append((char) nextChar);
index++;
nextChar = reader.read(index);
if (nextChar == '+' || nextChar == '-')
{
exponentialBuffer.append((char) nextChar);
index++;
}
while (true)
{
nextChar = reader.read(index);
int digitValue = Character.digit(nextChar, 10);
if (digitValue < 0)
{
// we do not have a digit in the range 0-9
break;
}
hasExponent = true;
exponentialBuffer.append((char) nextChar);
index++;
}
// only add the exponent if it all exists
if (hasExponent)
{
buffer.append(exponentialBuffer);
}
else
{
index = indexBeforeExponent;
}
}
if (hasFractionalPart || (hasInitialNumber && hasExponent))
{
String floatingPointText = buffer.toString();
reader.discard(index);
currentColumn += index;
FloatingLiteralAST literal = new FloatingLiteralAST(floatingPointText, new LexicalPhrase(currentLine, reader.getCurrentLine(), currentColumn - index, currentColumn));
return new Token<ParseType>(ParseType.FLOATING_LITERAL, literal);
}
// there was no valid floating literal, so do not return a Token
return null;
}
/**
* Reads an integer literal from the start of the reader.
* This method assumes that all whitespace and comments have just been discarded,
* and the currentLine and currentColumn are up to date.
* @return a Token read from the input stream, or null if no Token could be read
* @throws IOException - if an error occurs while reading from the stream
* @throws LanguageParseException - if an unexpected character sequence is detected inside the integer literal
*/
private Token<ParseType> readIntegerLiteral() throws IOException, LanguageParseException
{
int nextChar = reader.read(0);
int index = 1;
if (nextChar == '0')
{
StringBuffer buffer = new StringBuffer();
buffer.append((char) nextChar);
int secondChar = reader.read(index);
index++;
int base;
switch (secondChar)
{
case 'b':
case 'B':
base = 2; break;
case 'o':
case 'O':
base = 8; break;
case 'x':
case 'X':
base = 16; break;
default:
base = 10; break;
}
if (base != 10)
{
buffer.append((char) secondChar);
BigInteger value = readInteger(buffer, index, base);
reader.discard(buffer.length());
currentColumn += buffer.length();
if (value == null)
{
// there was no value after the 0b, 0o, or 0x, so we have a parse error
String baseString = "integer";
if (base == 2) { baseString = "binary"; }
else if (base == 8) { baseString = "octal"; }
else if (base == 16) { baseString = "hex"; }
throw new LanguageParseException("Unexpected end of " + baseString + " literal.", new LexicalPhrase(currentLine, reader.getCurrentLine(), currentColumn));
}
IntegerLiteralAST literal = new IntegerLiteralAST(value, buffer.toString(), new LexicalPhrase(currentLine, reader.getCurrentLine(), currentColumn - buffer.length(), currentColumn));
return new Token<ParseType>(ParseType.INTEGER_LITERAL, literal);
}
// backtrack an index, as we do not have b, o, or x as the second character in the literal
// this makes it easier to parse the decimal literal without ignoring the character after the 0
index--;
BigInteger value = readInteger(buffer, index, 10);
if (value == null)
{
// there was no value after the initial 0, so set the value to 0
value = BigInteger.valueOf(0);
}
reader.discard(buffer.length());
currentColumn += buffer.length();
IntegerLiteralAST literal = new IntegerLiteralAST(value, buffer.toString(), new LexicalPhrase(currentLine, reader.getCurrentLine(), currentColumn - buffer.length(), currentColumn));
return new Token<ParseType>(ParseType.INTEGER_LITERAL, literal);
}
// backtrack an index, as we do not have 0 as the first character in the literal
// this makes it easier to parse the decimal literal without ignoring the first character
index--;
StringBuffer buffer = new StringBuffer();
BigInteger value = readInteger(buffer, index, 10);
if (value == null)
{
// this is not an integer literal
return null;
}
reader.discard(buffer.length());
currentColumn += buffer.length();
IntegerLiteralAST literal = new IntegerLiteralAST(value, buffer.toString(), new LexicalPhrase(currentLine, reader.getCurrentLine(), currentColumn - buffer.length(), currentColumn));
return new Token<ParseType>(ParseType.INTEGER_LITERAL, literal);
}
/**
* Reads an integer in the specified radix from the stream, and calculates its value as well as appending it to the buffer.
* @param buffer - the buffer to append the raw string to
* @param startIndex - the index in the reader to start at
* @param radix - the radix to read the number in
* @return the value of the integer, or null if there was no numeric value
* @throws IOException - if there is an error reading from the stream
*/
private BigInteger readInteger(StringBuffer buffer, int startIndex, int radix) throws IOException
{
int index = startIndex;
BigInteger value = BigInteger.valueOf(0);
boolean hasNumeral = false;
while (true)
{
int nextChar = reader.read(index);
int digit = Character.digit(nextChar, radix);
if (digit < 0)
{
break;
}
hasNumeral = true;
buffer.append((char) nextChar);
value = value.multiply(BigInteger.valueOf(radix)).add(BigInteger.valueOf(digit));
index++;
}
if (hasNumeral)
{
return value;
}
return null;
}
/**
* Reads a character literal from the start of the reader.
* This method assumes that all whitespace and comments have just been discarded,
* and the currentLine and currentColumn are up to date.
* @return a Token read from the input stream, or null if no Token could be read
* @throws IOException - if an error occurs while reading from the stream
* @throws LanguageParseException - if an unexpected character is detected inside the character literal
*/
private Token<ParseType> readCharacterLiteral() throws IOException, LanguageParseException
{
int nextChar = reader.read(0);
if (nextChar != '\'')
{
// this is not a character literal, so return null
return null;
}
StringBuffer stringRepresentation = new StringBuffer();
stringRepresentation.append('\'');
nextChar = reader.read(1);
if (nextChar < 0)
{
throw new LanguageParseException("Unexpected end of input inside character literal.", new LexicalPhrase(currentLine, reader.getCurrentLine(), currentColumn + 1));
}
if (nextChar == '\n')
{
reader.discard(1); // discard so that getting the current line works correctly
throw new LanguageParseException("Unexpected end of line inside character literal.", new LexicalPhrase(currentLine, reader.getCurrentLine(), currentColumn + 1));
}
if (nextChar == '\'')
{
reader.discard(1); // discard so that getting the current line works correctly
throw new LanguageParseException("Empty character literal.", new LexicalPhrase(currentLine, reader.getCurrentLine(), currentColumn + 1));
}
char character;
int index = 1;
if (nextChar == '\\')
{
// process the escape sequence, and add all characters read from the stream to the stringRepresentation buffer
stringRepresentation.append((char) nextChar);
character = processEscapeSequence(index, stringRepresentation);
index = stringRepresentation.length();
}
else
{
// we have a non-escaped character, so use it
stringRepresentation.append((char) nextChar);
character = (char) nextChar;
index++;
}
int finalChar = reader.read(index);
index++;
if (finalChar != '\'')
{
reader.discard(index); // discard so that getting the current line works correctly
throw new LanguageParseException("Character literals cannot contain more than one character.", new LexicalPhrase(currentLine, reader.getCurrentLine(), currentColumn + 1, currentColumn + index));
}
stringRepresentation.append((char) finalChar);
reader.discard(index);
currentColumn += index;
CharacterLiteralAST literal = new CharacterLiteralAST(character, stringRepresentation.toString(), new LexicalPhrase(currentLine, reader.getCurrentLine(), currentColumn - index, currentColumn));
return new Token<ParseType>(ParseType.CHARACTER_LITERAL, literal);
}
/**
* Reads a string literal from the start of the reader.
* This method assumes that all whitespace and comments have just been discarded,
* and the currentLine and currentColumn are up to date.
* @return a Token read from the input stream, or null if no Token could be read
* @throws IOException - if an error occurs while reading from the stream
* @throws LanguageParseException - if an unexpected character is detected inside the string literal
*/
private Token<ParseType> readStringLiteral() throws IOException, LanguageParseException
{
int nextChar = reader.read(0);
if (nextChar != '"')
{
// this is not a string literal, so return null
return null;
}
StringBuffer stringRepresentation = new StringBuffer();
stringRepresentation.append('"');
StringBuffer buffer = new StringBuffer();
int index = 1;
while (true)
{
nextChar = reader.read(index);
if (nextChar < 0)
{
reader.discard(index - 1); // discard so that getting the current line works correctly
throw new LanguageParseException("Unexpected end of input inside string literal.", new LexicalPhrase(currentLine, reader.getCurrentLine(), currentColumn + index));
}
if (nextChar == '\n')
{
reader.discard(index); // discard so that getting the current line works correctly
throw new LanguageParseException("Unexpected end of line inside string literal.", new LexicalPhrase(currentLine, reader.getCurrentLine(), currentColumn + index));
}
if (nextChar == '"')
{
index++;
stringRepresentation.append((char) nextChar);
break;
}
if (nextChar == '\\')
{
stringRepresentation.append((char) nextChar);
// process the escape sequence, adding the read characters to the stringRepresentation buffer
// and the escaped character to the literal value buffer
char escapedChar = processEscapeSequence(index, stringRepresentation);
index = stringRepresentation.length();
buffer.append(escapedChar);
continue;
} // finished escape sequences
buffer.append((char) nextChar);
stringRepresentation.append((char) nextChar);
index++;
}
// a whole string literal has been read, so create a token from it
// (index is now the length of the entire literal, including quotes)
reader.discard(index);
currentColumn += index;
StringLiteralAST literal = new StringLiteralAST(buffer.toString(), stringRepresentation.toString(), new LexicalPhrase(currentLine, reader.getCurrentLine(), currentColumn - index, currentColumn));
return new Token<ParseType>(ParseType.STRING_LITERAL, literal);
}
/**
* Processes an escape sequence in a character or string literal.
* @param startIndex - the index of the start of the escape sequence (i.e. the '\' character)
* @param buffer - the buffer to append the characters from the stream to
* @return the escaped character
* @throws IOException - if there is an error reading from the stream
* @throws LanguageParseException - if there is an invalid character in the escape sequence
*/
private char processEscapeSequence(int startIndex, StringBuffer buffer) throws IOException, LanguageParseException
{
int index = startIndex;
int secondChar = reader.read(index + 1);
if (secondChar < 0)
{
reader.discard(index); // discard so that getting the current line works correctly
throw new LanguageParseException("Unexpected end of input inside escape sequence.", new LexicalPhrase(currentLine, reader.getCurrentLine(), currentColumn + index + 1));
}
Character escaped = null;
// check all of the single character escape sequences (i.e. the ones that only have one character after the \)
switch (secondChar)
{
case '\\': escaped = '\\'; break;
case 'b': escaped = '\b'; break;
case 't': escaped = '\t'; break;
case 'n': escaped = '\n'; break;
case 'f': escaped = '\f'; break;
case 'r': escaped = '\r'; break;
case '"': escaped = '"'; break;
case '\'': escaped = '\''; break;
default:
break;
}
if (escaped != null)
{
buffer.append((char) secondChar);
}
// check the multi-character escape sequences
int firstOctalDigit = Character.digit(secondChar, 4);
if (escaped == null && firstOctalDigit >= 0)
{
// the character is a valid digit in base 4, so it begins an octal character escape
int octal = firstOctalDigit;
buffer.append((char) secondChar);
int thirdChar = reader.read(index + 2);
int secondOctalDigit = Character.digit(thirdChar, 8);
if (secondOctalDigit >= 0)
{
octal = octal * 8 + secondOctalDigit;
buffer.append((char) thirdChar);
int fourthChar = reader.read(index + 3);
int thirdOctalDigit = Character.digit(fourthChar, 8);
if (thirdOctalDigit >= 0)
{
octal = octal * 8 + thirdOctalDigit;
buffer.append((char) fourthChar);
}
}
escaped = (char) octal;
}
if (escaped == null && secondChar == 'u')
{
buffer.append((char) secondChar);
// read the next 4 characters as a hexadecimal unicode constant
int hex = 0;
for (int i = 0; i < 4; i++)
{
int ithChar = reader.read(index + 2 + i);
int hexDigit = Character.digit(ithChar, 16);
if (hexDigit < 0)
{
reader.discard(index + 2 + i - 1); // discard so that getting the current line works correctly
throw new LanguageParseException("Invalid character in unicode escape sequence" + (ithChar >= 0 ? ": " + (char) ithChar : ""),
new LexicalPhrase(currentLine, reader.getCurrentLine(), currentColumn + index + 2 + i));
}
hex = hex * 8 + hexDigit;
buffer.append((char) ithChar);
}
escaped = (char) hex;
}
if (escaped == null)
{
reader.discard(index + 1); // discard so that getting the current line works correctly
throw new LanguageParseException("Invalid escape sequence" + (secondChar >= 0 ? ": \\" + (char) secondChar : ""),
new LexicalPhrase(currentLine, reader.getCurrentLine(), currentColumn + index + 1));
}
return escaped.charValue();
}
/**
* Reads a symbol token from the start of the reader.
* This method assumes that all whitespace and comments have just been discarded,
* and the currentLine and currentColumn are up to date.
* @return a Token read from the input stream, or null if no Token could be read
* @throws IOException - if an error occurs while reading from the stream
*/
private Token<ParseType> readSymbol() throws IOException
{
int nextChar = reader.read(0);
if (nextChar < 0)
{
// there is no symbol here, just the end of the file
return null;
}
if (nextChar == '&')
{
int secondChar = reader.read(1);
if (secondChar == '=')
{
return makeSymbolToken(ParseType.AMPERSAND_EQUALS, 2);
}
if (secondChar == '&')
{
int thirdChar = reader.read(2);
if (thirdChar == '=')
{
return makeSymbolToken(ParseType.DOUBLE_AMPERSAND_EQUALS, 3);
}
return makeSymbolToken(ParseType.DOUBLE_AMPERSAND, 2);
}
return makeSymbolToken(ParseType.AMPERSAND, 1);
}
if (nextChar == '|')
{
int secondChar = reader.read(1);
if (secondChar == '=')
{
return makeSymbolToken(ParseType.PIPE_EQUALS, 2);
}
if (secondChar == '|')
{
int thirdChar = reader.read(2);
if (thirdChar == '=')
{
return makeSymbolToken(ParseType.DOUBLE_PIPE_EQUALS, 3);
}
return makeSymbolToken(ParseType.DOUBLE_PIPE, 2);
}
return makeSymbolToken(ParseType.PIPE, 1);
}
if (nextChar == '^')
{
int secondChar = reader.read(1);
if (secondChar == '=')
{
return makeSymbolToken(ParseType.CARET_EQUALS, 2);
}
- if (secondChar == '|')
+ if (secondChar == '^')
{
int thirdChar = reader.read(2);
if (thirdChar == '=')
{
return makeSymbolToken(ParseType.DOUBLE_CARET_EQUALS, 3);
}
return makeSymbolToken(ParseType.DOUBLE_CARET, 2);
}
return makeSymbolToken(ParseType.CARET, 1);
}
if (nextChar == '+')
{
int secondChar = reader.read(1);
if (secondChar == '+')
{
return makeSymbolToken(ParseType.DOUBLE_PLUS, 2);
}
if (secondChar == '=')
{
return makeSymbolToken(ParseType.PLUS_EQUALS, 2);
}
return makeSymbolToken(ParseType.PLUS, 1);
}
if (nextChar == '-')
{
int secondChar = reader.read(1);
if (secondChar == '-')
{
return makeSymbolToken(ParseType.DOUBLE_MINUS, 2);
}
if (secondChar == '=')
{
return makeSymbolToken(ParseType.MINUS_EQUALS, 2);
}
if (secondChar == '>')
{
return makeSymbolToken(ParseType.ARROW, 2);
}
return makeSymbolToken(ParseType.MINUS, 1);
}
if (nextChar == '<')
{
int secondChar = reader.read(1);
if (secondChar == '=')
{
return makeSymbolToken(ParseType.LANGLE_EQUALS, 2);
}
if (secondChar == '<')
{
int thirdChar = reader.read(2);
if (thirdChar == '=')
{
return makeSymbolToken(ParseType.DOUBLE_LANGLE_EQUALS, 3);
}
return makeSymbolToken(ParseType.DOUBLE_LANGLE, 2);
}
return makeSymbolToken(ParseType.LANGLE, 1);
}
if (nextChar == '>')
{
int secondChar = reader.read(1);
if (secondChar == '=')
{
return makeSymbolToken(ParseType.RANGLE_EQUALS, 2);
}
if (secondChar == '>')
{
int thirdChar = reader.read(2);
if (thirdChar == '=')
{
return makeSymbolToken(ParseType.DOUBLE_RANGLE_EQUALS, 3);
}
if (thirdChar == '>')
{
int fourthChar = reader.read(3);
if (fourthChar == '=')
{
return makeSymbolToken(ParseType.TRIPLE_RANGLE_EQUALS, 4);
}
return makeSymbolToken(ParseType.TRIPLE_RANGLE, 3);
}
return makeSymbolToken(ParseType.DOUBLE_RANGLE, 2);
}
return makeSymbolToken(ParseType.RANGLE, 1);
}
if (nextChar == '=')
{
int secondChar = reader.read(1);
if (secondChar == '=')
{
return makeSymbolToken(ParseType.DOUBLE_EQUALS, 2);
}
return makeSymbolToken(ParseType.EQUALS, 1);
}
if (nextChar == '.')
{
int secondChar = reader.read(1);
if (secondChar == '.')
{
int thirdChar = reader.read(2);
if (thirdChar == '.')
{
return makeSymbolToken(ParseType.ELLIPSIS, 3);
}
}
return makeSymbolToken(ParseType.DOT, 1);
}
if (nextChar == '@')
{
return makeSymbolToken(ParseType.AT, 1);
}
if (nextChar == ':')
{
return makeSymbolToken(ParseType.COLON, 1);
}
if (nextChar == ',')
{
return makeSymbolToken(ParseType.COMMA, 1);
}
if (nextChar == '!')
{
int secondChar = reader.read(1);
if (secondChar == '=')
{
return makeSymbolToken(ParseType.EXCLAIMATION_MARK_EQUALS, 2);
}
return makeSymbolToken(ParseType.EXCLAIMATION_MARK, 1);
}
if (nextChar == '/')
{
int secondChar = reader.read(1);
if (secondChar == '=')
{
return makeSymbolToken(ParseType.FORWARD_SLASH_EQUALS, 2);
}
return makeSymbolToken(ParseType.FORWARD_SLASH, 1);
}
if (nextChar == '#')
{
return makeSymbolToken(ParseType.HASH, 1);
}
if (nextChar == '{')
{
return makeSymbolToken(ParseType.LBRACE, 1);
}
if (nextChar == '(')
{
return makeSymbolToken(ParseType.LPAREN, 1);
}
if (nextChar == '[')
{
return makeSymbolToken(ParseType.LSQUARE, 1);
}
if (nextChar == '%')
{
int secondChar = reader.read(1);
if (secondChar == '=')
{
return makeSymbolToken(ParseType.PERCENT_EQUALS, 2);
}
return makeSymbolToken(ParseType.PERCENT, 1);
}
if (nextChar == '?')
{
return makeSymbolToken(ParseType.QUESTION_MARK, 1);
}
if (nextChar == '}')
{
return makeSymbolToken(ParseType.RBRACE, 1);
}
if (nextChar == ')')
{
return makeSymbolToken(ParseType.RPAREN, 1);
}
if (nextChar == ']')
{
return makeSymbolToken(ParseType.RSQUARE, 1);
}
if (nextChar == ';')
{
return makeSymbolToken(ParseType.SEMICOLON, 1);
}
if (nextChar == '*')
{
int secondChar = reader.read(1);
if (secondChar == '=')
{
return makeSymbolToken(ParseType.STAR_EQUALS, 2);
}
return makeSymbolToken(ParseType.STAR, 1);
}
if (nextChar == '~')
{
return makeSymbolToken(ParseType.TILDE, 1);
}
// underscore is not handled here, as it is a special case of a name
// none of the symbols matched, so return null
return null;
}
/**
* Convenience method which readSymbol() uses to create its Tokens.
* This assumes that the symbol does not span multiple lines, and is exactly <code>length</code> columns long.
* @param parseType - the ParseType of the token to create.
* @param length - the length of the symbol
* @return the Token created
* @throws IOException - if there is an error discarding the characters that were read in
*/
private Token<ParseType> makeSymbolToken(ParseType parseType, int length) throws IOException
{
reader.discard(length);
currentColumn += length;
return new Token<ParseType>(parseType, new LexicalPhrase(currentLine, reader.getCurrentLine(), currentColumn - length, currentColumn));
}
/**
* @see parser.Tokenizer#generateToken()
*/
@Override
protected Token<ParseType> generateToken() throws ParseException
{
try
{
skipWhitespaceAndComments();
Token<ParseType> token = readNameOrKeyword();
if (token != null)
{
return token;
}
token = readFloatingLiteral();
if (token != null)
{
return token;
}
token = readIntegerLiteral();
if (token != null)
{
return token;
}
token = readCharacterLiteral();
if (token != null)
{
return token;
}
token = readStringLiteral();
if (token != null)
{
return token;
}
token = readSymbol();
if (token != null)
{
return token;
}
int nextChar = reader.read(0);
if (nextChar < 0)
{
// a value of less than 0 means the end of input, so return a token with type null
return new Token<ParseType>(null, new LexicalPhrase(currentLine, reader.getCurrentLine(), currentColumn));
}
throw new LanguageParseException("Unexpected character while parsing: '" + (char) nextChar + "'", new LexicalPhrase(currentLine, reader.getCurrentLine(), currentColumn));
}
catch (IOException e)
{
throw new LanguageParseException("An IO Exception occured while reading the source code.", e, new LexicalPhrase(currentLine, "", currentColumn));
}
}
/**
* Closes this LanguageTokenizer.
* @throws IOException - if there is an error closing the underlying stream
*/
public void close() throws IOException
{
reader.close();
}
/**
* A class that provides a sort of random-access interface to a stream.
* It keeps a buffer of characters, and lazily reads the stream into it.
* It allows single character reads from anywhere in the stream, and also supports discarding from the start of the buffer.
* @author Anthony Bryant
*/
private static final class RandomAccessReader
{
private Reader reader;
private StringBuffer lookahead;
private String currentLine;
/**
* Creates a new RandomAccessReader to read from the specified Reader
* @param reader - the Reader to read from
*/
public RandomAccessReader(Reader reader)
{
this.reader = new BufferedReader(reader);
lookahead = new StringBuffer();
}
/**
* Reads the character at the specified offset.
* @param offset - the offset to read the character at
* @return the character read from the stream, or -1 if the end of the stream was reached
* @throws IOException - if an error occurs while reading from the underlying reader
*/
public int read(int offset) throws IOException
{
int result = ensureContains(offset + 1);
if (result < 0)
{
return result;
}
return lookahead.charAt(offset);
}
/**
* Discards all of the characters in this reader before the specified offset.
* After calling this, the character previously returned from read(offset) will be returned from read(0).
* @param offset - the offset to delete all of the characters before, must be >= 0
* @throws IOException - if an error occurs while reading from the underlying reader
*/
public void discard(int offset) throws IOException
{
int result = ensureContains(offset);
if (result < offset)
{
throw new IndexOutOfBoundsException("Tried to discard past the end of a RandomAccessReader");
}
updateCurrentLine(offset);
lookahead.delete(0, offset);
}
/**
* @return the current line that is at offset 0 in this reader
* @throws IOException - if an error occurs while reading from the underlying reader
*/
public String getCurrentLine() throws IOException
{
if (currentLine == null)
{
updateCurrentLine(0);
}
return currentLine;
}
/**
* Ensures that the lookahead contains at least the specified number of characters.
* @param length - the number of characters to ensure are in the lookahead
* @return the number of characters now in the lookahead buffer, or -1 if the end of the stream has been reached
* @throws IOException - if an error occurs while reading from the underlying reader
*/
private int ensureContains(int length) throws IOException
{
if (length <= 0 || length < lookahead.length())
{
return lookahead.length();
}
char[] buffer = new char[length - lookahead.length()];
int readChars = reader.read(buffer);
if (readChars < 0)
{
return readChars;
}
lookahead.append(buffer, 0, readChars);
return lookahead.length();
}
/**
* Updates the current line to be the line at the specified offset.
* @param offset - the offset to update currentLine from
* @throws IOException - if an error occurs while reading from the underlying reader
*/
private void updateCurrentLine(int offset) throws IOException
{
ensureContains(offset);
ensureNewLineAfter(offset);
int start = -1;
// start at offset - 1 so that if we start on a \n we count backwards from there
for (int i = offset - 1; i >= 0; i--)
{
if (lookahead.charAt(i) == '\n')
{
start = i + 1;
break;
}
}
if (start < 0)
{
if (currentLine != null)
{
return;
}
start = 0;
}
int end = offset;
while (end < lookahead.length() && lookahead.charAt(end) != '\n')
{
end++;
}
currentLine = lookahead.substring(start, end);
}
/**
* Ensures that the lookahead buffer contains a newline after (or at) the specified index.
* @param offset - the offset to ensure there is a newline after.
* @throws IOException - if an error occurs while reading from the underlying reader
*/
private void ensureNewLineAfter(int offset) throws IOException
{
// after this many characters in lookahead, we will stop trying to read another newline
final int MAX_LOOKAHEAD_LENGTH = 10000;
for (int i = offset; i < lookahead.length(); i++)
{
if (lookahead.charAt(i) == '\n')
{
return;
}
}
while (lookahead.length() < MAX_LOOKAHEAD_LENGTH)
{
int nextChar = reader.read();
if (nextChar < 0)
{
// end of stream, just leave lookahead as it was
return;
}
lookahead.append((char) nextChar);
if (nextChar == '\n' && lookahead.length() >= offset)
{
return;
}
}
}
/**
* Closes the underlying stream of this RandomAccessReader
* @throws IOException - if an error occurs while reading from the underlying reader
*/
public void close() throws IOException
{
reader.close();
}
}
}
| true | true | private Token<ParseType> readSymbol() throws IOException
{
int nextChar = reader.read(0);
if (nextChar < 0)
{
// there is no symbol here, just the end of the file
return null;
}
if (nextChar == '&')
{
int secondChar = reader.read(1);
if (secondChar == '=')
{
return makeSymbolToken(ParseType.AMPERSAND_EQUALS, 2);
}
if (secondChar == '&')
{
int thirdChar = reader.read(2);
if (thirdChar == '=')
{
return makeSymbolToken(ParseType.DOUBLE_AMPERSAND_EQUALS, 3);
}
return makeSymbolToken(ParseType.DOUBLE_AMPERSAND, 2);
}
return makeSymbolToken(ParseType.AMPERSAND, 1);
}
if (nextChar == '|')
{
int secondChar = reader.read(1);
if (secondChar == '=')
{
return makeSymbolToken(ParseType.PIPE_EQUALS, 2);
}
if (secondChar == '|')
{
int thirdChar = reader.read(2);
if (thirdChar == '=')
{
return makeSymbolToken(ParseType.DOUBLE_PIPE_EQUALS, 3);
}
return makeSymbolToken(ParseType.DOUBLE_PIPE, 2);
}
return makeSymbolToken(ParseType.PIPE, 1);
}
if (nextChar == '^')
{
int secondChar = reader.read(1);
if (secondChar == '=')
{
return makeSymbolToken(ParseType.CARET_EQUALS, 2);
}
if (secondChar == '|')
{
int thirdChar = reader.read(2);
if (thirdChar == '=')
{
return makeSymbolToken(ParseType.DOUBLE_CARET_EQUALS, 3);
}
return makeSymbolToken(ParseType.DOUBLE_CARET, 2);
}
return makeSymbolToken(ParseType.CARET, 1);
}
if (nextChar == '+')
{
int secondChar = reader.read(1);
if (secondChar == '+')
{
return makeSymbolToken(ParseType.DOUBLE_PLUS, 2);
}
if (secondChar == '=')
{
return makeSymbolToken(ParseType.PLUS_EQUALS, 2);
}
return makeSymbolToken(ParseType.PLUS, 1);
}
if (nextChar == '-')
{
int secondChar = reader.read(1);
if (secondChar == '-')
{
return makeSymbolToken(ParseType.DOUBLE_MINUS, 2);
}
if (secondChar == '=')
{
return makeSymbolToken(ParseType.MINUS_EQUALS, 2);
}
if (secondChar == '>')
{
return makeSymbolToken(ParseType.ARROW, 2);
}
return makeSymbolToken(ParseType.MINUS, 1);
}
if (nextChar == '<')
{
int secondChar = reader.read(1);
if (secondChar == '=')
{
return makeSymbolToken(ParseType.LANGLE_EQUALS, 2);
}
if (secondChar == '<')
{
int thirdChar = reader.read(2);
if (thirdChar == '=')
{
return makeSymbolToken(ParseType.DOUBLE_LANGLE_EQUALS, 3);
}
return makeSymbolToken(ParseType.DOUBLE_LANGLE, 2);
}
return makeSymbolToken(ParseType.LANGLE, 1);
}
if (nextChar == '>')
{
int secondChar = reader.read(1);
if (secondChar == '=')
{
return makeSymbolToken(ParseType.RANGLE_EQUALS, 2);
}
if (secondChar == '>')
{
int thirdChar = reader.read(2);
if (thirdChar == '=')
{
return makeSymbolToken(ParseType.DOUBLE_RANGLE_EQUALS, 3);
}
if (thirdChar == '>')
{
int fourthChar = reader.read(3);
if (fourthChar == '=')
{
return makeSymbolToken(ParseType.TRIPLE_RANGLE_EQUALS, 4);
}
return makeSymbolToken(ParseType.TRIPLE_RANGLE, 3);
}
return makeSymbolToken(ParseType.DOUBLE_RANGLE, 2);
}
return makeSymbolToken(ParseType.RANGLE, 1);
}
if (nextChar == '=')
{
int secondChar = reader.read(1);
if (secondChar == '=')
{
return makeSymbolToken(ParseType.DOUBLE_EQUALS, 2);
}
return makeSymbolToken(ParseType.EQUALS, 1);
}
if (nextChar == '.')
{
int secondChar = reader.read(1);
if (secondChar == '.')
{
int thirdChar = reader.read(2);
if (thirdChar == '.')
{
return makeSymbolToken(ParseType.ELLIPSIS, 3);
}
}
return makeSymbolToken(ParseType.DOT, 1);
}
if (nextChar == '@')
{
return makeSymbolToken(ParseType.AT, 1);
}
if (nextChar == ':')
{
return makeSymbolToken(ParseType.COLON, 1);
}
if (nextChar == ',')
{
return makeSymbolToken(ParseType.COMMA, 1);
}
if (nextChar == '!')
{
int secondChar = reader.read(1);
if (secondChar == '=')
{
return makeSymbolToken(ParseType.EXCLAIMATION_MARK_EQUALS, 2);
}
return makeSymbolToken(ParseType.EXCLAIMATION_MARK, 1);
}
if (nextChar == '/')
{
int secondChar = reader.read(1);
if (secondChar == '=')
{
return makeSymbolToken(ParseType.FORWARD_SLASH_EQUALS, 2);
}
return makeSymbolToken(ParseType.FORWARD_SLASH, 1);
}
if (nextChar == '#')
{
return makeSymbolToken(ParseType.HASH, 1);
}
if (nextChar == '{')
{
return makeSymbolToken(ParseType.LBRACE, 1);
}
if (nextChar == '(')
{
return makeSymbolToken(ParseType.LPAREN, 1);
}
if (nextChar == '[')
{
return makeSymbolToken(ParseType.LSQUARE, 1);
}
if (nextChar == '%')
{
int secondChar = reader.read(1);
if (secondChar == '=')
{
return makeSymbolToken(ParseType.PERCENT_EQUALS, 2);
}
return makeSymbolToken(ParseType.PERCENT, 1);
}
if (nextChar == '?')
{
return makeSymbolToken(ParseType.QUESTION_MARK, 1);
}
if (nextChar == '}')
{
return makeSymbolToken(ParseType.RBRACE, 1);
}
if (nextChar == ')')
{
return makeSymbolToken(ParseType.RPAREN, 1);
}
if (nextChar == ']')
{
return makeSymbolToken(ParseType.RSQUARE, 1);
}
if (nextChar == ';')
{
return makeSymbolToken(ParseType.SEMICOLON, 1);
}
if (nextChar == '*')
{
int secondChar = reader.read(1);
if (secondChar == '=')
{
return makeSymbolToken(ParseType.STAR_EQUALS, 2);
}
return makeSymbolToken(ParseType.STAR, 1);
}
if (nextChar == '~')
{
return makeSymbolToken(ParseType.TILDE, 1);
}
// underscore is not handled here, as it is a special case of a name
// none of the symbols matched, so return null
return null;
}
| private Token<ParseType> readSymbol() throws IOException
{
int nextChar = reader.read(0);
if (nextChar < 0)
{
// there is no symbol here, just the end of the file
return null;
}
if (nextChar == '&')
{
int secondChar = reader.read(1);
if (secondChar == '=')
{
return makeSymbolToken(ParseType.AMPERSAND_EQUALS, 2);
}
if (secondChar == '&')
{
int thirdChar = reader.read(2);
if (thirdChar == '=')
{
return makeSymbolToken(ParseType.DOUBLE_AMPERSAND_EQUALS, 3);
}
return makeSymbolToken(ParseType.DOUBLE_AMPERSAND, 2);
}
return makeSymbolToken(ParseType.AMPERSAND, 1);
}
if (nextChar == '|')
{
int secondChar = reader.read(1);
if (secondChar == '=')
{
return makeSymbolToken(ParseType.PIPE_EQUALS, 2);
}
if (secondChar == '|')
{
int thirdChar = reader.read(2);
if (thirdChar == '=')
{
return makeSymbolToken(ParseType.DOUBLE_PIPE_EQUALS, 3);
}
return makeSymbolToken(ParseType.DOUBLE_PIPE, 2);
}
return makeSymbolToken(ParseType.PIPE, 1);
}
if (nextChar == '^')
{
int secondChar = reader.read(1);
if (secondChar == '=')
{
return makeSymbolToken(ParseType.CARET_EQUALS, 2);
}
if (secondChar == '^')
{
int thirdChar = reader.read(2);
if (thirdChar == '=')
{
return makeSymbolToken(ParseType.DOUBLE_CARET_EQUALS, 3);
}
return makeSymbolToken(ParseType.DOUBLE_CARET, 2);
}
return makeSymbolToken(ParseType.CARET, 1);
}
if (nextChar == '+')
{
int secondChar = reader.read(1);
if (secondChar == '+')
{
return makeSymbolToken(ParseType.DOUBLE_PLUS, 2);
}
if (secondChar == '=')
{
return makeSymbolToken(ParseType.PLUS_EQUALS, 2);
}
return makeSymbolToken(ParseType.PLUS, 1);
}
if (nextChar == '-')
{
int secondChar = reader.read(1);
if (secondChar == '-')
{
return makeSymbolToken(ParseType.DOUBLE_MINUS, 2);
}
if (secondChar == '=')
{
return makeSymbolToken(ParseType.MINUS_EQUALS, 2);
}
if (secondChar == '>')
{
return makeSymbolToken(ParseType.ARROW, 2);
}
return makeSymbolToken(ParseType.MINUS, 1);
}
if (nextChar == '<')
{
int secondChar = reader.read(1);
if (secondChar == '=')
{
return makeSymbolToken(ParseType.LANGLE_EQUALS, 2);
}
if (secondChar == '<')
{
int thirdChar = reader.read(2);
if (thirdChar == '=')
{
return makeSymbolToken(ParseType.DOUBLE_LANGLE_EQUALS, 3);
}
return makeSymbolToken(ParseType.DOUBLE_LANGLE, 2);
}
return makeSymbolToken(ParseType.LANGLE, 1);
}
if (nextChar == '>')
{
int secondChar = reader.read(1);
if (secondChar == '=')
{
return makeSymbolToken(ParseType.RANGLE_EQUALS, 2);
}
if (secondChar == '>')
{
int thirdChar = reader.read(2);
if (thirdChar == '=')
{
return makeSymbolToken(ParseType.DOUBLE_RANGLE_EQUALS, 3);
}
if (thirdChar == '>')
{
int fourthChar = reader.read(3);
if (fourthChar == '=')
{
return makeSymbolToken(ParseType.TRIPLE_RANGLE_EQUALS, 4);
}
return makeSymbolToken(ParseType.TRIPLE_RANGLE, 3);
}
return makeSymbolToken(ParseType.DOUBLE_RANGLE, 2);
}
return makeSymbolToken(ParseType.RANGLE, 1);
}
if (nextChar == '=')
{
int secondChar = reader.read(1);
if (secondChar == '=')
{
return makeSymbolToken(ParseType.DOUBLE_EQUALS, 2);
}
return makeSymbolToken(ParseType.EQUALS, 1);
}
if (nextChar == '.')
{
int secondChar = reader.read(1);
if (secondChar == '.')
{
int thirdChar = reader.read(2);
if (thirdChar == '.')
{
return makeSymbolToken(ParseType.ELLIPSIS, 3);
}
}
return makeSymbolToken(ParseType.DOT, 1);
}
if (nextChar == '@')
{
return makeSymbolToken(ParseType.AT, 1);
}
if (nextChar == ':')
{
return makeSymbolToken(ParseType.COLON, 1);
}
if (nextChar == ',')
{
return makeSymbolToken(ParseType.COMMA, 1);
}
if (nextChar == '!')
{
int secondChar = reader.read(1);
if (secondChar == '=')
{
return makeSymbolToken(ParseType.EXCLAIMATION_MARK_EQUALS, 2);
}
return makeSymbolToken(ParseType.EXCLAIMATION_MARK, 1);
}
if (nextChar == '/')
{
int secondChar = reader.read(1);
if (secondChar == '=')
{
return makeSymbolToken(ParseType.FORWARD_SLASH_EQUALS, 2);
}
return makeSymbolToken(ParseType.FORWARD_SLASH, 1);
}
if (nextChar == '#')
{
return makeSymbolToken(ParseType.HASH, 1);
}
if (nextChar == '{')
{
return makeSymbolToken(ParseType.LBRACE, 1);
}
if (nextChar == '(')
{
return makeSymbolToken(ParseType.LPAREN, 1);
}
if (nextChar == '[')
{
return makeSymbolToken(ParseType.LSQUARE, 1);
}
if (nextChar == '%')
{
int secondChar = reader.read(1);
if (secondChar == '=')
{
return makeSymbolToken(ParseType.PERCENT_EQUALS, 2);
}
return makeSymbolToken(ParseType.PERCENT, 1);
}
if (nextChar == '?')
{
return makeSymbolToken(ParseType.QUESTION_MARK, 1);
}
if (nextChar == '}')
{
return makeSymbolToken(ParseType.RBRACE, 1);
}
if (nextChar == ')')
{
return makeSymbolToken(ParseType.RPAREN, 1);
}
if (nextChar == ']')
{
return makeSymbolToken(ParseType.RSQUARE, 1);
}
if (nextChar == ';')
{
return makeSymbolToken(ParseType.SEMICOLON, 1);
}
if (nextChar == '*')
{
int secondChar = reader.read(1);
if (secondChar == '=')
{
return makeSymbolToken(ParseType.STAR_EQUALS, 2);
}
return makeSymbolToken(ParseType.STAR, 1);
}
if (nextChar == '~')
{
return makeSymbolToken(ParseType.TILDE, 1);
}
// underscore is not handled here, as it is a special case of a name
// none of the symbols matched, so return null
return null;
}
|
diff --git a/src/story/book/view/OnlineStoriesActivity.java b/src/story/book/view/OnlineStoriesActivity.java
index c3223bb..c74d740 100644
--- a/src/story/book/view/OnlineStoriesActivity.java
+++ b/src/story/book/view/OnlineStoriesActivity.java
@@ -1,257 +1,259 @@
/* CMPUT301F13T06-Adventure Club: A choose-your-own-adventure story platform
* Copyright (C) 2013 Alexander Cheung, Jessica Surya, Vina Nguyen, Anthony Ou,
* Nancy Pham-Nguyen
*
* 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
* 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.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package story.book.view;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
import story.book.view.R;
import story.book.controller.OnlineStoryController;
import story.book.controller.StoryController;
import story.book.model.Story;
import story.book.model.StoryInfo;
import android.os.Bundle;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.SearchView.OnQueryTextListener;
import android.widget.SimpleAdapter;
import android.support.v4.app.NavUtils;
/**
* Activity that allows the user to view stories from an available list of
* stories online and download them to their local stories list.
* It uses a controller called OnlineStoryController.
*
* @author Nancy Pham-Nguyen
* @author Anthony Ou
*/
public class OnlineStoriesActivity extends Activity implements StoryView<Story>{
ListView listView;
ArrayList<StoryInfo> storyInfo;
ArrayList<HashMap<String, String>> sList;
SimpleAdapter sAdapter;
SearchView searchView;
private OnlineStoryController onlineController;
//protected ArrayAdapter<StoryInfo> adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.library_activity);
onlineController = new OnlineStoryController();
sList = new ArrayList<HashMap<String,String>>();
//adapter = new ArrayAdapter<StoryInfo>(this, android.R.layout.simple_list_item_1, onlineController.getStoryList());
listView = (ListView) findViewById(R.id.listView);
refreshList(onlineController.getStoryList());
registerForContextMenu(listView);
listView.setOnItemClickListener(new OnItemClickListener() {
/*
* on click of an online story to display the story info immdiately.
*/
@Override
public void onItemClick
(AdapterView<?> parent , View view, int pos, long id) {
//onlineController.getStory(adapter.getItem(pos).getSID());
onlineController.getStory(getFromAdapter(pos));
readStory();
}});
Button luckyButton = (Button) findViewById(R.id.luckyButton);
luckyButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(sAdapter.getCount() > 0) {
//onlineController.getStory(adapter.getItem( new Random().nextInt(adapter.getCount())).getSID());
+ onlineController.getStory(getFromAdapter(new Random()
+ .nextInt(sAdapter.getCount())));
readStory();
}
}
});
// Show the Up button in the action bar.
setupActionBar();
}
/**
* Displays the list of local stories.
*/
public void refreshList(ArrayList<StoryInfo> storyList) {
sList.clear();
for (StoryInfo storyInfo : storyList) {
HashMap<String, String> item = new HashMap<String, String>();
item.put("Title", storyInfo.getTitle());
item.put("Author", storyInfo.getAuthor());
item.put("Date", storyInfo.getPublishDateString());
item.put("SID", String.valueOf(storyInfo.getSID()));
sList.add(item);
}
String[] from = new String[] {"Title", "Author", "Date", "SID"};
int[] to = new int[] {R.id.listItem1, R.id.listItem2, R.id.listItem3};
sAdapter = new SimpleAdapter(this, sList, R.layout.stories_list, from, to);
listView.setAdapter(sAdapter);
}
private int getFromAdapter(int pos){
return Integer.parseInt(((HashMap<String,String>) sAdapter.getItem(pos)).get("SID"));
}
/**
* Method that is called when a user chooses to read the story
*
* @param SID
*/
public void readStory() {
Intent intent = new Intent(this, StoryInfoActivity.class);
intent.putExtra("calledByOnline", false);
startActivity(intent);
}
@Override
public void onResume() {
super.onResume();
//adapter.clear();
//adapter.addAll(onlineController.getStoryList());
refreshList(onlineController.getStoryList());
}
/**
* Set up the {@link android.app.ActionBar}.
*/
private void setupActionBar() {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
/**
* http://stackoverflow.com/questions/18832890/android-nullpointerexception-on-searchview-in-action-bar
* http://stackoverflow.com/questions/17874951/searchview-onquerytextsubmit-runs-twice-while-i-pressed-once
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.local_stories, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
searchView = (SearchView) menu.findItem(R.id.action_search)
.getActionView();
// Assumes current activity is the searchable activity
searchView.setSearchableInfo(searchManager
.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(true); //iconify the widget
searchView.setSubmitButtonEnabled(true);
handleSearch();
return true;
}
private void searchResults(String query){
//adapter.clear();
//show the list with just the search results
//adapter = new ArrayAdapter<StoryInfo>(this, android.R.layout.simple_list_item_1, onlineController.search(query));
//listView.setAdapter(adapter);
//refreshList(onlineController.getStoryList());
refreshList(onlineController.search(query));
}
private void handleSearch(){
searchView.setOnQueryTextListener(new OnQueryTextListener(){
@Override
public boolean onQueryTextChange(String newText) {
// TODO Auto-generated method stub
if(newText.isEmpty()){
//adapter.addAll(onlineController.getStoryList());
refreshList(onlineController.getStoryList());
return true;
}
else{
return false;
}
}
@Override
public boolean onQueryTextSubmit(String query) {
// TODO Auto-generated method stub
//Do something when the user selects the submit button
searchResults(query);
return true;
}
});
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.title_activity_dashboard:
NavUtils.navigateUpFromSameTask(this);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void update(Story model) {
// TODO Auto-generated method stub
}
}
| true | true | protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.library_activity);
onlineController = new OnlineStoryController();
sList = new ArrayList<HashMap<String,String>>();
//adapter = new ArrayAdapter<StoryInfo>(this, android.R.layout.simple_list_item_1, onlineController.getStoryList());
listView = (ListView) findViewById(R.id.listView);
refreshList(onlineController.getStoryList());
registerForContextMenu(listView);
listView.setOnItemClickListener(new OnItemClickListener() {
/*
* on click of an online story to display the story info immdiately.
*/
@Override
public void onItemClick
(AdapterView<?> parent , View view, int pos, long id) {
//onlineController.getStory(adapter.getItem(pos).getSID());
onlineController.getStory(getFromAdapter(pos));
readStory();
}});
Button luckyButton = (Button) findViewById(R.id.luckyButton);
luckyButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(sAdapter.getCount() > 0) {
//onlineController.getStory(adapter.getItem( new Random().nextInt(adapter.getCount())).getSID());
readStory();
}
}
});
// Show the Up button in the action bar.
setupActionBar();
}
| protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.library_activity);
onlineController = new OnlineStoryController();
sList = new ArrayList<HashMap<String,String>>();
//adapter = new ArrayAdapter<StoryInfo>(this, android.R.layout.simple_list_item_1, onlineController.getStoryList());
listView = (ListView) findViewById(R.id.listView);
refreshList(onlineController.getStoryList());
registerForContextMenu(listView);
listView.setOnItemClickListener(new OnItemClickListener() {
/*
* on click of an online story to display the story info immdiately.
*/
@Override
public void onItemClick
(AdapterView<?> parent , View view, int pos, long id) {
//onlineController.getStory(adapter.getItem(pos).getSID());
onlineController.getStory(getFromAdapter(pos));
readStory();
}});
Button luckyButton = (Button) findViewById(R.id.luckyButton);
luckyButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(sAdapter.getCount() > 0) {
//onlineController.getStory(adapter.getItem( new Random().nextInt(adapter.getCount())).getSID());
onlineController.getStory(getFromAdapter(new Random()
.nextInt(sAdapter.getCount())));
readStory();
}
}
});
// Show the Up button in the action bar.
setupActionBar();
}
|
diff --git a/user/src/com/google/gwt/user/client/ui/ScrollPanel.java b/user/src/com/google/gwt/user/client/ui/ScrollPanel.java
index e0a6ee735..765ddaf78 100644
--- a/user/src/com/google/gwt/user/client/ui/ScrollPanel.java
+++ b/user/src/com/google/gwt/user/client/ui/ScrollPanel.java
@@ -1,233 +1,234 @@
/*
* Copyright 2008 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.gwt.user.client.ui;
import com.google.gwt.event.dom.client.HasScrollHandlers;
import com.google.gwt.event.dom.client.ScrollEvent;
import com.google.gwt.event.dom.client.ScrollHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
/**
* A simple panel that wraps its contents in a scrollable area.
*/
@SuppressWarnings("deprecation")
public class ScrollPanel extends SimplePanel implements SourcesScrollEvents,
HasScrollHandlers, RequiresResize, ProvidesResize {
private Element containerElem;
/**
* Creates an empty scroll panel.
*/
public ScrollPanel() {
setAlwaysShowScrollBars(false);
containerElem = DOM.createDiv();
getElement().appendChild(containerElem);
// Prevent IE standard mode bug when a AbsolutePanel is contained.
+ DOM.setStyleAttribute(getElement(), "position", "relative");
DOM.setStyleAttribute(containerElem, "position", "relative");
// Hack to account for the IE6/7 scrolling bug described here:
// http://stackoverflow.com/questions/139000/div-with-overflowauto-and-a-100-wide-table-problem
DOM.setStyleAttribute(getElement(), "zoom", "1");
DOM.setStyleAttribute(containerElem, "zoom", "1");
}
/**
* Creates a new scroll panel with the given child widget.
*
* @param child the widget to be wrapped by the scroll panel
*/
public ScrollPanel(Widget child) {
this();
setWidget(child);
}
public HandlerRegistration addScrollHandler(ScrollHandler handler) {
return addDomHandler(handler, ScrollEvent.getType());
}
/**
* @deprecated Use {@link #addScrollHandler} instead
*/
@Deprecated
public void addScrollListener(ScrollListener listener) {
ListenerWrapper.WrappedScrollListener.add(this, listener);
}
/**
* Ensures that the specified item is visible, by adjusting the panel's scroll
* position.
*
* @param item the item whose visibility is to be ensured
*/
public void ensureVisible(UIObject item) {
Element scroll = getElement();
Element element = item.getElement();
ensureVisibleImpl(scroll, element);
}
/**
* Gets the horizontal scroll position.
*
* @return the horizontal scroll position, in pixels
*/
public int getHorizontalScrollPosition() {
return DOM.getElementPropertyInt(getElement(), "scrollLeft");
}
/**
* Gets the vertical scroll position.
*
* @return the vertical scroll position, in pixels
*/
public int getScrollPosition() {
return DOM.getElementPropertyInt(getElement(), "scrollTop");
}
public void onResize() {
Widget child = getWidget();
if ((child != null) && (child instanceof RequiresResize)) {
((RequiresResize) child).onResize();
}
}
/**
* @deprecated Use the {@link HandlerRegistration#removeHandler}
* method on the object returned by {@link #addScrollHandler} instead
*/
@Deprecated
public void removeScrollListener(ScrollListener listener) {
ListenerWrapper.WrappedScrollListener.remove(this, listener);
}
/**
* Scroll to the bottom of this panel.
*/
public void scrollToBottom() {
setScrollPosition(DOM.getElementPropertyInt(getElement(), "scrollHeight"));
}
/**
* Scroll to the far left of this panel.
*/
public void scrollToLeft() {
setHorizontalScrollPosition(0);
}
/**
* Scroll to the far right of this panel.
*/
public void scrollToRight() {
setHorizontalScrollPosition(DOM.getElementPropertyInt(getElement(),
"scrollWidth"));
}
/**
* Scroll to the top of this panel.
*/
public void scrollToTop() {
setScrollPosition(0);
}
/**
* Sets whether this panel always shows its scroll bars, or only when
* necessary.
*
* @param alwaysShow <code>true</code> to show scroll bars at all times
*/
public void setAlwaysShowScrollBars(boolean alwaysShow) {
DOM.setStyleAttribute(getElement(), "overflow", alwaysShow ? "scroll"
: "auto");
}
/**
* Sets the object's height. This height does not include decorations such as
* border, margin, and padding.
*
* @param height the object's new height, in absolute CSS units (e.g. "10px",
* "1em" but not "50%")
*/
@Override
public void setHeight(String height) {
super.setHeight(height);
}
/**
* Sets the horizontal scroll position.
*
* @param position the new horizontal scroll position, in pixels
*/
public void setHorizontalScrollPosition(int position) {
DOM.setElementPropertyInt(getElement(), "scrollLeft", position);
}
/**
* Sets the vertical scroll position.
*
* @param position the new vertical scroll position, in pixels
*/
public void setScrollPosition(int position) {
DOM.setElementPropertyInt(getElement(), "scrollTop", position);
}
/**
* Sets the object's size. This size does not include decorations such as
* border, margin, and padding.
*
* @param width the object's new width, in absolute CSS units (e.g. "10px",
* "1em", but not "50%")
* @param height the object's new height, in absolute CSS units (e.g. "10px",
* "1em", but not "50%")
*/
@Override
public void setSize(String width, String height) {
super.setSize(width, height);
}
/**
* Sets the object's width. This width does not include decorations such as
* border, margin, and padding.
*
* @param width the object's new width, in absolute CSS units (e.g. "10px",
* "1em", but not "50%")
*/
@Override
public void setWidth(String width) {
super.setWidth(width);
}
protected Element getContainerElement() {
return containerElem;
}
private native void ensureVisibleImpl(Element scroll, Element e) /*-{
if (!e)
return;
var item = e;
var realOffset = 0;
while (item && (item != scroll)) {
realOffset += item.offsetTop;
item = item.offsetParent;
}
scroll.scrollTop = realOffset - scroll.offsetHeight / 2;
}-*/;
}
| true | true | public ScrollPanel() {
setAlwaysShowScrollBars(false);
containerElem = DOM.createDiv();
getElement().appendChild(containerElem);
// Prevent IE standard mode bug when a AbsolutePanel is contained.
DOM.setStyleAttribute(containerElem, "position", "relative");
// Hack to account for the IE6/7 scrolling bug described here:
// http://stackoverflow.com/questions/139000/div-with-overflowauto-and-a-100-wide-table-problem
DOM.setStyleAttribute(getElement(), "zoom", "1");
DOM.setStyleAttribute(containerElem, "zoom", "1");
}
| public ScrollPanel() {
setAlwaysShowScrollBars(false);
containerElem = DOM.createDiv();
getElement().appendChild(containerElem);
// Prevent IE standard mode bug when a AbsolutePanel is contained.
DOM.setStyleAttribute(getElement(), "position", "relative");
DOM.setStyleAttribute(containerElem, "position", "relative");
// Hack to account for the IE6/7 scrolling bug described here:
// http://stackoverflow.com/questions/139000/div-with-overflowauto-and-a-100-wide-table-problem
DOM.setStyleAttribute(getElement(), "zoom", "1");
DOM.setStyleAttribute(containerElem, "zoom", "1");
}
|
diff --git a/src/contributions/resources/policymanager/src/java/org/wyona/yanel/impl/resources/policymanager/PolicyManagerResource.java b/src/contributions/resources/policymanager/src/java/org/wyona/yanel/impl/resources/policymanager/PolicyManagerResource.java
index 16ec6b477..b5f838c93 100644
--- a/src/contributions/resources/policymanager/src/java/org/wyona/yanel/impl/resources/policymanager/PolicyManagerResource.java
+++ b/src/contributions/resources/policymanager/src/java/org/wyona/yanel/impl/resources/policymanager/PolicyManagerResource.java
@@ -1,386 +1,386 @@
/*
* Copyright 2007 Wyona
*/
package org.wyona.yanel.impl.resources.policymanager;
import org.wyona.security.core.api.AccessManagementException;
import org.wyona.security.core.api.IdentityManager;
import org.wyona.security.core.api.Item;
import org.wyona.security.core.api.Policy;
import org.wyona.security.core.api.PolicyManager;
import org.wyona.security.core.api.User;
import org.wyona.yanel.core.attributes.viewable.View;
import org.wyona.yanel.core.util.PathUtil;
import org.wyona.yanel.impl.resources.BasicXMLResource;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
/**
* Resource which acts as interface for editing tools in order to update/edit access policies
*/
public class PolicyManagerResource extends BasicXMLResource {
private static final String REFRESH_USERS_RC_PROPERTY_NAME = "always-get-fresh-users";
private static Logger log = Logger.getLogger(PolicyManagerResource.class);
private static String PARAMETER_EDIT_PATH = "policy-path";
private static String PARAMETER_USECASE = "yanel.policy";
/**
* See src/webapp/global-resource-configs/policy-manager_yanel-rc.xml or realm specific
*/
@Override
public View getView(String viewId) throws Exception {
String policyRequestPara = getEnvironment().getRequest().getParameter("yanel.policy");
if (policyRequestPara.equals("update")) {
String getXML = getEnvironment().getRequest().getParameter("get");
String postXML = getEnvironment().getRequest().getParameter("post");
if (getXML != null) {
viewId = "get-xml";
} else if (postXML != null) {
viewId = "post-xml";
} else {
viewId = "editor";
}
} else {
viewId = "default"; // default is default anyway!
}
return getXMLView(viewId, getContentXML(viewId));
}
/**
*
*/
@Override
protected InputStream getContentXML(String viewId) throws Exception {
// For example ?policy-path=/foo/bar.html
String policyPath = request.getParameter(PARAMETER_EDIT_PATH);
if (policyPath == null) {
log.info("No policy path specified (e.g. ?policy-path=/foo/bar.html). Request path used as default: " + getPath());
policyPath = getPath();
}
// For example ?yanel.policy=read
String policyUsecase = "read";
if (request.getParameter(PARAMETER_USECASE) != null) {
policyUsecase = request.getParameter(PARAMETER_USECASE);
}
String backToRealm = org.wyona.yanel.core.util.PathUtil.backToRealm(getPath());
StringBuilder sb = new StringBuilder("");
try {
if (policyUsecase.equals("read")) {
// Either order by usecases or identities
String orderedByParam = request.getParameter("orderedBy");
int orderedBy = 0;
if (orderedByParam != null) orderedBy = new Integer(orderedByParam).intValue();
// Either show parent policies or do not show them
boolean showParents = false;
String showParentsParam = request.getParameter("showParents");
if (showParentsParam != null) showParents = new Boolean(showParentsParam).booleanValue();
// Either show tabs or do not show them
boolean showTabs = true;
String showTabsParam = request.getParameter("showTabs");
if (showTabsParam != null) showTabs = new Boolean(showTabsParam).booleanValue();
boolean showAbbreviatedLabels = false;
if (getResourceConfigProperty("show-abbreviated-labels") != null) showAbbreviatedLabels = Boolean.valueOf(getResourceConfigProperty("show-abbreviated-labels"));
sb.append(PolicyViewer.getXHTMLView(getRealm().getPolicyManager(), getRealm().getIdentityManager().getGroupManager(), getPath(), null, orderedBy, showParents, showTabs, showAbbreviatedLabels));
} else if (policyUsecase.equals("update")) {
String getXML = request.getParameter("get");
String postXML = request.getParameter("post");
if (getXML != null && getXML.equals("identities")) {
//response.setContentType("application/xml; charset=" + DEFAULT_ENCODING);
sb.append(getIdentitiesAndRightsAsXML(getRealm().getIdentityManager(), getRealm().getPolicyManager(), getRequestedLanguage()));
} else if (getXML != null && getXML.equals("policy")) {
//response.setContentType("application/xml; charset=" + DEFAULT_ENCODING);
sb.append(getPolicyAsXML(getRealm().getPolicyManager(), getPath()));
} else if (postXML != null && postXML.equals("policy")) {
//response.setContentType("application/xml; charset=" + DEFAULT_ENCODING);
try {
writePolicy(getEnvironment().getRequest().getInputStream(), getRealm().getPolicyManager(), getPath(), getRealm().getIdentityManager());
sb.append("<?xml version=\"1.0\"?><saved/>");
} catch(Exception e) {
log.error(e,e);
getEnvironment().getResponse().setStatus(HttpServletResponse.SC_NOT_IMPLEMENTED);
sb.append("<?xml version=\"1.0\"?><not-saved>" + e.getMessage() + "</not-saved>");
}
} else {
//response.setContentType("text/html; charset=" + DEFAULT_ENCODING);
String identitiesURL = backToRealm + getPath().substring(1) + "?yanel.policy=update&get=identities";
String policyURL = backToRealm + getPath().substring(1) + "?yanel.policy=update&get=policy";
String saveURL = backToRealm + getPath().substring(1) + "?yanel.policy=update&post=policy"; // This doesn't seem to work with all browsers!
String cancelURL = getReferer(backToRealm);
log.warn("DEBUG: Cancel URL: " + cancelURL);
sb.append("<?xml version=\"1.0\"?>");
sb.append("<html xmlns=\"http://www.w3.org/1999/xhtml\">");
sb.append("<head>");
sb.append("<title>Edit Access Policy</title>");
sb.append("<meta name=\"generator\" content=\"" + this.getClass().getName() + "\"/>");
- sb.append("<link rel=\"stylesheet\" href=\"" + PathUtil.getResourcesHtdocsPath(this) + "js/accesspolicyeditor/style.css\" type=\"text/css\"/>");
+ sb.append("<link rel=\"stylesheet\" href=\"" + PathUtil.getResourcesHtdocsPath(this) + "org.wyona.security.gwt.accesspolicyeditor.AccessPolicyEditor/style.css\" type=\"text/css\"/>");
// IMPORTANT: Please make sure that the value of 'cancel-url-base-equals-host-page-url' corresponds with getReferer()
- sb.append("<script language=\"javascript\">var getURLs = {\"identities-url\": \"" + identitiesURL + "\", \"policy-url\": \"" + policyURL + "\", \"cancel-url\": \"" + cancelURL + "\", \"cancel-url-base-equals-host-page-url\": \"false\", \"save-url\": \"" + saveURL + "\"};</script><script language=\"javascript\" src=\"" + PathUtil.getResourcesHtdocsPath(this) + "js/accesspolicyeditor/org.wyona.security.gwt.accesspolicyeditor.AccessPolicyEditor.nocache.js\"></script>");
+ sb.append("<script language=\"javascript\">var getURLs = {\"identities-url\": \"" + identitiesURL + "\", \"policy-url\": \"" + policyURL + "\", \"cancel-url\": \"" + cancelURL + "\", \"cancel-url-base-equals-host-page-url\": \"false\", \"save-url\": \"" + saveURL + "\"};</script><script language=\"javascript\" src=\"" + PathUtil.getResourcesHtdocsPath(this) + "org.wyona.security.gwt.accesspolicyeditor.AccessPolicyEditor/org.wyona.security.gwt.accesspolicyeditor.AccessPolicyEditor.nocache.js\"></script>");
sb.append("</head>");
sb.append("<body><h1>Edit Access Policy</h1><p><div id=\"access-policy-editor-hook\"></div></p></body></html>");
}
} else {
//response.setContentType("text/html; charset=" + DEFAULT_ENCODING);
getEnvironment().getResponse().setStatus(HttpServletResponse.SC_NOT_IMPLEMENTED);
sb.append("<html><body>Policy usecase not implemented yet: " + policyUsecase + "</body></html>");
log.error("Policy usecase not implemented yet: " + policyUsecase);
}
} catch(Exception e) {
log.error(e, e);
throw new Exception(e.getMessage());
}
return new ByteArrayInputStream(sb.toString().getBytes("utf-8"));
}
/**
*
*/
private String getIdentitiesAndRightsAsXML(IdentityManager im, PolicyManager pm, String language) {
org.wyona.security.core.api.UserManager um = im.getUserManager();
org.wyona.security.core.api.GroupManager gm = im.getGroupManager();
StringBuffer sb = new StringBuffer("<?xml version=\"1.0\"?>");
sb.append("<access-control xmlns=\"http://www.wyona.org/security/1.0\">");
try {
boolean refreshUsers = true; // correctness trumps speed!
String refreshUsersText = getResourceConfigProperty(REFRESH_USERS_RC_PROPERTY_NAME);
if (refreshUsersText != null && "false".equals(refreshUsersText)) {
refreshUsers = false;
log.warn("Users will not be loaded afresh!");
}
User[] users = refreshUsers ? um.getUsers(true) : um.getUsers();
Arrays.sort(users, new ItemIDComparator());
sb.append("<users>");
for (int i = 0; i < users.length; i++) {
sb.append("<user id=\"" + users[i].getID() + "\">" + users[i].getName() + "</user>");
}
sb.append("</users>");
org.wyona.security.core.api.Group[] groups = gm.getGroups();
Arrays.sort(groups, new ItemIDComparator());
sb.append("<groups>");
for (int i = 0; i < groups.length; i++) {
sb.append("<group id=\"" + groups[i].getID() + "\">" + groups[i].getName() + "</group>");
}
sb.append("</groups>");
sb.append("<rights>");
String[] rights = pm.getUsecases();
if (rights != null) {
for (int i = 0; i < rights.length; i++) {
sb.append("<right id=\"" + rights[i] + "\">" + rights[i] + " (" + pm.getUsecaseLabel(rights[i], language) + ")</right>");
}
}
sb.append("</rights>");
} catch (Exception e) {
log.error(e, e);
sb.append("<exception>" + e.getMessage() + "</exception>");
}
sb.append("</access-control>");
return sb.toString();
}
public class ItemIDComparator implements Comparator<Item> {
public int compare(Item item1, Item item2) {
try {
String id1 = item1.getID();
String id2 = item2.getID();
return id1.compareToIgnoreCase(id2);
} catch (AccessManagementException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
}
/**
*
*/
private String getPolicyAsXML(PolicyManager pm, String path) {
StringBuffer sb = new StringBuffer("<?xml version=\"1.0\"?>");
try {
Policy policy = pm.getPolicy(path, false);
if (policy == null) {
String useInheritedPolicies = "false"; // For backwards compatibility (and security) reasons we set it to false
if (getResourceConfigProperty("use-inherited-policies-upon-creation") != null) {
useInheritedPolicies = getResourceConfigProperty("use-inherited-policies-upon-creation");
}
sb.append("<policy xmlns=\"http://www.wyona.org/security/1.0\" use-inherited-policies=\"" + useInheritedPolicies + "\">");
log.warn("No policy yet for path: " + path + " (Return empty policy)");
} else {
sb.append("<policy xmlns=\"http://www.wyona.org/security/1.0\" use-inherited-policies=\"" + policy.useInheritedPolicies() + "\">");
sb.append(getPolicyIdentities(policy));
sb.append(getPolicyGroups(policy));
}
} catch(Exception e) {
log.error(e, e);
sb.append("<policy xmlns=\"http://www.wyona.org/security/1.0\">");
sb.append("<exception>" + e.getMessage() + "</exception>");
}
sb.append("</policy>");
return sb.toString();
}
/**
* Get users (TODO: Move this code into the security package)
* XXX(?) REFACTORME this method seems suspiciously similar to {@link #getPolicyGroups(Policy)}...
*/
static public StringBuffer getPolicyIdentities(Policy p) {
List<String> world = new LinkedList<String>();
Map<String, List<String>> users = new HashMap<String, List<String>>();
org.wyona.security.core.UsecasePolicy[] up = p.getUsecasePolicies();
if (up != null && up.length > 0) {
for (int i = 0; i < up.length; i++) {
org.wyona.security.core.IdentityPolicy[] idps = up[i].getIdentityPolicies();
for (int j = 0; j < idps.length; j++) {
//log.debug("Usecase Identity Policy: " + up[i].getName() + ", " + idps[j].getIdentity().getUsername() + ", " + idps[j].getPermission());
if (idps[j].getIdentity().isWorld()) {
world.add(up[i].getName());
} else {
List<String> userRights;
if ((userRights = users.get(idps[j].getIdentity().getUsername())) != null) {
log.debug("User has already been added: " + idps[j].getIdentity().getUsername());
} else {
userRights = new LinkedList<String>();
users.put(idps[j].getIdentity().getUsername(), userRights);
}
if (idps[j].getPermission()) {
userRights.add(up[i].getName());
}
}
}
}
} else {
log.warn("No policy usecases!");
}
StringBuffer sb = new StringBuffer();
//sb.append("<li>WORLD (" + getCommaSeparatedList(world) + ")</li>");
for (String userName : users.keySet()) {
sb.append("<user id=\""+userName+"\">");
List<String> rights = users.get(userName);
for (String right : rights) {
// TODO: Do not hardcode permission
sb.append("<right id=\"" + right + "\" permission=\"true\"/>");
}
sb.append("</user>");
}
return sb;
}
/**
* Get groups (TODO: Move this code into the security package)
* XXX(?) REFACTORME this method seems suspiciously similar to {@link #getPolicyIdentities(Policy)}...
*/
static public StringBuffer getPolicyGroups(Policy p) {
Map<String, List<String>> groups = new HashMap<String, List<String>>();
org.wyona.security.core.UsecasePolicy[] up = p.getUsecasePolicies();
if (up != null && up.length > 0) {
for (int i = 0; i < up.length; i++) {
org.wyona.security.core.GroupPolicy[] ids = up[i].getGroupPolicies();
for (int j = 0; j < ids.length; j++) {
List<String> groupRights;
if ((groupRights = groups.get(ids[j].getId())) != null) {
log.debug("Group has already been added: " + ids[j].getId());
} else {
groupRights = new LinkedList<String>();
groups.put(ids[j].getId(), groupRights);
}
if (ids[j].getPermission()) {
groupRights.add(up[i].getName());
}
}
}
} else {
log.warn("No policy usecases!");
}
StringBuffer sb = new StringBuffer();
for (String userName : groups.keySet()) {
sb.append("<group id=\""+userName+"\">");
List<String> rights = groups.get(userName);
for (String right : rights) {
//TODO: Do not hardcode permission!
sb.append("<right id=\"" + right + "\" permission=\"true\"/>");
}
sb.append("</group>");
}
return sb;
}
/**
* Write/Save policy
*/
private void writePolicy(InputStream policyAsInputStream, PolicyManager pm, String path, IdentityManager im) throws Exception {
Policy policy = new org.wyona.security.util.PolicyParser().parseXML(policyAsInputStream, im);
pm.setPolicy(path, policy);
}
/**
* Get referer (also see org.wyona.yanel.impl.resources.ResourceCreatorResource#getReferer())
*/
private String getReferer(String backToRealm) throws Exception {
// IMPORTANT: Please make sure that the below corresponds with 'cancel-url-base-equals-host-page-url'
String referer = getEnvironment().getRequest().getHeader("Referer");
if(referer != null) {
java.net.URL url = new java.net.URL(referer);
String filenameQSWithoutLeadingSlash = url.getFile().substring(url.getFile().lastIndexOf("/") + 1);
log.warn("DEBUG: Manipulated referer: '" + filenameQSWithoutLeadingSlash + "'");
// IMPORTANT: The below might cause problems with certain reverse proxys, whereas with httpd and mod_proxy it seems to be fine. If this should be a problem, then either strip off the webapp and realm prefix, or use the host-page-url as base and submit a relative path using the filenameQSWithoutLeadingSlash
return replaceEntities(referer);
//return backToRealm + replaceEntities(url.getFile() + "?" + url.getQuery());
} else {
log.warn("No referer found!");
}
return getPath().substring(1); // Absolute
//return backToRealm + getPath().substring(1); // Relative
}
/**
* Replaces some characters by their corresponding xml entities.
* This method escapes those characters which must not occur in an xml text node.
* @param string
* @return escaped string
*/
private String replaceEntities(String str) {
// there may be some & and some & mixed in the input, so first transform all
// & to & and then transform all & back to &
// this way we don't get double escaped &amp;
str = str.replaceAll("&", "&");
str = str.replaceAll("&", "&");
str = str.replaceAll("<", "<");
return str;
}
}
| false | true | protected InputStream getContentXML(String viewId) throws Exception {
// For example ?policy-path=/foo/bar.html
String policyPath = request.getParameter(PARAMETER_EDIT_PATH);
if (policyPath == null) {
log.info("No policy path specified (e.g. ?policy-path=/foo/bar.html). Request path used as default: " + getPath());
policyPath = getPath();
}
// For example ?yanel.policy=read
String policyUsecase = "read";
if (request.getParameter(PARAMETER_USECASE) != null) {
policyUsecase = request.getParameter(PARAMETER_USECASE);
}
String backToRealm = org.wyona.yanel.core.util.PathUtil.backToRealm(getPath());
StringBuilder sb = new StringBuilder("");
try {
if (policyUsecase.equals("read")) {
// Either order by usecases or identities
String orderedByParam = request.getParameter("orderedBy");
int orderedBy = 0;
if (orderedByParam != null) orderedBy = new Integer(orderedByParam).intValue();
// Either show parent policies or do not show them
boolean showParents = false;
String showParentsParam = request.getParameter("showParents");
if (showParentsParam != null) showParents = new Boolean(showParentsParam).booleanValue();
// Either show tabs or do not show them
boolean showTabs = true;
String showTabsParam = request.getParameter("showTabs");
if (showTabsParam != null) showTabs = new Boolean(showTabsParam).booleanValue();
boolean showAbbreviatedLabels = false;
if (getResourceConfigProperty("show-abbreviated-labels") != null) showAbbreviatedLabels = Boolean.valueOf(getResourceConfigProperty("show-abbreviated-labels"));
sb.append(PolicyViewer.getXHTMLView(getRealm().getPolicyManager(), getRealm().getIdentityManager().getGroupManager(), getPath(), null, orderedBy, showParents, showTabs, showAbbreviatedLabels));
} else if (policyUsecase.equals("update")) {
String getXML = request.getParameter("get");
String postXML = request.getParameter("post");
if (getXML != null && getXML.equals("identities")) {
//response.setContentType("application/xml; charset=" + DEFAULT_ENCODING);
sb.append(getIdentitiesAndRightsAsXML(getRealm().getIdentityManager(), getRealm().getPolicyManager(), getRequestedLanguage()));
} else if (getXML != null && getXML.equals("policy")) {
//response.setContentType("application/xml; charset=" + DEFAULT_ENCODING);
sb.append(getPolicyAsXML(getRealm().getPolicyManager(), getPath()));
} else if (postXML != null && postXML.equals("policy")) {
//response.setContentType("application/xml; charset=" + DEFAULT_ENCODING);
try {
writePolicy(getEnvironment().getRequest().getInputStream(), getRealm().getPolicyManager(), getPath(), getRealm().getIdentityManager());
sb.append("<?xml version=\"1.0\"?><saved/>");
} catch(Exception e) {
log.error(e,e);
getEnvironment().getResponse().setStatus(HttpServletResponse.SC_NOT_IMPLEMENTED);
sb.append("<?xml version=\"1.0\"?><not-saved>" + e.getMessage() + "</not-saved>");
}
} else {
//response.setContentType("text/html; charset=" + DEFAULT_ENCODING);
String identitiesURL = backToRealm + getPath().substring(1) + "?yanel.policy=update&get=identities";
String policyURL = backToRealm + getPath().substring(1) + "?yanel.policy=update&get=policy";
String saveURL = backToRealm + getPath().substring(1) + "?yanel.policy=update&post=policy"; // This doesn't seem to work with all browsers!
String cancelURL = getReferer(backToRealm);
log.warn("DEBUG: Cancel URL: " + cancelURL);
sb.append("<?xml version=\"1.0\"?>");
sb.append("<html xmlns=\"http://www.w3.org/1999/xhtml\">");
sb.append("<head>");
sb.append("<title>Edit Access Policy</title>");
sb.append("<meta name=\"generator\" content=\"" + this.getClass().getName() + "\"/>");
sb.append("<link rel=\"stylesheet\" href=\"" + PathUtil.getResourcesHtdocsPath(this) + "js/accesspolicyeditor/style.css\" type=\"text/css\"/>");
// IMPORTANT: Please make sure that the value of 'cancel-url-base-equals-host-page-url' corresponds with getReferer()
sb.append("<script language=\"javascript\">var getURLs = {\"identities-url\": \"" + identitiesURL + "\", \"policy-url\": \"" + policyURL + "\", \"cancel-url\": \"" + cancelURL + "\", \"cancel-url-base-equals-host-page-url\": \"false\", \"save-url\": \"" + saveURL + "\"};</script><script language=\"javascript\" src=\"" + PathUtil.getResourcesHtdocsPath(this) + "js/accesspolicyeditor/org.wyona.security.gwt.accesspolicyeditor.AccessPolicyEditor.nocache.js\"></script>");
sb.append("</head>");
sb.append("<body><h1>Edit Access Policy</h1><p><div id=\"access-policy-editor-hook\"></div></p></body></html>");
}
} else {
//response.setContentType("text/html; charset=" + DEFAULT_ENCODING);
getEnvironment().getResponse().setStatus(HttpServletResponse.SC_NOT_IMPLEMENTED);
sb.append("<html><body>Policy usecase not implemented yet: " + policyUsecase + "</body></html>");
log.error("Policy usecase not implemented yet: " + policyUsecase);
}
} catch(Exception e) {
log.error(e, e);
throw new Exception(e.getMessage());
}
return new ByteArrayInputStream(sb.toString().getBytes("utf-8"));
}
| protected InputStream getContentXML(String viewId) throws Exception {
// For example ?policy-path=/foo/bar.html
String policyPath = request.getParameter(PARAMETER_EDIT_PATH);
if (policyPath == null) {
log.info("No policy path specified (e.g. ?policy-path=/foo/bar.html). Request path used as default: " + getPath());
policyPath = getPath();
}
// For example ?yanel.policy=read
String policyUsecase = "read";
if (request.getParameter(PARAMETER_USECASE) != null) {
policyUsecase = request.getParameter(PARAMETER_USECASE);
}
String backToRealm = org.wyona.yanel.core.util.PathUtil.backToRealm(getPath());
StringBuilder sb = new StringBuilder("");
try {
if (policyUsecase.equals("read")) {
// Either order by usecases or identities
String orderedByParam = request.getParameter("orderedBy");
int orderedBy = 0;
if (orderedByParam != null) orderedBy = new Integer(orderedByParam).intValue();
// Either show parent policies or do not show them
boolean showParents = false;
String showParentsParam = request.getParameter("showParents");
if (showParentsParam != null) showParents = new Boolean(showParentsParam).booleanValue();
// Either show tabs or do not show them
boolean showTabs = true;
String showTabsParam = request.getParameter("showTabs");
if (showTabsParam != null) showTabs = new Boolean(showTabsParam).booleanValue();
boolean showAbbreviatedLabels = false;
if (getResourceConfigProperty("show-abbreviated-labels") != null) showAbbreviatedLabels = Boolean.valueOf(getResourceConfigProperty("show-abbreviated-labels"));
sb.append(PolicyViewer.getXHTMLView(getRealm().getPolicyManager(), getRealm().getIdentityManager().getGroupManager(), getPath(), null, orderedBy, showParents, showTabs, showAbbreviatedLabels));
} else if (policyUsecase.equals("update")) {
String getXML = request.getParameter("get");
String postXML = request.getParameter("post");
if (getXML != null && getXML.equals("identities")) {
//response.setContentType("application/xml; charset=" + DEFAULT_ENCODING);
sb.append(getIdentitiesAndRightsAsXML(getRealm().getIdentityManager(), getRealm().getPolicyManager(), getRequestedLanguage()));
} else if (getXML != null && getXML.equals("policy")) {
//response.setContentType("application/xml; charset=" + DEFAULT_ENCODING);
sb.append(getPolicyAsXML(getRealm().getPolicyManager(), getPath()));
} else if (postXML != null && postXML.equals("policy")) {
//response.setContentType("application/xml; charset=" + DEFAULT_ENCODING);
try {
writePolicy(getEnvironment().getRequest().getInputStream(), getRealm().getPolicyManager(), getPath(), getRealm().getIdentityManager());
sb.append("<?xml version=\"1.0\"?><saved/>");
} catch(Exception e) {
log.error(e,e);
getEnvironment().getResponse().setStatus(HttpServletResponse.SC_NOT_IMPLEMENTED);
sb.append("<?xml version=\"1.0\"?><not-saved>" + e.getMessage() + "</not-saved>");
}
} else {
//response.setContentType("text/html; charset=" + DEFAULT_ENCODING);
String identitiesURL = backToRealm + getPath().substring(1) + "?yanel.policy=update&get=identities";
String policyURL = backToRealm + getPath().substring(1) + "?yanel.policy=update&get=policy";
String saveURL = backToRealm + getPath().substring(1) + "?yanel.policy=update&post=policy"; // This doesn't seem to work with all browsers!
String cancelURL = getReferer(backToRealm);
log.warn("DEBUG: Cancel URL: " + cancelURL);
sb.append("<?xml version=\"1.0\"?>");
sb.append("<html xmlns=\"http://www.w3.org/1999/xhtml\">");
sb.append("<head>");
sb.append("<title>Edit Access Policy</title>");
sb.append("<meta name=\"generator\" content=\"" + this.getClass().getName() + "\"/>");
sb.append("<link rel=\"stylesheet\" href=\"" + PathUtil.getResourcesHtdocsPath(this) + "org.wyona.security.gwt.accesspolicyeditor.AccessPolicyEditor/style.css\" type=\"text/css\"/>");
// IMPORTANT: Please make sure that the value of 'cancel-url-base-equals-host-page-url' corresponds with getReferer()
sb.append("<script language=\"javascript\">var getURLs = {\"identities-url\": \"" + identitiesURL + "\", \"policy-url\": \"" + policyURL + "\", \"cancel-url\": \"" + cancelURL + "\", \"cancel-url-base-equals-host-page-url\": \"false\", \"save-url\": \"" + saveURL + "\"};</script><script language=\"javascript\" src=\"" + PathUtil.getResourcesHtdocsPath(this) + "org.wyona.security.gwt.accesspolicyeditor.AccessPolicyEditor/org.wyona.security.gwt.accesspolicyeditor.AccessPolicyEditor.nocache.js\"></script>");
sb.append("</head>");
sb.append("<body><h1>Edit Access Policy</h1><p><div id=\"access-policy-editor-hook\"></div></p></body></html>");
}
} else {
//response.setContentType("text/html; charset=" + DEFAULT_ENCODING);
getEnvironment().getResponse().setStatus(HttpServletResponse.SC_NOT_IMPLEMENTED);
sb.append("<html><body>Policy usecase not implemented yet: " + policyUsecase + "</body></html>");
log.error("Policy usecase not implemented yet: " + policyUsecase);
}
} catch(Exception e) {
log.error(e, e);
throw new Exception(e.getMessage());
}
return new ByteArrayInputStream(sb.toString().getBytes("utf-8"));
}
|
diff --git a/core-task-impl/src/main/java/org/cytoscape/task/internal/CyActivator.java b/core-task-impl/src/main/java/org/cytoscape/task/internal/CyActivator.java
index 236bece33..a5d1293e4 100644
--- a/core-task-impl/src/main/java/org/cytoscape/task/internal/CyActivator.java
+++ b/core-task-impl/src/main/java/org/cytoscape/task/internal/CyActivator.java
@@ -1,1679 +1,1680 @@
package org.cytoscape.task.internal;
/*
* #%L
* Cytoscape Core Task Impl (core-task-impl)
* $Id:$
* $HeadURL:$
* %%
* Copyright (C) 2006 - 2013 The Cytoscape Consortium
* %%
* This program 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 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 Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import static org.cytoscape.work.ServiceProperties.ACCELERATOR;
import static org.cytoscape.work.ServiceProperties.COMMAND;
import static org.cytoscape.work.ServiceProperties.COMMAND_NAMESPACE;
import static org.cytoscape.work.ServiceProperties.ENABLE_FOR;
import static org.cytoscape.work.ServiceProperties.ID;
import static org.cytoscape.work.ServiceProperties.INSERT_SEPARATOR_AFTER;
import static org.cytoscape.work.ServiceProperties.IN_MENU_BAR;
import static org.cytoscape.work.ServiceProperties.IN_NETWORK_PANEL_CONTEXT_MENU;
import static org.cytoscape.work.ServiceProperties.IN_CONTEXT_MENU;
import static org.cytoscape.work.ServiceProperties.IN_TOOL_BAR;
import static org.cytoscape.work.ServiceProperties.LARGE_ICON_URL;
import static org.cytoscape.work.ServiceProperties.MENU_GRAVITY;
import static org.cytoscape.work.ServiceProperties.NETWORK_GROUP_MENU;
import static org.cytoscape.work.ServiceProperties.NETWORK_SELECT_MENU;
import static org.cytoscape.work.ServiceProperties.NODE_ADD_MENU;
import static org.cytoscape.work.ServiceProperties.NODE_EDIT_MENU;
import static org.cytoscape.work.ServiceProperties.NODE_GROUP_MENU;
import static org.cytoscape.work.ServiceProperties.NODE_SELECT_MENU;
import static org.cytoscape.work.ServiceProperties.PREFERRED_ACTION;
import static org.cytoscape.work.ServiceProperties.PREFERRED_MENU;
import static org.cytoscape.work.ServiceProperties.TITLE;
import static org.cytoscape.work.ServiceProperties.TOOLTIP;
import static org.cytoscape.work.ServiceProperties.TOOL_BAR_GRAVITY;
import java.util.Properties;
import org.cytoscape.application.CyApplicationManager;
import org.cytoscape.event.CyEventHelper;
import org.cytoscape.group.CyGroupFactory;
import org.cytoscape.group.CyGroupManager;
import org.cytoscape.io.read.CyNetworkReaderManager;
import org.cytoscape.io.read.CySessionReaderManager;
import org.cytoscape.io.read.CyTableReaderManager;
import org.cytoscape.io.read.VizmapReaderManager;
import org.cytoscape.io.util.RecentlyOpenedTracker;
import org.cytoscape.io.util.StreamUtil;
import org.cytoscape.io.write.CyNetworkViewWriterManager;
import org.cytoscape.io.write.CySessionWriterManager;
import org.cytoscape.io.write.CyTableWriterManager;
import org.cytoscape.io.write.PresentationWriterManager;
import org.cytoscape.io.write.VizmapWriterManager;
import org.cytoscape.model.CyEdge;
import org.cytoscape.model.CyNetwork;
import org.cytoscape.model.CyNetworkFactory;
import org.cytoscape.model.CyNetworkManager;
import org.cytoscape.model.CyNetworkTableManager;
import org.cytoscape.model.CyNode;
import org.cytoscape.model.CyTableFactory;
import org.cytoscape.model.CyTableManager;
import org.cytoscape.model.subnetwork.CyRootNetworkManager;
import org.cytoscape.property.CyProperty;
import org.cytoscape.service.util.AbstractCyActivator;
import org.cytoscape.session.CyNetworkNaming;
import org.cytoscape.session.CySessionManager;
import org.cytoscape.task.NetworkCollectionTaskFactory;
import org.cytoscape.task.NetworkTaskFactory;
import org.cytoscape.task.NetworkViewCollectionTaskFactory;
import org.cytoscape.task.NetworkViewTaskFactory;
import org.cytoscape.task.NodeViewTaskFactory;
import org.cytoscape.task.TableCellTaskFactory;
import org.cytoscape.task.TableColumnTaskFactory;
import org.cytoscape.task.TableTaskFactory;
import org.cytoscape.task.create.CloneNetworkTaskFactory;
import org.cytoscape.task.create.CreateNetworkViewTaskFactory;
import org.cytoscape.task.create.NewEmptyNetworkViewFactory;
import org.cytoscape.task.internal.creation.NewNetworkCommandTaskFactory;
import org.cytoscape.task.create.NewNetworkSelectedNodesAndEdgesTaskFactory;
import org.cytoscape.task.create.NewNetworkSelectedNodesOnlyTaskFactory;
import org.cytoscape.task.create.NewSessionTaskFactory;
import org.cytoscape.task.destroy.DeleteColumnTaskFactory;
import org.cytoscape.task.destroy.DeleteSelectedNodesAndEdgesTaskFactory;
import org.cytoscape.task.destroy.DeleteTableTaskFactory;
import org.cytoscape.task.destroy.DestroyNetworkTaskFactory;
import org.cytoscape.task.destroy.DestroyNetworkViewTaskFactory;
import org.cytoscape.task.edit.CollapseGroupTaskFactory;
import org.cytoscape.task.edit.ConnectSelectedNodesTaskFactory;
import org.cytoscape.task.edit.EditNetworkTitleTaskFactory;
import org.cytoscape.task.edit.ExpandGroupTaskFactory;
import org.cytoscape.task.edit.GroupNodesTaskFactory;
import org.cytoscape.task.edit.MapGlobalToLocalTableTaskFactory;
import org.cytoscape.task.edit.MapTableToNetworkTablesTaskFactory;
import org.cytoscape.task.edit.RenameColumnTaskFactory;
import org.cytoscape.task.edit.ImportDataTableTaskFactory;
import org.cytoscape.task.edit.MergeDataTableTaskFactory;
import org.cytoscape.task.edit.UnGroupNodesTaskFactory;
import org.cytoscape.task.edit.UnGroupTaskFactory;
import org.cytoscape.task.hide.HideSelectedEdgesTaskFactory;
import org.cytoscape.task.hide.HideSelectedNodesTaskFactory;
import org.cytoscape.task.hide.HideSelectedTaskFactory;
import org.cytoscape.task.hide.UnHideAllEdgesTaskFactory;
import org.cytoscape.task.hide.UnHideAllNodesTaskFactory;
import org.cytoscape.task.hide.UnHideAllTaskFactory;
import org.cytoscape.task.internal.creation.CloneNetworkTaskFactoryImpl;
import org.cytoscape.task.internal.creation.CreateNetworkViewTaskFactoryImpl;
import org.cytoscape.task.internal.creation.NewEmptyNetworkTaskFactoryImpl;
import org.cytoscape.task.internal.creation.NewNetworkSelectedNodesEdgesTaskFactoryImpl;
import org.cytoscape.task.internal.creation.NewNetworkSelectedNodesOnlyTaskFactoryImpl;
import org.cytoscape.task.internal.destruction.DestroyNetworkTaskFactoryImpl;
import org.cytoscape.task.internal.destruction.DestroyNetworkViewTaskFactoryImpl;
import org.cytoscape.task.internal.edit.ConnectSelectedNodesTaskFactoryImpl;
import org.cytoscape.task.internal.export.graphics.ExportNetworkImageTaskFactoryImpl;
import org.cytoscape.task.internal.export.network.ExportNetworkViewTaskFactoryImpl;
import org.cytoscape.task.internal.export.table.ExportSelectedTableTaskFactoryImpl;
import org.cytoscape.task.internal.export.table.ExportTableTaskFactoryImpl;
import org.cytoscape.task.internal.export.vizmap.ExportVizmapTaskFactoryImpl;
import org.cytoscape.task.internal.group.AddToGroupTaskFactory;
import org.cytoscape.task.internal.group.ListGroupsTaskFactory;
import org.cytoscape.task.internal.group.RemoveFromGroupTaskFactory;
import org.cytoscape.task.internal.group.RenameGroupTaskFactory;
import org.cytoscape.task.internal.group.GroupNodeContextTaskFactoryImpl;
import org.cytoscape.task.internal.group.GroupNodesTaskFactoryImpl;
import org.cytoscape.task.internal.group.UnGroupNodesTaskFactoryImpl;
import org.cytoscape.task.internal.hide.HideSelectedEdgesTaskFactoryImpl;
import org.cytoscape.task.internal.hide.HideSelectedNodesTaskFactoryImpl;
import org.cytoscape.task.internal.hide.HideSelectedTaskFactoryImpl;
import org.cytoscape.task.internal.hide.HideTaskFactory;
import org.cytoscape.task.internal.hide.UnHideAllEdgesTaskFactoryImpl;
import org.cytoscape.task.internal.hide.UnHideAllNodesTaskFactoryImpl;
import org.cytoscape.task.internal.hide.UnHideAllTaskFactoryImpl;
import org.cytoscape.task.internal.hide.UnHideTaskFactory;
import org.cytoscape.task.internal.layout.ApplyPreferredLayoutTaskFactoryImpl;
import org.cytoscape.task.internal.layout.GetPreferredLayoutTaskFactory;
import org.cytoscape.task.internal.layout.SetPreferredLayoutTaskFactory;
import org.cytoscape.task.internal.loaddatatable.LoadAttributesFileTaskFactoryImpl;
import org.cytoscape.task.internal.loaddatatable.LoadAttributesURLTaskFactoryImpl;
import org.cytoscape.task.internal.loaddatatable.ImportAttributesFileTaskFactoryImpl;
import org.cytoscape.task.internal.loaddatatable.ImportAttributesURLTaskFactoryImpl;
import org.cytoscape.task.internal.loadnetwork.LoadNetworkFileTaskFactoryImpl;
import org.cytoscape.task.internal.loadnetwork.LoadNetworkURLTaskFactoryImpl;
import org.cytoscape.task.internal.loadvizmap.LoadVizmapFileTaskFactoryImpl;
import org.cytoscape.task.internal.networkobjects.AddTaskFactory;
import org.cytoscape.task.internal.networkobjects.AddEdgeTaskFactory;
import org.cytoscape.task.internal.networkobjects.AddNodeTaskFactory;
import org.cytoscape.task.internal.networkobjects.DeleteSelectedNodesAndEdgesTaskFactoryImpl;
import org.cytoscape.task.internal.networkobjects.GetEdgeTaskFactory;
import org.cytoscape.task.internal.networkobjects.GetNetworkTaskFactory;
import org.cytoscape.task.internal.networkobjects.GetNodeTaskFactory;
import org.cytoscape.task.internal.networkobjects.GetPropertiesTaskFactory;
import org.cytoscape.task.internal.networkobjects.ListEdgesTaskFactory;
import org.cytoscape.task.internal.networkobjects.ListNetworksTaskFactory;
import org.cytoscape.task.internal.networkobjects.ListNodesTaskFactory;
import org.cytoscape.task.internal.networkobjects.ListPropertiesTaskFactory;
import org.cytoscape.task.internal.networkobjects.RenameEdgeTaskFactory;
import org.cytoscape.task.internal.networkobjects.RenameNodeTaskFactory;
import org.cytoscape.task.internal.networkobjects.SetCurrentNetworkTaskFactory;
import org.cytoscape.task.internal.networkobjects.SetPropertiesTaskFactory;
import org.cytoscape.task.internal.proxysettings.ProxySettingsTaskFactoryImpl;
import org.cytoscape.task.internal.select.DeselectAllEdgesTaskFactoryImpl;
import org.cytoscape.task.internal.select.DeselectAllNodesTaskFactoryImpl;
import org.cytoscape.task.internal.select.DeselectAllTaskFactoryImpl;
import org.cytoscape.task.internal.select.DeselectTaskFactory;
import org.cytoscape.task.internal.select.InvertSelectedEdgesTaskFactoryImpl;
import org.cytoscape.task.internal.select.InvertSelectedNodesTaskFactoryImpl;
import org.cytoscape.task.internal.select.SelectAdjacentEdgesTaskFactoryImpl;
import org.cytoscape.task.internal.select.SelectAllEdgesTaskFactoryImpl;
import org.cytoscape.task.internal.select.SelectAllNodesTaskFactoryImpl;
import org.cytoscape.task.internal.select.SelectAllTaskFactoryImpl;
import org.cytoscape.task.internal.select.SelectConnectedNodesTaskFactoryImpl;
import org.cytoscape.task.internal.select.SelectFirstNeighborsNodeViewTaskFactoryImpl;
import org.cytoscape.task.internal.select.SelectFirstNeighborsTaskFactoryImpl;
import org.cytoscape.task.internal.select.SelectFromFileListTaskFactoryImpl;
import org.cytoscape.task.internal.select.SelectTaskFactory;
import org.cytoscape.task.internal.session.NewSessionTaskFactoryImpl;
import org.cytoscape.task.internal.session.OpenSessionCommandTaskFactory;
import org.cytoscape.task.internal.session.OpenSessionTaskFactoryImpl;
import org.cytoscape.task.internal.session.SaveSessionAsTaskFactoryImpl;
import org.cytoscape.task.internal.session.SaveSessionTaskFactoryImpl;
import org.cytoscape.task.internal.table.AddRowTaskFactory;
import org.cytoscape.task.internal.table.CopyValueToColumnTaskFactoryImpl;
import org.cytoscape.task.internal.table.CreateColumnTaskFactory;
import org.cytoscape.task.internal.table.CreateNetworkAttributeTaskFactory;
import org.cytoscape.task.internal.table.CreateTableTaskFactory;
import org.cytoscape.task.internal.table.DeleteColumnTaskFactoryImpl;
import org.cytoscape.task.internal.table.DeleteColumnCommandTaskFactory;
import org.cytoscape.task.internal.table.DeleteRowTaskFactory;
import org.cytoscape.task.internal.table.DeleteTableTaskFactoryImpl;
import org.cytoscape.task.internal.table.DestroyTableTaskFactory;
import org.cytoscape.task.internal.table.GetColumnTaskFactory;
import org.cytoscape.task.internal.table.GetNetworkAttributeTaskFactory;
import org.cytoscape.task.internal.table.GetRowTaskFactory;
import org.cytoscape.task.internal.table.GetValueTaskFactory;
import org.cytoscape.task.internal.table.ListNetworkAttributesTaskFactory;
import org.cytoscape.task.internal.table.ListColumnsTaskFactory;
import org.cytoscape.task.internal.table.ListRowsTaskFactory;
import org.cytoscape.task.internal.table.ListTablesTaskFactory;
import org.cytoscape.task.internal.table.MapGlobalToLocalTableTaskFactoryImpl;
import org.cytoscape.task.internal.table.MapTableToNetworkTablesTaskFactoryImpl;
import org.cytoscape.task.internal.table.RenameColumnTaskFactoryImpl;
import org.cytoscape.task.internal.table.ImportDataTableTaskFactoryImpl;
import org.cytoscape.task.internal.table.MergeDataTableTaskFactoryImpl;
import org.cytoscape.task.internal.table.SetNetworkAttributeTaskFactory;
import org.cytoscape.task.internal.table.SetTableTitleTaskFactory;
import org.cytoscape.task.internal.table.SetValuesTaskFactory;
import org.cytoscape.task.internal.title.EditNetworkTitleTaskFactoryImpl;
import org.cytoscape.task.internal.view.GetCurrentNetworkViewTaskFactory;
import org.cytoscape.task.internal.view.ListNetworkViewsTaskFactory;
import org.cytoscape.task.internal.view.SetCurrentNetworkViewTaskFactory;
import org.cytoscape.task.internal.view.UpdateNetworkViewTaskFactory;
import org.cytoscape.task.internal.vizmap.ApplyVisualStyleTaskFactoryimpl;
import org.cytoscape.task.internal.vizmap.ClearEdgeBendTaskFactory;
import org.cytoscape.task.internal.zoom.FitContentTaskFactory;
import org.cytoscape.task.internal.zoom.FitSelectedTaskFactory;
import org.cytoscape.task.internal.zoom.ZoomInTaskFactory;
import org.cytoscape.task.internal.zoom.ZoomOutTaskFactory;
import org.cytoscape.task.read.LoadNetworkFileTaskFactory;
import org.cytoscape.task.read.LoadNetworkURLTaskFactory;
import org.cytoscape.task.read.LoadTableFileTaskFactory;
import org.cytoscape.task.read.ImportTableURLTaskFactory;
import org.cytoscape.task.read.ImportTableFileTaskFactory;
import org.cytoscape.task.read.LoadTableURLTaskFactory;
import org.cytoscape.task.read.LoadVizmapFileTaskFactory;
import org.cytoscape.task.read.OpenSessionTaskFactory;
import org.cytoscape.task.select.DeselectAllEdgesTaskFactory;
import org.cytoscape.task.select.DeselectAllNodesTaskFactory;
import org.cytoscape.task.select.DeselectAllTaskFactory;
import org.cytoscape.task.select.InvertSelectedEdgesTaskFactory;
import org.cytoscape.task.select.InvertSelectedNodesTaskFactory;
import org.cytoscape.task.select.SelectAdjacentEdgesTaskFactory;
import org.cytoscape.task.select.SelectAllEdgesTaskFactory;
import org.cytoscape.task.select.SelectAllNodesTaskFactory;
import org.cytoscape.task.select.SelectAllTaskFactory;
import org.cytoscape.task.select.SelectConnectedNodesTaskFactory;
import org.cytoscape.task.select.SelectFirstNeighborsNodeViewTaskFactory;
import org.cytoscape.task.select.SelectFirstNeighborsTaskFactory;
import org.cytoscape.task.select.SelectFromFileListTaskFactory;
import org.cytoscape.task.visualize.ApplyPreferredLayoutTaskFactory;
import org.cytoscape.task.visualize.ApplyVisualStyleTaskFactory;
import org.cytoscape.task.write.ExportNetworkImageTaskFactory;
import org.cytoscape.task.write.ExportNetworkViewTaskFactory;
import org.cytoscape.task.write.ExportSelectedTableTaskFactory;
import org.cytoscape.task.write.ExportTableTaskFactory;
import org.cytoscape.task.write.ExportVizmapTaskFactory;
import org.cytoscape.task.write.SaveSessionAsTaskFactory;
import org.cytoscape.view.layout.CyLayoutAlgorithmManager;
import org.cytoscape.view.model.CyNetworkViewFactory;
import org.cytoscape.view.model.CyNetworkViewManager;
import org.cytoscape.view.presentation.RenderingEngineManager;
import org.cytoscape.view.vizmap.VisualMappingManager;
import org.cytoscape.work.ServiceProperties;
import org.cytoscape.work.SynchronousTaskManager;
import org.cytoscape.work.TaskFactory;
import org.cytoscape.work.TunableSetter;
import org.cytoscape.work.undo.UndoSupport;
import org.osgi.framework.BundleContext;
public class CyActivator extends AbstractCyActivator {
public CyActivator() {
super();
}
public void start(BundleContext bc) {
CyEventHelper cyEventHelperRef = getService(bc,CyEventHelper.class);
RecentlyOpenedTracker recentlyOpenedTrackerServiceRef = getService(bc,RecentlyOpenedTracker.class);
CyNetworkNaming cyNetworkNamingServiceRef = getService(bc,CyNetworkNaming.class);
UndoSupport undoSupportServiceRef = getService(bc,UndoSupport.class);
CyNetworkViewFactory cyNetworkViewFactoryServiceRef = getService(bc,CyNetworkViewFactory.class);
CyNetworkFactory cyNetworkFactoryServiceRef = getService(bc,CyNetworkFactory.class);
CyRootNetworkManager cyRootNetworkFactoryServiceRef = getService(bc,CyRootNetworkManager.class);
CyNetworkReaderManager cyNetworkReaderManagerServiceRef = getService(bc,CyNetworkReaderManager.class);
CyTableReaderManager cyDataTableReaderManagerServiceRef = getService(bc,CyTableReaderManager.class);
VizmapReaderManager vizmapReaderManagerServiceRef = getService(bc,VizmapReaderManager.class);
VisualMappingManager visualMappingManagerServiceRef = getService(bc,VisualMappingManager.class);
StreamUtil streamUtilRef = getService(bc,StreamUtil.class);
PresentationWriterManager viewWriterManagerServiceRef = getService(bc,PresentationWriterManager.class);
CyNetworkViewWriterManager networkViewWriterManagerServiceRef = getService(bc,CyNetworkViewWriterManager.class);
VizmapWriterManager vizmapWriterManagerServiceRef = getService(bc,VizmapWriterManager.class);
CySessionWriterManager sessionWriterManagerServiceRef = getService(bc,CySessionWriterManager.class);
CySessionReaderManager sessionReaderManagerServiceRef = getService(bc,CySessionReaderManager.class);
CyNetworkManager cyNetworkManagerServiceRef = getService(bc,CyNetworkManager.class);
CyNetworkViewManager cyNetworkViewManagerServiceRef = getService(bc,CyNetworkViewManager.class);
CyApplicationManager cyApplicationManagerServiceRef = getService(bc,CyApplicationManager.class);
CySessionManager cySessionManagerServiceRef = getService(bc,CySessionManager.class);
CyProperty cyPropertyServiceRef = getService(bc,CyProperty.class,"(cyPropertyName=cytoscape3.props)");
CyTableFactory cyTableFactoryServiceRef = getService(bc,CyTableFactory.class);
CyTableManager cyTableManagerServiceRef = getService(bc,CyTableManager.class);
CyLayoutAlgorithmManager cyLayoutsServiceRef = getService(bc,CyLayoutAlgorithmManager.class);
CyTableWriterManager cyTableWriterManagerRef = getService(bc,CyTableWriterManager.class);
SynchronousTaskManager<?> synchronousTaskManagerServiceRef = getService(bc,SynchronousTaskManager.class);
TunableSetter tunableSetterServiceRef = getService(bc,TunableSetter.class);
CyRootNetworkManager rootNetworkManagerServiceRef = getService(bc, CyRootNetworkManager.class);
CyNetworkTableManager cyNetworkTableManagerServiceRef = getService(bc, CyNetworkTableManager.class);
RenderingEngineManager renderingEngineManagerServiceRef = getService(bc, RenderingEngineManager.class);
CyNetworkViewFactory nullNetworkViewFactory = getService(bc, CyNetworkViewFactory.class, "(id=NullCyNetworkViewFactory)");
CyGroupManager cyGroupManager = getService(bc, CyGroupManager.class);
CyGroupFactory cyGroupFactory = getService(bc, CyGroupFactory.class);
LoadVizmapFileTaskFactoryImpl loadVizmapFileTaskFactory = new LoadVizmapFileTaskFactoryImpl(vizmapReaderManagerServiceRef,visualMappingManagerServiceRef,synchronousTaskManagerServiceRef, tunableSetterServiceRef);
LoadNetworkFileTaskFactoryImpl loadNetworkFileTaskFactory = new LoadNetworkFileTaskFactoryImpl(cyNetworkReaderManagerServiceRef,cyNetworkManagerServiceRef,cyNetworkViewManagerServiceRef,cyPropertyServiceRef,cyNetworkNamingServiceRef, tunableSetterServiceRef, visualMappingManagerServiceRef, nullNetworkViewFactory);
LoadNetworkURLTaskFactoryImpl loadNetworkURLTaskFactory = new LoadNetworkURLTaskFactoryImpl(cyNetworkReaderManagerServiceRef,cyNetworkManagerServiceRef,cyNetworkViewManagerServiceRef,cyPropertyServiceRef,cyNetworkNamingServiceRef,streamUtilRef, synchronousTaskManagerServiceRef, tunableSetterServiceRef, visualMappingManagerServiceRef, nullNetworkViewFactory);
DeleteSelectedNodesAndEdgesTaskFactoryImpl deleteSelectedNodesAndEdgesTaskFactory = new DeleteSelectedNodesAndEdgesTaskFactoryImpl(cyApplicationManagerServiceRef, undoSupportServiceRef,cyNetworkViewManagerServiceRef,visualMappingManagerServiceRef,cyEventHelperRef);
SelectAllTaskFactoryImpl selectAllTaskFactory = new SelectAllTaskFactoryImpl(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef);
SelectAllEdgesTaskFactoryImpl selectAllEdgesTaskFactory = new SelectAllEdgesTaskFactoryImpl(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef);
SelectAllNodesTaskFactoryImpl selectAllNodesTaskFactory = new SelectAllNodesTaskFactoryImpl(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef);
SelectAdjacentEdgesTaskFactoryImpl selectAdjacentEdgesTaskFactory = new SelectAdjacentEdgesTaskFactoryImpl(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef);
SelectConnectedNodesTaskFactoryImpl selectConnectedNodesTaskFactory = new SelectConnectedNodesTaskFactoryImpl(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef);
SelectFirstNeighborsTaskFactoryImpl selectFirstNeighborsTaskFactory = new SelectFirstNeighborsTaskFactoryImpl(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef, CyEdge.Type.ANY);
SelectFirstNeighborsTaskFactoryImpl selectFirstNeighborsTaskFactoryInEdge = new SelectFirstNeighborsTaskFactoryImpl(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef, CyEdge.Type.INCOMING);
SelectFirstNeighborsTaskFactoryImpl selectFirstNeighborsTaskFactoryOutEdge = new SelectFirstNeighborsTaskFactoryImpl(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef, CyEdge.Type.OUTGOING);
DeselectAllTaskFactoryImpl deselectAllTaskFactory = new DeselectAllTaskFactoryImpl(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef);
DeselectAllEdgesTaskFactoryImpl deselectAllEdgesTaskFactory = new DeselectAllEdgesTaskFactoryImpl(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef);
DeselectAllNodesTaskFactoryImpl deselectAllNodesTaskFactory = new DeselectAllNodesTaskFactoryImpl(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef);
InvertSelectedEdgesTaskFactoryImpl invertSelectedEdgesTaskFactory = new InvertSelectedEdgesTaskFactoryImpl(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef);
InvertSelectedNodesTaskFactoryImpl invertSelectedNodesTaskFactory = new InvertSelectedNodesTaskFactoryImpl(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef);
SelectFromFileListTaskFactoryImpl selectFromFileListTaskFactory = new SelectFromFileListTaskFactoryImpl(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef, tunableSetterServiceRef);
SelectFirstNeighborsNodeViewTaskFactoryImpl selectFirstNeighborsNodeViewTaskFactory = new SelectFirstNeighborsNodeViewTaskFactoryImpl(CyEdge.Type.ANY);
HideSelectedTaskFactoryImpl hideSelectedTaskFactory = new HideSelectedTaskFactoryImpl(undoSupportServiceRef,cyEventHelperRef,visualMappingManagerServiceRef);
HideSelectedNodesTaskFactoryImpl hideSelectedNodesTaskFactory = new HideSelectedNodesTaskFactoryImpl(undoSupportServiceRef,cyEventHelperRef,visualMappingManagerServiceRef);
HideSelectedEdgesTaskFactoryImpl hideSelectedEdgesTaskFactory = new HideSelectedEdgesTaskFactoryImpl(undoSupportServiceRef,cyEventHelperRef,visualMappingManagerServiceRef);
UnHideAllTaskFactoryImpl unHideAllTaskFactory = new UnHideAllTaskFactoryImpl(undoSupportServiceRef,cyEventHelperRef,visualMappingManagerServiceRef);
UnHideAllNodesTaskFactoryImpl unHideAllNodesTaskFactory = new UnHideAllNodesTaskFactoryImpl(undoSupportServiceRef,cyEventHelperRef,visualMappingManagerServiceRef);
UnHideAllEdgesTaskFactoryImpl unHideAllEdgesTaskFactory = new UnHideAllEdgesTaskFactoryImpl(undoSupportServiceRef,cyEventHelperRef,visualMappingManagerServiceRef);
NewEmptyNetworkTaskFactoryImpl newEmptyNetworkTaskFactory = new NewEmptyNetworkTaskFactoryImpl(cyNetworkFactoryServiceRef,cyNetworkViewFactoryServiceRef,cyNetworkManagerServiceRef,cyNetworkViewManagerServiceRef,cyNetworkNamingServiceRef,synchronousTaskManagerServiceRef,visualMappingManagerServiceRef, cyRootNetworkFactoryServiceRef, cyApplicationManagerServiceRef);
CloneNetworkTaskFactoryImpl cloneNetworkTaskFactory = new CloneNetworkTaskFactoryImpl(cyNetworkManagerServiceRef,cyNetworkViewManagerServiceRef,visualMappingManagerServiceRef,cyNetworkFactoryServiceRef,cyNetworkViewFactoryServiceRef,cyNetworkNamingServiceRef,cyApplicationManagerServiceRef,cyNetworkTableManagerServiceRef,rootNetworkManagerServiceRef,cyGroupManager,cyGroupFactory,renderingEngineManagerServiceRef, nullNetworkViewFactory );
NewNetworkSelectedNodesEdgesTaskFactoryImpl newNetworkSelectedNodesEdgesTaskFactory = new NewNetworkSelectedNodesEdgesTaskFactoryImpl(undoSupportServiceRef,cyRootNetworkFactoryServiceRef,cyNetworkViewFactoryServiceRef,cyNetworkManagerServiceRef,cyNetworkViewManagerServiceRef,cyNetworkNamingServiceRef,visualMappingManagerServiceRef,cyApplicationManagerServiceRef,cyEventHelperRef,cyGroupManager,renderingEngineManagerServiceRef);
NewNetworkCommandTaskFactory newNetworkCommandTaskFactory = new NewNetworkCommandTaskFactory(undoSupportServiceRef,cyRootNetworkFactoryServiceRef,cyNetworkViewFactoryServiceRef,cyNetworkManagerServiceRef,cyNetworkViewManagerServiceRef,cyNetworkNamingServiceRef,visualMappingManagerServiceRef,cyApplicationManagerServiceRef,cyEventHelperRef,cyGroupManager,renderingEngineManagerServiceRef);
NewNetworkSelectedNodesOnlyTaskFactoryImpl newNetworkSelectedNodesOnlyTaskFactory = new NewNetworkSelectedNodesOnlyTaskFactoryImpl(undoSupportServiceRef,cyRootNetworkFactoryServiceRef,cyNetworkViewFactoryServiceRef,cyNetworkManagerServiceRef,cyNetworkViewManagerServiceRef,cyNetworkNamingServiceRef,visualMappingManagerServiceRef,cyApplicationManagerServiceRef,cyEventHelperRef,cyGroupManager,renderingEngineManagerServiceRef);
DestroyNetworkTaskFactoryImpl destroyNetworkTaskFactory = new DestroyNetworkTaskFactoryImpl(cyNetworkManagerServiceRef);
DestroyNetworkViewTaskFactoryImpl destroyNetworkViewTaskFactory = new DestroyNetworkViewTaskFactoryImpl(cyNetworkViewManagerServiceRef);
ZoomInTaskFactory zoomInTaskFactory = new ZoomInTaskFactory(undoSupportServiceRef, cyApplicationManagerServiceRef);
ZoomOutTaskFactory zoomOutTaskFactory = new ZoomOutTaskFactory(undoSupportServiceRef, cyApplicationManagerServiceRef);
FitSelectedTaskFactory fitSelectedTaskFactory = new FitSelectedTaskFactory(undoSupportServiceRef, cyApplicationManagerServiceRef);
FitContentTaskFactory fitContentTaskFactory = new FitContentTaskFactory(undoSupportServiceRef, cyApplicationManagerServiceRef);
NewSessionTaskFactoryImpl newSessionTaskFactory = new NewSessionTaskFactoryImpl(cySessionManagerServiceRef, tunableSetterServiceRef);
OpenSessionCommandTaskFactory openSessionCommandTaskFactory = new OpenSessionCommandTaskFactory(cySessionManagerServiceRef,sessionReaderManagerServiceRef,cyApplicationManagerServiceRef,cyNetworkManagerServiceRef,cyTableManagerServiceRef,cyNetworkTableManagerServiceRef,cyGroupManager,recentlyOpenedTrackerServiceRef);
OpenSessionTaskFactoryImpl openSessionTaskFactory = new OpenSessionTaskFactoryImpl(cySessionManagerServiceRef,sessionReaderManagerServiceRef,cyApplicationManagerServiceRef,cyNetworkManagerServiceRef,cyTableManagerServiceRef,cyNetworkTableManagerServiceRef,cyGroupManager,recentlyOpenedTrackerServiceRef,tunableSetterServiceRef);
SaveSessionTaskFactoryImpl saveSessionTaskFactory = new SaveSessionTaskFactoryImpl( sessionWriterManagerServiceRef, cySessionManagerServiceRef, recentlyOpenedTrackerServiceRef, cyEventHelperRef);
SaveSessionAsTaskFactoryImpl saveSessionAsTaskFactory = new SaveSessionAsTaskFactoryImpl( sessionWriterManagerServiceRef, cySessionManagerServiceRef, recentlyOpenedTrackerServiceRef, cyEventHelperRef, tunableSetterServiceRef);
ProxySettingsTaskFactoryImpl proxySettingsTaskFactory = new ProxySettingsTaskFactoryImpl(cyPropertyServiceRef, streamUtilRef);
EditNetworkTitleTaskFactoryImpl editNetworkTitleTaskFactory = new EditNetworkTitleTaskFactoryImpl(undoSupportServiceRef, cyNetworkManagerServiceRef, cyNetworkNamingServiceRef, tunableSetterServiceRef);
CreateNetworkViewTaskFactoryImpl createNetworkViewTaskFactory = new CreateNetworkViewTaskFactoryImpl(undoSupportServiceRef,cyNetworkViewFactoryServiceRef,cyNetworkViewManagerServiceRef,cyLayoutsServiceRef,cyEventHelperRef,visualMappingManagerServiceRef,renderingEngineManagerServiceRef,cyApplicationManagerServiceRef);
ExportNetworkImageTaskFactoryImpl exportNetworkImageTaskFactory = new ExportNetworkImageTaskFactoryImpl(viewWriterManagerServiceRef,cyApplicationManagerServiceRef);
ExportNetworkViewTaskFactoryImpl exportNetworkViewTaskFactory = new ExportNetworkViewTaskFactoryImpl(networkViewWriterManagerServiceRef, tunableSetterServiceRef);
ExportSelectedTableTaskFactoryImpl exportCurrentTableTaskFactory = new ExportSelectedTableTaskFactoryImpl(cyTableWriterManagerRef, cyTableManagerServiceRef, cyNetworkManagerServiceRef);
ApplyPreferredLayoutTaskFactoryImpl applyPreferredLayoutTaskFactory = new ApplyPreferredLayoutTaskFactoryImpl(cyApplicationManagerServiceRef, cyNetworkViewManagerServiceRef, cyLayoutsServiceRef,cyPropertyServiceRef);
DeleteColumnTaskFactoryImpl deleteColumnTaskFactory = new DeleteColumnTaskFactoryImpl(undoSupportServiceRef);
RenameColumnTaskFactoryImpl renameColumnTaskFactory = new RenameColumnTaskFactoryImpl(undoSupportServiceRef, tunableSetterServiceRef);
CopyValueToColumnTaskFactoryImpl copyValueToEntireColumnTaskFactory = new CopyValueToColumnTaskFactoryImpl(undoSupportServiceRef, false, "Apply to entire column");
CopyValueToColumnTaskFactoryImpl copyValueToSelectedNodesTaskFactory = new CopyValueToColumnTaskFactoryImpl(undoSupportServiceRef, true, "Apply to selected nodes");
CopyValueToColumnTaskFactoryImpl copyValueToSelectedEdgesTaskFactory = new CopyValueToColumnTaskFactoryImpl(undoSupportServiceRef, true, "Apply to selected edges");
DeleteTableTaskFactoryImpl deleteTableTaskFactory = new DeleteTableTaskFactoryImpl(cyTableManagerServiceRef);
ExportVizmapTaskFactoryImpl exportVizmapTaskFactory = new ExportVizmapTaskFactoryImpl(vizmapWriterManagerServiceRef,visualMappingManagerServiceRef, tunableSetterServiceRef);
ConnectSelectedNodesTaskFactoryImpl connectSelectedNodesTaskFactory = new ConnectSelectedNodesTaskFactoryImpl(undoSupportServiceRef, cyEventHelperRef, visualMappingManagerServiceRef, cyNetworkViewManagerServiceRef);
MapGlobalToLocalTableTaskFactoryImpl mapGlobal = new MapGlobalToLocalTableTaskFactoryImpl(cyTableManagerServiceRef, cyNetworkManagerServiceRef, tunableSetterServiceRef);
DynamicTaskFactoryProvisionerImpl dynamicTaskFactoryProvisionerImpl = new DynamicTaskFactoryProvisionerImpl(cyApplicationManagerServiceRef);
registerAllServices(bc, dynamicTaskFactoryProvisionerImpl, new Properties());
LoadAttributesFileTaskFactoryImpl loadAttrsFileTaskFactory = new LoadAttributesFileTaskFactoryImpl(cyDataTableReaderManagerServiceRef, tunableSetterServiceRef,cyNetworkManagerServiceRef, cyTableManagerServiceRef, rootNetworkManagerServiceRef );
LoadAttributesURLTaskFactoryImpl loadAttrsURLTaskFactory = new LoadAttributesURLTaskFactoryImpl(cyDataTableReaderManagerServiceRef, tunableSetterServiceRef, cyNetworkManagerServiceRef, cyTableManagerServiceRef, rootNetworkManagerServiceRef);
ImportAttributesFileTaskFactoryImpl importAttrsFileTaskFactory = new ImportAttributesFileTaskFactoryImpl(cyDataTableReaderManagerServiceRef, tunableSetterServiceRef,cyNetworkManagerServiceRef, cyTableManagerServiceRef, rootNetworkManagerServiceRef );
ImportAttributesURLTaskFactoryImpl importAttrsURLTaskFactory = new ImportAttributesURLTaskFactoryImpl(cyDataTableReaderManagerServiceRef, tunableSetterServiceRef, cyNetworkManagerServiceRef, cyTableManagerServiceRef, rootNetworkManagerServiceRef);
MergeDataTableTaskFactoryImpl mergeTableTaskFactory = new MergeDataTableTaskFactoryImpl( cyTableManagerServiceRef,cyNetworkManagerServiceRef,tunableSetterServiceRef, rootNetworkManagerServiceRef );
// Apply Visual Style Task
ApplyVisualStyleTaskFactoryimpl applyVisualStyleTaskFactory = new ApplyVisualStyleTaskFactoryimpl(visualMappingManagerServiceRef);
Properties applyVisualStyleProps = new Properties();
applyVisualStyleProps.setProperty(ID,"applyVisualStyleTaskFactory");
applyVisualStyleProps.setProperty(TITLE, "Apply Visual Style");
applyVisualStyleProps.setProperty(COMMAND,"apply");
applyVisualStyleProps.setProperty(COMMAND_NAMESPACE,"vizmap");
applyVisualStyleProps.setProperty(IN_NETWORK_PANEL_CONTEXT_MENU,"true");
applyVisualStyleProps.setProperty(ENABLE_FOR,"networkAndView");
registerService(bc, applyVisualStyleTaskFactory, NetworkViewCollectionTaskFactory.class, applyVisualStyleProps);
registerService(bc, applyVisualStyleTaskFactory, ApplyVisualStyleTaskFactory.class, applyVisualStyleProps);
// Clear edge bends
ClearEdgeBendTaskFactory clearEdgeBendTaskFactory = new ClearEdgeBendTaskFactory();
Properties clearEdgeBendProps = new Properties();
clearEdgeBendProps.setProperty(ID, "clearEdgeBendTaskFactory");
clearEdgeBendProps.setProperty(TITLE, "Clear Edge Bends");
clearEdgeBendProps.setProperty(IN_NETWORK_PANEL_CONTEXT_MENU, "true");
clearEdgeBendProps.setProperty(ENABLE_FOR, "networkAndView");
clearEdgeBendProps.setProperty(PREFERRED_MENU,"Layout");
clearEdgeBendProps.setProperty(MENU_GRAVITY,"0.1");
registerService(bc, clearEdgeBendTaskFactory, NetworkViewCollectionTaskFactory.class, clearEdgeBendProps);
Properties mapGlobalProps = new Properties();
/* mapGlobalProps.setProperty(ID,"mapGlobalToLocalTableTaskFactory");
mapGlobalProps.setProperty(PREFERRED_MENU,"Tools");
mapGlobalProps.setProperty(ACCELERATOR,"cmd m");
mapGlobalProps.setProperty(TITLE, "Map Table to Attributes");
mapGlobalProps.setProperty(MENU_GRAVITY,"1.0");
mapGlobalProps.setProperty(TOOL_BAR_GRAVITY,"3.0");
mapGlobalProps.setProperty(IN_TOOL_BAR,"false");
mapGlobalProps.setProperty(COMMAND,"map-global-to-local");
mapGlobalProps.setProperty(COMMAND_NAMESPACE,"table");
*/ registerService(bc, mapGlobal, TableTaskFactory.class, mapGlobalProps);
registerService(bc, mapGlobal, MapGlobalToLocalTableTaskFactory.class, mapGlobalProps);
Properties loadNetworkFileTaskFactoryProps = new Properties();
loadNetworkFileTaskFactoryProps.setProperty(ID,"loadNetworkFileTaskFactory");
loadNetworkFileTaskFactoryProps.setProperty(PREFERRED_MENU,"File.Import.Network");
loadNetworkFileTaskFactoryProps.setProperty(ACCELERATOR,"cmd l");
loadNetworkFileTaskFactoryProps.setProperty(TITLE,"File...");
loadNetworkFileTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"network");
loadNetworkFileTaskFactoryProps.setProperty(COMMAND,"load file");
loadNetworkFileTaskFactoryProps.setProperty(MENU_GRAVITY,"1.0");
loadNetworkFileTaskFactoryProps.setProperty(TOOL_BAR_GRAVITY,"3.0");
loadNetworkFileTaskFactoryProps.setProperty(LARGE_ICON_URL,getClass().getResource("/images/icons/net_file_import.png").toString());
loadNetworkFileTaskFactoryProps.setProperty(IN_TOOL_BAR,"true");
loadNetworkFileTaskFactoryProps.setProperty(TOOLTIP,"Import Network From File");
registerService(bc, loadNetworkFileTaskFactory, TaskFactory.class, loadNetworkFileTaskFactoryProps);
registerService(bc, loadNetworkFileTaskFactory, LoadNetworkFileTaskFactory.class, loadNetworkFileTaskFactoryProps);
Properties loadNetworkURLTaskFactoryProps = new Properties();
loadNetworkURLTaskFactoryProps.setProperty(ID,"loadNetworkURLTaskFactory");
loadNetworkURLTaskFactoryProps.setProperty(PREFERRED_MENU,"File.Import.Network");
loadNetworkURLTaskFactoryProps.setProperty(ACCELERATOR,"cmd shift l");
loadNetworkURLTaskFactoryProps.setProperty(MENU_GRAVITY,"2.0");
loadNetworkURLTaskFactoryProps.setProperty(TOOL_BAR_GRAVITY,"3.1");
loadNetworkURLTaskFactoryProps.setProperty(TITLE,"URL...");
loadNetworkURLTaskFactoryProps.setProperty(LARGE_ICON_URL,getClass().getResource("/images/icons/net_url_import.png").toString());
loadNetworkURLTaskFactoryProps.setProperty(IN_TOOL_BAR,"true");
loadNetworkURLTaskFactoryProps.setProperty(TOOLTIP,"Import Network From URL");
loadNetworkURLTaskFactoryProps.setProperty(COMMAND,"load url");
loadNetworkURLTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"network");
registerService(bc, loadNetworkURLTaskFactory, TaskFactory.class, loadNetworkURLTaskFactoryProps);
registerService(bc, loadNetworkURLTaskFactory, LoadNetworkURLTaskFactory.class, loadNetworkURLTaskFactoryProps);
Properties loadVizmapFileTaskFactoryProps = new Properties();
loadVizmapFileTaskFactoryProps.setProperty(PREFERRED_MENU,"File.Import");
loadVizmapFileTaskFactoryProps.setProperty(MENU_GRAVITY,"3.0");
loadVizmapFileTaskFactoryProps.setProperty(TITLE,"Vizmap File...");
loadVizmapFileTaskFactoryProps.setProperty(COMMAND,"load file");
loadVizmapFileTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"vizmap");
registerService(bc,loadVizmapFileTaskFactory,TaskFactory.class, loadVizmapFileTaskFactoryProps);
registerService(bc,loadVizmapFileTaskFactory,LoadVizmapFileTaskFactory.class, new Properties());
Properties importAttrsFileTaskFactoryProps = new Properties();
importAttrsFileTaskFactoryProps.setProperty(PREFERRED_MENU,"File.Import.Table");
importAttrsFileTaskFactoryProps.setProperty(MENU_GRAVITY,"1.1");
importAttrsFileTaskFactoryProps.setProperty(TOOL_BAR_GRAVITY,"3.2");
importAttrsFileTaskFactoryProps.setProperty(TITLE,"File...");
importAttrsFileTaskFactoryProps.setProperty(LARGE_ICON_URL,getClass().getResource("/images/icons/table_file_import.png").toString());
importAttrsFileTaskFactoryProps.setProperty(IN_TOOL_BAR,"true");
importAttrsFileTaskFactoryProps.setProperty(TOOLTIP,"Import Table From File");
importAttrsFileTaskFactoryProps.setProperty(COMMAND,"load file");
importAttrsFileTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"table");
importAttrsFileTaskFactoryProps.setProperty(ENABLE_FOR,"network");
registerService(bc,importAttrsFileTaskFactory,TaskFactory.class, importAttrsFileTaskFactoryProps);
registerService(bc,importAttrsFileTaskFactory,ImportTableFileTaskFactory.class, importAttrsFileTaskFactoryProps);
Properties importAttrsURLTaskFactoryProps = new Properties();
importAttrsURLTaskFactoryProps.setProperty(PREFERRED_MENU,"File.Import.Table");
importAttrsURLTaskFactoryProps.setProperty(MENU_GRAVITY,"1.2");
importAttrsURLTaskFactoryProps.setProperty(TOOL_BAR_GRAVITY,"3.3");
importAttrsURLTaskFactoryProps.setProperty(TITLE,"URL...");
importAttrsURLTaskFactoryProps.setProperty(LARGE_ICON_URL,getClass().getResource("/images/icons/table_url_import.png").toString());
importAttrsURLTaskFactoryProps.setProperty(IN_TOOL_BAR,"true");
importAttrsURLTaskFactoryProps.setProperty(TOOLTIP,"Import Table From URL");
importAttrsURLTaskFactoryProps.setProperty(COMMAND,"load url");
importAttrsURLTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"table");
importAttrsURLTaskFactoryProps.setProperty(ENABLE_FOR,"network");
registerService(bc,importAttrsURLTaskFactory,TaskFactory.class, importAttrsURLTaskFactoryProps);
registerService(bc,importAttrsURLTaskFactory,ImportTableURLTaskFactory.class, importAttrsURLTaskFactoryProps);
Properties proxySettingsTaskFactoryProps = new Properties();
proxySettingsTaskFactoryProps.setProperty(PREFERRED_MENU,"Edit.Preferences");
proxySettingsTaskFactoryProps.setProperty(MENU_GRAVITY,"1.0");
proxySettingsTaskFactoryProps.setProperty(TITLE,"Proxy Settings...");
registerService(bc,proxySettingsTaskFactory,TaskFactory.class, proxySettingsTaskFactoryProps);
Properties deleteSelectedNodesAndEdgesTaskFactoryProps = new Properties();
deleteSelectedNodesAndEdgesTaskFactoryProps.setProperty(PREFERRED_MENU,"Edit");
deleteSelectedNodesAndEdgesTaskFactoryProps.setProperty(ENABLE_FOR,"selectedNodesOrEdges");
deleteSelectedNodesAndEdgesTaskFactoryProps.setProperty(TITLE,"Delete Selected Nodes and Edges...");
deleteSelectedNodesAndEdgesTaskFactoryProps.setProperty(MENU_GRAVITY,"5.0");
deleteSelectedNodesAndEdgesTaskFactoryProps.setProperty(ACCELERATOR,"DELETE");
deleteSelectedNodesAndEdgesTaskFactoryProps.setProperty(COMMAND,"delete");
deleteSelectedNodesAndEdgesTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"network");
registerService(bc,deleteSelectedNodesAndEdgesTaskFactory,NetworkTaskFactory.class, deleteSelectedNodesAndEdgesTaskFactoryProps);
registerService(bc,deleteSelectedNodesAndEdgesTaskFactory,DeleteSelectedNodesAndEdgesTaskFactory.class, deleteSelectedNodesAndEdgesTaskFactoryProps);
Properties selectAllTaskFactoryProps = new Properties();
selectAllTaskFactoryProps.setProperty(PREFERRED_MENU,"Select");
selectAllTaskFactoryProps.setProperty(ACCELERATOR,"cmd alt a");
selectAllTaskFactoryProps.setProperty(ENABLE_FOR,"network");
selectAllTaskFactoryProps.setProperty(TITLE,"Select all nodes and edges");
selectAllTaskFactoryProps.setProperty(MENU_GRAVITY,"5.0");
selectAllTaskFactoryProps.setProperty(PREFERRED_ACTION, "NEW");
// selectAllTaskFactoryProps.setProperty(COMMAND,"select all");
// selectAllTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"network");
registerService(bc,selectAllTaskFactory,NetworkTaskFactory.class, selectAllTaskFactoryProps);
registerService(bc,selectAllTaskFactory,SelectAllTaskFactory.class, selectAllTaskFactoryProps);
Properties selectAllViewTaskFactoryProps = new Properties();
selectAllViewTaskFactoryProps.setProperty(PREFERRED_MENU, NETWORK_SELECT_MENU);
selectAllViewTaskFactoryProps.setProperty(ENABLE_FOR,"networkAndView");
selectAllViewTaskFactoryProps.setProperty(TITLE,"All nodes and edges");
selectAllViewTaskFactoryProps.setProperty(MENU_GRAVITY,"1.1");
selectAllViewTaskFactoryProps.setProperty(PREFERRED_ACTION, "NEW");
selectAllViewTaskFactoryProps.setProperty(IN_MENU_BAR,"false");
registerService(bc,selectAllTaskFactory,NetworkViewTaskFactory.class, selectAllViewTaskFactoryProps);
Properties selectAllEdgesTaskFactoryProps = new Properties();
selectAllEdgesTaskFactoryProps.setProperty(PREFERRED_MENU,"Select.Edges");
selectAllEdgesTaskFactoryProps.setProperty(ACCELERATOR,"cmd alt a");
selectAllEdgesTaskFactoryProps.setProperty(ENABLE_FOR,"network");
selectAllEdgesTaskFactoryProps.setProperty(TITLE,"Select all edges");
selectAllEdgesTaskFactoryProps.setProperty(MENU_GRAVITY,"4.0");
registerService(bc,selectAllEdgesTaskFactory,NetworkTaskFactory.class, selectAllEdgesTaskFactoryProps);
registerService(bc,selectAllEdgesTaskFactory,SelectAllEdgesTaskFactory.class, selectAllEdgesTaskFactoryProps);
Properties selectAllNodesTaskFactoryProps = new Properties();
selectAllNodesTaskFactoryProps.setProperty(ENABLE_FOR,"network");
selectAllNodesTaskFactoryProps.setProperty(PREFERRED_MENU,"Select.Nodes");
selectAllNodesTaskFactoryProps.setProperty(MENU_GRAVITY,"4.0");
selectAllNodesTaskFactoryProps.setProperty(ACCELERATOR,"cmd a");
selectAllNodesTaskFactoryProps.setProperty(TITLE,"Select all nodes");
registerService(bc,selectAllNodesTaskFactory,NetworkTaskFactory.class, selectAllNodesTaskFactoryProps);
registerService(bc,selectAllNodesTaskFactory,SelectAllNodesTaskFactory.class, selectAllNodesTaskFactoryProps);
Properties selectAdjacentEdgesTaskFactoryProps = new Properties();
selectAdjacentEdgesTaskFactoryProps.setProperty(ENABLE_FOR,"network");
selectAdjacentEdgesTaskFactoryProps.setProperty(PREFERRED_MENU,"Select.Edges");
selectAdjacentEdgesTaskFactoryProps.setProperty(MENU_GRAVITY,"6.0");
selectAdjacentEdgesTaskFactoryProps.setProperty(ACCELERATOR,"alt e");
selectAdjacentEdgesTaskFactoryProps.setProperty(TITLE,"Select adjacent edges");
// selectAdjacentEdgesTaskFactoryProps.setProperty(COMMAND,"select adjacent");
// selectAdjacentEdgesTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"edge");
registerService(bc,selectAdjacentEdgesTaskFactory,NetworkTaskFactory.class, selectAdjacentEdgesTaskFactoryProps);
registerService(bc,selectAdjacentEdgesTaskFactory,SelectAdjacentEdgesTaskFactory.class, selectAdjacentEdgesTaskFactoryProps);
Properties selectConnectedNodesTaskFactoryProps = new Properties();
selectConnectedNodesTaskFactoryProps.setProperty(ENABLE_FOR,"network");
selectConnectedNodesTaskFactoryProps.setProperty(PREFERRED_MENU,"Select.Nodes");
selectConnectedNodesTaskFactoryProps.setProperty(MENU_GRAVITY,"7.0");
selectConnectedNodesTaskFactoryProps.setProperty(ACCELERATOR,"cmd 7");
selectConnectedNodesTaskFactoryProps.setProperty(TITLE,"Nodes connected by selected edges");
// selectConnectedNodesTaskFactoryProps.setProperty(COMMAND,"select by connected edges");
// selectConnectedNodesTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"node");
registerService(bc,selectConnectedNodesTaskFactory,NetworkTaskFactory.class, selectConnectedNodesTaskFactoryProps);
registerService(bc,selectConnectedNodesTaskFactory,SelectConnectedNodesTaskFactory.class, selectConnectedNodesTaskFactoryProps);
Properties selectFirstNeighborsTaskFactoryProps = new Properties();
selectFirstNeighborsTaskFactoryProps.setProperty(ENABLE_FOR,"selectedNodesOrEdges");
selectFirstNeighborsTaskFactoryProps.setProperty(PREFERRED_MENU,"Select.Nodes.First Neighbors of Selected Nodes");
selectFirstNeighborsTaskFactoryProps.setProperty(MENU_GRAVITY,"6.0");
selectFirstNeighborsTaskFactoryProps.setProperty(TOOL_BAR_GRAVITY,"9.15");
selectFirstNeighborsTaskFactoryProps.setProperty(ACCELERATOR,"cmd 6");
selectFirstNeighborsTaskFactoryProps.setProperty(TITLE,"Undirected");
selectFirstNeighborsTaskFactoryProps.setProperty(LARGE_ICON_URL,getClass().getResource("/images/icons/select_firstneighbors.png").toString());
selectFirstNeighborsTaskFactoryProps.setProperty(IN_TOOL_BAR,"true");
selectFirstNeighborsTaskFactoryProps.setProperty(TOOLTIP,"First Neighbors of Selected Nodes (Undirected)");
// selectFirstNeighborsTaskFactoryProps.setProperty(COMMAND,"select first neighbors undirected");
// selectFirstNeighborsTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"node");
registerService(bc,selectFirstNeighborsTaskFactory,NetworkTaskFactory.class, selectFirstNeighborsTaskFactoryProps);
registerService(bc,selectFirstNeighborsTaskFactory,SelectFirstNeighborsTaskFactory.class, selectFirstNeighborsTaskFactoryProps);
Properties selectFirstNeighborsTaskFactoryInEdgeProps = new Properties();
selectFirstNeighborsTaskFactoryInEdgeProps.setProperty(ENABLE_FOR,"network");
selectFirstNeighborsTaskFactoryInEdgeProps.setProperty(PREFERRED_MENU,"Select.Nodes.First Neighbors of Selected Nodes");
selectFirstNeighborsTaskFactoryInEdgeProps.setProperty(MENU_GRAVITY,"6.1");
selectFirstNeighborsTaskFactoryInEdgeProps.setProperty(TITLE,"Directed: Incoming");
selectFirstNeighborsTaskFactoryInEdgeProps.setProperty(TOOLTIP,"First Neighbors of Selected Nodes (Directed: Incoming)");
// selectFirstNeighborsTaskFactoryInEdgeProps.setProperty(COMMAND,"select first neighbors incoming");
// selectFirstNeighborsTaskFactoryInEdgeProps.setProperty(COMMAND_NAMESPACE,"node");
registerService(bc,selectFirstNeighborsTaskFactoryInEdge,NetworkTaskFactory.class, selectFirstNeighborsTaskFactoryInEdgeProps);
registerService(bc,selectFirstNeighborsTaskFactoryInEdge,SelectFirstNeighborsTaskFactory.class, selectFirstNeighborsTaskFactoryInEdgeProps);
Properties selectFirstNeighborsTaskFactoryOutEdgeProps = new Properties();
selectFirstNeighborsTaskFactoryOutEdgeProps.setProperty(ENABLE_FOR,"network");
selectFirstNeighborsTaskFactoryOutEdgeProps.setProperty(PREFERRED_MENU,"Select.Nodes.First Neighbors of Selected Nodes");
selectFirstNeighborsTaskFactoryOutEdgeProps.setProperty(MENU_GRAVITY,"6.2");
selectFirstNeighborsTaskFactoryOutEdgeProps.setProperty(TITLE,"Directed: Outgoing");
selectFirstNeighborsTaskFactoryOutEdgeProps.setProperty(TOOLTIP,"First Neighbors of Selected Nodes (Directed: Outgoing)");
// selectFirstNeighborsTaskFactoryOutEdgeProps.setProperty(COMMAND,"select first neighbors outgoing");
// selectFirstNeighborsTaskFactoryOutEdgeProps.setProperty(COMMAND_NAMESPACE,"node");
registerService(bc,selectFirstNeighborsTaskFactoryOutEdge,NetworkTaskFactory.class, selectFirstNeighborsTaskFactoryOutEdgeProps);
registerService(bc,selectFirstNeighborsTaskFactoryOutEdge,SelectFirstNeighborsTaskFactory.class, selectFirstNeighborsTaskFactoryOutEdgeProps);
Properties deselectAllTaskFactoryProps = new Properties();
deselectAllTaskFactoryProps.setProperty(ENABLE_FOR,"network");
deselectAllTaskFactoryProps.setProperty(PREFERRED_MENU,"Select");
deselectAllTaskFactoryProps.setProperty(MENU_GRAVITY,"5.1");
deselectAllTaskFactoryProps.setProperty(ACCELERATOR,"cmd shift alt a");
deselectAllTaskFactoryProps.setProperty(TITLE,"Deselect all nodes and edges");
// deselectAllTaskFactoryProps.setProperty(COMMAND,"deselect all");
// deselectAllTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"network");
registerService(bc,deselectAllTaskFactory,NetworkTaskFactory.class, deselectAllTaskFactoryProps);
registerService(bc,deselectAllTaskFactory,DeselectAllTaskFactory.class, deselectAllTaskFactoryProps);
Properties deselectAllEdgesTaskFactoryProps = new Properties();
deselectAllEdgesTaskFactoryProps.setProperty(ENABLE_FOR,"network");
deselectAllEdgesTaskFactoryProps.setProperty(PREFERRED_MENU,"Select.Edges");
deselectAllEdgesTaskFactoryProps.setProperty(MENU_GRAVITY,"5.0");
deselectAllEdgesTaskFactoryProps.setProperty(ACCELERATOR,"alt shift a");
deselectAllEdgesTaskFactoryProps.setProperty(TITLE,"Deselect all edges");
registerService(bc,deselectAllEdgesTaskFactory,NetworkTaskFactory.class, deselectAllEdgesTaskFactoryProps);
registerService(bc,deselectAllEdgesTaskFactory,DeselectAllEdgesTaskFactory.class, deselectAllEdgesTaskFactoryProps);
Properties deselectAllNodesTaskFactoryProps = new Properties();
deselectAllNodesTaskFactoryProps.setProperty(ENABLE_FOR,"network");
deselectAllNodesTaskFactoryProps.setProperty(PREFERRED_MENU,"Select.Nodes");
deselectAllNodesTaskFactoryProps.setProperty(MENU_GRAVITY,"5.0");
deselectAllNodesTaskFactoryProps.setProperty(ACCELERATOR,"cmd shift a");
deselectAllNodesTaskFactoryProps.setProperty(TITLE,"Deselect all nodes");
registerService(bc,deselectAllNodesTaskFactory,NetworkTaskFactory.class, deselectAllNodesTaskFactoryProps);
registerService(bc,deselectAllNodesTaskFactory,DeselectAllNodesTaskFactory.class, deselectAllNodesTaskFactoryProps);
Properties invertSelectedEdgesTaskFactoryProps = new Properties();
invertSelectedEdgesTaskFactoryProps.setProperty(ENABLE_FOR,"network");
invertSelectedEdgesTaskFactoryProps.setProperty(PREFERRED_MENU,"Select.Edges");
invertSelectedEdgesTaskFactoryProps.setProperty(MENU_GRAVITY,"1.0");
invertSelectedEdgesTaskFactoryProps.setProperty(ACCELERATOR,"alt i");
invertSelectedEdgesTaskFactoryProps.setProperty(TITLE,"Invert edge selection");
registerService(bc,invertSelectedEdgesTaskFactory,NetworkTaskFactory.class, invertSelectedEdgesTaskFactoryProps);
registerService(bc,invertSelectedEdgesTaskFactory,InvertSelectedEdgesTaskFactory.class, invertSelectedEdgesTaskFactoryProps);
Properties invertSelectedNodesTaskFactoryProps = new Properties();
invertSelectedNodesTaskFactoryProps.setProperty(ENABLE_FOR,"selectedNodes");
invertSelectedNodesTaskFactoryProps.setProperty(PREFERRED_MENU,"Select.Nodes");
invertSelectedNodesTaskFactoryProps.setProperty(MENU_GRAVITY,"1.0");
invertSelectedNodesTaskFactoryProps.setProperty(TOOL_BAR_GRAVITY,"9.2");
invertSelectedNodesTaskFactoryProps.setProperty(ACCELERATOR,"cmd i");
invertSelectedNodesTaskFactoryProps.setProperty(TITLE,"Invert node selection");
invertSelectedNodesTaskFactoryProps.setProperty(LARGE_ICON_URL,getClass().getResource("/images/icons/invert_selection.png").toString());
invertSelectedNodesTaskFactoryProps.setProperty(IN_TOOL_BAR,"false");
invertSelectedNodesTaskFactoryProps.setProperty(TOOLTIP,"Invert Node Selection");
registerService(bc,invertSelectedNodesTaskFactory,NetworkTaskFactory.class, invertSelectedNodesTaskFactoryProps);
registerService(bc,invertSelectedNodesTaskFactory,InvertSelectedNodesTaskFactory.class, invertSelectedNodesTaskFactoryProps);
Properties selectFromFileListTaskFactoryProps = new Properties();
selectFromFileListTaskFactoryProps.setProperty(ENABLE_FOR,"network");
selectFromFileListTaskFactoryProps.setProperty(PREFERRED_MENU,"Select.Nodes");
selectFromFileListTaskFactoryProps.setProperty(MENU_GRAVITY,"8.0");
selectFromFileListTaskFactoryProps.setProperty(ACCELERATOR,"cmd i");
selectFromFileListTaskFactoryProps.setProperty(TITLE,"From ID List file...");
selectFromFileListTaskFactoryProps.setProperty(COMMAND,"select from file");
selectFromFileListTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"node");
registerService(bc,selectFromFileListTaskFactory,NetworkTaskFactory.class, selectFromFileListTaskFactoryProps);
registerService(bc,selectFromFileListTaskFactory,SelectFromFileListTaskFactory.class, selectFromFileListTaskFactoryProps);
Properties selectFirstNeighborsNodeViewTaskFactoryProps = new Properties();
selectFirstNeighborsNodeViewTaskFactoryProps.setProperty(PREFERRED_MENU,NODE_SELECT_MENU);
selectFirstNeighborsNodeViewTaskFactoryProps.setProperty(MENU_GRAVITY,"1.0");
selectFirstNeighborsNodeViewTaskFactoryProps.setProperty(TITLE,"Select First Neighbors (Undirected)");
registerService(bc,selectFirstNeighborsNodeViewTaskFactory,NodeViewTaskFactory.class, selectFirstNeighborsNodeViewTaskFactoryProps);
registerService(bc,selectFirstNeighborsNodeViewTaskFactory,SelectFirstNeighborsNodeViewTaskFactory.class, selectFirstNeighborsNodeViewTaskFactoryProps);
Properties hideSelectedTaskFactoryProps = new Properties();
hideSelectedTaskFactoryProps.setProperty(ENABLE_FOR,"selectedNodesOrEdges");
hideSelectedTaskFactoryProps.setProperty(PREFERRED_MENU,"Select");
hideSelectedTaskFactoryProps.setProperty(MENU_GRAVITY,"3.1");
hideSelectedTaskFactoryProps.setProperty(TOOL_BAR_GRAVITY,"9.5");
hideSelectedTaskFactoryProps.setProperty(TITLE,"Hide selected nodes and edges");
hideSelectedTaskFactoryProps.setProperty(LARGE_ICON_URL,getClass().getResource("/images/icons/hide_selected.png").toString());
hideSelectedTaskFactoryProps.setProperty(IN_TOOL_BAR,"true");
hideSelectedTaskFactoryProps.setProperty(TOOLTIP,"Hide Selected Nodes and Edges");
// hideSelectedTaskFactoryProps.setProperty(COMMAND,"hide selected");
// hideSelectedTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"view");
registerService(bc,hideSelectedTaskFactory,NetworkViewTaskFactory.class, hideSelectedTaskFactoryProps);
registerService(bc,hideSelectedTaskFactory,HideSelectedTaskFactory.class, hideSelectedTaskFactoryProps);
Properties hideSelectedNodesTaskFactoryProps = new Properties();
hideSelectedNodesTaskFactoryProps.setProperty(ENABLE_FOR,"selectedNodes");
hideSelectedNodesTaskFactoryProps.setProperty(PREFERRED_MENU,"Select.Nodes");
hideSelectedNodesTaskFactoryProps.setProperty(MENU_GRAVITY,"2.0");
hideSelectedNodesTaskFactoryProps.setProperty(TITLE,"Hide selected nodes");
// hideSelectedNodesTaskFactoryProps.setProperty(COMMAND,"hide selected nodes");
// hideSelectedNodesTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"view");
registerService(bc,hideSelectedNodesTaskFactory,NetworkViewTaskFactory.class, hideSelectedNodesTaskFactoryProps);
registerService(bc,hideSelectedNodesTaskFactory,HideSelectedNodesTaskFactory.class, hideSelectedNodesTaskFactoryProps);
Properties hideSelectedEdgesTaskFactoryProps = new Properties();
hideSelectedEdgesTaskFactoryProps.setProperty(ENABLE_FOR,"selectedEdges");
hideSelectedEdgesTaskFactoryProps.setProperty(PREFERRED_MENU,"Select.Edges");
hideSelectedEdgesTaskFactoryProps.setProperty(MENU_GRAVITY,"2.0");
hideSelectedEdgesTaskFactoryProps.setProperty(TITLE,"Hide selected edges");
// hideSelectedEdgesTaskFactoryProps.setProperty(COMMAND,"hide selected edges");
// hideSelectedEdgesTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"view");
registerService(bc,hideSelectedEdgesTaskFactory,NetworkViewTaskFactory.class, hideSelectedEdgesTaskFactoryProps);
registerService(bc,hideSelectedEdgesTaskFactory,HideSelectedEdgesTaskFactory.class, hideSelectedEdgesTaskFactoryProps);
Properties unHideAllTaskFactoryProps = new Properties();
unHideAllTaskFactoryProps.setProperty(ENABLE_FOR,"networkAndView");
unHideAllTaskFactoryProps.setProperty(PREFERRED_MENU,"Select");
unHideAllTaskFactoryProps.setProperty(MENU_GRAVITY,"3.0");
unHideAllTaskFactoryProps.setProperty(TOOL_BAR_GRAVITY,"9.6");
unHideAllTaskFactoryProps.setProperty(TITLE,"Show all nodes and edges");
// unHideAllTaskFactoryProps.setProperty(COMMAND,"show all");
// unHideAllTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"view");
unHideAllTaskFactoryProps.setProperty(LARGE_ICON_URL,getClass().getResource("/images/icons/unhide_all.png").toString());
unHideAllTaskFactoryProps.setProperty(IN_TOOL_BAR,"true");
unHideAllTaskFactoryProps.setProperty(TOOLTIP,"Show All Nodes and Edges");
registerService(bc,unHideAllTaskFactory,NetworkViewTaskFactory.class, unHideAllTaskFactoryProps);
registerService(bc,unHideAllTaskFactory,UnHideAllTaskFactory.class, unHideAllTaskFactoryProps);
Properties unHideAllNodesTaskFactoryProps = new Properties();
unHideAllNodesTaskFactoryProps.setProperty(ENABLE_FOR,"networkAndView");
unHideAllNodesTaskFactoryProps.setProperty(PREFERRED_MENU,"Select.Nodes");
unHideAllNodesTaskFactoryProps.setProperty(MENU_GRAVITY,"3.0");
unHideAllNodesTaskFactoryProps.setProperty(TITLE,"Show all nodes");
// unHideAllNodesTaskFactoryProps.setProperty(COMMAND,"show all nodes");
// unHideAllNodesTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"view");
registerService(bc,unHideAllNodesTaskFactory,NetworkViewTaskFactory.class, unHideAllNodesTaskFactoryProps);
registerService(bc,unHideAllNodesTaskFactory,UnHideAllNodesTaskFactory.class, unHideAllNodesTaskFactoryProps);
Properties unHideAllEdgesTaskFactoryProps = new Properties();
unHideAllEdgesTaskFactoryProps.setProperty(ENABLE_FOR,"networkAndView");
unHideAllEdgesTaskFactoryProps.setProperty(PREFERRED_MENU,"Select.Edges");
unHideAllEdgesTaskFactoryProps.setProperty(MENU_GRAVITY,"3.0");
unHideAllEdgesTaskFactoryProps.setProperty(TITLE,"Show all edges");
// unHideAllEdgesTaskFactoryProps.setProperty(COMMAND,"show all edges");
// unHideAllEdgesTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"view");
registerService(bc,unHideAllEdgesTaskFactory,NetworkViewTaskFactory.class, unHideAllEdgesTaskFactoryProps);
registerService(bc,unHideAllEdgesTaskFactory,UnHideAllEdgesTaskFactory.class, unHideAllEdgesTaskFactoryProps);
Properties newEmptyNetworkTaskFactoryProps = new Properties();
newEmptyNetworkTaskFactoryProps.setProperty(PREFERRED_MENU,"File.New.Network");
newEmptyNetworkTaskFactoryProps.setProperty(MENU_GRAVITY,"4.0");
newEmptyNetworkTaskFactoryProps.setProperty(TITLE,"Empty Network");
newEmptyNetworkTaskFactoryProps.setProperty(COMMAND,"create empty");
newEmptyNetworkTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"network");
registerService(bc,newEmptyNetworkTaskFactory,TaskFactory.class, newEmptyNetworkTaskFactoryProps);
registerService(bc,newEmptyNetworkTaskFactory,NewEmptyNetworkViewFactory.class, newEmptyNetworkTaskFactoryProps);
Properties newNetworkSelectedNodesEdgesTaskFactoryProps = new Properties();
newNetworkSelectedNodesEdgesTaskFactoryProps.setProperty(ENABLE_FOR,"selectedNodesOrEdges");
newNetworkSelectedNodesEdgesTaskFactoryProps.setProperty(PREFERRED_MENU,"File.New.Network");
newNetworkSelectedNodesEdgesTaskFactoryProps.setProperty(MENU_GRAVITY,"2.0");
newNetworkSelectedNodesEdgesTaskFactoryProps.setProperty(ACCELERATOR,"cmd shift n");
newNetworkSelectedNodesEdgesTaskFactoryProps.setProperty(TITLE,"From selected nodes, selected edges");
// newNetworkSelectedNodesEdgesTaskFactoryProps.setProperty(COMMAND,"create from selected nodes and edges");
// newNetworkSelectedNodesEdgesTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"network");
registerService(bc,newNetworkSelectedNodesEdgesTaskFactory,NetworkTaskFactory.class, newNetworkSelectedNodesEdgesTaskFactoryProps);
registerService(bc,newNetworkSelectedNodesEdgesTaskFactory,NewNetworkSelectedNodesAndEdgesTaskFactory.class, newNetworkSelectedNodesEdgesTaskFactoryProps);
Properties newNetworkSelectedNodesOnlyTaskFactoryProps = new Properties();
newNetworkSelectedNodesOnlyTaskFactoryProps.setProperty(PREFERRED_MENU,"File.New.Network");
newNetworkSelectedNodesOnlyTaskFactoryProps.setProperty(LARGE_ICON_URL,getClass().getResource("/images/icons/new_fromselected.png").toString());
newNetworkSelectedNodesOnlyTaskFactoryProps.setProperty(ACCELERATOR,"cmd n");
newNetworkSelectedNodesOnlyTaskFactoryProps.setProperty(ENABLE_FOR,"selectedNodes");
newNetworkSelectedNodesOnlyTaskFactoryProps.setProperty(TITLE,"From selected nodes, all edges");
newNetworkSelectedNodesOnlyTaskFactoryProps.setProperty(TOOL_BAR_GRAVITY,"9.1");
newNetworkSelectedNodesOnlyTaskFactoryProps.setProperty(IN_TOOL_BAR,"true");
newNetworkSelectedNodesOnlyTaskFactoryProps.setProperty(MENU_GRAVITY,"1.0");
newNetworkSelectedNodesOnlyTaskFactoryProps.setProperty(TOOLTIP,"New Network From Selection");
// newNetworkSelectedNodesOnlyTaskFactoryProps.setProperty(COMMAND,"create from selected nodes and all edges");
// newNetworkSelectedNodesOnlyTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"network");
registerService(bc,newNetworkSelectedNodesOnlyTaskFactory,NetworkTaskFactory.class, newNetworkSelectedNodesOnlyTaskFactoryProps);
registerService(bc,newNetworkSelectedNodesOnlyTaskFactory,NewNetworkSelectedNodesOnlyTaskFactory.class, newNetworkSelectedNodesOnlyTaskFactoryProps);
Properties newNetworkCommandTaskFactoryProps = new Properties();
newNetworkCommandTaskFactoryProps.setProperty(COMMAND,"create");
newNetworkCommandTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"network");
registerService(bc,newNetworkCommandTaskFactory,NetworkTaskFactory.class, newNetworkCommandTaskFactoryProps);
Properties cloneNetworkTaskFactoryProps = new Properties();
cloneNetworkTaskFactoryProps.setProperty(ENABLE_FOR,"network");
cloneNetworkTaskFactoryProps.setProperty(PREFERRED_MENU,"File.New.Network");
cloneNetworkTaskFactoryProps.setProperty(MENU_GRAVITY,"3.0");
cloneNetworkTaskFactoryProps.setProperty(TITLE,"Clone Current Network");
cloneNetworkTaskFactoryProps.setProperty(COMMAND,"clone");
cloneNetworkTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"network");
registerService(bc,cloneNetworkTaskFactory,NetworkTaskFactory.class, cloneNetworkTaskFactoryProps);
registerService(bc,cloneNetworkTaskFactory,CloneNetworkTaskFactory.class, cloneNetworkTaskFactoryProps);
Properties destroyNetworkTaskFactoryProps = new Properties();
destroyNetworkTaskFactoryProps.setProperty(PREFERRED_MENU,"Edit");
destroyNetworkTaskFactoryProps.setProperty(ACCELERATOR,"cmd shift w");
destroyNetworkTaskFactoryProps.setProperty(ENABLE_FOR,"network");
destroyNetworkTaskFactoryProps.setProperty(TITLE,"Destroy Network");
destroyNetworkTaskFactoryProps.setProperty(IN_NETWORK_PANEL_CONTEXT_MENU,"true");
destroyNetworkTaskFactoryProps.setProperty(MENU_GRAVITY,"3.2");
destroyNetworkTaskFactoryProps.setProperty(COMMAND,"destroy");
destroyNetworkTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"network");
registerService(bc,destroyNetworkTaskFactory,NetworkCollectionTaskFactory.class, destroyNetworkTaskFactoryProps);
registerService(bc,destroyNetworkTaskFactory,DestroyNetworkTaskFactory.class, destroyNetworkTaskFactoryProps);
registerService(bc,destroyNetworkTaskFactory,TaskFactory.class, destroyNetworkTaskFactoryProps);
Properties destroyNetworkViewTaskFactoryProps = new Properties();
destroyNetworkViewTaskFactoryProps.setProperty(PREFERRED_MENU,"Edit");
destroyNetworkViewTaskFactoryProps.setProperty(ACCELERATOR,"cmd w");
destroyNetworkViewTaskFactoryProps.setProperty(ENABLE_FOR,"networkAndView");
destroyNetworkViewTaskFactoryProps.setProperty(TITLE,"Destroy View");
destroyNetworkViewTaskFactoryProps.setProperty(IN_NETWORK_PANEL_CONTEXT_MENU,"true");
destroyNetworkViewTaskFactoryProps.setProperty(MENU_GRAVITY,"3.1");
destroyNetworkViewTaskFactoryProps.setProperty(COMMAND,"destroy");
destroyNetworkViewTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"view");
registerService(bc,destroyNetworkViewTaskFactory,NetworkViewCollectionTaskFactory.class, destroyNetworkViewTaskFactoryProps);
registerService(bc,destroyNetworkViewTaskFactory,DestroyNetworkViewTaskFactory.class, destroyNetworkViewTaskFactoryProps);
Properties zoomInTaskFactoryProps = new Properties();
zoomInTaskFactoryProps.setProperty(ACCELERATOR,"cmd equals");
zoomInTaskFactoryProps.setProperty(LARGE_ICON_URL,getClass().getResource("/images/icons/stock_zoom-in.png").toString());
zoomInTaskFactoryProps.setProperty(ENABLE_FOR,"networkAndView");
zoomInTaskFactoryProps.setProperty(TITLE,"Zoom In");
zoomInTaskFactoryProps.setProperty(TOOLTIP,"Zoom In");
zoomInTaskFactoryProps.setProperty(TOOL_BAR_GRAVITY,"5.1");
zoomInTaskFactoryProps.setProperty(IN_TOOL_BAR,"true");
// zoomInTaskFactoryProps.setProperty(COMMAND,"zoom in");
// zoomInTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"view");
registerService(bc,zoomInTaskFactory,NetworkTaskFactory.class, zoomInTaskFactoryProps);
Properties zoomOutTaskFactoryProps = new Properties();
zoomOutTaskFactoryProps.setProperty(ACCELERATOR,"cmd minus");
zoomOutTaskFactoryProps.setProperty(LARGE_ICON_URL,getClass().getResource("/images/icons/stock_zoom-out.png").toString());
zoomOutTaskFactoryProps.setProperty(ENABLE_FOR,"networkAndView");
zoomOutTaskFactoryProps.setProperty(TITLE,"Zoom Out");
zoomOutTaskFactoryProps.setProperty(TOOLTIP,"Zoom Out");
zoomOutTaskFactoryProps.setProperty(TOOL_BAR_GRAVITY,"5.2");
zoomOutTaskFactoryProps.setProperty(IN_TOOL_BAR,"true");
// zoomOutTaskFactoryProps.setProperty(COMMAND,"zoom out");
// zoomOutTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"view");
registerService(bc,zoomOutTaskFactory,NetworkTaskFactory.class, zoomOutTaskFactoryProps);
Properties fitSelectedTaskFactoryProps = new Properties();
fitSelectedTaskFactoryProps.setProperty(ACCELERATOR,"cmd shift f");
fitSelectedTaskFactoryProps.setProperty(LARGE_ICON_URL,getClass().getResource("/images/icons/stock_zoom-object.png").toString());
fitSelectedTaskFactoryProps.setProperty(ENABLE_FOR,"networkAndView");
fitSelectedTaskFactoryProps.setProperty(TITLE,"Fit Selected");
fitSelectedTaskFactoryProps.setProperty(TOOLTIP,"Zoom selected region");
fitSelectedTaskFactoryProps.setProperty(TOOL_BAR_GRAVITY,"5.4");
fitSelectedTaskFactoryProps.setProperty(IN_TOOL_BAR,"true");
fitSelectedTaskFactoryProps.setProperty(COMMAND,"fit selected");
fitSelectedTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"view");
registerService(bc,fitSelectedTaskFactory,NetworkTaskFactory.class, fitSelectedTaskFactoryProps);
Properties fitContentTaskFactoryProps = new Properties();
fitContentTaskFactoryProps.setProperty(ACCELERATOR,"cmd f");
fitContentTaskFactoryProps.setProperty(LARGE_ICON_URL,getClass().getResource("/images/icons/stock_zoom-1.png").toString());
fitContentTaskFactoryProps.setProperty(ENABLE_FOR,"networkAndView");
fitContentTaskFactoryProps.setProperty(TITLE,"Fit Content");
fitContentTaskFactoryProps.setProperty(TOOLTIP,"Zoom out to display all of current Network");
fitContentTaskFactoryProps.setProperty(TOOL_BAR_GRAVITY,"5.3");
fitContentTaskFactoryProps.setProperty(IN_TOOL_BAR,"true");
fitContentTaskFactoryProps.setProperty(COMMAND,"fit content");
fitContentTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"view");
registerService(bc,fitContentTaskFactory,NetworkTaskFactory.class, fitContentTaskFactoryProps);
Properties editNetworkTitleTaskFactoryProps = new Properties();
editNetworkTitleTaskFactoryProps.setProperty(ENABLE_FOR,"singleNetwork");
editNetworkTitleTaskFactoryProps.setProperty(PREFERRED_MENU,"Edit");
editNetworkTitleTaskFactoryProps.setProperty(MENU_GRAVITY,"5.5");
editNetworkTitleTaskFactoryProps.setProperty(TITLE,"Rename Network...");
editNetworkTitleTaskFactoryProps.setProperty(IN_NETWORK_PANEL_CONTEXT_MENU,"true");
editNetworkTitleTaskFactoryProps.setProperty(COMMAND,"rename");
editNetworkTitleTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"network");
registerService(bc,editNetworkTitleTaskFactory,NetworkTaskFactory.class, editNetworkTitleTaskFactoryProps);
registerService(bc,editNetworkTitleTaskFactory,EditNetworkTitleTaskFactory.class, editNetworkTitleTaskFactoryProps);
Properties createNetworkViewTaskFactoryProps = new Properties();
createNetworkViewTaskFactoryProps.setProperty(ID,"createNetworkViewTaskFactory");
// No ENABLE_FOR because that is handled by the isReady() methdod of the task factory.
createNetworkViewTaskFactoryProps.setProperty(PREFERRED_MENU,"Edit");
createNetworkViewTaskFactoryProps.setProperty(MENU_GRAVITY,"3.0");
createNetworkViewTaskFactoryProps.setProperty(TITLE,"Create View");
createNetworkViewTaskFactoryProps.setProperty(IN_NETWORK_PANEL_CONTEXT_MENU,"true");
createNetworkViewTaskFactoryProps.setProperty(COMMAND,"create");
createNetworkViewTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"view");
registerService(bc,createNetworkViewTaskFactory,NetworkCollectionTaskFactory.class, createNetworkViewTaskFactoryProps);
registerService(bc,createNetworkViewTaskFactory,CreateNetworkViewTaskFactory.class, createNetworkViewTaskFactoryProps);
// For commands
registerService(bc,createNetworkViewTaskFactory,TaskFactory.class, createNetworkViewTaskFactoryProps);
Properties exportNetworkImageTaskFactoryProps = new Properties();
exportNetworkImageTaskFactoryProps.setProperty(PREFERRED_MENU,"File.Export");
exportNetworkImageTaskFactoryProps.setProperty(LARGE_ICON_URL,getClass().getResource("/images/icons/img_file_export.png").toString());
exportNetworkImageTaskFactoryProps.setProperty(ENABLE_FOR,"networkAndView");
exportNetworkImageTaskFactoryProps.setProperty(MENU_GRAVITY,"1.2");
exportNetworkImageTaskFactoryProps.setProperty(TITLE,"Network View as Graphics...");
exportNetworkImageTaskFactoryProps.setProperty(TOOL_BAR_GRAVITY,"3.7");
exportNetworkImageTaskFactoryProps.setProperty(IN_TOOL_BAR,"true");
exportNetworkImageTaskFactoryProps.setProperty(IN_CONTEXT_MENU,"false");
exportNetworkImageTaskFactoryProps.setProperty(TOOLTIP,"Export Network Image to File");
exportNetworkImageTaskFactoryProps.setProperty(COMMAND,"export");
exportNetworkImageTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"view");
registerService(bc,exportNetworkImageTaskFactory,NetworkViewTaskFactory.class, exportNetworkImageTaskFactoryProps);
registerService(bc,exportNetworkImageTaskFactory,ExportNetworkImageTaskFactory.class, exportNetworkImageTaskFactoryProps);
Properties exportNetworkViewTaskFactoryProps = new Properties();
exportNetworkViewTaskFactoryProps.setProperty(ENABLE_FOR,"networkAndView");
exportNetworkViewTaskFactoryProps.setProperty(PREFERRED_MENU,"File.Export");
exportNetworkViewTaskFactoryProps.setProperty(MENU_GRAVITY,"1.1");
exportNetworkViewTaskFactoryProps.setProperty(TOOL_BAR_GRAVITY,"3.5");
exportNetworkViewTaskFactoryProps.setProperty(TITLE,"Network...");
exportNetworkViewTaskFactoryProps.setProperty(LARGE_ICON_URL,getClass().getResource("/images/icons/net_file_export.png").toString());
exportNetworkViewTaskFactoryProps.setProperty(IN_TOOL_BAR,"true");
exportNetworkViewTaskFactoryProps.setProperty(IN_CONTEXT_MENU,"false");
exportNetworkViewTaskFactoryProps.setProperty(TOOLTIP,"Export Network to File");
exportNetworkViewTaskFactoryProps.setProperty(COMMAND,"export");
exportNetworkViewTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"network");
registerService(bc,exportNetworkViewTaskFactory,NetworkViewTaskFactory.class, exportNetworkViewTaskFactoryProps);
registerService(bc,exportNetworkViewTaskFactory,ExportNetworkViewTaskFactory.class, exportNetworkViewTaskFactoryProps);
Properties exportCurrentTableTaskFactoryProps = new Properties();
exportCurrentTableTaskFactoryProps.setProperty(ENABLE_FOR,"table");
exportCurrentTableTaskFactoryProps.setProperty(PREFERRED_MENU,"File.Export");
exportCurrentTableTaskFactoryProps.setProperty(MENU_GRAVITY,"1.3");
exportCurrentTableTaskFactoryProps.setProperty(TOOL_BAR_GRAVITY,"3.6");
exportCurrentTableTaskFactoryProps.setProperty(TITLE,"Table...");
exportCurrentTableTaskFactoryProps.setProperty(LARGE_ICON_URL,getClass().getResource("/images/icons/table_file_export.png").toString());
exportCurrentTableTaskFactoryProps.setProperty(IN_TOOL_BAR,"true");
exportCurrentTableTaskFactoryProps.setProperty(TOOLTIP,"Export Table to File");
exportCurrentTableTaskFactoryProps.setProperty(COMMAND,"export");
exportCurrentTableTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"table");
registerService(bc,exportCurrentTableTaskFactory, TaskFactory.class, exportCurrentTableTaskFactoryProps);
registerService(bc,exportCurrentTableTaskFactory,ExportSelectedTableTaskFactory.class, exportCurrentTableTaskFactoryProps);
Properties exportVizmapTaskFactoryProps = new Properties();
exportVizmapTaskFactoryProps.setProperty(ENABLE_FOR,"vizmap");
exportVizmapTaskFactoryProps.setProperty(PREFERRED_MENU,"File.Export");
exportVizmapTaskFactoryProps.setProperty(MENU_GRAVITY,"1.4");
exportVizmapTaskFactoryProps.setProperty(TITLE,"Vizmap...");
exportVizmapTaskFactoryProps.setProperty(COMMAND,"export");
exportVizmapTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"vizmap");
registerService(bc,exportVizmapTaskFactory,TaskFactory.class, exportVizmapTaskFactoryProps);
registerService(bc,exportVizmapTaskFactory,ExportVizmapTaskFactory.class, exportVizmapTaskFactoryProps);
Properties loadDataFileTaskFactoryProps = new Properties();
loadDataFileTaskFactoryProps.setProperty(PREFERRED_MENU,"File.Load Data Table");
loadDataFileTaskFactoryProps.setProperty(MENU_GRAVITY,"1.1");
loadDataFileTaskFactoryProps.setProperty(TITLE,"File...");
//loadDataFileTaskFactoryProps.setProperty(ServiceProperties.INSERT_SEPARATOR_BEFORE, "true");
loadDataFileTaskFactoryProps.setProperty(TOOLTIP,"Load Data Table From File");
loadDataFileTaskFactoryProps.setProperty(COMMAND,"load file");
loadDataFileTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"table");
registerService(bc,loadAttrsFileTaskFactory,TaskFactory.class, loadDataFileTaskFactoryProps);
registerService(bc,loadAttrsFileTaskFactory,LoadTableFileTaskFactory.class, loadDataFileTaskFactoryProps);
Properties loadDataURLTaskFactoryProps = new Properties();
loadDataURLTaskFactoryProps.setProperty(PREFERRED_MENU,"File.Load Data Table");
loadDataURLTaskFactoryProps.setProperty(MENU_GRAVITY,"1.2");
loadDataURLTaskFactoryProps.setProperty(TITLE,"URL...");
loadDataURLTaskFactoryProps.setProperty(TOOLTIP,"Load Data Table From URL");
loadDataURLTaskFactoryProps.setProperty(COMMAND,"load url");
loadDataURLTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"table");
registerService(bc,loadAttrsURLTaskFactory,TaskFactory.class, loadDataURLTaskFactoryProps);
registerService(bc,loadAttrsURLTaskFactory,LoadTableURLTaskFactory.class, loadDataURLTaskFactoryProps);
Properties MergeGlobalTaskFactoryProps = new Properties();
MergeGlobalTaskFactoryProps.setProperty(ENABLE_FOR,"network");
MergeGlobalTaskFactoryProps.setProperty(PREFERRED_MENU,"File");
MergeGlobalTaskFactoryProps.setProperty(TITLE,"Merge Data Table...");
//MergeGlobalTaskFactoryProps.setProperty(ServiceProperties.INSERT_SEPARATOR_AFTER, "true");
//MergeGlobalTaskFactoryProps.setProperty(TOOL_BAR_GRAVITY,"1.1");
MergeGlobalTaskFactoryProps.setProperty(MENU_GRAVITY,"5.4");
MergeGlobalTaskFactoryProps.setProperty(TOOLTIP,"Merge Data Table");
registerService(bc,mergeTableTaskFactory,TaskFactory.class, MergeGlobalTaskFactoryProps);
registerService(bc,mergeTableTaskFactory,MergeDataTableTaskFactory.class, MergeGlobalTaskFactoryProps);
Properties newSessionTaskFactoryProps = new Properties();
newSessionTaskFactoryProps.setProperty(PREFERRED_MENU,"File.New");
newSessionTaskFactoryProps.setProperty(MENU_GRAVITY,"1.1");
newSessionTaskFactoryProps.setProperty(TITLE,"Session");
newSessionTaskFactoryProps.setProperty(COMMAND,"new");
newSessionTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"session");
registerService(bc,newSessionTaskFactory,TaskFactory.class, newSessionTaskFactoryProps);
registerService(bc,newSessionTaskFactory,NewSessionTaskFactory.class, newSessionTaskFactoryProps);
Properties openSessionTaskFactoryProps = new Properties();
openSessionTaskFactoryProps.setProperty(ID,"openSessionTaskFactory");
openSessionTaskFactoryProps.setProperty(PREFERRED_MENU,"File");
openSessionTaskFactoryProps.setProperty(ACCELERATOR,"cmd o");
openSessionTaskFactoryProps.setProperty(LARGE_ICON_URL,getClass().getResource("/images/icons/open_session.png").toString());
openSessionTaskFactoryProps.setProperty(TITLE,"Open...");
openSessionTaskFactoryProps.setProperty(TOOL_BAR_GRAVITY,"1.0");
openSessionTaskFactoryProps.setProperty(IN_TOOL_BAR,"true");
openSessionTaskFactoryProps.setProperty(MENU_GRAVITY,"1.0");
openSessionTaskFactoryProps.setProperty(TOOLTIP,"Open Session");
registerService(bc,openSessionTaskFactory,OpenSessionTaskFactory.class, openSessionTaskFactoryProps);
+ registerService(bc,openSessionTaskFactory,TaskFactory.class, openSessionTaskFactoryProps);
// We can't use the "normal" OpenSessionTaskFactory for commands
// because it inserts the task with the file tunable in it, so the
// Command processor never sees it, so we need a special OpenSessionTaskFactory
// for commands
// openSessionTaskFactoryProps.setProperty(COMMAND,"open");
// openSessionTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"session");
// registerService(bc,openSessionTaskFactory,TaskFactory.class, openSessionTaskFactoryProps);
Properties openSessionCommandTaskFactoryProps = new Properties();
openSessionCommandTaskFactoryProps.setProperty(COMMAND,"open");
openSessionCommandTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"session");
registerService(bc,openSessionCommandTaskFactory,TaskFactory.class, openSessionCommandTaskFactoryProps);
Properties saveSessionTaskFactoryProps = new Properties();
saveSessionTaskFactoryProps.setProperty(PREFERRED_MENU,"File");
saveSessionTaskFactoryProps.setProperty(ACCELERATOR,"cmd s");
saveSessionTaskFactoryProps.setProperty(LARGE_ICON_URL,getClass().getResource("/images/icons/stock_save.png").toString());
saveSessionTaskFactoryProps.setProperty(TITLE,"Save");
saveSessionTaskFactoryProps.setProperty(TOOL_BAR_GRAVITY,"1.1");
saveSessionTaskFactoryProps.setProperty(IN_TOOL_BAR,"true");
saveSessionTaskFactoryProps.setProperty(MENU_GRAVITY,"3.0");
saveSessionTaskFactoryProps.setProperty(TOOLTIP,"Save Session");
saveSessionTaskFactoryProps.setProperty(COMMAND,"save");
saveSessionTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"session");
registerService(bc,saveSessionTaskFactory,TaskFactory.class, saveSessionTaskFactoryProps);
Properties saveSessionAsTaskFactoryProps = new Properties();
saveSessionAsTaskFactoryProps.setProperty(PREFERRED_MENU,"File");
saveSessionAsTaskFactoryProps.setProperty(ACCELERATOR,"cmd shift s");
saveSessionAsTaskFactoryProps.setProperty(MENU_GRAVITY,"3.1");
saveSessionAsTaskFactoryProps.setProperty(TITLE,"Save As...");
saveSessionAsTaskFactoryProps.setProperty(COMMAND,"save as");
saveSessionAsTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"session");
registerService(bc,saveSessionAsTaskFactory,TaskFactory.class, saveSessionAsTaskFactoryProps);
registerService(bc,saveSessionAsTaskFactory,SaveSessionAsTaskFactory.class, saveSessionAsTaskFactoryProps);
Properties applyPreferredLayoutTaskFactoryProps = new Properties();
applyPreferredLayoutTaskFactoryProps.setProperty(PREFERRED_MENU,"Layout");
applyPreferredLayoutTaskFactoryProps.setProperty(ACCELERATOR,"fn5");
applyPreferredLayoutTaskFactoryProps.setProperty(LARGE_ICON_URL,getClass().getResource("/images/icons/apply_layout.png").toString());
applyPreferredLayoutTaskFactoryProps.setProperty(ENABLE_FOR,"networkAndView");
applyPreferredLayoutTaskFactoryProps.setProperty(TITLE,"Apply Preferred Layout");
applyPreferredLayoutTaskFactoryProps.setProperty(TOOL_BAR_GRAVITY,"7.0");
applyPreferredLayoutTaskFactoryProps.setProperty(IN_TOOL_BAR,"true");
applyPreferredLayoutTaskFactoryProps.setProperty(MENU_GRAVITY,"5.0");
applyPreferredLayoutTaskFactoryProps.setProperty(TOOLTIP,"Apply Preferred Layout");
registerService(bc,applyPreferredLayoutTaskFactory,NetworkViewCollectionTaskFactory.class, applyPreferredLayoutTaskFactoryProps);
registerService(bc,applyPreferredLayoutTaskFactory,ApplyPreferredLayoutTaskFactory.class, applyPreferredLayoutTaskFactoryProps);
// For commands
Properties applyPreferredLayoutTaskFactoryProps2 = new Properties();
applyPreferredLayoutTaskFactoryProps2.setProperty(COMMAND,"apply preferred");
applyPreferredLayoutTaskFactoryProps2.setProperty(COMMAND_NAMESPACE,"layout");
registerService(bc,applyPreferredLayoutTaskFactory,TaskFactory.class, applyPreferredLayoutTaskFactoryProps2);
Properties deleteColumnTaskFactoryProps = new Properties();
deleteColumnTaskFactoryProps.setProperty(TITLE,"Delete column");
deleteColumnTaskFactoryProps.setProperty(COMMAND,"delete column");
deleteColumnTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"table");
registerService(bc,deleteColumnTaskFactory,TableColumnTaskFactory.class, deleteColumnTaskFactoryProps);
registerService(bc,deleteColumnTaskFactory,DeleteColumnTaskFactory.class, deleteColumnTaskFactoryProps);
Properties renameColumnTaskFactoryProps = new Properties();
renameColumnTaskFactoryProps.setProperty(TITLE,"Rename column");
renameColumnTaskFactoryProps.setProperty(COMMAND,"rename column");
renameColumnTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"table");
registerService(bc,renameColumnTaskFactory,TableColumnTaskFactory.class, renameColumnTaskFactoryProps);
registerService(bc,renameColumnTaskFactory,RenameColumnTaskFactory.class, renameColumnTaskFactoryProps);
Properties copyValueToEntireColumnTaskFactoryProps = new Properties();
copyValueToEntireColumnTaskFactoryProps.setProperty(TITLE,copyValueToEntireColumnTaskFactory.getTaskFactoryName());
copyValueToEntireColumnTaskFactoryProps.setProperty("tableTypes", "node,edge,network,unassigned");
registerService(bc,copyValueToEntireColumnTaskFactory,TableCellTaskFactory.class, copyValueToEntireColumnTaskFactoryProps);
Properties copyValueToSelectedNodesTaskFactoryProps = new Properties();
copyValueToSelectedNodesTaskFactoryProps.setProperty(TITLE,copyValueToSelectedNodesTaskFactory.getTaskFactoryName());
copyValueToSelectedNodesTaskFactoryProps.setProperty("tableTypes", "node");
registerService(bc,copyValueToSelectedNodesTaskFactory,TableCellTaskFactory.class, copyValueToSelectedNodesTaskFactoryProps);
Properties copyValueToSelectedEdgesTaskFactoryProps = new Properties();
copyValueToSelectedEdgesTaskFactoryProps.setProperty(TITLE,copyValueToSelectedEdgesTaskFactory.getTaskFactoryName());
copyValueToSelectedEdgesTaskFactoryProps.setProperty("tableTypes", "edge");
registerService(bc,copyValueToSelectedEdgesTaskFactory,TableCellTaskFactory.class, copyValueToSelectedEdgesTaskFactoryProps);
registerService(bc,deleteTableTaskFactory,TableTaskFactory.class, new Properties());
registerService(bc,deleteTableTaskFactory,DeleteTableTaskFactory.class, new Properties());
// Register as 3 types of service.
Properties connectSelectedNodesTaskFactoryProps = new Properties();
connectSelectedNodesTaskFactoryProps.setProperty(IN_MENU_BAR,"false");
connectSelectedNodesTaskFactoryProps.setProperty(IN_TOOL_BAR,"false");
connectSelectedNodesTaskFactoryProps.setProperty(PREFERRED_ACTION, "NEW");
connectSelectedNodesTaskFactoryProps.setProperty(PREFERRED_MENU, NODE_ADD_MENU);
connectSelectedNodesTaskFactoryProps.setProperty(MENU_GRAVITY, "0.2");
connectSelectedNodesTaskFactoryProps.setProperty(TITLE, "Edges Connecting Selected Nodes");
connectSelectedNodesTaskFactoryProps.setProperty(COMMAND, "connect selected nodes");
connectSelectedNodesTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "network");
// registerService(bc, connectSelectedNodesTaskFactory, NetworkTaskFactory.class,
// connectSelectedNodesTaskFactoryProps);
registerService(bc, connectSelectedNodesTaskFactory, NodeViewTaskFactory.class,
connectSelectedNodesTaskFactoryProps);
registerService(bc, connectSelectedNodesTaskFactory, ConnectSelectedNodesTaskFactory.class,
connectSelectedNodesTaskFactoryProps);
GroupNodesTaskFactoryImpl groupNodesTaskFactory =
new GroupNodesTaskFactoryImpl(cyApplicationManagerServiceRef, cyGroupManager,
cyGroupFactory, undoSupportServiceRef);
Properties groupNodesTaskFactoryProps = new Properties();
groupNodesTaskFactoryProps.setProperty(PREFERRED_MENU,NETWORK_GROUP_MENU);
groupNodesTaskFactoryProps.setProperty(TITLE,"Group Selected Nodes");
groupNodesTaskFactoryProps.setProperty(TOOLTIP,"Group Selected Nodes Together");
groupNodesTaskFactoryProps.setProperty(IN_TOOL_BAR,"false");
groupNodesTaskFactoryProps.setProperty(MENU_GRAVITY,"0.0");
groupNodesTaskFactoryProps.setProperty(IN_MENU_BAR,"false");
groupNodesTaskFactoryProps.setProperty(PREFERRED_ACTION, "NEW");
registerService(bc,groupNodesTaskFactory,NetworkViewTaskFactory.class, groupNodesTaskFactoryProps);
registerService(bc,groupNodesTaskFactory,GroupNodesTaskFactory.class, groupNodesTaskFactoryProps);
// For commands
groupNodesTaskFactoryProps = new Properties();
groupNodesTaskFactoryProps.setProperty(COMMAND, "create");
groupNodesTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "group");
registerService(bc,groupNodesTaskFactory,TaskFactory.class, groupNodesTaskFactoryProps);
// Add Group Selected Nodes to the nodes context also
Properties groupNodeViewTaskFactoryProps = new Properties();
groupNodeViewTaskFactoryProps.setProperty(PREFERRED_MENU,NODE_GROUP_MENU);
groupNodeViewTaskFactoryProps.setProperty(MENU_GRAVITY, "0.0");
groupNodeViewTaskFactoryProps.setProperty(TITLE,"Group Selected Nodes");
groupNodeViewTaskFactoryProps.setProperty(TOOLTIP,"Group Selected Nodes Together");
groupNodeViewTaskFactoryProps.setProperty(IN_TOOL_BAR,"false");
groupNodeViewTaskFactoryProps.setProperty(IN_MENU_BAR,"false");
groupNodeViewTaskFactoryProps.setProperty(PREFERRED_ACTION, "NEW");
registerService(bc,groupNodesTaskFactory,NodeViewTaskFactory.class, groupNodeViewTaskFactoryProps);
UnGroupNodesTaskFactoryImpl unGroupTaskFactory =
new UnGroupNodesTaskFactoryImpl(cyApplicationManagerServiceRef, cyGroupManager,
cyGroupFactory, undoSupportServiceRef);
Properties unGroupNodesTaskFactoryProps = new Properties();
unGroupNodesTaskFactoryProps.setProperty(PREFERRED_MENU,NETWORK_GROUP_MENU);
unGroupNodesTaskFactoryProps.setProperty(TITLE,"Ungroup Selected Nodes");
unGroupNodesTaskFactoryProps.setProperty(TOOLTIP,"Ungroup Selected Nodes");
unGroupNodesTaskFactoryProps.setProperty(IN_TOOL_BAR,"false");
unGroupNodesTaskFactoryProps.setProperty(IN_MENU_BAR,"false");
unGroupNodesTaskFactoryProps.setProperty(MENU_GRAVITY,"1.0");
unGroupNodesTaskFactoryProps.setProperty(PREFERRED_ACTION, "NEW");
registerService(bc,unGroupTaskFactory,NetworkViewTaskFactory.class, unGroupNodesTaskFactoryProps);
registerService(bc,unGroupTaskFactory,UnGroupTaskFactory.class, unGroupNodesTaskFactoryProps);
unGroupNodesTaskFactoryProps = new Properties();
unGroupNodesTaskFactoryProps.setProperty(COMMAND, "ungroup");
groupNodesTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "group");
registerService(bc,unGroupTaskFactory,TaskFactory.class, unGroupNodesTaskFactoryProps);
// Add Ungroup Selected Nodes to the nodes context also
Properties unGroupNodeViewTaskFactoryProps = new Properties();
unGroupNodeViewTaskFactoryProps.setProperty(PREFERRED_MENU,NODE_GROUP_MENU);
unGroupNodeViewTaskFactoryProps.setProperty(MENU_GRAVITY, "1.0");
unGroupNodeViewTaskFactoryProps.setProperty(INSERT_SEPARATOR_AFTER, "true");
unGroupNodeViewTaskFactoryProps.setProperty(TITLE,"Ungroup Selected Nodes");
unGroupNodeViewTaskFactoryProps.setProperty(TOOLTIP,"Ungroup Selected Nodes");
unGroupNodeViewTaskFactoryProps.setProperty(IN_TOOL_BAR,"false");
unGroupNodeViewTaskFactoryProps.setProperty(IN_MENU_BAR,"false");
unGroupNodeViewTaskFactoryProps.setProperty(PREFERRED_ACTION, "NEW");
registerService(bc,unGroupTaskFactory,NodeViewTaskFactory.class, unGroupNodeViewTaskFactoryProps);
registerService(bc,unGroupTaskFactory,UnGroupNodesTaskFactory.class, unGroupNodeViewTaskFactoryProps);
GroupNodeContextTaskFactoryImpl collapseGroupTaskFactory =
new GroupNodeContextTaskFactoryImpl(cyApplicationManagerServiceRef,
cyNetworkViewManagerServiceRef, cyGroupManager, true);
Properties collapseGroupTaskFactoryProps = new Properties();
collapseGroupTaskFactoryProps.setProperty(PREFERRED_MENU,NODE_GROUP_MENU);
collapseGroupTaskFactoryProps.setProperty(TITLE,"Collapse Group(s)");
collapseGroupTaskFactoryProps.setProperty(TOOLTIP,"Collapse Grouped Nodes");
collapseGroupTaskFactoryProps.setProperty(PREFERRED_ACTION, "NEW");
collapseGroupTaskFactoryProps.setProperty(MENU_GRAVITY, "2.0");
registerService(bc,collapseGroupTaskFactory,NodeViewTaskFactory.class, collapseGroupTaskFactoryProps);
registerService(bc,collapseGroupTaskFactory,CollapseGroupTaskFactory.class, collapseGroupTaskFactoryProps);
collapseGroupTaskFactoryProps = new Properties();
collapseGroupTaskFactoryProps.setProperty(COMMAND, "collapse");
collapseGroupTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "group"); // TODO right namespace?
registerService(bc,collapseGroupTaskFactory,TaskFactory.class, collapseGroupTaskFactoryProps);
GroupNodeContextTaskFactoryImpl expandGroupTaskFactory =
new GroupNodeContextTaskFactoryImpl(cyApplicationManagerServiceRef,
cyNetworkViewManagerServiceRef, cyGroupManager, false);
Properties expandGroupTaskFactoryProps = new Properties();
expandGroupTaskFactoryProps.setProperty(PREFERRED_MENU,NODE_GROUP_MENU);
expandGroupTaskFactoryProps.setProperty(TITLE,"Expand Group(s)");
expandGroupTaskFactoryProps.setProperty(TOOLTIP,"Expand Group");
expandGroupTaskFactoryProps.setProperty(PREFERRED_ACTION, "NEW");
expandGroupTaskFactoryProps.setProperty(MENU_GRAVITY, "3.0");
registerService(bc,expandGroupTaskFactory,NodeViewTaskFactory.class, expandGroupTaskFactoryProps);
registerService(bc,expandGroupTaskFactory,ExpandGroupTaskFactory.class, expandGroupTaskFactoryProps);
expandGroupTaskFactoryProps = new Properties();
expandGroupTaskFactoryProps.setProperty(COMMAND, "expand");
expandGroupTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "group"); // TODO right namespace
registerService(bc,expandGroupTaskFactory,TaskFactory.class, expandGroupTaskFactoryProps);
// TODO: add to group...
// TODO: remove from group...
MapTableToNetworkTablesTaskFactoryImpl mapNetworkToTables = new MapTableToNetworkTablesTaskFactoryImpl(cyNetworkManagerServiceRef, tunableSetterServiceRef, rootNetworkManagerServiceRef);
Properties mapNetworkToTablesProps = new Properties();
registerService(bc, mapNetworkToTables, MapTableToNetworkTablesTaskFactory.class, mapNetworkToTablesProps);
ImportDataTableTaskFactoryImpl importTableTaskFactory = new ImportDataTableTaskFactoryImpl(cyNetworkManagerServiceRef,tunableSetterServiceRef,rootNetworkManagerServiceRef);
Properties importTablesProps = new Properties();
registerService(bc, importTableTaskFactory, ImportDataTableTaskFactory.class, importTablesProps);
ExportTableTaskFactoryImpl exportTableTaskFactory = new ExportTableTaskFactoryImpl(cyTableWriterManagerRef,tunableSetterServiceRef);
Properties exportTableTaskFactoryProps = new Properties();
registerService(bc,exportTableTaskFactory,ExportTableTaskFactory.class,exportTableTaskFactoryProps);
// These are task factories that are only available to the command line
// NAMESPACE: edge
CreateNetworkAttributeTaskFactory createEdgeAttributeTaskFactory =
new CreateNetworkAttributeTaskFactory(cyApplicationManagerServiceRef,
cyTableManagerServiceRef, CyEdge.class);
Properties createEdgeAttributeTaskFactoryProps = new Properties();
createEdgeAttributeTaskFactoryProps.setProperty(COMMAND, "create attribute");
createEdgeAttributeTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "edge");
registerService(bc,createEdgeAttributeTaskFactory,TaskFactory.class,createEdgeAttributeTaskFactoryProps);
GetEdgeTaskFactory getEdgeTaskFactory = new GetEdgeTaskFactory(cyApplicationManagerServiceRef);
Properties getEdgeTaskFactoryProps = new Properties();
getEdgeTaskFactoryProps.setProperty(COMMAND, "get");
getEdgeTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "edge");
registerService(bc,getEdgeTaskFactory,TaskFactory.class,getEdgeTaskFactoryProps);
GetNetworkAttributeTaskFactory getEdgeAttributeTaskFactory =
new GetNetworkAttributeTaskFactory(cyApplicationManagerServiceRef, cyTableManagerServiceRef, CyEdge.class);
Properties getEdgeAttributeTaskFactoryProps = new Properties();
getEdgeAttributeTaskFactoryProps.setProperty(COMMAND, "get attribute");
getEdgeAttributeTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "edge");
registerService(bc,getEdgeAttributeTaskFactory,TaskFactory.class,getEdgeAttributeTaskFactoryProps);
GetPropertiesTaskFactory getEdgePropertiesTaskFactory =
new GetPropertiesTaskFactory(cyApplicationManagerServiceRef, CyEdge.class,
cyNetworkViewManagerServiceRef, renderingEngineManagerServiceRef);
Properties getEdgePropertiesTaskFactoryProps = new Properties();
getEdgePropertiesTaskFactoryProps.setProperty(COMMAND, "get properties");
getEdgePropertiesTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "edge");
registerService(bc,getEdgePropertiesTaskFactory,TaskFactory.class,getEdgePropertiesTaskFactoryProps);
ListEdgesTaskFactory listEdges = new ListEdgesTaskFactory(cyApplicationManagerServiceRef);
Properties listEdgesTaskFactoryProps = new Properties();
listEdgesTaskFactoryProps.setProperty(COMMAND, "list");
listEdgesTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "edge");
registerService(bc,listEdges,TaskFactory.class,listEdgesTaskFactoryProps);
ListNetworkAttributesTaskFactory listEdgeAttributesTaskFactory =
new ListNetworkAttributesTaskFactory(cyApplicationManagerServiceRef,
cyTableManagerServiceRef, CyEdge.class);
Properties listEdgeAttributesTaskFactoryProps = new Properties();
listEdgeAttributesTaskFactoryProps.setProperty(COMMAND, "list attributes");
listEdgeAttributesTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "edge");
registerService(bc,listEdgeAttributesTaskFactory,TaskFactory.class,listEdgeAttributesTaskFactoryProps);
ListPropertiesTaskFactory listEdgeProperties =
new ListPropertiesTaskFactory(cyApplicationManagerServiceRef,
CyEdge.class, cyNetworkViewManagerServiceRef,
renderingEngineManagerServiceRef);
Properties listEdgePropertiesTaskFactoryProps = new Properties();
listEdgePropertiesTaskFactoryProps.setProperty(COMMAND, "list properties");
listEdgePropertiesTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "edge");
registerService(bc,listEdgeProperties,TaskFactory.class,listEdgePropertiesTaskFactoryProps);
RenameEdgeTaskFactory renameEdge = new RenameEdgeTaskFactory();
Properties renameEdgeTaskFactoryProps = new Properties();
renameEdgeTaskFactoryProps.setProperty(COMMAND, "rename");
renameEdgeTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "edge");
registerService(bc,renameEdge,TaskFactory.class,renameEdgeTaskFactoryProps);
SetNetworkAttributeTaskFactory setEdgeAttributeTaskFactory =
new SetNetworkAttributeTaskFactory(cyApplicationManagerServiceRef, cyTableManagerServiceRef, CyEdge.class);
Properties setEdgeAttributeTaskFactoryProps = new Properties();
setEdgeAttributeTaskFactoryProps.setProperty(COMMAND, "set attribute");
setEdgeAttributeTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "edge");
registerService(bc,setEdgeAttributeTaskFactory,TaskFactory.class,setEdgeAttributeTaskFactoryProps);
SetPropertiesTaskFactory setEdgePropertiesTaskFactory =
new SetPropertiesTaskFactory(cyApplicationManagerServiceRef, CyEdge.class,
cyNetworkViewManagerServiceRef, renderingEngineManagerServiceRef);
Properties setEdgePropertiesTaskFactoryProps = new Properties();
setEdgePropertiesTaskFactoryProps.setProperty(COMMAND, "set properties");
setEdgePropertiesTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "edge");
registerService(bc,setEdgePropertiesTaskFactory,TaskFactory.class,setEdgePropertiesTaskFactoryProps);
// NAMESPACE: group
AddToGroupTaskFactory addToGroupTaskFactory =
new AddToGroupTaskFactory(cyApplicationManagerServiceRef, cyGroupManager);
Properties addToGroupTFProps = new Properties();
addToGroupTFProps.setProperty(COMMAND, "add");
addToGroupTFProps.setProperty(COMMAND_NAMESPACE, "group");
registerService(bc,addToGroupTaskFactory,TaskFactory.class,addToGroupTFProps);
ListGroupsTaskFactory listGroupsTaskFactory =
new ListGroupsTaskFactory(cyApplicationManagerServiceRef, cyGroupManager);
Properties listGroupsTFProps = new Properties();
listGroupsTFProps.setProperty(COMMAND, "list");
listGroupsTFProps.setProperty(COMMAND_NAMESPACE, "group");
registerService(bc,listGroupsTaskFactory,TaskFactory.class,listGroupsTFProps);
RemoveFromGroupTaskFactory removeFromGroupTaskFactory =
new RemoveFromGroupTaskFactory(cyApplicationManagerServiceRef, cyGroupManager);
Properties removeFromGroupTFProps = new Properties();
removeFromGroupTFProps.setProperty(COMMAND, "remove");
removeFromGroupTFProps.setProperty(COMMAND_NAMESPACE, "group");
registerService(bc,removeFromGroupTaskFactory,TaskFactory.class,removeFromGroupTFProps);
RenameGroupTaskFactory renameGroupTaskFactory =
new RenameGroupTaskFactory(cyApplicationManagerServiceRef, cyGroupManager);
Properties renameGroupTFProps = new Properties();
renameGroupTFProps.setProperty(COMMAND, "rename");
renameGroupTFProps.setProperty(COMMAND_NAMESPACE, "group");
registerService(bc,renameGroupTaskFactory,TaskFactory.class,renameGroupTFProps);
// NAMESPACE: layout
GetPreferredLayoutTaskFactory getPreferredLayoutTaskFactory =
new GetPreferredLayoutTaskFactory(cyLayoutsServiceRef,cyPropertyServiceRef);
Properties getPreferredTFProps = new Properties();
getPreferredTFProps.setProperty(COMMAND, "get preferred");
getPreferredTFProps.setProperty(COMMAND_NAMESPACE, "layout");
registerService(bc,getPreferredLayoutTaskFactory,TaskFactory.class,getPreferredTFProps);
SetPreferredLayoutTaskFactory setPreferredLayoutTaskFactory =
new SetPreferredLayoutTaskFactory(cyLayoutsServiceRef,cyPropertyServiceRef);
Properties setPreferredTFProps = new Properties();
setPreferredTFProps.setProperty(COMMAND, "set preferred");
setPreferredTFProps.setProperty(COMMAND_NAMESPACE, "layout");
registerService(bc,setPreferredLayoutTaskFactory,TaskFactory.class,setPreferredTFProps);
// NAMESPACE: network
AddTaskFactory addTaskFactory = new AddTaskFactory();
Properties addTaskFactoryProps = new Properties();
addTaskFactoryProps.setProperty(COMMAND, "add");
addTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "network");
registerService(bc,addTaskFactory,TaskFactory.class,addTaskFactoryProps);
AddEdgeTaskFactory addEdgeTaskFactory = new AddEdgeTaskFactory();
Properties addEdgeTaskFactoryProps = new Properties();
addEdgeTaskFactoryProps.setProperty(COMMAND, "add edge");
addEdgeTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "network");
registerService(bc,addEdgeTaskFactory,TaskFactory.class,addEdgeTaskFactoryProps);
AddNodeTaskFactory addNodeTaskFactory = new AddNodeTaskFactory();
Properties addNodeTaskFactoryProps = new Properties();
addNodeTaskFactoryProps.setProperty(COMMAND, "add node");
addNodeTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "network");
registerService(bc,addNodeTaskFactory,TaskFactory.class,addNodeTaskFactoryProps);
CreateNetworkAttributeTaskFactory createNetworkAttributeTaskFactory =
new CreateNetworkAttributeTaskFactory(cyApplicationManagerServiceRef,
cyTableManagerServiceRef, CyNetwork.class);
Properties createNetworkAttributeTaskFactoryProps = new Properties();
createNetworkAttributeTaskFactoryProps.setProperty(COMMAND, "create attribute");
createNetworkAttributeTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "network");
registerService(bc,createNetworkAttributeTaskFactory,TaskFactory.class,createNetworkAttributeTaskFactoryProps);
DeselectTaskFactory deselectTaskFactory = new DeselectTaskFactory(cyNetworkViewManagerServiceRef, cyEventHelperRef);
Properties deselectTaskFactoryProps = new Properties();
deselectTaskFactoryProps.setProperty(COMMAND, "deselect");
deselectTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "network");
registerService(bc,deselectTaskFactory,TaskFactory.class,deselectTaskFactoryProps);
GetNetworkTaskFactory getNetwork = new GetNetworkTaskFactory(cyApplicationManagerServiceRef);
Properties getNetworkTaskFactoryProps = new Properties();
getNetworkTaskFactoryProps.setProperty(COMMAND, "get");
getNetworkTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "network");
registerService(bc,getNetwork,TaskFactory.class,getNetworkTaskFactoryProps);
GetNetworkAttributeTaskFactory getNetworkAttributeTaskFactory =
new GetNetworkAttributeTaskFactory(cyApplicationManagerServiceRef, cyTableManagerServiceRef, CyNetwork.class);
Properties getNetworkAttributeTaskFactoryProps = new Properties();
getNetworkAttributeTaskFactoryProps.setProperty(COMMAND, "get attribute");
getNetworkAttributeTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "network");
registerService(bc,getNetworkAttributeTaskFactory,TaskFactory.class,getNetworkAttributeTaskFactoryProps);
GetPropertiesTaskFactory getNetworkPropertiesTaskFactory =
new GetPropertiesTaskFactory(cyApplicationManagerServiceRef, CyNetwork.class,
cyNetworkViewManagerServiceRef, renderingEngineManagerServiceRef);
Properties getNetworkPropertiesTaskFactoryProps = new Properties();
getNetworkPropertiesTaskFactoryProps.setProperty(COMMAND, "get properties");
getNetworkPropertiesTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "network");
registerService(bc,getNetworkPropertiesTaskFactory,TaskFactory.class,getNetworkPropertiesTaskFactoryProps);
HideTaskFactory hideTaskFactory = new HideTaskFactory(cyApplicationManagerServiceRef, cyNetworkViewManagerServiceRef,
visualMappingManagerServiceRef);
Properties hideTaskFactoryProps = new Properties();
hideTaskFactoryProps.setProperty(COMMAND, "hide");
hideTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "network");
registerService(bc,hideTaskFactory,TaskFactory.class,hideTaskFactoryProps);
ListNetworksTaskFactory listNetworks = new ListNetworksTaskFactory(cyNetworkManagerServiceRef);
Properties listNetworksTaskFactoryProps = new Properties();
listNetworksTaskFactoryProps.setProperty(COMMAND, "list");
listNetworksTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "network");
registerService(bc,listNetworks,TaskFactory.class,listNetworksTaskFactoryProps);
ListNetworkAttributesTaskFactory listNetworkAttributesTaskFactory =
new ListNetworkAttributesTaskFactory(cyApplicationManagerServiceRef,
cyTableManagerServiceRef, CyNetwork.class);
Properties listNetworkAttributesTaskFactoryProps = new Properties();
listNetworkAttributesTaskFactoryProps.setProperty(COMMAND, "list attributes");
listNetworkAttributesTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "network");
registerService(bc,listNetworkAttributesTaskFactory,TaskFactory.class,listNetworkAttributesTaskFactoryProps);
ListPropertiesTaskFactory listNetworkProperties =
new ListPropertiesTaskFactory(cyApplicationManagerServiceRef,
CyNetwork.class, cyNetworkViewManagerServiceRef,
renderingEngineManagerServiceRef);
Properties listNetworkPropertiesTaskFactoryProps = new Properties();
listNetworkPropertiesTaskFactoryProps.setProperty(COMMAND, "list properties");
listNetworkPropertiesTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "network");
registerService(bc,listNetworkProperties,TaskFactory.class,listNetworkPropertiesTaskFactoryProps);
SelectTaskFactory selectTaskFactory = new SelectTaskFactory(cyApplicationManagerServiceRef,
cyNetworkViewManagerServiceRef, cyEventHelperRef); Properties selectTaskFactoryProps = new Properties();
selectTaskFactoryProps.setProperty(COMMAND, "select");
selectTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "network");
registerService(bc,selectTaskFactory,TaskFactory.class,selectTaskFactoryProps);
SetNetworkAttributeTaskFactory setNetworkAttributeTaskFactory =
new SetNetworkAttributeTaskFactory(cyApplicationManagerServiceRef, cyTableManagerServiceRef, CyNetwork.class);
Properties setNetworkAttributeTaskFactoryProps = new Properties();
setNetworkAttributeTaskFactoryProps.setProperty(COMMAND, "set attribute");
setNetworkAttributeTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "network");
registerService(bc,setNetworkAttributeTaskFactory,TaskFactory.class,setNetworkAttributeTaskFactoryProps);
SetCurrentNetworkTaskFactory setCurrentNetwork = new SetCurrentNetworkTaskFactory(cyApplicationManagerServiceRef);
Properties setCurrentNetworkTaskFactoryProps = new Properties();
setCurrentNetworkTaskFactoryProps.setProperty(COMMAND, "set current");
setCurrentNetworkTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "network");
registerService(bc,setCurrentNetwork,TaskFactory.class,setCurrentNetworkTaskFactoryProps);
SetPropertiesTaskFactory setNetworkPropertiesTaskFactory =
new SetPropertiesTaskFactory(cyApplicationManagerServiceRef, CyNetwork.class,
cyNetworkViewManagerServiceRef, renderingEngineManagerServiceRef);
Properties setNetworkPropertiesTaskFactoryProps = new Properties();
setNetworkPropertiesTaskFactoryProps.setProperty(COMMAND, "set properties");
setNetworkPropertiesTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "network");
registerService(bc,setNetworkPropertiesTaskFactory,TaskFactory.class,setNetworkPropertiesTaskFactoryProps);
UnHideTaskFactory unHideTaskFactory = new UnHideTaskFactory(cyApplicationManagerServiceRef, cyNetworkViewManagerServiceRef,
visualMappingManagerServiceRef);
Properties unHideTaskFactoryProps = new Properties();
unHideTaskFactoryProps.setProperty(COMMAND, "show");
unHideTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "network");
registerService(bc,unHideTaskFactory,TaskFactory.class,unHideTaskFactoryProps);
// NAMESPACE: node
CreateNetworkAttributeTaskFactory createNodeAttributeTaskFactory =
new CreateNetworkAttributeTaskFactory(cyApplicationManagerServiceRef,
cyTableManagerServiceRef, CyNode.class);
Properties createNodeAttributeTaskFactoryProps = new Properties();
createNodeAttributeTaskFactoryProps.setProperty(COMMAND, "create attribute");
createNodeAttributeTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "node");
registerService(bc,createNodeAttributeTaskFactory,TaskFactory.class,createNodeAttributeTaskFactoryProps);
GetNodeTaskFactory getNodeTaskFactory = new GetNodeTaskFactory(cyApplicationManagerServiceRef);
Properties getNodeTaskFactoryProps = new Properties();
getNodeTaskFactoryProps.setProperty(COMMAND, "get");
getNodeTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "node");
registerService(bc,getNodeTaskFactory,TaskFactory.class,getNodeTaskFactoryProps);
GetNetworkAttributeTaskFactory getNodeAttributeTaskFactory =
new GetNetworkAttributeTaskFactory(cyApplicationManagerServiceRef, cyTableManagerServiceRef, CyNode.class);
Properties getNodeAttributeTaskFactoryProps = new Properties();
getNodeAttributeTaskFactoryProps.setProperty(COMMAND, "get attribute");
getNodeAttributeTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "node");
registerService(bc,getNodeAttributeTaskFactory,TaskFactory.class,getNodeAttributeTaskFactoryProps);
GetPropertiesTaskFactory getNodePropertiesTaskFactory =
new GetPropertiesTaskFactory(cyApplicationManagerServiceRef, CyNode.class,
cyNetworkViewManagerServiceRef, renderingEngineManagerServiceRef);
Properties getNodePropertiesTaskFactoryProps = new Properties();
getNodePropertiesTaskFactoryProps.setProperty(COMMAND, "get properties");
getNodePropertiesTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "node");
registerService(bc,getNodePropertiesTaskFactory,TaskFactory.class,getNodePropertiesTaskFactoryProps);
ListNodesTaskFactory listNodes = new ListNodesTaskFactory(cyApplicationManagerServiceRef);
Properties listNodesTaskFactoryProps = new Properties();
listNodesTaskFactoryProps.setProperty(COMMAND, "list");
listNodesTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "node");
registerService(bc,listNodes,TaskFactory.class,listNodesTaskFactoryProps);
ListNetworkAttributesTaskFactory listNodeAttributesTaskFactory =
new ListNetworkAttributesTaskFactory(cyApplicationManagerServiceRef,
cyTableManagerServiceRef, CyNode.class);
Properties listNodeAttributesTaskFactoryProps = new Properties();
listNodeAttributesTaskFactoryProps.setProperty(COMMAND, "list attributes");
listNodeAttributesTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "node");
registerService(bc,listNodeAttributesTaskFactory,TaskFactory.class,listNodeAttributesTaskFactoryProps);
ListPropertiesTaskFactory listNodeProperties =
new ListPropertiesTaskFactory(cyApplicationManagerServiceRef,
CyNode.class, cyNetworkViewManagerServiceRef,
renderingEngineManagerServiceRef);
Properties listNodePropertiesTaskFactoryProps = new Properties();
listNodePropertiesTaskFactoryProps.setProperty(COMMAND, "list properties");
listNodePropertiesTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "node");
registerService(bc,listNodeProperties,TaskFactory.class,listNodePropertiesTaskFactoryProps);
RenameNodeTaskFactory renameNode = new RenameNodeTaskFactory();
Properties renameNodeTaskFactoryProps = new Properties();
renameNodeTaskFactoryProps.setProperty(COMMAND, "rename");
renameNodeTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "node");
registerService(bc,renameNode,TaskFactory.class,renameNodeTaskFactoryProps);
SetNetworkAttributeTaskFactory setNodeAttributeTaskFactory =
new SetNetworkAttributeTaskFactory(cyApplicationManagerServiceRef, cyTableManagerServiceRef, CyNode.class);
Properties setNodeAttributeTaskFactoryProps = new Properties();
setNodeAttributeTaskFactoryProps.setProperty(COMMAND, "set attribute");
setNodeAttributeTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "node");
registerService(bc,setNodeAttributeTaskFactory,TaskFactory.class,setNodeAttributeTaskFactoryProps);
SetPropertiesTaskFactory setNodePropertiesTaskFactory =
new SetPropertiesTaskFactory(cyApplicationManagerServiceRef, CyNode.class,
cyNetworkViewManagerServiceRef, renderingEngineManagerServiceRef);
Properties setNodePropertiesTaskFactoryProps = new Properties();
setNodePropertiesTaskFactoryProps.setProperty(COMMAND, "set properties");
setNodePropertiesTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "node");
registerService(bc,setNodePropertiesTaskFactory,TaskFactory.class,setNodePropertiesTaskFactoryProps);
// NAMESPACE: table
AddRowTaskFactory addRowTaskFactory =
new AddRowTaskFactory(cyApplicationManagerServiceRef, cyTableManagerServiceRef);
Properties addRowTaskFactoryProps = new Properties();
addRowTaskFactoryProps.setProperty(COMMAND, "add row");
addRowTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "table");
registerService(bc,addRowTaskFactory,TaskFactory.class,addRowTaskFactoryProps);
CreateColumnTaskFactory createColumnTaskFactory =
new CreateColumnTaskFactory(cyApplicationManagerServiceRef, cyTableManagerServiceRef);
Properties createColumnTaskFactoryProps = new Properties();
createColumnTaskFactoryProps.setProperty(COMMAND, "create column");
createColumnTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "table");
registerService(bc,createColumnTaskFactory,TaskFactory.class,createColumnTaskFactoryProps);
CreateTableTaskFactory createTableTaskFactory =
new CreateTableTaskFactory(cyApplicationManagerServiceRef,
cyTableFactoryServiceRef, cyTableManagerServiceRef);
Properties createTableTaskFactoryProps = new Properties();
createTableTaskFactoryProps.setProperty(COMMAND, "create table");
createTableTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "table");
registerService(bc,createTableTaskFactory,TaskFactory.class,createTableTaskFactoryProps);
DeleteColumnCommandTaskFactory deleteColumnCommandTaskFactory =
new DeleteColumnCommandTaskFactory(cyApplicationManagerServiceRef, cyTableManagerServiceRef);
Properties deleteColumnCommandTaskFactoryProps = new Properties();
deleteColumnCommandTaskFactoryProps.setProperty(COMMAND, "delete column");
deleteColumnCommandTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "table");
registerService(bc,deleteColumnCommandTaskFactory,TaskFactory.class,deleteColumnCommandTaskFactoryProps);
DeleteRowTaskFactory deleteRowTaskFactory =
new DeleteRowTaskFactory(cyApplicationManagerServiceRef, cyTableManagerServiceRef);
Properties deleteRowTaskFactoryProps = new Properties();
deleteRowTaskFactoryProps.setProperty(COMMAND, "delete row");
deleteRowTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "table");
registerService(bc,deleteRowTaskFactory,TaskFactory.class,deleteRowTaskFactoryProps);
DestroyTableTaskFactory destroyTableTaskFactory =
new DestroyTableTaskFactory(cyApplicationManagerServiceRef, cyTableManagerServiceRef);
Properties destroyTableTaskFactoryProps = new Properties();
destroyTableTaskFactoryProps.setProperty(COMMAND, "destroy");
destroyTableTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "table");
registerService(bc,destroyTableTaskFactory,TaskFactory.class,destroyTableTaskFactoryProps);
GetColumnTaskFactory getColumnTaskFactory =
new GetColumnTaskFactory(cyApplicationManagerServiceRef, cyTableManagerServiceRef);
Properties getColumnTaskFactoryProps = new Properties();
getColumnTaskFactoryProps.setProperty(COMMAND, "get column");
getColumnTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "table");
registerService(bc,getColumnTaskFactory,TaskFactory.class,getColumnTaskFactoryProps);
GetRowTaskFactory getRowTaskFactory =
new GetRowTaskFactory(cyApplicationManagerServiceRef, cyTableManagerServiceRef);
Properties getRowTaskFactoryProps = new Properties();
getRowTaskFactoryProps.setProperty(COMMAND, "get row");
getRowTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "table");
registerService(bc,getRowTaskFactory,TaskFactory.class,getRowTaskFactoryProps);
GetValueTaskFactory getValueTaskFactory =
new GetValueTaskFactory(cyApplicationManagerServiceRef, cyTableManagerServiceRef);
Properties getValueTaskFactoryProps = new Properties();
getValueTaskFactoryProps.setProperty(COMMAND, "get value");
getValueTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "table");
registerService(bc,getValueTaskFactory,TaskFactory.class,getValueTaskFactoryProps);
ListColumnsTaskFactory listColumnsTaskFactory =
new ListColumnsTaskFactory(cyApplicationManagerServiceRef, cyTableManagerServiceRef,
cyNetworkTableManagerServiceRef);
Properties listColumnsTaskFactoryProps = new Properties();
listColumnsTaskFactoryProps.setProperty(COMMAND, "list columns");
listColumnsTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "table");
registerService(bc,listColumnsTaskFactory,TaskFactory.class,listColumnsTaskFactoryProps);
ListRowsTaskFactory listRowsTaskFactory =
new ListRowsTaskFactory(cyApplicationManagerServiceRef, cyTableManagerServiceRef);
Properties listRowsTaskFactoryProps = new Properties();
listRowsTaskFactoryProps.setProperty(COMMAND, "list rows");
listRowsTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "table");
registerService(bc,listRowsTaskFactory,TaskFactory.class,listRowsTaskFactoryProps);
ListTablesTaskFactory listTablesTaskFactory =
new ListTablesTaskFactory(cyApplicationManagerServiceRef, cyTableManagerServiceRef,
cyNetworkTableManagerServiceRef);
Properties listTablesTaskFactoryProps = new Properties();
listTablesTaskFactoryProps.setProperty(COMMAND, "list");
listTablesTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "table");
registerService(bc,listTablesTaskFactory,TaskFactory.class,listTablesTaskFactoryProps);
SetTableTitleTaskFactory setTableTitleTaskFactory =
new SetTableTitleTaskFactory(cyApplicationManagerServiceRef, cyTableManagerServiceRef);
Properties setTableTitleTaskFactoryProps = new Properties();
setTableTitleTaskFactoryProps.setProperty(COMMAND, "set title");
setTableTitleTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "table");
registerService(bc,setTableTitleTaskFactory,TaskFactory.class,setTableTitleTaskFactoryProps);
SetValuesTaskFactory setValuesTaskFactory =
new SetValuesTaskFactory(cyApplicationManagerServiceRef, cyTableManagerServiceRef);
Properties setValuesTaskFactoryProps = new Properties();
setValuesTaskFactoryProps.setProperty(COMMAND, "set values");
setValuesTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "table");
registerService(bc,setValuesTaskFactory,TaskFactory.class,setValuesTaskFactoryProps);
// NAMESPACE: view
GetCurrentNetworkViewTaskFactory getCurrentView =
new GetCurrentNetworkViewTaskFactory(cyApplicationManagerServiceRef);
Properties getCurrentViewTaskFactoryProps = new Properties();
getCurrentViewTaskFactoryProps.setProperty(COMMAND, "get current");
getCurrentViewTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "view");
registerService(bc,getCurrentView,TaskFactory.class,getCurrentViewTaskFactoryProps);
ListNetworkViewsTaskFactory listNetworkViews =
new ListNetworkViewsTaskFactory(cyApplicationManagerServiceRef, cyNetworkViewManagerServiceRef);
Properties listNetworkViewsTaskFactoryProps = new Properties();
listNetworkViewsTaskFactoryProps.setProperty(COMMAND, "list");
listNetworkViewsTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "view");
registerService(bc,listNetworkViews,TaskFactory.class,listNetworkViewsTaskFactoryProps);
SetCurrentNetworkViewTaskFactory setCurrentView =
new SetCurrentNetworkViewTaskFactory(cyApplicationManagerServiceRef,
cyNetworkViewManagerServiceRef);
Properties setCurrentViewTaskFactoryProps = new Properties();
setCurrentViewTaskFactoryProps.setProperty(COMMAND, "set current");
setCurrentViewTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "view");
registerService(bc,setCurrentView,TaskFactory.class,setCurrentViewTaskFactoryProps);
UpdateNetworkViewTaskFactory updateView =
new UpdateNetworkViewTaskFactory(cyApplicationManagerServiceRef, cyNetworkViewManagerServiceRef);
Properties updateViewTaskFactoryProps = new Properties();
updateViewTaskFactoryProps.setProperty(COMMAND, "update");
updateViewTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "view");
registerService(bc,updateView,TaskFactory.class,updateViewTaskFactoryProps);
}
}
| true | true | public void start(BundleContext bc) {
CyEventHelper cyEventHelperRef = getService(bc,CyEventHelper.class);
RecentlyOpenedTracker recentlyOpenedTrackerServiceRef = getService(bc,RecentlyOpenedTracker.class);
CyNetworkNaming cyNetworkNamingServiceRef = getService(bc,CyNetworkNaming.class);
UndoSupport undoSupportServiceRef = getService(bc,UndoSupport.class);
CyNetworkViewFactory cyNetworkViewFactoryServiceRef = getService(bc,CyNetworkViewFactory.class);
CyNetworkFactory cyNetworkFactoryServiceRef = getService(bc,CyNetworkFactory.class);
CyRootNetworkManager cyRootNetworkFactoryServiceRef = getService(bc,CyRootNetworkManager.class);
CyNetworkReaderManager cyNetworkReaderManagerServiceRef = getService(bc,CyNetworkReaderManager.class);
CyTableReaderManager cyDataTableReaderManagerServiceRef = getService(bc,CyTableReaderManager.class);
VizmapReaderManager vizmapReaderManagerServiceRef = getService(bc,VizmapReaderManager.class);
VisualMappingManager visualMappingManagerServiceRef = getService(bc,VisualMappingManager.class);
StreamUtil streamUtilRef = getService(bc,StreamUtil.class);
PresentationWriterManager viewWriterManagerServiceRef = getService(bc,PresentationWriterManager.class);
CyNetworkViewWriterManager networkViewWriterManagerServiceRef = getService(bc,CyNetworkViewWriterManager.class);
VizmapWriterManager vizmapWriterManagerServiceRef = getService(bc,VizmapWriterManager.class);
CySessionWriterManager sessionWriterManagerServiceRef = getService(bc,CySessionWriterManager.class);
CySessionReaderManager sessionReaderManagerServiceRef = getService(bc,CySessionReaderManager.class);
CyNetworkManager cyNetworkManagerServiceRef = getService(bc,CyNetworkManager.class);
CyNetworkViewManager cyNetworkViewManagerServiceRef = getService(bc,CyNetworkViewManager.class);
CyApplicationManager cyApplicationManagerServiceRef = getService(bc,CyApplicationManager.class);
CySessionManager cySessionManagerServiceRef = getService(bc,CySessionManager.class);
CyProperty cyPropertyServiceRef = getService(bc,CyProperty.class,"(cyPropertyName=cytoscape3.props)");
CyTableFactory cyTableFactoryServiceRef = getService(bc,CyTableFactory.class);
CyTableManager cyTableManagerServiceRef = getService(bc,CyTableManager.class);
CyLayoutAlgorithmManager cyLayoutsServiceRef = getService(bc,CyLayoutAlgorithmManager.class);
CyTableWriterManager cyTableWriterManagerRef = getService(bc,CyTableWriterManager.class);
SynchronousTaskManager<?> synchronousTaskManagerServiceRef = getService(bc,SynchronousTaskManager.class);
TunableSetter tunableSetterServiceRef = getService(bc,TunableSetter.class);
CyRootNetworkManager rootNetworkManagerServiceRef = getService(bc, CyRootNetworkManager.class);
CyNetworkTableManager cyNetworkTableManagerServiceRef = getService(bc, CyNetworkTableManager.class);
RenderingEngineManager renderingEngineManagerServiceRef = getService(bc, RenderingEngineManager.class);
CyNetworkViewFactory nullNetworkViewFactory = getService(bc, CyNetworkViewFactory.class, "(id=NullCyNetworkViewFactory)");
CyGroupManager cyGroupManager = getService(bc, CyGroupManager.class);
CyGroupFactory cyGroupFactory = getService(bc, CyGroupFactory.class);
LoadVizmapFileTaskFactoryImpl loadVizmapFileTaskFactory = new LoadVizmapFileTaskFactoryImpl(vizmapReaderManagerServiceRef,visualMappingManagerServiceRef,synchronousTaskManagerServiceRef, tunableSetterServiceRef);
LoadNetworkFileTaskFactoryImpl loadNetworkFileTaskFactory = new LoadNetworkFileTaskFactoryImpl(cyNetworkReaderManagerServiceRef,cyNetworkManagerServiceRef,cyNetworkViewManagerServiceRef,cyPropertyServiceRef,cyNetworkNamingServiceRef, tunableSetterServiceRef, visualMappingManagerServiceRef, nullNetworkViewFactory);
LoadNetworkURLTaskFactoryImpl loadNetworkURLTaskFactory = new LoadNetworkURLTaskFactoryImpl(cyNetworkReaderManagerServiceRef,cyNetworkManagerServiceRef,cyNetworkViewManagerServiceRef,cyPropertyServiceRef,cyNetworkNamingServiceRef,streamUtilRef, synchronousTaskManagerServiceRef, tunableSetterServiceRef, visualMappingManagerServiceRef, nullNetworkViewFactory);
DeleteSelectedNodesAndEdgesTaskFactoryImpl deleteSelectedNodesAndEdgesTaskFactory = new DeleteSelectedNodesAndEdgesTaskFactoryImpl(cyApplicationManagerServiceRef, undoSupportServiceRef,cyNetworkViewManagerServiceRef,visualMappingManagerServiceRef,cyEventHelperRef);
SelectAllTaskFactoryImpl selectAllTaskFactory = new SelectAllTaskFactoryImpl(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef);
SelectAllEdgesTaskFactoryImpl selectAllEdgesTaskFactory = new SelectAllEdgesTaskFactoryImpl(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef);
SelectAllNodesTaskFactoryImpl selectAllNodesTaskFactory = new SelectAllNodesTaskFactoryImpl(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef);
SelectAdjacentEdgesTaskFactoryImpl selectAdjacentEdgesTaskFactory = new SelectAdjacentEdgesTaskFactoryImpl(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef);
SelectConnectedNodesTaskFactoryImpl selectConnectedNodesTaskFactory = new SelectConnectedNodesTaskFactoryImpl(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef);
SelectFirstNeighborsTaskFactoryImpl selectFirstNeighborsTaskFactory = new SelectFirstNeighborsTaskFactoryImpl(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef, CyEdge.Type.ANY);
SelectFirstNeighborsTaskFactoryImpl selectFirstNeighborsTaskFactoryInEdge = new SelectFirstNeighborsTaskFactoryImpl(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef, CyEdge.Type.INCOMING);
SelectFirstNeighborsTaskFactoryImpl selectFirstNeighborsTaskFactoryOutEdge = new SelectFirstNeighborsTaskFactoryImpl(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef, CyEdge.Type.OUTGOING);
DeselectAllTaskFactoryImpl deselectAllTaskFactory = new DeselectAllTaskFactoryImpl(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef);
DeselectAllEdgesTaskFactoryImpl deselectAllEdgesTaskFactory = new DeselectAllEdgesTaskFactoryImpl(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef);
DeselectAllNodesTaskFactoryImpl deselectAllNodesTaskFactory = new DeselectAllNodesTaskFactoryImpl(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef);
InvertSelectedEdgesTaskFactoryImpl invertSelectedEdgesTaskFactory = new InvertSelectedEdgesTaskFactoryImpl(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef);
InvertSelectedNodesTaskFactoryImpl invertSelectedNodesTaskFactory = new InvertSelectedNodesTaskFactoryImpl(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef);
SelectFromFileListTaskFactoryImpl selectFromFileListTaskFactory = new SelectFromFileListTaskFactoryImpl(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef, tunableSetterServiceRef);
SelectFirstNeighborsNodeViewTaskFactoryImpl selectFirstNeighborsNodeViewTaskFactory = new SelectFirstNeighborsNodeViewTaskFactoryImpl(CyEdge.Type.ANY);
HideSelectedTaskFactoryImpl hideSelectedTaskFactory = new HideSelectedTaskFactoryImpl(undoSupportServiceRef,cyEventHelperRef,visualMappingManagerServiceRef);
HideSelectedNodesTaskFactoryImpl hideSelectedNodesTaskFactory = new HideSelectedNodesTaskFactoryImpl(undoSupportServiceRef,cyEventHelperRef,visualMappingManagerServiceRef);
HideSelectedEdgesTaskFactoryImpl hideSelectedEdgesTaskFactory = new HideSelectedEdgesTaskFactoryImpl(undoSupportServiceRef,cyEventHelperRef,visualMappingManagerServiceRef);
UnHideAllTaskFactoryImpl unHideAllTaskFactory = new UnHideAllTaskFactoryImpl(undoSupportServiceRef,cyEventHelperRef,visualMappingManagerServiceRef);
UnHideAllNodesTaskFactoryImpl unHideAllNodesTaskFactory = new UnHideAllNodesTaskFactoryImpl(undoSupportServiceRef,cyEventHelperRef,visualMappingManagerServiceRef);
UnHideAllEdgesTaskFactoryImpl unHideAllEdgesTaskFactory = new UnHideAllEdgesTaskFactoryImpl(undoSupportServiceRef,cyEventHelperRef,visualMappingManagerServiceRef);
NewEmptyNetworkTaskFactoryImpl newEmptyNetworkTaskFactory = new NewEmptyNetworkTaskFactoryImpl(cyNetworkFactoryServiceRef,cyNetworkViewFactoryServiceRef,cyNetworkManagerServiceRef,cyNetworkViewManagerServiceRef,cyNetworkNamingServiceRef,synchronousTaskManagerServiceRef,visualMappingManagerServiceRef, cyRootNetworkFactoryServiceRef, cyApplicationManagerServiceRef);
CloneNetworkTaskFactoryImpl cloneNetworkTaskFactory = new CloneNetworkTaskFactoryImpl(cyNetworkManagerServiceRef,cyNetworkViewManagerServiceRef,visualMappingManagerServiceRef,cyNetworkFactoryServiceRef,cyNetworkViewFactoryServiceRef,cyNetworkNamingServiceRef,cyApplicationManagerServiceRef,cyNetworkTableManagerServiceRef,rootNetworkManagerServiceRef,cyGroupManager,cyGroupFactory,renderingEngineManagerServiceRef, nullNetworkViewFactory );
NewNetworkSelectedNodesEdgesTaskFactoryImpl newNetworkSelectedNodesEdgesTaskFactory = new NewNetworkSelectedNodesEdgesTaskFactoryImpl(undoSupportServiceRef,cyRootNetworkFactoryServiceRef,cyNetworkViewFactoryServiceRef,cyNetworkManagerServiceRef,cyNetworkViewManagerServiceRef,cyNetworkNamingServiceRef,visualMappingManagerServiceRef,cyApplicationManagerServiceRef,cyEventHelperRef,cyGroupManager,renderingEngineManagerServiceRef);
NewNetworkCommandTaskFactory newNetworkCommandTaskFactory = new NewNetworkCommandTaskFactory(undoSupportServiceRef,cyRootNetworkFactoryServiceRef,cyNetworkViewFactoryServiceRef,cyNetworkManagerServiceRef,cyNetworkViewManagerServiceRef,cyNetworkNamingServiceRef,visualMappingManagerServiceRef,cyApplicationManagerServiceRef,cyEventHelperRef,cyGroupManager,renderingEngineManagerServiceRef);
NewNetworkSelectedNodesOnlyTaskFactoryImpl newNetworkSelectedNodesOnlyTaskFactory = new NewNetworkSelectedNodesOnlyTaskFactoryImpl(undoSupportServiceRef,cyRootNetworkFactoryServiceRef,cyNetworkViewFactoryServiceRef,cyNetworkManagerServiceRef,cyNetworkViewManagerServiceRef,cyNetworkNamingServiceRef,visualMappingManagerServiceRef,cyApplicationManagerServiceRef,cyEventHelperRef,cyGroupManager,renderingEngineManagerServiceRef);
DestroyNetworkTaskFactoryImpl destroyNetworkTaskFactory = new DestroyNetworkTaskFactoryImpl(cyNetworkManagerServiceRef);
DestroyNetworkViewTaskFactoryImpl destroyNetworkViewTaskFactory = new DestroyNetworkViewTaskFactoryImpl(cyNetworkViewManagerServiceRef);
ZoomInTaskFactory zoomInTaskFactory = new ZoomInTaskFactory(undoSupportServiceRef, cyApplicationManagerServiceRef);
ZoomOutTaskFactory zoomOutTaskFactory = new ZoomOutTaskFactory(undoSupportServiceRef, cyApplicationManagerServiceRef);
FitSelectedTaskFactory fitSelectedTaskFactory = new FitSelectedTaskFactory(undoSupportServiceRef, cyApplicationManagerServiceRef);
FitContentTaskFactory fitContentTaskFactory = new FitContentTaskFactory(undoSupportServiceRef, cyApplicationManagerServiceRef);
NewSessionTaskFactoryImpl newSessionTaskFactory = new NewSessionTaskFactoryImpl(cySessionManagerServiceRef, tunableSetterServiceRef);
OpenSessionCommandTaskFactory openSessionCommandTaskFactory = new OpenSessionCommandTaskFactory(cySessionManagerServiceRef,sessionReaderManagerServiceRef,cyApplicationManagerServiceRef,cyNetworkManagerServiceRef,cyTableManagerServiceRef,cyNetworkTableManagerServiceRef,cyGroupManager,recentlyOpenedTrackerServiceRef);
OpenSessionTaskFactoryImpl openSessionTaskFactory = new OpenSessionTaskFactoryImpl(cySessionManagerServiceRef,sessionReaderManagerServiceRef,cyApplicationManagerServiceRef,cyNetworkManagerServiceRef,cyTableManagerServiceRef,cyNetworkTableManagerServiceRef,cyGroupManager,recentlyOpenedTrackerServiceRef,tunableSetterServiceRef);
SaveSessionTaskFactoryImpl saveSessionTaskFactory = new SaveSessionTaskFactoryImpl( sessionWriterManagerServiceRef, cySessionManagerServiceRef, recentlyOpenedTrackerServiceRef, cyEventHelperRef);
SaveSessionAsTaskFactoryImpl saveSessionAsTaskFactory = new SaveSessionAsTaskFactoryImpl( sessionWriterManagerServiceRef, cySessionManagerServiceRef, recentlyOpenedTrackerServiceRef, cyEventHelperRef, tunableSetterServiceRef);
ProxySettingsTaskFactoryImpl proxySettingsTaskFactory = new ProxySettingsTaskFactoryImpl(cyPropertyServiceRef, streamUtilRef);
EditNetworkTitleTaskFactoryImpl editNetworkTitleTaskFactory = new EditNetworkTitleTaskFactoryImpl(undoSupportServiceRef, cyNetworkManagerServiceRef, cyNetworkNamingServiceRef, tunableSetterServiceRef);
CreateNetworkViewTaskFactoryImpl createNetworkViewTaskFactory = new CreateNetworkViewTaskFactoryImpl(undoSupportServiceRef,cyNetworkViewFactoryServiceRef,cyNetworkViewManagerServiceRef,cyLayoutsServiceRef,cyEventHelperRef,visualMappingManagerServiceRef,renderingEngineManagerServiceRef,cyApplicationManagerServiceRef);
ExportNetworkImageTaskFactoryImpl exportNetworkImageTaskFactory = new ExportNetworkImageTaskFactoryImpl(viewWriterManagerServiceRef,cyApplicationManagerServiceRef);
ExportNetworkViewTaskFactoryImpl exportNetworkViewTaskFactory = new ExportNetworkViewTaskFactoryImpl(networkViewWriterManagerServiceRef, tunableSetterServiceRef);
ExportSelectedTableTaskFactoryImpl exportCurrentTableTaskFactory = new ExportSelectedTableTaskFactoryImpl(cyTableWriterManagerRef, cyTableManagerServiceRef, cyNetworkManagerServiceRef);
ApplyPreferredLayoutTaskFactoryImpl applyPreferredLayoutTaskFactory = new ApplyPreferredLayoutTaskFactoryImpl(cyApplicationManagerServiceRef, cyNetworkViewManagerServiceRef, cyLayoutsServiceRef,cyPropertyServiceRef);
DeleteColumnTaskFactoryImpl deleteColumnTaskFactory = new DeleteColumnTaskFactoryImpl(undoSupportServiceRef);
RenameColumnTaskFactoryImpl renameColumnTaskFactory = new RenameColumnTaskFactoryImpl(undoSupportServiceRef, tunableSetterServiceRef);
CopyValueToColumnTaskFactoryImpl copyValueToEntireColumnTaskFactory = new CopyValueToColumnTaskFactoryImpl(undoSupportServiceRef, false, "Apply to entire column");
CopyValueToColumnTaskFactoryImpl copyValueToSelectedNodesTaskFactory = new CopyValueToColumnTaskFactoryImpl(undoSupportServiceRef, true, "Apply to selected nodes");
CopyValueToColumnTaskFactoryImpl copyValueToSelectedEdgesTaskFactory = new CopyValueToColumnTaskFactoryImpl(undoSupportServiceRef, true, "Apply to selected edges");
DeleteTableTaskFactoryImpl deleteTableTaskFactory = new DeleteTableTaskFactoryImpl(cyTableManagerServiceRef);
ExportVizmapTaskFactoryImpl exportVizmapTaskFactory = new ExportVizmapTaskFactoryImpl(vizmapWriterManagerServiceRef,visualMappingManagerServiceRef, tunableSetterServiceRef);
ConnectSelectedNodesTaskFactoryImpl connectSelectedNodesTaskFactory = new ConnectSelectedNodesTaskFactoryImpl(undoSupportServiceRef, cyEventHelperRef, visualMappingManagerServiceRef, cyNetworkViewManagerServiceRef);
MapGlobalToLocalTableTaskFactoryImpl mapGlobal = new MapGlobalToLocalTableTaskFactoryImpl(cyTableManagerServiceRef, cyNetworkManagerServiceRef, tunableSetterServiceRef);
DynamicTaskFactoryProvisionerImpl dynamicTaskFactoryProvisionerImpl = new DynamicTaskFactoryProvisionerImpl(cyApplicationManagerServiceRef);
registerAllServices(bc, dynamicTaskFactoryProvisionerImpl, new Properties());
LoadAttributesFileTaskFactoryImpl loadAttrsFileTaskFactory = new LoadAttributesFileTaskFactoryImpl(cyDataTableReaderManagerServiceRef, tunableSetterServiceRef,cyNetworkManagerServiceRef, cyTableManagerServiceRef, rootNetworkManagerServiceRef );
LoadAttributesURLTaskFactoryImpl loadAttrsURLTaskFactory = new LoadAttributesURLTaskFactoryImpl(cyDataTableReaderManagerServiceRef, tunableSetterServiceRef, cyNetworkManagerServiceRef, cyTableManagerServiceRef, rootNetworkManagerServiceRef);
ImportAttributesFileTaskFactoryImpl importAttrsFileTaskFactory = new ImportAttributesFileTaskFactoryImpl(cyDataTableReaderManagerServiceRef, tunableSetterServiceRef,cyNetworkManagerServiceRef, cyTableManagerServiceRef, rootNetworkManagerServiceRef );
ImportAttributesURLTaskFactoryImpl importAttrsURLTaskFactory = new ImportAttributesURLTaskFactoryImpl(cyDataTableReaderManagerServiceRef, tunableSetterServiceRef, cyNetworkManagerServiceRef, cyTableManagerServiceRef, rootNetworkManagerServiceRef);
MergeDataTableTaskFactoryImpl mergeTableTaskFactory = new MergeDataTableTaskFactoryImpl( cyTableManagerServiceRef,cyNetworkManagerServiceRef,tunableSetterServiceRef, rootNetworkManagerServiceRef );
// Apply Visual Style Task
ApplyVisualStyleTaskFactoryimpl applyVisualStyleTaskFactory = new ApplyVisualStyleTaskFactoryimpl(visualMappingManagerServiceRef);
Properties applyVisualStyleProps = new Properties();
applyVisualStyleProps.setProperty(ID,"applyVisualStyleTaskFactory");
applyVisualStyleProps.setProperty(TITLE, "Apply Visual Style");
applyVisualStyleProps.setProperty(COMMAND,"apply");
applyVisualStyleProps.setProperty(COMMAND_NAMESPACE,"vizmap");
applyVisualStyleProps.setProperty(IN_NETWORK_PANEL_CONTEXT_MENU,"true");
applyVisualStyleProps.setProperty(ENABLE_FOR,"networkAndView");
registerService(bc, applyVisualStyleTaskFactory, NetworkViewCollectionTaskFactory.class, applyVisualStyleProps);
registerService(bc, applyVisualStyleTaskFactory, ApplyVisualStyleTaskFactory.class, applyVisualStyleProps);
// Clear edge bends
ClearEdgeBendTaskFactory clearEdgeBendTaskFactory = new ClearEdgeBendTaskFactory();
Properties clearEdgeBendProps = new Properties();
clearEdgeBendProps.setProperty(ID, "clearEdgeBendTaskFactory");
clearEdgeBendProps.setProperty(TITLE, "Clear Edge Bends");
clearEdgeBendProps.setProperty(IN_NETWORK_PANEL_CONTEXT_MENU, "true");
clearEdgeBendProps.setProperty(ENABLE_FOR, "networkAndView");
clearEdgeBendProps.setProperty(PREFERRED_MENU,"Layout");
clearEdgeBendProps.setProperty(MENU_GRAVITY,"0.1");
registerService(bc, clearEdgeBendTaskFactory, NetworkViewCollectionTaskFactory.class, clearEdgeBendProps);
Properties mapGlobalProps = new Properties();
/* mapGlobalProps.setProperty(ID,"mapGlobalToLocalTableTaskFactory");
mapGlobalProps.setProperty(PREFERRED_MENU,"Tools");
mapGlobalProps.setProperty(ACCELERATOR,"cmd m");
mapGlobalProps.setProperty(TITLE, "Map Table to Attributes");
mapGlobalProps.setProperty(MENU_GRAVITY,"1.0");
mapGlobalProps.setProperty(TOOL_BAR_GRAVITY,"3.0");
mapGlobalProps.setProperty(IN_TOOL_BAR,"false");
mapGlobalProps.setProperty(COMMAND,"map-global-to-local");
mapGlobalProps.setProperty(COMMAND_NAMESPACE,"table");
*/ registerService(bc, mapGlobal, TableTaskFactory.class, mapGlobalProps);
registerService(bc, mapGlobal, MapGlobalToLocalTableTaskFactory.class, mapGlobalProps);
Properties loadNetworkFileTaskFactoryProps = new Properties();
loadNetworkFileTaskFactoryProps.setProperty(ID,"loadNetworkFileTaskFactory");
loadNetworkFileTaskFactoryProps.setProperty(PREFERRED_MENU,"File.Import.Network");
loadNetworkFileTaskFactoryProps.setProperty(ACCELERATOR,"cmd l");
loadNetworkFileTaskFactoryProps.setProperty(TITLE,"File...");
loadNetworkFileTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"network");
loadNetworkFileTaskFactoryProps.setProperty(COMMAND,"load file");
loadNetworkFileTaskFactoryProps.setProperty(MENU_GRAVITY,"1.0");
loadNetworkFileTaskFactoryProps.setProperty(TOOL_BAR_GRAVITY,"3.0");
loadNetworkFileTaskFactoryProps.setProperty(LARGE_ICON_URL,getClass().getResource("/images/icons/net_file_import.png").toString());
loadNetworkFileTaskFactoryProps.setProperty(IN_TOOL_BAR,"true");
loadNetworkFileTaskFactoryProps.setProperty(TOOLTIP,"Import Network From File");
registerService(bc, loadNetworkFileTaskFactory, TaskFactory.class, loadNetworkFileTaskFactoryProps);
registerService(bc, loadNetworkFileTaskFactory, LoadNetworkFileTaskFactory.class, loadNetworkFileTaskFactoryProps);
Properties loadNetworkURLTaskFactoryProps = new Properties();
loadNetworkURLTaskFactoryProps.setProperty(ID,"loadNetworkURLTaskFactory");
loadNetworkURLTaskFactoryProps.setProperty(PREFERRED_MENU,"File.Import.Network");
loadNetworkURLTaskFactoryProps.setProperty(ACCELERATOR,"cmd shift l");
loadNetworkURLTaskFactoryProps.setProperty(MENU_GRAVITY,"2.0");
loadNetworkURLTaskFactoryProps.setProperty(TOOL_BAR_GRAVITY,"3.1");
loadNetworkURLTaskFactoryProps.setProperty(TITLE,"URL...");
loadNetworkURLTaskFactoryProps.setProperty(LARGE_ICON_URL,getClass().getResource("/images/icons/net_url_import.png").toString());
loadNetworkURLTaskFactoryProps.setProperty(IN_TOOL_BAR,"true");
loadNetworkURLTaskFactoryProps.setProperty(TOOLTIP,"Import Network From URL");
loadNetworkURLTaskFactoryProps.setProperty(COMMAND,"load url");
loadNetworkURLTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"network");
registerService(bc, loadNetworkURLTaskFactory, TaskFactory.class, loadNetworkURLTaskFactoryProps);
registerService(bc, loadNetworkURLTaskFactory, LoadNetworkURLTaskFactory.class, loadNetworkURLTaskFactoryProps);
Properties loadVizmapFileTaskFactoryProps = new Properties();
loadVizmapFileTaskFactoryProps.setProperty(PREFERRED_MENU,"File.Import");
loadVizmapFileTaskFactoryProps.setProperty(MENU_GRAVITY,"3.0");
loadVizmapFileTaskFactoryProps.setProperty(TITLE,"Vizmap File...");
loadVizmapFileTaskFactoryProps.setProperty(COMMAND,"load file");
loadVizmapFileTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"vizmap");
registerService(bc,loadVizmapFileTaskFactory,TaskFactory.class, loadVizmapFileTaskFactoryProps);
registerService(bc,loadVizmapFileTaskFactory,LoadVizmapFileTaskFactory.class, new Properties());
Properties importAttrsFileTaskFactoryProps = new Properties();
importAttrsFileTaskFactoryProps.setProperty(PREFERRED_MENU,"File.Import.Table");
importAttrsFileTaskFactoryProps.setProperty(MENU_GRAVITY,"1.1");
importAttrsFileTaskFactoryProps.setProperty(TOOL_BAR_GRAVITY,"3.2");
importAttrsFileTaskFactoryProps.setProperty(TITLE,"File...");
importAttrsFileTaskFactoryProps.setProperty(LARGE_ICON_URL,getClass().getResource("/images/icons/table_file_import.png").toString());
importAttrsFileTaskFactoryProps.setProperty(IN_TOOL_BAR,"true");
importAttrsFileTaskFactoryProps.setProperty(TOOLTIP,"Import Table From File");
importAttrsFileTaskFactoryProps.setProperty(COMMAND,"load file");
importAttrsFileTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"table");
importAttrsFileTaskFactoryProps.setProperty(ENABLE_FOR,"network");
registerService(bc,importAttrsFileTaskFactory,TaskFactory.class, importAttrsFileTaskFactoryProps);
registerService(bc,importAttrsFileTaskFactory,ImportTableFileTaskFactory.class, importAttrsFileTaskFactoryProps);
Properties importAttrsURLTaskFactoryProps = new Properties();
importAttrsURLTaskFactoryProps.setProperty(PREFERRED_MENU,"File.Import.Table");
importAttrsURLTaskFactoryProps.setProperty(MENU_GRAVITY,"1.2");
importAttrsURLTaskFactoryProps.setProperty(TOOL_BAR_GRAVITY,"3.3");
importAttrsURLTaskFactoryProps.setProperty(TITLE,"URL...");
importAttrsURLTaskFactoryProps.setProperty(LARGE_ICON_URL,getClass().getResource("/images/icons/table_url_import.png").toString());
importAttrsURLTaskFactoryProps.setProperty(IN_TOOL_BAR,"true");
importAttrsURLTaskFactoryProps.setProperty(TOOLTIP,"Import Table From URL");
importAttrsURLTaskFactoryProps.setProperty(COMMAND,"load url");
importAttrsURLTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"table");
importAttrsURLTaskFactoryProps.setProperty(ENABLE_FOR,"network");
registerService(bc,importAttrsURLTaskFactory,TaskFactory.class, importAttrsURLTaskFactoryProps);
registerService(bc,importAttrsURLTaskFactory,ImportTableURLTaskFactory.class, importAttrsURLTaskFactoryProps);
Properties proxySettingsTaskFactoryProps = new Properties();
proxySettingsTaskFactoryProps.setProperty(PREFERRED_MENU,"Edit.Preferences");
proxySettingsTaskFactoryProps.setProperty(MENU_GRAVITY,"1.0");
proxySettingsTaskFactoryProps.setProperty(TITLE,"Proxy Settings...");
registerService(bc,proxySettingsTaskFactory,TaskFactory.class, proxySettingsTaskFactoryProps);
Properties deleteSelectedNodesAndEdgesTaskFactoryProps = new Properties();
deleteSelectedNodesAndEdgesTaskFactoryProps.setProperty(PREFERRED_MENU,"Edit");
deleteSelectedNodesAndEdgesTaskFactoryProps.setProperty(ENABLE_FOR,"selectedNodesOrEdges");
deleteSelectedNodesAndEdgesTaskFactoryProps.setProperty(TITLE,"Delete Selected Nodes and Edges...");
deleteSelectedNodesAndEdgesTaskFactoryProps.setProperty(MENU_GRAVITY,"5.0");
deleteSelectedNodesAndEdgesTaskFactoryProps.setProperty(ACCELERATOR,"DELETE");
deleteSelectedNodesAndEdgesTaskFactoryProps.setProperty(COMMAND,"delete");
deleteSelectedNodesAndEdgesTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"network");
registerService(bc,deleteSelectedNodesAndEdgesTaskFactory,NetworkTaskFactory.class, deleteSelectedNodesAndEdgesTaskFactoryProps);
registerService(bc,deleteSelectedNodesAndEdgesTaskFactory,DeleteSelectedNodesAndEdgesTaskFactory.class, deleteSelectedNodesAndEdgesTaskFactoryProps);
Properties selectAllTaskFactoryProps = new Properties();
selectAllTaskFactoryProps.setProperty(PREFERRED_MENU,"Select");
selectAllTaskFactoryProps.setProperty(ACCELERATOR,"cmd alt a");
selectAllTaskFactoryProps.setProperty(ENABLE_FOR,"network");
selectAllTaskFactoryProps.setProperty(TITLE,"Select all nodes and edges");
selectAllTaskFactoryProps.setProperty(MENU_GRAVITY,"5.0");
selectAllTaskFactoryProps.setProperty(PREFERRED_ACTION, "NEW");
// selectAllTaskFactoryProps.setProperty(COMMAND,"select all");
// selectAllTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"network");
registerService(bc,selectAllTaskFactory,NetworkTaskFactory.class, selectAllTaskFactoryProps);
registerService(bc,selectAllTaskFactory,SelectAllTaskFactory.class, selectAllTaskFactoryProps);
Properties selectAllViewTaskFactoryProps = new Properties();
selectAllViewTaskFactoryProps.setProperty(PREFERRED_MENU, NETWORK_SELECT_MENU);
selectAllViewTaskFactoryProps.setProperty(ENABLE_FOR,"networkAndView");
selectAllViewTaskFactoryProps.setProperty(TITLE,"All nodes and edges");
selectAllViewTaskFactoryProps.setProperty(MENU_GRAVITY,"1.1");
selectAllViewTaskFactoryProps.setProperty(PREFERRED_ACTION, "NEW");
selectAllViewTaskFactoryProps.setProperty(IN_MENU_BAR,"false");
registerService(bc,selectAllTaskFactory,NetworkViewTaskFactory.class, selectAllViewTaskFactoryProps);
Properties selectAllEdgesTaskFactoryProps = new Properties();
selectAllEdgesTaskFactoryProps.setProperty(PREFERRED_MENU,"Select.Edges");
selectAllEdgesTaskFactoryProps.setProperty(ACCELERATOR,"cmd alt a");
selectAllEdgesTaskFactoryProps.setProperty(ENABLE_FOR,"network");
selectAllEdgesTaskFactoryProps.setProperty(TITLE,"Select all edges");
selectAllEdgesTaskFactoryProps.setProperty(MENU_GRAVITY,"4.0");
registerService(bc,selectAllEdgesTaskFactory,NetworkTaskFactory.class, selectAllEdgesTaskFactoryProps);
registerService(bc,selectAllEdgesTaskFactory,SelectAllEdgesTaskFactory.class, selectAllEdgesTaskFactoryProps);
Properties selectAllNodesTaskFactoryProps = new Properties();
selectAllNodesTaskFactoryProps.setProperty(ENABLE_FOR,"network");
selectAllNodesTaskFactoryProps.setProperty(PREFERRED_MENU,"Select.Nodes");
selectAllNodesTaskFactoryProps.setProperty(MENU_GRAVITY,"4.0");
selectAllNodesTaskFactoryProps.setProperty(ACCELERATOR,"cmd a");
selectAllNodesTaskFactoryProps.setProperty(TITLE,"Select all nodes");
registerService(bc,selectAllNodesTaskFactory,NetworkTaskFactory.class, selectAllNodesTaskFactoryProps);
registerService(bc,selectAllNodesTaskFactory,SelectAllNodesTaskFactory.class, selectAllNodesTaskFactoryProps);
Properties selectAdjacentEdgesTaskFactoryProps = new Properties();
selectAdjacentEdgesTaskFactoryProps.setProperty(ENABLE_FOR,"network");
selectAdjacentEdgesTaskFactoryProps.setProperty(PREFERRED_MENU,"Select.Edges");
selectAdjacentEdgesTaskFactoryProps.setProperty(MENU_GRAVITY,"6.0");
selectAdjacentEdgesTaskFactoryProps.setProperty(ACCELERATOR,"alt e");
selectAdjacentEdgesTaskFactoryProps.setProperty(TITLE,"Select adjacent edges");
// selectAdjacentEdgesTaskFactoryProps.setProperty(COMMAND,"select adjacent");
// selectAdjacentEdgesTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"edge");
registerService(bc,selectAdjacentEdgesTaskFactory,NetworkTaskFactory.class, selectAdjacentEdgesTaskFactoryProps);
registerService(bc,selectAdjacentEdgesTaskFactory,SelectAdjacentEdgesTaskFactory.class, selectAdjacentEdgesTaskFactoryProps);
Properties selectConnectedNodesTaskFactoryProps = new Properties();
selectConnectedNodesTaskFactoryProps.setProperty(ENABLE_FOR,"network");
selectConnectedNodesTaskFactoryProps.setProperty(PREFERRED_MENU,"Select.Nodes");
selectConnectedNodesTaskFactoryProps.setProperty(MENU_GRAVITY,"7.0");
selectConnectedNodesTaskFactoryProps.setProperty(ACCELERATOR,"cmd 7");
selectConnectedNodesTaskFactoryProps.setProperty(TITLE,"Nodes connected by selected edges");
// selectConnectedNodesTaskFactoryProps.setProperty(COMMAND,"select by connected edges");
// selectConnectedNodesTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"node");
registerService(bc,selectConnectedNodesTaskFactory,NetworkTaskFactory.class, selectConnectedNodesTaskFactoryProps);
registerService(bc,selectConnectedNodesTaskFactory,SelectConnectedNodesTaskFactory.class, selectConnectedNodesTaskFactoryProps);
Properties selectFirstNeighborsTaskFactoryProps = new Properties();
selectFirstNeighborsTaskFactoryProps.setProperty(ENABLE_FOR,"selectedNodesOrEdges");
selectFirstNeighborsTaskFactoryProps.setProperty(PREFERRED_MENU,"Select.Nodes.First Neighbors of Selected Nodes");
selectFirstNeighborsTaskFactoryProps.setProperty(MENU_GRAVITY,"6.0");
selectFirstNeighborsTaskFactoryProps.setProperty(TOOL_BAR_GRAVITY,"9.15");
selectFirstNeighborsTaskFactoryProps.setProperty(ACCELERATOR,"cmd 6");
selectFirstNeighborsTaskFactoryProps.setProperty(TITLE,"Undirected");
selectFirstNeighborsTaskFactoryProps.setProperty(LARGE_ICON_URL,getClass().getResource("/images/icons/select_firstneighbors.png").toString());
selectFirstNeighborsTaskFactoryProps.setProperty(IN_TOOL_BAR,"true");
selectFirstNeighborsTaskFactoryProps.setProperty(TOOLTIP,"First Neighbors of Selected Nodes (Undirected)");
// selectFirstNeighborsTaskFactoryProps.setProperty(COMMAND,"select first neighbors undirected");
// selectFirstNeighborsTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"node");
registerService(bc,selectFirstNeighborsTaskFactory,NetworkTaskFactory.class, selectFirstNeighborsTaskFactoryProps);
registerService(bc,selectFirstNeighborsTaskFactory,SelectFirstNeighborsTaskFactory.class, selectFirstNeighborsTaskFactoryProps);
Properties selectFirstNeighborsTaskFactoryInEdgeProps = new Properties();
selectFirstNeighborsTaskFactoryInEdgeProps.setProperty(ENABLE_FOR,"network");
selectFirstNeighborsTaskFactoryInEdgeProps.setProperty(PREFERRED_MENU,"Select.Nodes.First Neighbors of Selected Nodes");
selectFirstNeighborsTaskFactoryInEdgeProps.setProperty(MENU_GRAVITY,"6.1");
selectFirstNeighborsTaskFactoryInEdgeProps.setProperty(TITLE,"Directed: Incoming");
selectFirstNeighborsTaskFactoryInEdgeProps.setProperty(TOOLTIP,"First Neighbors of Selected Nodes (Directed: Incoming)");
// selectFirstNeighborsTaskFactoryInEdgeProps.setProperty(COMMAND,"select first neighbors incoming");
// selectFirstNeighborsTaskFactoryInEdgeProps.setProperty(COMMAND_NAMESPACE,"node");
registerService(bc,selectFirstNeighborsTaskFactoryInEdge,NetworkTaskFactory.class, selectFirstNeighborsTaskFactoryInEdgeProps);
registerService(bc,selectFirstNeighborsTaskFactoryInEdge,SelectFirstNeighborsTaskFactory.class, selectFirstNeighborsTaskFactoryInEdgeProps);
Properties selectFirstNeighborsTaskFactoryOutEdgeProps = new Properties();
selectFirstNeighborsTaskFactoryOutEdgeProps.setProperty(ENABLE_FOR,"network");
selectFirstNeighborsTaskFactoryOutEdgeProps.setProperty(PREFERRED_MENU,"Select.Nodes.First Neighbors of Selected Nodes");
selectFirstNeighborsTaskFactoryOutEdgeProps.setProperty(MENU_GRAVITY,"6.2");
selectFirstNeighborsTaskFactoryOutEdgeProps.setProperty(TITLE,"Directed: Outgoing");
selectFirstNeighborsTaskFactoryOutEdgeProps.setProperty(TOOLTIP,"First Neighbors of Selected Nodes (Directed: Outgoing)");
// selectFirstNeighborsTaskFactoryOutEdgeProps.setProperty(COMMAND,"select first neighbors outgoing");
// selectFirstNeighborsTaskFactoryOutEdgeProps.setProperty(COMMAND_NAMESPACE,"node");
registerService(bc,selectFirstNeighborsTaskFactoryOutEdge,NetworkTaskFactory.class, selectFirstNeighborsTaskFactoryOutEdgeProps);
registerService(bc,selectFirstNeighborsTaskFactoryOutEdge,SelectFirstNeighborsTaskFactory.class, selectFirstNeighborsTaskFactoryOutEdgeProps);
Properties deselectAllTaskFactoryProps = new Properties();
deselectAllTaskFactoryProps.setProperty(ENABLE_FOR,"network");
deselectAllTaskFactoryProps.setProperty(PREFERRED_MENU,"Select");
deselectAllTaskFactoryProps.setProperty(MENU_GRAVITY,"5.1");
deselectAllTaskFactoryProps.setProperty(ACCELERATOR,"cmd shift alt a");
deselectAllTaskFactoryProps.setProperty(TITLE,"Deselect all nodes and edges");
// deselectAllTaskFactoryProps.setProperty(COMMAND,"deselect all");
// deselectAllTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"network");
registerService(bc,deselectAllTaskFactory,NetworkTaskFactory.class, deselectAllTaskFactoryProps);
registerService(bc,deselectAllTaskFactory,DeselectAllTaskFactory.class, deselectAllTaskFactoryProps);
Properties deselectAllEdgesTaskFactoryProps = new Properties();
deselectAllEdgesTaskFactoryProps.setProperty(ENABLE_FOR,"network");
deselectAllEdgesTaskFactoryProps.setProperty(PREFERRED_MENU,"Select.Edges");
deselectAllEdgesTaskFactoryProps.setProperty(MENU_GRAVITY,"5.0");
deselectAllEdgesTaskFactoryProps.setProperty(ACCELERATOR,"alt shift a");
deselectAllEdgesTaskFactoryProps.setProperty(TITLE,"Deselect all edges");
registerService(bc,deselectAllEdgesTaskFactory,NetworkTaskFactory.class, deselectAllEdgesTaskFactoryProps);
registerService(bc,deselectAllEdgesTaskFactory,DeselectAllEdgesTaskFactory.class, deselectAllEdgesTaskFactoryProps);
Properties deselectAllNodesTaskFactoryProps = new Properties();
deselectAllNodesTaskFactoryProps.setProperty(ENABLE_FOR,"network");
deselectAllNodesTaskFactoryProps.setProperty(PREFERRED_MENU,"Select.Nodes");
deselectAllNodesTaskFactoryProps.setProperty(MENU_GRAVITY,"5.0");
deselectAllNodesTaskFactoryProps.setProperty(ACCELERATOR,"cmd shift a");
deselectAllNodesTaskFactoryProps.setProperty(TITLE,"Deselect all nodes");
registerService(bc,deselectAllNodesTaskFactory,NetworkTaskFactory.class, deselectAllNodesTaskFactoryProps);
registerService(bc,deselectAllNodesTaskFactory,DeselectAllNodesTaskFactory.class, deselectAllNodesTaskFactoryProps);
Properties invertSelectedEdgesTaskFactoryProps = new Properties();
invertSelectedEdgesTaskFactoryProps.setProperty(ENABLE_FOR,"network");
invertSelectedEdgesTaskFactoryProps.setProperty(PREFERRED_MENU,"Select.Edges");
invertSelectedEdgesTaskFactoryProps.setProperty(MENU_GRAVITY,"1.0");
invertSelectedEdgesTaskFactoryProps.setProperty(ACCELERATOR,"alt i");
invertSelectedEdgesTaskFactoryProps.setProperty(TITLE,"Invert edge selection");
registerService(bc,invertSelectedEdgesTaskFactory,NetworkTaskFactory.class, invertSelectedEdgesTaskFactoryProps);
registerService(bc,invertSelectedEdgesTaskFactory,InvertSelectedEdgesTaskFactory.class, invertSelectedEdgesTaskFactoryProps);
Properties invertSelectedNodesTaskFactoryProps = new Properties();
invertSelectedNodesTaskFactoryProps.setProperty(ENABLE_FOR,"selectedNodes");
invertSelectedNodesTaskFactoryProps.setProperty(PREFERRED_MENU,"Select.Nodes");
invertSelectedNodesTaskFactoryProps.setProperty(MENU_GRAVITY,"1.0");
invertSelectedNodesTaskFactoryProps.setProperty(TOOL_BAR_GRAVITY,"9.2");
invertSelectedNodesTaskFactoryProps.setProperty(ACCELERATOR,"cmd i");
invertSelectedNodesTaskFactoryProps.setProperty(TITLE,"Invert node selection");
invertSelectedNodesTaskFactoryProps.setProperty(LARGE_ICON_URL,getClass().getResource("/images/icons/invert_selection.png").toString());
invertSelectedNodesTaskFactoryProps.setProperty(IN_TOOL_BAR,"false");
invertSelectedNodesTaskFactoryProps.setProperty(TOOLTIP,"Invert Node Selection");
registerService(bc,invertSelectedNodesTaskFactory,NetworkTaskFactory.class, invertSelectedNodesTaskFactoryProps);
registerService(bc,invertSelectedNodesTaskFactory,InvertSelectedNodesTaskFactory.class, invertSelectedNodesTaskFactoryProps);
Properties selectFromFileListTaskFactoryProps = new Properties();
selectFromFileListTaskFactoryProps.setProperty(ENABLE_FOR,"network");
selectFromFileListTaskFactoryProps.setProperty(PREFERRED_MENU,"Select.Nodes");
selectFromFileListTaskFactoryProps.setProperty(MENU_GRAVITY,"8.0");
selectFromFileListTaskFactoryProps.setProperty(ACCELERATOR,"cmd i");
selectFromFileListTaskFactoryProps.setProperty(TITLE,"From ID List file...");
selectFromFileListTaskFactoryProps.setProperty(COMMAND,"select from file");
selectFromFileListTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"node");
registerService(bc,selectFromFileListTaskFactory,NetworkTaskFactory.class, selectFromFileListTaskFactoryProps);
registerService(bc,selectFromFileListTaskFactory,SelectFromFileListTaskFactory.class, selectFromFileListTaskFactoryProps);
Properties selectFirstNeighborsNodeViewTaskFactoryProps = new Properties();
selectFirstNeighborsNodeViewTaskFactoryProps.setProperty(PREFERRED_MENU,NODE_SELECT_MENU);
selectFirstNeighborsNodeViewTaskFactoryProps.setProperty(MENU_GRAVITY,"1.0");
selectFirstNeighborsNodeViewTaskFactoryProps.setProperty(TITLE,"Select First Neighbors (Undirected)");
registerService(bc,selectFirstNeighborsNodeViewTaskFactory,NodeViewTaskFactory.class, selectFirstNeighborsNodeViewTaskFactoryProps);
registerService(bc,selectFirstNeighborsNodeViewTaskFactory,SelectFirstNeighborsNodeViewTaskFactory.class, selectFirstNeighborsNodeViewTaskFactoryProps);
Properties hideSelectedTaskFactoryProps = new Properties();
hideSelectedTaskFactoryProps.setProperty(ENABLE_FOR,"selectedNodesOrEdges");
hideSelectedTaskFactoryProps.setProperty(PREFERRED_MENU,"Select");
hideSelectedTaskFactoryProps.setProperty(MENU_GRAVITY,"3.1");
hideSelectedTaskFactoryProps.setProperty(TOOL_BAR_GRAVITY,"9.5");
hideSelectedTaskFactoryProps.setProperty(TITLE,"Hide selected nodes and edges");
hideSelectedTaskFactoryProps.setProperty(LARGE_ICON_URL,getClass().getResource("/images/icons/hide_selected.png").toString());
hideSelectedTaskFactoryProps.setProperty(IN_TOOL_BAR,"true");
hideSelectedTaskFactoryProps.setProperty(TOOLTIP,"Hide Selected Nodes and Edges");
// hideSelectedTaskFactoryProps.setProperty(COMMAND,"hide selected");
// hideSelectedTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"view");
registerService(bc,hideSelectedTaskFactory,NetworkViewTaskFactory.class, hideSelectedTaskFactoryProps);
registerService(bc,hideSelectedTaskFactory,HideSelectedTaskFactory.class, hideSelectedTaskFactoryProps);
Properties hideSelectedNodesTaskFactoryProps = new Properties();
hideSelectedNodesTaskFactoryProps.setProperty(ENABLE_FOR,"selectedNodes");
hideSelectedNodesTaskFactoryProps.setProperty(PREFERRED_MENU,"Select.Nodes");
hideSelectedNodesTaskFactoryProps.setProperty(MENU_GRAVITY,"2.0");
hideSelectedNodesTaskFactoryProps.setProperty(TITLE,"Hide selected nodes");
// hideSelectedNodesTaskFactoryProps.setProperty(COMMAND,"hide selected nodes");
// hideSelectedNodesTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"view");
registerService(bc,hideSelectedNodesTaskFactory,NetworkViewTaskFactory.class, hideSelectedNodesTaskFactoryProps);
registerService(bc,hideSelectedNodesTaskFactory,HideSelectedNodesTaskFactory.class, hideSelectedNodesTaskFactoryProps);
Properties hideSelectedEdgesTaskFactoryProps = new Properties();
hideSelectedEdgesTaskFactoryProps.setProperty(ENABLE_FOR,"selectedEdges");
hideSelectedEdgesTaskFactoryProps.setProperty(PREFERRED_MENU,"Select.Edges");
hideSelectedEdgesTaskFactoryProps.setProperty(MENU_GRAVITY,"2.0");
hideSelectedEdgesTaskFactoryProps.setProperty(TITLE,"Hide selected edges");
// hideSelectedEdgesTaskFactoryProps.setProperty(COMMAND,"hide selected edges");
// hideSelectedEdgesTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"view");
registerService(bc,hideSelectedEdgesTaskFactory,NetworkViewTaskFactory.class, hideSelectedEdgesTaskFactoryProps);
registerService(bc,hideSelectedEdgesTaskFactory,HideSelectedEdgesTaskFactory.class, hideSelectedEdgesTaskFactoryProps);
Properties unHideAllTaskFactoryProps = new Properties();
unHideAllTaskFactoryProps.setProperty(ENABLE_FOR,"networkAndView");
unHideAllTaskFactoryProps.setProperty(PREFERRED_MENU,"Select");
unHideAllTaskFactoryProps.setProperty(MENU_GRAVITY,"3.0");
unHideAllTaskFactoryProps.setProperty(TOOL_BAR_GRAVITY,"9.6");
unHideAllTaskFactoryProps.setProperty(TITLE,"Show all nodes and edges");
// unHideAllTaskFactoryProps.setProperty(COMMAND,"show all");
// unHideAllTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"view");
unHideAllTaskFactoryProps.setProperty(LARGE_ICON_URL,getClass().getResource("/images/icons/unhide_all.png").toString());
unHideAllTaskFactoryProps.setProperty(IN_TOOL_BAR,"true");
unHideAllTaskFactoryProps.setProperty(TOOLTIP,"Show All Nodes and Edges");
registerService(bc,unHideAllTaskFactory,NetworkViewTaskFactory.class, unHideAllTaskFactoryProps);
registerService(bc,unHideAllTaskFactory,UnHideAllTaskFactory.class, unHideAllTaskFactoryProps);
Properties unHideAllNodesTaskFactoryProps = new Properties();
unHideAllNodesTaskFactoryProps.setProperty(ENABLE_FOR,"networkAndView");
unHideAllNodesTaskFactoryProps.setProperty(PREFERRED_MENU,"Select.Nodes");
unHideAllNodesTaskFactoryProps.setProperty(MENU_GRAVITY,"3.0");
unHideAllNodesTaskFactoryProps.setProperty(TITLE,"Show all nodes");
// unHideAllNodesTaskFactoryProps.setProperty(COMMAND,"show all nodes");
// unHideAllNodesTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"view");
registerService(bc,unHideAllNodesTaskFactory,NetworkViewTaskFactory.class, unHideAllNodesTaskFactoryProps);
registerService(bc,unHideAllNodesTaskFactory,UnHideAllNodesTaskFactory.class, unHideAllNodesTaskFactoryProps);
Properties unHideAllEdgesTaskFactoryProps = new Properties();
unHideAllEdgesTaskFactoryProps.setProperty(ENABLE_FOR,"networkAndView");
unHideAllEdgesTaskFactoryProps.setProperty(PREFERRED_MENU,"Select.Edges");
unHideAllEdgesTaskFactoryProps.setProperty(MENU_GRAVITY,"3.0");
unHideAllEdgesTaskFactoryProps.setProperty(TITLE,"Show all edges");
// unHideAllEdgesTaskFactoryProps.setProperty(COMMAND,"show all edges");
// unHideAllEdgesTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"view");
registerService(bc,unHideAllEdgesTaskFactory,NetworkViewTaskFactory.class, unHideAllEdgesTaskFactoryProps);
registerService(bc,unHideAllEdgesTaskFactory,UnHideAllEdgesTaskFactory.class, unHideAllEdgesTaskFactoryProps);
Properties newEmptyNetworkTaskFactoryProps = new Properties();
newEmptyNetworkTaskFactoryProps.setProperty(PREFERRED_MENU,"File.New.Network");
newEmptyNetworkTaskFactoryProps.setProperty(MENU_GRAVITY,"4.0");
newEmptyNetworkTaskFactoryProps.setProperty(TITLE,"Empty Network");
newEmptyNetworkTaskFactoryProps.setProperty(COMMAND,"create empty");
newEmptyNetworkTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"network");
registerService(bc,newEmptyNetworkTaskFactory,TaskFactory.class, newEmptyNetworkTaskFactoryProps);
registerService(bc,newEmptyNetworkTaskFactory,NewEmptyNetworkViewFactory.class, newEmptyNetworkTaskFactoryProps);
Properties newNetworkSelectedNodesEdgesTaskFactoryProps = new Properties();
newNetworkSelectedNodesEdgesTaskFactoryProps.setProperty(ENABLE_FOR,"selectedNodesOrEdges");
newNetworkSelectedNodesEdgesTaskFactoryProps.setProperty(PREFERRED_MENU,"File.New.Network");
newNetworkSelectedNodesEdgesTaskFactoryProps.setProperty(MENU_GRAVITY,"2.0");
newNetworkSelectedNodesEdgesTaskFactoryProps.setProperty(ACCELERATOR,"cmd shift n");
newNetworkSelectedNodesEdgesTaskFactoryProps.setProperty(TITLE,"From selected nodes, selected edges");
// newNetworkSelectedNodesEdgesTaskFactoryProps.setProperty(COMMAND,"create from selected nodes and edges");
// newNetworkSelectedNodesEdgesTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"network");
registerService(bc,newNetworkSelectedNodesEdgesTaskFactory,NetworkTaskFactory.class, newNetworkSelectedNodesEdgesTaskFactoryProps);
registerService(bc,newNetworkSelectedNodesEdgesTaskFactory,NewNetworkSelectedNodesAndEdgesTaskFactory.class, newNetworkSelectedNodesEdgesTaskFactoryProps);
Properties newNetworkSelectedNodesOnlyTaskFactoryProps = new Properties();
newNetworkSelectedNodesOnlyTaskFactoryProps.setProperty(PREFERRED_MENU,"File.New.Network");
newNetworkSelectedNodesOnlyTaskFactoryProps.setProperty(LARGE_ICON_URL,getClass().getResource("/images/icons/new_fromselected.png").toString());
newNetworkSelectedNodesOnlyTaskFactoryProps.setProperty(ACCELERATOR,"cmd n");
newNetworkSelectedNodesOnlyTaskFactoryProps.setProperty(ENABLE_FOR,"selectedNodes");
newNetworkSelectedNodesOnlyTaskFactoryProps.setProperty(TITLE,"From selected nodes, all edges");
newNetworkSelectedNodesOnlyTaskFactoryProps.setProperty(TOOL_BAR_GRAVITY,"9.1");
newNetworkSelectedNodesOnlyTaskFactoryProps.setProperty(IN_TOOL_BAR,"true");
newNetworkSelectedNodesOnlyTaskFactoryProps.setProperty(MENU_GRAVITY,"1.0");
newNetworkSelectedNodesOnlyTaskFactoryProps.setProperty(TOOLTIP,"New Network From Selection");
// newNetworkSelectedNodesOnlyTaskFactoryProps.setProperty(COMMAND,"create from selected nodes and all edges");
// newNetworkSelectedNodesOnlyTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"network");
registerService(bc,newNetworkSelectedNodesOnlyTaskFactory,NetworkTaskFactory.class, newNetworkSelectedNodesOnlyTaskFactoryProps);
registerService(bc,newNetworkSelectedNodesOnlyTaskFactory,NewNetworkSelectedNodesOnlyTaskFactory.class, newNetworkSelectedNodesOnlyTaskFactoryProps);
Properties newNetworkCommandTaskFactoryProps = new Properties();
newNetworkCommandTaskFactoryProps.setProperty(COMMAND,"create");
newNetworkCommandTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"network");
registerService(bc,newNetworkCommandTaskFactory,NetworkTaskFactory.class, newNetworkCommandTaskFactoryProps);
Properties cloneNetworkTaskFactoryProps = new Properties();
cloneNetworkTaskFactoryProps.setProperty(ENABLE_FOR,"network");
cloneNetworkTaskFactoryProps.setProperty(PREFERRED_MENU,"File.New.Network");
cloneNetworkTaskFactoryProps.setProperty(MENU_GRAVITY,"3.0");
cloneNetworkTaskFactoryProps.setProperty(TITLE,"Clone Current Network");
cloneNetworkTaskFactoryProps.setProperty(COMMAND,"clone");
cloneNetworkTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"network");
registerService(bc,cloneNetworkTaskFactory,NetworkTaskFactory.class, cloneNetworkTaskFactoryProps);
registerService(bc,cloneNetworkTaskFactory,CloneNetworkTaskFactory.class, cloneNetworkTaskFactoryProps);
Properties destroyNetworkTaskFactoryProps = new Properties();
destroyNetworkTaskFactoryProps.setProperty(PREFERRED_MENU,"Edit");
destroyNetworkTaskFactoryProps.setProperty(ACCELERATOR,"cmd shift w");
destroyNetworkTaskFactoryProps.setProperty(ENABLE_FOR,"network");
destroyNetworkTaskFactoryProps.setProperty(TITLE,"Destroy Network");
destroyNetworkTaskFactoryProps.setProperty(IN_NETWORK_PANEL_CONTEXT_MENU,"true");
destroyNetworkTaskFactoryProps.setProperty(MENU_GRAVITY,"3.2");
destroyNetworkTaskFactoryProps.setProperty(COMMAND,"destroy");
destroyNetworkTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"network");
registerService(bc,destroyNetworkTaskFactory,NetworkCollectionTaskFactory.class, destroyNetworkTaskFactoryProps);
registerService(bc,destroyNetworkTaskFactory,DestroyNetworkTaskFactory.class, destroyNetworkTaskFactoryProps);
registerService(bc,destroyNetworkTaskFactory,TaskFactory.class, destroyNetworkTaskFactoryProps);
Properties destroyNetworkViewTaskFactoryProps = new Properties();
destroyNetworkViewTaskFactoryProps.setProperty(PREFERRED_MENU,"Edit");
destroyNetworkViewTaskFactoryProps.setProperty(ACCELERATOR,"cmd w");
destroyNetworkViewTaskFactoryProps.setProperty(ENABLE_FOR,"networkAndView");
destroyNetworkViewTaskFactoryProps.setProperty(TITLE,"Destroy View");
destroyNetworkViewTaskFactoryProps.setProperty(IN_NETWORK_PANEL_CONTEXT_MENU,"true");
destroyNetworkViewTaskFactoryProps.setProperty(MENU_GRAVITY,"3.1");
destroyNetworkViewTaskFactoryProps.setProperty(COMMAND,"destroy");
destroyNetworkViewTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"view");
registerService(bc,destroyNetworkViewTaskFactory,NetworkViewCollectionTaskFactory.class, destroyNetworkViewTaskFactoryProps);
registerService(bc,destroyNetworkViewTaskFactory,DestroyNetworkViewTaskFactory.class, destroyNetworkViewTaskFactoryProps);
Properties zoomInTaskFactoryProps = new Properties();
zoomInTaskFactoryProps.setProperty(ACCELERATOR,"cmd equals");
zoomInTaskFactoryProps.setProperty(LARGE_ICON_URL,getClass().getResource("/images/icons/stock_zoom-in.png").toString());
zoomInTaskFactoryProps.setProperty(ENABLE_FOR,"networkAndView");
zoomInTaskFactoryProps.setProperty(TITLE,"Zoom In");
zoomInTaskFactoryProps.setProperty(TOOLTIP,"Zoom In");
zoomInTaskFactoryProps.setProperty(TOOL_BAR_GRAVITY,"5.1");
zoomInTaskFactoryProps.setProperty(IN_TOOL_BAR,"true");
// zoomInTaskFactoryProps.setProperty(COMMAND,"zoom in");
// zoomInTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"view");
registerService(bc,zoomInTaskFactory,NetworkTaskFactory.class, zoomInTaskFactoryProps);
Properties zoomOutTaskFactoryProps = new Properties();
zoomOutTaskFactoryProps.setProperty(ACCELERATOR,"cmd minus");
zoomOutTaskFactoryProps.setProperty(LARGE_ICON_URL,getClass().getResource("/images/icons/stock_zoom-out.png").toString());
zoomOutTaskFactoryProps.setProperty(ENABLE_FOR,"networkAndView");
zoomOutTaskFactoryProps.setProperty(TITLE,"Zoom Out");
zoomOutTaskFactoryProps.setProperty(TOOLTIP,"Zoom Out");
zoomOutTaskFactoryProps.setProperty(TOOL_BAR_GRAVITY,"5.2");
zoomOutTaskFactoryProps.setProperty(IN_TOOL_BAR,"true");
// zoomOutTaskFactoryProps.setProperty(COMMAND,"zoom out");
// zoomOutTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"view");
registerService(bc,zoomOutTaskFactory,NetworkTaskFactory.class, zoomOutTaskFactoryProps);
Properties fitSelectedTaskFactoryProps = new Properties();
fitSelectedTaskFactoryProps.setProperty(ACCELERATOR,"cmd shift f");
fitSelectedTaskFactoryProps.setProperty(LARGE_ICON_URL,getClass().getResource("/images/icons/stock_zoom-object.png").toString());
fitSelectedTaskFactoryProps.setProperty(ENABLE_FOR,"networkAndView");
fitSelectedTaskFactoryProps.setProperty(TITLE,"Fit Selected");
fitSelectedTaskFactoryProps.setProperty(TOOLTIP,"Zoom selected region");
fitSelectedTaskFactoryProps.setProperty(TOOL_BAR_GRAVITY,"5.4");
fitSelectedTaskFactoryProps.setProperty(IN_TOOL_BAR,"true");
fitSelectedTaskFactoryProps.setProperty(COMMAND,"fit selected");
fitSelectedTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"view");
registerService(bc,fitSelectedTaskFactory,NetworkTaskFactory.class, fitSelectedTaskFactoryProps);
Properties fitContentTaskFactoryProps = new Properties();
fitContentTaskFactoryProps.setProperty(ACCELERATOR,"cmd f");
fitContentTaskFactoryProps.setProperty(LARGE_ICON_URL,getClass().getResource("/images/icons/stock_zoom-1.png").toString());
fitContentTaskFactoryProps.setProperty(ENABLE_FOR,"networkAndView");
fitContentTaskFactoryProps.setProperty(TITLE,"Fit Content");
fitContentTaskFactoryProps.setProperty(TOOLTIP,"Zoom out to display all of current Network");
fitContentTaskFactoryProps.setProperty(TOOL_BAR_GRAVITY,"5.3");
fitContentTaskFactoryProps.setProperty(IN_TOOL_BAR,"true");
fitContentTaskFactoryProps.setProperty(COMMAND,"fit content");
fitContentTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"view");
registerService(bc,fitContentTaskFactory,NetworkTaskFactory.class, fitContentTaskFactoryProps);
Properties editNetworkTitleTaskFactoryProps = new Properties();
editNetworkTitleTaskFactoryProps.setProperty(ENABLE_FOR,"singleNetwork");
editNetworkTitleTaskFactoryProps.setProperty(PREFERRED_MENU,"Edit");
editNetworkTitleTaskFactoryProps.setProperty(MENU_GRAVITY,"5.5");
editNetworkTitleTaskFactoryProps.setProperty(TITLE,"Rename Network...");
editNetworkTitleTaskFactoryProps.setProperty(IN_NETWORK_PANEL_CONTEXT_MENU,"true");
editNetworkTitleTaskFactoryProps.setProperty(COMMAND,"rename");
editNetworkTitleTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"network");
registerService(bc,editNetworkTitleTaskFactory,NetworkTaskFactory.class, editNetworkTitleTaskFactoryProps);
registerService(bc,editNetworkTitleTaskFactory,EditNetworkTitleTaskFactory.class, editNetworkTitleTaskFactoryProps);
Properties createNetworkViewTaskFactoryProps = new Properties();
createNetworkViewTaskFactoryProps.setProperty(ID,"createNetworkViewTaskFactory");
// No ENABLE_FOR because that is handled by the isReady() methdod of the task factory.
createNetworkViewTaskFactoryProps.setProperty(PREFERRED_MENU,"Edit");
createNetworkViewTaskFactoryProps.setProperty(MENU_GRAVITY,"3.0");
createNetworkViewTaskFactoryProps.setProperty(TITLE,"Create View");
createNetworkViewTaskFactoryProps.setProperty(IN_NETWORK_PANEL_CONTEXT_MENU,"true");
createNetworkViewTaskFactoryProps.setProperty(COMMAND,"create");
createNetworkViewTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"view");
registerService(bc,createNetworkViewTaskFactory,NetworkCollectionTaskFactory.class, createNetworkViewTaskFactoryProps);
registerService(bc,createNetworkViewTaskFactory,CreateNetworkViewTaskFactory.class, createNetworkViewTaskFactoryProps);
// For commands
registerService(bc,createNetworkViewTaskFactory,TaskFactory.class, createNetworkViewTaskFactoryProps);
Properties exportNetworkImageTaskFactoryProps = new Properties();
exportNetworkImageTaskFactoryProps.setProperty(PREFERRED_MENU,"File.Export");
exportNetworkImageTaskFactoryProps.setProperty(LARGE_ICON_URL,getClass().getResource("/images/icons/img_file_export.png").toString());
exportNetworkImageTaskFactoryProps.setProperty(ENABLE_FOR,"networkAndView");
exportNetworkImageTaskFactoryProps.setProperty(MENU_GRAVITY,"1.2");
exportNetworkImageTaskFactoryProps.setProperty(TITLE,"Network View as Graphics...");
exportNetworkImageTaskFactoryProps.setProperty(TOOL_BAR_GRAVITY,"3.7");
exportNetworkImageTaskFactoryProps.setProperty(IN_TOOL_BAR,"true");
exportNetworkImageTaskFactoryProps.setProperty(IN_CONTEXT_MENU,"false");
exportNetworkImageTaskFactoryProps.setProperty(TOOLTIP,"Export Network Image to File");
exportNetworkImageTaskFactoryProps.setProperty(COMMAND,"export");
exportNetworkImageTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"view");
registerService(bc,exportNetworkImageTaskFactory,NetworkViewTaskFactory.class, exportNetworkImageTaskFactoryProps);
registerService(bc,exportNetworkImageTaskFactory,ExportNetworkImageTaskFactory.class, exportNetworkImageTaskFactoryProps);
Properties exportNetworkViewTaskFactoryProps = new Properties();
exportNetworkViewTaskFactoryProps.setProperty(ENABLE_FOR,"networkAndView");
exportNetworkViewTaskFactoryProps.setProperty(PREFERRED_MENU,"File.Export");
exportNetworkViewTaskFactoryProps.setProperty(MENU_GRAVITY,"1.1");
exportNetworkViewTaskFactoryProps.setProperty(TOOL_BAR_GRAVITY,"3.5");
exportNetworkViewTaskFactoryProps.setProperty(TITLE,"Network...");
exportNetworkViewTaskFactoryProps.setProperty(LARGE_ICON_URL,getClass().getResource("/images/icons/net_file_export.png").toString());
exportNetworkViewTaskFactoryProps.setProperty(IN_TOOL_BAR,"true");
exportNetworkViewTaskFactoryProps.setProperty(IN_CONTEXT_MENU,"false");
exportNetworkViewTaskFactoryProps.setProperty(TOOLTIP,"Export Network to File");
exportNetworkViewTaskFactoryProps.setProperty(COMMAND,"export");
exportNetworkViewTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"network");
registerService(bc,exportNetworkViewTaskFactory,NetworkViewTaskFactory.class, exportNetworkViewTaskFactoryProps);
registerService(bc,exportNetworkViewTaskFactory,ExportNetworkViewTaskFactory.class, exportNetworkViewTaskFactoryProps);
Properties exportCurrentTableTaskFactoryProps = new Properties();
exportCurrentTableTaskFactoryProps.setProperty(ENABLE_FOR,"table");
exportCurrentTableTaskFactoryProps.setProperty(PREFERRED_MENU,"File.Export");
exportCurrentTableTaskFactoryProps.setProperty(MENU_GRAVITY,"1.3");
exportCurrentTableTaskFactoryProps.setProperty(TOOL_BAR_GRAVITY,"3.6");
exportCurrentTableTaskFactoryProps.setProperty(TITLE,"Table...");
exportCurrentTableTaskFactoryProps.setProperty(LARGE_ICON_URL,getClass().getResource("/images/icons/table_file_export.png").toString());
exportCurrentTableTaskFactoryProps.setProperty(IN_TOOL_BAR,"true");
exportCurrentTableTaskFactoryProps.setProperty(TOOLTIP,"Export Table to File");
exportCurrentTableTaskFactoryProps.setProperty(COMMAND,"export");
exportCurrentTableTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"table");
registerService(bc,exportCurrentTableTaskFactory, TaskFactory.class, exportCurrentTableTaskFactoryProps);
registerService(bc,exportCurrentTableTaskFactory,ExportSelectedTableTaskFactory.class, exportCurrentTableTaskFactoryProps);
Properties exportVizmapTaskFactoryProps = new Properties();
exportVizmapTaskFactoryProps.setProperty(ENABLE_FOR,"vizmap");
exportVizmapTaskFactoryProps.setProperty(PREFERRED_MENU,"File.Export");
exportVizmapTaskFactoryProps.setProperty(MENU_GRAVITY,"1.4");
exportVizmapTaskFactoryProps.setProperty(TITLE,"Vizmap...");
exportVizmapTaskFactoryProps.setProperty(COMMAND,"export");
exportVizmapTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"vizmap");
registerService(bc,exportVizmapTaskFactory,TaskFactory.class, exportVizmapTaskFactoryProps);
registerService(bc,exportVizmapTaskFactory,ExportVizmapTaskFactory.class, exportVizmapTaskFactoryProps);
Properties loadDataFileTaskFactoryProps = new Properties();
loadDataFileTaskFactoryProps.setProperty(PREFERRED_MENU,"File.Load Data Table");
loadDataFileTaskFactoryProps.setProperty(MENU_GRAVITY,"1.1");
loadDataFileTaskFactoryProps.setProperty(TITLE,"File...");
//loadDataFileTaskFactoryProps.setProperty(ServiceProperties.INSERT_SEPARATOR_BEFORE, "true");
loadDataFileTaskFactoryProps.setProperty(TOOLTIP,"Load Data Table From File");
loadDataFileTaskFactoryProps.setProperty(COMMAND,"load file");
loadDataFileTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"table");
registerService(bc,loadAttrsFileTaskFactory,TaskFactory.class, loadDataFileTaskFactoryProps);
registerService(bc,loadAttrsFileTaskFactory,LoadTableFileTaskFactory.class, loadDataFileTaskFactoryProps);
Properties loadDataURLTaskFactoryProps = new Properties();
loadDataURLTaskFactoryProps.setProperty(PREFERRED_MENU,"File.Load Data Table");
loadDataURLTaskFactoryProps.setProperty(MENU_GRAVITY,"1.2");
loadDataURLTaskFactoryProps.setProperty(TITLE,"URL...");
loadDataURLTaskFactoryProps.setProperty(TOOLTIP,"Load Data Table From URL");
loadDataURLTaskFactoryProps.setProperty(COMMAND,"load url");
loadDataURLTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"table");
registerService(bc,loadAttrsURLTaskFactory,TaskFactory.class, loadDataURLTaskFactoryProps);
registerService(bc,loadAttrsURLTaskFactory,LoadTableURLTaskFactory.class, loadDataURLTaskFactoryProps);
Properties MergeGlobalTaskFactoryProps = new Properties();
MergeGlobalTaskFactoryProps.setProperty(ENABLE_FOR,"network");
MergeGlobalTaskFactoryProps.setProperty(PREFERRED_MENU,"File");
MergeGlobalTaskFactoryProps.setProperty(TITLE,"Merge Data Table...");
//MergeGlobalTaskFactoryProps.setProperty(ServiceProperties.INSERT_SEPARATOR_AFTER, "true");
//MergeGlobalTaskFactoryProps.setProperty(TOOL_BAR_GRAVITY,"1.1");
MergeGlobalTaskFactoryProps.setProperty(MENU_GRAVITY,"5.4");
MergeGlobalTaskFactoryProps.setProperty(TOOLTIP,"Merge Data Table");
registerService(bc,mergeTableTaskFactory,TaskFactory.class, MergeGlobalTaskFactoryProps);
registerService(bc,mergeTableTaskFactory,MergeDataTableTaskFactory.class, MergeGlobalTaskFactoryProps);
Properties newSessionTaskFactoryProps = new Properties();
newSessionTaskFactoryProps.setProperty(PREFERRED_MENU,"File.New");
newSessionTaskFactoryProps.setProperty(MENU_GRAVITY,"1.1");
newSessionTaskFactoryProps.setProperty(TITLE,"Session");
newSessionTaskFactoryProps.setProperty(COMMAND,"new");
newSessionTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"session");
registerService(bc,newSessionTaskFactory,TaskFactory.class, newSessionTaskFactoryProps);
registerService(bc,newSessionTaskFactory,NewSessionTaskFactory.class, newSessionTaskFactoryProps);
Properties openSessionTaskFactoryProps = new Properties();
openSessionTaskFactoryProps.setProperty(ID,"openSessionTaskFactory");
openSessionTaskFactoryProps.setProperty(PREFERRED_MENU,"File");
openSessionTaskFactoryProps.setProperty(ACCELERATOR,"cmd o");
openSessionTaskFactoryProps.setProperty(LARGE_ICON_URL,getClass().getResource("/images/icons/open_session.png").toString());
openSessionTaskFactoryProps.setProperty(TITLE,"Open...");
openSessionTaskFactoryProps.setProperty(TOOL_BAR_GRAVITY,"1.0");
openSessionTaskFactoryProps.setProperty(IN_TOOL_BAR,"true");
openSessionTaskFactoryProps.setProperty(MENU_GRAVITY,"1.0");
openSessionTaskFactoryProps.setProperty(TOOLTIP,"Open Session");
registerService(bc,openSessionTaskFactory,OpenSessionTaskFactory.class, openSessionTaskFactoryProps);
// We can't use the "normal" OpenSessionTaskFactory for commands
// because it inserts the task with the file tunable in it, so the
// Command processor never sees it, so we need a special OpenSessionTaskFactory
// for commands
// openSessionTaskFactoryProps.setProperty(COMMAND,"open");
// openSessionTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"session");
// registerService(bc,openSessionTaskFactory,TaskFactory.class, openSessionTaskFactoryProps);
Properties openSessionCommandTaskFactoryProps = new Properties();
openSessionCommandTaskFactoryProps.setProperty(COMMAND,"open");
openSessionCommandTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"session");
registerService(bc,openSessionCommandTaskFactory,TaskFactory.class, openSessionCommandTaskFactoryProps);
Properties saveSessionTaskFactoryProps = new Properties();
saveSessionTaskFactoryProps.setProperty(PREFERRED_MENU,"File");
saveSessionTaskFactoryProps.setProperty(ACCELERATOR,"cmd s");
saveSessionTaskFactoryProps.setProperty(LARGE_ICON_URL,getClass().getResource("/images/icons/stock_save.png").toString());
saveSessionTaskFactoryProps.setProperty(TITLE,"Save");
saveSessionTaskFactoryProps.setProperty(TOOL_BAR_GRAVITY,"1.1");
saveSessionTaskFactoryProps.setProperty(IN_TOOL_BAR,"true");
saveSessionTaskFactoryProps.setProperty(MENU_GRAVITY,"3.0");
saveSessionTaskFactoryProps.setProperty(TOOLTIP,"Save Session");
saveSessionTaskFactoryProps.setProperty(COMMAND,"save");
saveSessionTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"session");
registerService(bc,saveSessionTaskFactory,TaskFactory.class, saveSessionTaskFactoryProps);
Properties saveSessionAsTaskFactoryProps = new Properties();
saveSessionAsTaskFactoryProps.setProperty(PREFERRED_MENU,"File");
saveSessionAsTaskFactoryProps.setProperty(ACCELERATOR,"cmd shift s");
saveSessionAsTaskFactoryProps.setProperty(MENU_GRAVITY,"3.1");
saveSessionAsTaskFactoryProps.setProperty(TITLE,"Save As...");
saveSessionAsTaskFactoryProps.setProperty(COMMAND,"save as");
saveSessionAsTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"session");
registerService(bc,saveSessionAsTaskFactory,TaskFactory.class, saveSessionAsTaskFactoryProps);
registerService(bc,saveSessionAsTaskFactory,SaveSessionAsTaskFactory.class, saveSessionAsTaskFactoryProps);
Properties applyPreferredLayoutTaskFactoryProps = new Properties();
applyPreferredLayoutTaskFactoryProps.setProperty(PREFERRED_MENU,"Layout");
applyPreferredLayoutTaskFactoryProps.setProperty(ACCELERATOR,"fn5");
applyPreferredLayoutTaskFactoryProps.setProperty(LARGE_ICON_URL,getClass().getResource("/images/icons/apply_layout.png").toString());
applyPreferredLayoutTaskFactoryProps.setProperty(ENABLE_FOR,"networkAndView");
applyPreferredLayoutTaskFactoryProps.setProperty(TITLE,"Apply Preferred Layout");
applyPreferredLayoutTaskFactoryProps.setProperty(TOOL_BAR_GRAVITY,"7.0");
applyPreferredLayoutTaskFactoryProps.setProperty(IN_TOOL_BAR,"true");
applyPreferredLayoutTaskFactoryProps.setProperty(MENU_GRAVITY,"5.0");
applyPreferredLayoutTaskFactoryProps.setProperty(TOOLTIP,"Apply Preferred Layout");
registerService(bc,applyPreferredLayoutTaskFactory,NetworkViewCollectionTaskFactory.class, applyPreferredLayoutTaskFactoryProps);
registerService(bc,applyPreferredLayoutTaskFactory,ApplyPreferredLayoutTaskFactory.class, applyPreferredLayoutTaskFactoryProps);
// For commands
Properties applyPreferredLayoutTaskFactoryProps2 = new Properties();
applyPreferredLayoutTaskFactoryProps2.setProperty(COMMAND,"apply preferred");
applyPreferredLayoutTaskFactoryProps2.setProperty(COMMAND_NAMESPACE,"layout");
registerService(bc,applyPreferredLayoutTaskFactory,TaskFactory.class, applyPreferredLayoutTaskFactoryProps2);
Properties deleteColumnTaskFactoryProps = new Properties();
deleteColumnTaskFactoryProps.setProperty(TITLE,"Delete column");
deleteColumnTaskFactoryProps.setProperty(COMMAND,"delete column");
deleteColumnTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"table");
registerService(bc,deleteColumnTaskFactory,TableColumnTaskFactory.class, deleteColumnTaskFactoryProps);
registerService(bc,deleteColumnTaskFactory,DeleteColumnTaskFactory.class, deleteColumnTaskFactoryProps);
Properties renameColumnTaskFactoryProps = new Properties();
renameColumnTaskFactoryProps.setProperty(TITLE,"Rename column");
renameColumnTaskFactoryProps.setProperty(COMMAND,"rename column");
renameColumnTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"table");
registerService(bc,renameColumnTaskFactory,TableColumnTaskFactory.class, renameColumnTaskFactoryProps);
registerService(bc,renameColumnTaskFactory,RenameColumnTaskFactory.class, renameColumnTaskFactoryProps);
Properties copyValueToEntireColumnTaskFactoryProps = new Properties();
copyValueToEntireColumnTaskFactoryProps.setProperty(TITLE,copyValueToEntireColumnTaskFactory.getTaskFactoryName());
copyValueToEntireColumnTaskFactoryProps.setProperty("tableTypes", "node,edge,network,unassigned");
registerService(bc,copyValueToEntireColumnTaskFactory,TableCellTaskFactory.class, copyValueToEntireColumnTaskFactoryProps);
Properties copyValueToSelectedNodesTaskFactoryProps = new Properties();
copyValueToSelectedNodesTaskFactoryProps.setProperty(TITLE,copyValueToSelectedNodesTaskFactory.getTaskFactoryName());
copyValueToSelectedNodesTaskFactoryProps.setProperty("tableTypes", "node");
registerService(bc,copyValueToSelectedNodesTaskFactory,TableCellTaskFactory.class, copyValueToSelectedNodesTaskFactoryProps);
Properties copyValueToSelectedEdgesTaskFactoryProps = new Properties();
copyValueToSelectedEdgesTaskFactoryProps.setProperty(TITLE,copyValueToSelectedEdgesTaskFactory.getTaskFactoryName());
copyValueToSelectedEdgesTaskFactoryProps.setProperty("tableTypes", "edge");
registerService(bc,copyValueToSelectedEdgesTaskFactory,TableCellTaskFactory.class, copyValueToSelectedEdgesTaskFactoryProps);
registerService(bc,deleteTableTaskFactory,TableTaskFactory.class, new Properties());
registerService(bc,deleteTableTaskFactory,DeleteTableTaskFactory.class, new Properties());
// Register as 3 types of service.
Properties connectSelectedNodesTaskFactoryProps = new Properties();
connectSelectedNodesTaskFactoryProps.setProperty(IN_MENU_BAR,"false");
connectSelectedNodesTaskFactoryProps.setProperty(IN_TOOL_BAR,"false");
connectSelectedNodesTaskFactoryProps.setProperty(PREFERRED_ACTION, "NEW");
connectSelectedNodesTaskFactoryProps.setProperty(PREFERRED_MENU, NODE_ADD_MENU);
connectSelectedNodesTaskFactoryProps.setProperty(MENU_GRAVITY, "0.2");
connectSelectedNodesTaskFactoryProps.setProperty(TITLE, "Edges Connecting Selected Nodes");
connectSelectedNodesTaskFactoryProps.setProperty(COMMAND, "connect selected nodes");
connectSelectedNodesTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "network");
// registerService(bc, connectSelectedNodesTaskFactory, NetworkTaskFactory.class,
// connectSelectedNodesTaskFactoryProps);
registerService(bc, connectSelectedNodesTaskFactory, NodeViewTaskFactory.class,
connectSelectedNodesTaskFactoryProps);
registerService(bc, connectSelectedNodesTaskFactory, ConnectSelectedNodesTaskFactory.class,
connectSelectedNodesTaskFactoryProps);
GroupNodesTaskFactoryImpl groupNodesTaskFactory =
new GroupNodesTaskFactoryImpl(cyApplicationManagerServiceRef, cyGroupManager,
cyGroupFactory, undoSupportServiceRef);
Properties groupNodesTaskFactoryProps = new Properties();
groupNodesTaskFactoryProps.setProperty(PREFERRED_MENU,NETWORK_GROUP_MENU);
groupNodesTaskFactoryProps.setProperty(TITLE,"Group Selected Nodes");
groupNodesTaskFactoryProps.setProperty(TOOLTIP,"Group Selected Nodes Together");
groupNodesTaskFactoryProps.setProperty(IN_TOOL_BAR,"false");
groupNodesTaskFactoryProps.setProperty(MENU_GRAVITY,"0.0");
groupNodesTaskFactoryProps.setProperty(IN_MENU_BAR,"false");
groupNodesTaskFactoryProps.setProperty(PREFERRED_ACTION, "NEW");
registerService(bc,groupNodesTaskFactory,NetworkViewTaskFactory.class, groupNodesTaskFactoryProps);
registerService(bc,groupNodesTaskFactory,GroupNodesTaskFactory.class, groupNodesTaskFactoryProps);
// For commands
groupNodesTaskFactoryProps = new Properties();
groupNodesTaskFactoryProps.setProperty(COMMAND, "create");
groupNodesTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "group");
registerService(bc,groupNodesTaskFactory,TaskFactory.class, groupNodesTaskFactoryProps);
// Add Group Selected Nodes to the nodes context also
Properties groupNodeViewTaskFactoryProps = new Properties();
groupNodeViewTaskFactoryProps.setProperty(PREFERRED_MENU,NODE_GROUP_MENU);
groupNodeViewTaskFactoryProps.setProperty(MENU_GRAVITY, "0.0");
groupNodeViewTaskFactoryProps.setProperty(TITLE,"Group Selected Nodes");
groupNodeViewTaskFactoryProps.setProperty(TOOLTIP,"Group Selected Nodes Together");
groupNodeViewTaskFactoryProps.setProperty(IN_TOOL_BAR,"false");
groupNodeViewTaskFactoryProps.setProperty(IN_MENU_BAR,"false");
groupNodeViewTaskFactoryProps.setProperty(PREFERRED_ACTION, "NEW");
registerService(bc,groupNodesTaskFactory,NodeViewTaskFactory.class, groupNodeViewTaskFactoryProps);
UnGroupNodesTaskFactoryImpl unGroupTaskFactory =
new UnGroupNodesTaskFactoryImpl(cyApplicationManagerServiceRef, cyGroupManager,
cyGroupFactory, undoSupportServiceRef);
Properties unGroupNodesTaskFactoryProps = new Properties();
unGroupNodesTaskFactoryProps.setProperty(PREFERRED_MENU,NETWORK_GROUP_MENU);
unGroupNodesTaskFactoryProps.setProperty(TITLE,"Ungroup Selected Nodes");
unGroupNodesTaskFactoryProps.setProperty(TOOLTIP,"Ungroup Selected Nodes");
unGroupNodesTaskFactoryProps.setProperty(IN_TOOL_BAR,"false");
unGroupNodesTaskFactoryProps.setProperty(IN_MENU_BAR,"false");
unGroupNodesTaskFactoryProps.setProperty(MENU_GRAVITY,"1.0");
unGroupNodesTaskFactoryProps.setProperty(PREFERRED_ACTION, "NEW");
registerService(bc,unGroupTaskFactory,NetworkViewTaskFactory.class, unGroupNodesTaskFactoryProps);
registerService(bc,unGroupTaskFactory,UnGroupTaskFactory.class, unGroupNodesTaskFactoryProps);
unGroupNodesTaskFactoryProps = new Properties();
unGroupNodesTaskFactoryProps.setProperty(COMMAND, "ungroup");
groupNodesTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "group");
registerService(bc,unGroupTaskFactory,TaskFactory.class, unGroupNodesTaskFactoryProps);
// Add Ungroup Selected Nodes to the nodes context also
Properties unGroupNodeViewTaskFactoryProps = new Properties();
unGroupNodeViewTaskFactoryProps.setProperty(PREFERRED_MENU,NODE_GROUP_MENU);
unGroupNodeViewTaskFactoryProps.setProperty(MENU_GRAVITY, "1.0");
unGroupNodeViewTaskFactoryProps.setProperty(INSERT_SEPARATOR_AFTER, "true");
unGroupNodeViewTaskFactoryProps.setProperty(TITLE,"Ungroup Selected Nodes");
unGroupNodeViewTaskFactoryProps.setProperty(TOOLTIP,"Ungroup Selected Nodes");
unGroupNodeViewTaskFactoryProps.setProperty(IN_TOOL_BAR,"false");
unGroupNodeViewTaskFactoryProps.setProperty(IN_MENU_BAR,"false");
unGroupNodeViewTaskFactoryProps.setProperty(PREFERRED_ACTION, "NEW");
registerService(bc,unGroupTaskFactory,NodeViewTaskFactory.class, unGroupNodeViewTaskFactoryProps);
registerService(bc,unGroupTaskFactory,UnGroupNodesTaskFactory.class, unGroupNodeViewTaskFactoryProps);
GroupNodeContextTaskFactoryImpl collapseGroupTaskFactory =
new GroupNodeContextTaskFactoryImpl(cyApplicationManagerServiceRef,
cyNetworkViewManagerServiceRef, cyGroupManager, true);
Properties collapseGroupTaskFactoryProps = new Properties();
collapseGroupTaskFactoryProps.setProperty(PREFERRED_MENU,NODE_GROUP_MENU);
collapseGroupTaskFactoryProps.setProperty(TITLE,"Collapse Group(s)");
collapseGroupTaskFactoryProps.setProperty(TOOLTIP,"Collapse Grouped Nodes");
collapseGroupTaskFactoryProps.setProperty(PREFERRED_ACTION, "NEW");
collapseGroupTaskFactoryProps.setProperty(MENU_GRAVITY, "2.0");
registerService(bc,collapseGroupTaskFactory,NodeViewTaskFactory.class, collapseGroupTaskFactoryProps);
registerService(bc,collapseGroupTaskFactory,CollapseGroupTaskFactory.class, collapseGroupTaskFactoryProps);
collapseGroupTaskFactoryProps = new Properties();
collapseGroupTaskFactoryProps.setProperty(COMMAND, "collapse");
collapseGroupTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "group"); // TODO right namespace?
registerService(bc,collapseGroupTaskFactory,TaskFactory.class, collapseGroupTaskFactoryProps);
GroupNodeContextTaskFactoryImpl expandGroupTaskFactory =
new GroupNodeContextTaskFactoryImpl(cyApplicationManagerServiceRef,
cyNetworkViewManagerServiceRef, cyGroupManager, false);
Properties expandGroupTaskFactoryProps = new Properties();
expandGroupTaskFactoryProps.setProperty(PREFERRED_MENU,NODE_GROUP_MENU);
expandGroupTaskFactoryProps.setProperty(TITLE,"Expand Group(s)");
expandGroupTaskFactoryProps.setProperty(TOOLTIP,"Expand Group");
expandGroupTaskFactoryProps.setProperty(PREFERRED_ACTION, "NEW");
expandGroupTaskFactoryProps.setProperty(MENU_GRAVITY, "3.0");
registerService(bc,expandGroupTaskFactory,NodeViewTaskFactory.class, expandGroupTaskFactoryProps);
registerService(bc,expandGroupTaskFactory,ExpandGroupTaskFactory.class, expandGroupTaskFactoryProps);
expandGroupTaskFactoryProps = new Properties();
expandGroupTaskFactoryProps.setProperty(COMMAND, "expand");
expandGroupTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "group"); // TODO right namespace
registerService(bc,expandGroupTaskFactory,TaskFactory.class, expandGroupTaskFactoryProps);
// TODO: add to group...
// TODO: remove from group...
MapTableToNetworkTablesTaskFactoryImpl mapNetworkToTables = new MapTableToNetworkTablesTaskFactoryImpl(cyNetworkManagerServiceRef, tunableSetterServiceRef, rootNetworkManagerServiceRef);
Properties mapNetworkToTablesProps = new Properties();
registerService(bc, mapNetworkToTables, MapTableToNetworkTablesTaskFactory.class, mapNetworkToTablesProps);
ImportDataTableTaskFactoryImpl importTableTaskFactory = new ImportDataTableTaskFactoryImpl(cyNetworkManagerServiceRef,tunableSetterServiceRef,rootNetworkManagerServiceRef);
Properties importTablesProps = new Properties();
registerService(bc, importTableTaskFactory, ImportDataTableTaskFactory.class, importTablesProps);
ExportTableTaskFactoryImpl exportTableTaskFactory = new ExportTableTaskFactoryImpl(cyTableWriterManagerRef,tunableSetterServiceRef);
Properties exportTableTaskFactoryProps = new Properties();
registerService(bc,exportTableTaskFactory,ExportTableTaskFactory.class,exportTableTaskFactoryProps);
// These are task factories that are only available to the command line
// NAMESPACE: edge
CreateNetworkAttributeTaskFactory createEdgeAttributeTaskFactory =
new CreateNetworkAttributeTaskFactory(cyApplicationManagerServiceRef,
cyTableManagerServiceRef, CyEdge.class);
Properties createEdgeAttributeTaskFactoryProps = new Properties();
createEdgeAttributeTaskFactoryProps.setProperty(COMMAND, "create attribute");
createEdgeAttributeTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "edge");
registerService(bc,createEdgeAttributeTaskFactory,TaskFactory.class,createEdgeAttributeTaskFactoryProps);
GetEdgeTaskFactory getEdgeTaskFactory = new GetEdgeTaskFactory(cyApplicationManagerServiceRef);
Properties getEdgeTaskFactoryProps = new Properties();
getEdgeTaskFactoryProps.setProperty(COMMAND, "get");
getEdgeTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "edge");
registerService(bc,getEdgeTaskFactory,TaskFactory.class,getEdgeTaskFactoryProps);
GetNetworkAttributeTaskFactory getEdgeAttributeTaskFactory =
new GetNetworkAttributeTaskFactory(cyApplicationManagerServiceRef, cyTableManagerServiceRef, CyEdge.class);
Properties getEdgeAttributeTaskFactoryProps = new Properties();
getEdgeAttributeTaskFactoryProps.setProperty(COMMAND, "get attribute");
getEdgeAttributeTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "edge");
registerService(bc,getEdgeAttributeTaskFactory,TaskFactory.class,getEdgeAttributeTaskFactoryProps);
GetPropertiesTaskFactory getEdgePropertiesTaskFactory =
new GetPropertiesTaskFactory(cyApplicationManagerServiceRef, CyEdge.class,
cyNetworkViewManagerServiceRef, renderingEngineManagerServiceRef);
Properties getEdgePropertiesTaskFactoryProps = new Properties();
getEdgePropertiesTaskFactoryProps.setProperty(COMMAND, "get properties");
getEdgePropertiesTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "edge");
registerService(bc,getEdgePropertiesTaskFactory,TaskFactory.class,getEdgePropertiesTaskFactoryProps);
ListEdgesTaskFactory listEdges = new ListEdgesTaskFactory(cyApplicationManagerServiceRef);
Properties listEdgesTaskFactoryProps = new Properties();
listEdgesTaskFactoryProps.setProperty(COMMAND, "list");
listEdgesTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "edge");
registerService(bc,listEdges,TaskFactory.class,listEdgesTaskFactoryProps);
ListNetworkAttributesTaskFactory listEdgeAttributesTaskFactory =
new ListNetworkAttributesTaskFactory(cyApplicationManagerServiceRef,
cyTableManagerServiceRef, CyEdge.class);
Properties listEdgeAttributesTaskFactoryProps = new Properties();
listEdgeAttributesTaskFactoryProps.setProperty(COMMAND, "list attributes");
listEdgeAttributesTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "edge");
registerService(bc,listEdgeAttributesTaskFactory,TaskFactory.class,listEdgeAttributesTaskFactoryProps);
ListPropertiesTaskFactory listEdgeProperties =
new ListPropertiesTaskFactory(cyApplicationManagerServiceRef,
CyEdge.class, cyNetworkViewManagerServiceRef,
renderingEngineManagerServiceRef);
Properties listEdgePropertiesTaskFactoryProps = new Properties();
listEdgePropertiesTaskFactoryProps.setProperty(COMMAND, "list properties");
listEdgePropertiesTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "edge");
registerService(bc,listEdgeProperties,TaskFactory.class,listEdgePropertiesTaskFactoryProps);
RenameEdgeTaskFactory renameEdge = new RenameEdgeTaskFactory();
Properties renameEdgeTaskFactoryProps = new Properties();
renameEdgeTaskFactoryProps.setProperty(COMMAND, "rename");
renameEdgeTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "edge");
registerService(bc,renameEdge,TaskFactory.class,renameEdgeTaskFactoryProps);
SetNetworkAttributeTaskFactory setEdgeAttributeTaskFactory =
new SetNetworkAttributeTaskFactory(cyApplicationManagerServiceRef, cyTableManagerServiceRef, CyEdge.class);
Properties setEdgeAttributeTaskFactoryProps = new Properties();
setEdgeAttributeTaskFactoryProps.setProperty(COMMAND, "set attribute");
setEdgeAttributeTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "edge");
registerService(bc,setEdgeAttributeTaskFactory,TaskFactory.class,setEdgeAttributeTaskFactoryProps);
SetPropertiesTaskFactory setEdgePropertiesTaskFactory =
new SetPropertiesTaskFactory(cyApplicationManagerServiceRef, CyEdge.class,
cyNetworkViewManagerServiceRef, renderingEngineManagerServiceRef);
Properties setEdgePropertiesTaskFactoryProps = new Properties();
setEdgePropertiesTaskFactoryProps.setProperty(COMMAND, "set properties");
setEdgePropertiesTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "edge");
registerService(bc,setEdgePropertiesTaskFactory,TaskFactory.class,setEdgePropertiesTaskFactoryProps);
// NAMESPACE: group
AddToGroupTaskFactory addToGroupTaskFactory =
new AddToGroupTaskFactory(cyApplicationManagerServiceRef, cyGroupManager);
Properties addToGroupTFProps = new Properties();
addToGroupTFProps.setProperty(COMMAND, "add");
addToGroupTFProps.setProperty(COMMAND_NAMESPACE, "group");
registerService(bc,addToGroupTaskFactory,TaskFactory.class,addToGroupTFProps);
ListGroupsTaskFactory listGroupsTaskFactory =
new ListGroupsTaskFactory(cyApplicationManagerServiceRef, cyGroupManager);
Properties listGroupsTFProps = new Properties();
listGroupsTFProps.setProperty(COMMAND, "list");
listGroupsTFProps.setProperty(COMMAND_NAMESPACE, "group");
registerService(bc,listGroupsTaskFactory,TaskFactory.class,listGroupsTFProps);
RemoveFromGroupTaskFactory removeFromGroupTaskFactory =
new RemoveFromGroupTaskFactory(cyApplicationManagerServiceRef, cyGroupManager);
Properties removeFromGroupTFProps = new Properties();
removeFromGroupTFProps.setProperty(COMMAND, "remove");
removeFromGroupTFProps.setProperty(COMMAND_NAMESPACE, "group");
registerService(bc,removeFromGroupTaskFactory,TaskFactory.class,removeFromGroupTFProps);
RenameGroupTaskFactory renameGroupTaskFactory =
new RenameGroupTaskFactory(cyApplicationManagerServiceRef, cyGroupManager);
Properties renameGroupTFProps = new Properties();
renameGroupTFProps.setProperty(COMMAND, "rename");
renameGroupTFProps.setProperty(COMMAND_NAMESPACE, "group");
registerService(bc,renameGroupTaskFactory,TaskFactory.class,renameGroupTFProps);
// NAMESPACE: layout
GetPreferredLayoutTaskFactory getPreferredLayoutTaskFactory =
new GetPreferredLayoutTaskFactory(cyLayoutsServiceRef,cyPropertyServiceRef);
Properties getPreferredTFProps = new Properties();
getPreferredTFProps.setProperty(COMMAND, "get preferred");
getPreferredTFProps.setProperty(COMMAND_NAMESPACE, "layout");
registerService(bc,getPreferredLayoutTaskFactory,TaskFactory.class,getPreferredTFProps);
SetPreferredLayoutTaskFactory setPreferredLayoutTaskFactory =
new SetPreferredLayoutTaskFactory(cyLayoutsServiceRef,cyPropertyServiceRef);
Properties setPreferredTFProps = new Properties();
setPreferredTFProps.setProperty(COMMAND, "set preferred");
setPreferredTFProps.setProperty(COMMAND_NAMESPACE, "layout");
registerService(bc,setPreferredLayoutTaskFactory,TaskFactory.class,setPreferredTFProps);
// NAMESPACE: network
AddTaskFactory addTaskFactory = new AddTaskFactory();
Properties addTaskFactoryProps = new Properties();
addTaskFactoryProps.setProperty(COMMAND, "add");
addTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "network");
registerService(bc,addTaskFactory,TaskFactory.class,addTaskFactoryProps);
AddEdgeTaskFactory addEdgeTaskFactory = new AddEdgeTaskFactory();
Properties addEdgeTaskFactoryProps = new Properties();
addEdgeTaskFactoryProps.setProperty(COMMAND, "add edge");
addEdgeTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "network");
registerService(bc,addEdgeTaskFactory,TaskFactory.class,addEdgeTaskFactoryProps);
AddNodeTaskFactory addNodeTaskFactory = new AddNodeTaskFactory();
Properties addNodeTaskFactoryProps = new Properties();
addNodeTaskFactoryProps.setProperty(COMMAND, "add node");
addNodeTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "network");
registerService(bc,addNodeTaskFactory,TaskFactory.class,addNodeTaskFactoryProps);
CreateNetworkAttributeTaskFactory createNetworkAttributeTaskFactory =
new CreateNetworkAttributeTaskFactory(cyApplicationManagerServiceRef,
cyTableManagerServiceRef, CyNetwork.class);
Properties createNetworkAttributeTaskFactoryProps = new Properties();
createNetworkAttributeTaskFactoryProps.setProperty(COMMAND, "create attribute");
createNetworkAttributeTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "network");
registerService(bc,createNetworkAttributeTaskFactory,TaskFactory.class,createNetworkAttributeTaskFactoryProps);
DeselectTaskFactory deselectTaskFactory = new DeselectTaskFactory(cyNetworkViewManagerServiceRef, cyEventHelperRef);
Properties deselectTaskFactoryProps = new Properties();
deselectTaskFactoryProps.setProperty(COMMAND, "deselect");
deselectTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "network");
registerService(bc,deselectTaskFactory,TaskFactory.class,deselectTaskFactoryProps);
GetNetworkTaskFactory getNetwork = new GetNetworkTaskFactory(cyApplicationManagerServiceRef);
Properties getNetworkTaskFactoryProps = new Properties();
getNetworkTaskFactoryProps.setProperty(COMMAND, "get");
getNetworkTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "network");
registerService(bc,getNetwork,TaskFactory.class,getNetworkTaskFactoryProps);
GetNetworkAttributeTaskFactory getNetworkAttributeTaskFactory =
new GetNetworkAttributeTaskFactory(cyApplicationManagerServiceRef, cyTableManagerServiceRef, CyNetwork.class);
Properties getNetworkAttributeTaskFactoryProps = new Properties();
getNetworkAttributeTaskFactoryProps.setProperty(COMMAND, "get attribute");
getNetworkAttributeTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "network");
registerService(bc,getNetworkAttributeTaskFactory,TaskFactory.class,getNetworkAttributeTaskFactoryProps);
GetPropertiesTaskFactory getNetworkPropertiesTaskFactory =
new GetPropertiesTaskFactory(cyApplicationManagerServiceRef, CyNetwork.class,
cyNetworkViewManagerServiceRef, renderingEngineManagerServiceRef);
Properties getNetworkPropertiesTaskFactoryProps = new Properties();
getNetworkPropertiesTaskFactoryProps.setProperty(COMMAND, "get properties");
getNetworkPropertiesTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "network");
registerService(bc,getNetworkPropertiesTaskFactory,TaskFactory.class,getNetworkPropertiesTaskFactoryProps);
HideTaskFactory hideTaskFactory = new HideTaskFactory(cyApplicationManagerServiceRef, cyNetworkViewManagerServiceRef,
visualMappingManagerServiceRef);
Properties hideTaskFactoryProps = new Properties();
hideTaskFactoryProps.setProperty(COMMAND, "hide");
hideTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "network");
registerService(bc,hideTaskFactory,TaskFactory.class,hideTaskFactoryProps);
ListNetworksTaskFactory listNetworks = new ListNetworksTaskFactory(cyNetworkManagerServiceRef);
Properties listNetworksTaskFactoryProps = new Properties();
listNetworksTaskFactoryProps.setProperty(COMMAND, "list");
listNetworksTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "network");
registerService(bc,listNetworks,TaskFactory.class,listNetworksTaskFactoryProps);
ListNetworkAttributesTaskFactory listNetworkAttributesTaskFactory =
new ListNetworkAttributesTaskFactory(cyApplicationManagerServiceRef,
cyTableManagerServiceRef, CyNetwork.class);
Properties listNetworkAttributesTaskFactoryProps = new Properties();
listNetworkAttributesTaskFactoryProps.setProperty(COMMAND, "list attributes");
listNetworkAttributesTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "network");
registerService(bc,listNetworkAttributesTaskFactory,TaskFactory.class,listNetworkAttributesTaskFactoryProps);
ListPropertiesTaskFactory listNetworkProperties =
new ListPropertiesTaskFactory(cyApplicationManagerServiceRef,
CyNetwork.class, cyNetworkViewManagerServiceRef,
renderingEngineManagerServiceRef);
Properties listNetworkPropertiesTaskFactoryProps = new Properties();
listNetworkPropertiesTaskFactoryProps.setProperty(COMMAND, "list properties");
listNetworkPropertiesTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "network");
registerService(bc,listNetworkProperties,TaskFactory.class,listNetworkPropertiesTaskFactoryProps);
SelectTaskFactory selectTaskFactory = new SelectTaskFactory(cyApplicationManagerServiceRef,
cyNetworkViewManagerServiceRef, cyEventHelperRef); Properties selectTaskFactoryProps = new Properties();
selectTaskFactoryProps.setProperty(COMMAND, "select");
selectTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "network");
registerService(bc,selectTaskFactory,TaskFactory.class,selectTaskFactoryProps);
SetNetworkAttributeTaskFactory setNetworkAttributeTaskFactory =
new SetNetworkAttributeTaskFactory(cyApplicationManagerServiceRef, cyTableManagerServiceRef, CyNetwork.class);
Properties setNetworkAttributeTaskFactoryProps = new Properties();
setNetworkAttributeTaskFactoryProps.setProperty(COMMAND, "set attribute");
setNetworkAttributeTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "network");
registerService(bc,setNetworkAttributeTaskFactory,TaskFactory.class,setNetworkAttributeTaskFactoryProps);
SetCurrentNetworkTaskFactory setCurrentNetwork = new SetCurrentNetworkTaskFactory(cyApplicationManagerServiceRef);
Properties setCurrentNetworkTaskFactoryProps = new Properties();
setCurrentNetworkTaskFactoryProps.setProperty(COMMAND, "set current");
setCurrentNetworkTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "network");
registerService(bc,setCurrentNetwork,TaskFactory.class,setCurrentNetworkTaskFactoryProps);
SetPropertiesTaskFactory setNetworkPropertiesTaskFactory =
new SetPropertiesTaskFactory(cyApplicationManagerServiceRef, CyNetwork.class,
cyNetworkViewManagerServiceRef, renderingEngineManagerServiceRef);
Properties setNetworkPropertiesTaskFactoryProps = new Properties();
setNetworkPropertiesTaskFactoryProps.setProperty(COMMAND, "set properties");
setNetworkPropertiesTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "network");
registerService(bc,setNetworkPropertiesTaskFactory,TaskFactory.class,setNetworkPropertiesTaskFactoryProps);
UnHideTaskFactory unHideTaskFactory = new UnHideTaskFactory(cyApplicationManagerServiceRef, cyNetworkViewManagerServiceRef,
visualMappingManagerServiceRef);
Properties unHideTaskFactoryProps = new Properties();
unHideTaskFactoryProps.setProperty(COMMAND, "show");
unHideTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "network");
registerService(bc,unHideTaskFactory,TaskFactory.class,unHideTaskFactoryProps);
// NAMESPACE: node
CreateNetworkAttributeTaskFactory createNodeAttributeTaskFactory =
new CreateNetworkAttributeTaskFactory(cyApplicationManagerServiceRef,
cyTableManagerServiceRef, CyNode.class);
Properties createNodeAttributeTaskFactoryProps = new Properties();
createNodeAttributeTaskFactoryProps.setProperty(COMMAND, "create attribute");
createNodeAttributeTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "node");
registerService(bc,createNodeAttributeTaskFactory,TaskFactory.class,createNodeAttributeTaskFactoryProps);
GetNodeTaskFactory getNodeTaskFactory = new GetNodeTaskFactory(cyApplicationManagerServiceRef);
Properties getNodeTaskFactoryProps = new Properties();
getNodeTaskFactoryProps.setProperty(COMMAND, "get");
getNodeTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "node");
registerService(bc,getNodeTaskFactory,TaskFactory.class,getNodeTaskFactoryProps);
GetNetworkAttributeTaskFactory getNodeAttributeTaskFactory =
new GetNetworkAttributeTaskFactory(cyApplicationManagerServiceRef, cyTableManagerServiceRef, CyNode.class);
Properties getNodeAttributeTaskFactoryProps = new Properties();
getNodeAttributeTaskFactoryProps.setProperty(COMMAND, "get attribute");
getNodeAttributeTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "node");
registerService(bc,getNodeAttributeTaskFactory,TaskFactory.class,getNodeAttributeTaskFactoryProps);
GetPropertiesTaskFactory getNodePropertiesTaskFactory =
new GetPropertiesTaskFactory(cyApplicationManagerServiceRef, CyNode.class,
cyNetworkViewManagerServiceRef, renderingEngineManagerServiceRef);
Properties getNodePropertiesTaskFactoryProps = new Properties();
getNodePropertiesTaskFactoryProps.setProperty(COMMAND, "get properties");
getNodePropertiesTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "node");
registerService(bc,getNodePropertiesTaskFactory,TaskFactory.class,getNodePropertiesTaskFactoryProps);
ListNodesTaskFactory listNodes = new ListNodesTaskFactory(cyApplicationManagerServiceRef);
Properties listNodesTaskFactoryProps = new Properties();
listNodesTaskFactoryProps.setProperty(COMMAND, "list");
listNodesTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "node");
registerService(bc,listNodes,TaskFactory.class,listNodesTaskFactoryProps);
ListNetworkAttributesTaskFactory listNodeAttributesTaskFactory =
new ListNetworkAttributesTaskFactory(cyApplicationManagerServiceRef,
cyTableManagerServiceRef, CyNode.class);
Properties listNodeAttributesTaskFactoryProps = new Properties();
listNodeAttributesTaskFactoryProps.setProperty(COMMAND, "list attributes");
listNodeAttributesTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "node");
registerService(bc,listNodeAttributesTaskFactory,TaskFactory.class,listNodeAttributesTaskFactoryProps);
ListPropertiesTaskFactory listNodeProperties =
new ListPropertiesTaskFactory(cyApplicationManagerServiceRef,
CyNode.class, cyNetworkViewManagerServiceRef,
renderingEngineManagerServiceRef);
Properties listNodePropertiesTaskFactoryProps = new Properties();
listNodePropertiesTaskFactoryProps.setProperty(COMMAND, "list properties");
listNodePropertiesTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "node");
registerService(bc,listNodeProperties,TaskFactory.class,listNodePropertiesTaskFactoryProps);
RenameNodeTaskFactory renameNode = new RenameNodeTaskFactory();
Properties renameNodeTaskFactoryProps = new Properties();
renameNodeTaskFactoryProps.setProperty(COMMAND, "rename");
renameNodeTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "node");
registerService(bc,renameNode,TaskFactory.class,renameNodeTaskFactoryProps);
SetNetworkAttributeTaskFactory setNodeAttributeTaskFactory =
new SetNetworkAttributeTaskFactory(cyApplicationManagerServiceRef, cyTableManagerServiceRef, CyNode.class);
Properties setNodeAttributeTaskFactoryProps = new Properties();
setNodeAttributeTaskFactoryProps.setProperty(COMMAND, "set attribute");
setNodeAttributeTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "node");
registerService(bc,setNodeAttributeTaskFactory,TaskFactory.class,setNodeAttributeTaskFactoryProps);
SetPropertiesTaskFactory setNodePropertiesTaskFactory =
new SetPropertiesTaskFactory(cyApplicationManagerServiceRef, CyNode.class,
cyNetworkViewManagerServiceRef, renderingEngineManagerServiceRef);
Properties setNodePropertiesTaskFactoryProps = new Properties();
setNodePropertiesTaskFactoryProps.setProperty(COMMAND, "set properties");
setNodePropertiesTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "node");
registerService(bc,setNodePropertiesTaskFactory,TaskFactory.class,setNodePropertiesTaskFactoryProps);
// NAMESPACE: table
AddRowTaskFactory addRowTaskFactory =
new AddRowTaskFactory(cyApplicationManagerServiceRef, cyTableManagerServiceRef);
Properties addRowTaskFactoryProps = new Properties();
addRowTaskFactoryProps.setProperty(COMMAND, "add row");
addRowTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "table");
registerService(bc,addRowTaskFactory,TaskFactory.class,addRowTaskFactoryProps);
CreateColumnTaskFactory createColumnTaskFactory =
new CreateColumnTaskFactory(cyApplicationManagerServiceRef, cyTableManagerServiceRef);
Properties createColumnTaskFactoryProps = new Properties();
createColumnTaskFactoryProps.setProperty(COMMAND, "create column");
createColumnTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "table");
registerService(bc,createColumnTaskFactory,TaskFactory.class,createColumnTaskFactoryProps);
CreateTableTaskFactory createTableTaskFactory =
new CreateTableTaskFactory(cyApplicationManagerServiceRef,
cyTableFactoryServiceRef, cyTableManagerServiceRef);
Properties createTableTaskFactoryProps = new Properties();
createTableTaskFactoryProps.setProperty(COMMAND, "create table");
createTableTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "table");
registerService(bc,createTableTaskFactory,TaskFactory.class,createTableTaskFactoryProps);
DeleteColumnCommandTaskFactory deleteColumnCommandTaskFactory =
new DeleteColumnCommandTaskFactory(cyApplicationManagerServiceRef, cyTableManagerServiceRef);
Properties deleteColumnCommandTaskFactoryProps = new Properties();
deleteColumnCommandTaskFactoryProps.setProperty(COMMAND, "delete column");
deleteColumnCommandTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "table");
registerService(bc,deleteColumnCommandTaskFactory,TaskFactory.class,deleteColumnCommandTaskFactoryProps);
DeleteRowTaskFactory deleteRowTaskFactory =
new DeleteRowTaskFactory(cyApplicationManagerServiceRef, cyTableManagerServiceRef);
Properties deleteRowTaskFactoryProps = new Properties();
deleteRowTaskFactoryProps.setProperty(COMMAND, "delete row");
deleteRowTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "table");
registerService(bc,deleteRowTaskFactory,TaskFactory.class,deleteRowTaskFactoryProps);
DestroyTableTaskFactory destroyTableTaskFactory =
new DestroyTableTaskFactory(cyApplicationManagerServiceRef, cyTableManagerServiceRef);
Properties destroyTableTaskFactoryProps = new Properties();
destroyTableTaskFactoryProps.setProperty(COMMAND, "destroy");
destroyTableTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "table");
registerService(bc,destroyTableTaskFactory,TaskFactory.class,destroyTableTaskFactoryProps);
GetColumnTaskFactory getColumnTaskFactory =
new GetColumnTaskFactory(cyApplicationManagerServiceRef, cyTableManagerServiceRef);
Properties getColumnTaskFactoryProps = new Properties();
getColumnTaskFactoryProps.setProperty(COMMAND, "get column");
getColumnTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "table");
registerService(bc,getColumnTaskFactory,TaskFactory.class,getColumnTaskFactoryProps);
GetRowTaskFactory getRowTaskFactory =
new GetRowTaskFactory(cyApplicationManagerServiceRef, cyTableManagerServiceRef);
Properties getRowTaskFactoryProps = new Properties();
getRowTaskFactoryProps.setProperty(COMMAND, "get row");
getRowTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "table");
registerService(bc,getRowTaskFactory,TaskFactory.class,getRowTaskFactoryProps);
GetValueTaskFactory getValueTaskFactory =
new GetValueTaskFactory(cyApplicationManagerServiceRef, cyTableManagerServiceRef);
Properties getValueTaskFactoryProps = new Properties();
getValueTaskFactoryProps.setProperty(COMMAND, "get value");
getValueTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "table");
registerService(bc,getValueTaskFactory,TaskFactory.class,getValueTaskFactoryProps);
ListColumnsTaskFactory listColumnsTaskFactory =
new ListColumnsTaskFactory(cyApplicationManagerServiceRef, cyTableManagerServiceRef,
cyNetworkTableManagerServiceRef);
Properties listColumnsTaskFactoryProps = new Properties();
listColumnsTaskFactoryProps.setProperty(COMMAND, "list columns");
listColumnsTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "table");
registerService(bc,listColumnsTaskFactory,TaskFactory.class,listColumnsTaskFactoryProps);
ListRowsTaskFactory listRowsTaskFactory =
new ListRowsTaskFactory(cyApplicationManagerServiceRef, cyTableManagerServiceRef);
Properties listRowsTaskFactoryProps = new Properties();
listRowsTaskFactoryProps.setProperty(COMMAND, "list rows");
listRowsTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "table");
registerService(bc,listRowsTaskFactory,TaskFactory.class,listRowsTaskFactoryProps);
ListTablesTaskFactory listTablesTaskFactory =
new ListTablesTaskFactory(cyApplicationManagerServiceRef, cyTableManagerServiceRef,
cyNetworkTableManagerServiceRef);
Properties listTablesTaskFactoryProps = new Properties();
listTablesTaskFactoryProps.setProperty(COMMAND, "list");
listTablesTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "table");
registerService(bc,listTablesTaskFactory,TaskFactory.class,listTablesTaskFactoryProps);
SetTableTitleTaskFactory setTableTitleTaskFactory =
new SetTableTitleTaskFactory(cyApplicationManagerServiceRef, cyTableManagerServiceRef);
Properties setTableTitleTaskFactoryProps = new Properties();
setTableTitleTaskFactoryProps.setProperty(COMMAND, "set title");
setTableTitleTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "table");
registerService(bc,setTableTitleTaskFactory,TaskFactory.class,setTableTitleTaskFactoryProps);
SetValuesTaskFactory setValuesTaskFactory =
new SetValuesTaskFactory(cyApplicationManagerServiceRef, cyTableManagerServiceRef);
Properties setValuesTaskFactoryProps = new Properties();
setValuesTaskFactoryProps.setProperty(COMMAND, "set values");
setValuesTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "table");
registerService(bc,setValuesTaskFactory,TaskFactory.class,setValuesTaskFactoryProps);
// NAMESPACE: view
GetCurrentNetworkViewTaskFactory getCurrentView =
new GetCurrentNetworkViewTaskFactory(cyApplicationManagerServiceRef);
Properties getCurrentViewTaskFactoryProps = new Properties();
getCurrentViewTaskFactoryProps.setProperty(COMMAND, "get current");
getCurrentViewTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "view");
registerService(bc,getCurrentView,TaskFactory.class,getCurrentViewTaskFactoryProps);
ListNetworkViewsTaskFactory listNetworkViews =
new ListNetworkViewsTaskFactory(cyApplicationManagerServiceRef, cyNetworkViewManagerServiceRef);
Properties listNetworkViewsTaskFactoryProps = new Properties();
listNetworkViewsTaskFactoryProps.setProperty(COMMAND, "list");
listNetworkViewsTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "view");
registerService(bc,listNetworkViews,TaskFactory.class,listNetworkViewsTaskFactoryProps);
SetCurrentNetworkViewTaskFactory setCurrentView =
new SetCurrentNetworkViewTaskFactory(cyApplicationManagerServiceRef,
cyNetworkViewManagerServiceRef);
Properties setCurrentViewTaskFactoryProps = new Properties();
setCurrentViewTaskFactoryProps.setProperty(COMMAND, "set current");
setCurrentViewTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "view");
registerService(bc,setCurrentView,TaskFactory.class,setCurrentViewTaskFactoryProps);
UpdateNetworkViewTaskFactory updateView =
new UpdateNetworkViewTaskFactory(cyApplicationManagerServiceRef, cyNetworkViewManagerServiceRef);
Properties updateViewTaskFactoryProps = new Properties();
updateViewTaskFactoryProps.setProperty(COMMAND, "update");
updateViewTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "view");
registerService(bc,updateView,TaskFactory.class,updateViewTaskFactoryProps);
}
| public void start(BundleContext bc) {
CyEventHelper cyEventHelperRef = getService(bc,CyEventHelper.class);
RecentlyOpenedTracker recentlyOpenedTrackerServiceRef = getService(bc,RecentlyOpenedTracker.class);
CyNetworkNaming cyNetworkNamingServiceRef = getService(bc,CyNetworkNaming.class);
UndoSupport undoSupportServiceRef = getService(bc,UndoSupport.class);
CyNetworkViewFactory cyNetworkViewFactoryServiceRef = getService(bc,CyNetworkViewFactory.class);
CyNetworkFactory cyNetworkFactoryServiceRef = getService(bc,CyNetworkFactory.class);
CyRootNetworkManager cyRootNetworkFactoryServiceRef = getService(bc,CyRootNetworkManager.class);
CyNetworkReaderManager cyNetworkReaderManagerServiceRef = getService(bc,CyNetworkReaderManager.class);
CyTableReaderManager cyDataTableReaderManagerServiceRef = getService(bc,CyTableReaderManager.class);
VizmapReaderManager vizmapReaderManagerServiceRef = getService(bc,VizmapReaderManager.class);
VisualMappingManager visualMappingManagerServiceRef = getService(bc,VisualMappingManager.class);
StreamUtil streamUtilRef = getService(bc,StreamUtil.class);
PresentationWriterManager viewWriterManagerServiceRef = getService(bc,PresentationWriterManager.class);
CyNetworkViewWriterManager networkViewWriterManagerServiceRef = getService(bc,CyNetworkViewWriterManager.class);
VizmapWriterManager vizmapWriterManagerServiceRef = getService(bc,VizmapWriterManager.class);
CySessionWriterManager sessionWriterManagerServiceRef = getService(bc,CySessionWriterManager.class);
CySessionReaderManager sessionReaderManagerServiceRef = getService(bc,CySessionReaderManager.class);
CyNetworkManager cyNetworkManagerServiceRef = getService(bc,CyNetworkManager.class);
CyNetworkViewManager cyNetworkViewManagerServiceRef = getService(bc,CyNetworkViewManager.class);
CyApplicationManager cyApplicationManagerServiceRef = getService(bc,CyApplicationManager.class);
CySessionManager cySessionManagerServiceRef = getService(bc,CySessionManager.class);
CyProperty cyPropertyServiceRef = getService(bc,CyProperty.class,"(cyPropertyName=cytoscape3.props)");
CyTableFactory cyTableFactoryServiceRef = getService(bc,CyTableFactory.class);
CyTableManager cyTableManagerServiceRef = getService(bc,CyTableManager.class);
CyLayoutAlgorithmManager cyLayoutsServiceRef = getService(bc,CyLayoutAlgorithmManager.class);
CyTableWriterManager cyTableWriterManagerRef = getService(bc,CyTableWriterManager.class);
SynchronousTaskManager<?> synchronousTaskManagerServiceRef = getService(bc,SynchronousTaskManager.class);
TunableSetter tunableSetterServiceRef = getService(bc,TunableSetter.class);
CyRootNetworkManager rootNetworkManagerServiceRef = getService(bc, CyRootNetworkManager.class);
CyNetworkTableManager cyNetworkTableManagerServiceRef = getService(bc, CyNetworkTableManager.class);
RenderingEngineManager renderingEngineManagerServiceRef = getService(bc, RenderingEngineManager.class);
CyNetworkViewFactory nullNetworkViewFactory = getService(bc, CyNetworkViewFactory.class, "(id=NullCyNetworkViewFactory)");
CyGroupManager cyGroupManager = getService(bc, CyGroupManager.class);
CyGroupFactory cyGroupFactory = getService(bc, CyGroupFactory.class);
LoadVizmapFileTaskFactoryImpl loadVizmapFileTaskFactory = new LoadVizmapFileTaskFactoryImpl(vizmapReaderManagerServiceRef,visualMappingManagerServiceRef,synchronousTaskManagerServiceRef, tunableSetterServiceRef);
LoadNetworkFileTaskFactoryImpl loadNetworkFileTaskFactory = new LoadNetworkFileTaskFactoryImpl(cyNetworkReaderManagerServiceRef,cyNetworkManagerServiceRef,cyNetworkViewManagerServiceRef,cyPropertyServiceRef,cyNetworkNamingServiceRef, tunableSetterServiceRef, visualMappingManagerServiceRef, nullNetworkViewFactory);
LoadNetworkURLTaskFactoryImpl loadNetworkURLTaskFactory = new LoadNetworkURLTaskFactoryImpl(cyNetworkReaderManagerServiceRef,cyNetworkManagerServiceRef,cyNetworkViewManagerServiceRef,cyPropertyServiceRef,cyNetworkNamingServiceRef,streamUtilRef, synchronousTaskManagerServiceRef, tunableSetterServiceRef, visualMappingManagerServiceRef, nullNetworkViewFactory);
DeleteSelectedNodesAndEdgesTaskFactoryImpl deleteSelectedNodesAndEdgesTaskFactory = new DeleteSelectedNodesAndEdgesTaskFactoryImpl(cyApplicationManagerServiceRef, undoSupportServiceRef,cyNetworkViewManagerServiceRef,visualMappingManagerServiceRef,cyEventHelperRef);
SelectAllTaskFactoryImpl selectAllTaskFactory = new SelectAllTaskFactoryImpl(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef);
SelectAllEdgesTaskFactoryImpl selectAllEdgesTaskFactory = new SelectAllEdgesTaskFactoryImpl(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef);
SelectAllNodesTaskFactoryImpl selectAllNodesTaskFactory = new SelectAllNodesTaskFactoryImpl(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef);
SelectAdjacentEdgesTaskFactoryImpl selectAdjacentEdgesTaskFactory = new SelectAdjacentEdgesTaskFactoryImpl(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef);
SelectConnectedNodesTaskFactoryImpl selectConnectedNodesTaskFactory = new SelectConnectedNodesTaskFactoryImpl(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef);
SelectFirstNeighborsTaskFactoryImpl selectFirstNeighborsTaskFactory = new SelectFirstNeighborsTaskFactoryImpl(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef, CyEdge.Type.ANY);
SelectFirstNeighborsTaskFactoryImpl selectFirstNeighborsTaskFactoryInEdge = new SelectFirstNeighborsTaskFactoryImpl(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef, CyEdge.Type.INCOMING);
SelectFirstNeighborsTaskFactoryImpl selectFirstNeighborsTaskFactoryOutEdge = new SelectFirstNeighborsTaskFactoryImpl(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef, CyEdge.Type.OUTGOING);
DeselectAllTaskFactoryImpl deselectAllTaskFactory = new DeselectAllTaskFactoryImpl(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef);
DeselectAllEdgesTaskFactoryImpl deselectAllEdgesTaskFactory = new DeselectAllEdgesTaskFactoryImpl(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef);
DeselectAllNodesTaskFactoryImpl deselectAllNodesTaskFactory = new DeselectAllNodesTaskFactoryImpl(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef);
InvertSelectedEdgesTaskFactoryImpl invertSelectedEdgesTaskFactory = new InvertSelectedEdgesTaskFactoryImpl(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef);
InvertSelectedNodesTaskFactoryImpl invertSelectedNodesTaskFactory = new InvertSelectedNodesTaskFactoryImpl(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef);
SelectFromFileListTaskFactoryImpl selectFromFileListTaskFactory = new SelectFromFileListTaskFactoryImpl(undoSupportServiceRef,cyNetworkViewManagerServiceRef,cyEventHelperRef, tunableSetterServiceRef);
SelectFirstNeighborsNodeViewTaskFactoryImpl selectFirstNeighborsNodeViewTaskFactory = new SelectFirstNeighborsNodeViewTaskFactoryImpl(CyEdge.Type.ANY);
HideSelectedTaskFactoryImpl hideSelectedTaskFactory = new HideSelectedTaskFactoryImpl(undoSupportServiceRef,cyEventHelperRef,visualMappingManagerServiceRef);
HideSelectedNodesTaskFactoryImpl hideSelectedNodesTaskFactory = new HideSelectedNodesTaskFactoryImpl(undoSupportServiceRef,cyEventHelperRef,visualMappingManagerServiceRef);
HideSelectedEdgesTaskFactoryImpl hideSelectedEdgesTaskFactory = new HideSelectedEdgesTaskFactoryImpl(undoSupportServiceRef,cyEventHelperRef,visualMappingManagerServiceRef);
UnHideAllTaskFactoryImpl unHideAllTaskFactory = new UnHideAllTaskFactoryImpl(undoSupportServiceRef,cyEventHelperRef,visualMappingManagerServiceRef);
UnHideAllNodesTaskFactoryImpl unHideAllNodesTaskFactory = new UnHideAllNodesTaskFactoryImpl(undoSupportServiceRef,cyEventHelperRef,visualMappingManagerServiceRef);
UnHideAllEdgesTaskFactoryImpl unHideAllEdgesTaskFactory = new UnHideAllEdgesTaskFactoryImpl(undoSupportServiceRef,cyEventHelperRef,visualMappingManagerServiceRef);
NewEmptyNetworkTaskFactoryImpl newEmptyNetworkTaskFactory = new NewEmptyNetworkTaskFactoryImpl(cyNetworkFactoryServiceRef,cyNetworkViewFactoryServiceRef,cyNetworkManagerServiceRef,cyNetworkViewManagerServiceRef,cyNetworkNamingServiceRef,synchronousTaskManagerServiceRef,visualMappingManagerServiceRef, cyRootNetworkFactoryServiceRef, cyApplicationManagerServiceRef);
CloneNetworkTaskFactoryImpl cloneNetworkTaskFactory = new CloneNetworkTaskFactoryImpl(cyNetworkManagerServiceRef,cyNetworkViewManagerServiceRef,visualMappingManagerServiceRef,cyNetworkFactoryServiceRef,cyNetworkViewFactoryServiceRef,cyNetworkNamingServiceRef,cyApplicationManagerServiceRef,cyNetworkTableManagerServiceRef,rootNetworkManagerServiceRef,cyGroupManager,cyGroupFactory,renderingEngineManagerServiceRef, nullNetworkViewFactory );
NewNetworkSelectedNodesEdgesTaskFactoryImpl newNetworkSelectedNodesEdgesTaskFactory = new NewNetworkSelectedNodesEdgesTaskFactoryImpl(undoSupportServiceRef,cyRootNetworkFactoryServiceRef,cyNetworkViewFactoryServiceRef,cyNetworkManagerServiceRef,cyNetworkViewManagerServiceRef,cyNetworkNamingServiceRef,visualMappingManagerServiceRef,cyApplicationManagerServiceRef,cyEventHelperRef,cyGroupManager,renderingEngineManagerServiceRef);
NewNetworkCommandTaskFactory newNetworkCommandTaskFactory = new NewNetworkCommandTaskFactory(undoSupportServiceRef,cyRootNetworkFactoryServiceRef,cyNetworkViewFactoryServiceRef,cyNetworkManagerServiceRef,cyNetworkViewManagerServiceRef,cyNetworkNamingServiceRef,visualMappingManagerServiceRef,cyApplicationManagerServiceRef,cyEventHelperRef,cyGroupManager,renderingEngineManagerServiceRef);
NewNetworkSelectedNodesOnlyTaskFactoryImpl newNetworkSelectedNodesOnlyTaskFactory = new NewNetworkSelectedNodesOnlyTaskFactoryImpl(undoSupportServiceRef,cyRootNetworkFactoryServiceRef,cyNetworkViewFactoryServiceRef,cyNetworkManagerServiceRef,cyNetworkViewManagerServiceRef,cyNetworkNamingServiceRef,visualMappingManagerServiceRef,cyApplicationManagerServiceRef,cyEventHelperRef,cyGroupManager,renderingEngineManagerServiceRef);
DestroyNetworkTaskFactoryImpl destroyNetworkTaskFactory = new DestroyNetworkTaskFactoryImpl(cyNetworkManagerServiceRef);
DestroyNetworkViewTaskFactoryImpl destroyNetworkViewTaskFactory = new DestroyNetworkViewTaskFactoryImpl(cyNetworkViewManagerServiceRef);
ZoomInTaskFactory zoomInTaskFactory = new ZoomInTaskFactory(undoSupportServiceRef, cyApplicationManagerServiceRef);
ZoomOutTaskFactory zoomOutTaskFactory = new ZoomOutTaskFactory(undoSupportServiceRef, cyApplicationManagerServiceRef);
FitSelectedTaskFactory fitSelectedTaskFactory = new FitSelectedTaskFactory(undoSupportServiceRef, cyApplicationManagerServiceRef);
FitContentTaskFactory fitContentTaskFactory = new FitContentTaskFactory(undoSupportServiceRef, cyApplicationManagerServiceRef);
NewSessionTaskFactoryImpl newSessionTaskFactory = new NewSessionTaskFactoryImpl(cySessionManagerServiceRef, tunableSetterServiceRef);
OpenSessionCommandTaskFactory openSessionCommandTaskFactory = new OpenSessionCommandTaskFactory(cySessionManagerServiceRef,sessionReaderManagerServiceRef,cyApplicationManagerServiceRef,cyNetworkManagerServiceRef,cyTableManagerServiceRef,cyNetworkTableManagerServiceRef,cyGroupManager,recentlyOpenedTrackerServiceRef);
OpenSessionTaskFactoryImpl openSessionTaskFactory = new OpenSessionTaskFactoryImpl(cySessionManagerServiceRef,sessionReaderManagerServiceRef,cyApplicationManagerServiceRef,cyNetworkManagerServiceRef,cyTableManagerServiceRef,cyNetworkTableManagerServiceRef,cyGroupManager,recentlyOpenedTrackerServiceRef,tunableSetterServiceRef);
SaveSessionTaskFactoryImpl saveSessionTaskFactory = new SaveSessionTaskFactoryImpl( sessionWriterManagerServiceRef, cySessionManagerServiceRef, recentlyOpenedTrackerServiceRef, cyEventHelperRef);
SaveSessionAsTaskFactoryImpl saveSessionAsTaskFactory = new SaveSessionAsTaskFactoryImpl( sessionWriterManagerServiceRef, cySessionManagerServiceRef, recentlyOpenedTrackerServiceRef, cyEventHelperRef, tunableSetterServiceRef);
ProxySettingsTaskFactoryImpl proxySettingsTaskFactory = new ProxySettingsTaskFactoryImpl(cyPropertyServiceRef, streamUtilRef);
EditNetworkTitleTaskFactoryImpl editNetworkTitleTaskFactory = new EditNetworkTitleTaskFactoryImpl(undoSupportServiceRef, cyNetworkManagerServiceRef, cyNetworkNamingServiceRef, tunableSetterServiceRef);
CreateNetworkViewTaskFactoryImpl createNetworkViewTaskFactory = new CreateNetworkViewTaskFactoryImpl(undoSupportServiceRef,cyNetworkViewFactoryServiceRef,cyNetworkViewManagerServiceRef,cyLayoutsServiceRef,cyEventHelperRef,visualMappingManagerServiceRef,renderingEngineManagerServiceRef,cyApplicationManagerServiceRef);
ExportNetworkImageTaskFactoryImpl exportNetworkImageTaskFactory = new ExportNetworkImageTaskFactoryImpl(viewWriterManagerServiceRef,cyApplicationManagerServiceRef);
ExportNetworkViewTaskFactoryImpl exportNetworkViewTaskFactory = new ExportNetworkViewTaskFactoryImpl(networkViewWriterManagerServiceRef, tunableSetterServiceRef);
ExportSelectedTableTaskFactoryImpl exportCurrentTableTaskFactory = new ExportSelectedTableTaskFactoryImpl(cyTableWriterManagerRef, cyTableManagerServiceRef, cyNetworkManagerServiceRef);
ApplyPreferredLayoutTaskFactoryImpl applyPreferredLayoutTaskFactory = new ApplyPreferredLayoutTaskFactoryImpl(cyApplicationManagerServiceRef, cyNetworkViewManagerServiceRef, cyLayoutsServiceRef,cyPropertyServiceRef);
DeleteColumnTaskFactoryImpl deleteColumnTaskFactory = new DeleteColumnTaskFactoryImpl(undoSupportServiceRef);
RenameColumnTaskFactoryImpl renameColumnTaskFactory = new RenameColumnTaskFactoryImpl(undoSupportServiceRef, tunableSetterServiceRef);
CopyValueToColumnTaskFactoryImpl copyValueToEntireColumnTaskFactory = new CopyValueToColumnTaskFactoryImpl(undoSupportServiceRef, false, "Apply to entire column");
CopyValueToColumnTaskFactoryImpl copyValueToSelectedNodesTaskFactory = new CopyValueToColumnTaskFactoryImpl(undoSupportServiceRef, true, "Apply to selected nodes");
CopyValueToColumnTaskFactoryImpl copyValueToSelectedEdgesTaskFactory = new CopyValueToColumnTaskFactoryImpl(undoSupportServiceRef, true, "Apply to selected edges");
DeleteTableTaskFactoryImpl deleteTableTaskFactory = new DeleteTableTaskFactoryImpl(cyTableManagerServiceRef);
ExportVizmapTaskFactoryImpl exportVizmapTaskFactory = new ExportVizmapTaskFactoryImpl(vizmapWriterManagerServiceRef,visualMappingManagerServiceRef, tunableSetterServiceRef);
ConnectSelectedNodesTaskFactoryImpl connectSelectedNodesTaskFactory = new ConnectSelectedNodesTaskFactoryImpl(undoSupportServiceRef, cyEventHelperRef, visualMappingManagerServiceRef, cyNetworkViewManagerServiceRef);
MapGlobalToLocalTableTaskFactoryImpl mapGlobal = new MapGlobalToLocalTableTaskFactoryImpl(cyTableManagerServiceRef, cyNetworkManagerServiceRef, tunableSetterServiceRef);
DynamicTaskFactoryProvisionerImpl dynamicTaskFactoryProvisionerImpl = new DynamicTaskFactoryProvisionerImpl(cyApplicationManagerServiceRef);
registerAllServices(bc, dynamicTaskFactoryProvisionerImpl, new Properties());
LoadAttributesFileTaskFactoryImpl loadAttrsFileTaskFactory = new LoadAttributesFileTaskFactoryImpl(cyDataTableReaderManagerServiceRef, tunableSetterServiceRef,cyNetworkManagerServiceRef, cyTableManagerServiceRef, rootNetworkManagerServiceRef );
LoadAttributesURLTaskFactoryImpl loadAttrsURLTaskFactory = new LoadAttributesURLTaskFactoryImpl(cyDataTableReaderManagerServiceRef, tunableSetterServiceRef, cyNetworkManagerServiceRef, cyTableManagerServiceRef, rootNetworkManagerServiceRef);
ImportAttributesFileTaskFactoryImpl importAttrsFileTaskFactory = new ImportAttributesFileTaskFactoryImpl(cyDataTableReaderManagerServiceRef, tunableSetterServiceRef,cyNetworkManagerServiceRef, cyTableManagerServiceRef, rootNetworkManagerServiceRef );
ImportAttributesURLTaskFactoryImpl importAttrsURLTaskFactory = new ImportAttributesURLTaskFactoryImpl(cyDataTableReaderManagerServiceRef, tunableSetterServiceRef, cyNetworkManagerServiceRef, cyTableManagerServiceRef, rootNetworkManagerServiceRef);
MergeDataTableTaskFactoryImpl mergeTableTaskFactory = new MergeDataTableTaskFactoryImpl( cyTableManagerServiceRef,cyNetworkManagerServiceRef,tunableSetterServiceRef, rootNetworkManagerServiceRef );
// Apply Visual Style Task
ApplyVisualStyleTaskFactoryimpl applyVisualStyleTaskFactory = new ApplyVisualStyleTaskFactoryimpl(visualMappingManagerServiceRef);
Properties applyVisualStyleProps = new Properties();
applyVisualStyleProps.setProperty(ID,"applyVisualStyleTaskFactory");
applyVisualStyleProps.setProperty(TITLE, "Apply Visual Style");
applyVisualStyleProps.setProperty(COMMAND,"apply");
applyVisualStyleProps.setProperty(COMMAND_NAMESPACE,"vizmap");
applyVisualStyleProps.setProperty(IN_NETWORK_PANEL_CONTEXT_MENU,"true");
applyVisualStyleProps.setProperty(ENABLE_FOR,"networkAndView");
registerService(bc, applyVisualStyleTaskFactory, NetworkViewCollectionTaskFactory.class, applyVisualStyleProps);
registerService(bc, applyVisualStyleTaskFactory, ApplyVisualStyleTaskFactory.class, applyVisualStyleProps);
// Clear edge bends
ClearEdgeBendTaskFactory clearEdgeBendTaskFactory = new ClearEdgeBendTaskFactory();
Properties clearEdgeBendProps = new Properties();
clearEdgeBendProps.setProperty(ID, "clearEdgeBendTaskFactory");
clearEdgeBendProps.setProperty(TITLE, "Clear Edge Bends");
clearEdgeBendProps.setProperty(IN_NETWORK_PANEL_CONTEXT_MENU, "true");
clearEdgeBendProps.setProperty(ENABLE_FOR, "networkAndView");
clearEdgeBendProps.setProperty(PREFERRED_MENU,"Layout");
clearEdgeBendProps.setProperty(MENU_GRAVITY,"0.1");
registerService(bc, clearEdgeBendTaskFactory, NetworkViewCollectionTaskFactory.class, clearEdgeBendProps);
Properties mapGlobalProps = new Properties();
/* mapGlobalProps.setProperty(ID,"mapGlobalToLocalTableTaskFactory");
mapGlobalProps.setProperty(PREFERRED_MENU,"Tools");
mapGlobalProps.setProperty(ACCELERATOR,"cmd m");
mapGlobalProps.setProperty(TITLE, "Map Table to Attributes");
mapGlobalProps.setProperty(MENU_GRAVITY,"1.0");
mapGlobalProps.setProperty(TOOL_BAR_GRAVITY,"3.0");
mapGlobalProps.setProperty(IN_TOOL_BAR,"false");
mapGlobalProps.setProperty(COMMAND,"map-global-to-local");
mapGlobalProps.setProperty(COMMAND_NAMESPACE,"table");
*/ registerService(bc, mapGlobal, TableTaskFactory.class, mapGlobalProps);
registerService(bc, mapGlobal, MapGlobalToLocalTableTaskFactory.class, mapGlobalProps);
Properties loadNetworkFileTaskFactoryProps = new Properties();
loadNetworkFileTaskFactoryProps.setProperty(ID,"loadNetworkFileTaskFactory");
loadNetworkFileTaskFactoryProps.setProperty(PREFERRED_MENU,"File.Import.Network");
loadNetworkFileTaskFactoryProps.setProperty(ACCELERATOR,"cmd l");
loadNetworkFileTaskFactoryProps.setProperty(TITLE,"File...");
loadNetworkFileTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"network");
loadNetworkFileTaskFactoryProps.setProperty(COMMAND,"load file");
loadNetworkFileTaskFactoryProps.setProperty(MENU_GRAVITY,"1.0");
loadNetworkFileTaskFactoryProps.setProperty(TOOL_BAR_GRAVITY,"3.0");
loadNetworkFileTaskFactoryProps.setProperty(LARGE_ICON_URL,getClass().getResource("/images/icons/net_file_import.png").toString());
loadNetworkFileTaskFactoryProps.setProperty(IN_TOOL_BAR,"true");
loadNetworkFileTaskFactoryProps.setProperty(TOOLTIP,"Import Network From File");
registerService(bc, loadNetworkFileTaskFactory, TaskFactory.class, loadNetworkFileTaskFactoryProps);
registerService(bc, loadNetworkFileTaskFactory, LoadNetworkFileTaskFactory.class, loadNetworkFileTaskFactoryProps);
Properties loadNetworkURLTaskFactoryProps = new Properties();
loadNetworkURLTaskFactoryProps.setProperty(ID,"loadNetworkURLTaskFactory");
loadNetworkURLTaskFactoryProps.setProperty(PREFERRED_MENU,"File.Import.Network");
loadNetworkURLTaskFactoryProps.setProperty(ACCELERATOR,"cmd shift l");
loadNetworkURLTaskFactoryProps.setProperty(MENU_GRAVITY,"2.0");
loadNetworkURLTaskFactoryProps.setProperty(TOOL_BAR_GRAVITY,"3.1");
loadNetworkURLTaskFactoryProps.setProperty(TITLE,"URL...");
loadNetworkURLTaskFactoryProps.setProperty(LARGE_ICON_URL,getClass().getResource("/images/icons/net_url_import.png").toString());
loadNetworkURLTaskFactoryProps.setProperty(IN_TOOL_BAR,"true");
loadNetworkURLTaskFactoryProps.setProperty(TOOLTIP,"Import Network From URL");
loadNetworkURLTaskFactoryProps.setProperty(COMMAND,"load url");
loadNetworkURLTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"network");
registerService(bc, loadNetworkURLTaskFactory, TaskFactory.class, loadNetworkURLTaskFactoryProps);
registerService(bc, loadNetworkURLTaskFactory, LoadNetworkURLTaskFactory.class, loadNetworkURLTaskFactoryProps);
Properties loadVizmapFileTaskFactoryProps = new Properties();
loadVizmapFileTaskFactoryProps.setProperty(PREFERRED_MENU,"File.Import");
loadVizmapFileTaskFactoryProps.setProperty(MENU_GRAVITY,"3.0");
loadVizmapFileTaskFactoryProps.setProperty(TITLE,"Vizmap File...");
loadVizmapFileTaskFactoryProps.setProperty(COMMAND,"load file");
loadVizmapFileTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"vizmap");
registerService(bc,loadVizmapFileTaskFactory,TaskFactory.class, loadVizmapFileTaskFactoryProps);
registerService(bc,loadVizmapFileTaskFactory,LoadVizmapFileTaskFactory.class, new Properties());
Properties importAttrsFileTaskFactoryProps = new Properties();
importAttrsFileTaskFactoryProps.setProperty(PREFERRED_MENU,"File.Import.Table");
importAttrsFileTaskFactoryProps.setProperty(MENU_GRAVITY,"1.1");
importAttrsFileTaskFactoryProps.setProperty(TOOL_BAR_GRAVITY,"3.2");
importAttrsFileTaskFactoryProps.setProperty(TITLE,"File...");
importAttrsFileTaskFactoryProps.setProperty(LARGE_ICON_URL,getClass().getResource("/images/icons/table_file_import.png").toString());
importAttrsFileTaskFactoryProps.setProperty(IN_TOOL_BAR,"true");
importAttrsFileTaskFactoryProps.setProperty(TOOLTIP,"Import Table From File");
importAttrsFileTaskFactoryProps.setProperty(COMMAND,"load file");
importAttrsFileTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"table");
importAttrsFileTaskFactoryProps.setProperty(ENABLE_FOR,"network");
registerService(bc,importAttrsFileTaskFactory,TaskFactory.class, importAttrsFileTaskFactoryProps);
registerService(bc,importAttrsFileTaskFactory,ImportTableFileTaskFactory.class, importAttrsFileTaskFactoryProps);
Properties importAttrsURLTaskFactoryProps = new Properties();
importAttrsURLTaskFactoryProps.setProperty(PREFERRED_MENU,"File.Import.Table");
importAttrsURLTaskFactoryProps.setProperty(MENU_GRAVITY,"1.2");
importAttrsURLTaskFactoryProps.setProperty(TOOL_BAR_GRAVITY,"3.3");
importAttrsURLTaskFactoryProps.setProperty(TITLE,"URL...");
importAttrsURLTaskFactoryProps.setProperty(LARGE_ICON_URL,getClass().getResource("/images/icons/table_url_import.png").toString());
importAttrsURLTaskFactoryProps.setProperty(IN_TOOL_BAR,"true");
importAttrsURLTaskFactoryProps.setProperty(TOOLTIP,"Import Table From URL");
importAttrsURLTaskFactoryProps.setProperty(COMMAND,"load url");
importAttrsURLTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"table");
importAttrsURLTaskFactoryProps.setProperty(ENABLE_FOR,"network");
registerService(bc,importAttrsURLTaskFactory,TaskFactory.class, importAttrsURLTaskFactoryProps);
registerService(bc,importAttrsURLTaskFactory,ImportTableURLTaskFactory.class, importAttrsURLTaskFactoryProps);
Properties proxySettingsTaskFactoryProps = new Properties();
proxySettingsTaskFactoryProps.setProperty(PREFERRED_MENU,"Edit.Preferences");
proxySettingsTaskFactoryProps.setProperty(MENU_GRAVITY,"1.0");
proxySettingsTaskFactoryProps.setProperty(TITLE,"Proxy Settings...");
registerService(bc,proxySettingsTaskFactory,TaskFactory.class, proxySettingsTaskFactoryProps);
Properties deleteSelectedNodesAndEdgesTaskFactoryProps = new Properties();
deleteSelectedNodesAndEdgesTaskFactoryProps.setProperty(PREFERRED_MENU,"Edit");
deleteSelectedNodesAndEdgesTaskFactoryProps.setProperty(ENABLE_FOR,"selectedNodesOrEdges");
deleteSelectedNodesAndEdgesTaskFactoryProps.setProperty(TITLE,"Delete Selected Nodes and Edges...");
deleteSelectedNodesAndEdgesTaskFactoryProps.setProperty(MENU_GRAVITY,"5.0");
deleteSelectedNodesAndEdgesTaskFactoryProps.setProperty(ACCELERATOR,"DELETE");
deleteSelectedNodesAndEdgesTaskFactoryProps.setProperty(COMMAND,"delete");
deleteSelectedNodesAndEdgesTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"network");
registerService(bc,deleteSelectedNodesAndEdgesTaskFactory,NetworkTaskFactory.class, deleteSelectedNodesAndEdgesTaskFactoryProps);
registerService(bc,deleteSelectedNodesAndEdgesTaskFactory,DeleteSelectedNodesAndEdgesTaskFactory.class, deleteSelectedNodesAndEdgesTaskFactoryProps);
Properties selectAllTaskFactoryProps = new Properties();
selectAllTaskFactoryProps.setProperty(PREFERRED_MENU,"Select");
selectAllTaskFactoryProps.setProperty(ACCELERATOR,"cmd alt a");
selectAllTaskFactoryProps.setProperty(ENABLE_FOR,"network");
selectAllTaskFactoryProps.setProperty(TITLE,"Select all nodes and edges");
selectAllTaskFactoryProps.setProperty(MENU_GRAVITY,"5.0");
selectAllTaskFactoryProps.setProperty(PREFERRED_ACTION, "NEW");
// selectAllTaskFactoryProps.setProperty(COMMAND,"select all");
// selectAllTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"network");
registerService(bc,selectAllTaskFactory,NetworkTaskFactory.class, selectAllTaskFactoryProps);
registerService(bc,selectAllTaskFactory,SelectAllTaskFactory.class, selectAllTaskFactoryProps);
Properties selectAllViewTaskFactoryProps = new Properties();
selectAllViewTaskFactoryProps.setProperty(PREFERRED_MENU, NETWORK_SELECT_MENU);
selectAllViewTaskFactoryProps.setProperty(ENABLE_FOR,"networkAndView");
selectAllViewTaskFactoryProps.setProperty(TITLE,"All nodes and edges");
selectAllViewTaskFactoryProps.setProperty(MENU_GRAVITY,"1.1");
selectAllViewTaskFactoryProps.setProperty(PREFERRED_ACTION, "NEW");
selectAllViewTaskFactoryProps.setProperty(IN_MENU_BAR,"false");
registerService(bc,selectAllTaskFactory,NetworkViewTaskFactory.class, selectAllViewTaskFactoryProps);
Properties selectAllEdgesTaskFactoryProps = new Properties();
selectAllEdgesTaskFactoryProps.setProperty(PREFERRED_MENU,"Select.Edges");
selectAllEdgesTaskFactoryProps.setProperty(ACCELERATOR,"cmd alt a");
selectAllEdgesTaskFactoryProps.setProperty(ENABLE_FOR,"network");
selectAllEdgesTaskFactoryProps.setProperty(TITLE,"Select all edges");
selectAllEdgesTaskFactoryProps.setProperty(MENU_GRAVITY,"4.0");
registerService(bc,selectAllEdgesTaskFactory,NetworkTaskFactory.class, selectAllEdgesTaskFactoryProps);
registerService(bc,selectAllEdgesTaskFactory,SelectAllEdgesTaskFactory.class, selectAllEdgesTaskFactoryProps);
Properties selectAllNodesTaskFactoryProps = new Properties();
selectAllNodesTaskFactoryProps.setProperty(ENABLE_FOR,"network");
selectAllNodesTaskFactoryProps.setProperty(PREFERRED_MENU,"Select.Nodes");
selectAllNodesTaskFactoryProps.setProperty(MENU_GRAVITY,"4.0");
selectAllNodesTaskFactoryProps.setProperty(ACCELERATOR,"cmd a");
selectAllNodesTaskFactoryProps.setProperty(TITLE,"Select all nodes");
registerService(bc,selectAllNodesTaskFactory,NetworkTaskFactory.class, selectAllNodesTaskFactoryProps);
registerService(bc,selectAllNodesTaskFactory,SelectAllNodesTaskFactory.class, selectAllNodesTaskFactoryProps);
Properties selectAdjacentEdgesTaskFactoryProps = new Properties();
selectAdjacentEdgesTaskFactoryProps.setProperty(ENABLE_FOR,"network");
selectAdjacentEdgesTaskFactoryProps.setProperty(PREFERRED_MENU,"Select.Edges");
selectAdjacentEdgesTaskFactoryProps.setProperty(MENU_GRAVITY,"6.0");
selectAdjacentEdgesTaskFactoryProps.setProperty(ACCELERATOR,"alt e");
selectAdjacentEdgesTaskFactoryProps.setProperty(TITLE,"Select adjacent edges");
// selectAdjacentEdgesTaskFactoryProps.setProperty(COMMAND,"select adjacent");
// selectAdjacentEdgesTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"edge");
registerService(bc,selectAdjacentEdgesTaskFactory,NetworkTaskFactory.class, selectAdjacentEdgesTaskFactoryProps);
registerService(bc,selectAdjacentEdgesTaskFactory,SelectAdjacentEdgesTaskFactory.class, selectAdjacentEdgesTaskFactoryProps);
Properties selectConnectedNodesTaskFactoryProps = new Properties();
selectConnectedNodesTaskFactoryProps.setProperty(ENABLE_FOR,"network");
selectConnectedNodesTaskFactoryProps.setProperty(PREFERRED_MENU,"Select.Nodes");
selectConnectedNodesTaskFactoryProps.setProperty(MENU_GRAVITY,"7.0");
selectConnectedNodesTaskFactoryProps.setProperty(ACCELERATOR,"cmd 7");
selectConnectedNodesTaskFactoryProps.setProperty(TITLE,"Nodes connected by selected edges");
// selectConnectedNodesTaskFactoryProps.setProperty(COMMAND,"select by connected edges");
// selectConnectedNodesTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"node");
registerService(bc,selectConnectedNodesTaskFactory,NetworkTaskFactory.class, selectConnectedNodesTaskFactoryProps);
registerService(bc,selectConnectedNodesTaskFactory,SelectConnectedNodesTaskFactory.class, selectConnectedNodesTaskFactoryProps);
Properties selectFirstNeighborsTaskFactoryProps = new Properties();
selectFirstNeighborsTaskFactoryProps.setProperty(ENABLE_FOR,"selectedNodesOrEdges");
selectFirstNeighborsTaskFactoryProps.setProperty(PREFERRED_MENU,"Select.Nodes.First Neighbors of Selected Nodes");
selectFirstNeighborsTaskFactoryProps.setProperty(MENU_GRAVITY,"6.0");
selectFirstNeighborsTaskFactoryProps.setProperty(TOOL_BAR_GRAVITY,"9.15");
selectFirstNeighborsTaskFactoryProps.setProperty(ACCELERATOR,"cmd 6");
selectFirstNeighborsTaskFactoryProps.setProperty(TITLE,"Undirected");
selectFirstNeighborsTaskFactoryProps.setProperty(LARGE_ICON_URL,getClass().getResource("/images/icons/select_firstneighbors.png").toString());
selectFirstNeighborsTaskFactoryProps.setProperty(IN_TOOL_BAR,"true");
selectFirstNeighborsTaskFactoryProps.setProperty(TOOLTIP,"First Neighbors of Selected Nodes (Undirected)");
// selectFirstNeighborsTaskFactoryProps.setProperty(COMMAND,"select first neighbors undirected");
// selectFirstNeighborsTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"node");
registerService(bc,selectFirstNeighborsTaskFactory,NetworkTaskFactory.class, selectFirstNeighborsTaskFactoryProps);
registerService(bc,selectFirstNeighborsTaskFactory,SelectFirstNeighborsTaskFactory.class, selectFirstNeighborsTaskFactoryProps);
Properties selectFirstNeighborsTaskFactoryInEdgeProps = new Properties();
selectFirstNeighborsTaskFactoryInEdgeProps.setProperty(ENABLE_FOR,"network");
selectFirstNeighborsTaskFactoryInEdgeProps.setProperty(PREFERRED_MENU,"Select.Nodes.First Neighbors of Selected Nodes");
selectFirstNeighborsTaskFactoryInEdgeProps.setProperty(MENU_GRAVITY,"6.1");
selectFirstNeighborsTaskFactoryInEdgeProps.setProperty(TITLE,"Directed: Incoming");
selectFirstNeighborsTaskFactoryInEdgeProps.setProperty(TOOLTIP,"First Neighbors of Selected Nodes (Directed: Incoming)");
// selectFirstNeighborsTaskFactoryInEdgeProps.setProperty(COMMAND,"select first neighbors incoming");
// selectFirstNeighborsTaskFactoryInEdgeProps.setProperty(COMMAND_NAMESPACE,"node");
registerService(bc,selectFirstNeighborsTaskFactoryInEdge,NetworkTaskFactory.class, selectFirstNeighborsTaskFactoryInEdgeProps);
registerService(bc,selectFirstNeighborsTaskFactoryInEdge,SelectFirstNeighborsTaskFactory.class, selectFirstNeighborsTaskFactoryInEdgeProps);
Properties selectFirstNeighborsTaskFactoryOutEdgeProps = new Properties();
selectFirstNeighborsTaskFactoryOutEdgeProps.setProperty(ENABLE_FOR,"network");
selectFirstNeighborsTaskFactoryOutEdgeProps.setProperty(PREFERRED_MENU,"Select.Nodes.First Neighbors of Selected Nodes");
selectFirstNeighborsTaskFactoryOutEdgeProps.setProperty(MENU_GRAVITY,"6.2");
selectFirstNeighborsTaskFactoryOutEdgeProps.setProperty(TITLE,"Directed: Outgoing");
selectFirstNeighborsTaskFactoryOutEdgeProps.setProperty(TOOLTIP,"First Neighbors of Selected Nodes (Directed: Outgoing)");
// selectFirstNeighborsTaskFactoryOutEdgeProps.setProperty(COMMAND,"select first neighbors outgoing");
// selectFirstNeighborsTaskFactoryOutEdgeProps.setProperty(COMMAND_NAMESPACE,"node");
registerService(bc,selectFirstNeighborsTaskFactoryOutEdge,NetworkTaskFactory.class, selectFirstNeighborsTaskFactoryOutEdgeProps);
registerService(bc,selectFirstNeighborsTaskFactoryOutEdge,SelectFirstNeighborsTaskFactory.class, selectFirstNeighborsTaskFactoryOutEdgeProps);
Properties deselectAllTaskFactoryProps = new Properties();
deselectAllTaskFactoryProps.setProperty(ENABLE_FOR,"network");
deselectAllTaskFactoryProps.setProperty(PREFERRED_MENU,"Select");
deselectAllTaskFactoryProps.setProperty(MENU_GRAVITY,"5.1");
deselectAllTaskFactoryProps.setProperty(ACCELERATOR,"cmd shift alt a");
deselectAllTaskFactoryProps.setProperty(TITLE,"Deselect all nodes and edges");
// deselectAllTaskFactoryProps.setProperty(COMMAND,"deselect all");
// deselectAllTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"network");
registerService(bc,deselectAllTaskFactory,NetworkTaskFactory.class, deselectAllTaskFactoryProps);
registerService(bc,deselectAllTaskFactory,DeselectAllTaskFactory.class, deselectAllTaskFactoryProps);
Properties deselectAllEdgesTaskFactoryProps = new Properties();
deselectAllEdgesTaskFactoryProps.setProperty(ENABLE_FOR,"network");
deselectAllEdgesTaskFactoryProps.setProperty(PREFERRED_MENU,"Select.Edges");
deselectAllEdgesTaskFactoryProps.setProperty(MENU_GRAVITY,"5.0");
deselectAllEdgesTaskFactoryProps.setProperty(ACCELERATOR,"alt shift a");
deselectAllEdgesTaskFactoryProps.setProperty(TITLE,"Deselect all edges");
registerService(bc,deselectAllEdgesTaskFactory,NetworkTaskFactory.class, deselectAllEdgesTaskFactoryProps);
registerService(bc,deselectAllEdgesTaskFactory,DeselectAllEdgesTaskFactory.class, deselectAllEdgesTaskFactoryProps);
Properties deselectAllNodesTaskFactoryProps = new Properties();
deselectAllNodesTaskFactoryProps.setProperty(ENABLE_FOR,"network");
deselectAllNodesTaskFactoryProps.setProperty(PREFERRED_MENU,"Select.Nodes");
deselectAllNodesTaskFactoryProps.setProperty(MENU_GRAVITY,"5.0");
deselectAllNodesTaskFactoryProps.setProperty(ACCELERATOR,"cmd shift a");
deselectAllNodesTaskFactoryProps.setProperty(TITLE,"Deselect all nodes");
registerService(bc,deselectAllNodesTaskFactory,NetworkTaskFactory.class, deselectAllNodesTaskFactoryProps);
registerService(bc,deselectAllNodesTaskFactory,DeselectAllNodesTaskFactory.class, deselectAllNodesTaskFactoryProps);
Properties invertSelectedEdgesTaskFactoryProps = new Properties();
invertSelectedEdgesTaskFactoryProps.setProperty(ENABLE_FOR,"network");
invertSelectedEdgesTaskFactoryProps.setProperty(PREFERRED_MENU,"Select.Edges");
invertSelectedEdgesTaskFactoryProps.setProperty(MENU_GRAVITY,"1.0");
invertSelectedEdgesTaskFactoryProps.setProperty(ACCELERATOR,"alt i");
invertSelectedEdgesTaskFactoryProps.setProperty(TITLE,"Invert edge selection");
registerService(bc,invertSelectedEdgesTaskFactory,NetworkTaskFactory.class, invertSelectedEdgesTaskFactoryProps);
registerService(bc,invertSelectedEdgesTaskFactory,InvertSelectedEdgesTaskFactory.class, invertSelectedEdgesTaskFactoryProps);
Properties invertSelectedNodesTaskFactoryProps = new Properties();
invertSelectedNodesTaskFactoryProps.setProperty(ENABLE_FOR,"selectedNodes");
invertSelectedNodesTaskFactoryProps.setProperty(PREFERRED_MENU,"Select.Nodes");
invertSelectedNodesTaskFactoryProps.setProperty(MENU_GRAVITY,"1.0");
invertSelectedNodesTaskFactoryProps.setProperty(TOOL_BAR_GRAVITY,"9.2");
invertSelectedNodesTaskFactoryProps.setProperty(ACCELERATOR,"cmd i");
invertSelectedNodesTaskFactoryProps.setProperty(TITLE,"Invert node selection");
invertSelectedNodesTaskFactoryProps.setProperty(LARGE_ICON_URL,getClass().getResource("/images/icons/invert_selection.png").toString());
invertSelectedNodesTaskFactoryProps.setProperty(IN_TOOL_BAR,"false");
invertSelectedNodesTaskFactoryProps.setProperty(TOOLTIP,"Invert Node Selection");
registerService(bc,invertSelectedNodesTaskFactory,NetworkTaskFactory.class, invertSelectedNodesTaskFactoryProps);
registerService(bc,invertSelectedNodesTaskFactory,InvertSelectedNodesTaskFactory.class, invertSelectedNodesTaskFactoryProps);
Properties selectFromFileListTaskFactoryProps = new Properties();
selectFromFileListTaskFactoryProps.setProperty(ENABLE_FOR,"network");
selectFromFileListTaskFactoryProps.setProperty(PREFERRED_MENU,"Select.Nodes");
selectFromFileListTaskFactoryProps.setProperty(MENU_GRAVITY,"8.0");
selectFromFileListTaskFactoryProps.setProperty(ACCELERATOR,"cmd i");
selectFromFileListTaskFactoryProps.setProperty(TITLE,"From ID List file...");
selectFromFileListTaskFactoryProps.setProperty(COMMAND,"select from file");
selectFromFileListTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"node");
registerService(bc,selectFromFileListTaskFactory,NetworkTaskFactory.class, selectFromFileListTaskFactoryProps);
registerService(bc,selectFromFileListTaskFactory,SelectFromFileListTaskFactory.class, selectFromFileListTaskFactoryProps);
Properties selectFirstNeighborsNodeViewTaskFactoryProps = new Properties();
selectFirstNeighborsNodeViewTaskFactoryProps.setProperty(PREFERRED_MENU,NODE_SELECT_MENU);
selectFirstNeighborsNodeViewTaskFactoryProps.setProperty(MENU_GRAVITY,"1.0");
selectFirstNeighborsNodeViewTaskFactoryProps.setProperty(TITLE,"Select First Neighbors (Undirected)");
registerService(bc,selectFirstNeighborsNodeViewTaskFactory,NodeViewTaskFactory.class, selectFirstNeighborsNodeViewTaskFactoryProps);
registerService(bc,selectFirstNeighborsNodeViewTaskFactory,SelectFirstNeighborsNodeViewTaskFactory.class, selectFirstNeighborsNodeViewTaskFactoryProps);
Properties hideSelectedTaskFactoryProps = new Properties();
hideSelectedTaskFactoryProps.setProperty(ENABLE_FOR,"selectedNodesOrEdges");
hideSelectedTaskFactoryProps.setProperty(PREFERRED_MENU,"Select");
hideSelectedTaskFactoryProps.setProperty(MENU_GRAVITY,"3.1");
hideSelectedTaskFactoryProps.setProperty(TOOL_BAR_GRAVITY,"9.5");
hideSelectedTaskFactoryProps.setProperty(TITLE,"Hide selected nodes and edges");
hideSelectedTaskFactoryProps.setProperty(LARGE_ICON_URL,getClass().getResource("/images/icons/hide_selected.png").toString());
hideSelectedTaskFactoryProps.setProperty(IN_TOOL_BAR,"true");
hideSelectedTaskFactoryProps.setProperty(TOOLTIP,"Hide Selected Nodes and Edges");
// hideSelectedTaskFactoryProps.setProperty(COMMAND,"hide selected");
// hideSelectedTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"view");
registerService(bc,hideSelectedTaskFactory,NetworkViewTaskFactory.class, hideSelectedTaskFactoryProps);
registerService(bc,hideSelectedTaskFactory,HideSelectedTaskFactory.class, hideSelectedTaskFactoryProps);
Properties hideSelectedNodesTaskFactoryProps = new Properties();
hideSelectedNodesTaskFactoryProps.setProperty(ENABLE_FOR,"selectedNodes");
hideSelectedNodesTaskFactoryProps.setProperty(PREFERRED_MENU,"Select.Nodes");
hideSelectedNodesTaskFactoryProps.setProperty(MENU_GRAVITY,"2.0");
hideSelectedNodesTaskFactoryProps.setProperty(TITLE,"Hide selected nodes");
// hideSelectedNodesTaskFactoryProps.setProperty(COMMAND,"hide selected nodes");
// hideSelectedNodesTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"view");
registerService(bc,hideSelectedNodesTaskFactory,NetworkViewTaskFactory.class, hideSelectedNodesTaskFactoryProps);
registerService(bc,hideSelectedNodesTaskFactory,HideSelectedNodesTaskFactory.class, hideSelectedNodesTaskFactoryProps);
Properties hideSelectedEdgesTaskFactoryProps = new Properties();
hideSelectedEdgesTaskFactoryProps.setProperty(ENABLE_FOR,"selectedEdges");
hideSelectedEdgesTaskFactoryProps.setProperty(PREFERRED_MENU,"Select.Edges");
hideSelectedEdgesTaskFactoryProps.setProperty(MENU_GRAVITY,"2.0");
hideSelectedEdgesTaskFactoryProps.setProperty(TITLE,"Hide selected edges");
// hideSelectedEdgesTaskFactoryProps.setProperty(COMMAND,"hide selected edges");
// hideSelectedEdgesTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"view");
registerService(bc,hideSelectedEdgesTaskFactory,NetworkViewTaskFactory.class, hideSelectedEdgesTaskFactoryProps);
registerService(bc,hideSelectedEdgesTaskFactory,HideSelectedEdgesTaskFactory.class, hideSelectedEdgesTaskFactoryProps);
Properties unHideAllTaskFactoryProps = new Properties();
unHideAllTaskFactoryProps.setProperty(ENABLE_FOR,"networkAndView");
unHideAllTaskFactoryProps.setProperty(PREFERRED_MENU,"Select");
unHideAllTaskFactoryProps.setProperty(MENU_GRAVITY,"3.0");
unHideAllTaskFactoryProps.setProperty(TOOL_BAR_GRAVITY,"9.6");
unHideAllTaskFactoryProps.setProperty(TITLE,"Show all nodes and edges");
// unHideAllTaskFactoryProps.setProperty(COMMAND,"show all");
// unHideAllTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"view");
unHideAllTaskFactoryProps.setProperty(LARGE_ICON_URL,getClass().getResource("/images/icons/unhide_all.png").toString());
unHideAllTaskFactoryProps.setProperty(IN_TOOL_BAR,"true");
unHideAllTaskFactoryProps.setProperty(TOOLTIP,"Show All Nodes and Edges");
registerService(bc,unHideAllTaskFactory,NetworkViewTaskFactory.class, unHideAllTaskFactoryProps);
registerService(bc,unHideAllTaskFactory,UnHideAllTaskFactory.class, unHideAllTaskFactoryProps);
Properties unHideAllNodesTaskFactoryProps = new Properties();
unHideAllNodesTaskFactoryProps.setProperty(ENABLE_FOR,"networkAndView");
unHideAllNodesTaskFactoryProps.setProperty(PREFERRED_MENU,"Select.Nodes");
unHideAllNodesTaskFactoryProps.setProperty(MENU_GRAVITY,"3.0");
unHideAllNodesTaskFactoryProps.setProperty(TITLE,"Show all nodes");
// unHideAllNodesTaskFactoryProps.setProperty(COMMAND,"show all nodes");
// unHideAllNodesTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"view");
registerService(bc,unHideAllNodesTaskFactory,NetworkViewTaskFactory.class, unHideAllNodesTaskFactoryProps);
registerService(bc,unHideAllNodesTaskFactory,UnHideAllNodesTaskFactory.class, unHideAllNodesTaskFactoryProps);
Properties unHideAllEdgesTaskFactoryProps = new Properties();
unHideAllEdgesTaskFactoryProps.setProperty(ENABLE_FOR,"networkAndView");
unHideAllEdgesTaskFactoryProps.setProperty(PREFERRED_MENU,"Select.Edges");
unHideAllEdgesTaskFactoryProps.setProperty(MENU_GRAVITY,"3.0");
unHideAllEdgesTaskFactoryProps.setProperty(TITLE,"Show all edges");
// unHideAllEdgesTaskFactoryProps.setProperty(COMMAND,"show all edges");
// unHideAllEdgesTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"view");
registerService(bc,unHideAllEdgesTaskFactory,NetworkViewTaskFactory.class, unHideAllEdgesTaskFactoryProps);
registerService(bc,unHideAllEdgesTaskFactory,UnHideAllEdgesTaskFactory.class, unHideAllEdgesTaskFactoryProps);
Properties newEmptyNetworkTaskFactoryProps = new Properties();
newEmptyNetworkTaskFactoryProps.setProperty(PREFERRED_MENU,"File.New.Network");
newEmptyNetworkTaskFactoryProps.setProperty(MENU_GRAVITY,"4.0");
newEmptyNetworkTaskFactoryProps.setProperty(TITLE,"Empty Network");
newEmptyNetworkTaskFactoryProps.setProperty(COMMAND,"create empty");
newEmptyNetworkTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"network");
registerService(bc,newEmptyNetworkTaskFactory,TaskFactory.class, newEmptyNetworkTaskFactoryProps);
registerService(bc,newEmptyNetworkTaskFactory,NewEmptyNetworkViewFactory.class, newEmptyNetworkTaskFactoryProps);
Properties newNetworkSelectedNodesEdgesTaskFactoryProps = new Properties();
newNetworkSelectedNodesEdgesTaskFactoryProps.setProperty(ENABLE_FOR,"selectedNodesOrEdges");
newNetworkSelectedNodesEdgesTaskFactoryProps.setProperty(PREFERRED_MENU,"File.New.Network");
newNetworkSelectedNodesEdgesTaskFactoryProps.setProperty(MENU_GRAVITY,"2.0");
newNetworkSelectedNodesEdgesTaskFactoryProps.setProperty(ACCELERATOR,"cmd shift n");
newNetworkSelectedNodesEdgesTaskFactoryProps.setProperty(TITLE,"From selected nodes, selected edges");
// newNetworkSelectedNodesEdgesTaskFactoryProps.setProperty(COMMAND,"create from selected nodes and edges");
// newNetworkSelectedNodesEdgesTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"network");
registerService(bc,newNetworkSelectedNodesEdgesTaskFactory,NetworkTaskFactory.class, newNetworkSelectedNodesEdgesTaskFactoryProps);
registerService(bc,newNetworkSelectedNodesEdgesTaskFactory,NewNetworkSelectedNodesAndEdgesTaskFactory.class, newNetworkSelectedNodesEdgesTaskFactoryProps);
Properties newNetworkSelectedNodesOnlyTaskFactoryProps = new Properties();
newNetworkSelectedNodesOnlyTaskFactoryProps.setProperty(PREFERRED_MENU,"File.New.Network");
newNetworkSelectedNodesOnlyTaskFactoryProps.setProperty(LARGE_ICON_URL,getClass().getResource("/images/icons/new_fromselected.png").toString());
newNetworkSelectedNodesOnlyTaskFactoryProps.setProperty(ACCELERATOR,"cmd n");
newNetworkSelectedNodesOnlyTaskFactoryProps.setProperty(ENABLE_FOR,"selectedNodes");
newNetworkSelectedNodesOnlyTaskFactoryProps.setProperty(TITLE,"From selected nodes, all edges");
newNetworkSelectedNodesOnlyTaskFactoryProps.setProperty(TOOL_BAR_GRAVITY,"9.1");
newNetworkSelectedNodesOnlyTaskFactoryProps.setProperty(IN_TOOL_BAR,"true");
newNetworkSelectedNodesOnlyTaskFactoryProps.setProperty(MENU_GRAVITY,"1.0");
newNetworkSelectedNodesOnlyTaskFactoryProps.setProperty(TOOLTIP,"New Network From Selection");
// newNetworkSelectedNodesOnlyTaskFactoryProps.setProperty(COMMAND,"create from selected nodes and all edges");
// newNetworkSelectedNodesOnlyTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"network");
registerService(bc,newNetworkSelectedNodesOnlyTaskFactory,NetworkTaskFactory.class, newNetworkSelectedNodesOnlyTaskFactoryProps);
registerService(bc,newNetworkSelectedNodesOnlyTaskFactory,NewNetworkSelectedNodesOnlyTaskFactory.class, newNetworkSelectedNodesOnlyTaskFactoryProps);
Properties newNetworkCommandTaskFactoryProps = new Properties();
newNetworkCommandTaskFactoryProps.setProperty(COMMAND,"create");
newNetworkCommandTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"network");
registerService(bc,newNetworkCommandTaskFactory,NetworkTaskFactory.class, newNetworkCommandTaskFactoryProps);
Properties cloneNetworkTaskFactoryProps = new Properties();
cloneNetworkTaskFactoryProps.setProperty(ENABLE_FOR,"network");
cloneNetworkTaskFactoryProps.setProperty(PREFERRED_MENU,"File.New.Network");
cloneNetworkTaskFactoryProps.setProperty(MENU_GRAVITY,"3.0");
cloneNetworkTaskFactoryProps.setProperty(TITLE,"Clone Current Network");
cloneNetworkTaskFactoryProps.setProperty(COMMAND,"clone");
cloneNetworkTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"network");
registerService(bc,cloneNetworkTaskFactory,NetworkTaskFactory.class, cloneNetworkTaskFactoryProps);
registerService(bc,cloneNetworkTaskFactory,CloneNetworkTaskFactory.class, cloneNetworkTaskFactoryProps);
Properties destroyNetworkTaskFactoryProps = new Properties();
destroyNetworkTaskFactoryProps.setProperty(PREFERRED_MENU,"Edit");
destroyNetworkTaskFactoryProps.setProperty(ACCELERATOR,"cmd shift w");
destroyNetworkTaskFactoryProps.setProperty(ENABLE_FOR,"network");
destroyNetworkTaskFactoryProps.setProperty(TITLE,"Destroy Network");
destroyNetworkTaskFactoryProps.setProperty(IN_NETWORK_PANEL_CONTEXT_MENU,"true");
destroyNetworkTaskFactoryProps.setProperty(MENU_GRAVITY,"3.2");
destroyNetworkTaskFactoryProps.setProperty(COMMAND,"destroy");
destroyNetworkTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"network");
registerService(bc,destroyNetworkTaskFactory,NetworkCollectionTaskFactory.class, destroyNetworkTaskFactoryProps);
registerService(bc,destroyNetworkTaskFactory,DestroyNetworkTaskFactory.class, destroyNetworkTaskFactoryProps);
registerService(bc,destroyNetworkTaskFactory,TaskFactory.class, destroyNetworkTaskFactoryProps);
Properties destroyNetworkViewTaskFactoryProps = new Properties();
destroyNetworkViewTaskFactoryProps.setProperty(PREFERRED_MENU,"Edit");
destroyNetworkViewTaskFactoryProps.setProperty(ACCELERATOR,"cmd w");
destroyNetworkViewTaskFactoryProps.setProperty(ENABLE_FOR,"networkAndView");
destroyNetworkViewTaskFactoryProps.setProperty(TITLE,"Destroy View");
destroyNetworkViewTaskFactoryProps.setProperty(IN_NETWORK_PANEL_CONTEXT_MENU,"true");
destroyNetworkViewTaskFactoryProps.setProperty(MENU_GRAVITY,"3.1");
destroyNetworkViewTaskFactoryProps.setProperty(COMMAND,"destroy");
destroyNetworkViewTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"view");
registerService(bc,destroyNetworkViewTaskFactory,NetworkViewCollectionTaskFactory.class, destroyNetworkViewTaskFactoryProps);
registerService(bc,destroyNetworkViewTaskFactory,DestroyNetworkViewTaskFactory.class, destroyNetworkViewTaskFactoryProps);
Properties zoomInTaskFactoryProps = new Properties();
zoomInTaskFactoryProps.setProperty(ACCELERATOR,"cmd equals");
zoomInTaskFactoryProps.setProperty(LARGE_ICON_URL,getClass().getResource("/images/icons/stock_zoom-in.png").toString());
zoomInTaskFactoryProps.setProperty(ENABLE_FOR,"networkAndView");
zoomInTaskFactoryProps.setProperty(TITLE,"Zoom In");
zoomInTaskFactoryProps.setProperty(TOOLTIP,"Zoom In");
zoomInTaskFactoryProps.setProperty(TOOL_BAR_GRAVITY,"5.1");
zoomInTaskFactoryProps.setProperty(IN_TOOL_BAR,"true");
// zoomInTaskFactoryProps.setProperty(COMMAND,"zoom in");
// zoomInTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"view");
registerService(bc,zoomInTaskFactory,NetworkTaskFactory.class, zoomInTaskFactoryProps);
Properties zoomOutTaskFactoryProps = new Properties();
zoomOutTaskFactoryProps.setProperty(ACCELERATOR,"cmd minus");
zoomOutTaskFactoryProps.setProperty(LARGE_ICON_URL,getClass().getResource("/images/icons/stock_zoom-out.png").toString());
zoomOutTaskFactoryProps.setProperty(ENABLE_FOR,"networkAndView");
zoomOutTaskFactoryProps.setProperty(TITLE,"Zoom Out");
zoomOutTaskFactoryProps.setProperty(TOOLTIP,"Zoom Out");
zoomOutTaskFactoryProps.setProperty(TOOL_BAR_GRAVITY,"5.2");
zoomOutTaskFactoryProps.setProperty(IN_TOOL_BAR,"true");
// zoomOutTaskFactoryProps.setProperty(COMMAND,"zoom out");
// zoomOutTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"view");
registerService(bc,zoomOutTaskFactory,NetworkTaskFactory.class, zoomOutTaskFactoryProps);
Properties fitSelectedTaskFactoryProps = new Properties();
fitSelectedTaskFactoryProps.setProperty(ACCELERATOR,"cmd shift f");
fitSelectedTaskFactoryProps.setProperty(LARGE_ICON_URL,getClass().getResource("/images/icons/stock_zoom-object.png").toString());
fitSelectedTaskFactoryProps.setProperty(ENABLE_FOR,"networkAndView");
fitSelectedTaskFactoryProps.setProperty(TITLE,"Fit Selected");
fitSelectedTaskFactoryProps.setProperty(TOOLTIP,"Zoom selected region");
fitSelectedTaskFactoryProps.setProperty(TOOL_BAR_GRAVITY,"5.4");
fitSelectedTaskFactoryProps.setProperty(IN_TOOL_BAR,"true");
fitSelectedTaskFactoryProps.setProperty(COMMAND,"fit selected");
fitSelectedTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"view");
registerService(bc,fitSelectedTaskFactory,NetworkTaskFactory.class, fitSelectedTaskFactoryProps);
Properties fitContentTaskFactoryProps = new Properties();
fitContentTaskFactoryProps.setProperty(ACCELERATOR,"cmd f");
fitContentTaskFactoryProps.setProperty(LARGE_ICON_URL,getClass().getResource("/images/icons/stock_zoom-1.png").toString());
fitContentTaskFactoryProps.setProperty(ENABLE_FOR,"networkAndView");
fitContentTaskFactoryProps.setProperty(TITLE,"Fit Content");
fitContentTaskFactoryProps.setProperty(TOOLTIP,"Zoom out to display all of current Network");
fitContentTaskFactoryProps.setProperty(TOOL_BAR_GRAVITY,"5.3");
fitContentTaskFactoryProps.setProperty(IN_TOOL_BAR,"true");
fitContentTaskFactoryProps.setProperty(COMMAND,"fit content");
fitContentTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"view");
registerService(bc,fitContentTaskFactory,NetworkTaskFactory.class, fitContentTaskFactoryProps);
Properties editNetworkTitleTaskFactoryProps = new Properties();
editNetworkTitleTaskFactoryProps.setProperty(ENABLE_FOR,"singleNetwork");
editNetworkTitleTaskFactoryProps.setProperty(PREFERRED_MENU,"Edit");
editNetworkTitleTaskFactoryProps.setProperty(MENU_GRAVITY,"5.5");
editNetworkTitleTaskFactoryProps.setProperty(TITLE,"Rename Network...");
editNetworkTitleTaskFactoryProps.setProperty(IN_NETWORK_PANEL_CONTEXT_MENU,"true");
editNetworkTitleTaskFactoryProps.setProperty(COMMAND,"rename");
editNetworkTitleTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"network");
registerService(bc,editNetworkTitleTaskFactory,NetworkTaskFactory.class, editNetworkTitleTaskFactoryProps);
registerService(bc,editNetworkTitleTaskFactory,EditNetworkTitleTaskFactory.class, editNetworkTitleTaskFactoryProps);
Properties createNetworkViewTaskFactoryProps = new Properties();
createNetworkViewTaskFactoryProps.setProperty(ID,"createNetworkViewTaskFactory");
// No ENABLE_FOR because that is handled by the isReady() methdod of the task factory.
createNetworkViewTaskFactoryProps.setProperty(PREFERRED_MENU,"Edit");
createNetworkViewTaskFactoryProps.setProperty(MENU_GRAVITY,"3.0");
createNetworkViewTaskFactoryProps.setProperty(TITLE,"Create View");
createNetworkViewTaskFactoryProps.setProperty(IN_NETWORK_PANEL_CONTEXT_MENU,"true");
createNetworkViewTaskFactoryProps.setProperty(COMMAND,"create");
createNetworkViewTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"view");
registerService(bc,createNetworkViewTaskFactory,NetworkCollectionTaskFactory.class, createNetworkViewTaskFactoryProps);
registerService(bc,createNetworkViewTaskFactory,CreateNetworkViewTaskFactory.class, createNetworkViewTaskFactoryProps);
// For commands
registerService(bc,createNetworkViewTaskFactory,TaskFactory.class, createNetworkViewTaskFactoryProps);
Properties exportNetworkImageTaskFactoryProps = new Properties();
exportNetworkImageTaskFactoryProps.setProperty(PREFERRED_MENU,"File.Export");
exportNetworkImageTaskFactoryProps.setProperty(LARGE_ICON_URL,getClass().getResource("/images/icons/img_file_export.png").toString());
exportNetworkImageTaskFactoryProps.setProperty(ENABLE_FOR,"networkAndView");
exportNetworkImageTaskFactoryProps.setProperty(MENU_GRAVITY,"1.2");
exportNetworkImageTaskFactoryProps.setProperty(TITLE,"Network View as Graphics...");
exportNetworkImageTaskFactoryProps.setProperty(TOOL_BAR_GRAVITY,"3.7");
exportNetworkImageTaskFactoryProps.setProperty(IN_TOOL_BAR,"true");
exportNetworkImageTaskFactoryProps.setProperty(IN_CONTEXT_MENU,"false");
exportNetworkImageTaskFactoryProps.setProperty(TOOLTIP,"Export Network Image to File");
exportNetworkImageTaskFactoryProps.setProperty(COMMAND,"export");
exportNetworkImageTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"view");
registerService(bc,exportNetworkImageTaskFactory,NetworkViewTaskFactory.class, exportNetworkImageTaskFactoryProps);
registerService(bc,exportNetworkImageTaskFactory,ExportNetworkImageTaskFactory.class, exportNetworkImageTaskFactoryProps);
Properties exportNetworkViewTaskFactoryProps = new Properties();
exportNetworkViewTaskFactoryProps.setProperty(ENABLE_FOR,"networkAndView");
exportNetworkViewTaskFactoryProps.setProperty(PREFERRED_MENU,"File.Export");
exportNetworkViewTaskFactoryProps.setProperty(MENU_GRAVITY,"1.1");
exportNetworkViewTaskFactoryProps.setProperty(TOOL_BAR_GRAVITY,"3.5");
exportNetworkViewTaskFactoryProps.setProperty(TITLE,"Network...");
exportNetworkViewTaskFactoryProps.setProperty(LARGE_ICON_URL,getClass().getResource("/images/icons/net_file_export.png").toString());
exportNetworkViewTaskFactoryProps.setProperty(IN_TOOL_BAR,"true");
exportNetworkViewTaskFactoryProps.setProperty(IN_CONTEXT_MENU,"false");
exportNetworkViewTaskFactoryProps.setProperty(TOOLTIP,"Export Network to File");
exportNetworkViewTaskFactoryProps.setProperty(COMMAND,"export");
exportNetworkViewTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"network");
registerService(bc,exportNetworkViewTaskFactory,NetworkViewTaskFactory.class, exportNetworkViewTaskFactoryProps);
registerService(bc,exportNetworkViewTaskFactory,ExportNetworkViewTaskFactory.class, exportNetworkViewTaskFactoryProps);
Properties exportCurrentTableTaskFactoryProps = new Properties();
exportCurrentTableTaskFactoryProps.setProperty(ENABLE_FOR,"table");
exportCurrentTableTaskFactoryProps.setProperty(PREFERRED_MENU,"File.Export");
exportCurrentTableTaskFactoryProps.setProperty(MENU_GRAVITY,"1.3");
exportCurrentTableTaskFactoryProps.setProperty(TOOL_BAR_GRAVITY,"3.6");
exportCurrentTableTaskFactoryProps.setProperty(TITLE,"Table...");
exportCurrentTableTaskFactoryProps.setProperty(LARGE_ICON_URL,getClass().getResource("/images/icons/table_file_export.png").toString());
exportCurrentTableTaskFactoryProps.setProperty(IN_TOOL_BAR,"true");
exportCurrentTableTaskFactoryProps.setProperty(TOOLTIP,"Export Table to File");
exportCurrentTableTaskFactoryProps.setProperty(COMMAND,"export");
exportCurrentTableTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"table");
registerService(bc,exportCurrentTableTaskFactory, TaskFactory.class, exportCurrentTableTaskFactoryProps);
registerService(bc,exportCurrentTableTaskFactory,ExportSelectedTableTaskFactory.class, exportCurrentTableTaskFactoryProps);
Properties exportVizmapTaskFactoryProps = new Properties();
exportVizmapTaskFactoryProps.setProperty(ENABLE_FOR,"vizmap");
exportVizmapTaskFactoryProps.setProperty(PREFERRED_MENU,"File.Export");
exportVizmapTaskFactoryProps.setProperty(MENU_GRAVITY,"1.4");
exportVizmapTaskFactoryProps.setProperty(TITLE,"Vizmap...");
exportVizmapTaskFactoryProps.setProperty(COMMAND,"export");
exportVizmapTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"vizmap");
registerService(bc,exportVizmapTaskFactory,TaskFactory.class, exportVizmapTaskFactoryProps);
registerService(bc,exportVizmapTaskFactory,ExportVizmapTaskFactory.class, exportVizmapTaskFactoryProps);
Properties loadDataFileTaskFactoryProps = new Properties();
loadDataFileTaskFactoryProps.setProperty(PREFERRED_MENU,"File.Load Data Table");
loadDataFileTaskFactoryProps.setProperty(MENU_GRAVITY,"1.1");
loadDataFileTaskFactoryProps.setProperty(TITLE,"File...");
//loadDataFileTaskFactoryProps.setProperty(ServiceProperties.INSERT_SEPARATOR_BEFORE, "true");
loadDataFileTaskFactoryProps.setProperty(TOOLTIP,"Load Data Table From File");
loadDataFileTaskFactoryProps.setProperty(COMMAND,"load file");
loadDataFileTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"table");
registerService(bc,loadAttrsFileTaskFactory,TaskFactory.class, loadDataFileTaskFactoryProps);
registerService(bc,loadAttrsFileTaskFactory,LoadTableFileTaskFactory.class, loadDataFileTaskFactoryProps);
Properties loadDataURLTaskFactoryProps = new Properties();
loadDataURLTaskFactoryProps.setProperty(PREFERRED_MENU,"File.Load Data Table");
loadDataURLTaskFactoryProps.setProperty(MENU_GRAVITY,"1.2");
loadDataURLTaskFactoryProps.setProperty(TITLE,"URL...");
loadDataURLTaskFactoryProps.setProperty(TOOLTIP,"Load Data Table From URL");
loadDataURLTaskFactoryProps.setProperty(COMMAND,"load url");
loadDataURLTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"table");
registerService(bc,loadAttrsURLTaskFactory,TaskFactory.class, loadDataURLTaskFactoryProps);
registerService(bc,loadAttrsURLTaskFactory,LoadTableURLTaskFactory.class, loadDataURLTaskFactoryProps);
Properties MergeGlobalTaskFactoryProps = new Properties();
MergeGlobalTaskFactoryProps.setProperty(ENABLE_FOR,"network");
MergeGlobalTaskFactoryProps.setProperty(PREFERRED_MENU,"File");
MergeGlobalTaskFactoryProps.setProperty(TITLE,"Merge Data Table...");
//MergeGlobalTaskFactoryProps.setProperty(ServiceProperties.INSERT_SEPARATOR_AFTER, "true");
//MergeGlobalTaskFactoryProps.setProperty(TOOL_BAR_GRAVITY,"1.1");
MergeGlobalTaskFactoryProps.setProperty(MENU_GRAVITY,"5.4");
MergeGlobalTaskFactoryProps.setProperty(TOOLTIP,"Merge Data Table");
registerService(bc,mergeTableTaskFactory,TaskFactory.class, MergeGlobalTaskFactoryProps);
registerService(bc,mergeTableTaskFactory,MergeDataTableTaskFactory.class, MergeGlobalTaskFactoryProps);
Properties newSessionTaskFactoryProps = new Properties();
newSessionTaskFactoryProps.setProperty(PREFERRED_MENU,"File.New");
newSessionTaskFactoryProps.setProperty(MENU_GRAVITY,"1.1");
newSessionTaskFactoryProps.setProperty(TITLE,"Session");
newSessionTaskFactoryProps.setProperty(COMMAND,"new");
newSessionTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"session");
registerService(bc,newSessionTaskFactory,TaskFactory.class, newSessionTaskFactoryProps);
registerService(bc,newSessionTaskFactory,NewSessionTaskFactory.class, newSessionTaskFactoryProps);
Properties openSessionTaskFactoryProps = new Properties();
openSessionTaskFactoryProps.setProperty(ID,"openSessionTaskFactory");
openSessionTaskFactoryProps.setProperty(PREFERRED_MENU,"File");
openSessionTaskFactoryProps.setProperty(ACCELERATOR,"cmd o");
openSessionTaskFactoryProps.setProperty(LARGE_ICON_URL,getClass().getResource("/images/icons/open_session.png").toString());
openSessionTaskFactoryProps.setProperty(TITLE,"Open...");
openSessionTaskFactoryProps.setProperty(TOOL_BAR_GRAVITY,"1.0");
openSessionTaskFactoryProps.setProperty(IN_TOOL_BAR,"true");
openSessionTaskFactoryProps.setProperty(MENU_GRAVITY,"1.0");
openSessionTaskFactoryProps.setProperty(TOOLTIP,"Open Session");
registerService(bc,openSessionTaskFactory,OpenSessionTaskFactory.class, openSessionTaskFactoryProps);
registerService(bc,openSessionTaskFactory,TaskFactory.class, openSessionTaskFactoryProps);
// We can't use the "normal" OpenSessionTaskFactory for commands
// because it inserts the task with the file tunable in it, so the
// Command processor never sees it, so we need a special OpenSessionTaskFactory
// for commands
// openSessionTaskFactoryProps.setProperty(COMMAND,"open");
// openSessionTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"session");
// registerService(bc,openSessionTaskFactory,TaskFactory.class, openSessionTaskFactoryProps);
Properties openSessionCommandTaskFactoryProps = new Properties();
openSessionCommandTaskFactoryProps.setProperty(COMMAND,"open");
openSessionCommandTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"session");
registerService(bc,openSessionCommandTaskFactory,TaskFactory.class, openSessionCommandTaskFactoryProps);
Properties saveSessionTaskFactoryProps = new Properties();
saveSessionTaskFactoryProps.setProperty(PREFERRED_MENU,"File");
saveSessionTaskFactoryProps.setProperty(ACCELERATOR,"cmd s");
saveSessionTaskFactoryProps.setProperty(LARGE_ICON_URL,getClass().getResource("/images/icons/stock_save.png").toString());
saveSessionTaskFactoryProps.setProperty(TITLE,"Save");
saveSessionTaskFactoryProps.setProperty(TOOL_BAR_GRAVITY,"1.1");
saveSessionTaskFactoryProps.setProperty(IN_TOOL_BAR,"true");
saveSessionTaskFactoryProps.setProperty(MENU_GRAVITY,"3.0");
saveSessionTaskFactoryProps.setProperty(TOOLTIP,"Save Session");
saveSessionTaskFactoryProps.setProperty(COMMAND,"save");
saveSessionTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"session");
registerService(bc,saveSessionTaskFactory,TaskFactory.class, saveSessionTaskFactoryProps);
Properties saveSessionAsTaskFactoryProps = new Properties();
saveSessionAsTaskFactoryProps.setProperty(PREFERRED_MENU,"File");
saveSessionAsTaskFactoryProps.setProperty(ACCELERATOR,"cmd shift s");
saveSessionAsTaskFactoryProps.setProperty(MENU_GRAVITY,"3.1");
saveSessionAsTaskFactoryProps.setProperty(TITLE,"Save As...");
saveSessionAsTaskFactoryProps.setProperty(COMMAND,"save as");
saveSessionAsTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"session");
registerService(bc,saveSessionAsTaskFactory,TaskFactory.class, saveSessionAsTaskFactoryProps);
registerService(bc,saveSessionAsTaskFactory,SaveSessionAsTaskFactory.class, saveSessionAsTaskFactoryProps);
Properties applyPreferredLayoutTaskFactoryProps = new Properties();
applyPreferredLayoutTaskFactoryProps.setProperty(PREFERRED_MENU,"Layout");
applyPreferredLayoutTaskFactoryProps.setProperty(ACCELERATOR,"fn5");
applyPreferredLayoutTaskFactoryProps.setProperty(LARGE_ICON_URL,getClass().getResource("/images/icons/apply_layout.png").toString());
applyPreferredLayoutTaskFactoryProps.setProperty(ENABLE_FOR,"networkAndView");
applyPreferredLayoutTaskFactoryProps.setProperty(TITLE,"Apply Preferred Layout");
applyPreferredLayoutTaskFactoryProps.setProperty(TOOL_BAR_GRAVITY,"7.0");
applyPreferredLayoutTaskFactoryProps.setProperty(IN_TOOL_BAR,"true");
applyPreferredLayoutTaskFactoryProps.setProperty(MENU_GRAVITY,"5.0");
applyPreferredLayoutTaskFactoryProps.setProperty(TOOLTIP,"Apply Preferred Layout");
registerService(bc,applyPreferredLayoutTaskFactory,NetworkViewCollectionTaskFactory.class, applyPreferredLayoutTaskFactoryProps);
registerService(bc,applyPreferredLayoutTaskFactory,ApplyPreferredLayoutTaskFactory.class, applyPreferredLayoutTaskFactoryProps);
// For commands
Properties applyPreferredLayoutTaskFactoryProps2 = new Properties();
applyPreferredLayoutTaskFactoryProps2.setProperty(COMMAND,"apply preferred");
applyPreferredLayoutTaskFactoryProps2.setProperty(COMMAND_NAMESPACE,"layout");
registerService(bc,applyPreferredLayoutTaskFactory,TaskFactory.class, applyPreferredLayoutTaskFactoryProps2);
Properties deleteColumnTaskFactoryProps = new Properties();
deleteColumnTaskFactoryProps.setProperty(TITLE,"Delete column");
deleteColumnTaskFactoryProps.setProperty(COMMAND,"delete column");
deleteColumnTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"table");
registerService(bc,deleteColumnTaskFactory,TableColumnTaskFactory.class, deleteColumnTaskFactoryProps);
registerService(bc,deleteColumnTaskFactory,DeleteColumnTaskFactory.class, deleteColumnTaskFactoryProps);
Properties renameColumnTaskFactoryProps = new Properties();
renameColumnTaskFactoryProps.setProperty(TITLE,"Rename column");
renameColumnTaskFactoryProps.setProperty(COMMAND,"rename column");
renameColumnTaskFactoryProps.setProperty(COMMAND_NAMESPACE,"table");
registerService(bc,renameColumnTaskFactory,TableColumnTaskFactory.class, renameColumnTaskFactoryProps);
registerService(bc,renameColumnTaskFactory,RenameColumnTaskFactory.class, renameColumnTaskFactoryProps);
Properties copyValueToEntireColumnTaskFactoryProps = new Properties();
copyValueToEntireColumnTaskFactoryProps.setProperty(TITLE,copyValueToEntireColumnTaskFactory.getTaskFactoryName());
copyValueToEntireColumnTaskFactoryProps.setProperty("tableTypes", "node,edge,network,unassigned");
registerService(bc,copyValueToEntireColumnTaskFactory,TableCellTaskFactory.class, copyValueToEntireColumnTaskFactoryProps);
Properties copyValueToSelectedNodesTaskFactoryProps = new Properties();
copyValueToSelectedNodesTaskFactoryProps.setProperty(TITLE,copyValueToSelectedNodesTaskFactory.getTaskFactoryName());
copyValueToSelectedNodesTaskFactoryProps.setProperty("tableTypes", "node");
registerService(bc,copyValueToSelectedNodesTaskFactory,TableCellTaskFactory.class, copyValueToSelectedNodesTaskFactoryProps);
Properties copyValueToSelectedEdgesTaskFactoryProps = new Properties();
copyValueToSelectedEdgesTaskFactoryProps.setProperty(TITLE,copyValueToSelectedEdgesTaskFactory.getTaskFactoryName());
copyValueToSelectedEdgesTaskFactoryProps.setProperty("tableTypes", "edge");
registerService(bc,copyValueToSelectedEdgesTaskFactory,TableCellTaskFactory.class, copyValueToSelectedEdgesTaskFactoryProps);
registerService(bc,deleteTableTaskFactory,TableTaskFactory.class, new Properties());
registerService(bc,deleteTableTaskFactory,DeleteTableTaskFactory.class, new Properties());
// Register as 3 types of service.
Properties connectSelectedNodesTaskFactoryProps = new Properties();
connectSelectedNodesTaskFactoryProps.setProperty(IN_MENU_BAR,"false");
connectSelectedNodesTaskFactoryProps.setProperty(IN_TOOL_BAR,"false");
connectSelectedNodesTaskFactoryProps.setProperty(PREFERRED_ACTION, "NEW");
connectSelectedNodesTaskFactoryProps.setProperty(PREFERRED_MENU, NODE_ADD_MENU);
connectSelectedNodesTaskFactoryProps.setProperty(MENU_GRAVITY, "0.2");
connectSelectedNodesTaskFactoryProps.setProperty(TITLE, "Edges Connecting Selected Nodes");
connectSelectedNodesTaskFactoryProps.setProperty(COMMAND, "connect selected nodes");
connectSelectedNodesTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "network");
// registerService(bc, connectSelectedNodesTaskFactory, NetworkTaskFactory.class,
// connectSelectedNodesTaskFactoryProps);
registerService(bc, connectSelectedNodesTaskFactory, NodeViewTaskFactory.class,
connectSelectedNodesTaskFactoryProps);
registerService(bc, connectSelectedNodesTaskFactory, ConnectSelectedNodesTaskFactory.class,
connectSelectedNodesTaskFactoryProps);
GroupNodesTaskFactoryImpl groupNodesTaskFactory =
new GroupNodesTaskFactoryImpl(cyApplicationManagerServiceRef, cyGroupManager,
cyGroupFactory, undoSupportServiceRef);
Properties groupNodesTaskFactoryProps = new Properties();
groupNodesTaskFactoryProps.setProperty(PREFERRED_MENU,NETWORK_GROUP_MENU);
groupNodesTaskFactoryProps.setProperty(TITLE,"Group Selected Nodes");
groupNodesTaskFactoryProps.setProperty(TOOLTIP,"Group Selected Nodes Together");
groupNodesTaskFactoryProps.setProperty(IN_TOOL_BAR,"false");
groupNodesTaskFactoryProps.setProperty(MENU_GRAVITY,"0.0");
groupNodesTaskFactoryProps.setProperty(IN_MENU_BAR,"false");
groupNodesTaskFactoryProps.setProperty(PREFERRED_ACTION, "NEW");
registerService(bc,groupNodesTaskFactory,NetworkViewTaskFactory.class, groupNodesTaskFactoryProps);
registerService(bc,groupNodesTaskFactory,GroupNodesTaskFactory.class, groupNodesTaskFactoryProps);
// For commands
groupNodesTaskFactoryProps = new Properties();
groupNodesTaskFactoryProps.setProperty(COMMAND, "create");
groupNodesTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "group");
registerService(bc,groupNodesTaskFactory,TaskFactory.class, groupNodesTaskFactoryProps);
// Add Group Selected Nodes to the nodes context also
Properties groupNodeViewTaskFactoryProps = new Properties();
groupNodeViewTaskFactoryProps.setProperty(PREFERRED_MENU,NODE_GROUP_MENU);
groupNodeViewTaskFactoryProps.setProperty(MENU_GRAVITY, "0.0");
groupNodeViewTaskFactoryProps.setProperty(TITLE,"Group Selected Nodes");
groupNodeViewTaskFactoryProps.setProperty(TOOLTIP,"Group Selected Nodes Together");
groupNodeViewTaskFactoryProps.setProperty(IN_TOOL_BAR,"false");
groupNodeViewTaskFactoryProps.setProperty(IN_MENU_BAR,"false");
groupNodeViewTaskFactoryProps.setProperty(PREFERRED_ACTION, "NEW");
registerService(bc,groupNodesTaskFactory,NodeViewTaskFactory.class, groupNodeViewTaskFactoryProps);
UnGroupNodesTaskFactoryImpl unGroupTaskFactory =
new UnGroupNodesTaskFactoryImpl(cyApplicationManagerServiceRef, cyGroupManager,
cyGroupFactory, undoSupportServiceRef);
Properties unGroupNodesTaskFactoryProps = new Properties();
unGroupNodesTaskFactoryProps.setProperty(PREFERRED_MENU,NETWORK_GROUP_MENU);
unGroupNodesTaskFactoryProps.setProperty(TITLE,"Ungroup Selected Nodes");
unGroupNodesTaskFactoryProps.setProperty(TOOLTIP,"Ungroup Selected Nodes");
unGroupNodesTaskFactoryProps.setProperty(IN_TOOL_BAR,"false");
unGroupNodesTaskFactoryProps.setProperty(IN_MENU_BAR,"false");
unGroupNodesTaskFactoryProps.setProperty(MENU_GRAVITY,"1.0");
unGroupNodesTaskFactoryProps.setProperty(PREFERRED_ACTION, "NEW");
registerService(bc,unGroupTaskFactory,NetworkViewTaskFactory.class, unGroupNodesTaskFactoryProps);
registerService(bc,unGroupTaskFactory,UnGroupTaskFactory.class, unGroupNodesTaskFactoryProps);
unGroupNodesTaskFactoryProps = new Properties();
unGroupNodesTaskFactoryProps.setProperty(COMMAND, "ungroup");
groupNodesTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "group");
registerService(bc,unGroupTaskFactory,TaskFactory.class, unGroupNodesTaskFactoryProps);
// Add Ungroup Selected Nodes to the nodes context also
Properties unGroupNodeViewTaskFactoryProps = new Properties();
unGroupNodeViewTaskFactoryProps.setProperty(PREFERRED_MENU,NODE_GROUP_MENU);
unGroupNodeViewTaskFactoryProps.setProperty(MENU_GRAVITY, "1.0");
unGroupNodeViewTaskFactoryProps.setProperty(INSERT_SEPARATOR_AFTER, "true");
unGroupNodeViewTaskFactoryProps.setProperty(TITLE,"Ungroup Selected Nodes");
unGroupNodeViewTaskFactoryProps.setProperty(TOOLTIP,"Ungroup Selected Nodes");
unGroupNodeViewTaskFactoryProps.setProperty(IN_TOOL_BAR,"false");
unGroupNodeViewTaskFactoryProps.setProperty(IN_MENU_BAR,"false");
unGroupNodeViewTaskFactoryProps.setProperty(PREFERRED_ACTION, "NEW");
registerService(bc,unGroupTaskFactory,NodeViewTaskFactory.class, unGroupNodeViewTaskFactoryProps);
registerService(bc,unGroupTaskFactory,UnGroupNodesTaskFactory.class, unGroupNodeViewTaskFactoryProps);
GroupNodeContextTaskFactoryImpl collapseGroupTaskFactory =
new GroupNodeContextTaskFactoryImpl(cyApplicationManagerServiceRef,
cyNetworkViewManagerServiceRef, cyGroupManager, true);
Properties collapseGroupTaskFactoryProps = new Properties();
collapseGroupTaskFactoryProps.setProperty(PREFERRED_MENU,NODE_GROUP_MENU);
collapseGroupTaskFactoryProps.setProperty(TITLE,"Collapse Group(s)");
collapseGroupTaskFactoryProps.setProperty(TOOLTIP,"Collapse Grouped Nodes");
collapseGroupTaskFactoryProps.setProperty(PREFERRED_ACTION, "NEW");
collapseGroupTaskFactoryProps.setProperty(MENU_GRAVITY, "2.0");
registerService(bc,collapseGroupTaskFactory,NodeViewTaskFactory.class, collapseGroupTaskFactoryProps);
registerService(bc,collapseGroupTaskFactory,CollapseGroupTaskFactory.class, collapseGroupTaskFactoryProps);
collapseGroupTaskFactoryProps = new Properties();
collapseGroupTaskFactoryProps.setProperty(COMMAND, "collapse");
collapseGroupTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "group"); // TODO right namespace?
registerService(bc,collapseGroupTaskFactory,TaskFactory.class, collapseGroupTaskFactoryProps);
GroupNodeContextTaskFactoryImpl expandGroupTaskFactory =
new GroupNodeContextTaskFactoryImpl(cyApplicationManagerServiceRef,
cyNetworkViewManagerServiceRef, cyGroupManager, false);
Properties expandGroupTaskFactoryProps = new Properties();
expandGroupTaskFactoryProps.setProperty(PREFERRED_MENU,NODE_GROUP_MENU);
expandGroupTaskFactoryProps.setProperty(TITLE,"Expand Group(s)");
expandGroupTaskFactoryProps.setProperty(TOOLTIP,"Expand Group");
expandGroupTaskFactoryProps.setProperty(PREFERRED_ACTION, "NEW");
expandGroupTaskFactoryProps.setProperty(MENU_GRAVITY, "3.0");
registerService(bc,expandGroupTaskFactory,NodeViewTaskFactory.class, expandGroupTaskFactoryProps);
registerService(bc,expandGroupTaskFactory,ExpandGroupTaskFactory.class, expandGroupTaskFactoryProps);
expandGroupTaskFactoryProps = new Properties();
expandGroupTaskFactoryProps.setProperty(COMMAND, "expand");
expandGroupTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "group"); // TODO right namespace
registerService(bc,expandGroupTaskFactory,TaskFactory.class, expandGroupTaskFactoryProps);
// TODO: add to group...
// TODO: remove from group...
MapTableToNetworkTablesTaskFactoryImpl mapNetworkToTables = new MapTableToNetworkTablesTaskFactoryImpl(cyNetworkManagerServiceRef, tunableSetterServiceRef, rootNetworkManagerServiceRef);
Properties mapNetworkToTablesProps = new Properties();
registerService(bc, mapNetworkToTables, MapTableToNetworkTablesTaskFactory.class, mapNetworkToTablesProps);
ImportDataTableTaskFactoryImpl importTableTaskFactory = new ImportDataTableTaskFactoryImpl(cyNetworkManagerServiceRef,tunableSetterServiceRef,rootNetworkManagerServiceRef);
Properties importTablesProps = new Properties();
registerService(bc, importTableTaskFactory, ImportDataTableTaskFactory.class, importTablesProps);
ExportTableTaskFactoryImpl exportTableTaskFactory = new ExportTableTaskFactoryImpl(cyTableWriterManagerRef,tunableSetterServiceRef);
Properties exportTableTaskFactoryProps = new Properties();
registerService(bc,exportTableTaskFactory,ExportTableTaskFactory.class,exportTableTaskFactoryProps);
// These are task factories that are only available to the command line
// NAMESPACE: edge
CreateNetworkAttributeTaskFactory createEdgeAttributeTaskFactory =
new CreateNetworkAttributeTaskFactory(cyApplicationManagerServiceRef,
cyTableManagerServiceRef, CyEdge.class);
Properties createEdgeAttributeTaskFactoryProps = new Properties();
createEdgeAttributeTaskFactoryProps.setProperty(COMMAND, "create attribute");
createEdgeAttributeTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "edge");
registerService(bc,createEdgeAttributeTaskFactory,TaskFactory.class,createEdgeAttributeTaskFactoryProps);
GetEdgeTaskFactory getEdgeTaskFactory = new GetEdgeTaskFactory(cyApplicationManagerServiceRef);
Properties getEdgeTaskFactoryProps = new Properties();
getEdgeTaskFactoryProps.setProperty(COMMAND, "get");
getEdgeTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "edge");
registerService(bc,getEdgeTaskFactory,TaskFactory.class,getEdgeTaskFactoryProps);
GetNetworkAttributeTaskFactory getEdgeAttributeTaskFactory =
new GetNetworkAttributeTaskFactory(cyApplicationManagerServiceRef, cyTableManagerServiceRef, CyEdge.class);
Properties getEdgeAttributeTaskFactoryProps = new Properties();
getEdgeAttributeTaskFactoryProps.setProperty(COMMAND, "get attribute");
getEdgeAttributeTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "edge");
registerService(bc,getEdgeAttributeTaskFactory,TaskFactory.class,getEdgeAttributeTaskFactoryProps);
GetPropertiesTaskFactory getEdgePropertiesTaskFactory =
new GetPropertiesTaskFactory(cyApplicationManagerServiceRef, CyEdge.class,
cyNetworkViewManagerServiceRef, renderingEngineManagerServiceRef);
Properties getEdgePropertiesTaskFactoryProps = new Properties();
getEdgePropertiesTaskFactoryProps.setProperty(COMMAND, "get properties");
getEdgePropertiesTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "edge");
registerService(bc,getEdgePropertiesTaskFactory,TaskFactory.class,getEdgePropertiesTaskFactoryProps);
ListEdgesTaskFactory listEdges = new ListEdgesTaskFactory(cyApplicationManagerServiceRef);
Properties listEdgesTaskFactoryProps = new Properties();
listEdgesTaskFactoryProps.setProperty(COMMAND, "list");
listEdgesTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "edge");
registerService(bc,listEdges,TaskFactory.class,listEdgesTaskFactoryProps);
ListNetworkAttributesTaskFactory listEdgeAttributesTaskFactory =
new ListNetworkAttributesTaskFactory(cyApplicationManagerServiceRef,
cyTableManagerServiceRef, CyEdge.class);
Properties listEdgeAttributesTaskFactoryProps = new Properties();
listEdgeAttributesTaskFactoryProps.setProperty(COMMAND, "list attributes");
listEdgeAttributesTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "edge");
registerService(bc,listEdgeAttributesTaskFactory,TaskFactory.class,listEdgeAttributesTaskFactoryProps);
ListPropertiesTaskFactory listEdgeProperties =
new ListPropertiesTaskFactory(cyApplicationManagerServiceRef,
CyEdge.class, cyNetworkViewManagerServiceRef,
renderingEngineManagerServiceRef);
Properties listEdgePropertiesTaskFactoryProps = new Properties();
listEdgePropertiesTaskFactoryProps.setProperty(COMMAND, "list properties");
listEdgePropertiesTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "edge");
registerService(bc,listEdgeProperties,TaskFactory.class,listEdgePropertiesTaskFactoryProps);
RenameEdgeTaskFactory renameEdge = new RenameEdgeTaskFactory();
Properties renameEdgeTaskFactoryProps = new Properties();
renameEdgeTaskFactoryProps.setProperty(COMMAND, "rename");
renameEdgeTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "edge");
registerService(bc,renameEdge,TaskFactory.class,renameEdgeTaskFactoryProps);
SetNetworkAttributeTaskFactory setEdgeAttributeTaskFactory =
new SetNetworkAttributeTaskFactory(cyApplicationManagerServiceRef, cyTableManagerServiceRef, CyEdge.class);
Properties setEdgeAttributeTaskFactoryProps = new Properties();
setEdgeAttributeTaskFactoryProps.setProperty(COMMAND, "set attribute");
setEdgeAttributeTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "edge");
registerService(bc,setEdgeAttributeTaskFactory,TaskFactory.class,setEdgeAttributeTaskFactoryProps);
SetPropertiesTaskFactory setEdgePropertiesTaskFactory =
new SetPropertiesTaskFactory(cyApplicationManagerServiceRef, CyEdge.class,
cyNetworkViewManagerServiceRef, renderingEngineManagerServiceRef);
Properties setEdgePropertiesTaskFactoryProps = new Properties();
setEdgePropertiesTaskFactoryProps.setProperty(COMMAND, "set properties");
setEdgePropertiesTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "edge");
registerService(bc,setEdgePropertiesTaskFactory,TaskFactory.class,setEdgePropertiesTaskFactoryProps);
// NAMESPACE: group
AddToGroupTaskFactory addToGroupTaskFactory =
new AddToGroupTaskFactory(cyApplicationManagerServiceRef, cyGroupManager);
Properties addToGroupTFProps = new Properties();
addToGroupTFProps.setProperty(COMMAND, "add");
addToGroupTFProps.setProperty(COMMAND_NAMESPACE, "group");
registerService(bc,addToGroupTaskFactory,TaskFactory.class,addToGroupTFProps);
ListGroupsTaskFactory listGroupsTaskFactory =
new ListGroupsTaskFactory(cyApplicationManagerServiceRef, cyGroupManager);
Properties listGroupsTFProps = new Properties();
listGroupsTFProps.setProperty(COMMAND, "list");
listGroupsTFProps.setProperty(COMMAND_NAMESPACE, "group");
registerService(bc,listGroupsTaskFactory,TaskFactory.class,listGroupsTFProps);
RemoveFromGroupTaskFactory removeFromGroupTaskFactory =
new RemoveFromGroupTaskFactory(cyApplicationManagerServiceRef, cyGroupManager);
Properties removeFromGroupTFProps = new Properties();
removeFromGroupTFProps.setProperty(COMMAND, "remove");
removeFromGroupTFProps.setProperty(COMMAND_NAMESPACE, "group");
registerService(bc,removeFromGroupTaskFactory,TaskFactory.class,removeFromGroupTFProps);
RenameGroupTaskFactory renameGroupTaskFactory =
new RenameGroupTaskFactory(cyApplicationManagerServiceRef, cyGroupManager);
Properties renameGroupTFProps = new Properties();
renameGroupTFProps.setProperty(COMMAND, "rename");
renameGroupTFProps.setProperty(COMMAND_NAMESPACE, "group");
registerService(bc,renameGroupTaskFactory,TaskFactory.class,renameGroupTFProps);
// NAMESPACE: layout
GetPreferredLayoutTaskFactory getPreferredLayoutTaskFactory =
new GetPreferredLayoutTaskFactory(cyLayoutsServiceRef,cyPropertyServiceRef);
Properties getPreferredTFProps = new Properties();
getPreferredTFProps.setProperty(COMMAND, "get preferred");
getPreferredTFProps.setProperty(COMMAND_NAMESPACE, "layout");
registerService(bc,getPreferredLayoutTaskFactory,TaskFactory.class,getPreferredTFProps);
SetPreferredLayoutTaskFactory setPreferredLayoutTaskFactory =
new SetPreferredLayoutTaskFactory(cyLayoutsServiceRef,cyPropertyServiceRef);
Properties setPreferredTFProps = new Properties();
setPreferredTFProps.setProperty(COMMAND, "set preferred");
setPreferredTFProps.setProperty(COMMAND_NAMESPACE, "layout");
registerService(bc,setPreferredLayoutTaskFactory,TaskFactory.class,setPreferredTFProps);
// NAMESPACE: network
AddTaskFactory addTaskFactory = new AddTaskFactory();
Properties addTaskFactoryProps = new Properties();
addTaskFactoryProps.setProperty(COMMAND, "add");
addTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "network");
registerService(bc,addTaskFactory,TaskFactory.class,addTaskFactoryProps);
AddEdgeTaskFactory addEdgeTaskFactory = new AddEdgeTaskFactory();
Properties addEdgeTaskFactoryProps = new Properties();
addEdgeTaskFactoryProps.setProperty(COMMAND, "add edge");
addEdgeTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "network");
registerService(bc,addEdgeTaskFactory,TaskFactory.class,addEdgeTaskFactoryProps);
AddNodeTaskFactory addNodeTaskFactory = new AddNodeTaskFactory();
Properties addNodeTaskFactoryProps = new Properties();
addNodeTaskFactoryProps.setProperty(COMMAND, "add node");
addNodeTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "network");
registerService(bc,addNodeTaskFactory,TaskFactory.class,addNodeTaskFactoryProps);
CreateNetworkAttributeTaskFactory createNetworkAttributeTaskFactory =
new CreateNetworkAttributeTaskFactory(cyApplicationManagerServiceRef,
cyTableManagerServiceRef, CyNetwork.class);
Properties createNetworkAttributeTaskFactoryProps = new Properties();
createNetworkAttributeTaskFactoryProps.setProperty(COMMAND, "create attribute");
createNetworkAttributeTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "network");
registerService(bc,createNetworkAttributeTaskFactory,TaskFactory.class,createNetworkAttributeTaskFactoryProps);
DeselectTaskFactory deselectTaskFactory = new DeselectTaskFactory(cyNetworkViewManagerServiceRef, cyEventHelperRef);
Properties deselectTaskFactoryProps = new Properties();
deselectTaskFactoryProps.setProperty(COMMAND, "deselect");
deselectTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "network");
registerService(bc,deselectTaskFactory,TaskFactory.class,deselectTaskFactoryProps);
GetNetworkTaskFactory getNetwork = new GetNetworkTaskFactory(cyApplicationManagerServiceRef);
Properties getNetworkTaskFactoryProps = new Properties();
getNetworkTaskFactoryProps.setProperty(COMMAND, "get");
getNetworkTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "network");
registerService(bc,getNetwork,TaskFactory.class,getNetworkTaskFactoryProps);
GetNetworkAttributeTaskFactory getNetworkAttributeTaskFactory =
new GetNetworkAttributeTaskFactory(cyApplicationManagerServiceRef, cyTableManagerServiceRef, CyNetwork.class);
Properties getNetworkAttributeTaskFactoryProps = new Properties();
getNetworkAttributeTaskFactoryProps.setProperty(COMMAND, "get attribute");
getNetworkAttributeTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "network");
registerService(bc,getNetworkAttributeTaskFactory,TaskFactory.class,getNetworkAttributeTaskFactoryProps);
GetPropertiesTaskFactory getNetworkPropertiesTaskFactory =
new GetPropertiesTaskFactory(cyApplicationManagerServiceRef, CyNetwork.class,
cyNetworkViewManagerServiceRef, renderingEngineManagerServiceRef);
Properties getNetworkPropertiesTaskFactoryProps = new Properties();
getNetworkPropertiesTaskFactoryProps.setProperty(COMMAND, "get properties");
getNetworkPropertiesTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "network");
registerService(bc,getNetworkPropertiesTaskFactory,TaskFactory.class,getNetworkPropertiesTaskFactoryProps);
HideTaskFactory hideTaskFactory = new HideTaskFactory(cyApplicationManagerServiceRef, cyNetworkViewManagerServiceRef,
visualMappingManagerServiceRef);
Properties hideTaskFactoryProps = new Properties();
hideTaskFactoryProps.setProperty(COMMAND, "hide");
hideTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "network");
registerService(bc,hideTaskFactory,TaskFactory.class,hideTaskFactoryProps);
ListNetworksTaskFactory listNetworks = new ListNetworksTaskFactory(cyNetworkManagerServiceRef);
Properties listNetworksTaskFactoryProps = new Properties();
listNetworksTaskFactoryProps.setProperty(COMMAND, "list");
listNetworksTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "network");
registerService(bc,listNetworks,TaskFactory.class,listNetworksTaskFactoryProps);
ListNetworkAttributesTaskFactory listNetworkAttributesTaskFactory =
new ListNetworkAttributesTaskFactory(cyApplicationManagerServiceRef,
cyTableManagerServiceRef, CyNetwork.class);
Properties listNetworkAttributesTaskFactoryProps = new Properties();
listNetworkAttributesTaskFactoryProps.setProperty(COMMAND, "list attributes");
listNetworkAttributesTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "network");
registerService(bc,listNetworkAttributesTaskFactory,TaskFactory.class,listNetworkAttributesTaskFactoryProps);
ListPropertiesTaskFactory listNetworkProperties =
new ListPropertiesTaskFactory(cyApplicationManagerServiceRef,
CyNetwork.class, cyNetworkViewManagerServiceRef,
renderingEngineManagerServiceRef);
Properties listNetworkPropertiesTaskFactoryProps = new Properties();
listNetworkPropertiesTaskFactoryProps.setProperty(COMMAND, "list properties");
listNetworkPropertiesTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "network");
registerService(bc,listNetworkProperties,TaskFactory.class,listNetworkPropertiesTaskFactoryProps);
SelectTaskFactory selectTaskFactory = new SelectTaskFactory(cyApplicationManagerServiceRef,
cyNetworkViewManagerServiceRef, cyEventHelperRef); Properties selectTaskFactoryProps = new Properties();
selectTaskFactoryProps.setProperty(COMMAND, "select");
selectTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "network");
registerService(bc,selectTaskFactory,TaskFactory.class,selectTaskFactoryProps);
SetNetworkAttributeTaskFactory setNetworkAttributeTaskFactory =
new SetNetworkAttributeTaskFactory(cyApplicationManagerServiceRef, cyTableManagerServiceRef, CyNetwork.class);
Properties setNetworkAttributeTaskFactoryProps = new Properties();
setNetworkAttributeTaskFactoryProps.setProperty(COMMAND, "set attribute");
setNetworkAttributeTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "network");
registerService(bc,setNetworkAttributeTaskFactory,TaskFactory.class,setNetworkAttributeTaskFactoryProps);
SetCurrentNetworkTaskFactory setCurrentNetwork = new SetCurrentNetworkTaskFactory(cyApplicationManagerServiceRef);
Properties setCurrentNetworkTaskFactoryProps = new Properties();
setCurrentNetworkTaskFactoryProps.setProperty(COMMAND, "set current");
setCurrentNetworkTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "network");
registerService(bc,setCurrentNetwork,TaskFactory.class,setCurrentNetworkTaskFactoryProps);
SetPropertiesTaskFactory setNetworkPropertiesTaskFactory =
new SetPropertiesTaskFactory(cyApplicationManagerServiceRef, CyNetwork.class,
cyNetworkViewManagerServiceRef, renderingEngineManagerServiceRef);
Properties setNetworkPropertiesTaskFactoryProps = new Properties();
setNetworkPropertiesTaskFactoryProps.setProperty(COMMAND, "set properties");
setNetworkPropertiesTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "network");
registerService(bc,setNetworkPropertiesTaskFactory,TaskFactory.class,setNetworkPropertiesTaskFactoryProps);
UnHideTaskFactory unHideTaskFactory = new UnHideTaskFactory(cyApplicationManagerServiceRef, cyNetworkViewManagerServiceRef,
visualMappingManagerServiceRef);
Properties unHideTaskFactoryProps = new Properties();
unHideTaskFactoryProps.setProperty(COMMAND, "show");
unHideTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "network");
registerService(bc,unHideTaskFactory,TaskFactory.class,unHideTaskFactoryProps);
// NAMESPACE: node
CreateNetworkAttributeTaskFactory createNodeAttributeTaskFactory =
new CreateNetworkAttributeTaskFactory(cyApplicationManagerServiceRef,
cyTableManagerServiceRef, CyNode.class);
Properties createNodeAttributeTaskFactoryProps = new Properties();
createNodeAttributeTaskFactoryProps.setProperty(COMMAND, "create attribute");
createNodeAttributeTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "node");
registerService(bc,createNodeAttributeTaskFactory,TaskFactory.class,createNodeAttributeTaskFactoryProps);
GetNodeTaskFactory getNodeTaskFactory = new GetNodeTaskFactory(cyApplicationManagerServiceRef);
Properties getNodeTaskFactoryProps = new Properties();
getNodeTaskFactoryProps.setProperty(COMMAND, "get");
getNodeTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "node");
registerService(bc,getNodeTaskFactory,TaskFactory.class,getNodeTaskFactoryProps);
GetNetworkAttributeTaskFactory getNodeAttributeTaskFactory =
new GetNetworkAttributeTaskFactory(cyApplicationManagerServiceRef, cyTableManagerServiceRef, CyNode.class);
Properties getNodeAttributeTaskFactoryProps = new Properties();
getNodeAttributeTaskFactoryProps.setProperty(COMMAND, "get attribute");
getNodeAttributeTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "node");
registerService(bc,getNodeAttributeTaskFactory,TaskFactory.class,getNodeAttributeTaskFactoryProps);
GetPropertiesTaskFactory getNodePropertiesTaskFactory =
new GetPropertiesTaskFactory(cyApplicationManagerServiceRef, CyNode.class,
cyNetworkViewManagerServiceRef, renderingEngineManagerServiceRef);
Properties getNodePropertiesTaskFactoryProps = new Properties();
getNodePropertiesTaskFactoryProps.setProperty(COMMAND, "get properties");
getNodePropertiesTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "node");
registerService(bc,getNodePropertiesTaskFactory,TaskFactory.class,getNodePropertiesTaskFactoryProps);
ListNodesTaskFactory listNodes = new ListNodesTaskFactory(cyApplicationManagerServiceRef);
Properties listNodesTaskFactoryProps = new Properties();
listNodesTaskFactoryProps.setProperty(COMMAND, "list");
listNodesTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "node");
registerService(bc,listNodes,TaskFactory.class,listNodesTaskFactoryProps);
ListNetworkAttributesTaskFactory listNodeAttributesTaskFactory =
new ListNetworkAttributesTaskFactory(cyApplicationManagerServiceRef,
cyTableManagerServiceRef, CyNode.class);
Properties listNodeAttributesTaskFactoryProps = new Properties();
listNodeAttributesTaskFactoryProps.setProperty(COMMAND, "list attributes");
listNodeAttributesTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "node");
registerService(bc,listNodeAttributesTaskFactory,TaskFactory.class,listNodeAttributesTaskFactoryProps);
ListPropertiesTaskFactory listNodeProperties =
new ListPropertiesTaskFactory(cyApplicationManagerServiceRef,
CyNode.class, cyNetworkViewManagerServiceRef,
renderingEngineManagerServiceRef);
Properties listNodePropertiesTaskFactoryProps = new Properties();
listNodePropertiesTaskFactoryProps.setProperty(COMMAND, "list properties");
listNodePropertiesTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "node");
registerService(bc,listNodeProperties,TaskFactory.class,listNodePropertiesTaskFactoryProps);
RenameNodeTaskFactory renameNode = new RenameNodeTaskFactory();
Properties renameNodeTaskFactoryProps = new Properties();
renameNodeTaskFactoryProps.setProperty(COMMAND, "rename");
renameNodeTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "node");
registerService(bc,renameNode,TaskFactory.class,renameNodeTaskFactoryProps);
SetNetworkAttributeTaskFactory setNodeAttributeTaskFactory =
new SetNetworkAttributeTaskFactory(cyApplicationManagerServiceRef, cyTableManagerServiceRef, CyNode.class);
Properties setNodeAttributeTaskFactoryProps = new Properties();
setNodeAttributeTaskFactoryProps.setProperty(COMMAND, "set attribute");
setNodeAttributeTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "node");
registerService(bc,setNodeAttributeTaskFactory,TaskFactory.class,setNodeAttributeTaskFactoryProps);
SetPropertiesTaskFactory setNodePropertiesTaskFactory =
new SetPropertiesTaskFactory(cyApplicationManagerServiceRef, CyNode.class,
cyNetworkViewManagerServiceRef, renderingEngineManagerServiceRef);
Properties setNodePropertiesTaskFactoryProps = new Properties();
setNodePropertiesTaskFactoryProps.setProperty(COMMAND, "set properties");
setNodePropertiesTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "node");
registerService(bc,setNodePropertiesTaskFactory,TaskFactory.class,setNodePropertiesTaskFactoryProps);
// NAMESPACE: table
AddRowTaskFactory addRowTaskFactory =
new AddRowTaskFactory(cyApplicationManagerServiceRef, cyTableManagerServiceRef);
Properties addRowTaskFactoryProps = new Properties();
addRowTaskFactoryProps.setProperty(COMMAND, "add row");
addRowTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "table");
registerService(bc,addRowTaskFactory,TaskFactory.class,addRowTaskFactoryProps);
CreateColumnTaskFactory createColumnTaskFactory =
new CreateColumnTaskFactory(cyApplicationManagerServiceRef, cyTableManagerServiceRef);
Properties createColumnTaskFactoryProps = new Properties();
createColumnTaskFactoryProps.setProperty(COMMAND, "create column");
createColumnTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "table");
registerService(bc,createColumnTaskFactory,TaskFactory.class,createColumnTaskFactoryProps);
CreateTableTaskFactory createTableTaskFactory =
new CreateTableTaskFactory(cyApplicationManagerServiceRef,
cyTableFactoryServiceRef, cyTableManagerServiceRef);
Properties createTableTaskFactoryProps = new Properties();
createTableTaskFactoryProps.setProperty(COMMAND, "create table");
createTableTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "table");
registerService(bc,createTableTaskFactory,TaskFactory.class,createTableTaskFactoryProps);
DeleteColumnCommandTaskFactory deleteColumnCommandTaskFactory =
new DeleteColumnCommandTaskFactory(cyApplicationManagerServiceRef, cyTableManagerServiceRef);
Properties deleteColumnCommandTaskFactoryProps = new Properties();
deleteColumnCommandTaskFactoryProps.setProperty(COMMAND, "delete column");
deleteColumnCommandTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "table");
registerService(bc,deleteColumnCommandTaskFactory,TaskFactory.class,deleteColumnCommandTaskFactoryProps);
DeleteRowTaskFactory deleteRowTaskFactory =
new DeleteRowTaskFactory(cyApplicationManagerServiceRef, cyTableManagerServiceRef);
Properties deleteRowTaskFactoryProps = new Properties();
deleteRowTaskFactoryProps.setProperty(COMMAND, "delete row");
deleteRowTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "table");
registerService(bc,deleteRowTaskFactory,TaskFactory.class,deleteRowTaskFactoryProps);
DestroyTableTaskFactory destroyTableTaskFactory =
new DestroyTableTaskFactory(cyApplicationManagerServiceRef, cyTableManagerServiceRef);
Properties destroyTableTaskFactoryProps = new Properties();
destroyTableTaskFactoryProps.setProperty(COMMAND, "destroy");
destroyTableTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "table");
registerService(bc,destroyTableTaskFactory,TaskFactory.class,destroyTableTaskFactoryProps);
GetColumnTaskFactory getColumnTaskFactory =
new GetColumnTaskFactory(cyApplicationManagerServiceRef, cyTableManagerServiceRef);
Properties getColumnTaskFactoryProps = new Properties();
getColumnTaskFactoryProps.setProperty(COMMAND, "get column");
getColumnTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "table");
registerService(bc,getColumnTaskFactory,TaskFactory.class,getColumnTaskFactoryProps);
GetRowTaskFactory getRowTaskFactory =
new GetRowTaskFactory(cyApplicationManagerServiceRef, cyTableManagerServiceRef);
Properties getRowTaskFactoryProps = new Properties();
getRowTaskFactoryProps.setProperty(COMMAND, "get row");
getRowTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "table");
registerService(bc,getRowTaskFactory,TaskFactory.class,getRowTaskFactoryProps);
GetValueTaskFactory getValueTaskFactory =
new GetValueTaskFactory(cyApplicationManagerServiceRef, cyTableManagerServiceRef);
Properties getValueTaskFactoryProps = new Properties();
getValueTaskFactoryProps.setProperty(COMMAND, "get value");
getValueTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "table");
registerService(bc,getValueTaskFactory,TaskFactory.class,getValueTaskFactoryProps);
ListColumnsTaskFactory listColumnsTaskFactory =
new ListColumnsTaskFactory(cyApplicationManagerServiceRef, cyTableManagerServiceRef,
cyNetworkTableManagerServiceRef);
Properties listColumnsTaskFactoryProps = new Properties();
listColumnsTaskFactoryProps.setProperty(COMMAND, "list columns");
listColumnsTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "table");
registerService(bc,listColumnsTaskFactory,TaskFactory.class,listColumnsTaskFactoryProps);
ListRowsTaskFactory listRowsTaskFactory =
new ListRowsTaskFactory(cyApplicationManagerServiceRef, cyTableManagerServiceRef);
Properties listRowsTaskFactoryProps = new Properties();
listRowsTaskFactoryProps.setProperty(COMMAND, "list rows");
listRowsTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "table");
registerService(bc,listRowsTaskFactory,TaskFactory.class,listRowsTaskFactoryProps);
ListTablesTaskFactory listTablesTaskFactory =
new ListTablesTaskFactory(cyApplicationManagerServiceRef, cyTableManagerServiceRef,
cyNetworkTableManagerServiceRef);
Properties listTablesTaskFactoryProps = new Properties();
listTablesTaskFactoryProps.setProperty(COMMAND, "list");
listTablesTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "table");
registerService(bc,listTablesTaskFactory,TaskFactory.class,listTablesTaskFactoryProps);
SetTableTitleTaskFactory setTableTitleTaskFactory =
new SetTableTitleTaskFactory(cyApplicationManagerServiceRef, cyTableManagerServiceRef);
Properties setTableTitleTaskFactoryProps = new Properties();
setTableTitleTaskFactoryProps.setProperty(COMMAND, "set title");
setTableTitleTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "table");
registerService(bc,setTableTitleTaskFactory,TaskFactory.class,setTableTitleTaskFactoryProps);
SetValuesTaskFactory setValuesTaskFactory =
new SetValuesTaskFactory(cyApplicationManagerServiceRef, cyTableManagerServiceRef);
Properties setValuesTaskFactoryProps = new Properties();
setValuesTaskFactoryProps.setProperty(COMMAND, "set values");
setValuesTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "table");
registerService(bc,setValuesTaskFactory,TaskFactory.class,setValuesTaskFactoryProps);
// NAMESPACE: view
GetCurrentNetworkViewTaskFactory getCurrentView =
new GetCurrentNetworkViewTaskFactory(cyApplicationManagerServiceRef);
Properties getCurrentViewTaskFactoryProps = new Properties();
getCurrentViewTaskFactoryProps.setProperty(COMMAND, "get current");
getCurrentViewTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "view");
registerService(bc,getCurrentView,TaskFactory.class,getCurrentViewTaskFactoryProps);
ListNetworkViewsTaskFactory listNetworkViews =
new ListNetworkViewsTaskFactory(cyApplicationManagerServiceRef, cyNetworkViewManagerServiceRef);
Properties listNetworkViewsTaskFactoryProps = new Properties();
listNetworkViewsTaskFactoryProps.setProperty(COMMAND, "list");
listNetworkViewsTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "view");
registerService(bc,listNetworkViews,TaskFactory.class,listNetworkViewsTaskFactoryProps);
SetCurrentNetworkViewTaskFactory setCurrentView =
new SetCurrentNetworkViewTaskFactory(cyApplicationManagerServiceRef,
cyNetworkViewManagerServiceRef);
Properties setCurrentViewTaskFactoryProps = new Properties();
setCurrentViewTaskFactoryProps.setProperty(COMMAND, "set current");
setCurrentViewTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "view");
registerService(bc,setCurrentView,TaskFactory.class,setCurrentViewTaskFactoryProps);
UpdateNetworkViewTaskFactory updateView =
new UpdateNetworkViewTaskFactory(cyApplicationManagerServiceRef, cyNetworkViewManagerServiceRef);
Properties updateViewTaskFactoryProps = new Properties();
updateViewTaskFactoryProps.setProperty(COMMAND, "update");
updateViewTaskFactoryProps.setProperty(COMMAND_NAMESPACE, "view");
registerService(bc,updateView,TaskFactory.class,updateViewTaskFactoryProps);
}
|
diff --git a/src/main/java/org/glom/web/client/ui/details/DetailsCell.java b/src/main/java/org/glom/web/client/ui/details/DetailsCell.java
index 1ace038..1411e7b 100644
--- a/src/main/java/org/glom/web/client/ui/details/DetailsCell.java
+++ b/src/main/java/org/glom/web/client/ui/details/DetailsCell.java
@@ -1,150 +1,151 @@
/*
* Copyright (C) 2011 Openismus GmbH
*
* This file is part of GWT-Glom.
*
* GWT-Glom 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 3 of the License, or (at your
* option) any later version.
*
* GWT-Glom 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 GWT-Glom. If not, see <http://www.gnu.org/licenses/>.
*/
package org.glom.web.client.ui.details;
import org.glom.web.client.Utils;
import org.glom.web.shared.DataItem;
import org.glom.web.shared.GlomNumericFormat;
import org.glom.web.shared.layout.Formatting;
import org.glom.web.shared.layout.LayoutItemField;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.Label;
/**
* Holds a label, data and a navigation button.
*
* @author Ben Konrath <[email protected]>
*
*/
public class DetailsCell extends Composite {
private LayoutItemField layoutItemField;
private Label detailsData = new Label();
private DataItem dataItem;
Button openButton = null;
public DetailsCell(LayoutItemField layoutItemField) {
// Labels (text in div element) are being used so that the height of the details-data element can be set for
// the multiline height of LayoutItemFeilds. This allows the the data element to display the correct height
// if style is applied that shows the height. This has the added benefit of allowing the order of the label and
// data elements to be changed for right-to-left languages.
Label detailsLabel = new Label(layoutItemField.getTitle() + ":");
detailsLabel.setStyleName("details-label");
detailsData.setStyleName("details-data");
Formatting formatting = layoutItemField.getFormatting();
// set the height based on the number of lines
detailsData.setHeight(formatting.getTextFormatMultilineHeightLines() + "em");
// set the alignment
switch (formatting.getHorizontalAlignment()) {
case HORIZONTAL_ALIGNMENT_LEFT:
detailsData.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
break;
case HORIZONTAL_ALIGNMENT_RIGHT:
detailsData.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT);
break;
case HORIZONTAL_ALIGNMENT_AUTO:
default:
detailsData.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_DEFAULT);
break;
}
// set the text foreground and background colours
String foregroundColour = formatting.getTextFormatColourForeground();
if (foregroundColour != null && !foregroundColour.isEmpty())
detailsData.getElement().getStyle().setColor(foregroundColour);
String backgroundColour = formatting.getTextFormatColourBackground();
if (backgroundColour != null && !backgroundColour.isEmpty())
detailsData.getElement().getStyle().setBackgroundColor(backgroundColour);
FlowPanel mainPanel = new FlowPanel();
mainPanel.setStyleName("details-cell");
mainPanel.add(detailsLabel);
mainPanel.add(detailsData);
if (layoutItemField.getAddNavigation()) {
openButton = new Button("Open");
+ openButton.setStyleName("details-navigation");
openButton.setEnabled(false);
mainPanel.add(openButton);
}
this.layoutItemField = layoutItemField;
initWidget(mainPanel);
}
public DataItem getData() {
return dataItem;
}
public void setData(DataItem dataItem) {
// FIXME use the cell renderers from the list view to render the inforamtion here
switch (layoutItemField.getType()) {
case TYPE_BOOLEAN:
detailsData.setText(dataItem.getBoolean() ? "TRUE" : "FALSE");
break;
case TYPE_NUMERIC:
GlomNumericFormat glomNumericFormat = layoutItemField.getFormatting().getGlomNumericFormat();
NumberFormat gwtNumberFormat = Utils.getNumberFormat(glomNumericFormat);
// set the foreground colour to red if the number is negative and this is requested
if (glomNumericFormat.getUseAltForegroundColourForNegatives() && dataItem.getNumber() < 0) {
// The default alternative colour in libglom is red.
detailsData.getElement().getStyle().setColor("Red");
}
detailsData.setText(gwtNumberFormat.format(dataItem.getNumber()));
break;
case TYPE_TEXT:
detailsData.setText(dataItem.getText());
default:
break;
}
this.dataItem = dataItem;
}
public LayoutItemField getLayoutItemField() {
return layoutItemField;
}
public HandlerRegistration setOpenButtonClickHandler(ClickHandler clickHandler) {
HandlerRegistration handlerRegistration = null;
if (openButton != null) {
handlerRegistration = openButton.addClickHandler(clickHandler);
openButton.setEnabled(true);
}
return handlerRegistration;
}
}
| true | true | public DetailsCell(LayoutItemField layoutItemField) {
// Labels (text in div element) are being used so that the height of the details-data element can be set for
// the multiline height of LayoutItemFeilds. This allows the the data element to display the correct height
// if style is applied that shows the height. This has the added benefit of allowing the order of the label and
// data elements to be changed for right-to-left languages.
Label detailsLabel = new Label(layoutItemField.getTitle() + ":");
detailsLabel.setStyleName("details-label");
detailsData.setStyleName("details-data");
Formatting formatting = layoutItemField.getFormatting();
// set the height based on the number of lines
detailsData.setHeight(formatting.getTextFormatMultilineHeightLines() + "em");
// set the alignment
switch (formatting.getHorizontalAlignment()) {
case HORIZONTAL_ALIGNMENT_LEFT:
detailsData.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
break;
case HORIZONTAL_ALIGNMENT_RIGHT:
detailsData.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT);
break;
case HORIZONTAL_ALIGNMENT_AUTO:
default:
detailsData.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_DEFAULT);
break;
}
// set the text foreground and background colours
String foregroundColour = formatting.getTextFormatColourForeground();
if (foregroundColour != null && !foregroundColour.isEmpty())
detailsData.getElement().getStyle().setColor(foregroundColour);
String backgroundColour = formatting.getTextFormatColourBackground();
if (backgroundColour != null && !backgroundColour.isEmpty())
detailsData.getElement().getStyle().setBackgroundColor(backgroundColour);
FlowPanel mainPanel = new FlowPanel();
mainPanel.setStyleName("details-cell");
mainPanel.add(detailsLabel);
mainPanel.add(detailsData);
if (layoutItemField.getAddNavigation()) {
openButton = new Button("Open");
openButton.setEnabled(false);
mainPanel.add(openButton);
}
this.layoutItemField = layoutItemField;
initWidget(mainPanel);
}
| public DetailsCell(LayoutItemField layoutItemField) {
// Labels (text in div element) are being used so that the height of the details-data element can be set for
// the multiline height of LayoutItemFeilds. This allows the the data element to display the correct height
// if style is applied that shows the height. This has the added benefit of allowing the order of the label and
// data elements to be changed for right-to-left languages.
Label detailsLabel = new Label(layoutItemField.getTitle() + ":");
detailsLabel.setStyleName("details-label");
detailsData.setStyleName("details-data");
Formatting formatting = layoutItemField.getFormatting();
// set the height based on the number of lines
detailsData.setHeight(formatting.getTextFormatMultilineHeightLines() + "em");
// set the alignment
switch (formatting.getHorizontalAlignment()) {
case HORIZONTAL_ALIGNMENT_LEFT:
detailsData.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
break;
case HORIZONTAL_ALIGNMENT_RIGHT:
detailsData.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT);
break;
case HORIZONTAL_ALIGNMENT_AUTO:
default:
detailsData.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_DEFAULT);
break;
}
// set the text foreground and background colours
String foregroundColour = formatting.getTextFormatColourForeground();
if (foregroundColour != null && !foregroundColour.isEmpty())
detailsData.getElement().getStyle().setColor(foregroundColour);
String backgroundColour = formatting.getTextFormatColourBackground();
if (backgroundColour != null && !backgroundColour.isEmpty())
detailsData.getElement().getStyle().setBackgroundColor(backgroundColour);
FlowPanel mainPanel = new FlowPanel();
mainPanel.setStyleName("details-cell");
mainPanel.add(detailsLabel);
mainPanel.add(detailsData);
if (layoutItemField.getAddNavigation()) {
openButton = new Button("Open");
openButton.setStyleName("details-navigation");
openButton.setEnabled(false);
mainPanel.add(openButton);
}
this.layoutItemField = layoutItemField;
initWidget(mainPanel);
}
|
diff --git a/sikuli-ide/src/main/java/edu/mit/csail/uid/TargetOffsetPane.java b/sikuli-ide/src/main/java/edu/mit/csail/uid/TargetOffsetPane.java
index f98dd027..8ec19fb9 100644
--- a/sikuli-ide/src/main/java/edu/mit/csail/uid/TargetOffsetPane.java
+++ b/sikuli-ide/src/main/java/edu/mit/csail/uid/TargetOffsetPane.java
@@ -1,264 +1,264 @@
package edu.mit.csail.uid;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.imageio.*;
class TargetOffsetPane extends JPanel implements MouseListener, MouseWheelListener, ChangeListener{
final static int DEFAULT_H = 300;
final static float DEFAULT_PATTERN_RATIO=0.4f;
ScreenImage _simg;
BufferedImage _img;
Match _match;
int _viewX, _viewY, _viewW, _viewH;
float _zoomRatio, _ratio;
Location _tar = new Location(0,0);
Location _offset = new Location(0,0);
JSpinner txtX, txtY;
public TargetOffsetPane(ScreenImage simg, String patFilename, Location initOffset){
_simg = simg;
_ratio = DEFAULT_PATTERN_RATIO;
Rectangle r = _simg.getROI();
int w = DEFAULT_H/r.height*r.width;
setPreferredSize(new Dimension(w, DEFAULT_H));
Finder f = new Finder(_simg, new Region(0,0,0,0));
- f.find(patFilename);
- if(f.hasNext()){
- _match = f.next();
- if(initOffset!=null)
- setTarget(initOffset.x, initOffset.y);
- else
- setTarget(0,0);
- }
- try {
+ try{
+ f.find(patFilename);
+ if(f.hasNext()){
+ _match = f.next();
+ if(initOffset!=null)
+ setTarget(initOffset.x, initOffset.y);
+ else
+ setTarget(0,0);
+ }
_img = ImageIO.read(new File(patFilename));
} catch (IOException e) {
Debug.error("Can't load " + patFilename);
}
addMouseListener(this);
addMouseWheelListener(this);
}
static String _I(String key, Object... args){
return I18N._I(key, args);
}
private void zoomToMatch(){
_viewW = (int)(_match.w/_ratio);
_zoomRatio = getWidth()/(float)_viewW;
_viewH = (int)(getHeight()/_zoomRatio);
_viewX = _match.x + _match.w/2 - _viewW/2;
_viewY = _match.y + _match.h/2 - _viewH/2;
}
public void setTarget(int dx, int dy){
Debug.log(3, "new target: " + dx + "," + dy);
if(_match != null){
Location center = _match.getCenter();
_tar.x = center.x + dx;
_tar.y = center.y + dy;
}
else{
_tar.x = dx;
_tar.y = dy;
}
_offset = new Location(dx, dy);
if(txtX != null){
txtX.setValue(new Integer(dx));
txtY.setValue(new Integer(dy));
}
repaint();
}
public void mousePressed ( MouseEvent me ) {
Location tar = convertViewToScreen(me.getPoint());
Debug.log(4, "click: " + me.getPoint() + " -> " + tar);
if(_match != null){
Location center = _match.getCenter();
setTarget(tar.x-center.x, tar.y-center.y);
}
else{
setTarget(tar.x, tar.y);
}
}
public void mouseWheelMoved(MouseWheelEvent e) {
int rot = e.getWheelRotation();
int patW = (int)(getWidth()*_ratio);
float zoomRatio = patW/(float)_img.getWidth();
int patH = (int)(_img.getHeight()*_zoomRatio);;
if(rot<0){
if(patW < 2*getWidth() && patH < 2*getHeight())
_ratio *= 1.1;
}
else{
if(patW > 20 && patH > 20)
_ratio *= 0.9;
}
repaint();
}
public void mouseClicked ( MouseEvent me ) { }
public void mouseReleased ( MouseEvent me ) {
}
public void mouseEntered ( MouseEvent me ) { }
public void mouseExited ( MouseEvent me ) { }
private static Color COLOR_BG_LINE = new Color(210,210,210,130);
void paintRulers(Graphics g2d){
int step = (int)(10*_zoomRatio);
if(step<2) step = 2;
int h = getHeight(), w = getWidth();
if(h%2==1) h--;
if(w%2==1) w--;
g2d.setColor(COLOR_BG_LINE);
for(int x=w/2;x>=0;x-=step){
g2d.drawLine(x, 0, x, h);
g2d.drawLine(w-x, 0, w-x, h);
}
for(int y=h/2;y>=0;y-=step){
g2d.drawLine(0, y, w, y);
g2d.drawLine(0, h-y, w, h-y);
}
}
void paintBackground(Graphics g2d){
g2d.setColor(Color.WHITE);
g2d.fillRect(0, 0, getWidth(), getHeight());
}
void paintPatternOnly(Graphics g2d){
int patW = (int)(getWidth()*_ratio);
_zoomRatio = patW/(float)_img.getWidth();
int patH = (int)(_img.getHeight()*_zoomRatio);;
int patX = getWidth()/2-patW/2, patY = getHeight()/2-patH/2;
paintBackground(g2d);
g2d.drawImage(_img, patX, patY, patW, patH, null);
}
void paintSubScreen(Graphics g2d){
if(_viewX<0 || _viewY<0) paintBackground(g2d);
int subX = _viewX<0?0:_viewX, subY = _viewY<0?0:_viewY;
int subW = _viewW-(subX-_viewX), subH = _viewH-(subY-_viewY);
BufferedImage img = _simg.getImage();
if(subX+subW >= img.getWidth()) subW = img.getWidth()-subX;
if(subY+subH >= img.getHeight()) subH = img.getHeight()-subY;
BufferedImage clip = img.getSubimage(subX, subY, subW, subH);
int destX = (int)((subX-_viewX)*_zoomRatio),
destY = (int)((subY-_viewY)*_zoomRatio);
int destW = (int)(subW * _zoomRatio),
destH = (int)(subH * _zoomRatio);
g2d.drawImage(clip, destX, destY, destW, destH, null);
}
public void paint(Graphics g){
Graphics2D g2d = (Graphics2D)g;
if( getWidth() > 0 && getHeight() > 0){
if(_match!=null){
zoomToMatch();
paintSubScreen(g2d);
paintMatch(g2d);
}
else
paintPatternOnly(g2d);
paintRulers(g2d);
paintTarget(g2d);
}
}
Location convertViewToScreen(Point p){
Location ret = new Location(0,0);
if(_match!=null){
ret.x = (int)(p.x/_zoomRatio+_viewX);
ret.y = (int)(p.y/_zoomRatio+_viewY);
}
else{
ret.x = (int)((p.x-getWidth()/2)/_zoomRatio);
ret.y = (int)((p.y-getHeight()/2)/_zoomRatio);
}
return ret;
}
Point convertScreenToView(Location loc){
Point ret = new Point();
if(_match!=null){
ret.x = (int)((loc.x - _viewX) * _zoomRatio);
ret.y = (int)((loc.y - _viewY) * _zoomRatio);
}
else{
ret.x = (int)(getWidth()/2 + loc.x * _zoomRatio);
ret.y = (int)(getHeight()/2 + loc.y * _zoomRatio);
}
return ret;
}
void paintTarget(Graphics2D g2d){
final int CROSS_LEN=20/2;
Point l = convertScreenToView(_tar);
g2d.setColor(Color.BLACK);
g2d.drawLine(l.x-CROSS_LEN, l.y+1, l.x+CROSS_LEN, l.y+1);
g2d.drawLine(l.x+1, l.y-CROSS_LEN, l.x+1, l.y+CROSS_LEN);
g2d.setColor(Color.WHITE);
g2d.drawLine(l.x-CROSS_LEN, l.y, l.x+CROSS_LEN, l.y);
g2d.drawLine(l.x, l.y-CROSS_LEN, l.x, l.y+CROSS_LEN);
}
void paintMatch(Graphics2D g2d){
int w = (int)(getWidth() * _ratio),
h = (int)((float)w/_img.getWidth()*_img.getHeight());
int x = getWidth()/2- w/2, y = getHeight()/2-h/2;
Color c = SimilaritySlider.getScoreColor(_match.score);
g2d.setColor(c);
g2d.fillRect(x, y, w, h);
g2d.drawRect(x, y, w-1, h-1);
}
public JComponent createControls(){
JPanel pane = new JPanel(new GridBagLayout());
JLabel lblTargetX = new JLabel(_I("lblTargetOffsetX"));
JLabel lblY = new JLabel(_I("lblTargetOffsetY"));
int x = _offset!=null? _offset.x : 0;
int y = _offset!=null? _offset.y : 0;
txtX = new JSpinner(new SpinnerNumberModel(x, -999, 999, 1));
txtY = new JSpinner(new SpinnerNumberModel(y, -999, 999, 1));
txtX.addChangeListener(this);
txtY.addChangeListener(this);
GridBagConstraints c = new GridBagConstraints();
c.fill = 1;
c.gridy = 0;
pane.add( lblTargetX, c );
pane.add( txtX, c );
pane.add( lblY, c );
pane.add( txtY, c );
return pane;
}
public void stateChanged(javax.swing.event.ChangeEvent e) {
int x = (Integer)txtX.getValue();
int y = (Integer)txtY.getValue();
setTarget(x, y);
}
public Location getTargetOffset(){
return new Location(_offset);
}
}
| true | true | public TargetOffsetPane(ScreenImage simg, String patFilename, Location initOffset){
_simg = simg;
_ratio = DEFAULT_PATTERN_RATIO;
Rectangle r = _simg.getROI();
int w = DEFAULT_H/r.height*r.width;
setPreferredSize(new Dimension(w, DEFAULT_H));
Finder f = new Finder(_simg, new Region(0,0,0,0));
f.find(patFilename);
if(f.hasNext()){
_match = f.next();
if(initOffset!=null)
setTarget(initOffset.x, initOffset.y);
else
setTarget(0,0);
}
try {
_img = ImageIO.read(new File(patFilename));
} catch (IOException e) {
Debug.error("Can't load " + patFilename);
}
addMouseListener(this);
addMouseWheelListener(this);
}
| public TargetOffsetPane(ScreenImage simg, String patFilename, Location initOffset){
_simg = simg;
_ratio = DEFAULT_PATTERN_RATIO;
Rectangle r = _simg.getROI();
int w = DEFAULT_H/r.height*r.width;
setPreferredSize(new Dimension(w, DEFAULT_H));
Finder f = new Finder(_simg, new Region(0,0,0,0));
try{
f.find(patFilename);
if(f.hasNext()){
_match = f.next();
if(initOffset!=null)
setTarget(initOffset.x, initOffset.y);
else
setTarget(0,0);
}
_img = ImageIO.read(new File(patFilename));
} catch (IOException e) {
Debug.error("Can't load " + patFilename);
}
addMouseListener(this);
addMouseWheelListener(this);
}
|
diff --git a/src/main/java/de/lessvoid/nifty/loader/xpp3/elements/ElementType.java b/src/main/java/de/lessvoid/nifty/loader/xpp3/elements/ElementType.java
index c6840d8d..5b70481f 100644
--- a/src/main/java/de/lessvoid/nifty/loader/xpp3/elements/ElementType.java
+++ b/src/main/java/de/lessvoid/nifty/loader/xpp3/elements/ElementType.java
@@ -1,578 +1,578 @@
package de.lessvoid.nifty.loader.xpp3.elements;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import java.util.Map.Entry;
import java.util.logging.Logger;
import org.newdawn.slick.util.Log;
import de.lessvoid.nifty.Nifty;
import de.lessvoid.nifty.controls.NiftyInputControl;
import de.lessvoid.nifty.elements.Element;
import de.lessvoid.nifty.elements.render.ImageRenderer;
import de.lessvoid.nifty.elements.render.PanelRenderer;
import de.lessvoid.nifty.elements.render.TextRenderer;
import de.lessvoid.nifty.layout.align.HorizontalAlign;
import de.lessvoid.nifty.layout.align.VerticalAlign;
import de.lessvoid.nifty.loader.xpp3.Attributes;
import de.lessvoid.nifty.loader.xpp3.elements.helper.StyleHandler;
import de.lessvoid.nifty.loader.xpp3.processor.helper.TypeContext;
import de.lessvoid.nifty.render.NiftyImage;
import de.lessvoid.nifty.render.NiftyImageMode;
import de.lessvoid.nifty.render.NiftyRenderEngine;
import de.lessvoid.nifty.screen.Screen;
import de.lessvoid.nifty.screen.ScreenController;
import de.lessvoid.nifty.tools.SizeValue;
import de.lessvoid.nifty.tools.TimeProvider;
/**
* ElementType.
* @author void
*/
public class ElementType {
/**
* logger.
*/
private static Logger log = Logger.getLogger(ElementType.class.getName());
/**
* attributes.
*/
protected AttributesType attributes;
/**
* interact.
* @optional
*/
private InteractType interact;
/**
* hover.
* @optional
*/
private HoverType hover;
/**
* EffectsType.
* @optional
*/
private EffectsType effects;
/**
* elements.
* @optional
*/
private Collection < ElementType > elements = new ArrayList < ElementType >();
protected TypeContext typeContext;
protected ElementType elementTypeParent;
public ElementType(final TypeContext newTypeContext) {
typeContext = newTypeContext;
}
/**
* Create element.
* @param parent parent element
* @param screen screen
* @param inputControl inputControl we should attach to the element (can be null)
* @param screenController ScreenController
* @return element
*/
public Element createElement(
final Element parent,
final Screen screen,
final NiftyInputControl inputControl,
final ScreenController screenController) {
return null;
}
/**
* add attributes to the element.
* @param element element
* @param screen screen
* @param screenController screenController
* @param control attached control (might be null)
*/
protected void addElementAttributes(
final Element element,
final Screen screen,
final ScreenController screenController,
final NiftyInputControl ... control) {
// if the element we process has a style set, we try to apply
// the style attributes first
String styleId = attributes.getStyle();
applyStyle(
element,
typeContext.nifty,
typeContext.registeredEffects,
typeContext.styleHandler,
typeContext.time,
styleId,
screen);
// now apply our own attributes
applyAttributes(attributes, screen, element, typeContext.nifty.getRenderDevice());
// attach input control
if (control != null) {
element.attachInputControl(control[control.length - 1]);
}
// interact
if (interact != null) {
if (control != null) {
interact.initWithControl(element, getControllerArray(control, screenController));
} else {
interact.initWithScreenController(element, screenController);
}
}
// hover
if (hover != null) {
hover.initElement(element);
}
// effects
if (effects != null) {
effects.initElement(element, typeContext.nifty, typeContext.registeredEffects, typeContext.time);
}
// children
for (ElementType elementType : elements) {
elementType.createElement(
element,
screen,
control[control.length - 1],
screenController);
}
}
/**
* Get controller array.
* @param control input controls
* @param screenController screen controller
* @return object array
*/
private Object[] getControllerArray(final NiftyInputControl[] control, final ScreenController screenController) {
ArrayList < Object > controlList = new ArrayList < Object >();
for (NiftyInputControl c : control) {
if (c != null) {
controlList.add(c.getController());
}
}
if (screenController != null) {
controlList.add(screenController);
}
return controlList.toArray(new Object[0]);
}
/**
* apply style.
* @param element element
* @param nifty nifty
* @param registeredEffects effects
* @param styleHandler style handler
* @param time time provider
* @param styleId style id
* @param screen screen
*/
private void applyStyle(
final Element element,
final Nifty nifty,
final Map < String, RegisterEffectType > registeredEffects,
final StyleHandler styleHandler,
final TimeProvider time,
final String styleId,
final Screen screen) {
if (styleId != null) {
StyleType style = styleHandler.getStyle(styleId);
if (style != null) {
style.applyStyle(element, nifty, registeredEffects, time, screen);
}
}
}
/**
* apply given attributes to the element.
* @param attrib attributes
* @param screen screen
* @param element the element to apply attributes
* @param renderDevice RenderDevice
*/
public static void applyAttributes(
final AttributesType attrib,
final Screen screen,
final Element element,
final NiftyRenderEngine renderDevice) {
if (attrib == null) {
return;
}
// height
if (attrib.getHeight() != null) {
SizeValue heightValue = new SizeValue(attrib.getHeight());
element.setConstraintHeight(heightValue);
}
// width
if (attrib.getWidth() != null) {
SizeValue widthValue = new SizeValue(attrib.getWidth());
element.setConstraintWidth(widthValue);
}
// set absolute x position when given
if (attrib.getX() != null) {
element.setConstraintX(new SizeValue(attrib.getX()));
}
// set absolute y position when given
if (attrib.getY() != null) {
element.setConstraintY(new SizeValue(attrib.getY()));
}
// horizontal align
if (attrib.getAlign() != null) {
element.setConstraintHorizontalAlign(HorizontalAlign.valueOf(attrib.getAlign().getValue()));
}
// vertical align
if (attrib.getValign() != null) {
element.setConstraintVerticalAlign(VerticalAlign.valueOf(attrib.getValign().getValue()));
}
// paddingLeft
if (attrib.getPaddingLeft() != null) {
SizeValue paddingValue = new SizeValue(attrib.getPaddingLeft());
element.setPaddingLeft(paddingValue);
}
// paddingRight
if (attrib.getPaddingRight() != null) {
SizeValue paddingValue = new SizeValue(attrib.getPaddingRight());
element.setPaddingRight(paddingValue);
}
// paddingTop
if (attrib.getPaddingTop() != null) {
SizeValue paddingValue = new SizeValue(attrib.getPaddingTop());
element.setPaddingTop(paddingValue);
}
// paddingBottom
if (attrib.getPaddingBottom() != null) {
SizeValue paddingValue = new SizeValue(attrib.getPaddingBottom());
element.setPaddingBottom(paddingValue);
}
// child clip
if (attrib.getChildClip() != null) {
element.setClipChildren(attrib.getChildClip());
}
// visible
if (attrib.getVisible() != null) {
if (attrib.getVisible()) {
element.show();
} else {
element.hide();
}
}
// visibleToMouse
if (attrib.getVisibleToMouse() != null) {
element.setVisibleToMouseEvents(attrib.getVisibleToMouse());
}
// childLayout
if (attrib.getChildLayoutType() != null) {
element.setLayoutManager(attrib.getChildLayoutType().getLayoutManager());
}
// focusable
if (attrib.getFocusable() != null) {
element.setFocusable(attrib.getFocusable());
}
// textRenderer
TextRenderer textRenderer = element.getRenderer(TextRenderer.class);
if (textRenderer != null) {
// font
if (attrib.getFont() != null) {
textRenderer.setFont(renderDevice.createFont(attrib.getFont()));
}
// text horizontal align
if (attrib.getTextHAlign() != null) {
textRenderer.setTextHAlign(HorizontalAlign.valueOf(attrib.getTextHAlign().getValue()));
}
// text vertical align
if (attrib.getTextVAlign() != null) {
textRenderer.setTextVAlign(VerticalAlign.valueOf(attrib.getTextVAlign().getValue()));
}
// text color
if (attrib.getColor() != null) {
textRenderer.setColor(attrib.getColor().createColor());
}
// text
if (attrib.getText() != null) {
textRenderer.setText(attrib.getText());
}
}
// panelRenderer
PanelRenderer panelRenderer = element.getRenderer(PanelRenderer.class);
if (panelRenderer != null) {
// background color
if (attrib.getBackgroundColor() != null) {
panelRenderer.setBackgroundColor(attrib.getBackgroundColor().createColor());
}
}
// imageRenderer
ImageRenderer imageRenderer = element.getRenderer(ImageRenderer.class);
if (imageRenderer != null) {
// filename
if (attrib.getFilename() != null) {
imageRenderer.setImage(renderDevice.createImage(attrib.getFilename(), attrib.getFilter()));
}
if (attrib.getBackgroundImage() != null) {
imageRenderer.setImage(renderDevice.createImage(attrib.getBackgroundImage(), attrib.getFilter()));
}
// set imageMode?
NiftyImage image = imageRenderer.getImage();
String imageMode = attrib.getImageMode();
if (image != null && imageMode != null) {
image.setImageMode(NiftyImageMode.valueOf(imageMode));
}
// set width and height to image width and height (for now)
image = imageRenderer.getImage();
if (image != null) {
if (element.getConstraintWidth() == null) {
- // element.setConstraintWidth(new SizeValue(image.getWidth() + "px"));
+ element.setConstraintWidth(new SizeValue(image.getWidth() + "px"));
}
if (element.getConstraintHeight() == null) {
- // element.setConstraintHeight(new SizeValue(image.getHeight() + "px"));
+ element.setConstraintHeight(new SizeValue(image.getHeight() + "px"));
}
if (attrib.getInset() != null) {
imageRenderer.setInset(new SizeValue(attrib.getInset()).getValueAsInt(image.getHeight()));
}
}
}
}
/**
* add element.
* @param elementType elementType
*/
public void addElementType(final ElementType elementType) {
elements.add(elementType);
elementType.setParent(this);
}
private void setParent(final ElementType newElementTypeParent) {
elementTypeParent = newElementTypeParent;
}
/**
* set interact.
* @param interactParam interact
*/
public void setInteract(final InteractType interactParam) {
this.interact = interactParam;
}
/**
* set hover.
* @param hoverParam hover
*/
public void setHover(final HoverType hoverParam) {
this.hover = hoverParam;
}
/**
* set effects.
* @param effectsParam effects
*/
public void setEffects(final EffectsType effectsParam) {
this.effects = effectsParam;
}
/**
* get attributes.
* @return attributes
*/
public AttributesType getAttributes() {
return attributes;
}
/**
* set attributes.
* @param attributesTypeParam attributes type to set
*/
public void setAttributes(final AttributesType attributesTypeParam) {
attributes = attributesTypeParam;
}
public void applyStyle(
final Element element,
final Screen screen,
final String newStyle) {
applyStyle(
element,
typeContext.nifty,
typeContext.registeredEffects,
typeContext.styleHandler,
typeContext.time,
newStyle,
screen);
controlProcessStyleAttribute(
element,
typeContext.styleHandler,
null,
newStyle,
typeContext.nifty,
typeContext.registeredEffects,
typeContext.time,
screen);
for (Element child : element.getElements()) {
applyControlStyle(
child,
typeContext.styleHandler,
null,
newStyle,
typeContext.nifty,
typeContext.registeredEffects,
typeContext.time,
screen);
}
}
/**
* process this elements styleId. this is used for controls and
* changes the given styleId and the elements style id to a new
* combined one.
* @param element element
* @param styleHandler style handler
* @param controlDefinitionAttributes controlDefinitionAttributes
* @param controlAttributes controlAttributes
* @param nifty nifty
* @param registeredEffects effects
* @param time time
* @param screen screen
*/
public static void applyControlStyle(
final Element element,
final StyleHandler styleHandler,
final String controlDefinitionStyle,
final String controlStyle,
final Nifty nifty,
final Map < String, RegisterEffectType > registeredEffects,
final TimeProvider time,
final Screen screen) {
controlProcessStyleAttribute(
element,
styleHandler,
controlDefinitionStyle,
controlStyle,
nifty,
registeredEffects,
time,
screen);
for (Element child : element.getElements()) {
applyControlStyle(
child,
styleHandler,
controlDefinitionStyle,
controlStyle,
nifty,
registeredEffects,
time,
screen);
}
}
/**
* apply control parameters.
* @param element element
* @param controlAttributes control attributes
* @param nifty nifty instance
* @param screen screen
*/
public static void applyControlParameters(
final Element element,
final Attributes controlAttributes,
final Nifty nifty,
final Screen screen) {
controlProcessParameters(element, controlAttributes, nifty.getRenderDevice(), screen);
for (Element child : element.getElements()) {
applyControlParameters(child, controlAttributes, nifty, screen);
}
}
/**
* process style attribute.
* @param element element
* @param styleHandler style handler
* @param controlDefinitionAttributes control definition attributes
* @param controlAttributes control attributes
* @param nifty nifty
* @param registeredEffects effects
* @param time time
* @param screen screen
*/
private static void controlProcessStyleAttribute(
final Element element,
final StyleHandler styleHandler,
final String controlDefinitionStyle,
final String controlStyle,
final Nifty nifty,
final Map < String, RegisterEffectType > registeredEffects,
final TimeProvider time,
final Screen screen) {
String myStyleId = element.getElementType().getAttributes().getStyle();
if (myStyleId != null) {
// this element has a style id set. is a special substyle?
int indexOfSep = myStyleId.indexOf("#");
if (indexOfSep != -1) {
StyleType style = resolveStyle(styleHandler, myStyleId, controlStyle);
if (style == null) {
style = resolveStyle(styleHandler, myStyleId, controlDefinitionStyle);
}
if (style != null) {
style.applyStyle(element, nifty, registeredEffects, time, screen);
}
}
}
}
/**
* try to resolve style.
* @param styleHandler style handler
* @param myStyleId my style
* @param newStyle new style
* @return StyleType when resolved or null on error.
*/
private static StyleType resolveStyle(
final StyleHandler styleHandler,
final String myStyleId,
final String newStyle) {
if (myStyleId.startsWith("#")) {
String resolvedStyle = newStyle + myStyleId;
// check if newStyleId exists.
return styleHandler.getStyle(resolvedStyle);
} else {
return null;
}
}
/**
* process parameters.
* @param element element
* @param controlAttributes control attributes
* @param niftyRenderEngine render engine
* @param screen screen
*/
private static void controlProcessParameters(
final Element element,
final Attributes controlAttributes,
final NiftyRenderEngine niftyRenderEngine,
final Screen screen) {
for (Entry < String, String > entry
: element.getElementType().getAttributes().findParameterAttributes().entrySet()) {
String value = controlAttributes.get(entry.getValue());
if (value == null) {
value = "'" + entry.getValue() + "' missing o_O";
continue;
}
log.fine("[" + element.getId() + "{" + element + "}] setting [" + entry.getKey() + "] to [" + value + "]");
Attributes attributes = new Attributes();
attributes.overwriteAttribute(entry.getKey(), value);
ElementType.applyAttributes(new AttributesType(attributes), screen, element, niftyRenderEngine);
}
}
}
| false | true | public static void applyAttributes(
final AttributesType attrib,
final Screen screen,
final Element element,
final NiftyRenderEngine renderDevice) {
if (attrib == null) {
return;
}
// height
if (attrib.getHeight() != null) {
SizeValue heightValue = new SizeValue(attrib.getHeight());
element.setConstraintHeight(heightValue);
}
// width
if (attrib.getWidth() != null) {
SizeValue widthValue = new SizeValue(attrib.getWidth());
element.setConstraintWidth(widthValue);
}
// set absolute x position when given
if (attrib.getX() != null) {
element.setConstraintX(new SizeValue(attrib.getX()));
}
// set absolute y position when given
if (attrib.getY() != null) {
element.setConstraintY(new SizeValue(attrib.getY()));
}
// horizontal align
if (attrib.getAlign() != null) {
element.setConstraintHorizontalAlign(HorizontalAlign.valueOf(attrib.getAlign().getValue()));
}
// vertical align
if (attrib.getValign() != null) {
element.setConstraintVerticalAlign(VerticalAlign.valueOf(attrib.getValign().getValue()));
}
// paddingLeft
if (attrib.getPaddingLeft() != null) {
SizeValue paddingValue = new SizeValue(attrib.getPaddingLeft());
element.setPaddingLeft(paddingValue);
}
// paddingRight
if (attrib.getPaddingRight() != null) {
SizeValue paddingValue = new SizeValue(attrib.getPaddingRight());
element.setPaddingRight(paddingValue);
}
// paddingTop
if (attrib.getPaddingTop() != null) {
SizeValue paddingValue = new SizeValue(attrib.getPaddingTop());
element.setPaddingTop(paddingValue);
}
// paddingBottom
if (attrib.getPaddingBottom() != null) {
SizeValue paddingValue = new SizeValue(attrib.getPaddingBottom());
element.setPaddingBottom(paddingValue);
}
// child clip
if (attrib.getChildClip() != null) {
element.setClipChildren(attrib.getChildClip());
}
// visible
if (attrib.getVisible() != null) {
if (attrib.getVisible()) {
element.show();
} else {
element.hide();
}
}
// visibleToMouse
if (attrib.getVisibleToMouse() != null) {
element.setVisibleToMouseEvents(attrib.getVisibleToMouse());
}
// childLayout
if (attrib.getChildLayoutType() != null) {
element.setLayoutManager(attrib.getChildLayoutType().getLayoutManager());
}
// focusable
if (attrib.getFocusable() != null) {
element.setFocusable(attrib.getFocusable());
}
// textRenderer
TextRenderer textRenderer = element.getRenderer(TextRenderer.class);
if (textRenderer != null) {
// font
if (attrib.getFont() != null) {
textRenderer.setFont(renderDevice.createFont(attrib.getFont()));
}
// text horizontal align
if (attrib.getTextHAlign() != null) {
textRenderer.setTextHAlign(HorizontalAlign.valueOf(attrib.getTextHAlign().getValue()));
}
// text vertical align
if (attrib.getTextVAlign() != null) {
textRenderer.setTextVAlign(VerticalAlign.valueOf(attrib.getTextVAlign().getValue()));
}
// text color
if (attrib.getColor() != null) {
textRenderer.setColor(attrib.getColor().createColor());
}
// text
if (attrib.getText() != null) {
textRenderer.setText(attrib.getText());
}
}
// panelRenderer
PanelRenderer panelRenderer = element.getRenderer(PanelRenderer.class);
if (panelRenderer != null) {
// background color
if (attrib.getBackgroundColor() != null) {
panelRenderer.setBackgroundColor(attrib.getBackgroundColor().createColor());
}
}
// imageRenderer
ImageRenderer imageRenderer = element.getRenderer(ImageRenderer.class);
if (imageRenderer != null) {
// filename
if (attrib.getFilename() != null) {
imageRenderer.setImage(renderDevice.createImage(attrib.getFilename(), attrib.getFilter()));
}
if (attrib.getBackgroundImage() != null) {
imageRenderer.setImage(renderDevice.createImage(attrib.getBackgroundImage(), attrib.getFilter()));
}
// set imageMode?
NiftyImage image = imageRenderer.getImage();
String imageMode = attrib.getImageMode();
if (image != null && imageMode != null) {
image.setImageMode(NiftyImageMode.valueOf(imageMode));
}
// set width and height to image width and height (for now)
image = imageRenderer.getImage();
if (image != null) {
if (element.getConstraintWidth() == null) {
// element.setConstraintWidth(new SizeValue(image.getWidth() + "px"));
}
if (element.getConstraintHeight() == null) {
// element.setConstraintHeight(new SizeValue(image.getHeight() + "px"));
}
if (attrib.getInset() != null) {
imageRenderer.setInset(new SizeValue(attrib.getInset()).getValueAsInt(image.getHeight()));
}
}
}
}
| public static void applyAttributes(
final AttributesType attrib,
final Screen screen,
final Element element,
final NiftyRenderEngine renderDevice) {
if (attrib == null) {
return;
}
// height
if (attrib.getHeight() != null) {
SizeValue heightValue = new SizeValue(attrib.getHeight());
element.setConstraintHeight(heightValue);
}
// width
if (attrib.getWidth() != null) {
SizeValue widthValue = new SizeValue(attrib.getWidth());
element.setConstraintWidth(widthValue);
}
// set absolute x position when given
if (attrib.getX() != null) {
element.setConstraintX(new SizeValue(attrib.getX()));
}
// set absolute y position when given
if (attrib.getY() != null) {
element.setConstraintY(new SizeValue(attrib.getY()));
}
// horizontal align
if (attrib.getAlign() != null) {
element.setConstraintHorizontalAlign(HorizontalAlign.valueOf(attrib.getAlign().getValue()));
}
// vertical align
if (attrib.getValign() != null) {
element.setConstraintVerticalAlign(VerticalAlign.valueOf(attrib.getValign().getValue()));
}
// paddingLeft
if (attrib.getPaddingLeft() != null) {
SizeValue paddingValue = new SizeValue(attrib.getPaddingLeft());
element.setPaddingLeft(paddingValue);
}
// paddingRight
if (attrib.getPaddingRight() != null) {
SizeValue paddingValue = new SizeValue(attrib.getPaddingRight());
element.setPaddingRight(paddingValue);
}
// paddingTop
if (attrib.getPaddingTop() != null) {
SizeValue paddingValue = new SizeValue(attrib.getPaddingTop());
element.setPaddingTop(paddingValue);
}
// paddingBottom
if (attrib.getPaddingBottom() != null) {
SizeValue paddingValue = new SizeValue(attrib.getPaddingBottom());
element.setPaddingBottom(paddingValue);
}
// child clip
if (attrib.getChildClip() != null) {
element.setClipChildren(attrib.getChildClip());
}
// visible
if (attrib.getVisible() != null) {
if (attrib.getVisible()) {
element.show();
} else {
element.hide();
}
}
// visibleToMouse
if (attrib.getVisibleToMouse() != null) {
element.setVisibleToMouseEvents(attrib.getVisibleToMouse());
}
// childLayout
if (attrib.getChildLayoutType() != null) {
element.setLayoutManager(attrib.getChildLayoutType().getLayoutManager());
}
// focusable
if (attrib.getFocusable() != null) {
element.setFocusable(attrib.getFocusable());
}
// textRenderer
TextRenderer textRenderer = element.getRenderer(TextRenderer.class);
if (textRenderer != null) {
// font
if (attrib.getFont() != null) {
textRenderer.setFont(renderDevice.createFont(attrib.getFont()));
}
// text horizontal align
if (attrib.getTextHAlign() != null) {
textRenderer.setTextHAlign(HorizontalAlign.valueOf(attrib.getTextHAlign().getValue()));
}
// text vertical align
if (attrib.getTextVAlign() != null) {
textRenderer.setTextVAlign(VerticalAlign.valueOf(attrib.getTextVAlign().getValue()));
}
// text color
if (attrib.getColor() != null) {
textRenderer.setColor(attrib.getColor().createColor());
}
// text
if (attrib.getText() != null) {
textRenderer.setText(attrib.getText());
}
}
// panelRenderer
PanelRenderer panelRenderer = element.getRenderer(PanelRenderer.class);
if (panelRenderer != null) {
// background color
if (attrib.getBackgroundColor() != null) {
panelRenderer.setBackgroundColor(attrib.getBackgroundColor().createColor());
}
}
// imageRenderer
ImageRenderer imageRenderer = element.getRenderer(ImageRenderer.class);
if (imageRenderer != null) {
// filename
if (attrib.getFilename() != null) {
imageRenderer.setImage(renderDevice.createImage(attrib.getFilename(), attrib.getFilter()));
}
if (attrib.getBackgroundImage() != null) {
imageRenderer.setImage(renderDevice.createImage(attrib.getBackgroundImage(), attrib.getFilter()));
}
// set imageMode?
NiftyImage image = imageRenderer.getImage();
String imageMode = attrib.getImageMode();
if (image != null && imageMode != null) {
image.setImageMode(NiftyImageMode.valueOf(imageMode));
}
// set width and height to image width and height (for now)
image = imageRenderer.getImage();
if (image != null) {
if (element.getConstraintWidth() == null) {
element.setConstraintWidth(new SizeValue(image.getWidth() + "px"));
}
if (element.getConstraintHeight() == null) {
element.setConstraintHeight(new SizeValue(image.getHeight() + "px"));
}
if (attrib.getInset() != null) {
imageRenderer.setInset(new SizeValue(attrib.getInset()).getValueAsInt(image.getHeight()));
}
}
}
}
|
diff --git a/asgn/src/chord/rels/RelMputInstFldInst.java b/asgn/src/chord/rels/RelMputInstFldInst.java
index c729c16..b77786d 100644
--- a/asgn/src/chord/rels/RelMputInstFldInst.java
+++ b/asgn/src/chord/rels/RelMputInstFldInst.java
@@ -1,46 +1,46 @@
package chord.rels;
import chord.program.CFG;
import chord.program.Method;
import chord.program.insts.Inst;
import chord.program.insts.InstFldRefInst;
import chord.project.Chord;
import chord.project.ProgramRel;
import chord.program.Var;
import chord.doms.DomM;
import chord.doms.DomV;
import chord.doms.DomF;
/**
* Relation containing each tuple (m,b,f,v) such that method m
* contains a statement of the form <tt>b.f = v</tt>.
*/
@Chord(
name = "MputInstFldInst",
sign = "M0,V0,F0,V1:F0_M0_V0xV1"
)
public class RelMputInstFldInst extends ProgramRel {
public void fill() {
DomM domM = (DomM) doms[0];
// DomV domV = (DomV) doms[1];
// DomF domF = (DomF) doms[2];
// DomV domB = (DomV) doms[3];
for (Method meth : domM) {
CFG cfg = meth.getCFG();
if (cfg == null)
continue;
for (Inst inst : cfg.getNodes()) {
if (inst instanceof InstFldRefInst) {
InstFldRefInst asgn = (InstFldRefInst) inst;
if (asgn.isWr()) {
Var v = asgn.getVar();
if (v == null) continue;
- add(meth, v, asgn.getField(), asgn.getBase());
+ add(meth, asgn.getBase(), asgn.getField(), v);
}
}
}
}
}
}
| true | true | public void fill() {
DomM domM = (DomM) doms[0];
// DomV domV = (DomV) doms[1];
// DomF domF = (DomF) doms[2];
// DomV domB = (DomV) doms[3];
for (Method meth : domM) {
CFG cfg = meth.getCFG();
if (cfg == null)
continue;
for (Inst inst : cfg.getNodes()) {
if (inst instanceof InstFldRefInst) {
InstFldRefInst asgn = (InstFldRefInst) inst;
if (asgn.isWr()) {
Var v = asgn.getVar();
if (v == null) continue;
add(meth, v, asgn.getField(), asgn.getBase());
}
}
}
}
}
| public void fill() {
DomM domM = (DomM) doms[0];
// DomV domV = (DomV) doms[1];
// DomF domF = (DomF) doms[2];
// DomV domB = (DomV) doms[3];
for (Method meth : domM) {
CFG cfg = meth.getCFG();
if (cfg == null)
continue;
for (Inst inst : cfg.getNodes()) {
if (inst instanceof InstFldRefInst) {
InstFldRefInst asgn = (InstFldRefInst) inst;
if (asgn.isWr()) {
Var v = asgn.getVar();
if (v == null) continue;
add(meth, asgn.getBase(), asgn.getField(), v);
}
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.