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/src/test.java b/src/test.java
index 07d6e00..97fe3f9 100644
--- a/src/test.java
+++ b/src/test.java
@@ -1,8 +1,8 @@
final class test {
public static void main(String argv[]) {
Eval.initializeSystem();
- Eval.loadProgram("C:\\Users\\kzfm1024\\GitHub\\jakld7\\src\\test.scm");
+ Eval.loadProgram("src\\test.scm");
}
}
| true | true | public static void main(String argv[]) {
Eval.initializeSystem();
Eval.loadProgram("C:\\Users\\kzfm1024\\GitHub\\jakld7\\src\\test.scm");
}
| public static void main(String argv[]) {
Eval.initializeSystem();
Eval.loadProgram("src\\test.scm");
}
|
diff --git a/simbeeotic-core/src/main/java/harvard/robobees/simbeeotic/model/InertHive.java b/simbeeotic-core/src/main/java/harvard/robobees/simbeeotic/model/InertHive.java
index 4ab20ef..c026174 100644
--- a/simbeeotic-core/src/main/java/harvard/robobees/simbeeotic/model/InertHive.java
+++ b/simbeeotic-core/src/main/java/harvard/robobees/simbeeotic/model/InertHive.java
@@ -1,40 +1,40 @@
package harvard.robobees.simbeeotic.model;
/**
* A hive logic implementation that has no behavior. The hive is
* completely inert.
*
* @author bkate
*/
public class InertHive implements GenericHiveLogic {
/**
* {@inheritDoc}
*
* Does nothing.
*/
@Override
- public void intialize(GenericHive bee) {
+ public void initialize(GenericHive bee) {
}
/**
* {@inheritDoc}
*
* Does nothing.
*/
@Override
public void update(double time) {
}
/**
* {@inheritDoc}
*
* Does nothing.
*/
@Override
public void messageReceived(double time, byte[] data, float rxPower) {
}
}
| true | true | public void intialize(GenericHive bee) {
}
| public void initialize(GenericHive bee) {
}
|
diff --git a/src/org/openstreetmap/josm/io/DefaultProxySelector.java b/src/org/openstreetmap/josm/io/DefaultProxySelector.java
index ea738c59..523cf5d6 100644
--- a/src/org/openstreetmap/josm/io/DefaultProxySelector.java
+++ b/src/org/openstreetmap/josm/io/DefaultProxySelector.java
@@ -1,169 +1,169 @@
// License: GPL. For details, see LICENSE file.
package org.openstreetmap.josm.io;
import static org.openstreetmap.josm.tools.I18n.tr;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.SocketAddress;
import java.net.URI;
import java.net.Proxy.Type;
import java.util.Collections;
import java.util.List;
import java.util.logging.Logger;
import org.openstreetmap.josm.Main;
import org.openstreetmap.josm.gui.preferences.ProxyPreferences;
import org.openstreetmap.josm.gui.preferences.ProxyPreferences.ProxyPolicy;
/**
* This is the default proxy selector used in JOSM.
*
*/
public class DefaultProxySelector extends ProxySelector {
static private final Logger logger = Logger.getLogger(DefaultProxySelector.class.getName());
/**
* The {@see ProxySelector} provided by the JDK will retrieve proxy information
* from the system settings, if the system property <tt>java.net.useSystemProxies</tt>
* is defined <strong>at startup</strong>. It has no effect if the property is set
* later by the application.
*
* We therefore read the property at class loading time and remember it's value.
*/
private static boolean JVM_WILL_USE_SYSTEM_PROXIES = false;
{
String v = System.getProperty("java.net.useSystemProxies");
if (v != null && v.equals(Boolean.TRUE.toString())) {
JVM_WILL_USE_SYSTEM_PROXIES = true;
}
}
/**
* The {@see ProxySelector} provided by the JDK will retrieve proxy information
* from the system settings, if the system property <tt>java.net.useSystemProxies</tt>
* is defined <strong>at startup</strong>. If the property is set later by the application,
* this has no effect.
*
* @return true, if <tt>java.net.useSystemProxies</tt> was set to true at class initialization time
*
*/
public static boolean willJvmRetrieveSystemProxies() {
return JVM_WILL_USE_SYSTEM_PROXIES;
}
private ProxyPolicy proxyPolicy;
private InetSocketAddress httpProxySocketAddress;
private InetSocketAddress socksProxySocketAddress;
private ProxySelector delegate;
/**
* A typical example is:
* <pre>
* PropertySelector delegate = PropertySelector.getDefault();
* PropertySelector.setDefault(new DefaultPropertySelector(delegate));
* </pre>
*
* @param delegate the proxy selector to delegate to if system settings are used. Usually
* this is the proxy selector found by ProxySelector.getDefault() before this proxy
* selector is installed
*/
public DefaultProxySelector(ProxySelector delegate) {
this.delegate = delegate;
initFromPreferences();
}
protected int parseProxyPortValue(String property, String value) {
if (value == null) return 0;
int port = 0;
try {
port = Integer.parseInt(value);
} catch(NumberFormatException e){
System.err.println(tr("Unexpected format for port number in in preference ''{0}''. Got ''{1}''. Proxy won't be used.", property, value));
return 0;
}
if (port <= 0 || port > 65535) {
System.err.println(tr("Illegal port number in preference ''{0}''. Got {1}. Proxy won't be used.", property, port));
return 0;
}
return port;
}
/**
* Initializes the proxy selector from the setting in the preferences.
*
*/
public void initFromPreferences() {
String value = Main.pref.get(ProxyPreferences.PROXY_POLICY);
- if (value == null) {
+ if (value.length() == 0) {
System.err.println(tr("Warning: no preference ''{0}'' found. Will use no proxy.", ProxyPreferences.PROXY_POLICY));
proxyPolicy = ProxyPolicy.NO_PROXY;
} else {
proxyPolicy= ProxyPolicy.fromName(value);
if (proxyPolicy == null) {
System.err.println(tr("Warning: unexpected value for preference ''{0}'' found. Got ''{1}''. Will use no proxy.", ProxyPreferences.PROXY_POLICY, value));
proxyPolicy = ProxyPolicy.NO_PROXY;
}
}
String host = Main.pref.get(ProxyPreferences.PROXY_HTTP_HOST, null);
int port = parseProxyPortValue(ProxyPreferences.PROXY_HTTP_PORT, Main.pref.get(ProxyPreferences.PROXY_HTTP_PORT, null));
if (host != null && ! host.trim().equals("") && port > 0) {
httpProxySocketAddress = new InetSocketAddress(host,port);
} else {
httpProxySocketAddress = null;
if (proxyPolicy.equals(ProxyPolicy.USE_HTTP_PROXY)) {
System.err.println(tr("Warning: Unexpected parameters for HTTP proxy. Got host ''{0}'' and port ''{1}''. Proxy won't be used", host, port));
}
}
host = Main.pref.get(ProxyPreferences.PROXY_SOCKS_HOST, null);
port = parseProxyPortValue(ProxyPreferences.PROXY_SOCKS_PORT, Main.pref.get(ProxyPreferences.PROXY_SOCKS_PORT, null));
if (host != null && ! host.trim().equals("") && port > 0) {
socksProxySocketAddress = new InetSocketAddress(host,port);
} else {
socksProxySocketAddress = null;
if (proxyPolicy.equals(ProxyPolicy.USE_SOCKS_PROXY)) {
System.err.println(tr("Warning: Unexpected parameters for SOCKS proxy. Got host ''{0}'' and port ''{1}''. Proxy won't be used", host, port));
}
}
}
@Override
public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
// Just log something. The network stack will also throw an exception which will be caught
// somewhere else
//
System.out.println(tr("Error: Connection to proxy ''{0}'' for URI ''{1}'' failed. Exception was: {2}", sa.toString(), uri.toString(), ioe.toString()));
}
@Override
public List<Proxy> select(URI uri) {
Proxy proxy;
switch(proxyPolicy) {
case USE_SYSTEM_SETTINGS:
if (!JVM_WILL_USE_SYSTEM_PROXIES) {
System.err.println(tr("Warning: the JVM is not configured to lookup proxies from the system settings. The property ''java.net.useSystemProxies'' was missing at startup time. Won't use a proxy."));
return Collections.singletonList(Proxy.NO_PROXY);
}
// delegate to the former proxy selector
List<Proxy> ret = delegate.select(uri);
return ret;
case NO_PROXY:
return Collections.singletonList(Proxy.NO_PROXY);
case USE_HTTP_PROXY:
if (httpProxySocketAddress == null)
return Collections.singletonList(Proxy.NO_PROXY);
proxy = new Proxy(Type.HTTP, httpProxySocketAddress);
return Collections.singletonList(proxy);
case USE_SOCKS_PROXY:
if (socksProxySocketAddress == null)
return Collections.singletonList(Proxy.NO_PROXY);
proxy = new Proxy(Type.SOCKS, socksProxySocketAddress);
return Collections.singletonList(proxy);
}
// should not happen
return null;
}
}
| true | true | public void initFromPreferences() {
String value = Main.pref.get(ProxyPreferences.PROXY_POLICY);
if (value == null) {
System.err.println(tr("Warning: no preference ''{0}'' found. Will use no proxy.", ProxyPreferences.PROXY_POLICY));
proxyPolicy = ProxyPolicy.NO_PROXY;
} else {
proxyPolicy= ProxyPolicy.fromName(value);
if (proxyPolicy == null) {
System.err.println(tr("Warning: unexpected value for preference ''{0}'' found. Got ''{1}''. Will use no proxy.", ProxyPreferences.PROXY_POLICY, value));
proxyPolicy = ProxyPolicy.NO_PROXY;
}
}
String host = Main.pref.get(ProxyPreferences.PROXY_HTTP_HOST, null);
int port = parseProxyPortValue(ProxyPreferences.PROXY_HTTP_PORT, Main.pref.get(ProxyPreferences.PROXY_HTTP_PORT, null));
if (host != null && ! host.trim().equals("") && port > 0) {
httpProxySocketAddress = new InetSocketAddress(host,port);
} else {
httpProxySocketAddress = null;
if (proxyPolicy.equals(ProxyPolicy.USE_HTTP_PROXY)) {
System.err.println(tr("Warning: Unexpected parameters for HTTP proxy. Got host ''{0}'' and port ''{1}''. Proxy won't be used", host, port));
}
}
host = Main.pref.get(ProxyPreferences.PROXY_SOCKS_HOST, null);
port = parseProxyPortValue(ProxyPreferences.PROXY_SOCKS_PORT, Main.pref.get(ProxyPreferences.PROXY_SOCKS_PORT, null));
if (host != null && ! host.trim().equals("") && port > 0) {
socksProxySocketAddress = new InetSocketAddress(host,port);
} else {
socksProxySocketAddress = null;
if (proxyPolicy.equals(ProxyPolicy.USE_SOCKS_PROXY)) {
System.err.println(tr("Warning: Unexpected parameters for SOCKS proxy. Got host ''{0}'' and port ''{1}''. Proxy won't be used", host, port));
}
}
}
| public void initFromPreferences() {
String value = Main.pref.get(ProxyPreferences.PROXY_POLICY);
if (value.length() == 0) {
System.err.println(tr("Warning: no preference ''{0}'' found. Will use no proxy.", ProxyPreferences.PROXY_POLICY));
proxyPolicy = ProxyPolicy.NO_PROXY;
} else {
proxyPolicy= ProxyPolicy.fromName(value);
if (proxyPolicy == null) {
System.err.println(tr("Warning: unexpected value for preference ''{0}'' found. Got ''{1}''. Will use no proxy.", ProxyPreferences.PROXY_POLICY, value));
proxyPolicy = ProxyPolicy.NO_PROXY;
}
}
String host = Main.pref.get(ProxyPreferences.PROXY_HTTP_HOST, null);
int port = parseProxyPortValue(ProxyPreferences.PROXY_HTTP_PORT, Main.pref.get(ProxyPreferences.PROXY_HTTP_PORT, null));
if (host != null && ! host.trim().equals("") && port > 0) {
httpProxySocketAddress = new InetSocketAddress(host,port);
} else {
httpProxySocketAddress = null;
if (proxyPolicy.equals(ProxyPolicy.USE_HTTP_PROXY)) {
System.err.println(tr("Warning: Unexpected parameters for HTTP proxy. Got host ''{0}'' and port ''{1}''. Proxy won't be used", host, port));
}
}
host = Main.pref.get(ProxyPreferences.PROXY_SOCKS_HOST, null);
port = parseProxyPortValue(ProxyPreferences.PROXY_SOCKS_PORT, Main.pref.get(ProxyPreferences.PROXY_SOCKS_PORT, null));
if (host != null && ! host.trim().equals("") && port > 0) {
socksProxySocketAddress = new InetSocketAddress(host,port);
} else {
socksProxySocketAddress = null;
if (proxyPolicy.equals(ProxyPolicy.USE_SOCKS_PROXY)) {
System.err.println(tr("Warning: Unexpected parameters for SOCKS proxy. Got host ''{0}'' and port ''{1}''. Proxy won't be used", host, port));
}
}
}
|
diff --git a/org/jruby/RubyFixnum.java b/org/jruby/RubyFixnum.java
index ea0c84f54..abc67ef47 100644
--- a/org/jruby/RubyFixnum.java
+++ b/org/jruby/RubyFixnum.java
@@ -1,360 +1,362 @@
/*
* RubyFixnum.java - Implementation of the Fixnum class.
* Created on 04. Juli 2001, 22:53
*
* Copyright (C) 2001, 2002 Jan Arne Petersen, Alan Moore, Benoit Cerrina
* Jan Arne Petersen <[email protected]>
* Alan Moore <[email protected]>
* Benoit Cerrina <[email protected]>
*
* JRuby - http://jruby.sourceforge.net
*
* This file is part of JRuby
*
* JRuby 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.
*
* JRuby 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 JRuby; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
package org.jruby;
import org.jruby.runtime.*;
import org.jruby.marshal.*;
/** Implementation of the Fixnum class.
*
* @author jpetersen
* @version $Revision$
*/
public class RubyFixnum extends RubyInteger {
private long value;
private static int BIT_SIZE = 63;
public RubyFixnum(Ruby ruby) {
this(ruby, 0);
}
public RubyFixnum(Ruby ruby, long value) {
super(ruby, ruby.getClasses().getFixnumClass());
this.value = value;
}
public static RubyClass createFixnumClass(Ruby ruby) {
RubyClass fixnumClass = ruby.defineClass("Fixnum", ruby.getClasses().getIntegerClass());
fixnumClass.includeModule(ruby.getClasses().getPrecisionModule());
fixnumClass.defineSingletonMethod("induced_from", CallbackFactory.getSingletonMethod(RubyFixnum.class, "induced_from", RubyObject.class));
fixnumClass.defineMethod("to_f", CallbackFactory.getMethod(RubyFixnum.class, "to_f"));
fixnumClass.defineMethod("to_s", CallbackFactory.getMethod(RubyFixnum.class, "to_s"));
fixnumClass.defineMethod("to_str", CallbackFactory.getMethod(RubyFixnum.class, "to_s"));
fixnumClass.defineMethod("taint", CallbackFactory.getSelfMethod(0));
fixnumClass.defineMethod("freeze", CallbackFactory.getSelfMethod(0));
fixnumClass.defineMethod("<<", CallbackFactory.getMethod(RubyFixnum.class, "op_lshift", RubyObject.class));
fixnumClass.defineMethod(">>", CallbackFactory.getMethod(RubyFixnum.class, "op_rshift", RubyObject.class));
fixnumClass.defineMethod("+", CallbackFactory.getMethod(RubyFixnum.class, "op_plus", RubyObject.class));
fixnumClass.defineMethod("-", CallbackFactory.getMethod(RubyFixnum.class, "op_minus", RubyObject.class));
fixnumClass.defineMethod("*", CallbackFactory.getMethod(RubyFixnum.class, "op_mul", RubyObject.class));
fixnumClass.defineMethod("/", CallbackFactory.getMethod(RubyFixnum.class, "op_div", RubyObject.class));
fixnumClass.defineMethod("%", CallbackFactory.getMethod(RubyFixnum.class, "op_mod", RubyObject.class));
fixnumClass.defineMethod("**", CallbackFactory.getMethod(RubyFixnum.class, "op_pow", RubyObject.class));
fixnumClass.defineMethod("==", CallbackFactory.getMethod(RubyFixnum.class, "op_equal", RubyObject.class));
+ fixnumClass.defineMethod("eql?", CallbackFactory.getMethod(RubyFixnum.class, "op_equal", RubyObject.class));
+ fixnumClass.defineMethod("equal?", CallbackFactory.getMethod(RubyFixnum.class, "op_equal", RubyObject.class));
fixnumClass.defineMethod("<=>", CallbackFactory.getMethod(RubyFixnum.class, "op_cmp", RubyObject.class));
fixnumClass.defineMethod(">", CallbackFactory.getMethod(RubyFixnum.class, "op_gt", RubyObject.class));
fixnumClass.defineMethod(">=", CallbackFactory.getMethod(RubyFixnum.class, "op_ge", RubyObject.class));
fixnumClass.defineMethod("<", CallbackFactory.getMethod(RubyFixnum.class, "op_lt", RubyObject.class));
fixnumClass.defineMethod("<=", CallbackFactory.getMethod(RubyFixnum.class, "op_le", RubyObject.class));
fixnumClass.defineMethod("&", CallbackFactory.getMethod(RubyFixnum.class, "op_and", RubyObject.class));
fixnumClass.defineMethod("|", CallbackFactory.getMethod(RubyFixnum.class, "op_or", RubyInteger.class));
fixnumClass.defineMethod("^", CallbackFactory.getMethod(RubyFixnum.class, "op_xor", RubyInteger.class));
fixnumClass.defineMethod("size", CallbackFactory.getMethod(RubyFixnum.class, "size"));
fixnumClass.defineMethod("[]", CallbackFactory.getMethod(RubyFixnum.class, "aref", RubyInteger.class));
return fixnumClass;
}
public Class getJavaClass() {
return Long.TYPE;
}
public double getDoubleValue() {
return (double) value;
}
public long getLongValue() {
return value;
}
public static RubyFixnum zero(Ruby ruby) {
return newFixnum(ruby, 0);
}
public static RubyFixnum one(Ruby ruby) {
return newFixnum(ruby, 1);
}
public static RubyFixnum minus_one(Ruby ruby) {
return newFixnum(ruby, -1);
}
protected int compareValue(RubyNumeric other) {
if (other instanceof RubyBignum) {
return ((RubyBignum) other).compareValue(this) * -1;
} else if (other instanceof RubyFloat) {
double otherVal = other.getDoubleValue();
double thisVal = getDoubleValue();
return thisVal > otherVal ? 1 : thisVal < otherVal ? -1 : 0;
} else {
long otherVal = other.getLongValue();
return getLongValue() > otherVal ? 1 : getLongValue() < otherVal ? -1 : 0;
}
}
public int hashCode() {
return (((int) value) ^ (int) (value >> 32));
}
// Methods of the Fixnum Class (fix_*):
public static RubyFixnum newFixnum(Ruby ruby, long value) {
RubyFixnum fixnum;
if (value >= 0 && value < ruby.fixnumCache.length) {
fixnum = ruby.fixnumCache[(int) value];
if (fixnum == null) {
fixnum = new RubyFixnum(ruby, value);
ruby.fixnumCache[(int) value] = fixnum;
}
} else {
fixnum = new RubyFixnum(ruby, value);
}
return fixnum;
}
public RubyFixnum newFixnum(long value) {
return newFixnum(ruby, value);
}
public static RubyInteger induced_from(Ruby ruby, RubyObject recv, RubyObject number) {
if (number instanceof RubyFixnum) {
return (RubyFixnum) number;
} else if (number instanceof RubyFloat) {
return ((RubyFloat) number).to_i();
} else if (number instanceof RubyBignum) {
return RubyFixnum.newFixnum(ruby, ((RubyBignum) number).getLongValue());
}
return (RubyFixnum) number.convertToType("Fixnum", "to_int", true);
}
public RubyNumeric op_plus(RubyObject num) {
RubyNumeric other = numericValue(num);
if (other instanceof RubyFloat) {
return RubyFloat.newFloat(getRuby(), getDoubleValue()).op_plus(other);
} else if (other instanceof RubyBignum) {
return RubyBignum.newBignum(getRuby(), value).op_plus(other);
} else {
long otherValue = other.getLongValue();
long result = value + otherValue;
if ((value < 0 && otherValue < 0 && result > 0) || (value > 0 && otherValue > 0 && result < 0)) {
return RubyBignum.newBignum(getRuby(), value).op_plus(other);
}
return newFixnum(result);
}
}
public RubyNumeric op_minus(RubyObject num) {
RubyNumeric other = numericValue(num);
if (other instanceof RubyFloat) {
return RubyFloat.newFloat(getRuby(), getDoubleValue()).op_minus(other);
} else if (other instanceof RubyBignum) {
return RubyBignum.newBignum(getRuby(), value).op_minus(other);
} else {
long otherValue = other.getLongValue();
long result = value - otherValue;
if ((value < 0 && otherValue > 0 && result > 0) || (value > 0 && otherValue < 0 && result < 0)) {
return RubyBignum.newBignum(getRuby(), value).op_minus(other);
}
return newFixnum(result);
}
}
public RubyNumeric op_mul(RubyObject num) {
RubyNumeric other = numericValue(num);
if (other instanceof RubyFloat) {
return RubyFloat.newFloat(getRuby(), getDoubleValue()).op_mul(other);
} else if (other instanceof RubyBignum) {
return RubyBignum.newBignum(getRuby(), getLongValue()).op_mul(other);
} else {
long otherValue = other.getLongValue();
long result = value * otherValue;
if (result / otherValue == value) {
return newFixnum(result);
} else {
return RubyBignum.newBignum(getRuby(), getLongValue()).op_mul(other);
}
}
}
public RubyNumeric op_div(RubyObject num) {
RubyNumeric other = numericValue(num);
if (other instanceof RubyFloat) {
return RubyFloat.newFloat(getRuby(), getDoubleValue()).op_div(other);
} else if (other instanceof RubyBignum) {
return RubyBignum.newBignum(getRuby(), getLongValue()).op_div(other);
} else {
return newFixnum(getRuby(), getLongValue() / other.getLongValue());
}
}
public RubyNumeric op_mod(RubyObject num) {
RubyNumeric other = numericValue(num);
if (other instanceof RubyFloat) {
return RubyFloat.newFloat(getRuby(), getDoubleValue()).op_mod(other);
} else if (other instanceof RubyBignum) {
return RubyBignum.newBignum(getRuby(), getLongValue()).op_mod(other);
} else {
return newFixnum(getRuby(), getLongValue() % other.getLongValue());
}
}
public RubyNumeric op_pow(RubyObject num) {
RubyNumeric other = numericValue(num);
if (other instanceof RubyFloat) {
return RubyFloat.newFloat(getRuby(), getDoubleValue()).op_pow(other);
} else {
if (other.getLongValue() == 0) {
return newFixnum(getRuby(), 1);
} else if (other.getLongValue() == 1) {
return this;
} else if (other.getLongValue() > 1) {
return RubyBignum.newBignum(getRuby(), getLongValue()).op_pow(other);
} else {
return RubyFloat.newFloat(getRuby(), getDoubleValue()).op_pow(other);
}
}
}
public RubyBoolean op_equal(RubyObject other) {
if (!(other instanceof RubyNumeric)) {
return getRuby().getFalse();
} else {
return RubyBoolean.newBoolean(getRuby(), compareValue((RubyNumeric) other) == 0);
}
}
public RubyNumeric op_cmp(RubyObject num) {
RubyNumeric other = numericValue(num);
return RubyFixnum.newFixnum(getRuby(), compareValue(other));
}
public RubyBoolean op_gt(RubyObject num) {
RubyNumeric other = numericValue(num);
return RubyBoolean.newBoolean(getRuby(), compareValue(other) > 0);
}
public RubyBoolean op_ge(RubyObject num) {
RubyNumeric other = numericValue(num);
return RubyBoolean.newBoolean(getRuby(), compareValue(other) >= 0);
}
public RubyBoolean op_lt(RubyObject num) {
RubyNumeric other = numericValue(num);
return RubyBoolean.newBoolean(getRuby(), compareValue(other) < 0);
}
public RubyBoolean op_le(RubyObject num) {
RubyNumeric other = numericValue(num);
return RubyBoolean.newBoolean(getRuby(), compareValue(other) <= 0);
}
public RubyString to_s() {
return RubyString.newString(getRuby(), String.valueOf(getLongValue()));
}
public RubyFloat to_f() {
return RubyFloat.newFloat(getRuby(), getDoubleValue());
}
public RubyInteger op_lshift(RubyObject num) {
RubyNumeric other = numericValue(num);
long width = other.getLongValue();
if (width < 0)
return op_rshift(other.op_uminus());
if (width > BIT_SIZE || value >>> (BIT_SIZE - width) > 0) {
RubyBignum lBigValue = new RubyBignum(ruby, RubyBignum.bigIntValue(this));
return lBigValue.op_lshift(other);
}
return newFixnum(value << width);
}
public RubyInteger op_rshift(RubyObject num) {
RubyNumeric other = numericValue(num);
long width = other.getLongValue();
if (width < 0)
return op_lshift(other.op_uminus());
return newFixnum(value >>> width);
}
public RubyNumeric op_and(RubyObject other) {
RubyNumeric otherNumeric = numericValue(other);
long otherLong = otherNumeric.getTruncatedLongValue();
return newFixnum(value & otherLong);
}
public RubyInteger op_or(RubyInteger other) {
if (other instanceof RubyBignum) {
return (RubyInteger) other.funcall("|", this);
}
return newFixnum(value | other.getLongValue());
}
public RubyInteger op_xor(RubyInteger other) {
if (other instanceof RubyBignum) {
return (RubyInteger) other.funcall("^", this);
}
return newFixnum(value ^ other.getLongValue());
}
/**
* @see RubyObject#equal(RubyObject)
*/
public RubyBoolean equal(RubyObject obj) {
return RubyBoolean.newBoolean(ruby, obj instanceof RubyFixnum &&
((RubyFixnum)obj).getLongValue() == getLongValue());
}
public RubyFixnum size() {
return newFixnum(4);
}
public RubyFixnum aref(RubyInteger pos) {
long mask = 1 << pos.getLongValue();
return newFixnum((value & mask) == 0 ? 0 : 1);
}
public void marshalTo(MarshalStream output) throws java.io.IOException {
if (value <= Integer.MAX_VALUE) {
output.write('i');
output.dumpInt((int) value);
} else {
output.dumpObject(RubyBignum.newBignum(ruby, value));
}
}
public static RubyFixnum unmarshalFrom(UnmarshalStream input) throws java.io.IOException {
return RubyFixnum.newFixnum(input.getRuby(),
input.unmarshalInt());
}
}
| true | true | public static RubyClass createFixnumClass(Ruby ruby) {
RubyClass fixnumClass = ruby.defineClass("Fixnum", ruby.getClasses().getIntegerClass());
fixnumClass.includeModule(ruby.getClasses().getPrecisionModule());
fixnumClass.defineSingletonMethod("induced_from", CallbackFactory.getSingletonMethod(RubyFixnum.class, "induced_from", RubyObject.class));
fixnumClass.defineMethod("to_f", CallbackFactory.getMethod(RubyFixnum.class, "to_f"));
fixnumClass.defineMethod("to_s", CallbackFactory.getMethod(RubyFixnum.class, "to_s"));
fixnumClass.defineMethod("to_str", CallbackFactory.getMethod(RubyFixnum.class, "to_s"));
fixnumClass.defineMethod("taint", CallbackFactory.getSelfMethod(0));
fixnumClass.defineMethod("freeze", CallbackFactory.getSelfMethod(0));
fixnumClass.defineMethod("<<", CallbackFactory.getMethod(RubyFixnum.class, "op_lshift", RubyObject.class));
fixnumClass.defineMethod(">>", CallbackFactory.getMethod(RubyFixnum.class, "op_rshift", RubyObject.class));
fixnumClass.defineMethod("+", CallbackFactory.getMethod(RubyFixnum.class, "op_plus", RubyObject.class));
fixnumClass.defineMethod("-", CallbackFactory.getMethod(RubyFixnum.class, "op_minus", RubyObject.class));
fixnumClass.defineMethod("*", CallbackFactory.getMethod(RubyFixnum.class, "op_mul", RubyObject.class));
fixnumClass.defineMethod("/", CallbackFactory.getMethod(RubyFixnum.class, "op_div", RubyObject.class));
fixnumClass.defineMethod("%", CallbackFactory.getMethod(RubyFixnum.class, "op_mod", RubyObject.class));
fixnumClass.defineMethod("**", CallbackFactory.getMethod(RubyFixnum.class, "op_pow", RubyObject.class));
fixnumClass.defineMethod("==", CallbackFactory.getMethod(RubyFixnum.class, "op_equal", RubyObject.class));
fixnumClass.defineMethod("<=>", CallbackFactory.getMethod(RubyFixnum.class, "op_cmp", RubyObject.class));
fixnumClass.defineMethod(">", CallbackFactory.getMethod(RubyFixnum.class, "op_gt", RubyObject.class));
fixnumClass.defineMethod(">=", CallbackFactory.getMethod(RubyFixnum.class, "op_ge", RubyObject.class));
fixnumClass.defineMethod("<", CallbackFactory.getMethod(RubyFixnum.class, "op_lt", RubyObject.class));
fixnumClass.defineMethod("<=", CallbackFactory.getMethod(RubyFixnum.class, "op_le", RubyObject.class));
fixnumClass.defineMethod("&", CallbackFactory.getMethod(RubyFixnum.class, "op_and", RubyObject.class));
fixnumClass.defineMethod("|", CallbackFactory.getMethod(RubyFixnum.class, "op_or", RubyInteger.class));
fixnumClass.defineMethod("^", CallbackFactory.getMethod(RubyFixnum.class, "op_xor", RubyInteger.class));
fixnumClass.defineMethod("size", CallbackFactory.getMethod(RubyFixnum.class, "size"));
fixnumClass.defineMethod("[]", CallbackFactory.getMethod(RubyFixnum.class, "aref", RubyInteger.class));
return fixnumClass;
}
| public static RubyClass createFixnumClass(Ruby ruby) {
RubyClass fixnumClass = ruby.defineClass("Fixnum", ruby.getClasses().getIntegerClass());
fixnumClass.includeModule(ruby.getClasses().getPrecisionModule());
fixnumClass.defineSingletonMethod("induced_from", CallbackFactory.getSingletonMethod(RubyFixnum.class, "induced_from", RubyObject.class));
fixnumClass.defineMethod("to_f", CallbackFactory.getMethod(RubyFixnum.class, "to_f"));
fixnumClass.defineMethod("to_s", CallbackFactory.getMethod(RubyFixnum.class, "to_s"));
fixnumClass.defineMethod("to_str", CallbackFactory.getMethod(RubyFixnum.class, "to_s"));
fixnumClass.defineMethod("taint", CallbackFactory.getSelfMethod(0));
fixnumClass.defineMethod("freeze", CallbackFactory.getSelfMethod(0));
fixnumClass.defineMethod("<<", CallbackFactory.getMethod(RubyFixnum.class, "op_lshift", RubyObject.class));
fixnumClass.defineMethod(">>", CallbackFactory.getMethod(RubyFixnum.class, "op_rshift", RubyObject.class));
fixnumClass.defineMethod("+", CallbackFactory.getMethod(RubyFixnum.class, "op_plus", RubyObject.class));
fixnumClass.defineMethod("-", CallbackFactory.getMethod(RubyFixnum.class, "op_minus", RubyObject.class));
fixnumClass.defineMethod("*", CallbackFactory.getMethod(RubyFixnum.class, "op_mul", RubyObject.class));
fixnumClass.defineMethod("/", CallbackFactory.getMethod(RubyFixnum.class, "op_div", RubyObject.class));
fixnumClass.defineMethod("%", CallbackFactory.getMethod(RubyFixnum.class, "op_mod", RubyObject.class));
fixnumClass.defineMethod("**", CallbackFactory.getMethod(RubyFixnum.class, "op_pow", RubyObject.class));
fixnumClass.defineMethod("==", CallbackFactory.getMethod(RubyFixnum.class, "op_equal", RubyObject.class));
fixnumClass.defineMethod("eql?", CallbackFactory.getMethod(RubyFixnum.class, "op_equal", RubyObject.class));
fixnumClass.defineMethod("equal?", CallbackFactory.getMethod(RubyFixnum.class, "op_equal", RubyObject.class));
fixnumClass.defineMethod("<=>", CallbackFactory.getMethod(RubyFixnum.class, "op_cmp", RubyObject.class));
fixnumClass.defineMethod(">", CallbackFactory.getMethod(RubyFixnum.class, "op_gt", RubyObject.class));
fixnumClass.defineMethod(">=", CallbackFactory.getMethod(RubyFixnum.class, "op_ge", RubyObject.class));
fixnumClass.defineMethod("<", CallbackFactory.getMethod(RubyFixnum.class, "op_lt", RubyObject.class));
fixnumClass.defineMethod("<=", CallbackFactory.getMethod(RubyFixnum.class, "op_le", RubyObject.class));
fixnumClass.defineMethod("&", CallbackFactory.getMethod(RubyFixnum.class, "op_and", RubyObject.class));
fixnumClass.defineMethod("|", CallbackFactory.getMethod(RubyFixnum.class, "op_or", RubyInteger.class));
fixnumClass.defineMethod("^", CallbackFactory.getMethod(RubyFixnum.class, "op_xor", RubyInteger.class));
fixnumClass.defineMethod("size", CallbackFactory.getMethod(RubyFixnum.class, "size"));
fixnumClass.defineMethod("[]", CallbackFactory.getMethod(RubyFixnum.class, "aref", RubyInteger.class));
return fixnumClass;
}
|
diff --git a/ev/endrov/flowMeasure/ParticleMeasureCenterOfMass.java b/ev/endrov/flowMeasure/ParticleMeasureCenterOfMass.java
index 8901af17..8df12b99 100644
--- a/ev/endrov/flowMeasure/ParticleMeasureCenterOfMass.java
+++ b/ev/endrov/flowMeasure/ParticleMeasureCenterOfMass.java
@@ -1,100 +1,100 @@
/***
* Copyright (C) 2010 Johan Henriksson
* This code is under the Endrov / BSD license. See www.endrov.net
* for the full text and how to cite.
*/
package endrov.flowMeasure;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import javax.vecmath.Vector3d;
import endrov.imageset.EvStack;
/**
* Measure: center of mass
* @author Johan Henriksson
*
*/
public class ParticleMeasureCenterOfMass implements ParticleMeasure.MeasurePropertyType
{
private static String propertyName="com";
public void analyze(EvStack stackValue, EvStack stackMask, ParticleMeasure.FrameInfo info)
{
//TODO should thickness be taken into account? world or pixel coordinates?
HashMap<Integer,Vector3d> sum=new HashMap<Integer, Vector3d>();
HashMap<Integer,Integer> vol=new HashMap<Integer, Integer>();
//TODO: a special map for this case could speed up plenty.
//also: only accept integer IDs? this would speed up hashing and indexing.
//can be made even faster as a non-hash
for(int az=0;az<stackValue.getDepth();az++)
{
double[] arrValue=stackValue.getInt(az).getPixels().convertToDouble(true).getArrayDouble();
int[] arrID=stackMask.getInt(az).getPixels().convertToInt(true).getArrayInt();
int w=stackValue.getWidth();
int h=stackValue.getHeight();
for(int ay=0;ay<h;ay++)
for(int ax=0;ax<w;ax++)
{
int index=ay*w+ax;
double v=arrValue[index];
int id=arrID[index];
if(id!=0)
{
Vector3d lastSum=sum.get(id);
if(lastSum==null)
sum.put(id,lastSum=new Vector3d());
lastSum.add(new Vector3d(ax*v,ay*v,az*v));
Integer lastVol=vol.get(id);
if(lastVol==null)
lastVol=0;
vol.put(id, lastVol+1);
}
}
}
//Write into particles
for(int id:sum.keySet())
{
HashMap<String, Object> p=info.getCreate(id);
Vector3d s=sum.get(id);
double v=vol.get(id);
- p.put(propertyName+"X", s.getX()/v);
- p.put(propertyName+"Y", s.getY()/v);
- p.put(propertyName+"Z", s.getZ()/v);
+ p.put(propertyName+"X", s.x/v);
+ p.put(propertyName+"Y", s.y/v);
+ p.put(propertyName+"Z", s.z/v);
}
}
public String getDesc()
{
return "Center of mass (takes intensity into account)";
}
public Set<String> getColumns()
{
HashSet<String> set=new HashSet<String>();
set.add(propertyName+"X");
set.add(propertyName+"Y");
set.add(propertyName+"Z");
return set;
}
}
| true | true | public void analyze(EvStack stackValue, EvStack stackMask, ParticleMeasure.FrameInfo info)
{
//TODO should thickness be taken into account? world or pixel coordinates?
HashMap<Integer,Vector3d> sum=new HashMap<Integer, Vector3d>();
HashMap<Integer,Integer> vol=new HashMap<Integer, Integer>();
//TODO: a special map for this case could speed up plenty.
//also: only accept integer IDs? this would speed up hashing and indexing.
//can be made even faster as a non-hash
for(int az=0;az<stackValue.getDepth();az++)
{
double[] arrValue=stackValue.getInt(az).getPixels().convertToDouble(true).getArrayDouble();
int[] arrID=stackMask.getInt(az).getPixels().convertToInt(true).getArrayInt();
int w=stackValue.getWidth();
int h=stackValue.getHeight();
for(int ay=0;ay<h;ay++)
for(int ax=0;ax<w;ax++)
{
int index=ay*w+ax;
double v=arrValue[index];
int id=arrID[index];
if(id!=0)
{
Vector3d lastSum=sum.get(id);
if(lastSum==null)
sum.put(id,lastSum=new Vector3d());
lastSum.add(new Vector3d(ax*v,ay*v,az*v));
Integer lastVol=vol.get(id);
if(lastVol==null)
lastVol=0;
vol.put(id, lastVol+1);
}
}
}
//Write into particles
for(int id:sum.keySet())
{
HashMap<String, Object> p=info.getCreate(id);
Vector3d s=sum.get(id);
double v=vol.get(id);
p.put(propertyName+"X", s.getX()/v);
p.put(propertyName+"Y", s.getY()/v);
p.put(propertyName+"Z", s.getZ()/v);
}
}
| public void analyze(EvStack stackValue, EvStack stackMask, ParticleMeasure.FrameInfo info)
{
//TODO should thickness be taken into account? world or pixel coordinates?
HashMap<Integer,Vector3d> sum=new HashMap<Integer, Vector3d>();
HashMap<Integer,Integer> vol=new HashMap<Integer, Integer>();
//TODO: a special map for this case could speed up plenty.
//also: only accept integer IDs? this would speed up hashing and indexing.
//can be made even faster as a non-hash
for(int az=0;az<stackValue.getDepth();az++)
{
double[] arrValue=stackValue.getInt(az).getPixels().convertToDouble(true).getArrayDouble();
int[] arrID=stackMask.getInt(az).getPixels().convertToInt(true).getArrayInt();
int w=stackValue.getWidth();
int h=stackValue.getHeight();
for(int ay=0;ay<h;ay++)
for(int ax=0;ax<w;ax++)
{
int index=ay*w+ax;
double v=arrValue[index];
int id=arrID[index];
if(id!=0)
{
Vector3d lastSum=sum.get(id);
if(lastSum==null)
sum.put(id,lastSum=new Vector3d());
lastSum.add(new Vector3d(ax*v,ay*v,az*v));
Integer lastVol=vol.get(id);
if(lastVol==null)
lastVol=0;
vol.put(id, lastVol+1);
}
}
}
//Write into particles
for(int id:sum.keySet())
{
HashMap<String, Object> p=info.getCreate(id);
Vector3d s=sum.get(id);
double v=vol.get(id);
p.put(propertyName+"X", s.x/v);
p.put(propertyName+"Y", s.y/v);
p.put(propertyName+"Z", s.z/v);
}
}
|
diff --git a/chef/core/src/main/java/org/jclouds/karaf/chef/core/ChefHelper.java b/chef/core/src/main/java/org/jclouds/karaf/chef/core/ChefHelper.java
index c28756c..b409e6b 100644
--- a/chef/core/src/main/java/org/jclouds/karaf/chef/core/ChefHelper.java
+++ b/chef/core/src/main/java/org/jclouds/karaf/chef/core/ChefHelper.java
@@ -1,371 +1,372 @@
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds 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.jclouds.karaf.chef.core;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.io.Files;
import com.google.inject.Module;
import org.jclouds.ContextBuilder;
import org.jclouds.apis.ApiMetadata;
import org.jclouds.apis.Apis;
import org.jclouds.chef.ChefContext;
import org.jclouds.chef.ChefService;
import org.jclouds.chef.config.ChefProperties;
import org.jclouds.logging.slf4j.config.SLF4JLoggingModule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import static com.google.common.base.Charsets.UTF_8;
public class ChefHelper {
private static final Logger LOGGER = LoggerFactory.getLogger(ChefHelper.class);
public static final String JCLOUDS_CHEF_API = "JCLOUDS_CHEF_API";
public static final String JCLOUDS_CHEF_CLIENT_NAME = "JCLOUDS_CHEF_CLIENT_NAME";
public static final String JCLOUDS_CHEF_CLIENT_KEY_FILE = "JCLOUDS_CHEF_CLIENT_KEY_FILE";
public static final String JCLOUDS_CHEF_CLIENT_CREDENTIAL = "JCLOUDS_CHEF_CLIENT_CREDENTIAL";
public static final String JCLOUDS_CHEF_VALIDATOR_NAME = "JCLOUDS_CHEF_VALIDATOR_NAME";
public static final String JCLOUDS_CHEF_VALIDATOR_KEY_FILE = "JCLOUDS_CHEF_VALIDATOR_KEY_FILE";
public static final String JCLOUDS_CHEF_VALIDATOR_CREDENTIAL = "JCLOUDS_CHEF_VALIDATOR_CREDENTIAL";
public static final String JCLOUDS_CHEF_ENDPOINT = "JCLOUDS_CHEF_ENDPOINT";
private ChefHelper() {
//Utility Class
}
/**
* Returns the provider value and falls back to env if the specified value is null.
*
* @param api
* @return
*/
public static String getChefApi(String api) {
if (api != null) {
return api;
} else {
return System.getenv(JCLOUDS_CHEF_API);
}
}
/**
* Returns the client name value and falls back to env if the specified value is null.
*
* @param clientName
* @return
*/
public static String getClientName(String clientName) {
if (clientName != null) {
return clientName;
} else {
return System.getenv(JCLOUDS_CHEF_CLIENT_NAME);
}
}
/**
* Returns the validator credential value and falls back to env if the specified value is null.
*
* @param clientCredential
* @return
*/
public static String getClientCredential(String clientCredential) {
if (clientCredential != null) {
return clientCredential;
} else {
return System.getenv(JCLOUDS_CHEF_CLIENT_CREDENTIAL);
}
}
/**
* Returns the client pem location value and falls back to env if the specified value is null.
*
* @param clientKeyFile
* @return
*/
public static String getClientKeyFile(String clientKeyFile) {
if (clientKeyFile != null) {
return clientKeyFile;
} else {
return System.getenv(JCLOUDS_CHEF_CLIENT_KEY_FILE);
}
}
/**
* Returns the validator name value and falls back to env if the specified value is null.
*
* @param validatorName
* @return
*/
public static String getValidatorName(String validatorName) {
if (validatorName != null) {
return validatorName;
} else {
return System.getenv(JCLOUDS_CHEF_VALIDATOR_NAME);
}
}
/**
* Returns the validator credential value and falls back to env if the specified value is null.
*
* @param validatorCredential
* @return
*/
public static String getValidatorCredential(String validatorCredential) {
if (validatorCredential != null) {
return validatorCredential;
} else {
return System.getenv(JCLOUDS_CHEF_VALIDATOR_CREDENTIAL);
}
}
/**
* Returns the validator pem localtion value and falls back to env if the specified value is null.
*
* @param validatorKeyFile
* @return
*/
public static String getValidatorKeyFile(String validatorKeyFile) {
if (validatorKeyFile != null) {
return validatorKeyFile;
} else {
return System.getenv(JCLOUDS_CHEF_VALIDATOR_KEY_FILE);
}
}
/**
* Returns the endpoint value and falls back to env if the specified value is null.
*
* @param endpoint
* @return
*/
public static String getChefEndpoint(String endpoint) {
if (endpoint != null) {
return endpoint;
} else {
return System.getenv(JCLOUDS_CHEF_ENDPOINT);
}
}
/**
* Chooses a {@link ChefService} that matches the specified a service id or a api.
*
* @param id
* @param api
* @param services
* @return
*/
public static ChefService getChefService(String id, String api, List<ChefService> services) {
if (!Strings.isNullOrEmpty(id)) {
ChefService service = null;
for (ChefService svc : services) {
if (id.equals(svc.getContext().getName())) {
service = svc;
break;
}
}
if (service == null) {
throw new IllegalArgumentException("No chef service with id" + id + " found.");
}
return service;
}
if (!Strings.isNullOrEmpty(api)) {
ChefService service = null;
for (ChefService svc : services) {
if (api.equals(svc.getContext().getId())) {
service = svc;
break;
}
}
if (service == null) {
throw new IllegalArgumentException("No Api named " + api + " found.");
}
return service;
} else {
if (services.size() == 0) {
throw new IllegalArgumentException("No apis are present. Note: It takes a couple of seconds for the provider to initialize.");
} else if (services.size() != 1) {
StringBuilder sb = new StringBuilder();
for (ChefService svc : services) {
if (sb.length() > 0) {
sb.append(", ");
}
sb.append(svc.getContext().getId());
}
throw new IllegalArgumentException("Multiple apis are present, please select one using the--api argument in the following values: " + sb.toString());
} else {
return services.get(0);
}
}
}
/**
* Creates a {@link ChefService} just by using Environmental variables.
*
* @return
*/
public static ChefService createChefServiceFromEnvironment() {
return findOrCreateChefService(null, null, null, null, null, null, null, null, null, Lists.<ChefService>newArrayList());
}
public static ChefService findOrCreateChefService(String api, String name, String clientName, String clientCredential, String clientKeyFile, String validatorName, String validatorCredential, String validatorKeyFile, String endpoint, List<ChefService> chefServices) {
if ((name == null && api == null) && (chefServices != null && chefServices.size() == 1)) {
return chefServices.get(0);
}
ChefService chefService = null;
String apiValue = ChefHelper.getChefApi(api);
String clientNameValue = ChefHelper.getClientName(clientName);
String clientCredentialValue = ChefHelper.getClientCredential(clientCredential);
- String clientKeyFileValue = ChefHelper.getClientName(clientKeyFile);
- String validatorNameValue = ChefHelper.getClientName(validatorName);
+ String clientKeyFileValue = ChefHelper.getClientKeyFile(clientKeyFile);
+ String validatorNameValue = ChefHelper.getValidatorName(validatorName);
String validatorCredentialValue = ChefHelper.getValidatorCredential(validatorCredential);
- String validatorKeyFileValue = ChefHelper.getClientName(validatorKeyFile);
+ String validatorKeyFileValue = ChefHelper.getValidatorKeyFile(validatorKeyFile);
String endpointValue = ChefHelper.getChefEndpoint(endpoint);
boolean contextNameProvided = !Strings.isNullOrEmpty(name);
boolean canCreateService = (!Strings.isNullOrEmpty(clientNameValue) || !Strings.isNullOrEmpty(clientKeyFileValue))
&& !Strings.isNullOrEmpty(validatorNameValue) && !Strings.isNullOrEmpty(validatorKeyFileValue);
apiValue = !Strings.isNullOrEmpty(apiValue) ? apiValue : "chef";
+ name = !Strings.isNullOrEmpty(name) ? name : apiValue;
try {
chefService = ChefHelper.getChefService(name, apiValue, chefServices);
} catch (Throwable t) {
if (contextNameProvided) {
throw new RuntimeException("Could not find chef service with id:" + name);
} else if (!canCreateService) {
StringBuilder sb = new StringBuilder();
sb.append("Insufficient information to create chef service:").append("\n");
if (apiValue == null) {
sb.append(
"Missing provider or api. Please specify either using the --api options, or the JCLOUDS_CHEF_API environmental variables.")
.append("\n");
}
if (clientNameValue == null) {
sb.append(
"Missing client name. Please specify either using the --client-name option, or the JCLOUDS_CHEF_CLIENT_NAME environmental variable.")
.append("\n");
}
if (clientKeyFileValue == null) {
sb.append(
"Missing client credential. Please specify either using the --client-key-file option, or the JCLOUDS_CHEF_CLIENT_KEY_FILE environmental variable.")
.append("\n");
}
if (validatorName == null) {
sb.append(
"Missing validator name. Please specify either using the --validator-name option, or the JCLOUDS_CHEF_VALIDATOR_NAME environmental variable.")
.append("\n");
}
if (validatorKeyFile == null) {
sb.append(
"Missing validator credential. Please specify either using the --validator-key-file option, or the JCLOUDS_CHEF_VALIDATOR_KEY_FILE environmental variable.")
.append("\n");
}
throw new RuntimeException(sb.toString());
}
}
if (chefService == null && canCreateService) {
try {
- chefService = ChefHelper.createChefService(Apis.withId(apiValue), name, clientNameValue, clientCredentialValue, clientKeyFile, validatorNameValue, validatorCredentialValue, validatorKeyFileValue, endpointValue);
+ chefService = ChefHelper.createChefService(Apis.withId(apiValue), name, clientNameValue, clientCredentialValue, clientKeyFileValue, validatorNameValue, validatorCredentialValue, validatorKeyFileValue, endpointValue);
} catch (Exception ex) {
throw new RuntimeException("Failed to create service:" + ex.getMessage());
}
}
return chefService;
}
public static ChefService createChefService(ApiMetadata apiMetadata, String name, String clientName, String clientCredential, String clientKeyFile, String validatorName, String validatorCredential, String validatorKeyFile, String endpoint) throws Exception {
if (Strings.isNullOrEmpty(clientName) && apiMetadata != null && !apiMetadata.getDefaultCredential().isPresent()) {
LOGGER.warn("No client specified for api {}.", apiMetadata.getId());
return null;
}
if (Strings.isNullOrEmpty(validatorName) && apiMetadata != null && !apiMetadata.getDefaultCredential().isPresent()) {
LOGGER.warn("No validator name specified for api {}.", apiMetadata.getId());
return null;
}
if (Strings.isNullOrEmpty(validatorCredential) && !Strings.isNullOrEmpty(validatorKeyFile)) {
validatorCredential = credentialsFromPath(validatorKeyFile);
}
if (Strings.isNullOrEmpty(clientCredential) && !Strings.isNullOrEmpty(clientKeyFile)) {
clientCredential = credentialsFromPath(clientKeyFile);
} else if (Strings.isNullOrEmpty(clientCredential)) {
clientCredential = credentialForClient(clientName);
}
Properties chefConfig = new Properties();
chefConfig.put(ChefProperties.CHEF_VALIDATOR_NAME, validatorName);
chefConfig.put(ChefProperties.CHEF_VALIDATOR_CREDENTIAL, validatorCredential);
ContextBuilder builder = null;
if (apiMetadata != null) {
builder = ContextBuilder.newBuilder(apiMetadata).overrides(chefConfig);
}
if (!Strings.isNullOrEmpty(endpoint)) {
builder = builder.endpoint(endpoint);
}
builder = builder.name(name).modules(ImmutableSet.<Module>of(new SLF4JLoggingModule()));
builder = builder.name(name).credentials(clientName, clientCredential).overrides(chefConfig);
ChefContext context = builder.build();
ChefService service = context.getChefService();
return service;
}
/**
* Returns credentials for client.
*
* @param client
* @return
* @throws Exception
*/
public static String credentialForClient(final String client) throws Exception {
String pemFile = System.getProperty("user.home") + "/.chef/" + client + ".pem";
return Files.toString(new File(pemFile), UTF_8);
}
/**
* Returns credentials from a specified path.
*
* @param path
* @return
* @throws Exception
*/
public static String credentialsFromPath(final String path) throws Exception {
return Files.toString(new File(path), UTF_8);
}
}
| false | true | public static ChefService findOrCreateChefService(String api, String name, String clientName, String clientCredential, String clientKeyFile, String validatorName, String validatorCredential, String validatorKeyFile, String endpoint, List<ChefService> chefServices) {
if ((name == null && api == null) && (chefServices != null && chefServices.size() == 1)) {
return chefServices.get(0);
}
ChefService chefService = null;
String apiValue = ChefHelper.getChefApi(api);
String clientNameValue = ChefHelper.getClientName(clientName);
String clientCredentialValue = ChefHelper.getClientCredential(clientCredential);
String clientKeyFileValue = ChefHelper.getClientName(clientKeyFile);
String validatorNameValue = ChefHelper.getClientName(validatorName);
String validatorCredentialValue = ChefHelper.getValidatorCredential(validatorCredential);
String validatorKeyFileValue = ChefHelper.getClientName(validatorKeyFile);
String endpointValue = ChefHelper.getChefEndpoint(endpoint);
boolean contextNameProvided = !Strings.isNullOrEmpty(name);
boolean canCreateService = (!Strings.isNullOrEmpty(clientNameValue) || !Strings.isNullOrEmpty(clientKeyFileValue))
&& !Strings.isNullOrEmpty(validatorNameValue) && !Strings.isNullOrEmpty(validatorKeyFileValue);
apiValue = !Strings.isNullOrEmpty(apiValue) ? apiValue : "chef";
try {
chefService = ChefHelper.getChefService(name, apiValue, chefServices);
} catch (Throwable t) {
if (contextNameProvided) {
throw new RuntimeException("Could not find chef service with id:" + name);
} else if (!canCreateService) {
StringBuilder sb = new StringBuilder();
sb.append("Insufficient information to create chef service:").append("\n");
if (apiValue == null) {
sb.append(
"Missing provider or api. Please specify either using the --api options, or the JCLOUDS_CHEF_API environmental variables.")
.append("\n");
}
if (clientNameValue == null) {
sb.append(
"Missing client name. Please specify either using the --client-name option, or the JCLOUDS_CHEF_CLIENT_NAME environmental variable.")
.append("\n");
}
if (clientKeyFileValue == null) {
sb.append(
"Missing client credential. Please specify either using the --client-key-file option, or the JCLOUDS_CHEF_CLIENT_KEY_FILE environmental variable.")
.append("\n");
}
if (validatorName == null) {
sb.append(
"Missing validator name. Please specify either using the --validator-name option, or the JCLOUDS_CHEF_VALIDATOR_NAME environmental variable.")
.append("\n");
}
if (validatorKeyFile == null) {
sb.append(
"Missing validator credential. Please specify either using the --validator-key-file option, or the JCLOUDS_CHEF_VALIDATOR_KEY_FILE environmental variable.")
.append("\n");
}
throw new RuntimeException(sb.toString());
}
}
if (chefService == null && canCreateService) {
try {
chefService = ChefHelper.createChefService(Apis.withId(apiValue), name, clientNameValue, clientCredentialValue, clientKeyFile, validatorNameValue, validatorCredentialValue, validatorKeyFileValue, endpointValue);
} catch (Exception ex) {
throw new RuntimeException("Failed to create service:" + ex.getMessage());
}
}
return chefService;
}
| public static ChefService findOrCreateChefService(String api, String name, String clientName, String clientCredential, String clientKeyFile, String validatorName, String validatorCredential, String validatorKeyFile, String endpoint, List<ChefService> chefServices) {
if ((name == null && api == null) && (chefServices != null && chefServices.size() == 1)) {
return chefServices.get(0);
}
ChefService chefService = null;
String apiValue = ChefHelper.getChefApi(api);
String clientNameValue = ChefHelper.getClientName(clientName);
String clientCredentialValue = ChefHelper.getClientCredential(clientCredential);
String clientKeyFileValue = ChefHelper.getClientKeyFile(clientKeyFile);
String validatorNameValue = ChefHelper.getValidatorName(validatorName);
String validatorCredentialValue = ChefHelper.getValidatorCredential(validatorCredential);
String validatorKeyFileValue = ChefHelper.getValidatorKeyFile(validatorKeyFile);
String endpointValue = ChefHelper.getChefEndpoint(endpoint);
boolean contextNameProvided = !Strings.isNullOrEmpty(name);
boolean canCreateService = (!Strings.isNullOrEmpty(clientNameValue) || !Strings.isNullOrEmpty(clientKeyFileValue))
&& !Strings.isNullOrEmpty(validatorNameValue) && !Strings.isNullOrEmpty(validatorKeyFileValue);
apiValue = !Strings.isNullOrEmpty(apiValue) ? apiValue : "chef";
name = !Strings.isNullOrEmpty(name) ? name : apiValue;
try {
chefService = ChefHelper.getChefService(name, apiValue, chefServices);
} catch (Throwable t) {
if (contextNameProvided) {
throw new RuntimeException("Could not find chef service with id:" + name);
} else if (!canCreateService) {
StringBuilder sb = new StringBuilder();
sb.append("Insufficient information to create chef service:").append("\n");
if (apiValue == null) {
sb.append(
"Missing provider or api. Please specify either using the --api options, or the JCLOUDS_CHEF_API environmental variables.")
.append("\n");
}
if (clientNameValue == null) {
sb.append(
"Missing client name. Please specify either using the --client-name option, or the JCLOUDS_CHEF_CLIENT_NAME environmental variable.")
.append("\n");
}
if (clientKeyFileValue == null) {
sb.append(
"Missing client credential. Please specify either using the --client-key-file option, or the JCLOUDS_CHEF_CLIENT_KEY_FILE environmental variable.")
.append("\n");
}
if (validatorName == null) {
sb.append(
"Missing validator name. Please specify either using the --validator-name option, or the JCLOUDS_CHEF_VALIDATOR_NAME environmental variable.")
.append("\n");
}
if (validatorKeyFile == null) {
sb.append(
"Missing validator credential. Please specify either using the --validator-key-file option, or the JCLOUDS_CHEF_VALIDATOR_KEY_FILE environmental variable.")
.append("\n");
}
throw new RuntimeException(sb.toString());
}
}
if (chefService == null && canCreateService) {
try {
chefService = ChefHelper.createChefService(Apis.withId(apiValue), name, clientNameValue, clientCredentialValue, clientKeyFileValue, validatorNameValue, validatorCredentialValue, validatorKeyFileValue, endpointValue);
} catch (Exception ex) {
throw new RuntimeException("Failed to create service:" + ex.getMessage());
}
}
return chefService;
}
|
diff --git a/dbflute/src/main/java/org/apache/torque/engine/database/model/TypeMap.java b/dbflute/src/main/java/org/apache/torque/engine/database/model/TypeMap.java
index 764046be5..ca7e8184e 100644
--- a/dbflute/src/main/java/org/apache/torque/engine/database/model/TypeMap.java
+++ b/dbflute/src/main/java/org/apache/torque/engine/database/model/TypeMap.java
@@ -1,443 +1,443 @@
package org.apache.torque.engine.database.model;
/* ====================================================================
* The Apache Software License, Version 1.1
*
* Copyright (c) 2001 The Apache Software Foundation. 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 end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Apache" and "Apache Software Foundation" and
* "Apache Turbine" must not be used to endorse or promote products
* derived from this software without prior written permission. For
* written permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* "Apache Turbine", nor may "Apache" appear in their name, without
* prior written permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
import java.sql.Types;
import java.util.Hashtable;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.seasar.dbflute.DfBuildProperties;
import org.seasar.dbflute.helper.language.DfLanguageDependencyInfo;
import org.seasar.dbflute.helper.language.metadata.LanguageMetaData;
import org.seasar.dbflute.properties.DfBasicProperties;
/**
* A class that maps JDBC types to their corresponding
* Java object types, and Java native types. Used
* by Column.java to perform object/native mappings.
*
* These are the official SQL type to Java type mappings.
* These don't quite correspond to the way the peer
* system works so we'll have to make some adjustments.
* <pre>
* ----------------------------------------------------
* JDBC Type | Java Type | CSharp Type |
* ----------------------------------------------------
* CHAR | java.lang.String | String |
* VARCHAR | java.lang.String | String |
* LONGVARCHAR | java.lang.String | String |
* NUMERIC | java.math.BigDecimal | decimal? |
* DECIMAL | java.math.BigDecimal | decimal? |
* BIT | java.lang.Boolean | bool? |
* BOOLEAN | java.lang.Boolean | bool? |
* TINYINT | java.lang.Integer | int? |
* SMALLINT | java.lang.Integer | int? |
* INTEGER | java.lang.Integer | int? |
* BIGINT | java.lang.Long | long? |
* REAL | java.math.BigDecimal | decimal? |
* FLOAT | java.math.BigDecimal | decimal? |
* DOUBLE | java.math.BigDecimal | decimal? |
* BINARY | byte[] | byte[] |
* VARBINARY | byte[] | byte[] |
* LONGVARBINARY | byte[] | byte[] |
* DATE | java.util.Date | DateTime? |
* TIME | java.sql.Time | DateTime? |
* TIMESTAMP | java.sql.Timestamp | DateTime? |
* ----------------------------------------------------
* </pre>
*/
public class TypeMap {
// ===================================================================================
// Log
// ===
/** Log instance. */
public static final Log _log = LogFactory.getLog(TypeMap.class);
// ===================================================================================
// Torque(DBFlute) Type
// ====================
public static final String CHAR = "CHAR";
public static final String VARCHAR = "VARCHAR";
public static final String LONGVARCHAR = "LONGVARCHAR";
public static final String CLOB = "CLOB";
public static final String NUMERIC = "NUMERIC";
public static final String DECIMAL = "DECIMAL";
public static final String BIT = "BIT";
public static final String BOOLEAN = "BOOLEAN";
public static final String TINYINT = "TINYINT";
public static final String SMALLINT = "SMALLINT";
public static final String INTEGER = "INTEGER";
public static final String BIGINT = "BIGINT";
public static final String REAL = "REAL";
public static final String FLOAT = "FLOAT";
public static final String DOUBLE = "DOUBLE";
public static final String BINARY = "BINARY";
public static final String VARBINARY = "VARBINARY";
public static final String LONGVARBINARY = "LONGVARBINARY";
public static final String BLOB = "BLOB";
public static final String DATE = "DATE";
public static final String TIME = "TIME";
public static final String TIMESTAMP = "TIMESTAMP";
public static final String BOOLEANCHAR = "BOOLEANCHAR";
public static final String BOOLEANINT = "BOOLEANINT";
private static final String[] TEXT_TYPES = { CHAR, VARCHAR, LONGVARCHAR, CLOB, DATE, TIME, TIMESTAMP, BOOLEANCHAR };
// ===================================================================================
// Java Type
// =========
// This is default native type(for Java).
public static final String CHAR_NATIVE_TYPE = "String";
public static final String VARCHAR_NATIVE_TYPE = "String";
public static final String LONGVARCHAR_NATIVE_TYPE = "String";
public static final String CLOB_NATIVE_TYPE = "String";
public static final String NUMERIC_NATIVE_TYPE = "java.math.BigDecimal";
public static final String DECIMAL_NATIVE_TYPE = "java.math.BigDecimal";
public static final String BIT_NATIVE_TYPE = "Boolean";
public static final String BOOLEAN_NATIVE_TYPE = "Boolean";
public static final String TINYINT_NATIVE_TYPE = "Integer";
public static final String SMALLINT_NATIVE_TYPE = "Integer";
public static final String INTEGER_NATIVE_TYPE = "Integer";
public static final String BIGINT_NATIVE_TYPE = "Long";
public static final String REAL_NATIVE_TYPE = "java.math.BigDecimal";
public static final String FLOAT_NATIVE_TYPE = "java.math.BigDecimal";
public static final String DOUBLE_NATIVE_TYPE = "java.math.BigDecimal";
public static final String BINARY_NATIVE_TYPE = "byte[]";
public static final String VARBINARY_NATIVE_TYPE = "byte[]";
public static final String LONGVARBINARY_NATIVE_TYPE = "byte[]";
public static final String BLOB_NATIVE_TYPE = "byte[]";
public static final String DATE_NATIVE_TYPE = "java.util.Date";
public static final String TIME_NATIVE_TYPE = "java.sql.Time";
public static final String TIMESTAMP_NATIVE_TYPE = "java.sql.Timestamp";
public static final String BOOLEANCHAR_NATIVE_TYPE = "Boolean";
public static final String BOOLEANINT_NATIVE_TYPE = "Boolean";
// ===================================================================================
// Type Map
// ========
private static Hashtable<String, String> _torqueTypeToJavaNativeMap = null;
private static Hashtable<Integer, String> _jdbcTypeToTorqueTypeMap = null;
private static Hashtable<String, String> _torqueTypeToFlexNativeMap = null;
// ===================================================================================
// Property StringJdbcTypeToJavaNativeMap
// ======================================
protected static final Map<String, Object> _propertyTorqueTypeToJavaNativeMap;
static {
final DfBuildProperties prop = DfBuildProperties.getInstance();
_propertyTorqueTypeToJavaNativeMap = prop.getTypeMappingProperties().getJdbcToJavaNative();
}
// ===================================================================================
// Initialized Mark
// ================
private static boolean _initialized = false;
// ===================================================================================
// Initialize
// ==========
/**
* Initializes the SQL to Java map so that it
* can be used by client code.
*/
public synchronized static void initialize() {
if (_initialized) {
return;
}
/*
* Create JDBC -> native Java type mappings.
*/
_torqueTypeToJavaNativeMap = new Hashtable<String, String>();
// Default types are for Java.
_torqueTypeToJavaNativeMap.put(CHAR, findJavaNative(CHAR, CHAR_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(VARCHAR, findJavaNative(VARCHAR, VARCHAR_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(LONGVARCHAR, findJavaNative(LONGVARCHAR, LONGVARCHAR_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(CLOB, findJavaNative(CLOB, CLOB_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(NUMERIC, findJavaNative(NUMERIC, getDefaultNumericJavaType()));
_torqueTypeToJavaNativeMap.put(DECIMAL, findJavaNative(DECIMAL, DECIMAL_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(BIT, findJavaNative(BIT, BIT_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(BOOLEAN, findJavaNative(BOOLEAN, BOOLEAN_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(TINYINT, findJavaNative(TINYINT, TINYINT_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(SMALLINT, findJavaNative(SMALLINT, SMALLINT_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(INTEGER, findJavaNative(INTEGER, INTEGER_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(BIGINT, findJavaNative(BIGINT, BIGINT_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(REAL, findJavaNative(REAL, REAL_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(FLOAT, findJavaNative(FLOAT, FLOAT_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(DOUBLE, findJavaNative(DOUBLE, DOUBLE_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(BINARY, findJavaNative(BINARY, BINARY_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(VARBINARY, findJavaNative(VARBINARY, VARBINARY_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(LONGVARBINARY, findJavaNative(LONGVARBINARY, LONGVARBINARY_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(BLOB, findJavaNative(BLOB, BLOB_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(DATE, findJavaNative(DATE, DATE_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(TIME, findJavaNative(TIME, TIME_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(TIMESTAMP, findJavaNative(TIMESTAMP, TIMESTAMP_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(BOOLEANCHAR, findJavaNative(BOOLEANCHAR, BOOLEANCHAR_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(BOOLEANINT, findJavaNative(BOOLEANINT, BOOLEANINT_NATIVE_TYPE));
_jdbcTypeToTorqueTypeMap = new Hashtable<Integer, String>();
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.CHAR), CHAR);
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.VARCHAR), VARCHAR);
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.LONGVARCHAR), LONGVARCHAR);
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.CLOB), CLOB);
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.NUMERIC), NUMERIC);
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.DECIMAL), DECIMAL);
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.BIT), BIT);
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.BOOLEAN), BOOLEAN);
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.TINYINT), TINYINT);
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.SMALLINT), SMALLINT);
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.INTEGER), INTEGER);
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.BIGINT), BIGINT);
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.REAL), REAL);
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.FLOAT), FLOAT);
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.DOUBLE), DOUBLE);
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.BINARY), BINARY);
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.VARBINARY), VARBINARY);
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.LONGVARBINARY), LONGVARBINARY);
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.BLOB), BLOB);
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.DATE), DATE);
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.TIME), TIME);
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.TIMESTAMP), TIMESTAMP);
_torqueTypeToFlexNativeMap = new Hashtable<String, String>();
_torqueTypeToFlexNativeMap.put(CHAR, "String");
_torqueTypeToFlexNativeMap.put(VARCHAR, "String");
_torqueTypeToFlexNativeMap.put(LONGVARCHAR, "String");
_torqueTypeToFlexNativeMap.put(CLOB, "String");
_torqueTypeToFlexNativeMap.put(NUMERIC, "Number");
_torqueTypeToFlexNativeMap.put(DECIMAL, "Number");
_torqueTypeToFlexNativeMap.put(BIT, "Boolean");
_torqueTypeToFlexNativeMap.put(BOOLEAN, "Boolean");
- _torqueTypeToFlexNativeMap.put(TINYINT, "Number");
- _torqueTypeToFlexNativeMap.put(SMALLINT, "Number");
- _torqueTypeToFlexNativeMap.put(INTEGER, "Number");
+ _torqueTypeToFlexNativeMap.put(TINYINT, "int");
+ _torqueTypeToFlexNativeMap.put(SMALLINT, "int");
+ _torqueTypeToFlexNativeMap.put(INTEGER, "int");
_torqueTypeToFlexNativeMap.put(BIGINT, "Number");
_torqueTypeToFlexNativeMap.put(REAL, "Number");
_torqueTypeToFlexNativeMap.put(FLOAT, "Number");
_torqueTypeToFlexNativeMap.put(DOUBLE, "Number");
_torqueTypeToFlexNativeMap.put(BINARY, "Object");
_torqueTypeToFlexNativeMap.put(VARBINARY, "Object");
_torqueTypeToFlexNativeMap.put(LONGVARBINARY, "Object");
_torqueTypeToFlexNativeMap.put(BLOB, "Object");
_torqueTypeToFlexNativeMap.put(DATE, "Date");
_torqueTypeToFlexNativeMap.put(TIME, "Date");
_torqueTypeToFlexNativeMap.put(TIMESTAMP, "Date");
_initialized = true;
}
/**
* @param torqueType String JDBC type. (NotNull)
* @param defaultJavaNative Default java-native. (NotNull)
* @return Java-native. (NotNull: If the key does not have an element, it returns default type.)
*/
protected static String findJavaNative(String torqueType, String defaultJavaNative) {
final String javaNative = (String) _propertyTorqueTypeToJavaNativeMap.get(torqueType);
if (javaNative == null) {
return defaultJavaNative;
}
return javaNative;
}
// ===================================================================================
// Torque Type Getter
// ==================
public static String getTorqueType(Integer jdbcType) {
// Make sure the we are initialized.
if (!_initialized) {
initialize();
}
if (java.sql.Types.OTHER == jdbcType) {
String msg = "The jdbcType is unsupported: jdbcType=java.sql.Types.OTHER(" + jdbcType + ")";
throw new UnsupportedOperationException(msg);
}
if (!_jdbcTypeToTorqueTypeMap.containsKey(jdbcType)) {
String msg = "_jdbcIntToTorqueTypeMap doesn't contain the type as key: ";
msg = msg + "key=" + jdbcType + " map=" + _jdbcTypeToTorqueTypeMap;
throw new IllegalStateException(msg);
}
return _jdbcTypeToTorqueTypeMap.get(jdbcType);
}
// ===================================================================================
// Java Type Getter
// ================
public static Class<?> findJavaNativeTypeClass(String torqueType) {
final String javaTypeString = getJavaTypeAsString(torqueType);
Class<?> clazz = null;
try {
clazz = Class.forName(javaTypeString);
} catch (ClassNotFoundException e) {
final String fullName = "java.lang." + javaTypeString;
try {
clazz = Class.forName(fullName);
} catch (ClassNotFoundException e1) {
}
}
return clazz;
}
public static String findJavaNativeTypeString(String torqueType, Integer columnSize, Integer decimalDigits) {
final String javaType = getJavaTypeAsString(torqueType);
if (isAutoMappingTargetType(torqueType) && javaType.equalsIgnoreCase("$$AutoMapping$$")) {
if (decimalDigits != null && decimalDigits > 0) {
if (NUMERIC.equalsIgnoreCase(torqueType)) {
return getDefaultNumericJavaType();
} else {// DECIMAL
return getDefaultDecimalJavaType();
}
} else {
if (columnSize == null) {
return getJavaTypeAsString(TypeMap.BIGINT);
}
if (columnSize > 9) {
return getJavaTypeAsString(TypeMap.BIGINT);
} else {
return getJavaTypeAsString(TypeMap.INTEGER);
}
}
}
return javaType;
}
public static String findFlexNativeTypeString(String torqueType) {
return _torqueTypeToFlexNativeMap.get(torqueType);
}
protected static boolean isAutoMappingTargetType(String torqueType) {
return TypeMap.NUMERIC.equals(torqueType) || TypeMap.DECIMAL.equals(torqueType);
}
protected static String getDefaultNumericJavaType() {
final DfBuildProperties prop = DfBuildProperties.getInstance();
final DfBasicProperties basicProperties = prop.getBasicProperties();
if (basicProperties.isTargetLanguageJava()) {
return NUMERIC_NATIVE_TYPE;
} else {
final DfLanguageDependencyInfo languageDependencyInfo = basicProperties.getLanguageDependencyInfo();
final LanguageMetaData languageMetaData = languageDependencyInfo.createLanguageMetaData();
final Map<String, Object> jdbcToJavaNativeMap = languageMetaData.getJdbcToJavaNativeMap();
return (String) jdbcToJavaNativeMap.get(NUMERIC);
}
}
protected static String getDefaultDecimalJavaType() {
final DfBuildProperties prop = DfBuildProperties.getInstance();
final DfBasicProperties basicProperties = prop.getBasicProperties();
if (basicProperties.isTargetLanguageJava()) {
return DECIMAL_NATIVE_TYPE;
} else {
final DfLanguageDependencyInfo languageDependencyInfo = basicProperties.getLanguageDependencyInfo();
final LanguageMetaData languageMetaData = languageDependencyInfo.createLanguageMetaData();
final Map<String, Object> jdbcToJavaNativeMap = languageMetaData.getJdbcToJavaNativeMap();
return (String) jdbcToJavaNativeMap.get(DECIMAL);
}
}
protected static String getJavaTypeAsString(String torqueType) {
// Make sure the we are initialized.
if (!_initialized) {
initialize();
}
if (!_torqueTypeToJavaNativeMap.containsKey(torqueType)) {
String msg = "_torqueTypeToJavaNativeMap doesn't contain the type as key: ";
msg = msg + "key=" + torqueType + " map=" + _torqueTypeToJavaNativeMap;
_log.warn(msg);
throw new IllegalStateException(msg);
}
return _torqueTypeToJavaNativeMap.get(torqueType);
}
// ===================================================================================
// Determination
// =============
/**
* Returns true if the type is boolean in the java object and a numeric (1 or 0) in the database.
* @param type The type to check.
* @return true if the type is BOOLEANINT
*/
public static boolean isBooleanInt(String type) {
return BOOLEANINT.equals(type);
}
/**
* Returns true if the type is boolean in the
* java object and a String "Y" or "N" in the database.
* @param type The type to check.
* @return true if the type is BOOLEANCHAR
*/
public static boolean isBooleanChar(String type) {
return BOOLEANCHAR.equals(type);
}
/**
* Returns true if values for the type need to be quoted.
* @param type The type to check.
* @return true if values for the type need to be quoted.
*/
public static final boolean isTextType(String type) {
for (int i = 0; i < TEXT_TYPES.length; i++) {
if (type.equals(TEXT_TYPES[i])) {
return true;
}
}
// If we get this far, there were no matches.
return false;
}
}
| true | true | public synchronized static void initialize() {
if (_initialized) {
return;
}
/*
* Create JDBC -> native Java type mappings.
*/
_torqueTypeToJavaNativeMap = new Hashtable<String, String>();
// Default types are for Java.
_torqueTypeToJavaNativeMap.put(CHAR, findJavaNative(CHAR, CHAR_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(VARCHAR, findJavaNative(VARCHAR, VARCHAR_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(LONGVARCHAR, findJavaNative(LONGVARCHAR, LONGVARCHAR_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(CLOB, findJavaNative(CLOB, CLOB_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(NUMERIC, findJavaNative(NUMERIC, getDefaultNumericJavaType()));
_torqueTypeToJavaNativeMap.put(DECIMAL, findJavaNative(DECIMAL, DECIMAL_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(BIT, findJavaNative(BIT, BIT_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(BOOLEAN, findJavaNative(BOOLEAN, BOOLEAN_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(TINYINT, findJavaNative(TINYINT, TINYINT_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(SMALLINT, findJavaNative(SMALLINT, SMALLINT_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(INTEGER, findJavaNative(INTEGER, INTEGER_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(BIGINT, findJavaNative(BIGINT, BIGINT_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(REAL, findJavaNative(REAL, REAL_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(FLOAT, findJavaNative(FLOAT, FLOAT_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(DOUBLE, findJavaNative(DOUBLE, DOUBLE_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(BINARY, findJavaNative(BINARY, BINARY_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(VARBINARY, findJavaNative(VARBINARY, VARBINARY_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(LONGVARBINARY, findJavaNative(LONGVARBINARY, LONGVARBINARY_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(BLOB, findJavaNative(BLOB, BLOB_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(DATE, findJavaNative(DATE, DATE_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(TIME, findJavaNative(TIME, TIME_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(TIMESTAMP, findJavaNative(TIMESTAMP, TIMESTAMP_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(BOOLEANCHAR, findJavaNative(BOOLEANCHAR, BOOLEANCHAR_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(BOOLEANINT, findJavaNative(BOOLEANINT, BOOLEANINT_NATIVE_TYPE));
_jdbcTypeToTorqueTypeMap = new Hashtable<Integer, String>();
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.CHAR), CHAR);
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.VARCHAR), VARCHAR);
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.LONGVARCHAR), LONGVARCHAR);
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.CLOB), CLOB);
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.NUMERIC), NUMERIC);
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.DECIMAL), DECIMAL);
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.BIT), BIT);
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.BOOLEAN), BOOLEAN);
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.TINYINT), TINYINT);
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.SMALLINT), SMALLINT);
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.INTEGER), INTEGER);
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.BIGINT), BIGINT);
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.REAL), REAL);
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.FLOAT), FLOAT);
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.DOUBLE), DOUBLE);
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.BINARY), BINARY);
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.VARBINARY), VARBINARY);
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.LONGVARBINARY), LONGVARBINARY);
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.BLOB), BLOB);
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.DATE), DATE);
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.TIME), TIME);
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.TIMESTAMP), TIMESTAMP);
_torqueTypeToFlexNativeMap = new Hashtable<String, String>();
_torqueTypeToFlexNativeMap.put(CHAR, "String");
_torqueTypeToFlexNativeMap.put(VARCHAR, "String");
_torqueTypeToFlexNativeMap.put(LONGVARCHAR, "String");
_torqueTypeToFlexNativeMap.put(CLOB, "String");
_torqueTypeToFlexNativeMap.put(NUMERIC, "Number");
_torqueTypeToFlexNativeMap.put(DECIMAL, "Number");
_torqueTypeToFlexNativeMap.put(BIT, "Boolean");
_torqueTypeToFlexNativeMap.put(BOOLEAN, "Boolean");
_torqueTypeToFlexNativeMap.put(TINYINT, "Number");
_torqueTypeToFlexNativeMap.put(SMALLINT, "Number");
_torqueTypeToFlexNativeMap.put(INTEGER, "Number");
_torqueTypeToFlexNativeMap.put(BIGINT, "Number");
_torqueTypeToFlexNativeMap.put(REAL, "Number");
_torqueTypeToFlexNativeMap.put(FLOAT, "Number");
_torqueTypeToFlexNativeMap.put(DOUBLE, "Number");
_torqueTypeToFlexNativeMap.put(BINARY, "Object");
_torqueTypeToFlexNativeMap.put(VARBINARY, "Object");
_torqueTypeToFlexNativeMap.put(LONGVARBINARY, "Object");
_torqueTypeToFlexNativeMap.put(BLOB, "Object");
_torqueTypeToFlexNativeMap.put(DATE, "Date");
_torqueTypeToFlexNativeMap.put(TIME, "Date");
_torqueTypeToFlexNativeMap.put(TIMESTAMP, "Date");
_initialized = true;
}
| public synchronized static void initialize() {
if (_initialized) {
return;
}
/*
* Create JDBC -> native Java type mappings.
*/
_torqueTypeToJavaNativeMap = new Hashtable<String, String>();
// Default types are for Java.
_torqueTypeToJavaNativeMap.put(CHAR, findJavaNative(CHAR, CHAR_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(VARCHAR, findJavaNative(VARCHAR, VARCHAR_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(LONGVARCHAR, findJavaNative(LONGVARCHAR, LONGVARCHAR_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(CLOB, findJavaNative(CLOB, CLOB_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(NUMERIC, findJavaNative(NUMERIC, getDefaultNumericJavaType()));
_torqueTypeToJavaNativeMap.put(DECIMAL, findJavaNative(DECIMAL, DECIMAL_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(BIT, findJavaNative(BIT, BIT_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(BOOLEAN, findJavaNative(BOOLEAN, BOOLEAN_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(TINYINT, findJavaNative(TINYINT, TINYINT_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(SMALLINT, findJavaNative(SMALLINT, SMALLINT_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(INTEGER, findJavaNative(INTEGER, INTEGER_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(BIGINT, findJavaNative(BIGINT, BIGINT_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(REAL, findJavaNative(REAL, REAL_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(FLOAT, findJavaNative(FLOAT, FLOAT_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(DOUBLE, findJavaNative(DOUBLE, DOUBLE_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(BINARY, findJavaNative(BINARY, BINARY_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(VARBINARY, findJavaNative(VARBINARY, VARBINARY_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(LONGVARBINARY, findJavaNative(LONGVARBINARY, LONGVARBINARY_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(BLOB, findJavaNative(BLOB, BLOB_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(DATE, findJavaNative(DATE, DATE_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(TIME, findJavaNative(TIME, TIME_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(TIMESTAMP, findJavaNative(TIMESTAMP, TIMESTAMP_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(BOOLEANCHAR, findJavaNative(BOOLEANCHAR, BOOLEANCHAR_NATIVE_TYPE));
_torqueTypeToJavaNativeMap.put(BOOLEANINT, findJavaNative(BOOLEANINT, BOOLEANINT_NATIVE_TYPE));
_jdbcTypeToTorqueTypeMap = new Hashtable<Integer, String>();
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.CHAR), CHAR);
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.VARCHAR), VARCHAR);
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.LONGVARCHAR), LONGVARCHAR);
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.CLOB), CLOB);
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.NUMERIC), NUMERIC);
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.DECIMAL), DECIMAL);
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.BIT), BIT);
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.BOOLEAN), BOOLEAN);
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.TINYINT), TINYINT);
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.SMALLINT), SMALLINT);
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.INTEGER), INTEGER);
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.BIGINT), BIGINT);
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.REAL), REAL);
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.FLOAT), FLOAT);
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.DOUBLE), DOUBLE);
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.BINARY), BINARY);
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.VARBINARY), VARBINARY);
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.LONGVARBINARY), LONGVARBINARY);
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.BLOB), BLOB);
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.DATE), DATE);
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.TIME), TIME);
_jdbcTypeToTorqueTypeMap.put(new Integer(Types.TIMESTAMP), TIMESTAMP);
_torqueTypeToFlexNativeMap = new Hashtable<String, String>();
_torqueTypeToFlexNativeMap.put(CHAR, "String");
_torqueTypeToFlexNativeMap.put(VARCHAR, "String");
_torqueTypeToFlexNativeMap.put(LONGVARCHAR, "String");
_torqueTypeToFlexNativeMap.put(CLOB, "String");
_torqueTypeToFlexNativeMap.put(NUMERIC, "Number");
_torqueTypeToFlexNativeMap.put(DECIMAL, "Number");
_torqueTypeToFlexNativeMap.put(BIT, "Boolean");
_torqueTypeToFlexNativeMap.put(BOOLEAN, "Boolean");
_torqueTypeToFlexNativeMap.put(TINYINT, "int");
_torqueTypeToFlexNativeMap.put(SMALLINT, "int");
_torqueTypeToFlexNativeMap.put(INTEGER, "int");
_torqueTypeToFlexNativeMap.put(BIGINT, "Number");
_torqueTypeToFlexNativeMap.put(REAL, "Number");
_torqueTypeToFlexNativeMap.put(FLOAT, "Number");
_torqueTypeToFlexNativeMap.put(DOUBLE, "Number");
_torqueTypeToFlexNativeMap.put(BINARY, "Object");
_torqueTypeToFlexNativeMap.put(VARBINARY, "Object");
_torqueTypeToFlexNativeMap.put(LONGVARBINARY, "Object");
_torqueTypeToFlexNativeMap.put(BLOB, "Object");
_torqueTypeToFlexNativeMap.put(DATE, "Date");
_torqueTypeToFlexNativeMap.put(TIME, "Date");
_torqueTypeToFlexNativeMap.put(TIMESTAMP, "Date");
_initialized = true;
}
|
diff --git a/modules/requisition/src/main/java/org/openlmis/rnr/domain/ProgramRnrTemplate.java b/modules/requisition/src/main/java/org/openlmis/rnr/domain/ProgramRnrTemplate.java
index c2f0aef2c8..21420d21e0 100644
--- a/modules/requisition/src/main/java/org/openlmis/rnr/domain/ProgramRnrTemplate.java
+++ b/modules/requisition/src/main/java/org/openlmis/rnr/domain/ProgramRnrTemplate.java
@@ -1,161 +1,161 @@
/*
* Copyright © 2013 VillageReach. All Rights Reserved. This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
*
* If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package org.openlmis.rnr.domain;
import lombok.Getter;
import org.openlmis.core.message.OpenLmisMessage;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ProgramRnrTemplate {
public static final String STOCK_IN_HAND = "stockInHand";
public static final String QUANTITY_DISPENSED = "quantityDispensed";
public static final String BEGINNING_BALANCE = "beginningBalance";
public static final String QUANTITY_RECEIVED = "quantityReceived";
public static final String QUANTITY_APPROVED = "quantityApproved";
public static final String LOSSES_AND_ADJUSTMENTS = "lossesAndAdjustments";
public static final String STOCK_OUT_DAYS = "stockOutDays";
public static final String NORMALIZED_CONSUMPTION = "normalizedConsumption";
public static final String QUANTITY_REQUESTED = "quantityRequested";
public static final String REASON_FOR_REQUESTED_QUANTITY = "reasonForRequestedQuantity";
public static final String NEW_PATIENT_COUNT = "newPatientCount";
public static final String COST = "cost";
public static final String PRICE = "price";
public static final String PRODUCT = "product";
@Getter
private Map<String, RnrColumn> rnrColumnsMap = new HashMap<>();
private Map<String, OpenLmisMessage> errorMap = new HashMap<>();
@Getter
private Integer programId;
@Getter
private List<RnrColumn> rnrColumns;
private static final String USER_NEEDS_TO_ENTER_DEPENDENT_FIELD = "user.needs.to.enter.dependent.field";
private static final String INTERDEPENDENT_FIELDS_CAN_NOT_BE_CALCULATED = "interdependent.fields.can.not.be.calculated";
public static final String COLUMN_SHOULD_BE_VISIBLE_IF_USER_INPUT = "column.should.be.visible.if.user.input";
private static final String USER_NEED_TO_ENTER_REQUESTED_QUANTITY_REASON = "user.needs.to.enter.requested.quantity.reason";
public ProgramRnrTemplate(Integer programId, List<RnrColumn> rnrColumns) {
this.programId = programId;
this.rnrColumns = rnrColumns;
for (RnrColumn rnrColumn : rnrColumns) {
rnrColumnsMap.put(rnrColumn.getName(), rnrColumn);
}
}
public ProgramRnrTemplate(List<RnrColumn> programRnrColumns) {
this.rnrColumns = programRnrColumns;
for (RnrColumn rnrColumn : rnrColumns) {
rnrColumnsMap.put(rnrColumn.getName(), rnrColumn);
}
}
public boolean columnsVisible(String... rnrColumnNames) {
boolean visible = true;
for (String rnrColumnName : rnrColumnNames) {
visible = visible && rnrColumnsMap.get(rnrColumnName).isVisible();
}
return visible;
}
public boolean columnsCalculated(String... rnrColumnNames) {
boolean calculated = false;
for (String rnrColumnName : rnrColumnNames) {
calculated = calculated || (rnrColumnsMap.get(rnrColumnName).getSource() == RnRColumnSource.CALCULATED);
}
return calculated;
}
public String getRnrColumnLabelFor(String columnName) {
return rnrColumnsMap.get(columnName).getLabel();
}
private boolean areSelectedTogether(String column1, String column2) {
return (columnsVisible(column1) && columnsVisible(column2)) || (!columnsVisible(column1) && !columnsVisible(column2));
}
public Map<String, OpenLmisMessage> validateToSave() {
validateColumnsTobeCheckedIfUserInput();
validateCalculatedColumnHasDependentChecked(STOCK_IN_HAND, QUANTITY_DISPENSED);
validateCalculatedColumnHasDependentChecked(QUANTITY_DISPENSED, STOCK_IN_HAND);
validateQuantityDispensedAndStockInHandCannotBeCalculatedAtSameTime();
quantityRequestedAndReasonForRequestedQuantityBothShouldBeVisibleTogether();
return errorMap;
}
private void validateColumnsTobeCheckedIfUserInput() {
validateColumnToBeCheckedIfUserInput(STOCK_IN_HAND);
validateColumnToBeCheckedIfUserInput(QUANTITY_DISPENSED);
}
private void validateColumnToBeCheckedIfUserInput(String column) {
if (columnIsUserInput(column) && !columnsVisible(column)) {
errorMap.put(column, new OpenLmisMessage(COLUMN_SHOULD_BE_VISIBLE_IF_USER_INPUT, getRnrColumnLabelFor(column)));
}
}
private boolean columnIsUserInput(String column) {
return !columnsCalculated(column);
}
private void validateQuantityDispensedAndStockInHandCannotBeCalculatedAtSameTime() {
if (columnsCalculated(QUANTITY_DISPENSED) && columnsCalculated(STOCK_IN_HAND)) {
OpenLmisMessage errorMessage = new OpenLmisMessage(INTERDEPENDENT_FIELDS_CAN_NOT_BE_CALCULATED, getRnrColumnLabelFor(QUANTITY_DISPENSED), getRnrColumnLabelFor(STOCK_IN_HAND));
errorMap.put(QUANTITY_DISPENSED, errorMessage);
errorMap.put(STOCK_IN_HAND, errorMessage);
}
}
private void validateCalculatedColumnHasDependentChecked(String columnToEvaluate, String dependent) {
if (columnsCalculated(columnToEvaluate) && !columnsVisible(dependent)) {
errorMap.put(columnToEvaluate, new OpenLmisMessage(USER_NEEDS_TO_ENTER_DEPENDENT_FIELD, getRnrColumnLabelFor(dependent), getRnrColumnLabelFor(columnToEvaluate)));
}
}
private void quantityRequestedAndReasonForRequestedQuantityBothShouldBeVisibleTogether() {
if (!areSelectedTogether(QUANTITY_REQUESTED, REASON_FOR_REQUESTED_QUANTITY)) {
if (columnsVisible(QUANTITY_REQUESTED))
errorMap.put(QUANTITY_REQUESTED, new OpenLmisMessage(USER_NEED_TO_ENTER_REQUESTED_QUANTITY_REASON, getRnrColumnLabelFor(QUANTITY_REQUESTED), getRnrColumnLabelFor(REASON_FOR_REQUESTED_QUANTITY)));
else
errorMap.put(REASON_FOR_REQUESTED_QUANTITY, new OpenLmisMessage(USER_NEED_TO_ENTER_REQUESTED_QUANTITY_REASON, getRnrColumnLabelFor(REASON_FOR_REQUESTED_QUANTITY), getRnrColumnLabelFor(QUANTITY_REQUESTED)));
}
}
public List<RnrColumn> getVisibleColumns(boolean fullSupply) {
List<RnrColumn> visibleRnrColumns = new ArrayList<>();
if (fullSupply) {
for (RnrColumn rnrColumn : rnrColumns) {
if (rnrColumn.getName().equals("remarks") || rnrColumn.getName().equals("reasonForRequestedQuantity"))
continue;
if (rnrColumn.isVisible()) {
visibleRnrColumns.add(rnrColumn);
}
}
} else {
for (RnrColumn rnrColumn : rnrColumns) {
if (rnrColumn.getName().equals("product") || rnrColumn.getName().equals("productCode") ||
rnrColumn.getName().equals("dispensingUnit") || rnrColumn.getName().equals("quantityRequested") ||
rnrColumn.getName().equals("packsToShip") || rnrColumn.getName().equals("price") ||
- rnrColumn.getName().equals("cost")) {
+ rnrColumn.getName().equals("cost") || rnrColumn.getName().equals("quantityApproved")){
if (rnrColumn.isVisible()) {
visibleRnrColumns.add(rnrColumn);
}
}
}
}
return visibleRnrColumns;
}
}
| true | true | public List<RnrColumn> getVisibleColumns(boolean fullSupply) {
List<RnrColumn> visibleRnrColumns = new ArrayList<>();
if (fullSupply) {
for (RnrColumn rnrColumn : rnrColumns) {
if (rnrColumn.getName().equals("remarks") || rnrColumn.getName().equals("reasonForRequestedQuantity"))
continue;
if (rnrColumn.isVisible()) {
visibleRnrColumns.add(rnrColumn);
}
}
} else {
for (RnrColumn rnrColumn : rnrColumns) {
if (rnrColumn.getName().equals("product") || rnrColumn.getName().equals("productCode") ||
rnrColumn.getName().equals("dispensingUnit") || rnrColumn.getName().equals("quantityRequested") ||
rnrColumn.getName().equals("packsToShip") || rnrColumn.getName().equals("price") ||
rnrColumn.getName().equals("cost")) {
if (rnrColumn.isVisible()) {
visibleRnrColumns.add(rnrColumn);
}
}
}
}
return visibleRnrColumns;
}
| public List<RnrColumn> getVisibleColumns(boolean fullSupply) {
List<RnrColumn> visibleRnrColumns = new ArrayList<>();
if (fullSupply) {
for (RnrColumn rnrColumn : rnrColumns) {
if (rnrColumn.getName().equals("remarks") || rnrColumn.getName().equals("reasonForRequestedQuantity"))
continue;
if (rnrColumn.isVisible()) {
visibleRnrColumns.add(rnrColumn);
}
}
} else {
for (RnrColumn rnrColumn : rnrColumns) {
if (rnrColumn.getName().equals("product") || rnrColumn.getName().equals("productCode") ||
rnrColumn.getName().equals("dispensingUnit") || rnrColumn.getName().equals("quantityRequested") ||
rnrColumn.getName().equals("packsToShip") || rnrColumn.getName().equals("price") ||
rnrColumn.getName().equals("cost") || rnrColumn.getName().equals("quantityApproved")){
if (rnrColumn.isVisible()) {
visibleRnrColumns.add(rnrColumn);
}
}
}
}
return visibleRnrColumns;
}
|
diff --git a/cli/src/main/java/hudson/cli/CLI.java b/cli/src/main/java/hudson/cli/CLI.java
index c0003218f..9907eebdf 100644
--- a/cli/src/main/java/hudson/cli/CLI.java
+++ b/cli/src/main/java/hudson/cli/CLI.java
@@ -1,104 +1,104 @@
/*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc.
*
* 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 hudson.cli;
import hudson.remoting.Channel;
import hudson.remoting.RemoteInputStream;
import hudson.remoting.RemoteOutputStream;
import hudson.remoting.PingThread;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* CLI entry point to Hudson.
*
* @author Kohsuke Kawaguchi
*/
public class CLI {
public static void main(final String[] _args) throws Exception {
List<String> args = Arrays.asList(_args);
String url = System.getenv("HUDSON_URL");
while(!args.isEmpty()) {
String head = args.get(0);
if(head.equals("-s") && args.size()>=2) {
url = args.get(1);
args = args.subList(2,args.size());
continue;
}
break;
}
if(url==null)
printUsageAndExit(Messages.CLI_NoURL());
if(!url.endsWith("/")) url+='/';
url+="cli";
if(args.isEmpty())
args = Arrays.asList("help"); // default to help
FullDuplexHttpStream con = new FullDuplexHttpStream(new URL(url));
ExecutorService pool = Executors.newCachedThreadPool();
Channel channel = new Channel("Chunked connection to "+url,
pool,con.getInputStream(),con.getOutputStream());
new PingThread(channel,30*1000) {
protected void onDead() {
// noop. the point of ping is to keep the connection alive
// as most HTTP servers have a rather short read time out
}
}.start();
// execute the command
int r=-1;
try {
CliEntryPoint cli = (CliEntryPoint)channel.getRemoteProperty(CliEntryPoint.class.getName());
if(cli.protocolVersion()!=CliEntryPoint.VERSION) {
System.err.println(Messages.CLI_VersionMismatch());
} else {
- // Arrays.asList is not serializable --- presumably a bug in JRE.
+ // Arrays.asList is not serializable --- see 6835580
args = new ArrayList<String>(args);
r = cli.main(args, Locale.getDefault(), new RemoteInputStream(System.in),
new RemoteOutputStream(System.out), new RemoteOutputStream(System.err));
}
} finally {
channel.close();
pool.shutdown();
}
System.exit(r);
}
private static void printUsageAndExit(String msg) {
if(msg!=null) System.out.println(msg);
System.err.println(Messages.CLI_Usage());
System.exit(-1);
}
}
| true | true | public static void main(final String[] _args) throws Exception {
List<String> args = Arrays.asList(_args);
String url = System.getenv("HUDSON_URL");
while(!args.isEmpty()) {
String head = args.get(0);
if(head.equals("-s") && args.size()>=2) {
url = args.get(1);
args = args.subList(2,args.size());
continue;
}
break;
}
if(url==null)
printUsageAndExit(Messages.CLI_NoURL());
if(!url.endsWith("/")) url+='/';
url+="cli";
if(args.isEmpty())
args = Arrays.asList("help"); // default to help
FullDuplexHttpStream con = new FullDuplexHttpStream(new URL(url));
ExecutorService pool = Executors.newCachedThreadPool();
Channel channel = new Channel("Chunked connection to "+url,
pool,con.getInputStream(),con.getOutputStream());
new PingThread(channel,30*1000) {
protected void onDead() {
// noop. the point of ping is to keep the connection alive
// as most HTTP servers have a rather short read time out
}
}.start();
// execute the command
int r=-1;
try {
CliEntryPoint cli = (CliEntryPoint)channel.getRemoteProperty(CliEntryPoint.class.getName());
if(cli.protocolVersion()!=CliEntryPoint.VERSION) {
System.err.println(Messages.CLI_VersionMismatch());
} else {
// Arrays.asList is not serializable --- presumably a bug in JRE.
args = new ArrayList<String>(args);
r = cli.main(args, Locale.getDefault(), new RemoteInputStream(System.in),
new RemoteOutputStream(System.out), new RemoteOutputStream(System.err));
}
} finally {
channel.close();
pool.shutdown();
}
System.exit(r);
}
| public static void main(final String[] _args) throws Exception {
List<String> args = Arrays.asList(_args);
String url = System.getenv("HUDSON_URL");
while(!args.isEmpty()) {
String head = args.get(0);
if(head.equals("-s") && args.size()>=2) {
url = args.get(1);
args = args.subList(2,args.size());
continue;
}
break;
}
if(url==null)
printUsageAndExit(Messages.CLI_NoURL());
if(!url.endsWith("/")) url+='/';
url+="cli";
if(args.isEmpty())
args = Arrays.asList("help"); // default to help
FullDuplexHttpStream con = new FullDuplexHttpStream(new URL(url));
ExecutorService pool = Executors.newCachedThreadPool();
Channel channel = new Channel("Chunked connection to "+url,
pool,con.getInputStream(),con.getOutputStream());
new PingThread(channel,30*1000) {
protected void onDead() {
// noop. the point of ping is to keep the connection alive
// as most HTTP servers have a rather short read time out
}
}.start();
// execute the command
int r=-1;
try {
CliEntryPoint cli = (CliEntryPoint)channel.getRemoteProperty(CliEntryPoint.class.getName());
if(cli.protocolVersion()!=CliEntryPoint.VERSION) {
System.err.println(Messages.CLI_VersionMismatch());
} else {
// Arrays.asList is not serializable --- see 6835580
args = new ArrayList<String>(args);
r = cli.main(args, Locale.getDefault(), new RemoteInputStream(System.in),
new RemoteOutputStream(System.out), new RemoteOutputStream(System.err));
}
} finally {
channel.close();
pool.shutdown();
}
System.exit(r);
}
|
diff --git a/rhogen-wizard/test/rhogenwizard/sdk/task/RunDebugRhodesAppTaskTest.java b/rhogen-wizard/test/rhogenwizard/sdk/task/RunDebugRhodesAppTaskTest.java
index f4da50e..10dd43f 100644
--- a/rhogen-wizard/test/rhogenwizard/sdk/task/RunDebugRhodesAppTaskTest.java
+++ b/rhogen-wizard/test/rhogenwizard/sdk/task/RunDebugRhodesAppTaskTest.java
@@ -1,498 +1,498 @@
package rhogenwizard.sdk.task;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
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 java.util.concurrent.Semaphore;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchManager;
import org.eclipse.debug.core.Launch;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import rhogenwizard.ConsoleHelper;
import rhogenwizard.ILogDevice;
import rhogenwizard.OSHelper;
import rhogenwizard.OSValidator;
import rhogenwizard.PlatformType;
import rhogenwizard.SysCommandExecutor;
import rhogenwizard.debugger.backend.DebugServer;
import rhogenwizard.debugger.backend.DebugState;
import rhogenwizard.debugger.backend.DebugVariableType;
import rhogenwizard.debugger.backend.IDebugCallback;
import rhogenwizard.sdk.facade.RhoTaskHolder;
import rhogenwizard.sdk.helper.TaskResultConverter;
public class RunDebugRhodesAppTaskTest
{
private SynchronousQueue<String> m_eventQueue;
private Semaphore m_semaphore;
private static class DebugCallback implements IDebugCallback
{
private final SynchronousQueue<String> m_eventQueue;
private final Semaphore m_semaphore;
public DebugCallback(SynchronousQueue<String> eventQueue, Semaphore semaphore)
{
m_eventQueue = eventQueue;
m_semaphore = semaphore;
}
@Override
public void connected()
{
send("connected");
}
@Override
public void stopped(DebugState state, String file, int line, String className,
String method)
{
send("stopped [" + DebugState.getName(state) + "] [" + file + "] ["
+ line + "] [" + className + "] [" + method + "]");
}
@Override
public void resumed()
{
send("resumed");
}
@Override
public void evaluation(boolean valid, String code, String value)
{
send("evaluation [" + valid + "] [" + code + "] [" + value + "]");
}
@Override
public void unknown(String cmd)
{
send("unknown [" + cmd + "]");
}
@Override
public void exited()
{
send("exited");
}
@Override
public void watch(DebugVariableType type, String variable, String value)
{
send("watch [" + DebugVariableType.getName(type) + "] [" + variable + "] ["
+ value + "]");
}
@Override
public void watchBOL(DebugVariableType type)
{
send("watchBOL [" + DebugVariableType.getName(type) + "]");
}
@Override
public void watchEOL(DebugVariableType type)
{
send("watchEOL [" + DebugVariableType.getName(type) + "]");
}
private void send(String event)
{
try
{
m_eventQueue.put(event);
m_semaphore.acquire();
}
catch (InterruptedException e)
{
throw new RuntimeException("Can not send event. Impossible!", e);
}
}
}
private static ILogDevice nullLogDevice = new ILogDevice()
{
@Override
public void log(String str)
{
}
};
private static final String workspaceFolder = new File(
System.getProperty("java.io.tmpdir"), "junitworkfiles").getPath();
@BeforeClass
public static void setUpBeforeClass() throws Exception
{
ConsoleHelper.disableConsoles();
}
@AfterClass
public static void tearDownAfterClass() throws Exception
{
}
@Before
public void setUp() throws Exception
{
m_eventQueue = new SynchronousQueue<String>();
m_semaphore = new Semaphore(0);
OSHelper.deleteFolder(workspaceFolder);
File newWsFodler = new File(workspaceFolder);
newWsFodler.mkdir();
}
@After
public void tearDown() throws Exception
{
OSHelper.deleteFolder(workspaceFolder);
}
@Test
public void testRunDebugRhodesAppTask() throws Throwable
{
String appName = "app";
String projectLocation = OSHelper.concat(workspaceFolder, appName).getPath();
- String signature1 = (OSValidator.isWindows())
+ String signature1 = OSValidator.isWindows()
? "rhosimulator.exe -approot=\'" + unixSlashes(projectLocation) + "\'"
: "RhoSimulator -approot=/private" + projectLocation;
String signature2 =
- (OSValidator.isWindows())
- ? "rake run:android:rhosimulator_debug rho_debug_port=9000 rho_reload_app_changes=0"
- : "cmd /c rhodes.bat app app";
+ OSValidator.isWindows()
+ ? "cmd /c rhodes.bat app app"
+ : "rake run:android:rhosimulator_debug rho_debug_port=9000 rho_reload_app_changes=0";
Set<Integer> before1 = getProcessesIds(signature1);
Set<Integer> before2 = getProcessesIds(signature2);
try
{
// create application
{
Map<String, Object> params = new HashMap<String, Object>();
params.put(GenerateRhodesAppTask.appName, appName);
params.put(GenerateRhodesAppTask.workDir, workspaceFolder);
Map<String, ?> results =
RhoTaskHolder.getInstance().runTask(GenerateRhodesAppTask.class, params);
assertEquals(0, TaskResultConverter.getResultIntCode(results));
}
// write new application.rb
{
String text[] =
{
/* 01 */"require 'rho/rhoapplication'",
/* 02 */"class AppApplication < Rho::RhoApplication",
/* 03 */" def initialize",
/* 04 */" super",
/* 05 */" x = 0",
/* 06 */" x = x + 1",
/* 07 */" $y = 11",
/* 08 */" m",
/* 09 */" $y = $y + 22",
/* 10 */" end",
/* 11 */" def m",
/* 12 */" z = 0",
/* 13 */" zz = 0",
/* 14 */" end",
/* 15 */"end",
/* 16 */""
};
String appRb =
OSHelper.concat(projectLocation, "app", "application.rb").getPath();
writeTextFile(appRb, join("\n", text));
}
// start debug server
DebugCallback debugCallback = new DebugCallback(m_eventQueue, m_semaphore);
final DebugServer debugServer = new DebugServer(debugCallback);
final Throwable[] exception = new Throwable[1];
Thread debugServerThread = new Thread(new Runnable()
{
@Override
public void run()
{
try
{
debugServer.run();
}
catch (Throwable t)
{
exception[0] = t;
}
}
});
debugServerThread.start();
// run debug Rhodes application [android] [rhosimulator]
{
Map<String, Object> params = new HashMap<String, Object>();
ILaunch launch = new Launch(null, ILaunchManager.DEBUG_MODE, null);
params.put(RunDebugRhodesAppTask.workDir, projectLocation);
params.put(RunDebugRhodesAppTask.appName, appName);
params.put(RunDebugRhodesAppTask.platformType, PlatformType.eAndroid);
params.put(RunDebugRhodesAppTask.reloadCode, false);
params.put(RunDebugRhodesAppTask.launchObj, launch);
params.put(RunDebugRhodesAppTask.traceFlag, false);
Map<String, ?> results =
RhoTaskHolder.getInstance().runTask(RunDebugRhodesAppTask.class, params);
assertEquals(TaskResultConverter.okCode,
TaskResultConverter.getResultIntCode(results));
}
suspend("connected");
debugServer.debugBreakpoint("application.rb", 5);
debugServer.debugBreakpoint("application.rb", 6);
debugServer.debugRemoveBreakpoint("application.rb", 5);
pass(
"unknown [HOST=127.0.0.1]",
"unknown [PORT=9000]",
"unknown [DEBUG PATH="
+ unixSlashes(prependPrivate(OSHelper.concat(projectLocation, "app")
.getPath()))
+ "/]",
"stopped [breakpoint] [application.rb] [6] [AppApplication] [initialize]");
debugServer.debugEvaluate("x");
pass("evaluation [true] [x] [0]");
debugServer.debugBreakpoint("application.rb", 7);
debugServer.debugResume();
pass(
"resumed",
"stopped [breakpoint] [application.rb] [7] [AppApplication] [initialize]");
debugServer.debugEvaluate("x");
pass("evaluation [true] [x] [1]");
debugServer.debugStepOver();
pass(
"unknown [STEPOVER start]",
"resumed",
"stopped [stopped (over)] [application.rb] [8] [AppApplication] [initialize]");
debugServer.debugEvaluate("$y");
pass("evaluation [true] [$y] [11]");
debugServer.debugBreakpoint("application.rb", 12);
debugServer.debugResume();
pass(
"resumed",
"stopped [breakpoint] [application.rb] [12] [AppApplication] [m]");
debugServer.debugBreakpoint("application.rb", 13);
debugServer.debugRemoveAllBreakpoints();
debugServer.debugStepReturn();
pass(
"resumed",
"stopped [stopped (return)] [application.rb] [9] [AppApplication] [initialize]");
debugServer.debugEvaluate("(1+2");
pass("evaluation [false] [(1+2] [\""
+ prependPrivate(unixSlashes(OSHelper.concat(projectLocation, "app",
"application.rb").getPath()))
+ ":9: syntax error, unexpected $end, expecting ')'\"]");
debugServer.debugEvaluate("\"\\\\n\"");
pass("evaluation [true] [\"\\\\n\"] [\"\\\\n\"]");
debugServer.debugEvaluate("$y\n2+2 # comment");
pass("evaluation [true] [$y\n2+2 # comment] [4]");
debugServer.debugTerminate();
pass("exited");
debugServer.shutdown();
resume();
debugServerThread.join();
if (exception[0] != null)
{
throw exception[0];
}
}
finally
{
Set<Integer> after1 = getProcessesIds(signature1);
Set<Integer> after2 = getProcessesIds(signature2);
Set<Integer> diff1 = new HashSet<Integer>(after1);
diff1.removeAll(before1);
for (int pid : diff1)
{
OSHelper.killProcess(pid);
}
Set<Integer> diff2 = new HashSet<Integer>(after2);
diff2.removeAll(before2);
for (int pid : diff2)
{
OSHelper.killProcess(pid);
}
}
}
private void suspend(String s) throws InterruptedException
{
String event = m_eventQueue.poll(10, TimeUnit.SECONDS);
if (event == null)
{
fail("timeout for \"" + s + "\"");
}
assertEquals(s, event);
}
private void resume()
{
assertEquals(0, m_semaphore.availablePermits());
m_semaphore.release();
}
private void pass(String... events) throws InterruptedException
{
for (String event : events)
{
resume();
suspend(event);
}
}
private static String join(String delimiter, String... text)
{
boolean first = true;
StringBuilder sb = new StringBuilder();
for (String line : text)
{
if (first)
{
first = false;
}
else
{
sb.append(delimiter);
}
sb.append(line);
}
return sb.toString();
}
private static String readTextFile(String filename) throws IOException
{
FileReader fr = new FileReader(filename);
try
{
StringBuilder sb = new StringBuilder();
char[] buffer = new char[16 * 1024];
while (true)
{
int read = fr.read(buffer);
if (read == -1)
{
break;
}
sb.append(buffer, 0, read);
}
return sb.toString();
}
finally
{
fr.close();
}
}
private static void writeTextFile(String filename, String text) throws IOException
{
FileWriter fw = new FileWriter(filename);
try
{
fw.write(text);
}
finally
{
fw.close();
}
}
private static String getProcessesListing() throws Exception
{
List<String> cmdLine = Arrays.asList("ps", "ax");
SysCommandExecutor executor = new SysCommandExecutor();
executor.setOutputLogDevice(nullLogDevice);
executor.setErrorLogDevice(nullLogDevice);
executor.runCommand(cmdLine);
return executor.getCommandOutput();
}
private static Set<Integer> getProcessesIds(String signature) throws Exception
{
Pattern pattern = Pattern.compile("^ *(\\d+).*");
String listing = getProcessesListing();
Set<Integer> ids = new HashSet<Integer>();
for (String line : listing.split("\n"))
{
if (!line.contains(signature))
{
continue;
}
Matcher matcher = pattern.matcher(line);
if (!matcher.matches())
{
continue;
}
ids.add(Integer.parseInt(matcher.group(1)));
}
return ids;
}
private static String prependPrivate(String path)
{
return ((OSValidator.isWindows()) ? "" : "/private") + path;
}
private static String unixSlashes(String path)
{
return path.replace('\\', '/');
}
}
| false | true | public void testRunDebugRhodesAppTask() throws Throwable
{
String appName = "app";
String projectLocation = OSHelper.concat(workspaceFolder, appName).getPath();
String signature1 = (OSValidator.isWindows())
? "rhosimulator.exe -approot=\'" + unixSlashes(projectLocation) + "\'"
: "RhoSimulator -approot=/private" + projectLocation;
String signature2 =
(OSValidator.isWindows())
? "rake run:android:rhosimulator_debug rho_debug_port=9000 rho_reload_app_changes=0"
: "cmd /c rhodes.bat app app";
Set<Integer> before1 = getProcessesIds(signature1);
Set<Integer> before2 = getProcessesIds(signature2);
try
{
// create application
{
Map<String, Object> params = new HashMap<String, Object>();
params.put(GenerateRhodesAppTask.appName, appName);
params.put(GenerateRhodesAppTask.workDir, workspaceFolder);
Map<String, ?> results =
RhoTaskHolder.getInstance().runTask(GenerateRhodesAppTask.class, params);
assertEquals(0, TaskResultConverter.getResultIntCode(results));
}
// write new application.rb
{
String text[] =
{
/* 01 */"require 'rho/rhoapplication'",
/* 02 */"class AppApplication < Rho::RhoApplication",
/* 03 */" def initialize",
/* 04 */" super",
/* 05 */" x = 0",
/* 06 */" x = x + 1",
/* 07 */" $y = 11",
/* 08 */" m",
/* 09 */" $y = $y + 22",
/* 10 */" end",
/* 11 */" def m",
/* 12 */" z = 0",
/* 13 */" zz = 0",
/* 14 */" end",
/* 15 */"end",
/* 16 */""
};
String appRb =
OSHelper.concat(projectLocation, "app", "application.rb").getPath();
writeTextFile(appRb, join("\n", text));
}
// start debug server
DebugCallback debugCallback = new DebugCallback(m_eventQueue, m_semaphore);
final DebugServer debugServer = new DebugServer(debugCallback);
final Throwable[] exception = new Throwable[1];
Thread debugServerThread = new Thread(new Runnable()
{
@Override
public void run()
{
try
{
debugServer.run();
}
catch (Throwable t)
{
exception[0] = t;
}
}
});
debugServerThread.start();
// run debug Rhodes application [android] [rhosimulator]
{
Map<String, Object> params = new HashMap<String, Object>();
ILaunch launch = new Launch(null, ILaunchManager.DEBUG_MODE, null);
params.put(RunDebugRhodesAppTask.workDir, projectLocation);
params.put(RunDebugRhodesAppTask.appName, appName);
params.put(RunDebugRhodesAppTask.platformType, PlatformType.eAndroid);
params.put(RunDebugRhodesAppTask.reloadCode, false);
params.put(RunDebugRhodesAppTask.launchObj, launch);
params.put(RunDebugRhodesAppTask.traceFlag, false);
Map<String, ?> results =
RhoTaskHolder.getInstance().runTask(RunDebugRhodesAppTask.class, params);
assertEquals(TaskResultConverter.okCode,
TaskResultConverter.getResultIntCode(results));
}
suspend("connected");
debugServer.debugBreakpoint("application.rb", 5);
debugServer.debugBreakpoint("application.rb", 6);
debugServer.debugRemoveBreakpoint("application.rb", 5);
pass(
"unknown [HOST=127.0.0.1]",
"unknown [PORT=9000]",
"unknown [DEBUG PATH="
+ unixSlashes(prependPrivate(OSHelper.concat(projectLocation, "app")
.getPath()))
+ "/]",
"stopped [breakpoint] [application.rb] [6] [AppApplication] [initialize]");
debugServer.debugEvaluate("x");
pass("evaluation [true] [x] [0]");
debugServer.debugBreakpoint("application.rb", 7);
debugServer.debugResume();
pass(
"resumed",
"stopped [breakpoint] [application.rb] [7] [AppApplication] [initialize]");
debugServer.debugEvaluate("x");
pass("evaluation [true] [x] [1]");
debugServer.debugStepOver();
pass(
"unknown [STEPOVER start]",
"resumed",
"stopped [stopped (over)] [application.rb] [8] [AppApplication] [initialize]");
debugServer.debugEvaluate("$y");
pass("evaluation [true] [$y] [11]");
debugServer.debugBreakpoint("application.rb", 12);
debugServer.debugResume();
pass(
"resumed",
"stopped [breakpoint] [application.rb] [12] [AppApplication] [m]");
debugServer.debugBreakpoint("application.rb", 13);
debugServer.debugRemoveAllBreakpoints();
debugServer.debugStepReturn();
pass(
"resumed",
"stopped [stopped (return)] [application.rb] [9] [AppApplication] [initialize]");
debugServer.debugEvaluate("(1+2");
pass("evaluation [false] [(1+2] [\""
+ prependPrivate(unixSlashes(OSHelper.concat(projectLocation, "app",
"application.rb").getPath()))
+ ":9: syntax error, unexpected $end, expecting ')'\"]");
debugServer.debugEvaluate("\"\\\\n\"");
pass("evaluation [true] [\"\\\\n\"] [\"\\\\n\"]");
debugServer.debugEvaluate("$y\n2+2 # comment");
pass("evaluation [true] [$y\n2+2 # comment] [4]");
debugServer.debugTerminate();
pass("exited");
debugServer.shutdown();
resume();
debugServerThread.join();
if (exception[0] != null)
{
throw exception[0];
}
}
finally
{
Set<Integer> after1 = getProcessesIds(signature1);
Set<Integer> after2 = getProcessesIds(signature2);
Set<Integer> diff1 = new HashSet<Integer>(after1);
diff1.removeAll(before1);
for (int pid : diff1)
{
OSHelper.killProcess(pid);
}
Set<Integer> diff2 = new HashSet<Integer>(after2);
diff2.removeAll(before2);
for (int pid : diff2)
{
OSHelper.killProcess(pid);
}
}
}
| public void testRunDebugRhodesAppTask() throws Throwable
{
String appName = "app";
String projectLocation = OSHelper.concat(workspaceFolder, appName).getPath();
String signature1 = OSValidator.isWindows()
? "rhosimulator.exe -approot=\'" + unixSlashes(projectLocation) + "\'"
: "RhoSimulator -approot=/private" + projectLocation;
String signature2 =
OSValidator.isWindows()
? "cmd /c rhodes.bat app app"
: "rake run:android:rhosimulator_debug rho_debug_port=9000 rho_reload_app_changes=0";
Set<Integer> before1 = getProcessesIds(signature1);
Set<Integer> before2 = getProcessesIds(signature2);
try
{
// create application
{
Map<String, Object> params = new HashMap<String, Object>();
params.put(GenerateRhodesAppTask.appName, appName);
params.put(GenerateRhodesAppTask.workDir, workspaceFolder);
Map<String, ?> results =
RhoTaskHolder.getInstance().runTask(GenerateRhodesAppTask.class, params);
assertEquals(0, TaskResultConverter.getResultIntCode(results));
}
// write new application.rb
{
String text[] =
{
/* 01 */"require 'rho/rhoapplication'",
/* 02 */"class AppApplication < Rho::RhoApplication",
/* 03 */" def initialize",
/* 04 */" super",
/* 05 */" x = 0",
/* 06 */" x = x + 1",
/* 07 */" $y = 11",
/* 08 */" m",
/* 09 */" $y = $y + 22",
/* 10 */" end",
/* 11 */" def m",
/* 12 */" z = 0",
/* 13 */" zz = 0",
/* 14 */" end",
/* 15 */"end",
/* 16 */""
};
String appRb =
OSHelper.concat(projectLocation, "app", "application.rb").getPath();
writeTextFile(appRb, join("\n", text));
}
// start debug server
DebugCallback debugCallback = new DebugCallback(m_eventQueue, m_semaphore);
final DebugServer debugServer = new DebugServer(debugCallback);
final Throwable[] exception = new Throwable[1];
Thread debugServerThread = new Thread(new Runnable()
{
@Override
public void run()
{
try
{
debugServer.run();
}
catch (Throwable t)
{
exception[0] = t;
}
}
});
debugServerThread.start();
// run debug Rhodes application [android] [rhosimulator]
{
Map<String, Object> params = new HashMap<String, Object>();
ILaunch launch = new Launch(null, ILaunchManager.DEBUG_MODE, null);
params.put(RunDebugRhodesAppTask.workDir, projectLocation);
params.put(RunDebugRhodesAppTask.appName, appName);
params.put(RunDebugRhodesAppTask.platformType, PlatformType.eAndroid);
params.put(RunDebugRhodesAppTask.reloadCode, false);
params.put(RunDebugRhodesAppTask.launchObj, launch);
params.put(RunDebugRhodesAppTask.traceFlag, false);
Map<String, ?> results =
RhoTaskHolder.getInstance().runTask(RunDebugRhodesAppTask.class, params);
assertEquals(TaskResultConverter.okCode,
TaskResultConverter.getResultIntCode(results));
}
suspend("connected");
debugServer.debugBreakpoint("application.rb", 5);
debugServer.debugBreakpoint("application.rb", 6);
debugServer.debugRemoveBreakpoint("application.rb", 5);
pass(
"unknown [HOST=127.0.0.1]",
"unknown [PORT=9000]",
"unknown [DEBUG PATH="
+ unixSlashes(prependPrivate(OSHelper.concat(projectLocation, "app")
.getPath()))
+ "/]",
"stopped [breakpoint] [application.rb] [6] [AppApplication] [initialize]");
debugServer.debugEvaluate("x");
pass("evaluation [true] [x] [0]");
debugServer.debugBreakpoint("application.rb", 7);
debugServer.debugResume();
pass(
"resumed",
"stopped [breakpoint] [application.rb] [7] [AppApplication] [initialize]");
debugServer.debugEvaluate("x");
pass("evaluation [true] [x] [1]");
debugServer.debugStepOver();
pass(
"unknown [STEPOVER start]",
"resumed",
"stopped [stopped (over)] [application.rb] [8] [AppApplication] [initialize]");
debugServer.debugEvaluate("$y");
pass("evaluation [true] [$y] [11]");
debugServer.debugBreakpoint("application.rb", 12);
debugServer.debugResume();
pass(
"resumed",
"stopped [breakpoint] [application.rb] [12] [AppApplication] [m]");
debugServer.debugBreakpoint("application.rb", 13);
debugServer.debugRemoveAllBreakpoints();
debugServer.debugStepReturn();
pass(
"resumed",
"stopped [stopped (return)] [application.rb] [9] [AppApplication] [initialize]");
debugServer.debugEvaluate("(1+2");
pass("evaluation [false] [(1+2] [\""
+ prependPrivate(unixSlashes(OSHelper.concat(projectLocation, "app",
"application.rb").getPath()))
+ ":9: syntax error, unexpected $end, expecting ')'\"]");
debugServer.debugEvaluate("\"\\\\n\"");
pass("evaluation [true] [\"\\\\n\"] [\"\\\\n\"]");
debugServer.debugEvaluate("$y\n2+2 # comment");
pass("evaluation [true] [$y\n2+2 # comment] [4]");
debugServer.debugTerminate();
pass("exited");
debugServer.shutdown();
resume();
debugServerThread.join();
if (exception[0] != null)
{
throw exception[0];
}
}
finally
{
Set<Integer> after1 = getProcessesIds(signature1);
Set<Integer> after2 = getProcessesIds(signature2);
Set<Integer> diff1 = new HashSet<Integer>(after1);
diff1.removeAll(before1);
for (int pid : diff1)
{
OSHelper.killProcess(pid);
}
Set<Integer> diff2 = new HashSet<Integer>(after2);
diff2.removeAll(before2);
for (int pid : diff2)
{
OSHelper.killProcess(pid);
}
}
}
|
diff --git a/crono/src/crono/Interpreter.java b/crono/src/crono/Interpreter.java
index 750b9ac..a7a130e 100644
--- a/crono/src/crono/Interpreter.java
+++ b/crono/src/crono/Interpreter.java
@@ -1,559 +1,569 @@
package crono;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Stack;
import crono.type.Atom;
import crono.type.Cons;
import crono.type.CronoType;
import crono.type.Function;
import crono.type.Function.EvalType;
import crono.type.LambdaFunction;
import crono.type.Nil;
import crono.type.Quote;
import crono.type.Symbol;
import crono.type.CronoTypeId;
import crono.type.TypeId;
public class Interpreter extends Visitor {
public class InterpreterState extends Visitor.VisitorState {
public boolean showEnv, rShowEnv;
public boolean showClosure, rShowClosure;
public boolean dynamic, rDynamic;
public boolean trace, rTrace;
public boolean printAST, rPrintAST;
public Stack<Environment> envStack;
public InterpreterState() {
showEnv = Interpreter.this.showEnv;
rShowEnv = Interpreter.this.rShowEnv;
showClosure = Interpreter.this.showClosure;
rShowClosure = Interpreter.this.rShowClosure;
dynamic = Interpreter.this.dynamic;
rDynamic = Interpreter.this.rDynamic;
trace = Interpreter.this.trace;
rTrace = Interpreter.this.rTrace;
printAST = Interpreter.this.printAST;
rPrintAST = Interpreter.this.rPrintAST;
envStack = new Stack<Environment>();
envStack.addAll(Interpreter.this.envStack);
int size = envStack.size();
for(int i = 0; i < size; ++i) {
envStack.set(i, new Environment(envStack.get(i)));
}
}
}
private static final String _scope_err = "No object %s in scope";
private static final String _too_many_args =
"Too many arguments to %s: %d/%d recieved";
private static final String _type_scope_err = "No type %s in scope";
private static final String _type_mismatch =
"Function '%s' expected arguments %s; got %s";
private static final String _indent_level = " ";
protected boolean showEnv, rShowEnv;
protected boolean showClosure, rShowClosure;
protected boolean dynamic, rDynamic;
protected boolean trace, rTrace;
protected boolean printAST, rPrintAST;
protected EvalType eval;
protected StringBuilder indent;
protected Stack<Environment> envStack;
/**
* Creates a new Interpreter with default option values.
*/
public Interpreter() {
showEnv(false);
showClosure(false);
dynamic(false);
trace(false);
printAST(false);
indent = new StringBuilder();
eval = Function.EvalType.FULL;
envStack = new Stack<Environment>();
reset(); /*< Set up initial environment and types */
}
/**
* Turns environment reporting on or off.
* @param on If the Interpreter should report the contents of the
* Environment.
*/
public void showEnv(boolean on) {
showEnv = on;
rShowEnv = on;
}
/**
* Turns printing of closures on or off.
* Not currently implemented.
* @param on If closures should be shown.
*/
public void showClosure(boolean on) {
showClosure = on;
rShowClosure = on;
}
/**
* Turns dynamic scoping on or off.
* TODO: add a description of dynamic scoping.
*/
public void dynamic(boolean on) {
dynamic = on;
rDynamic = on;
}
/**
* Turns operation tracing on or off.
* @param on If the interpreter should perform operation tracing.
*/
public void trace(boolean on) {
trace = on;
rTrace = on;
}
/**
* Turn AST printing on or off.
* @param on If the Interpreter should print the AST node it is at.
*/
public void printAST(boolean on) {
printAST = on;
rPrintAST = on;
}
/**
* Helper method to indent correctly.
*/
protected void indent() {
indent.append(_indent_level);
}
/**
* Helper method to de-indent correctly.
*/
protected void deindent() {
int size = indent.length();
if(size < 2) {
indent = new StringBuilder();
}else {
indent.deleteCharAt(size - 1);
indent.deleteCharAt(size - 2);
}
}
/**
* Resets interpreter state to it's default state.
*/
protected void resetOptions() {
/* Restore defaults that may have been changed */
showEnv = rShowEnv;
showClosure = rShowClosure;
dynamic = rDynamic;
trace = rTrace;
printAST = rPrintAST;
}
/**
* Turns off all options that only affect information that is printed.
*/
protected void optionsOff() {
showEnv = false;
showClosure = false;
trace = false;
printAST = false;
}
/**
* Prints the trace notification of a node visit.
* This function only prints a trace if the Interpreter.trace(boolean)
* method was called with a value of true.
* @param node The node that is being visited.
*/
protected void traceVisit(CronoType node) {
if(trace) {
System.out.printf("%sVisiting %s\n", indent, node.repr());
}
}
/**
* Prints the trace results of evaluating a node.
* This function only prints a trace if the Interpreter.trace(boolean)
* method was called with a value of true.
* @param result The results to report
*/
protected void traceResult(CronoType result) {
if(trace) {
System.out.printf("%sResult: %s [%s]\n", indent, result.repr(),
result.typeId());
}
}
/**
* Prints out a message that a node was visited on the AST.
* This function only prints a trace if the Interpreter.printAST(boolean)
* method was called with a value of true.
* @param nodeName The name of the node type that is being visited.
*/
protected void printASTNode(String nodeName) {
if(printAST) {
System.out.printf("%sAST: %s\n", indent, nodeName);
}
}
protected void printEnvironment() {
if(showEnv) {
System.out.printf("%sEnv: %s\n", indent, getEnv());
}
}
/**
* On exceptions, instead of throwing and forgetting, it should call except
* to reset the evaluation level, reset all options and then throw. This
* ensures that the interpreter doesn't get into an invalid state.
*/
protected void except(RuntimeException e) {
resetOptions();
eval = EvalType.FULL;
indent = new StringBuilder();
throw e;
}
/**
* Resets the Interpreter to it's default state, including the environment.
*/
public void reset() {
envStack.clear();
pushEnv(new Environment());
resetOptions();
}
/**
* Visit a cons node.
* There are a few cases the interpreter has to deal with:
* 1. The evaluation type is set to NONE:
* * The node is a 'list', and is processed by the sub-node in some
* * interpreter unknown way.
* 2. The node is Nil:
* * Return Nil
* 3. The node is a function application:
* a. The evaluation type is PARTIAL:
* * Perform name substitution by visiting all sub nodes.
* b. The evaluation type is FULL:
* * Number of arguments statisfys the function requirments:
* * Run the function
* * Number of arguments is less than required:
* * Curry the function
* * Too many arguments:
* * Throw an exception
* The Nil case could be seperated out by giving Nil.java an accept method,
* and adding a visit method to Visitor.java and Interpreter.java.
* @param c The Cons node to visit.
* @return The value obtained by visiting this node.
*/
public CronoType visit(Cons c) {
if(eval == EvalType.NONE) {
printASTNode("List Node");
traceVisit(c);
traceResult(c);
printEnvironment();
return c;
}
Iterator<CronoType> iter = c.iterator();
if(!(iter.hasNext())) {
printASTNode("Nil Node");
traceVisit(Nil.NIL);
traceResult(Nil.NIL);
printEnvironment();
return c; /*< C is an empty list (may be Nil or T) */
}
printASTNode("Function Application Node");
traceVisit(c);
indent();
CronoType value = iter.next().accept(this);
if(value instanceof Function) {
Function fun = ((Function)value);
EvalType reserve = eval;
eval = fun.eval;
if(eval.level > reserve.level) {
eval = reserve;
}
List<CronoType> args = new ArrayList<CronoType>();
while(iter.hasNext()) {
args.add(iter.next().accept(this));
}
eval = reserve;
int arglen = args.size();
int nargs = fun.arity;
if(arglen < nargs) {
if(arglen == 0) {
/* Special case -- we don't have to do anything to the
* function to return it properly. */
deindent();
traceResult(fun);
printEnvironment();
return fun;
}
/* Curry it */
if(fun instanceof LambdaFunction) {
LambdaFunction lfun = ((LambdaFunction)fun);
Environment env = getEnv();
if(!dynamic) {
/* Use the lambda's stored environment */
env = lfun.environment;
}
/* We want to preserve the current environment */
env = new Environment(false);
/* Put known values into the new environment */
for(int i = 0; i < arglen; ++i) {
env.put(lfun.arglist[i], args.get(i));
}
/* Create new argument list and remove remaining args from
* the new environment */
List<Symbol> largs = new ArrayList<Symbol>();
for(int i = arglen; i < lfun.arglist.length; ++i) {
largs.add(lfun.arglist[i]);
env.remove(lfun.arglist[i]);
}
/* Evaluate the body as much as possible */
reserve = eval;
CronoType[] lbody = new CronoType[lfun.body.length];
optionsOff(); /*< Extra indent for clarity */
{
eval = EvalType.PARTIAL;
pushEnv(env);
for(int i = 0; i < lfun.body.length; ++i) {
lbody[i] = lfun.body[i].accept(this);
}
eval = reserve;
popEnv();
}
resetOptions(); /*< Set options back to what they were */
/* Return the new, partially evaluated lambda */
Symbol[] arglist = new Symbol[largs.size()];
LambdaFunction clfun;
clfun = new LambdaFunction(largs.toArray(arglist), lbody,
lfun.environment);
deindent();
traceResult(clfun);
printEnvironment();
return clfun;
}
/* Builtin partial evaluation */
List<CronoType> body = new LinkedList<CronoType>();
body.add(fun);
body.addAll(args); /*< Dump args in order into the new cons */
/* Add symbols for missing args */
List<Symbol> arglist = new ArrayList<Symbol>();
Symbol sym;
for(int i = arglen, n = 0; i < nargs; ++i, ++n) {
sym = new Symbol(String.format("_i?%d!_", n));
body.add(sym);
arglist.add(sym);
}
/* Create a new lambda */
Symbol[] narglist = new Symbol[arglist.size()];
LambdaFunction blfun;
CronoType[] barr = new CronoType[] {Cons.fromList(body)};
blfun = new LambdaFunction(arglist.toArray(narglist), barr,
getEnv());
deindent();
traceResult(blfun);
printEnvironment();
return blfun;
}
if(arglen > nargs && !fun.variadic) {
eval = reserve;
except(new InterpreterException(_too_many_args, fun, arglen,
nargs));
}
/* Full evaluation */
if(eval == EvalType.FULL) {
if(fun instanceof LambdaFunction && dynamic) {
/* We have to trick the lambda function if we want dynamic
* scoping. I hate making so many objects left and right,
* but this is the easiest way to do what I want here. */
LambdaFunction lfun = ((LambdaFunction)fun);
lfun = new LambdaFunction(lfun.arglist, lfun.body,
getEnv());
CronoType[] argarray = new CronoType[args.size()];
optionsOff();
- CronoType lresult = lfun.run(this, args.toArray(argarray));
+ CronoType lresult = null;
+ try {
+ lresult = lfun.run(this, args.toArray(argarray));
+ }catch(RuntimeException e) {
+ except(e);
+ }
resetOptions();
deindent();
traceResult(lresult);
printEnvironment();
return lresult;
}
CronoType[] argarray = new CronoType[args.size()];
argarray = args.toArray(argarray);
TypeId[] types = new TypeId[args.size()];
for(int i = 0; i < types.length; ++i) {
types[i] = argarray[i].typeId();
}
for(int i = 0; i < fun.args.length; ++i) {
if(!(fun.args[i].isType(argarray[i]))) {
String argstr = Arrays.toString(types);
String expected = Arrays.toString(fun.args);
except(new InterpreterException(_type_mismatch, fun,
expected, argstr));
}
}
optionsOff();
- CronoType fresult;
- fresult = ((Function)value).run(this, args.toArray(argarray));
+ CronoType fresult = null;
+ Function fun2 = (Function)value;
+ try {
+ fresult = fun2.run(this, args.toArray(argarray));
+ }catch(RuntimeException re) {
+ except(re);
+ }
resetOptions();
deindent();
traceResult(fresult);
printEnvironment();
return fresult;
}else {
args.add(0, value);
deindent();
Cons cresult = Cons.fromList(args);
traceResult(cresult);
printEnvironment();
return cresult;
}
}else if(eval == EvalType.PARTIAL) {
List<CronoType> args = new ArrayList<CronoType>();
args.add(value);
while(iter.hasNext()) {
args.add(iter.next().accept(this));
}
CronoType conres = Cons.fromList(args);
traceResult(conres);
return conres;
}
deindent();
/* The initial value is not a function */
except(new InterpreterException("Invalid Function Application: %s is not a function in %s", value, c));
return null;
}
/**
* Visits an atom node.
* The results of this method depend on the current evaluation type of the
* Interpreter.
* 1. NONE:
* * Return the atom without doing anything.
* 2. PARTIAL of FULL:
* * If the atom is a symbol, do name resolution based on the current
* environment.
* * If the atom is a type, or was resolved to a type, do type
* resolution.
* @param a The atom to visit
* @return The value obtained by visiting this node.
*/
public CronoType visit(Atom a) {
printASTNode(String.format("Atom Node -> %s[%s]\n", a, a.typeId()));
traceVisit(a);
if(eval == EvalType.NONE) {
traceResult(a);
return a;
}
CronoType t = a;
if(t instanceof Symbol) {
t = getEnv().get((Symbol)a);
if(t == null) {
if(eval == EvalType.FULL) {
except(new InterpreterException(_scope_err, a.repr()));
}
t = a;
}
}
/* Not else-if, so that we perform a double-resolution on a symbol that
* represents a TypeId */
if(t instanceof CronoTypeId) {
CronoType res = t; /*< Save symbol resolution */
t = getEnv().getType((CronoTypeId)t);
if(t == null) {
if(eval == EvalType.FULL) {
except(new InterpreterException(_type_scope_err, a));
}
t = res; /*< Revert to symbol resolution */
}
}
traceResult(t); /* We don't need to show the environment after atoms */
return t;
}
/**
* Visits a quote node.
* Quote nodes simply return the value obtained by visiting their sub-node
* with a forced eval-type of NONE.
* @param q The quote node to visit.
* @return The node below this unchanged.
*/
public CronoType visit(Quote q) {
printASTNode("Quote Node");
traceVisit(q);
EvalType reserve = eval;
eval = EvalType.NONE;
CronoType result = q.node.accept(this);
eval = reserve;
traceResult(result);
return result;
}
public Visitor.VisitorState getState() {
return new InterpreterState();
}
public void setState(Visitor.VisitorState state) {
InterpreterState is = (InterpreterState)state;
showEnv = is.showEnv;
rShowEnv = is.rShowEnv;
showClosure = is.showClosure;
rShowClosure = is.rShowClosure;
dynamic = is.dynamic;
rDynamic = is.rDynamic;
trace = is.trace;
rTrace = is.rTrace;
printAST = is.printAST;
rPrintAST = is.rPrintAST;
envStack = new Stack<Environment>();
envStack.addAll(is.envStack);
int size = envStack.size();
for(int i = 0; i < size; ++i) {
envStack.set(i, new Environment(envStack.get(i)));
}
}
public Environment getEnv() {
return envStack.peek();
}
public void pushEnv(Environment env) {
envStack.push(env);
}
public void popEnv() {
envStack.pop();
}
}
| false | true | public CronoType visit(Cons c) {
if(eval == EvalType.NONE) {
printASTNode("List Node");
traceVisit(c);
traceResult(c);
printEnvironment();
return c;
}
Iterator<CronoType> iter = c.iterator();
if(!(iter.hasNext())) {
printASTNode("Nil Node");
traceVisit(Nil.NIL);
traceResult(Nil.NIL);
printEnvironment();
return c; /*< C is an empty list (may be Nil or T) */
}
printASTNode("Function Application Node");
traceVisit(c);
indent();
CronoType value = iter.next().accept(this);
if(value instanceof Function) {
Function fun = ((Function)value);
EvalType reserve = eval;
eval = fun.eval;
if(eval.level > reserve.level) {
eval = reserve;
}
List<CronoType> args = new ArrayList<CronoType>();
while(iter.hasNext()) {
args.add(iter.next().accept(this));
}
eval = reserve;
int arglen = args.size();
int nargs = fun.arity;
if(arglen < nargs) {
if(arglen == 0) {
/* Special case -- we don't have to do anything to the
* function to return it properly. */
deindent();
traceResult(fun);
printEnvironment();
return fun;
}
/* Curry it */
if(fun instanceof LambdaFunction) {
LambdaFunction lfun = ((LambdaFunction)fun);
Environment env = getEnv();
if(!dynamic) {
/* Use the lambda's stored environment */
env = lfun.environment;
}
/* We want to preserve the current environment */
env = new Environment(false);
/* Put known values into the new environment */
for(int i = 0; i < arglen; ++i) {
env.put(lfun.arglist[i], args.get(i));
}
/* Create new argument list and remove remaining args from
* the new environment */
List<Symbol> largs = new ArrayList<Symbol>();
for(int i = arglen; i < lfun.arglist.length; ++i) {
largs.add(lfun.arglist[i]);
env.remove(lfun.arglist[i]);
}
/* Evaluate the body as much as possible */
reserve = eval;
CronoType[] lbody = new CronoType[lfun.body.length];
optionsOff(); /*< Extra indent for clarity */
{
eval = EvalType.PARTIAL;
pushEnv(env);
for(int i = 0; i < lfun.body.length; ++i) {
lbody[i] = lfun.body[i].accept(this);
}
eval = reserve;
popEnv();
}
resetOptions(); /*< Set options back to what they were */
/* Return the new, partially evaluated lambda */
Symbol[] arglist = new Symbol[largs.size()];
LambdaFunction clfun;
clfun = new LambdaFunction(largs.toArray(arglist), lbody,
lfun.environment);
deindent();
traceResult(clfun);
printEnvironment();
return clfun;
}
/* Builtin partial evaluation */
List<CronoType> body = new LinkedList<CronoType>();
body.add(fun);
body.addAll(args); /*< Dump args in order into the new cons */
/* Add symbols for missing args */
List<Symbol> arglist = new ArrayList<Symbol>();
Symbol sym;
for(int i = arglen, n = 0; i < nargs; ++i, ++n) {
sym = new Symbol(String.format("_i?%d!_", n));
body.add(sym);
arglist.add(sym);
}
/* Create a new lambda */
Symbol[] narglist = new Symbol[arglist.size()];
LambdaFunction blfun;
CronoType[] barr = new CronoType[] {Cons.fromList(body)};
blfun = new LambdaFunction(arglist.toArray(narglist), barr,
getEnv());
deindent();
traceResult(blfun);
printEnvironment();
return blfun;
}
if(arglen > nargs && !fun.variadic) {
eval = reserve;
except(new InterpreterException(_too_many_args, fun, arglen,
nargs));
}
/* Full evaluation */
if(eval == EvalType.FULL) {
if(fun instanceof LambdaFunction && dynamic) {
/* We have to trick the lambda function if we want dynamic
* scoping. I hate making so many objects left and right,
* but this is the easiest way to do what I want here. */
LambdaFunction lfun = ((LambdaFunction)fun);
lfun = new LambdaFunction(lfun.arglist, lfun.body,
getEnv());
CronoType[] argarray = new CronoType[args.size()];
optionsOff();
CronoType lresult = lfun.run(this, args.toArray(argarray));
resetOptions();
deindent();
traceResult(lresult);
printEnvironment();
return lresult;
}
CronoType[] argarray = new CronoType[args.size()];
argarray = args.toArray(argarray);
TypeId[] types = new TypeId[args.size()];
for(int i = 0; i < types.length; ++i) {
types[i] = argarray[i].typeId();
}
for(int i = 0; i < fun.args.length; ++i) {
if(!(fun.args[i].isType(argarray[i]))) {
String argstr = Arrays.toString(types);
String expected = Arrays.toString(fun.args);
except(new InterpreterException(_type_mismatch, fun,
expected, argstr));
}
}
optionsOff();
CronoType fresult;
fresult = ((Function)value).run(this, args.toArray(argarray));
resetOptions();
deindent();
traceResult(fresult);
printEnvironment();
return fresult;
}else {
args.add(0, value);
deindent();
Cons cresult = Cons.fromList(args);
traceResult(cresult);
printEnvironment();
return cresult;
}
}else if(eval == EvalType.PARTIAL) {
List<CronoType> args = new ArrayList<CronoType>();
args.add(value);
while(iter.hasNext()) {
args.add(iter.next().accept(this));
}
CronoType conres = Cons.fromList(args);
traceResult(conres);
return conres;
}
deindent();
/* The initial value is not a function */
except(new InterpreterException("Invalid Function Application: %s is not a function in %s", value, c));
return null;
}
| public CronoType visit(Cons c) {
if(eval == EvalType.NONE) {
printASTNode("List Node");
traceVisit(c);
traceResult(c);
printEnvironment();
return c;
}
Iterator<CronoType> iter = c.iterator();
if(!(iter.hasNext())) {
printASTNode("Nil Node");
traceVisit(Nil.NIL);
traceResult(Nil.NIL);
printEnvironment();
return c; /*< C is an empty list (may be Nil or T) */
}
printASTNode("Function Application Node");
traceVisit(c);
indent();
CronoType value = iter.next().accept(this);
if(value instanceof Function) {
Function fun = ((Function)value);
EvalType reserve = eval;
eval = fun.eval;
if(eval.level > reserve.level) {
eval = reserve;
}
List<CronoType> args = new ArrayList<CronoType>();
while(iter.hasNext()) {
args.add(iter.next().accept(this));
}
eval = reserve;
int arglen = args.size();
int nargs = fun.arity;
if(arglen < nargs) {
if(arglen == 0) {
/* Special case -- we don't have to do anything to the
* function to return it properly. */
deindent();
traceResult(fun);
printEnvironment();
return fun;
}
/* Curry it */
if(fun instanceof LambdaFunction) {
LambdaFunction lfun = ((LambdaFunction)fun);
Environment env = getEnv();
if(!dynamic) {
/* Use the lambda's stored environment */
env = lfun.environment;
}
/* We want to preserve the current environment */
env = new Environment(false);
/* Put known values into the new environment */
for(int i = 0; i < arglen; ++i) {
env.put(lfun.arglist[i], args.get(i));
}
/* Create new argument list and remove remaining args from
* the new environment */
List<Symbol> largs = new ArrayList<Symbol>();
for(int i = arglen; i < lfun.arglist.length; ++i) {
largs.add(lfun.arglist[i]);
env.remove(lfun.arglist[i]);
}
/* Evaluate the body as much as possible */
reserve = eval;
CronoType[] lbody = new CronoType[lfun.body.length];
optionsOff(); /*< Extra indent for clarity */
{
eval = EvalType.PARTIAL;
pushEnv(env);
for(int i = 0; i < lfun.body.length; ++i) {
lbody[i] = lfun.body[i].accept(this);
}
eval = reserve;
popEnv();
}
resetOptions(); /*< Set options back to what they were */
/* Return the new, partially evaluated lambda */
Symbol[] arglist = new Symbol[largs.size()];
LambdaFunction clfun;
clfun = new LambdaFunction(largs.toArray(arglist), lbody,
lfun.environment);
deindent();
traceResult(clfun);
printEnvironment();
return clfun;
}
/* Builtin partial evaluation */
List<CronoType> body = new LinkedList<CronoType>();
body.add(fun);
body.addAll(args); /*< Dump args in order into the new cons */
/* Add symbols for missing args */
List<Symbol> arglist = new ArrayList<Symbol>();
Symbol sym;
for(int i = arglen, n = 0; i < nargs; ++i, ++n) {
sym = new Symbol(String.format("_i?%d!_", n));
body.add(sym);
arglist.add(sym);
}
/* Create a new lambda */
Symbol[] narglist = new Symbol[arglist.size()];
LambdaFunction blfun;
CronoType[] barr = new CronoType[] {Cons.fromList(body)};
blfun = new LambdaFunction(arglist.toArray(narglist), barr,
getEnv());
deindent();
traceResult(blfun);
printEnvironment();
return blfun;
}
if(arglen > nargs && !fun.variadic) {
eval = reserve;
except(new InterpreterException(_too_many_args, fun, arglen,
nargs));
}
/* Full evaluation */
if(eval == EvalType.FULL) {
if(fun instanceof LambdaFunction && dynamic) {
/* We have to trick the lambda function if we want dynamic
* scoping. I hate making so many objects left and right,
* but this is the easiest way to do what I want here. */
LambdaFunction lfun = ((LambdaFunction)fun);
lfun = new LambdaFunction(lfun.arglist, lfun.body,
getEnv());
CronoType[] argarray = new CronoType[args.size()];
optionsOff();
CronoType lresult = null;
try {
lresult = lfun.run(this, args.toArray(argarray));
}catch(RuntimeException e) {
except(e);
}
resetOptions();
deindent();
traceResult(lresult);
printEnvironment();
return lresult;
}
CronoType[] argarray = new CronoType[args.size()];
argarray = args.toArray(argarray);
TypeId[] types = new TypeId[args.size()];
for(int i = 0; i < types.length; ++i) {
types[i] = argarray[i].typeId();
}
for(int i = 0; i < fun.args.length; ++i) {
if(!(fun.args[i].isType(argarray[i]))) {
String argstr = Arrays.toString(types);
String expected = Arrays.toString(fun.args);
except(new InterpreterException(_type_mismatch, fun,
expected, argstr));
}
}
optionsOff();
CronoType fresult = null;
Function fun2 = (Function)value;
try {
fresult = fun2.run(this, args.toArray(argarray));
}catch(RuntimeException re) {
except(re);
}
resetOptions();
deindent();
traceResult(fresult);
printEnvironment();
return fresult;
}else {
args.add(0, value);
deindent();
Cons cresult = Cons.fromList(args);
traceResult(cresult);
printEnvironment();
return cresult;
}
}else if(eval == EvalType.PARTIAL) {
List<CronoType> args = new ArrayList<CronoType>();
args.add(value);
while(iter.hasNext()) {
args.add(iter.next().accept(this));
}
CronoType conres = Cons.fromList(args);
traceResult(conres);
return conres;
}
deindent();
/* The initial value is not a function */
except(new InterpreterException("Invalid Function Application: %s is not a function in %s", value, c));
return null;
}
|
diff --git a/plugins/org.eclipse.tcf.core/src/org/eclipse/tcf/util/TCFTask.java b/plugins/org.eclipse.tcf.core/src/org/eclipse/tcf/util/TCFTask.java
index 9193b6a47..323b5f453 100644
--- a/plugins/org.eclipse.tcf.core/src/org/eclipse/tcf/util/TCFTask.java
+++ b/plugins/org.eclipse.tcf.core/src/org/eclipse/tcf/util/TCFTask.java
@@ -1,323 +1,324 @@
/*******************************************************************************
* Copyright (c) 2007, 2010 Wind River Systems, Inc. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Wind River Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.tcf.util;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.eclipse.tcf.protocol.IChannel;
import org.eclipse.tcf.protocol.Protocol;
/**
* A <tt>TCFTask</tt> is an utility class that represents the result of an asynchronous
* communication over TCF framework. Methods are provided to check if the communication is
* complete, to wait for its completion, and to retrieve the result of
* the communication.
*
* TCFTask is useful when communication is requested by a thread other then TCF dispatch thread.
* If client has a global state, for example, cached remote data, multithreading should be avoided,
* because it is extremely difficult to ensure absence of racing conditions or deadlocks in such environment.
* Such clients should consider message driven design, see TCFDataCache and its usage as an example.
*
* If a client is extending TCFTask it should implement run() method to perform actual communications.
* The run() method will be execute by TCF dispatch thread, and client code should then call either done() or
* error() to indicate that task computations are complete.
*/
public abstract class TCFTask<V> implements Runnable, Future<V> {
private V result;
private boolean done;
private Throwable error;
private boolean canceled;
private IChannel channel;
private IChannel.IChannelListener channel_listener;
/**
* Construct a TCF task object and schedule it for execution.
*/
public TCFTask() {
Protocol.invokeLater(new Runnable() {
public void run() {
try {
TCFTask.this.run();
}
catch (Throwable x) {
if (!done && error == null) error(x);
}
}
});
}
/**
* Construct a TCF task object and schedule it for execution.
* The task will be canceled if it is not completed after given timeout.
* @param timeout - max time in milliseconds.
*/
public TCFTask(long timeout) {
Protocol.invokeLater(new Runnable() {
public void run() {
try {
TCFTask.this.run();
}
catch (Throwable x) {
if (!done && error == null) error(x);
}
}
});
Protocol.invokeLater(timeout, new Runnable() {
public void run() {
cancel(true);
}
});
}
/**
* Construct a TCF task object and schedule it for execution.
* The task will be canceled if the given channel is closed or
* terminated while the task is in progress.
* @param channel
*/
public TCFTask(final IChannel channel) {
Protocol.invokeLater(new Runnable() {
public void run() {
try {
if (channel.getState() != IChannel.STATE_OPEN) throw new Exception("Channel is closed");
TCFTask.this.channel = channel;
channel_listener = new IChannel.IChannelListener() {
public void congestionLevel(int level) {
}
public void onChannelClosed(final Throwable error) {
- cancel(true);
+ if (error != null) error(error);
+ else cancel(true);
}
public void onChannelOpened() {
}
};
channel.addChannelListener(channel_listener);
TCFTask.this.run();
}
catch (Throwable x) {
if (!done && error == null) error(x);
}
}
});
}
/**
* Set a result of this task and notify all threads waiting for the task to complete.
* The method is supposed to be called in response to executing of run() method of this task.
*
* @param result - the computed result
*/
public synchronized void done(V result) {
assert Protocol.isDispatchThread();
if (canceled) return;
assert !done;
assert this.error == null;
assert this.result == null;
this.result = result;
done = true;
if (channel != null) channel.removeChannelListener(channel_listener);
notifyAll();
}
/**
* Set a error and notify all threads waiting for the task to complete.
* The method is supposed to be called in response to executing of run() method of this task.
*
* @param error - computation error.
*/
public synchronized void error(Throwable error) {
assert Protocol.isDispatchThread();
assert error != null;
if (canceled) return;
assert this.error == null;
assert this.result == null;
assert !done;
this.error = error;
if (channel != null) channel.removeChannelListener(channel_listener);
notifyAll();
}
/**
* Attempts to cancel execution of this task. This attempt will
* fail if the task has already completed, already been canceled,
* or could not be canceled for some other reason. If successful,
* and this task has not started when <tt>cancel</tt> is called,
* this task should never run. If the task has already started,
* then the <tt>mayInterruptIfRunning</tt> parameter determines
* whether the thread executing this task should be interrupted in
* an attempt to stop the task.
*
* @param mayInterruptIfRunning <tt>true</tt> if the thread executing this
* task should be interrupted; otherwise, in-progress tasks are allowed
* to complete
* @return <tt>false</tt> if the task could not be canceled,
* typically because it has already completed normally;
* <tt>true</tt> otherwise
*/
public synchronized boolean cancel(boolean mayInterruptIfRunning) {
assert Protocol.isDispatchThread();
if (isDone()) return false;
canceled = true;
error = new CancellationException();
if (channel != null) channel.removeChannelListener(channel_listener);
notifyAll();
return true;
}
/**
* Waits if necessary for the computation to complete, and then
* retrieves its result.
*
* @return the computed result
* @throws CancellationException if the computation was canceled
* @throws ExecutionException if the computation threw an
* exception
* @throws InterruptedException if the current thread was interrupted
* while waiting
*/
public synchronized V get() throws InterruptedException, ExecutionException {
assert !Protocol.isDispatchThread();
while (!isDone()) wait();
if (error != null) {
if (error instanceof ExecutionException) throw (ExecutionException)error;
if (error instanceof InterruptedException) throw (InterruptedException)error;
throw new ExecutionException("TCF task aborted", error);
}
return result;
}
/**
* Waits if necessary for the computation to complete, and then
* retrieves its result.
*
* @return the computed result
* @throws Error if the computation was canceled or threw an exception
*/
public synchronized V getE() {
assert !Protocol.isDispatchThread();
while (!isDone()) {
try {
wait();
}
catch (InterruptedException x) {
throw new Error(x);
}
}
if (error != null) {
if (error instanceof Error) throw (Error)error;
throw new Error("TCF task aborted", error);
}
return result;
}
/**
* Waits if necessary for the computation to complete, and then
* retrieves its result.
*
* @return the computed result
* @throws IOException if the computation was canceled or threw an exception
*/
public synchronized V getIO() throws IOException {
assert !Protocol.isDispatchThread();
while (!isDone()) {
try {
wait();
}
catch (InterruptedException x) {
throw new InterruptedIOException();
}
}
if (error != null) {
if (error instanceof IOException) throw (IOException)error;
IOException y = new IOException("TCF task aborted");
y.initCause(error);
throw y;
}
return result;
}
/**
* Waits if necessary for at most the given time for the computation
* to complete, and then retrieves its result, if available.
*
* @param timeout the maximum time to wait
* @param unit the time unit of the timeout argument
* @return the computed result
* @throws CancellationException if the computation was canceled
* @throws ExecutionException if the computation threw an exception
* @throws InterruptedException if the current thread was interrupted
* while waiting
* @throws TimeoutException if the wait timed out
*/
public synchronized V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
assert !Protocol.isDispatchThread();
if (!isDone()) {
wait(unit.toMillis(timeout));
if (!isDone()) throw new TimeoutException();
}
if (error != null) {
if (error instanceof InterruptedException) throw (InterruptedException)error;
if (error instanceof ExecutionException) throw (ExecutionException)error;
if (error instanceof TimeoutException) throw (TimeoutException)error;
throw new ExecutionException("TCF task aborted", error);
}
return result;
}
/**
* Returns <tt>true</tt> if this task was canceled before it completed
* normally.
*
* @return <tt>true</tt> if task was canceled before it completed
*/
public synchronized boolean isCancelled() {
return canceled;
}
/**
* Returns <tt>true</tt> if this task completed.
*
* Completion may be due to normal termination, an exception, or
* cancellation -- in all of these cases, this method will return
* <tt>true</tt>.
*
* @return <tt>true</tt> if this task completed.
*/
public synchronized boolean isDone() {
return error != null || done;
}
/**
* Return task execution error if any.
* @return Throwable object or null
*/
protected Throwable getError() {
return error;
}
/**
* Return task execution result if any.
* @return result object
*/
protected V getResult() {
return result;
}
}
| true | true | public TCFTask(final IChannel channel) {
Protocol.invokeLater(new Runnable() {
public void run() {
try {
if (channel.getState() != IChannel.STATE_OPEN) throw new Exception("Channel is closed");
TCFTask.this.channel = channel;
channel_listener = new IChannel.IChannelListener() {
public void congestionLevel(int level) {
}
public void onChannelClosed(final Throwable error) {
cancel(true);
}
public void onChannelOpened() {
}
};
channel.addChannelListener(channel_listener);
TCFTask.this.run();
}
catch (Throwable x) {
if (!done && error == null) error(x);
}
}
});
}
| public TCFTask(final IChannel channel) {
Protocol.invokeLater(new Runnable() {
public void run() {
try {
if (channel.getState() != IChannel.STATE_OPEN) throw new Exception("Channel is closed");
TCFTask.this.channel = channel;
channel_listener = new IChannel.IChannelListener() {
public void congestionLevel(int level) {
}
public void onChannelClosed(final Throwable error) {
if (error != null) error(error);
else cancel(true);
}
public void onChannelOpened() {
}
};
channel.addChannelListener(channel_listener);
TCFTask.this.run();
}
catch (Throwable x) {
if (!done && error == null) error(x);
}
}
});
}
|
diff --git a/com/raphfrk/bukkit/serverport/CPUMeasure.java b/com/raphfrk/bukkit/serverport/CPUMeasure.java
index e266f1d..af8eb2b 100644
--- a/com/raphfrk/bukkit/serverport/CPUMeasure.java
+++ b/com/raphfrk/bukkit/serverport/CPUMeasure.java
@@ -1,43 +1,43 @@
package com.raphfrk.bukkit.serverport;
import net.hailxenu.serverautostop.AutoStopPlugin;
import org.bukkit.command.ConsoleCommandSender;
public class CPUMeasure implements Runnable {
Object sync = new Object();
int counter = 0;
long oldTime = 0;
public void run() {
synchronized(sync) {
long delay = ((ServerPortBukkit)MyServer.plugin).serverPortListenerCommon.communicationManager.restartDelay;
long currentTime = System.currentTimeMillis()/1000;
if(oldTime == 0) {
oldTime = currentTime;
counter = 0;
return;
}
counter += 10;
if(currentTime > oldTime + delay) {
double ticksPerMinute = (counter * 60.0) / (currentTime - oldTime);
oldTime = currentTime;
counter = 0;
if(ticksPerMinute < ((ServerPortBukkit)MyServer.plugin).serverPortListenerCommon.communicationManager.restartThreshold) {
AutoStopPlugin autoStop;
autoStop = (AutoStopPlugin)MyServer.bukkitServer.getPluginManager().getPlugin("ServerAutoStop");
if(autoStop != null) {
MyServer.bukkitServer.broadcastMessage("[ServerPort] CPU overload detected, restarting server");
MyServer.bukkitServer.dispatchCommand(new ConsoleCommandSender(MyServer.bukkitServer), "restart");
} else {
MiscUtils.safeLogging("[ServerPort] Autostop plugin required to restart server");
}
}
- System.out.println("ticks per minute: " + ticksPerMinute);
+ //System.out.println("ticks per minute: " + ticksPerMinute);
}
}
}
}
| true | true | public void run() {
synchronized(sync) {
long delay = ((ServerPortBukkit)MyServer.plugin).serverPortListenerCommon.communicationManager.restartDelay;
long currentTime = System.currentTimeMillis()/1000;
if(oldTime == 0) {
oldTime = currentTime;
counter = 0;
return;
}
counter += 10;
if(currentTime > oldTime + delay) {
double ticksPerMinute = (counter * 60.0) / (currentTime - oldTime);
oldTime = currentTime;
counter = 0;
if(ticksPerMinute < ((ServerPortBukkit)MyServer.plugin).serverPortListenerCommon.communicationManager.restartThreshold) {
AutoStopPlugin autoStop;
autoStop = (AutoStopPlugin)MyServer.bukkitServer.getPluginManager().getPlugin("ServerAutoStop");
if(autoStop != null) {
MyServer.bukkitServer.broadcastMessage("[ServerPort] CPU overload detected, restarting server");
MyServer.bukkitServer.dispatchCommand(new ConsoleCommandSender(MyServer.bukkitServer), "restart");
} else {
MiscUtils.safeLogging("[ServerPort] Autostop plugin required to restart server");
}
}
System.out.println("ticks per minute: " + ticksPerMinute);
}
}
}
| public void run() {
synchronized(sync) {
long delay = ((ServerPortBukkit)MyServer.plugin).serverPortListenerCommon.communicationManager.restartDelay;
long currentTime = System.currentTimeMillis()/1000;
if(oldTime == 0) {
oldTime = currentTime;
counter = 0;
return;
}
counter += 10;
if(currentTime > oldTime + delay) {
double ticksPerMinute = (counter * 60.0) / (currentTime - oldTime);
oldTime = currentTime;
counter = 0;
if(ticksPerMinute < ((ServerPortBukkit)MyServer.plugin).serverPortListenerCommon.communicationManager.restartThreshold) {
AutoStopPlugin autoStop;
autoStop = (AutoStopPlugin)MyServer.bukkitServer.getPluginManager().getPlugin("ServerAutoStop");
if(autoStop != null) {
MyServer.bukkitServer.broadcastMessage("[ServerPort] CPU overload detected, restarting server");
MyServer.bukkitServer.dispatchCommand(new ConsoleCommandSender(MyServer.bukkitServer), "restart");
} else {
MiscUtils.safeLogging("[ServerPort] Autostop plugin required to restart server");
}
}
//System.out.println("ticks per minute: " + ticksPerMinute);
}
}
}
|
diff --git a/src/java/main/esg/orp/orp/RegistrationRelayController.java b/src/java/main/esg/orp/orp/RegistrationRelayController.java
index 8a644b7..9e21ce7 100644
--- a/src/java/main/esg/orp/orp/RegistrationRelayController.java
+++ b/src/java/main/esg/orp/orp/RegistrationRelayController.java
@@ -1,149 +1,149 @@
package esg.orp.orp;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
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.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import esg.orp.Parameters;
import esg.orp.utils.HttpUtils;
import esg.security.common.SAMLParameters;
import esg.security.policy.service.api.PolicyAttribute;
import esg.security.policy.web.PolicySerializer;
import esg.security.registration.web.RegistrationRequestUtils;
import esg.security.registration.web.RegistrationResponseUtils;
/**
* Controller that performs registration relay operations.
* This controller acts as the ORP client to the ESGF security services.
*
* @author Luca Cinquini
*/
@Controller
@RequestMapping("/registration-request.htm")
public class RegistrationRelayController {
private final Log LOG = LogFactory.getLog(this.getClass());
private final static String POLICY_ATTRIBUTES_KEY = "policyAttributes";
private final static String POLICY_SERVICE_URI = "/esgf-security/secure/policyService.htm";
private final static String ACTION = "Read";
private final static String REGISTRATION_REQUEST_VIEW = "registration-request";
private final static String REGISTRATION_RESPONSE_URI = "/registration-response.htm";
/**
* GET method invokes the remote PolicyService, parses the XML response, and displays the group selection form.
*
* @param resource : the URL of the resource to be accessed
* @return
* @throws ServletException
*/
@RequestMapping(method = { RequestMethod.GET } )
public String doGet(final HttpServletRequest request, final HttpServletResponse response, final Model model) throws ServletException {
final String resource = request.getParameter(Parameters.HTTP_PARAMETER_RESOURCE);
if (LOG.isDebugEnabled()) LOG.debug("Requested resource="+resource);
// build policy service URL (hosted on the same servlet container)
final String url = "https://"+request.getServerName()+":"+request.getServerPort()+POLICY_SERVICE_URI;
final Map<String,String> pars= new HashMap<String,String>();
pars.put(SAMLParameters.HTTP_PARAMETER_RESOURCE, resource);
pars.put(SAMLParameters.HTTP_PARAMETER_ACTION, ACTION);
if (LOG.isDebugEnabled()) LOG.debug("Invoking policy service at: "+url);
try {
// execute HTTP GET request to PolicyService
String xml = HttpUtils.get(url, pars);
// deserialize XML
Map<PolicyAttribute, List<URL>> attributes = PolicySerializer.deserialize(xml);
// return required attributes to view
model.addAttribute(POLICY_ATTRIBUTES_KEY, attributes);
} catch(Exception e) {
throw new ServletException(e.getMessage());
}
return REGISTRATION_REQUEST_VIEW;
}
/**
* POST method invokes the remote registration service, parses the XML response, and redirects to the view.
*
* @param request
* @param response
* @param model
* @return
* @throws ServletException
*/
@RequestMapping(method = { RequestMethod.POST } )
public void doPost(final HttpServletRequest request, final HttpServletResponse response, final Model model) throws ServletException {
// retrieve POST request parameters
final String user = request.getParameter(Parameters.HTTP_PARAMETER_USER);
final String group = request.getParameter(Parameters.HTTP_PARAMETER_GROUP);
final String role = request.getParameter(Parameters.HTTP_PARAMETER_ROLE);
final String url = request.getParameter(Parameters.HTTP_PARAMETER_URL);
final String resource = request.getParameter(Parameters.HTTP_PARAMETER_RESOURCE);
// compare user to authentication information
final SecurityContext secCtx = SecurityContextHolder.getContext();
final Authentication auth = secCtx.getAuthentication();
if (LOG.isDebugEnabled()) LOG.debug("Security context authentication="+auth);
if (auth==null) throw new ServletException("User not authenticated");
if (!user.equals(auth.getName()))
throw new ServletException("Identity mismatch: post parameter="+user+" authentication identity="+auth.getName());
try {
// build registration request XML
String xmlRequest = RegistrationRequestUtils.serialize(user, group, role);
if (LOG.isInfoEnabled()) LOG.info("Submitting registration request: "+xmlRequest+"\n to URL: "+url);
// execute HTTP POST request to PolicyService
final Map<String,String> pars = new HashMap<String,String>();
pars.put(Parameters.HTTP_PARAMETER_XML, xmlRequest);
String xmlResponse = HttpUtils.post(url, pars);
if (LOG.isInfoEnabled()) LOG.info("Received registration response: "+xmlResponse);
// deserialize XML
final String result = RegistrationResponseUtils.deserialize(xmlResponse);
// GET-POST-REDIRECT
- final String redirect = REGISTRATION_RESPONSE_URI
+ final String redirect = request.getContextPath() + REGISTRATION_RESPONSE_URI
+ "?" + Parameters.HTTP_PARAMETER_GROUP + "=" + URLEncoder.encode(group,"UTF-8")
+ "&" + Parameters.HTTP_PARAMETER_RESULT + "=" + URLEncoder.encode(result,"UTF-8")
+ "&" + Parameters.HTTP_PARAMETER_RESOURCE + "=" + URLEncoder.encode(resource,"UTF-8");
if (LOG.isInfoEnabled()) LOG.info("Redirecting to URL:"+redirect);
response.sendRedirect(redirect);
} catch(Exception e) {
throw new ServletException(e);
}
}
}
| true | true | public void doPost(final HttpServletRequest request, final HttpServletResponse response, final Model model) throws ServletException {
// retrieve POST request parameters
final String user = request.getParameter(Parameters.HTTP_PARAMETER_USER);
final String group = request.getParameter(Parameters.HTTP_PARAMETER_GROUP);
final String role = request.getParameter(Parameters.HTTP_PARAMETER_ROLE);
final String url = request.getParameter(Parameters.HTTP_PARAMETER_URL);
final String resource = request.getParameter(Parameters.HTTP_PARAMETER_RESOURCE);
// compare user to authentication information
final SecurityContext secCtx = SecurityContextHolder.getContext();
final Authentication auth = secCtx.getAuthentication();
if (LOG.isDebugEnabled()) LOG.debug("Security context authentication="+auth);
if (auth==null) throw new ServletException("User not authenticated");
if (!user.equals(auth.getName()))
throw new ServletException("Identity mismatch: post parameter="+user+" authentication identity="+auth.getName());
try {
// build registration request XML
String xmlRequest = RegistrationRequestUtils.serialize(user, group, role);
if (LOG.isInfoEnabled()) LOG.info("Submitting registration request: "+xmlRequest+"\n to URL: "+url);
// execute HTTP POST request to PolicyService
final Map<String,String> pars = new HashMap<String,String>();
pars.put(Parameters.HTTP_PARAMETER_XML, xmlRequest);
String xmlResponse = HttpUtils.post(url, pars);
if (LOG.isInfoEnabled()) LOG.info("Received registration response: "+xmlResponse);
// deserialize XML
final String result = RegistrationResponseUtils.deserialize(xmlResponse);
// GET-POST-REDIRECT
final String redirect = REGISTRATION_RESPONSE_URI
+ "?" + Parameters.HTTP_PARAMETER_GROUP + "=" + URLEncoder.encode(group,"UTF-8")
+ "&" + Parameters.HTTP_PARAMETER_RESULT + "=" + URLEncoder.encode(result,"UTF-8")
+ "&" + Parameters.HTTP_PARAMETER_RESOURCE + "=" + URLEncoder.encode(resource,"UTF-8");
if (LOG.isInfoEnabled()) LOG.info("Redirecting to URL:"+redirect);
response.sendRedirect(redirect);
} catch(Exception e) {
throw new ServletException(e);
}
}
| public void doPost(final HttpServletRequest request, final HttpServletResponse response, final Model model) throws ServletException {
// retrieve POST request parameters
final String user = request.getParameter(Parameters.HTTP_PARAMETER_USER);
final String group = request.getParameter(Parameters.HTTP_PARAMETER_GROUP);
final String role = request.getParameter(Parameters.HTTP_PARAMETER_ROLE);
final String url = request.getParameter(Parameters.HTTP_PARAMETER_URL);
final String resource = request.getParameter(Parameters.HTTP_PARAMETER_RESOURCE);
// compare user to authentication information
final SecurityContext secCtx = SecurityContextHolder.getContext();
final Authentication auth = secCtx.getAuthentication();
if (LOG.isDebugEnabled()) LOG.debug("Security context authentication="+auth);
if (auth==null) throw new ServletException("User not authenticated");
if (!user.equals(auth.getName()))
throw new ServletException("Identity mismatch: post parameter="+user+" authentication identity="+auth.getName());
try {
// build registration request XML
String xmlRequest = RegistrationRequestUtils.serialize(user, group, role);
if (LOG.isInfoEnabled()) LOG.info("Submitting registration request: "+xmlRequest+"\n to URL: "+url);
// execute HTTP POST request to PolicyService
final Map<String,String> pars = new HashMap<String,String>();
pars.put(Parameters.HTTP_PARAMETER_XML, xmlRequest);
String xmlResponse = HttpUtils.post(url, pars);
if (LOG.isInfoEnabled()) LOG.info("Received registration response: "+xmlResponse);
// deserialize XML
final String result = RegistrationResponseUtils.deserialize(xmlResponse);
// GET-POST-REDIRECT
final String redirect = request.getContextPath() + REGISTRATION_RESPONSE_URI
+ "?" + Parameters.HTTP_PARAMETER_GROUP + "=" + URLEncoder.encode(group,"UTF-8")
+ "&" + Parameters.HTTP_PARAMETER_RESULT + "=" + URLEncoder.encode(result,"UTF-8")
+ "&" + Parameters.HTTP_PARAMETER_RESOURCE + "=" + URLEncoder.encode(resource,"UTF-8");
if (LOG.isInfoEnabled()) LOG.info("Redirecting to URL:"+redirect);
response.sendRedirect(redirect);
} catch(Exception e) {
throw new ServletException(e);
}
}
|
diff --git a/src/de/ueller/gps/nmea/NmeaMessage.java b/src/de/ueller/gps/nmea/NmeaMessage.java
index 3bf24b7d..14c027a0 100644
--- a/src/de/ueller/gps/nmea/NmeaMessage.java
+++ b/src/de/ueller/gps/nmea/NmeaMessage.java
@@ -1,272 +1,272 @@
package de.ueller.gps.nmea;
/*
* GpsMid - Copyright (c) 2007 Harald Mueller james22 at users dot sourceforge dot net
* Copyright (c) 2008 Kai Krueger apm at users dot sourceforge dot net
* See Copying
*/
/**
* Geographic Location in Lat/Lon
* field #: 0 1 2 3 4
* sentence: GLL,####.##,N,#####.##,W
*1, Lat (deg, min, hundredths); 2, North or South; 3, Lon; 4, West
*or East.
*
*Geographic Location in Time Differences
* field #: 0 1 2 3 4 5
* sentence: GTD,#####.#,#####.#,#####.#,#####.#,#####.#
*1-5, TD's for secondaries 1 through 5, respectively.
*
*Bearing to Dest wpt from Origin wpt
* field #: 0 1 2 3 4 5 6
* sentence: BOD,###,T,###,M,####,####
*1-2, brg,True; 3-4, brg, Mag; 5, dest wpt; 6, org wpt.
*
*Vector Track and Speed Over Ground (SOG)
* field #: 0 1 2 3 4 5 6 7 8
* sentence: VTG,###,T,###,M,##.#,N,##.#,K
*1-2, brg, True; 3-4, brg, Mag; 5-6, speed, kNots; 7-8, speed,
*Kilometers/hr.
*
*Cross Track Error
* field #: 0 1 2 3 4 5
* sentence: XTE,A,A,#.##,L,N
*1, blink/SNR (A=valid, V=invalid); 2, cycle lock (A/V); 3-5, dist
*off, Left or Right, Nautical miles or Kilometers.
*
*Autopilot (format A)
* field #: 0 1 2 3 4 5 6 7 8 9 10
* sentence: APA,A,A,#.##,L,N,A,A,###,M,####
*1, blink/SNR (A/V); 2 cycle lock (A/V); 3-5, dist off, Left or
*Right, Nautical miles or Kilometers; 6-7, arrival circle, arrival
*perpendicular (A/V); 8-9, brg, Magnetic; 10, dest wpt.
*
*Bearing to Waypoint along Great Circle
* fld: 0 1 2 3 4 5 6 7 8 9 10 11 12
* sen: BWC,HHMMSS,####.##,N,#####.##,W,###,T,###,M,###.#,N,####
*1, Hours, Minutes, Seconds of universal time code; 2-3, Lat, N/S;
*4-5, Lon, W/E; 6-7, brg, True; 8-9, brg, Mag; 10-12, range,
*Nautical miles or Kilometers, dest wpt.
*
*BWR: Bearing to Waypoint, Rhumbline, BPI: Bearing to Point of
*Interest, all follow data field format of BWC.
*
*/
import java.util.Calendar;
import java.util.Date;
import java.util.Vector;
import de.ueller.gps.data.Position;
import de.ueller.gps.data.Satelit;
import de.ueller.gps.tools.StringTokenizer;
import de.ueller.gpsMid.mapData.QueueReader;
import de.ueller.midlet.gps.LocationMsgReceiver;
import de.ueller.midlet.gps.Logger;
public class NmeaMessage {
protected static final Logger logger = Logger.getInstance(NmeaMessage.class,Logger.TRACE);
public StringBuffer buffer=new StringBuffer(80);
private static String spChar=",";
private float head,speed,alt;
private final LocationMsgReceiver receiver;
private int mAllSatellites;
private int qual;
private boolean lastMsgGSV=false;
private Satelit satelit[]=new Satelit[12];
private Calendar cal = Calendar.getInstance();
public NmeaMessage(LocationMsgReceiver receiver) {
this.receiver = receiver;
}
public StringBuffer getBuffer() {
return buffer;
}
public void decodeMessage() {
decodeMessage(buffer.toString());
}
public void decodeMessage(String nmea_sentence) {
Vector param = StringTokenizer.getVector(nmea_sentence, spChar);
String sentence=(String)param.elementAt(0);
try {
// receiver.receiveMessage("got "+buffer.toString() );
if (lastMsgGSV && ! "GSV".equals(sentence)){
receiver.receiveStatelit(satelit);
//satelit=new Satelit[12];
lastMsgGSV=false;
}
if ("GGA".equals(sentence)){
// time
// Time of when fix was taken in UTC
int time_tmp = (int)getFloatToken((String)param.elementAt(1));
cal.set(Calendar.SECOND, time_tmp % 100);
cal.set(Calendar.MINUTE, (time_tmp / 100) % 100);
cal.set(Calendar.HOUR_OF_DAY, (time_tmp / 10000) % 100);
// lat
float lat=getLat((String)param.elementAt(2));
if ("S".equals((String)param.elementAt(3))){
lat= -lat;
}
// lon
float lon=getLon((String)param.elementAt(4));
if ("W".equals((String)param.elementAt(5))){
lon=-lon;
}
// quality
qual = getIntegerToken((String)param.elementAt(6));
// no of Sat;
mAllSatellites = getIntegerToken((String)param.elementAt(7));
// Relative accuracy of horizontal position
// meters above mean sea level
alt=getFloatToken((String)param.elementAt(9));
// Height of geoid above WGS84 ellipsoid
} else if ("RMC".equals(sentence)){
/* RMC encodes the recomended minimum information */
// Time of when fix was taken in UTC
int time_tmp = (int)getFloatToken((String)param.elementAt(1));
cal.set(Calendar.SECOND, time_tmp % 100);
cal.set(Calendar.MINUTE, (time_tmp / 100) % 100);
cal.set(Calendar.HOUR_OF_DAY, (time_tmp / 10000) % 100);
//Status A=active or V=Void.
String valSolution = (String)param.elementAt(2);
if (valSolution.equals("V")) {
this.qual = 0;
receiver.receiveSolution("NoFix");
return;
}
if (valSolution.equalsIgnoreCase("A") && this.qual == 0) this.qual = 1;
//Latitude
float lat=getLat((String)param.elementAt(3));
if ("S".equals((String)param.elementAt(4))){
lat= -lat;
}
//Longitude
float lon=getLon((String)param.elementAt(5));
if ("W".equals((String)param.elementAt(6))){
lon=-lon;
}
//Speed over the ground in knots
//GpsMid uses m/s
speed=getFloatToken((String)param.elementAt(7))*0.5144444f;
//Track angle in degrees
head=getFloatToken((String)param.elementAt(8));
//Date
int date_tmp = getIntegerToken((String)param.elementAt(9));
cal.set(Calendar.YEAR, 2000 + date_tmp % 100);
cal.set(Calendar.MONTH, ((date_tmp / 100) % 100) - 1);
cal.set(Calendar.DAY_OF_MONTH, (date_tmp / 10000) % 100);
//Magnetic Variation
Position p=new Position(lat,lon,alt,speed,head,0,cal.getTime());
receiver.receivePosItion(p);
if (this.qual > 1) {
receiver.receiveSolution("D" + mAllSatellites + "S");
} else {
receiver.receiveSolution(mAllSatellites + "S");
}
} else if ("VTG".equals(sentence)){
head=getFloatToken((String)param.elementAt(1));
//Convert from knots to m/s
speed=getFloatToken((String)param.elementAt(7))*0.5144444f;
} else if ("GSA".equals(sentence)){
//#debug info
logger.info("Decoding GSA");
/**
* Encodes Satellite status
*
* Auto selection of 2D or 3D fix (M = manual)
* 3D fix - values include: 1 = no fix
* 2 = 2D fix
* 3 = 3D fix
*/
/**
* A list of up to 12 PRNs which are used for the fix
*/
for (int j = 0; j < 12; j++) {
/**
* Resetting all the satelits to non locked
*/
if ((satelit[j] != null)) {
satelit[j].isLocked(false);
}
}
for (int i = 0; i < 12; i++) {
int prn = getIntegerToken((String)param.elementAt(i + 3));
if (prn != 0) {
//#debug info
logger.info("Satelit " + prn + " is part of fix");
for (int j = 0; j < 12; j++) {
if ((satelit[j] != null) && (satelit[j].id == prn)) {
satelit[j].isLocked(true);
}
}
}
}
/**
* PDOP (dilution of precision)
* Horizontal dilution of precision (HDOP)
* Vertical dilution of precision (VDOP)
*/
} else if ("GSV".equals(sentence)) {
/* GSV encodes the satellites that are currently in view
* A maximum of 4 satellites are reported per message,
* if more are visible, then they are split over multiple messages *
*/
int j;
// Calculate which satellites are in this message (message number * 4)
j=(getIntegerToken((String)param.elementAt(2))-1)*4;
int noSatInView =(getIntegerToken((String)param.elementAt(3)));
for (int i=4; i < param.size() && j < 12; i+=4, j++) {
if (satelit[j]==null){
satelit[j]=new Satelit();
}
satelit[j].id=getIntegerToken((String)param.elementAt(i));
satelit[j].elev=getIntegerToken((String)param.elementAt(i+1));
satelit[j].azimut=getIntegerToken((String)param.elementAt(i+2));
satelit[j].snr=getIntegerToken((String)param.elementAt(i+3));
}
lastMsgGSV=true;
for (int i = noSatInView; i < 12; i++) {
satelit[i] = null;
}
}
} catch (RuntimeException e) {
- logger.error("Error while decoding "+sentence + " " + e.getMessage());
+ logger.exception("Error while decoding "+sentence, e);
}
}
private int getIntegerToken(String s){
if (s==null || s.length()==0)
return 0;
return Integer.parseInt(s);
}
private float getFloatToken(String s){
if (s==null || s.length()==0)
return 0;
return Float.parseFloat(s);
}
private float getLat(String s){
if (s.length() < 2)
return 0.0f;
int lat=Integer.parseInt(s.substring(0,2));
float latf=Float.parseFloat(s.substring(2));
return lat+latf/60;
}
private float getLon(String s){
if (s.length() < 3)
return 0.0f;
int lon=Integer.parseInt(s.substring(0,3));
float lonf=Float.parseFloat(s.substring(3));
return lon+lonf/60;
}
}
| true | true | public void decodeMessage(String nmea_sentence) {
Vector param = StringTokenizer.getVector(nmea_sentence, spChar);
String sentence=(String)param.elementAt(0);
try {
// receiver.receiveMessage("got "+buffer.toString() );
if (lastMsgGSV && ! "GSV".equals(sentence)){
receiver.receiveStatelit(satelit);
//satelit=new Satelit[12];
lastMsgGSV=false;
}
if ("GGA".equals(sentence)){
// time
// Time of when fix was taken in UTC
int time_tmp = (int)getFloatToken((String)param.elementAt(1));
cal.set(Calendar.SECOND, time_tmp % 100);
cal.set(Calendar.MINUTE, (time_tmp / 100) % 100);
cal.set(Calendar.HOUR_OF_DAY, (time_tmp / 10000) % 100);
// lat
float lat=getLat((String)param.elementAt(2));
if ("S".equals((String)param.elementAt(3))){
lat= -lat;
}
// lon
float lon=getLon((String)param.elementAt(4));
if ("W".equals((String)param.elementAt(5))){
lon=-lon;
}
// quality
qual = getIntegerToken((String)param.elementAt(6));
// no of Sat;
mAllSatellites = getIntegerToken((String)param.elementAt(7));
// Relative accuracy of horizontal position
// meters above mean sea level
alt=getFloatToken((String)param.elementAt(9));
// Height of geoid above WGS84 ellipsoid
} else if ("RMC".equals(sentence)){
/* RMC encodes the recomended minimum information */
// Time of when fix was taken in UTC
int time_tmp = (int)getFloatToken((String)param.elementAt(1));
cal.set(Calendar.SECOND, time_tmp % 100);
cal.set(Calendar.MINUTE, (time_tmp / 100) % 100);
cal.set(Calendar.HOUR_OF_DAY, (time_tmp / 10000) % 100);
//Status A=active or V=Void.
String valSolution = (String)param.elementAt(2);
if (valSolution.equals("V")) {
this.qual = 0;
receiver.receiveSolution("NoFix");
return;
}
if (valSolution.equalsIgnoreCase("A") && this.qual == 0) this.qual = 1;
//Latitude
float lat=getLat((String)param.elementAt(3));
if ("S".equals((String)param.elementAt(4))){
lat= -lat;
}
//Longitude
float lon=getLon((String)param.elementAt(5));
if ("W".equals((String)param.elementAt(6))){
lon=-lon;
}
//Speed over the ground in knots
//GpsMid uses m/s
speed=getFloatToken((String)param.elementAt(7))*0.5144444f;
//Track angle in degrees
head=getFloatToken((String)param.elementAt(8));
//Date
int date_tmp = getIntegerToken((String)param.elementAt(9));
cal.set(Calendar.YEAR, 2000 + date_tmp % 100);
cal.set(Calendar.MONTH, ((date_tmp / 100) % 100) - 1);
cal.set(Calendar.DAY_OF_MONTH, (date_tmp / 10000) % 100);
//Magnetic Variation
Position p=new Position(lat,lon,alt,speed,head,0,cal.getTime());
receiver.receivePosItion(p);
if (this.qual > 1) {
receiver.receiveSolution("D" + mAllSatellites + "S");
} else {
receiver.receiveSolution(mAllSatellites + "S");
}
} else if ("VTG".equals(sentence)){
head=getFloatToken((String)param.elementAt(1));
//Convert from knots to m/s
speed=getFloatToken((String)param.elementAt(7))*0.5144444f;
} else if ("GSA".equals(sentence)){
//#debug info
logger.info("Decoding GSA");
/**
* Encodes Satellite status
*
* Auto selection of 2D or 3D fix (M = manual)
* 3D fix - values include: 1 = no fix
* 2 = 2D fix
* 3 = 3D fix
*/
/**
* A list of up to 12 PRNs which are used for the fix
*/
for (int j = 0; j < 12; j++) {
/**
* Resetting all the satelits to non locked
*/
if ((satelit[j] != null)) {
satelit[j].isLocked(false);
}
}
for (int i = 0; i < 12; i++) {
int prn = getIntegerToken((String)param.elementAt(i + 3));
if (prn != 0) {
//#debug info
logger.info("Satelit " + prn + " is part of fix");
for (int j = 0; j < 12; j++) {
if ((satelit[j] != null) && (satelit[j].id == prn)) {
satelit[j].isLocked(true);
}
}
}
}
/**
* PDOP (dilution of precision)
* Horizontal dilution of precision (HDOP)
* Vertical dilution of precision (VDOP)
*/
} else if ("GSV".equals(sentence)) {
/* GSV encodes the satellites that are currently in view
* A maximum of 4 satellites are reported per message,
* if more are visible, then they are split over multiple messages *
*/
int j;
// Calculate which satellites are in this message (message number * 4)
j=(getIntegerToken((String)param.elementAt(2))-1)*4;
int noSatInView =(getIntegerToken((String)param.elementAt(3)));
for (int i=4; i < param.size() && j < 12; i+=4, j++) {
if (satelit[j]==null){
satelit[j]=new Satelit();
}
satelit[j].id=getIntegerToken((String)param.elementAt(i));
satelit[j].elev=getIntegerToken((String)param.elementAt(i+1));
satelit[j].azimut=getIntegerToken((String)param.elementAt(i+2));
satelit[j].snr=getIntegerToken((String)param.elementAt(i+3));
}
lastMsgGSV=true;
for (int i = noSatInView; i < 12; i++) {
satelit[i] = null;
}
}
} catch (RuntimeException e) {
logger.error("Error while decoding "+sentence + " " + e.getMessage());
}
}
| public void decodeMessage(String nmea_sentence) {
Vector param = StringTokenizer.getVector(nmea_sentence, spChar);
String sentence=(String)param.elementAt(0);
try {
// receiver.receiveMessage("got "+buffer.toString() );
if (lastMsgGSV && ! "GSV".equals(sentence)){
receiver.receiveStatelit(satelit);
//satelit=new Satelit[12];
lastMsgGSV=false;
}
if ("GGA".equals(sentence)){
// time
// Time of when fix was taken in UTC
int time_tmp = (int)getFloatToken((String)param.elementAt(1));
cal.set(Calendar.SECOND, time_tmp % 100);
cal.set(Calendar.MINUTE, (time_tmp / 100) % 100);
cal.set(Calendar.HOUR_OF_DAY, (time_tmp / 10000) % 100);
// lat
float lat=getLat((String)param.elementAt(2));
if ("S".equals((String)param.elementAt(3))){
lat= -lat;
}
// lon
float lon=getLon((String)param.elementAt(4));
if ("W".equals((String)param.elementAt(5))){
lon=-lon;
}
// quality
qual = getIntegerToken((String)param.elementAt(6));
// no of Sat;
mAllSatellites = getIntegerToken((String)param.elementAt(7));
// Relative accuracy of horizontal position
// meters above mean sea level
alt=getFloatToken((String)param.elementAt(9));
// Height of geoid above WGS84 ellipsoid
} else if ("RMC".equals(sentence)){
/* RMC encodes the recomended minimum information */
// Time of when fix was taken in UTC
int time_tmp = (int)getFloatToken((String)param.elementAt(1));
cal.set(Calendar.SECOND, time_tmp % 100);
cal.set(Calendar.MINUTE, (time_tmp / 100) % 100);
cal.set(Calendar.HOUR_OF_DAY, (time_tmp / 10000) % 100);
//Status A=active or V=Void.
String valSolution = (String)param.elementAt(2);
if (valSolution.equals("V")) {
this.qual = 0;
receiver.receiveSolution("NoFix");
return;
}
if (valSolution.equalsIgnoreCase("A") && this.qual == 0) this.qual = 1;
//Latitude
float lat=getLat((String)param.elementAt(3));
if ("S".equals((String)param.elementAt(4))){
lat= -lat;
}
//Longitude
float lon=getLon((String)param.elementAt(5));
if ("W".equals((String)param.elementAt(6))){
lon=-lon;
}
//Speed over the ground in knots
//GpsMid uses m/s
speed=getFloatToken((String)param.elementAt(7))*0.5144444f;
//Track angle in degrees
head=getFloatToken((String)param.elementAt(8));
//Date
int date_tmp = getIntegerToken((String)param.elementAt(9));
cal.set(Calendar.YEAR, 2000 + date_tmp % 100);
cal.set(Calendar.MONTH, ((date_tmp / 100) % 100) - 1);
cal.set(Calendar.DAY_OF_MONTH, (date_tmp / 10000) % 100);
//Magnetic Variation
Position p=new Position(lat,lon,alt,speed,head,0,cal.getTime());
receiver.receivePosItion(p);
if (this.qual > 1) {
receiver.receiveSolution("D" + mAllSatellites + "S");
} else {
receiver.receiveSolution(mAllSatellites + "S");
}
} else if ("VTG".equals(sentence)){
head=getFloatToken((String)param.elementAt(1));
//Convert from knots to m/s
speed=getFloatToken((String)param.elementAt(7))*0.5144444f;
} else if ("GSA".equals(sentence)){
//#debug info
logger.info("Decoding GSA");
/**
* Encodes Satellite status
*
* Auto selection of 2D or 3D fix (M = manual)
* 3D fix - values include: 1 = no fix
* 2 = 2D fix
* 3 = 3D fix
*/
/**
* A list of up to 12 PRNs which are used for the fix
*/
for (int j = 0; j < 12; j++) {
/**
* Resetting all the satelits to non locked
*/
if ((satelit[j] != null)) {
satelit[j].isLocked(false);
}
}
for (int i = 0; i < 12; i++) {
int prn = getIntegerToken((String)param.elementAt(i + 3));
if (prn != 0) {
//#debug info
logger.info("Satelit " + prn + " is part of fix");
for (int j = 0; j < 12; j++) {
if ((satelit[j] != null) && (satelit[j].id == prn)) {
satelit[j].isLocked(true);
}
}
}
}
/**
* PDOP (dilution of precision)
* Horizontal dilution of precision (HDOP)
* Vertical dilution of precision (VDOP)
*/
} else if ("GSV".equals(sentence)) {
/* GSV encodes the satellites that are currently in view
* A maximum of 4 satellites are reported per message,
* if more are visible, then they are split over multiple messages *
*/
int j;
// Calculate which satellites are in this message (message number * 4)
j=(getIntegerToken((String)param.elementAt(2))-1)*4;
int noSatInView =(getIntegerToken((String)param.elementAt(3)));
for (int i=4; i < param.size() && j < 12; i+=4, j++) {
if (satelit[j]==null){
satelit[j]=new Satelit();
}
satelit[j].id=getIntegerToken((String)param.elementAt(i));
satelit[j].elev=getIntegerToken((String)param.elementAt(i+1));
satelit[j].azimut=getIntegerToken((String)param.elementAt(i+2));
satelit[j].snr=getIntegerToken((String)param.elementAt(i+3));
}
lastMsgGSV=true;
for (int i = noSatInView; i < 12; i++) {
satelit[i] = null;
}
}
} catch (RuntimeException e) {
logger.exception("Error while decoding "+sentence, e);
}
}
|
diff --git a/src/com/android/settings/accounts/ManageAccountsSettings.java b/src/com/android/settings/accounts/ManageAccountsSettings.java
index 4efe62be0..d769cdb3a 100644
--- a/src/com/android/settings/accounts/ManageAccountsSettings.java
+++ b/src/com/android/settings/accounts/ManageAccountsSettings.java
@@ -1,351 +1,353 @@
/*
* Copyright (C) 2008 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.settings.accounts;
import com.android.settings.AccountPreference;
import com.android.settings.DialogCreatable;
import com.android.settings.R;
import com.android.settings.vpn.VpnTypeSelection;
import com.google.android.collect.Maps;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AuthenticatorDescription;
import android.accounts.OnAccountsUpdateListener;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SyncAdapterType;
import android.content.SyncInfo;
import android.content.SyncStatusInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceCategory;
import android.preference.PreferenceScreen;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
public class ManageAccountsSettings extends AccountPreferenceBase
implements OnAccountsUpdateListener, DialogCreatable {
private static final String TAG = ManageAccountsSettings.class.getSimpleName();
private static final String AUTHORITIES_FILTER_KEY = "authorities";
private static final boolean LDEBUG = Log.isLoggable(TAG, Log.DEBUG);
private static final String AUTO_SYNC_CHECKBOX_KEY = "syncAutomaticallyCheckBox";
private static final String MANAGE_ACCOUNTS_CATEGORY_KEY = "manageAccountsCategory";
private static final String BACKGROUND_DATA_CHECKBOX_KEY = "backgroundDataCheckBox";
private static final int DIALOG_DISABLE_BACKGROUND_DATA = 1;
private static final int MENU_ADD_ACCOUNT = Menu.FIRST;
private static final int REQUEST_SHOW_SYNC_SETTINGS = 1;
private CheckBoxPreference mBackgroundDataCheckBox;
private PreferenceCategory mManageAccountsCategory;
private String[] mAuthorities;
private TextView mErrorInfoView;
private Button mAddAccountButton;
private CheckBoxPreference mAutoSyncCheckbox;
private SettingsDialogFragment mDialogFragment;
private AuthenticatorDescription[] mAuthDescs;
private Map<String, AuthenticatorDescription> mTypeToAuthDescription
= new HashMap<String, AuthenticatorDescription>();
private HashMap<String, ArrayList<String>> mAccountTypeToAuthorities = null;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
addPreferencesFromResource(R.xml.manage_accounts_settings);
AccountManager.get(getActivity()).addOnAccountsUpdatedListener(this, null, true);
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.manage_accounts_screen, container, false);
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
final Activity activity = getActivity();
final View view = getView();
mErrorInfoView = (TextView)view.findViewById(R.id.sync_settings_error_info);
mErrorInfoView.setVisibility(View.GONE);
mErrorInfoView.setCompoundDrawablesWithIntrinsicBounds(
activity.getResources().getDrawable(R.drawable.ic_list_syncerror),
null, null, null);
mBackgroundDataCheckBox = (CheckBoxPreference) findPreference(BACKGROUND_DATA_CHECKBOX_KEY);
mAutoSyncCheckbox = (CheckBoxPreference) findPreference(AUTO_SYNC_CHECKBOX_KEY);
mManageAccountsCategory = (PreferenceCategory)findPreference(MANAGE_ACCOUNTS_CATEGORY_KEY);
mAuthorities = activity.getIntent().getStringArrayExtra(AUTHORITIES_FILTER_KEY);
updateAuthDescriptions();
}
@Override
public void onDestroy() {
AccountManager.get(getActivity()).removeOnAccountsUpdatedListener(this);
super.onDestroy();
}
@Override
public boolean onPreferenceTreeClick(PreferenceScreen preferences, Preference preference) {
if (preference == mBackgroundDataCheckBox) {
final ConnectivityManager connManager = (ConnectivityManager)
getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
final boolean oldBackgroundDataSetting = connManager.getBackgroundDataSetting();
final boolean backgroundDataSetting = mBackgroundDataCheckBox.isChecked();
if (oldBackgroundDataSetting != backgroundDataSetting) {
if (backgroundDataSetting) {
setBackgroundDataInt(true);
onSyncStateUpdated();
} else {
// This will get unchecked only if the user hits "Ok"
mBackgroundDataCheckBox.setChecked(true);
showDialog(DIALOG_DISABLE_BACKGROUND_DATA);
}
}
} else if (preference == mAutoSyncCheckbox) {
ContentResolver.setMasterSyncAutomatically(mAutoSyncCheckbox.isChecked());
onSyncStateUpdated();
} else if (preference instanceof AccountPreference) {
startAccountSettings((AccountPreference) preference);
} else {
return false;
}
return true;
}
private void startAccountSettings(AccountPreference acctPref) {
Bundle args = new Bundle();
args.putParcelable(AccountSyncSettings.ACCOUNT_KEY, acctPref.getAccount());
((PreferenceActivity) getActivity()).startPreferencePanel(
AccountSyncSettings.class.getCanonicalName(), args,
R.string.account_sync_settings_title, acctPref.getAccount().name,
this, REQUEST_SHOW_SYNC_SETTINGS);
}
@Override
public Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DISABLE_BACKGROUND_DATA:
final CheckBoxPreference pref =
(CheckBoxPreference) findPreference(BACKGROUND_DATA_CHECKBOX_KEY);
return new AlertDialog.Builder(getActivity())
.setTitle(R.string.background_data_dialog_title)
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage(R.string.background_data_dialog_message)
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
setBackgroundDataInt(false);
pref.setChecked(false);
onSyncStateUpdated();
}
})
.setNegativeButton(android.R.string.cancel, null)
.create();
}
return null;
}
public void showDialog(int dialogId) {
if (mDialogFragment != null) {
Log.e(TAG, "Old dialog fragment not null!");
}
mDialogFragment = new SettingsDialogFragment(this, dialogId);
mDialogFragment.show(getActivity().getFragmentManager(), Integer.toString(dialogId));
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
MenuItem actionItem =
menu.add(0, MENU_ADD_ACCOUNT, 0, R.string.add_account_label)
.setIcon(R.drawable.ic_menu_add);
actionItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM
| MenuItem.SHOW_AS_ACTION_WITH_TEXT);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == MENU_ADD_ACCOUNT) {
onAddAccountClicked();
return true;
} else {
return super.onOptionsItemSelected(item);
}
}
private void setBackgroundDataInt(boolean enabled) {
final ConnectivityManager connManager = (ConnectivityManager)
getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
connManager.setBackgroundDataSetting(enabled);
}
protected void onSyncStateUpdated() {
+ // Catch any delayed delivery of update messages
+ if (getActivity() == null) return;
// Set background connection state
final ConnectivityManager connManager = (ConnectivityManager)
getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
final boolean backgroundDataSetting = connManager.getBackgroundDataSetting();
mBackgroundDataCheckBox.setChecked(backgroundDataSetting);
boolean masterSyncAutomatically = ContentResolver.getMasterSyncAutomatically();
mAutoSyncCheckbox.setChecked(masterSyncAutomatically);
// iterate over all the preferences, setting the state properly for each
SyncInfo currentSync = ContentResolver.getCurrentSync();
boolean anySyncFailed = false; // true if sync on any account failed
// only track userfacing sync adapters when deciding if account is synced or not
final SyncAdapterType[] syncAdapters = ContentResolver.getSyncAdapterTypes();
HashSet<String> userFacing = new HashSet<String>();
for (int k = 0, n = syncAdapters.length; k < n; k++) {
final SyncAdapterType sa = syncAdapters[k];
if (sa.isUserVisible()) {
userFacing.add(sa.authority);
}
}
for (int i = 0, count = mManageAccountsCategory.getPreferenceCount(); i < count; i++) {
Preference pref = mManageAccountsCategory.getPreference(i);
if (! (pref instanceof AccountPreference)) {
continue;
}
AccountPreference accountPref = (AccountPreference) pref;
Account account = accountPref.getAccount();
int syncCount = 0;
boolean syncIsFailing = false;
final ArrayList<String> authorities = accountPref.getAuthorities();
if (authorities != null) {
for (String authority : authorities) {
SyncStatusInfo status = ContentResolver.getSyncStatus(account, authority);
boolean syncEnabled = ContentResolver.getSyncAutomatically(account, authority)
&& masterSyncAutomatically
&& backgroundDataSetting
&& (ContentResolver.getIsSyncable(account, authority) > 0);
boolean authorityIsPending = ContentResolver.isSyncPending(account, authority);
boolean activelySyncing = currentSync != null
&& currentSync.authority.equals(authority)
&& new Account(currentSync.account.name, currentSync.account.type)
.equals(account);
boolean lastSyncFailed = status != null
&& syncEnabled
&& status.lastFailureTime != 0
&& status.getLastFailureMesgAsInt(0)
!= ContentResolver.SYNC_ERROR_SYNC_ALREADY_IN_PROGRESS;
if (lastSyncFailed && !activelySyncing && !authorityIsPending) {
syncIsFailing = true;
anySyncFailed = true;
}
syncCount += syncEnabled && userFacing.contains(authority) ? 1 : 0;
}
} else {
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.v(TAG, "no syncadapters found for " + account);
}
}
int syncStatus = AccountPreference.SYNC_DISABLED;
if (syncIsFailing) {
syncStatus = AccountPreference.SYNC_ERROR;
} else if (syncCount == 0) {
syncStatus = AccountPreference.SYNC_DISABLED;
} else if (syncCount > 0) {
syncStatus = AccountPreference.SYNC_ENABLED;
}
accountPref.setSyncStatus(syncStatus);
}
mErrorInfoView.setVisibility(anySyncFailed ? View.VISIBLE : View.GONE);
}
@Override
public void onAccountsUpdated(Account[] accounts) {
mManageAccountsCategory.removeAll();
for (int i = 0, n = accounts.length; i < n; i++) {
final Account account = accounts[i];
final ArrayList<String> auths = getAuthoritiesForAccountType(account.type);
boolean showAccount = true;
if (mAuthorities != null && auths != null) {
showAccount = false;
for (String requestedAuthority : mAuthorities) {
if (auths.contains(requestedAuthority)) {
showAccount = true;
break;
}
}
}
if (showAccount) {
final Drawable icon = getDrawableForType(account.type);
final AccountPreference preference =
new AccountPreference(getActivity(), account, icon, auths);
mManageAccountsCategory.addPreference(preference);
}
}
onSyncStateUpdated();
}
protected void onAuthDescriptionsUpdated() {
// Update account icons for all account preference items
for (int i = 0; i < mManageAccountsCategory.getPreferenceCount(); i++) {
AccountPreference pref = (AccountPreference) mManageAccountsCategory.getPreference(i);
pref.setProviderIcon(getDrawableForType(pref.getAccount().type));
pref.setSummary(getLabelForType(pref.getAccount().type));
}
}
public void onAddAccountClicked() {
Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS");
intent.putExtra(AUTHORITIES_FILTER_KEY, mAuthorities);
startActivity(intent);
}
}
| true | true | protected void onSyncStateUpdated() {
// Set background connection state
final ConnectivityManager connManager = (ConnectivityManager)
getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
final boolean backgroundDataSetting = connManager.getBackgroundDataSetting();
mBackgroundDataCheckBox.setChecked(backgroundDataSetting);
boolean masterSyncAutomatically = ContentResolver.getMasterSyncAutomatically();
mAutoSyncCheckbox.setChecked(masterSyncAutomatically);
// iterate over all the preferences, setting the state properly for each
SyncInfo currentSync = ContentResolver.getCurrentSync();
boolean anySyncFailed = false; // true if sync on any account failed
// only track userfacing sync adapters when deciding if account is synced or not
final SyncAdapterType[] syncAdapters = ContentResolver.getSyncAdapterTypes();
HashSet<String> userFacing = new HashSet<String>();
for (int k = 0, n = syncAdapters.length; k < n; k++) {
final SyncAdapterType sa = syncAdapters[k];
if (sa.isUserVisible()) {
userFacing.add(sa.authority);
}
}
for (int i = 0, count = mManageAccountsCategory.getPreferenceCount(); i < count; i++) {
Preference pref = mManageAccountsCategory.getPreference(i);
if (! (pref instanceof AccountPreference)) {
continue;
}
AccountPreference accountPref = (AccountPreference) pref;
Account account = accountPref.getAccount();
int syncCount = 0;
boolean syncIsFailing = false;
final ArrayList<String> authorities = accountPref.getAuthorities();
if (authorities != null) {
for (String authority : authorities) {
SyncStatusInfo status = ContentResolver.getSyncStatus(account, authority);
boolean syncEnabled = ContentResolver.getSyncAutomatically(account, authority)
&& masterSyncAutomatically
&& backgroundDataSetting
&& (ContentResolver.getIsSyncable(account, authority) > 0);
boolean authorityIsPending = ContentResolver.isSyncPending(account, authority);
boolean activelySyncing = currentSync != null
&& currentSync.authority.equals(authority)
&& new Account(currentSync.account.name, currentSync.account.type)
.equals(account);
boolean lastSyncFailed = status != null
&& syncEnabled
&& status.lastFailureTime != 0
&& status.getLastFailureMesgAsInt(0)
!= ContentResolver.SYNC_ERROR_SYNC_ALREADY_IN_PROGRESS;
if (lastSyncFailed && !activelySyncing && !authorityIsPending) {
syncIsFailing = true;
anySyncFailed = true;
}
syncCount += syncEnabled && userFacing.contains(authority) ? 1 : 0;
}
} else {
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.v(TAG, "no syncadapters found for " + account);
}
}
int syncStatus = AccountPreference.SYNC_DISABLED;
if (syncIsFailing) {
syncStatus = AccountPreference.SYNC_ERROR;
} else if (syncCount == 0) {
syncStatus = AccountPreference.SYNC_DISABLED;
} else if (syncCount > 0) {
syncStatus = AccountPreference.SYNC_ENABLED;
}
accountPref.setSyncStatus(syncStatus);
}
mErrorInfoView.setVisibility(anySyncFailed ? View.VISIBLE : View.GONE);
}
| protected void onSyncStateUpdated() {
// Catch any delayed delivery of update messages
if (getActivity() == null) return;
// Set background connection state
final ConnectivityManager connManager = (ConnectivityManager)
getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
final boolean backgroundDataSetting = connManager.getBackgroundDataSetting();
mBackgroundDataCheckBox.setChecked(backgroundDataSetting);
boolean masterSyncAutomatically = ContentResolver.getMasterSyncAutomatically();
mAutoSyncCheckbox.setChecked(masterSyncAutomatically);
// iterate over all the preferences, setting the state properly for each
SyncInfo currentSync = ContentResolver.getCurrentSync();
boolean anySyncFailed = false; // true if sync on any account failed
// only track userfacing sync adapters when deciding if account is synced or not
final SyncAdapterType[] syncAdapters = ContentResolver.getSyncAdapterTypes();
HashSet<String> userFacing = new HashSet<String>();
for (int k = 0, n = syncAdapters.length; k < n; k++) {
final SyncAdapterType sa = syncAdapters[k];
if (sa.isUserVisible()) {
userFacing.add(sa.authority);
}
}
for (int i = 0, count = mManageAccountsCategory.getPreferenceCount(); i < count; i++) {
Preference pref = mManageAccountsCategory.getPreference(i);
if (! (pref instanceof AccountPreference)) {
continue;
}
AccountPreference accountPref = (AccountPreference) pref;
Account account = accountPref.getAccount();
int syncCount = 0;
boolean syncIsFailing = false;
final ArrayList<String> authorities = accountPref.getAuthorities();
if (authorities != null) {
for (String authority : authorities) {
SyncStatusInfo status = ContentResolver.getSyncStatus(account, authority);
boolean syncEnabled = ContentResolver.getSyncAutomatically(account, authority)
&& masterSyncAutomatically
&& backgroundDataSetting
&& (ContentResolver.getIsSyncable(account, authority) > 0);
boolean authorityIsPending = ContentResolver.isSyncPending(account, authority);
boolean activelySyncing = currentSync != null
&& currentSync.authority.equals(authority)
&& new Account(currentSync.account.name, currentSync.account.type)
.equals(account);
boolean lastSyncFailed = status != null
&& syncEnabled
&& status.lastFailureTime != 0
&& status.getLastFailureMesgAsInt(0)
!= ContentResolver.SYNC_ERROR_SYNC_ALREADY_IN_PROGRESS;
if (lastSyncFailed && !activelySyncing && !authorityIsPending) {
syncIsFailing = true;
anySyncFailed = true;
}
syncCount += syncEnabled && userFacing.contains(authority) ? 1 : 0;
}
} else {
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.v(TAG, "no syncadapters found for " + account);
}
}
int syncStatus = AccountPreference.SYNC_DISABLED;
if (syncIsFailing) {
syncStatus = AccountPreference.SYNC_ERROR;
} else if (syncCount == 0) {
syncStatus = AccountPreference.SYNC_DISABLED;
} else if (syncCount > 0) {
syncStatus = AccountPreference.SYNC_ENABLED;
}
accountPref.setSyncStatus(syncStatus);
}
mErrorInfoView.setVisibility(anySyncFailed ? View.VISIBLE : View.GONE);
}
|
diff --git a/src/main/org/jboss/messaging/core/ChannelSupport.java b/src/main/org/jboss/messaging/core/ChannelSupport.java
index e9711ce2c..d57c5c144 100644
--- a/src/main/org/jboss/messaging/core/ChannelSupport.java
+++ b/src/main/org/jboss/messaging/core/ChannelSupport.java
@@ -1,438 +1,438 @@
/**
* JBoss, Home of Professional Open Source
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package org.jboss.messaging.core;
import org.jboss.logging.Logger;
import org.jboss.messaging.core.tx.Transaction;
import java.util.Iterator;
import java.util.Set;
import java.util.List;
import java.util.ArrayList;
import java.io.Serializable;
/**
* A basic channel implementation. It supports atomicity, isolation and, if a non-null
* PersistenceManager is available, it supports recoverability of reliable messages.
*
* @author <a href="mailto:[email protected]">Ovidiu Feodorov</a>
* @author <a href="mailto:[email protected]">Tim Fox</a>
* @version <tt>$Revision$</tt>
* $Id$
*/
public class ChannelSupport implements Channel
{
// Constants -----------------------------------------------------
private static final Logger log = Logger.getLogger(ChannelSupport.class);
// Static --------------------------------------------------------
// Attributes ----------------------------------------------------
protected Serializable channelID;
protected Router router;
protected State state;
protected PersistenceManager pm;
protected MessageStore ms;
// Constructors --------------------------------------------------
/**
* @param acceptReliableMessages - it only makes sense if pm is null. Otherwise ignored (a
* recoverable channel always accepts reliable messages)
*/
protected ChannelSupport(Serializable channelID,
MessageStore ms,
PersistenceManager pm,
boolean acceptReliableMessages)
{
if (log.isTraceEnabled()) { log.trace("creating " + (pm != null ? "recoverable " : "non-recoverable ") + "channel[" + channelID + "]"); }
this.channelID = channelID;
this.ms = ms;
this.pm = pm;
if (pm == null)
{
state = new NonRecoverableState(this, acceptReliableMessages);
}
else
{
state = new RecoverableState(this, pm);
// acceptReliableMessage ignored, the channel alwyas accepts reliable messages
}
}
// Receiver implementation ---------------------------------------
public final Delivery handle(DeliveryObserver sender, Routable r, Transaction tx)
{
if (r == null)
{
return null;
}
if (log.isTraceEnabled()){ log.trace(this + " handles " + r + (tx == null ? " non-transactionally" : " in transaction: " + tx) ); }
MessageReference ref = ref(r);
if (tx == null)
{
return handleNoTx(sender, r);
}
if (log.isTraceEnabled()){ log.trace("adding " + ref + " to state " + (tx == null ? "non-transactionally" : "in transaction: " + tx) ); }
try
{
state.add(ref, tx);
}
catch (Throwable t)
{
log.error("Failed to add message reference " + ref + " to state", t);
return null;
}
// I might as well return null, the sender shouldn't care
return new SimpleDelivery(sender, ref, true);
}
// DeliveryObserver implementation --------------------------
public void acknowledge(Delivery d, Transaction tx)
{
if (tx == null)
{
// acknowledge non transactionally
acknowledgeNoTx(d);
return;
}
if (log.isTraceEnabled()){ log.trace("acknowledge " + d + (tx == null ? " non-transactionally" : " transactionally in " + tx)); }
try
{
state.remove(d, tx);
}
catch (Throwable t)
{
log.error("Failed to remove delivery " + d + " from state", t);
}
}
public boolean cancel(Delivery d) throws Throwable
{
if (!state.remove(d, null))
{
return false;
}
if (log.isTraceEnabled()) { log.trace(this + " canceled delivery " + d); }
state.add(d.getReference(), null);
if (log.isTraceEnabled()) { log.trace(this + " marked message " + d.getReference() + " as undelivered"); }
return true;
}
public void redeliver(Delivery old, Receiver r) throws Throwable
{
if (log.isTraceEnabled()) { log.trace(this + " redelivery request for delivery " + old + " by receiver " + r); }
// TODO must be done atomically
if (state.remove(old, null))
{
if (log.isTraceEnabled()) { log.trace(this + "old delivery was active, canceled it"); }
MessageReference ref = old.getReference();
//FIXME - What if the message is only redelivered for one particular
//receiver - won't this set it globally?
if (log.isTraceEnabled()) { log.trace("Setting redelivered to true"); }
ref.setRedelivered(true);
Delivery newd = r.handle(this, ref, null);
if (newd == null || newd.isDone())
{
return;
}
// TODO race condition: what if the receiver acknowledges right here v ?
state.add(newd);
}
}
// Distributor implementation ------------------------------------
public boolean add(Receiver r)
{
if (log.isTraceEnabled()) { log.trace("Attempting to add receiver to channel[" + getChannelID() + "]: " + r); }
boolean added = router.add(r);
if (added)
{
deliver();
}
return added;
}
public boolean remove(Receiver r)
{
return router.remove(r);
}
public void clear()
{
router.clear();
}
public boolean contains(Receiver r)
{
return router.contains(r);
}
public Iterator iterator()
{
return router.iterator();
}
// Channel implementation ----------------------------------------
public Serializable getChannelID()
{
return channelID;
}
public boolean isRecoverable()
{
return state.isRecoverable();
}
public boolean acceptReliableMessages()
{
return state.acceptReliableMessages();
}
public List browse()
{
return browse(null);
}
public List browse(Filter f)
{
if (log.isTraceEnabled()) { log.trace(this + " browse" + (f == null ? "" : ", filter = " + f)); }
List references = state.browse(f);
// dereference pass
ArrayList messages = new ArrayList(references.size());
for(Iterator i = references.iterator(); i.hasNext();)
{
MessageReference ref = (MessageReference)i.next();
messages.add(ref.getMessage());
}
return messages;
}
public MessageStore getMessageStore()
{
return ms;
}
public void deliver()
{
if (log.isTraceEnabled()){ log.trace("attempting to deliver channel's " + this + " messages"); }
List messages = state.undelivered(null);
for(Iterator i = messages.iterator(); i.hasNext(); )
{
MessageReference r = (MessageReference)i.next();
try
{
state.remove(r);
}
catch (Throwable t)
{
log.error("Failed to remove ref", t);
return;
}
// TODO: if I crash now I could lose a persisent message
if (log.isTraceEnabled()){ log.trace("removed " + r + " from state"); }
handleNoTx(null, r);
}
}
public void close()
{
if (state == null)
{
return;
}
router.clear();
router = null;
state.clear();
state = null;
channelID = null;
}
// Public --------------------------------------------------------
// Package protected ---------------------------------------------
// Protected -----------------------------------------------------
protected MessageReference ref(Routable r)
{
MessageReference ref = null;
if (r.isReference())
{
return (MessageReference)r;
}
else
{
//Convert to reference
try
{
ref = ms.reference(r);
return ref;
}
catch (Throwable t)
{
log.error("Failed to reference routable", t);
return null;
}
}
}
// Private -------------------------------------------------------
private void checkClosed()
{
if (state == null)
{
throw new IllegalStateException(this + " closed");
}
}
/**
* @param sender - may be null, in which case the returned acknowledgment will probably be ignored.
*/
private Delivery handleNoTx(DeliveryObserver sender, Routable r)
{
checkClosed();
if (r == null)
{
return null;
}
// don't even attempt synchronous delivery for a reliable message when we have an
// non-recoverable state that doesn't accept reliable messages. If we do, we may get into the
// situation where we need to reliably store an active delivery of a reliable message, which
// in these conditions cannot be done.
if (r.isReliable() && !state.acceptReliableMessages())
{
log.error("Cannot handle reliable message " + r +
" because the channel has a non-recoverable state!");
return null;
}
if (log.isTraceEnabled()){ log.trace("handling non-transactionally " + r); }
MessageReference ref = ref(r);
Set deliveries = router.handle(this, ref, null);
if (deliveries.isEmpty())
{
// no receivers, receivers that don't accept the message or broken receivers
if (log.isTraceEnabled()){ log.trace("No deliveries returned for message; there are no receivers"); }
try
{
state.add(ref, null);
- if (log.isTraceEnabled()){ log.trace("adding reference to state successful"); }
+ if (log.isTraceEnabled()){ log.trace("adding reference to state successfully"); }
}
catch(Throwable t)
{
// this channel cannot safely hold the message, so it doesn't accept it
log.error("Cannot handle the message", t);
return null;
}
}
else
{
// there are receivers
try
{
for (Iterator i = deliveries.iterator(); i.hasNext(); )
{
Delivery d = (Delivery)i.next();
if (!d.isDone())
{
state.add(d);
}
}
}
catch(Throwable t)
{
log.error(this + " cannot manage delivery, passing responsibility to the sender", t);
// cannot manage this delivery, pass the responsibility to the sender
// cannot split delivery, because in case of crash, the message must be recoverable
// from one and only one channel
// TODO this is untested
return new CompositeDelivery(sender, deliveries);
}
}
// the channel can safely assume responsibility for delivery
return new SimpleDelivery(true);
}
private void acknowledgeNoTx(Delivery d)
{
checkClosed();
if (log.isTraceEnabled()){ log.trace("acknowledging non transactionally " + d); }
try
{
if (state.remove(d, null))
{
if (log.isTraceEnabled()) { log.trace(this + " delivery " + d + " completed and forgotten"); }
}
}
catch(Throwable t)
{
// a non transactional remove shound't throw any transaction
log.error(this + " failed to remove delivery", t);
}
}
// Inner classes -------------------------------------------------
}
| true | true | private Delivery handleNoTx(DeliveryObserver sender, Routable r)
{
checkClosed();
if (r == null)
{
return null;
}
// don't even attempt synchronous delivery for a reliable message when we have an
// non-recoverable state that doesn't accept reliable messages. If we do, we may get into the
// situation where we need to reliably store an active delivery of a reliable message, which
// in these conditions cannot be done.
if (r.isReliable() && !state.acceptReliableMessages())
{
log.error("Cannot handle reliable message " + r +
" because the channel has a non-recoverable state!");
return null;
}
if (log.isTraceEnabled()){ log.trace("handling non-transactionally " + r); }
MessageReference ref = ref(r);
Set deliveries = router.handle(this, ref, null);
if (deliveries.isEmpty())
{
// no receivers, receivers that don't accept the message or broken receivers
if (log.isTraceEnabled()){ log.trace("No deliveries returned for message; there are no receivers"); }
try
{
state.add(ref, null);
if (log.isTraceEnabled()){ log.trace("adding reference to state successful"); }
}
catch(Throwable t)
{
// this channel cannot safely hold the message, so it doesn't accept it
log.error("Cannot handle the message", t);
return null;
}
}
else
{
// there are receivers
try
{
for (Iterator i = deliveries.iterator(); i.hasNext(); )
{
Delivery d = (Delivery)i.next();
if (!d.isDone())
{
state.add(d);
}
}
}
catch(Throwable t)
{
log.error(this + " cannot manage delivery, passing responsibility to the sender", t);
// cannot manage this delivery, pass the responsibility to the sender
// cannot split delivery, because in case of crash, the message must be recoverable
// from one and only one channel
// TODO this is untested
return new CompositeDelivery(sender, deliveries);
}
}
// the channel can safely assume responsibility for delivery
return new SimpleDelivery(true);
}
| private Delivery handleNoTx(DeliveryObserver sender, Routable r)
{
checkClosed();
if (r == null)
{
return null;
}
// don't even attempt synchronous delivery for a reliable message when we have an
// non-recoverable state that doesn't accept reliable messages. If we do, we may get into the
// situation where we need to reliably store an active delivery of a reliable message, which
// in these conditions cannot be done.
if (r.isReliable() && !state.acceptReliableMessages())
{
log.error("Cannot handle reliable message " + r +
" because the channel has a non-recoverable state!");
return null;
}
if (log.isTraceEnabled()){ log.trace("handling non-transactionally " + r); }
MessageReference ref = ref(r);
Set deliveries = router.handle(this, ref, null);
if (deliveries.isEmpty())
{
// no receivers, receivers that don't accept the message or broken receivers
if (log.isTraceEnabled()){ log.trace("No deliveries returned for message; there are no receivers"); }
try
{
state.add(ref, null);
if (log.isTraceEnabled()){ log.trace("adding reference to state successfully"); }
}
catch(Throwable t)
{
// this channel cannot safely hold the message, so it doesn't accept it
log.error("Cannot handle the message", t);
return null;
}
}
else
{
// there are receivers
try
{
for (Iterator i = deliveries.iterator(); i.hasNext(); )
{
Delivery d = (Delivery)i.next();
if (!d.isDone())
{
state.add(d);
}
}
}
catch(Throwable t)
{
log.error(this + " cannot manage delivery, passing responsibility to the sender", t);
// cannot manage this delivery, pass the responsibility to the sender
// cannot split delivery, because in case of crash, the message must be recoverable
// from one and only one channel
// TODO this is untested
return new CompositeDelivery(sender, deliveries);
}
}
// the channel can safely assume responsibility for delivery
return new SimpleDelivery(true);
}
|
diff --git a/src/org/yaxim/androidclient/preferences/AccountPrefs.java b/src/org/yaxim/androidclient/preferences/AccountPrefs.java
index bc0be4d..2bf1058 100644
--- a/src/org/yaxim/androidclient/preferences/AccountPrefs.java
+++ b/src/org/yaxim/androidclient/preferences/AccountPrefs.java
@@ -1,120 +1,120 @@
package org.yaxim.androidclient.preferences;
import org.yaxim.androidclient.exceptions.YaximXMPPAdressMalformedException;
import org.yaxim.androidclient.util.XMPPHelper;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import org.yaxim.androidclient.R;
public class AccountPrefs extends PreferenceActivity {
private final static String ACCOUNT_JABBERID = "account_jabberID";
private final static String ACCOUNT_RESSOURCE = "account_resource";
private final static String ACCOUNT_PRIO = "account_prio";
private CharSequence newPrioValue = null;
private SharedPreferences sharedPreference;
private static int prioIntValue = 0;
private EditTextPreference prefPrio;
private EditTextPreference prefAccountID;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.layout.accountprefs);
sharedPreference = PreferenceManager.getDefaultSharedPreferences(this);
this.prefAccountID = (EditTextPreference) findPreference(ACCOUNT_JABBERID);
this.prefAccountID.getEditText().addTextChangedListener(
new TextWatcher() {
public void afterTextChanged(Editable s) {
// Nothing
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
// Nothing
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
try {
XMPPHelper.verifyJabberID(s.toString());
prefAccountID.getEditText().setTextColor(
Color.DKGRAY);
} catch (YaximXMPPAdressMalformedException e) {
prefAccountID.getEditText().setTextColor(Color.RED);
}
}
});
this.prefPrio = (EditTextPreference) findPreference(ACCOUNT_PRIO);
this.prefPrio
.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference,
Object newValue) {
try {
int prioIntValue = Integer.parseInt(newValue
.toString());
newPrioValue = (CharSequence) newValue;
- if (prioIntValue <= 127 && prioIntValue >= 0) {
+ if (prioIntValue <= 127 && prioIntValue >= -128) {
sharedPreference.edit().putInt(ACCOUNT_PRIO,
prioIntValue);
} else {
sharedPreference.edit().putInt(ACCOUNT_PRIO, 0);
}
return true;
} catch (NumberFormatException ex) {
sharedPreference.edit().putInt(ACCOUNT_PRIO, 0);
return true;
}
}
});
this.prefPrio.getEditText().addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
try {
prioIntValue = Integer.parseInt(s.toString());
- if (prioIntValue <= 127 && prioIntValue >= 0) {
+ if (prioIntValue <= 127 && prioIntValue >= -128) {
prefPrio.getEditText().setTextColor(Color.DKGRAY);
prefPrio.setPositiveButtonText(android.R.string.ok);
} else {
prefPrio.getEditText().setTextColor(Color.RED);
}
} catch (NumberFormatException numF) {
prioIntValue = 0;
prefPrio.getEditText().setTextColor(Color.RED);
}
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// Nothing
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
});
}
}
| false | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.layout.accountprefs);
sharedPreference = PreferenceManager.getDefaultSharedPreferences(this);
this.prefAccountID = (EditTextPreference) findPreference(ACCOUNT_JABBERID);
this.prefAccountID.getEditText().addTextChangedListener(
new TextWatcher() {
public void afterTextChanged(Editable s) {
// Nothing
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
// Nothing
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
try {
XMPPHelper.verifyJabberID(s.toString());
prefAccountID.getEditText().setTextColor(
Color.DKGRAY);
} catch (YaximXMPPAdressMalformedException e) {
prefAccountID.getEditText().setTextColor(Color.RED);
}
}
});
this.prefPrio = (EditTextPreference) findPreference(ACCOUNT_PRIO);
this.prefPrio
.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference,
Object newValue) {
try {
int prioIntValue = Integer.parseInt(newValue
.toString());
newPrioValue = (CharSequence) newValue;
if (prioIntValue <= 127 && prioIntValue >= 0) {
sharedPreference.edit().putInt(ACCOUNT_PRIO,
prioIntValue);
} else {
sharedPreference.edit().putInt(ACCOUNT_PRIO, 0);
}
return true;
} catch (NumberFormatException ex) {
sharedPreference.edit().putInt(ACCOUNT_PRIO, 0);
return true;
}
}
});
this.prefPrio.getEditText().addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
try {
prioIntValue = Integer.parseInt(s.toString());
if (prioIntValue <= 127 && prioIntValue >= 0) {
prefPrio.getEditText().setTextColor(Color.DKGRAY);
prefPrio.setPositiveButtonText(android.R.string.ok);
} else {
prefPrio.getEditText().setTextColor(Color.RED);
}
} catch (NumberFormatException numF) {
prioIntValue = 0;
prefPrio.getEditText().setTextColor(Color.RED);
}
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// Nothing
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
});
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.layout.accountprefs);
sharedPreference = PreferenceManager.getDefaultSharedPreferences(this);
this.prefAccountID = (EditTextPreference) findPreference(ACCOUNT_JABBERID);
this.prefAccountID.getEditText().addTextChangedListener(
new TextWatcher() {
public void afterTextChanged(Editable s) {
// Nothing
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
// Nothing
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
try {
XMPPHelper.verifyJabberID(s.toString());
prefAccountID.getEditText().setTextColor(
Color.DKGRAY);
} catch (YaximXMPPAdressMalformedException e) {
prefAccountID.getEditText().setTextColor(Color.RED);
}
}
});
this.prefPrio = (EditTextPreference) findPreference(ACCOUNT_PRIO);
this.prefPrio
.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference,
Object newValue) {
try {
int prioIntValue = Integer.parseInt(newValue
.toString());
newPrioValue = (CharSequence) newValue;
if (prioIntValue <= 127 && prioIntValue >= -128) {
sharedPreference.edit().putInt(ACCOUNT_PRIO,
prioIntValue);
} else {
sharedPreference.edit().putInt(ACCOUNT_PRIO, 0);
}
return true;
} catch (NumberFormatException ex) {
sharedPreference.edit().putInt(ACCOUNT_PRIO, 0);
return true;
}
}
});
this.prefPrio.getEditText().addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
try {
prioIntValue = Integer.parseInt(s.toString());
if (prioIntValue <= 127 && prioIntValue >= -128) {
prefPrio.getEditText().setTextColor(Color.DKGRAY);
prefPrio.setPositiveButtonText(android.R.string.ok);
} else {
prefPrio.getEditText().setTextColor(Color.RED);
}
} catch (NumberFormatException numF) {
prioIntValue = 0;
prefPrio.getEditText().setTextColor(Color.RED);
}
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// Nothing
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
});
}
|
diff --git a/src/edu/jhu/thrax/util/TestSetFilter.java b/src/edu/jhu/thrax/util/TestSetFilter.java
index d398896..ad7f61c 100644
--- a/src/edu/jhu/thrax/util/TestSetFilter.java
+++ b/src/edu/jhu/thrax/util/TestSetFilter.java
@@ -1,165 +1,165 @@
package edu.jhu.thrax.util;
import java.util.Scanner;
import java.util.Collections;
import java.util.Set;
import java.util.HashSet;
import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.io.FileNotFoundException;
import java.io.File;
import edu.jhu.thrax.ThraxConfig;
public class TestSetFilter
{
private static List<String> testSentences;
private static Map<String,Set<Integer>> sentencesByWord;
private static final String NT_REGEX = "\\[[^\\]]+?\\]";
private static boolean verbose = false;
private static void getTestSentences(String filename)
{
try {
Scanner scanner = new Scanner(new File(filename), "UTF-8");
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
addSentenceToWordHash(sentencesByWord, line, testSentences.size());
testSentences.add(line);
}
}
catch (FileNotFoundException e) {
System.err.printf("Could not open %s\n", e.getMessage());
}
if (verbose)
System.err.println("Added " + testSentences.size() + " sentences.\n");
}
public static Pattern getPattern(String rule)
{
String [] parts = rule.split(ThraxConfig.DELIMITER_REGEX);
if (parts.length != 4) {
return null;
}
String source = parts[1].trim();
String pattern = Pattern.quote(source);
pattern = pattern.replaceAll(NT_REGEX, "\\\\E.+\\\\Q");
pattern = pattern.replaceAll("\\\\Q\\\\E", "");
pattern = "(?:^|\\s)" + pattern + "(?:$|\\s)";
return Pattern.compile(pattern);
}
private static boolean inTestSet(String rule)
{
Pattern pattern = getPattern(rule);
for (int i : getSentencesForRule(sentencesByWord, rule)) {
if (pattern.matcher(testSentences.get(i)).find()) {
return true;
}
}
return false;
}
private static void addSentenceToWordHash(Map<String,Set<Integer>> sentencesByWord, String sentence, int index)
{
String [] tokens = sentence.split("\\s+");
for (String t : tokens) {
if (sentencesByWord.containsKey(t))
sentencesByWord.get(t).add(index);
else {
Set<Integer> set = new HashSet<Integer>();
set.add(index);
sentencesByWord.put(t, set);
}
}
}
private static Set<Integer> getSentencesForRule(Map<String,Set<Integer>> sentencesByWord, String rule)
{
String [] parts = rule.split(ThraxConfig.DELIMITER_REGEX);
if (parts.length != 4)
return Collections.emptySet();
String source = parts[1].trim();
List<Set<Integer>> list = new ArrayList<Set<Integer>>();
for (String t : source.split("\\s+")) {
if (t.matches(NT_REGEX))
continue;
if (sentencesByWord.containsKey(t))
list.add(sentencesByWord.get(t));
else
return Collections.emptySet();
}
return intersect(list);
}
private static <T> Set<T> intersect(List<Set<T>> list)
{
if (list.isEmpty())
return Collections.emptySet();
Set<T> result = new HashSet<T>(list.get(0));
for (int i = 1; i < list.size(); i++) {
result.retainAll(list.get(i));
if (result.isEmpty())
return Collections.emptySet();
}
if (result.isEmpty())
return Collections.emptySet();
return result;
}
public static void main(String [] argv)
{
// do some setup
if (argv.length < 1) {
System.err.println("usage: TestSetFilter [-v] <test set1> [test set2 ...]");
return;
}
testSentences = new ArrayList<String>();
sentencesByWord = new HashMap<String,Set<Integer>>();
for (int i = 0; i < argv.length; i++) {
if (argv[i].equals("-v")) {
verbose = true;
continue;
}
getTestSentences(argv[i]);
}
Scanner scanner = new Scanner(System.in, "UTF-8");
int rulesIn = 0;
int rulesOut = 0;
System.err.println("Processing rules...");
while (scanner.hasNextLine()) {
if (verbose) {
if ((rulesIn+1) % 2000 == 0) {
System.err.print(".");
System.err.flush();
}
if ((rulesIn+1) % 100000 == 0) {
- System.err.println(" [" + rulesIn + "]");
+ System.err.println(" [" + (rulesIn+1) + "]");
System.err.flush();
}
}
rulesIn++;
String rule = scanner.nextLine();
if (inTestSet(rule)) {
System.out.println(rule);
rulesOut++;
}
}
if (verbose) {
System.err.println("[INFO] Total rules read: " + rulesIn);
System.err.println("[INFO] Rules kept: " + rulesOut);
System.err.println("[INFO] Rules dropped: " + (rulesIn - rulesOut));
}
return;
}
}
| true | true | public static void main(String [] argv)
{
// do some setup
if (argv.length < 1) {
System.err.println("usage: TestSetFilter [-v] <test set1> [test set2 ...]");
return;
}
testSentences = new ArrayList<String>();
sentencesByWord = new HashMap<String,Set<Integer>>();
for (int i = 0; i < argv.length; i++) {
if (argv[i].equals("-v")) {
verbose = true;
continue;
}
getTestSentences(argv[i]);
}
Scanner scanner = new Scanner(System.in, "UTF-8");
int rulesIn = 0;
int rulesOut = 0;
System.err.println("Processing rules...");
while (scanner.hasNextLine()) {
if (verbose) {
if ((rulesIn+1) % 2000 == 0) {
System.err.print(".");
System.err.flush();
}
if ((rulesIn+1) % 100000 == 0) {
System.err.println(" [" + rulesIn + "]");
System.err.flush();
}
}
rulesIn++;
String rule = scanner.nextLine();
if (inTestSet(rule)) {
System.out.println(rule);
rulesOut++;
}
}
if (verbose) {
System.err.println("[INFO] Total rules read: " + rulesIn);
System.err.println("[INFO] Rules kept: " + rulesOut);
System.err.println("[INFO] Rules dropped: " + (rulesIn - rulesOut));
}
return;
}
| public static void main(String [] argv)
{
// do some setup
if (argv.length < 1) {
System.err.println("usage: TestSetFilter [-v] <test set1> [test set2 ...]");
return;
}
testSentences = new ArrayList<String>();
sentencesByWord = new HashMap<String,Set<Integer>>();
for (int i = 0; i < argv.length; i++) {
if (argv[i].equals("-v")) {
verbose = true;
continue;
}
getTestSentences(argv[i]);
}
Scanner scanner = new Scanner(System.in, "UTF-8");
int rulesIn = 0;
int rulesOut = 0;
System.err.println("Processing rules...");
while (scanner.hasNextLine()) {
if (verbose) {
if ((rulesIn+1) % 2000 == 0) {
System.err.print(".");
System.err.flush();
}
if ((rulesIn+1) % 100000 == 0) {
System.err.println(" [" + (rulesIn+1) + "]");
System.err.flush();
}
}
rulesIn++;
String rule = scanner.nextLine();
if (inTestSet(rule)) {
System.out.println(rule);
rulesOut++;
}
}
if (verbose) {
System.err.println("[INFO] Total rules read: " + rulesIn);
System.err.println("[INFO] Rules kept: " + rulesOut);
System.err.println("[INFO] Rules dropped: " + (rulesIn - rulesOut));
}
return;
}
|
diff --git a/content-tool/tool/src/java/org/sakaiproject/content/tool/ListItem.java b/content-tool/tool/src/java/org/sakaiproject/content/tool/ListItem.java
index 12c8e91b..9228c24d 100644
--- a/content-tool/tool/src/java/org/sakaiproject/content/tool/ListItem.java
+++ b/content-tool/tool/src/java/org/sakaiproject/content/tool/ListItem.java
@@ -1,1333 +1,1335 @@
/**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2007 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.content.tool;
import java.text.NumberFormat;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.Stack;
import java.util.TreeSet;
import java.util.Vector;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.component.cover.ComponentManager;
import org.sakaiproject.content.api.ContentCollection;
import org.sakaiproject.content.api.ContentEntity;
import org.sakaiproject.content.api.ContentResource;
import org.sakaiproject.content.api.GroupAwareEntity;
import org.sakaiproject.content.api.ResourceToolAction;
import org.sakaiproject.content.api.ResourceType;
import org.sakaiproject.content.api.ResourceTypeRegistry;
import org.sakaiproject.content.cover.ContentHostingService;
import org.sakaiproject.content.api.ServiceLevelAction;
import org.sakaiproject.content.api.GroupAwareEntity.AccessMode;
import org.sakaiproject.content.cover.ContentTypeImageService;
import org.sakaiproject.content.tool.ResourcesAction.ContentPermissions;
import org.sakaiproject.entity.api.EntityPropertyNotDefinedException;
import org.sakaiproject.entity.api.EntityPropertyTypeException;
import org.sakaiproject.entity.api.Reference;
import org.sakaiproject.entity.api.ResourceProperties;
import org.sakaiproject.entity.cover.EntityManager;
import org.sakaiproject.exception.IdUnusedException;
import org.sakaiproject.site.api.Group;
import org.sakaiproject.site.api.Site;
import org.sakaiproject.site.cover.SiteService;
import org.sakaiproject.time.api.Time;
import org.sakaiproject.time.cover.TimeService;
import org.sakaiproject.user.api.User;
import org.sakaiproject.util.ResourceLoader;
/**
* ListItem
*
*/
public class ListItem
{
/** Resource bundle using current language locale */
private static ResourceLoader rb = new ResourceLoader("content");
/** Resource bundle using current language locale */
private static ResourceLoader trb = new ResourceLoader("types");
private static final Log logger = LogFactory.getLog(ResourcesAction.class);
protected static Comparator DEFAULT_COMPARATOR = ContentHostingService.newContentHostingComparator(ResourceProperties.PROP_DISPLAY_NAME, true);
protected static final Comparator PRIORITY_SORT_COMPARATOR = ContentHostingService.newContentHostingComparator(ResourceProperties.PROP_CONTENT_PRIORITY, true);
protected String name;
protected String id;
protected List<ResourceToolAction> addActions;
protected List<ResourceToolAction> otherActions;
protected String otherActionsLabel;
protected List<ListItem> members;
protected Set<ContentPermissions> permissions;
protected boolean selected;
protected boolean collection;
protected String hoverText;
protected String accessUrl;
protected String iconLocation;
protected String mimetype;
protected String resourceType;
protected boolean isEmpty = true;
protected boolean isExpanded = false;
protected boolean isPubviewPossible;
protected boolean isPubviewInherited = false;
protected boolean isPubview = false;
protected boolean isSortable = false;
protected boolean isTooBig = false;
protected String size = "";
protected String createdBy;
protected String modifiedTime;
protected int depth;
protected Map<String, ResourceToolAction> multipleItemActions = new HashMap<String, ResourceToolAction>();
protected boolean canSelect = false;
protected ContentEntity entity;
protected AccessMode accessMode;
protected AccessMode effectiveAccess;
protected Collection<Group> groups = new Vector<Group>();
protected Collection<Group> inheritedGroups = new Vector<Group>();
protected Collection<Group> possibleGroups = new Vector<Group>();
protected Collection<Group> allowedRemoveGroupRefs;
protected Collection<Group> allowedAddGroupRefs;
protected Map<String,Group> possibleGroupsMap = new HashMap<String, Group>();
protected boolean hidden;
protected boolean isAvailable;
protected boolean useReleaseDate;
protected Time releaseDate;
protected boolean useRetractDate;
protected Time retractDate;
/**
* @param entity
*/
public ListItem(ContentEntity entity)
{
org.sakaiproject.content.api.ContentHostingService contentService = ContentHostingService.getInstance();
this.entity = entity;
ResourceProperties props = entity.getProperties();
this.accessUrl = entity.getUrl();
this.collection = entity.isCollection();
this.id = entity.getId();
this.name = props.getProperty(ResourceProperties.PROP_DISPLAY_NAME);
this.permissions = new TreeSet<ContentPermissions>();
this.selected = false;
ResourceTypeRegistry registry = (ResourceTypeRegistry) ComponentManager.get("org.sakaiproject.content.api.ResourceTypeRegistry");
this.resourceType = entity.getResourceType();
ResourceType typeDef = registry.getType(resourceType);
this.hoverText = this.name;
if(typeDef != null)
{
this.hoverText = typeDef.getLocalizedHoverText(entity);
this.iconLocation = typeDef.getIconLocation();
String[] args = { typeDef.getLabel() };
this.otherActionsLabel = trb.getFormattedMessage("action.other", args);
}
if(this.collection)
{
ContentCollection collection = (ContentCollection) entity;
int collection_size = collection.getMemberCount();
if(collection_size == 1)
{
setSize(rb.getString("size.item"));
}
else
{
String[] args = { Integer.toString(collection_size) };
setSize(rb.getFormattedMessage("size.items", args));
}
setIsEmpty(collection_size < 1);
setSortable(contentService.isSortByPriorityEnabled() && collection_size > 1 && collection_size < ResourcesAction.EXPANDABLE_FOLDER_SIZE_LIMIT);
if(collection_size > ResourcesAction.EXPANDABLE_FOLDER_SIZE_LIMIT)
{
setIsTooBig(true);
}
}
else
{
ContentResource resource = (ContentResource) entity;
this.mimetype = resource.getContentType();
if(this.mimetype == null)
{
}
if(this.iconLocation == null)
{
this.iconLocation = ContentTypeImageService.getContentTypeImage(this.mimetype);
}
String size = "";
if(props.getProperty(ResourceProperties.PROP_CONTENT_LENGTH) != null)
{
long size_long = 0;
try
{
size_long = props.getLongProperty(ResourceProperties.PROP_CONTENT_LENGTH);
}
catch (EntityPropertyNotDefinedException e)
{
// TODO Auto-generated catch block
logger.warn("EntityPropertyNotDefinedException for size of " + this.id);
}
catch (EntityPropertyTypeException e)
{
// TODO Auto-generated catch block
logger.warn("EntityPropertyTypeException for size of " + this.id);
}
NumberFormat formatter = NumberFormat.getInstance(rb.getLocale());
formatter.setMaximumFractionDigits(1);
if(size_long > 700000000L)
{
String[] args = { formatter.format(1.0 * size_long / (1024L * 1024L * 1024L)) };
size = rb.getFormattedMessage("size.gb", args);
}
else if(size_long > 700000L)
{
String[] args = { formatter.format(1.0 * size_long / (1024L * 1024L)) };
size = rb.getFormattedMessage("size.mb", args);
}
else if(size_long > 700L)
{
String[] args = { formatter.format(1.0 * size_long / 1024L) };
size = rb.getFormattedMessage("size.kb", args);
}
else
{
String[] args = { formatter.format(size_long) };
size = rb.getFormattedMessage("size.bytes", args);
}
}
setSize(size);
}
User creator = ResourcesAction.getUserProperty(props, ResourceProperties.PROP_CREATOR);
if(creator != null)
{
String createdBy = creator.getDisplayName();
setCreatedBy(createdBy);
}
// setCreatedBy(props.getProperty(ResourceProperties.PROP_CREATOR));
this.setModifiedTime(props.getPropertyFormatted(ResourceProperties.PROP_MODIFIED_DATE));
this.accessMode = entity.getAccess();
this.effectiveAccess = entity.getInheritedAccess();
this.groups.clear();
this.groups.addAll(entity.getGroupObjects());
this.inheritedGroups.clear();
this.inheritedGroups.addAll(entity.getInheritedGroupObjects());
Reference ref = EntityManager.newReference(entity.getReference());
- try
- {
- Site site = SiteService.getSite(ref.getContext());
- setPossibleGroups(site.getGroups());
- }
- catch (IdUnusedException e)
- {
- // TODO Auto-generated catch block
- logger.warn("IdUnusedException ", e);
- }
+ if(ref != null && ref.getContext() != null)
+ {
+ try
+ {
+ Site site = SiteService.getSite(ref.getContext());
+ setPossibleGroups(site.getGroups());
+ }
+ catch (IdUnusedException e)
+ {
+ logger.warn("IdUnusedException for a site in resources: " + ref.getContext() + " (" + ref.getReference() + ")");
+ }
+ }
Collection<Group> allowedRemoveGroups = null;
if(AccessMode.GROUPED == this.accessMode)
{
allowedRemoveGroups = contentService.getGroupsWithRemovePermission(id);
Collection<Group> more = contentService.getGroupsWithRemovePermission(ref.getContainer());
if(more != null && ! more.isEmpty())
{
allowedRemoveGroups.addAll(more);
}
}
else if(AccessMode.GROUPED == this.effectiveAccess)
{
allowedRemoveGroups = contentService.getGroupsWithRemovePermission(ref.getContainer());
}
else
{
allowedRemoveGroups = contentService.getGroupsWithRemovePermission(contentService.getSiteCollection(ref.getContext()));
}
this.allowedRemoveGroupRefs = allowedRemoveGroups;
Collection<Group> allowedAddGroups = null;
if(AccessMode.GROUPED == this.accessMode)
{
allowedAddGroups = contentService.getGroupsWithAddPermission(id);
Collection<Group> more = contentService.getGroupsWithAddPermission(ref.getContainer());
if(more != null && ! more.isEmpty())
{
allowedAddGroups.addAll(more);
}
}
else if(AccessMode.GROUPED == this.effectiveAccess)
{
allowedAddGroups = contentService.getGroupsWithAddPermission(ref.getContainer());
}
else
{
allowedAddGroups = contentService.getGroupsWithAddPermission(contentService.getSiteCollection(ref.getContext()));
}
this.allowedAddGroupRefs = allowedAddGroups;
this.isPubviewInherited = contentService.isInheritingPubView(id);
if (!this.isPubviewInherited)
{
this.isPubview = contentService.isPubView(id);
}
this.hidden = entity.isHidden();
Time releaseDate = entity.getReleaseDate();
if(releaseDate == null)
{
this.useReleaseDate = false;
this.releaseDate = TimeService.newTime();
}
else
{
this.useReleaseDate = true;
this.releaseDate = releaseDate;
}
Time retractDate = entity.getRetractDate();
if(retractDate == null)
{
this.useRetractDate = false;
}
else
{
this.useRetractDate = true;
this.retractDate = retractDate;
}
this.isAvailable = entity.isAvailable();
}
public static ListItem getListItem(ContentEntity entity, ListItem parent, ResourceTypeRegistry registry, boolean expandAll, Set<String> expandedFolders, List<String> items_to_be_moved, List<String> items_to_be_copied, int depth, Comparator userSelectedSort, boolean preventPublicDisplay)
{
ListItem item = null;
boolean isCollection = entity.isCollection();
org.sakaiproject.content.api.ContentHostingService contentService = ContentHostingService.getInstance();
boolean isAvailabilityEnabled = contentService.isAvailabilityEnabled();
Reference ref = EntityManager.newReference(entity.getReference());
item = new ListItem(entity);
item.setPubviewPossible(! preventPublicDisplay);
item.setDepth(depth);
/*
* calculate permissions for this entity. If its access mode is
* GROUPED, we need to calculate permissions based on current user's
* role in group. Otherwise, we inherit from containing collection
* and check to see if additional permissions are set on this entity
* that were't set on containing collection...
*/
if(GroupAwareEntity.AccessMode.INHERITED == entity.getAccess())
{
// permissions are same as parent or site
if(parent == null)
{
// permissions are same as site
item.setPermissions(ResourcesAction.getPermissions(entity.getId(), null));
}
else
{
// permissions are same as parent
item.setPermissions(ResourcesAction.getPermissions(entity.getId(), parent.getPermissions()));
}
}
else if(GroupAwareEntity.AccessMode.GROUPED == entity.getAccess())
{
// permissions are determined by group(s)
item.setPermissions(ResourcesAction.getPermissions(entity.getId(), null));
}
if(isCollection)
{
ContentCollection collection = (ContentCollection) entity;
if(item.isTooBig)
{
// do nothing
}
else if(expandAll)
{
expandedFolders.add(entity.getId());
}
if(expandedFolders.contains(entity.getId()))
{
item.setExpanded(true);
List<ContentEntity> children = collection.getMemberResources();
Comparator comparator = null;
if(userSelectedSort != null)
{
comparator = userSelectedSort;
}
else
{
boolean hasCustomSort = false;
try
{
hasCustomSort = collection.getProperties().getBooleanProperty(ResourceProperties.PROP_HAS_CUSTOM_SORT);
}
catch(Exception e)
{
// ignore -- let value be false
}
if(hasCustomSort)
{
comparator = PRIORITY_SORT_COMPARATOR;
}
else
{
comparator = DEFAULT_COMPARATOR;
}
}
Collections.sort(children, comparator);
Iterator<ContentEntity> childIt = children.iterator();
while(childIt.hasNext())
{
ContentEntity childEntity = childIt.next();
if(isAvailabilityEnabled && ! contentService.isAvailable(childEntity.getId()))
{
continue;
}
ListItem child = getListItem(childEntity, item, registry, expandAll, expandedFolders, items_to_be_moved, items_to_be_copied, depth + 1, userSelectedSort, preventPublicDisplay);
item.addMember(child);
}
}
item.setAddActions(ResourcesAction.getAddActions(entity, item.getPermissions(), registry, items_to_be_moved, items_to_be_copied));
//this.members = coll.getMembers();
item.setIconLocation( ContentTypeImageService.getContentTypeImage("folder"));
}
item.setOtherActions(ResourcesAction.getActions(entity, item.getPermissions(), registry, items_to_be_moved, items_to_be_copied));
return item;
}
/**
*
*/
public ListItem(String entityId)
{
this.id = entityId;
}
/**
* @return the mimetype
*/
public String getMimetype()
{
return this.mimetype;
}
/**
* @param mimetype the mimetype to set
*/
public void setMimetype(String mimetype)
{
this.mimetype = mimetype;
}
/**
* @return the iconLocation
*/
public String getIconLocation()
{
return this.iconLocation;
}
/**
* @param iconLocation the iconLocation to set
*/
public void setIconLocation(String iconLocation)
{
this.iconLocation = iconLocation;
}
/**
* @return the hoverText
*/
public String getHoverText()
{
return this.hoverText;
}
public boolean isEmpty()
{
return this.isEmpty;
}
/**
* @return the collection
*/
public boolean isCollection()
{
return this.collection;
}
/**
* @param collection the collection to set
*/
public void setCollection(boolean collection)
{
this.collection = collection;
}
/**
* @return the permissions
*/
public Set<ContentPermissions> getPermissions()
{
return this.permissions;
}
/**
* @param permissions the permissions to set
*/
public void setPermissions(Collection<ContentPermissions> permissions)
{
if(this.permissions == null)
{
this.permissions = new TreeSet<ContentPermissions>();
}
this.permissions.clear();
this.permissions.addAll(permissions);
}
/**
* @param permission
*/
public void addPermission(ContentPermissions permission)
{
if(this.permissions == null)
{
this.permissions = new TreeSet<ContentPermissions>();
}
this.permissions.add(permission);
}
public boolean canRead()
{
return isPermitted(ContentPermissions.READ);
}
/**
* @param permission
* @return
*/
public boolean isPermitted(ContentPermissions permission)
{
if(this.permissions == null)
{
this.permissions = new TreeSet<ContentPermissions>();
}
return this.permissions.contains(permission);
}
/**
* @return
*/
public String getId()
{
return id;
}
/**
* @param id
*/
public void setId(String id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public List<ListItem> getMembers()
{
return members;
}
public void setMembers(List<ListItem> members)
{
if(this.members == null)
{
this.members = new Vector<ListItem>();
}
this.members.clear();
this.members.addAll(members);
}
public void setSelected(boolean selected)
{
this.selected = selected;
}
public boolean isSelected()
{
return selected;
}
/**
* @param hover
*/
public void setHoverText(String hover)
{
this.hoverText = hover;
}
/**
* @return the accessUrl
*/
public String getAccessUrl()
{
return this.accessUrl;
}
/**
* @param accessUrl the accessUrl to set
*/
public void setAccessUrl(String accessUrl)
{
this.accessUrl = accessUrl;
}
/**
* @param child
*/
public void addMember(ListItem member)
{
if(this.members == null)
{
this.members = new Vector<ListItem>();
}
this.members.add(member);
}
/**
* @param isEmpty
*/
public void setIsEmpty(boolean isEmpty)
{
this.isEmpty = isEmpty;
}
/**
* @param isSortable
*/
public void setSortable(boolean isSortable)
{
this.isSortable = isSortable;
}
public boolean isTooBig()
{
return this.isTooBig;
}
/**
* @param b
*/
public void setIsTooBig(boolean isTooBig)
{
this.isTooBig = isTooBig;
}
/**
* @return the isExpanded
*/
public boolean isExpanded()
{
return isExpanded;
}
/**
* @param isExpanded the isExpanded to set
*/
public void setExpanded(boolean isExpanded)
{
this.isExpanded = isExpanded;
}
/**
* @param string
*/
public void setSize(String size)
{
this.size = size;
}
/**
* @return the size
*/
public String getSize()
{
return size;
}
/**
* @return the addActions
*/
public List<ResourceToolAction> getAddActions()
{
return addActions;
}
/**
* @param addActions the addActions to set
*/
public void setAddActions(List<ResourceToolAction> addActions)
{
for(ResourceToolAction action : addActions)
{
if(action instanceof ServiceLevelAction && ((ServiceLevelAction) action).isMultipleItemAction())
{
this.multipleItemActions.put(action.getId(), action);
}
}
this.addActions = addActions;
}
/**
* @return the createdBy
*/
public String getCreatedBy()
{
return createdBy;
}
/**
* @param createdBy the createdBy to set
*/
public void setCreatedBy(String createdBy)
{
this.createdBy = createdBy;
}
/**
* @return the modifiedTime
*/
public String getModifiedTime()
{
return modifiedTime;
}
/**
* @param modifiedTime the modifiedTime to set
*/
public void setModifiedTime(String modifiedTime)
{
this.modifiedTime = modifiedTime;
}
/**
* @return the otherActions
*/
public List<ResourceToolAction> getOtherActions()
{
return otherActions;
}
/**
* @param otherActions the otherActions to set
*/
public void setOtherActions(List<ResourceToolAction> otherActions)
{
for(ResourceToolAction action : otherActions)
{
if(action instanceof ServiceLevelAction && ((ServiceLevelAction) action).isMultipleItemAction())
{
this.multipleItemActions.put(action.getId(), action);
}
}
this.otherActions = otherActions;
}
/**
* @return the depth
*/
public int getDepth()
{
return depth;
}
/**
* @param depth the depth to set
*/
public void setDepth(int depth)
{
this.depth = depth;
}
/**
* @return the otherActionsLabel
*/
public String getOtherActionsLabel()
{
return otherActionsLabel;
}
/**
* @param otherActionsLabel the otherActionsLabel to set
*/
public void setOtherActionsLabel(String otherActionsLabel)
{
this.otherActionsLabel = otherActionsLabel;
}
/**
* @param canSelect
*/
public void setCanSelect(boolean canSelect)
{
this.canSelect = canSelect;
}
/**
* @return
*/
public boolean canSelect()
{
return canSelect;
}
/**
* @param item
* @return
*/
public List<ListItem> convert2list()
{
List<ListItem> list = new Vector<ListItem>();
Stack<ListItem> processStack = new Stack<ListItem>();
processStack.push(this);
while(! processStack.empty())
{
ListItem parent = processStack.pop();
list.add(parent);
List<ListItem> children = parent.getMembers();
if(children != null)
{
for(int i = children.size() - 1; i >= 0; i--)
{
ListItem child = children.get(i);
processStack.push(child);
}
}
}
return list;
} // convert2list
/**
* @return
*/
public ContentEntity getEntity()
{
// TODO Auto-generated method stub
return this.entity;
}
/**
* @param action
*/
public void addMultipleItemAction(ResourceToolAction action)
{
this.multipleItemActions.put(action.getId(), action);
}
public boolean hasMultipleItemActions()
{
return ! this.multipleItemActions.isEmpty();
}
public boolean hasMultipleItemAction(String key)
{
return this.multipleItemActions.containsKey(key);
}
public ResourceToolAction getMultipleItemAction(String key)
{
return this.multipleItemActions.get(key);
}
/**
* @return
*/
public Map<String, ResourceToolAction> getMultipleItemActions()
{
return this.multipleItemActions;
}
/**
* @return the accessMode
*/
public AccessMode getAccessMode()
{
return accessMode;
}
/**
* @param accessMode the accessMode to set
*/
public void setAccessMode(AccessMode accessMode)
{
this.accessMode = accessMode;
}
/**
* @return the groups
*/
public Collection<Group> getGroups()
{
return new Vector<Group>(groups);
}
/**
* @return
*/
public Collection<String> getInheritedGroupRefs()
{
SortedSet<String> refs = new TreeSet<String>();
for(Group group : this.inheritedGroups)
{
refs.add(group.getReference());
}
return refs;
}
/**
* @return
*/
public Collection<String> getGroupRefs()
{
SortedSet<String> refs = new TreeSet<String>();
for(Group group : this.groups)
{
refs.add(group.getReference());
}
return refs;
}
/**
* @param groups the groups to set
*/
public void setGroups(Collection<Group> groups)
{
this.groups.clear();
this.groups.addAll(groups);
}
/**
* @return the inheritedGroups
*/
public Collection<Group> getInheritedGroups()
{
return new Vector<Group>(inheritedGroups);
}
/**
* @param inheritedGroups the inheritedGroups to set
*/
public void setInheritedGroups(Collection<Group> inheritedGroups)
{
this.inheritedGroups.clear();
this.inheritedGroups.addAll(inheritedGroups);
}
/**
* @return the possibleGroups
*/
public Collection<Group> getPossibleGroups()
{
return new Vector<Group>(possibleGroups);
}
/**
* Does this entity inherit grouped access mode with a single group that has access?
* @return true if this entity inherits grouped access mode with a single group that has access, and false otherwise.
*/
public boolean isSingleGroupInherited()
{
//Collection groups = getInheritedGroups();
return // AccessMode.INHERITED.toString().equals(this.m_access) &&
AccessMode.GROUPED == this.effectiveAccess &&
this.inheritedGroups != null &&
this.inheritedGroups.size() == 1;
// && this.m_oldInheritedGroups != null
// && this.m_oldInheritedGroups.size() == 1;
}
/**
* Is this entity's access restricted to the site (not pubview) and are there no groups defined for the site?
* @return
*/
public boolean isSiteOnly()
{
boolean isSiteOnly = false;
isSiteOnly = !isGroupPossible() && !isPubviewPossible();
return isSiteOnly;
}
/**
* @return
*/
public boolean isSitePossible()
{
return !this.isPubviewInherited && !isGroupInherited() && !isSingleGroupInherited();
}
/**
* @return
*/
public boolean isPubviewPossible()
{
return isPubviewPossible;
}
/**
* @return
*/
public Collection<String> getPossibleGroupRefs()
{
SortedSet<String> refs = new TreeSet<String>();
for(Group group : this.possibleGroups)
{
refs.add(group.getReference());
}
return refs;
}
/**
* @param possibleGroups the possibleGroups to set
*/
public void setPossibleGroups(Collection<Group> possibleGroups)
{
this.possibleGroups.clear();
this.possibleGroups.addAll(possibleGroups);
for(Group group : this.possibleGroups)
{
this.possibleGroupsMap.put(group.getId(), group);
}
}
/**
* @return the effectiveAccess
*/
public AccessMode getEffectiveAccess()
{
return effectiveAccess;
}
/**
* @param effectiveAccess the effectiveAccess to set
*/
public void setEffectiveAccess(AccessMode effectiveAccess)
{
this.effectiveAccess = effectiveAccess;
}
/**
* @return
*/
public boolean isGroupPossible()
{
return this.allowedAddGroupRefs != null && ! this.allowedAddGroupRefs.isEmpty();
}
/**
* @param group
* @return
*/
public boolean isPossible(Group group)
{
boolean isPossible = false;
Collection<Group> groupsToCheck = this.possibleGroups;
if(AccessMode.GROUPED == this.effectiveAccess)
{
groupsToCheck = this.inheritedGroups;
}
for(Group gr : groupsToCheck)
{
if(gr.getId().equals(group.getId()))
{
isPossible = true;
break;
}
}
return isPossible;
}
/**
* @param group
* @return
*/
public boolean allowedRemove(Group group)
{
boolean allowed = false;
for(Group gr : this.allowedRemoveGroupRefs)
{
if(gr.getId().equals(group.getId()))
{
allowed = true;
break;
}
}
return allowed;
}
public boolean isGroupInherited()
{
return AccessMode.GROUPED == this.effectiveAccess && AccessMode.INHERITED == this.accessMode;
}
/**
* @param group
* @return
*/
public boolean isLocal(Group group)
{
boolean isLocal = false;
for(Group gr : this.groups)
{
if(gr.getId().equals(group.getId()))
{
isLocal = true;
break;
}
}
return isLocal;
}
/**
* @return the isPubview
*/
public boolean isPubview()
{
return isPubview;
}
/**
* @param isPubview the isPubview to set
*/
public void setPubview(boolean isPubview)
{
this.isPubview = isPubview;
}
/**
* @return the isPubviewInherited
*/
public boolean isPubviewInherited()
{
return isPubviewInherited;
}
/**
* @param isPubviewInherited the isPubviewInherited to set
*/
public void setPubviewInherited(boolean isPubviewInherited)
{
this.isPubviewInherited = isPubviewInherited;
}
/**
* @return the hidden
*/
public boolean isHidden()
{
return hidden;
}
/**
* @param hidden the hidden to set
*/
public void setHidden(boolean hidden)
{
this.hidden = hidden;
}
/**
* @return the releaseDate
*/
public Time getReleaseDate()
{
return releaseDate;
}
/**
* @param releaseDate the releaseDate to set
*/
public void setReleaseDate(Time releaseDate)
{
this.releaseDate = releaseDate;
}
/**
* @return the retractDate
*/
public Time getRetractDate()
{
return retractDate;
}
/**
* @param retractDate the retractDate to set
*/
public void setRetractDate(Time retractDate)
{
this.retractDate = retractDate;
}
/**
* @return the useReleaseDate
*/
public boolean useReleaseDate()
{
return useReleaseDate;
}
/**
* @param useReleaseDate the useReleaseDate to set
*/
public void setUseReleaseDate(boolean useReleaseDate)
{
this.useReleaseDate = useReleaseDate;
}
/**
* @return the useRetractDate
*/
public boolean useRetractDate()
{
return useRetractDate;
}
/**
* @param useRetractDate the useRetractDate to set
*/
public void setUseRetractDate(boolean useRetractDate)
{
this.useRetractDate = useRetractDate;
}
/**
* @return the isAvailable
*/
public boolean isAvailable()
{
return isAvailable;
}
/**
* @param isAvailable the isAvailable to set
*/
public void setAvailable(boolean isAvailable)
{
this.isAvailable = isAvailable;
}
/**
* @param isPubviewPossible the isPubviewPossible to set
*/
public void setPubviewPossible(boolean isPubviewPossible)
{
this.isPubviewPossible = isPubviewPossible;
}
/**
* @param new_groups
* @return
*/
public SortedSet<String> convertToRefs(Collection<String> groupIds)
{
SortedSet<String> groupRefs = new TreeSet<String>();
for(String groupId : groupIds)
{
Group group = (Group) this.possibleGroupsMap.get(groupId);
if(group != null)
{
groupRefs.add(group.getReference());
}
}
return groupRefs;
}
/**
* @param new_groups
*/
public void setGroupsById(Collection<String> groupIds)
{
this.groups.clear();
if(groupIds != null && ! groupIds.isEmpty())
{
for(String groupId : groupIds)
{
Group group = this.possibleGroupsMap.get(groupId);
this.groups.add(group);
}
}
}
}
| true | true | public ListItem(ContentEntity entity)
{
org.sakaiproject.content.api.ContentHostingService contentService = ContentHostingService.getInstance();
this.entity = entity;
ResourceProperties props = entity.getProperties();
this.accessUrl = entity.getUrl();
this.collection = entity.isCollection();
this.id = entity.getId();
this.name = props.getProperty(ResourceProperties.PROP_DISPLAY_NAME);
this.permissions = new TreeSet<ContentPermissions>();
this.selected = false;
ResourceTypeRegistry registry = (ResourceTypeRegistry) ComponentManager.get("org.sakaiproject.content.api.ResourceTypeRegistry");
this.resourceType = entity.getResourceType();
ResourceType typeDef = registry.getType(resourceType);
this.hoverText = this.name;
if(typeDef != null)
{
this.hoverText = typeDef.getLocalizedHoverText(entity);
this.iconLocation = typeDef.getIconLocation();
String[] args = { typeDef.getLabel() };
this.otherActionsLabel = trb.getFormattedMessage("action.other", args);
}
if(this.collection)
{
ContentCollection collection = (ContentCollection) entity;
int collection_size = collection.getMemberCount();
if(collection_size == 1)
{
setSize(rb.getString("size.item"));
}
else
{
String[] args = { Integer.toString(collection_size) };
setSize(rb.getFormattedMessage("size.items", args));
}
setIsEmpty(collection_size < 1);
setSortable(contentService.isSortByPriorityEnabled() && collection_size > 1 && collection_size < ResourcesAction.EXPANDABLE_FOLDER_SIZE_LIMIT);
if(collection_size > ResourcesAction.EXPANDABLE_FOLDER_SIZE_LIMIT)
{
setIsTooBig(true);
}
}
else
{
ContentResource resource = (ContentResource) entity;
this.mimetype = resource.getContentType();
if(this.mimetype == null)
{
}
if(this.iconLocation == null)
{
this.iconLocation = ContentTypeImageService.getContentTypeImage(this.mimetype);
}
String size = "";
if(props.getProperty(ResourceProperties.PROP_CONTENT_LENGTH) != null)
{
long size_long = 0;
try
{
size_long = props.getLongProperty(ResourceProperties.PROP_CONTENT_LENGTH);
}
catch (EntityPropertyNotDefinedException e)
{
// TODO Auto-generated catch block
logger.warn("EntityPropertyNotDefinedException for size of " + this.id);
}
catch (EntityPropertyTypeException e)
{
// TODO Auto-generated catch block
logger.warn("EntityPropertyTypeException for size of " + this.id);
}
NumberFormat formatter = NumberFormat.getInstance(rb.getLocale());
formatter.setMaximumFractionDigits(1);
if(size_long > 700000000L)
{
String[] args = { formatter.format(1.0 * size_long / (1024L * 1024L * 1024L)) };
size = rb.getFormattedMessage("size.gb", args);
}
else if(size_long > 700000L)
{
String[] args = { formatter.format(1.0 * size_long / (1024L * 1024L)) };
size = rb.getFormattedMessage("size.mb", args);
}
else if(size_long > 700L)
{
String[] args = { formatter.format(1.0 * size_long / 1024L) };
size = rb.getFormattedMessage("size.kb", args);
}
else
{
String[] args = { formatter.format(size_long) };
size = rb.getFormattedMessage("size.bytes", args);
}
}
setSize(size);
}
User creator = ResourcesAction.getUserProperty(props, ResourceProperties.PROP_CREATOR);
if(creator != null)
{
String createdBy = creator.getDisplayName();
setCreatedBy(createdBy);
}
// setCreatedBy(props.getProperty(ResourceProperties.PROP_CREATOR));
this.setModifiedTime(props.getPropertyFormatted(ResourceProperties.PROP_MODIFIED_DATE));
this.accessMode = entity.getAccess();
this.effectiveAccess = entity.getInheritedAccess();
this.groups.clear();
this.groups.addAll(entity.getGroupObjects());
this.inheritedGroups.clear();
this.inheritedGroups.addAll(entity.getInheritedGroupObjects());
Reference ref = EntityManager.newReference(entity.getReference());
try
{
Site site = SiteService.getSite(ref.getContext());
setPossibleGroups(site.getGroups());
}
catch (IdUnusedException e)
{
// TODO Auto-generated catch block
logger.warn("IdUnusedException ", e);
}
Collection<Group> allowedRemoveGroups = null;
if(AccessMode.GROUPED == this.accessMode)
{
allowedRemoveGroups = contentService.getGroupsWithRemovePermission(id);
Collection<Group> more = contentService.getGroupsWithRemovePermission(ref.getContainer());
if(more != null && ! more.isEmpty())
{
allowedRemoveGroups.addAll(more);
}
}
else if(AccessMode.GROUPED == this.effectiveAccess)
{
allowedRemoveGroups = contentService.getGroupsWithRemovePermission(ref.getContainer());
}
else
{
allowedRemoveGroups = contentService.getGroupsWithRemovePermission(contentService.getSiteCollection(ref.getContext()));
}
this.allowedRemoveGroupRefs = allowedRemoveGroups;
Collection<Group> allowedAddGroups = null;
if(AccessMode.GROUPED == this.accessMode)
{
allowedAddGroups = contentService.getGroupsWithAddPermission(id);
Collection<Group> more = contentService.getGroupsWithAddPermission(ref.getContainer());
if(more != null && ! more.isEmpty())
{
allowedAddGroups.addAll(more);
}
}
else if(AccessMode.GROUPED == this.effectiveAccess)
{
allowedAddGroups = contentService.getGroupsWithAddPermission(ref.getContainer());
}
else
{
allowedAddGroups = contentService.getGroupsWithAddPermission(contentService.getSiteCollection(ref.getContext()));
}
this.allowedAddGroupRefs = allowedAddGroups;
this.isPubviewInherited = contentService.isInheritingPubView(id);
if (!this.isPubviewInherited)
{
this.isPubview = contentService.isPubView(id);
}
this.hidden = entity.isHidden();
Time releaseDate = entity.getReleaseDate();
if(releaseDate == null)
{
this.useReleaseDate = false;
this.releaseDate = TimeService.newTime();
}
else
{
this.useReleaseDate = true;
this.releaseDate = releaseDate;
}
Time retractDate = entity.getRetractDate();
if(retractDate == null)
{
this.useRetractDate = false;
}
else
{
this.useRetractDate = true;
this.retractDate = retractDate;
}
this.isAvailable = entity.isAvailable();
}
| public ListItem(ContentEntity entity)
{
org.sakaiproject.content.api.ContentHostingService contentService = ContentHostingService.getInstance();
this.entity = entity;
ResourceProperties props = entity.getProperties();
this.accessUrl = entity.getUrl();
this.collection = entity.isCollection();
this.id = entity.getId();
this.name = props.getProperty(ResourceProperties.PROP_DISPLAY_NAME);
this.permissions = new TreeSet<ContentPermissions>();
this.selected = false;
ResourceTypeRegistry registry = (ResourceTypeRegistry) ComponentManager.get("org.sakaiproject.content.api.ResourceTypeRegistry");
this.resourceType = entity.getResourceType();
ResourceType typeDef = registry.getType(resourceType);
this.hoverText = this.name;
if(typeDef != null)
{
this.hoverText = typeDef.getLocalizedHoverText(entity);
this.iconLocation = typeDef.getIconLocation();
String[] args = { typeDef.getLabel() };
this.otherActionsLabel = trb.getFormattedMessage("action.other", args);
}
if(this.collection)
{
ContentCollection collection = (ContentCollection) entity;
int collection_size = collection.getMemberCount();
if(collection_size == 1)
{
setSize(rb.getString("size.item"));
}
else
{
String[] args = { Integer.toString(collection_size) };
setSize(rb.getFormattedMessage("size.items", args));
}
setIsEmpty(collection_size < 1);
setSortable(contentService.isSortByPriorityEnabled() && collection_size > 1 && collection_size < ResourcesAction.EXPANDABLE_FOLDER_SIZE_LIMIT);
if(collection_size > ResourcesAction.EXPANDABLE_FOLDER_SIZE_LIMIT)
{
setIsTooBig(true);
}
}
else
{
ContentResource resource = (ContentResource) entity;
this.mimetype = resource.getContentType();
if(this.mimetype == null)
{
}
if(this.iconLocation == null)
{
this.iconLocation = ContentTypeImageService.getContentTypeImage(this.mimetype);
}
String size = "";
if(props.getProperty(ResourceProperties.PROP_CONTENT_LENGTH) != null)
{
long size_long = 0;
try
{
size_long = props.getLongProperty(ResourceProperties.PROP_CONTENT_LENGTH);
}
catch (EntityPropertyNotDefinedException e)
{
// TODO Auto-generated catch block
logger.warn("EntityPropertyNotDefinedException for size of " + this.id);
}
catch (EntityPropertyTypeException e)
{
// TODO Auto-generated catch block
logger.warn("EntityPropertyTypeException for size of " + this.id);
}
NumberFormat formatter = NumberFormat.getInstance(rb.getLocale());
formatter.setMaximumFractionDigits(1);
if(size_long > 700000000L)
{
String[] args = { formatter.format(1.0 * size_long / (1024L * 1024L * 1024L)) };
size = rb.getFormattedMessage("size.gb", args);
}
else if(size_long > 700000L)
{
String[] args = { formatter.format(1.0 * size_long / (1024L * 1024L)) };
size = rb.getFormattedMessage("size.mb", args);
}
else if(size_long > 700L)
{
String[] args = { formatter.format(1.0 * size_long / 1024L) };
size = rb.getFormattedMessage("size.kb", args);
}
else
{
String[] args = { formatter.format(size_long) };
size = rb.getFormattedMessage("size.bytes", args);
}
}
setSize(size);
}
User creator = ResourcesAction.getUserProperty(props, ResourceProperties.PROP_CREATOR);
if(creator != null)
{
String createdBy = creator.getDisplayName();
setCreatedBy(createdBy);
}
// setCreatedBy(props.getProperty(ResourceProperties.PROP_CREATOR));
this.setModifiedTime(props.getPropertyFormatted(ResourceProperties.PROP_MODIFIED_DATE));
this.accessMode = entity.getAccess();
this.effectiveAccess = entity.getInheritedAccess();
this.groups.clear();
this.groups.addAll(entity.getGroupObjects());
this.inheritedGroups.clear();
this.inheritedGroups.addAll(entity.getInheritedGroupObjects());
Reference ref = EntityManager.newReference(entity.getReference());
if(ref != null && ref.getContext() != null)
{
try
{
Site site = SiteService.getSite(ref.getContext());
setPossibleGroups(site.getGroups());
}
catch (IdUnusedException e)
{
logger.warn("IdUnusedException for a site in resources: " + ref.getContext() + " (" + ref.getReference() + ")");
}
}
Collection<Group> allowedRemoveGroups = null;
if(AccessMode.GROUPED == this.accessMode)
{
allowedRemoveGroups = contentService.getGroupsWithRemovePermission(id);
Collection<Group> more = contentService.getGroupsWithRemovePermission(ref.getContainer());
if(more != null && ! more.isEmpty())
{
allowedRemoveGroups.addAll(more);
}
}
else if(AccessMode.GROUPED == this.effectiveAccess)
{
allowedRemoveGroups = contentService.getGroupsWithRemovePermission(ref.getContainer());
}
else
{
allowedRemoveGroups = contentService.getGroupsWithRemovePermission(contentService.getSiteCollection(ref.getContext()));
}
this.allowedRemoveGroupRefs = allowedRemoveGroups;
Collection<Group> allowedAddGroups = null;
if(AccessMode.GROUPED == this.accessMode)
{
allowedAddGroups = contentService.getGroupsWithAddPermission(id);
Collection<Group> more = contentService.getGroupsWithAddPermission(ref.getContainer());
if(more != null && ! more.isEmpty())
{
allowedAddGroups.addAll(more);
}
}
else if(AccessMode.GROUPED == this.effectiveAccess)
{
allowedAddGroups = contentService.getGroupsWithAddPermission(ref.getContainer());
}
else
{
allowedAddGroups = contentService.getGroupsWithAddPermission(contentService.getSiteCollection(ref.getContext()));
}
this.allowedAddGroupRefs = allowedAddGroups;
this.isPubviewInherited = contentService.isInheritingPubView(id);
if (!this.isPubviewInherited)
{
this.isPubview = contentService.isPubView(id);
}
this.hidden = entity.isHidden();
Time releaseDate = entity.getReleaseDate();
if(releaseDate == null)
{
this.useReleaseDate = false;
this.releaseDate = TimeService.newTime();
}
else
{
this.useReleaseDate = true;
this.releaseDate = releaseDate;
}
Time retractDate = entity.getRetractDate();
if(retractDate == null)
{
this.useRetractDate = false;
}
else
{
this.useRetractDate = true;
this.retractDate = retractDate;
}
this.isAvailable = entity.isAvailable();
}
|
diff --git a/modules/cpr/src/main/java/org/atmosphere/container/GrizzlyCometSupport.java b/modules/cpr/src/main/java/org/atmosphere/container/GrizzlyCometSupport.java
index 1a0d7b1bf..3845ad7ce 100644
--- a/modules/cpr/src/main/java/org/atmosphere/container/GrizzlyCometSupport.java
+++ b/modules/cpr/src/main/java/org/atmosphere/container/GrizzlyCometSupport.java
@@ -1,244 +1,246 @@
/*
* Copyright 2013 Jeanfrancois Arcand
*
* 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.
*/
/*
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2007-2008 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can obtain
* a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
* or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
* Sun designates this particular file as subject to the "Classpath" exception
* as provided by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the License
* Header, with the fields enclosed by brackets [] replaced by your own
* identifying information: "Portions Copyrighted [year]
* [name of copyright owner]"
*
* Contributor(s):
*
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*
*/
package org.atmosphere.container;
import com.sun.grizzly.comet.CometContext;
import com.sun.grizzly.comet.CometEngine;
import com.sun.grizzly.comet.CometEvent;
import com.sun.grizzly.comet.CometHandler;
import org.atmosphere.cpr.Action;
import org.atmosphere.cpr.ApplicationConfig;
import org.atmosphere.cpr.AsynchronousProcessor;
import org.atmosphere.cpr.AtmosphereConfig;
import org.atmosphere.cpr.AtmosphereRequest;
import org.atmosphere.cpr.AtmosphereResourceImpl;
import org.atmosphere.cpr.AtmosphereResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import java.io.IOException;
import static org.atmosphere.cpr.ApplicationConfig.MAX_INACTIVE;
/**
* Comet Portable Runtime implementation on top of Grizzly 1.5 and up.
*
* @author Jeanfrancois Arcand
*/
public class GrizzlyCometSupport extends AsynchronousProcessor {
private static final Logger logger = LoggerFactory.getLogger(GrizzlyCometSupport.class);
private static final String ATMOSPHERE = "/atmosphere";
private String atmosphereCtx = "";
public GrizzlyCometSupport(AtmosphereConfig config) {
super(config);
}
/**
* Init Grizzly's {@link CometContext} that will be used to suspend and resume the response.
*
* @param sc the {@link ServletContext}
* @throws javax.servlet.ServletException
*/
@Override
public void init(ServletConfig sc) throws ServletException {
super.init(sc);
atmosphereCtx = sc.getServletContext().getContextPath() + ATMOSPHERE;
CometEngine cometEngine = CometEngine.getEngine();
CometContext context = cometEngine.register(atmosphereCtx);
context.setExpirationDelay(-1);
logger.debug("Created CometContext for atmosphere context: {}", atmosphereCtx);
}
@Override
public Action service(AtmosphereRequest req, AtmosphereResponse res)
throws IOException, ServletException {
CometContext ctx = CometEngine.getEngine().getCometContext(atmosphereCtx);
Action action = suspended(req, res);
if (action.type() == Action.TYPE.SUSPEND) {
suspend(ctx, action, req, res);
} else if (action.type() == Action.TYPE.RESUME) {
resume(req, ctx);
}
return action;
}
/**
* Suspend the response
*
* @param ctx
* @param action
* @param req
* @param res
*/
private void suspend(CometContext ctx, Action action, AtmosphereRequest req, AtmosphereResponse res) {
VoidCometHandler c = new VoidCometHandler(req, res);
ctx.setExpirationDelay(action.timeout());
ctx.addCometHandler(c);
req.setAttribute(ATMOSPHERE, c.hashCode());
ctx.addAttribute("Time", System.currentTimeMillis());
if (supportSession()) {
// Store as well in the session in case the resume operation
// happens outside the AtmosphereHandler.onStateChange scope.
req.getSession().setAttribute(ATMOSPHERE, c.hashCode());
}
}
/**
* Resume the underlying response.
*
* @param req an {@link AtmosphereRequest}
* @param ctx a {@link CometContext}
*/
private void resume(AtmosphereRequest req, CometContext ctx) {
if (req.getAttribute(ATMOSPHERE) == null) {
return;
}
CometHandler handler = ctx.getCometHandler((Integer) req.getAttribute(ATMOSPHERE));
req.removeAttribute(ATMOSPHERE);
if (handler == null && supportSession() && req.getSession(false) != null) {
handler = ctx.getCometHandler((Integer) req.getSession(false).getAttribute(ATMOSPHERE));
req.getSession().removeAttribute(ATMOSPHERE);
}
- try {
- AtmosphereResourceImpl.class.cast(req.resource()).cancel();
- } catch (IOException e) {
- logger.trace("", e);
+ if (req.resource() != null) {
+ try {
+ AtmosphereResourceImpl.class.cast(req.resource()).cancel();
+ } catch (IOException e) {
+ logger.trace("", e);
+ }
}
if (handler != null && (config.getInitParameter(ApplicationConfig.RESUME_AND_KEEPALIVE) == null
|| config.getInitParameter(ApplicationConfig.RESUME_AND_KEEPALIVE).equalsIgnoreCase("false"))) {
ctx.resumeCometHandler(handler);
}
}
@Override
public void action(AtmosphereResourceImpl r) {
super.action(r);
if (r.action().type() == Action.TYPE.RESUME && r.isInScope()) {
CometContext ctx = CometEngine.getEngine().getCometContext(atmosphereCtx);
resume(r.getRequest(), ctx);
}
}
@Override
public Action cancelled(AtmosphereRequest req, AtmosphereResponse res)
throws IOException, ServletException {
Action action = super.cancelled(req, res);
if (req.getAttribute(MAX_INACTIVE) != null && Long.class.cast(req.getAttribute(MAX_INACTIVE)) == -1) {
resume(req, CometEngine.getEngine().getCometContext(atmosphereCtx));
}
return action;
}
/**
* Void {@link CometHandler}, which delegate the processing of the
* {@link AtmosphereRequest} to an {@link org.atmosphere.cpr.AtmosphereResourceImpl}.
*/
private class VoidCometHandler implements CometHandler {
AtmosphereRequest req;
AtmosphereResponse res;
public VoidCometHandler(AtmosphereRequest req, AtmosphereResponse res) {
this.req = req;
this.res = res;
}
@Override
public void attach(Object o) {
}
@Override
public void onEvent(CometEvent ce) throws IOException {
}
@Override
public void onInitialize(CometEvent ce) throws IOException {
}
@Override
public void onTerminate(CometEvent ce) throws IOException {
}
@Override
public synchronized void onInterrupt(CometEvent ce) throws IOException {
long timeStamp = (Long) ce.getCometContext().getAttribute("Time");
try {
if (ce.getCometContext().getExpirationDelay() > 0
&& (System.currentTimeMillis() - timeStamp) >= ce.getCometContext().getExpirationDelay()) {
timedout(req, res);
} else {
cancelled(req, res);
}
} catch (ServletException ex) {
logger.warn("onInterrupt() encountered exception", ex);
}
}
}
}
| true | true | private void resume(AtmosphereRequest req, CometContext ctx) {
if (req.getAttribute(ATMOSPHERE) == null) {
return;
}
CometHandler handler = ctx.getCometHandler((Integer) req.getAttribute(ATMOSPHERE));
req.removeAttribute(ATMOSPHERE);
if (handler == null && supportSession() && req.getSession(false) != null) {
handler = ctx.getCometHandler((Integer) req.getSession(false).getAttribute(ATMOSPHERE));
req.getSession().removeAttribute(ATMOSPHERE);
}
try {
AtmosphereResourceImpl.class.cast(req.resource()).cancel();
} catch (IOException e) {
logger.trace("", e);
}
if (handler != null && (config.getInitParameter(ApplicationConfig.RESUME_AND_KEEPALIVE) == null
|| config.getInitParameter(ApplicationConfig.RESUME_AND_KEEPALIVE).equalsIgnoreCase("false"))) {
ctx.resumeCometHandler(handler);
}
}
| private void resume(AtmosphereRequest req, CometContext ctx) {
if (req.getAttribute(ATMOSPHERE) == null) {
return;
}
CometHandler handler = ctx.getCometHandler((Integer) req.getAttribute(ATMOSPHERE));
req.removeAttribute(ATMOSPHERE);
if (handler == null && supportSession() && req.getSession(false) != null) {
handler = ctx.getCometHandler((Integer) req.getSession(false).getAttribute(ATMOSPHERE));
req.getSession().removeAttribute(ATMOSPHERE);
}
if (req.resource() != null) {
try {
AtmosphereResourceImpl.class.cast(req.resource()).cancel();
} catch (IOException e) {
logger.trace("", e);
}
}
if (handler != null && (config.getInitParameter(ApplicationConfig.RESUME_AND_KEEPALIVE) == null
|| config.getInitParameter(ApplicationConfig.RESUME_AND_KEEPALIVE).equalsIgnoreCase("false"))) {
ctx.resumeCometHandler(handler);
}
}
|
diff --git a/src/me/naithantu/ArenaPVP/Util/Util.java b/src/me/naithantu/ArenaPVP/Util/Util.java
index 28491d5..0e661aa 100644
--- a/src/me/naithantu/ArenaPVP/Util/Util.java
+++ b/src/me/naithantu/ArenaPVP/Util/Util.java
@@ -1,124 +1,124 @@
package me.naithantu.ArenaPVP.Util;
import java.util.Collection;
import java.util.List;
import me.naithantu.ArenaPVP.Storage.YamlStorage;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.Configuration;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.potion.PotionEffect;
import org.bukkit.util.Vector;
public class Util {
public static void broadcast(String msg) {
msg = ChatColor.translateAlternateColorCodes('&', msg);
Bukkit.getServer().broadcastMessage(ChatColor.DARK_RED + "[PVP] " + ChatColor.WHITE + msg);
}
public static void msg(CommandSender sender, String msg) {
msg = ChatColor.translateAlternateColorCodes('&', msg);
if (sender instanceof Player) {
sender.sendMessage(ChatColor.DARK_RED + "[PVP] " + ChatColor.WHITE + msg);
} else {
sender.sendMessage("[PVP] " + msg);
}
}
public static Location getLocationFromString(String string) {
String[] stringSplit = string.split(":");
World world = Bukkit.getServer().getWorld(stringSplit[0]);
Double x = Double.valueOf(stringSplit[1]);
Double y = Double.valueOf(stringSplit[2]);
Double z = Double.valueOf(stringSplit[3]);
Float yaw = Float.valueOf(stringSplit[4]);
Float pitch = Float.valueOf(stringSplit[5]);
Location location = new Location(world, x, y, z, yaw, pitch);
return location;
}
public static String getStringFromLocation(Location location) {
return location.getWorld().getName() + ":" + location.getX() + ":" + location.getY() + ":" + location.getZ() + ":" + location.getYaw() + ":" + location.getPitch();
}
@SuppressWarnings("unchecked")
public static void playerLeave(Player player, YamlStorage playerStorage) {
Configuration playerConfig = playerStorage.getConfig();
//Clear players inventory and then load saved inventory.
PlayerInventory inventory = player.getInventory();
inventory.clear();
inventory.setArmorContents(new ItemStack[4]);
List<ItemStack> inventoryContents = (List<ItemStack>) playerConfig.getList("inventory");
List<ItemStack> armorContents = (List<ItemStack>) playerConfig.getList("armor");
player.setLevel(playerConfig.getInt("level"));
player.setExp((float) playerConfig.getDouble("exp"));
player.setHealth(playerConfig.getDouble("health"));
player.setFoodLevel(playerConfig.getInt("hunger"));
player.setGameMode(GameMode.valueOf(playerConfig.getString("gamemode")));
- if (playerConfig.getBoolean("flying")) {
+ if (playerConfig.getBoolean("flying") || GameMode.valueOf(playerConfig.getString("gamemode")) == GameMode.CREATIVE) {
player.setAllowFlight(true);
player.setFlying(true);
} else {
player.setAllowFlight(false);
}
player.addPotionEffects((Collection<PotionEffect>) playerConfig.getList("potioneffects"));
inventory.setContents(inventoryContents.toArray(new ItemStack[36]));
inventory.setArmorContents(armorContents.toArray(new ItemStack[4]));
playerConfig.set("inventory", null);
playerConfig.set("armor", null);
playerConfig.set("level", null);
playerConfig.set("exp", null);
playerConfig.set("health", null);
playerConfig.set("hunger", null);
playerConfig.set("gamemode", null);
playerConfig.set("flying", null);
playerConfig.set("potioneffects", null);
playerConfig.set("hastoleave", null);
playerStorage.saveConfig();
}
public static void playerJoin(Player player, YamlStorage playerStorage) {
Configuration playerConfig = playerStorage.getConfig();
//Save players inventory and then clear it.
PlayerInventory inventory = player.getInventory();
playerConfig.set("inventory", inventory.getContents());
playerConfig.set("armor", inventory.getArmorContents());
playerConfig.set("level", player.getLevel());
playerConfig.set("exp", player.getExp());
playerConfig.set("health", player.getHealth());
playerConfig.set("hunger", player.getFoodLevel());
playerConfig.set("gamemode", player.getGameMode().toString());
playerConfig.set("flying", player.isFlying());
playerConfig.set("potioneffects", player.getActivePotionEffects());
playerStorage.saveConfig();
inventory.clear();
inventory.setArmorContents(new ItemStack[4]);
player.setLevel(0);
player.setExp(0);
player.setVelocity(new Vector(0, 0, 0));
player.setGameMode(GameMode.SURVIVAL);
player.setFoodLevel(20);
player.setHealth(20);
for (PotionEffect effect : player.getActivePotionEffects())
player.removePotionEffect(effect.getType());
}
public static String capaltizeFirstLetter(String s) {
return s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
}
}
| true | true | public static void playerLeave(Player player, YamlStorage playerStorage) {
Configuration playerConfig = playerStorage.getConfig();
//Clear players inventory and then load saved inventory.
PlayerInventory inventory = player.getInventory();
inventory.clear();
inventory.setArmorContents(new ItemStack[4]);
List<ItemStack> inventoryContents = (List<ItemStack>) playerConfig.getList("inventory");
List<ItemStack> armorContents = (List<ItemStack>) playerConfig.getList("armor");
player.setLevel(playerConfig.getInt("level"));
player.setExp((float) playerConfig.getDouble("exp"));
player.setHealth(playerConfig.getDouble("health"));
player.setFoodLevel(playerConfig.getInt("hunger"));
player.setGameMode(GameMode.valueOf(playerConfig.getString("gamemode")));
if (playerConfig.getBoolean("flying")) {
player.setAllowFlight(true);
player.setFlying(true);
} else {
player.setAllowFlight(false);
}
player.addPotionEffects((Collection<PotionEffect>) playerConfig.getList("potioneffects"));
inventory.setContents(inventoryContents.toArray(new ItemStack[36]));
inventory.setArmorContents(armorContents.toArray(new ItemStack[4]));
playerConfig.set("inventory", null);
playerConfig.set("armor", null);
playerConfig.set("level", null);
playerConfig.set("exp", null);
playerConfig.set("health", null);
playerConfig.set("hunger", null);
playerConfig.set("gamemode", null);
playerConfig.set("flying", null);
playerConfig.set("potioneffects", null);
playerConfig.set("hastoleave", null);
playerStorage.saveConfig();
}
| public static void playerLeave(Player player, YamlStorage playerStorage) {
Configuration playerConfig = playerStorage.getConfig();
//Clear players inventory and then load saved inventory.
PlayerInventory inventory = player.getInventory();
inventory.clear();
inventory.setArmorContents(new ItemStack[4]);
List<ItemStack> inventoryContents = (List<ItemStack>) playerConfig.getList("inventory");
List<ItemStack> armorContents = (List<ItemStack>) playerConfig.getList("armor");
player.setLevel(playerConfig.getInt("level"));
player.setExp((float) playerConfig.getDouble("exp"));
player.setHealth(playerConfig.getDouble("health"));
player.setFoodLevel(playerConfig.getInt("hunger"));
player.setGameMode(GameMode.valueOf(playerConfig.getString("gamemode")));
if (playerConfig.getBoolean("flying") || GameMode.valueOf(playerConfig.getString("gamemode")) == GameMode.CREATIVE) {
player.setAllowFlight(true);
player.setFlying(true);
} else {
player.setAllowFlight(false);
}
player.addPotionEffects((Collection<PotionEffect>) playerConfig.getList("potioneffects"));
inventory.setContents(inventoryContents.toArray(new ItemStack[36]));
inventory.setArmorContents(armorContents.toArray(new ItemStack[4]));
playerConfig.set("inventory", null);
playerConfig.set("armor", null);
playerConfig.set("level", null);
playerConfig.set("exp", null);
playerConfig.set("health", null);
playerConfig.set("hunger", null);
playerConfig.set("gamemode", null);
playerConfig.set("flying", null);
playerConfig.set("potioneffects", null);
playerConfig.set("hastoleave", null);
playerStorage.saveConfig();
}
|
diff --git a/src/com/jidesoft/swing/CheckBoxTreeCellRenderer.java b/src/com/jidesoft/swing/CheckBoxTreeCellRenderer.java
index 76c0e511..2f3ff771 100644
--- a/src/com/jidesoft/swing/CheckBoxTreeCellRenderer.java
+++ b/src/com/jidesoft/swing/CheckBoxTreeCellRenderer.java
@@ -1,165 +1,165 @@
/*
* @(#)CheckBoxTreeCellRenderer.java 8/11/2005
*
* Copyright 2002 - 2005 JIDE Software Inc. All rights reserved.
*/
package com.jidesoft.swing;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.tree.TreeCellRenderer;
import javax.swing.tree.TreePath;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.io.Serializable;
/**
* Renderers an item in a tree using JCheckBox.
*/
public class CheckBoxTreeCellRenderer extends JPanel implements TreeCellRenderer, Serializable {
private static final long serialVersionUID = 30207434500313004L;
/**
* The checkbox that is used to paint the check box in cell renderer
*/
protected TristateCheckBox _checkBox = null;
protected JComponent _emptyBox = null;
protected JCheckBox _protoType;
/**
* The label which appears after the check box.
*/
protected TreeCellRenderer _actualTreeRenderer;
/**
* Constructs a default renderer object for an item in a list.
*/
public CheckBoxTreeCellRenderer() {
this(null);
}
public CheckBoxTreeCellRenderer(TreeCellRenderer renderer) {
this(renderer, null);
}
public CheckBoxTreeCellRenderer(TreeCellRenderer renderer, TristateCheckBox checkBox) {
_protoType = new TristateCheckBox();
if (checkBox == null) {
_checkBox = createCheckBox();
}
else {
_checkBox = checkBox;
}
_emptyBox = (JComponent) Box.createHorizontalStrut(_protoType.getPreferredSize().width);
setLayout(new BorderLayout(0, 0));
setOpaque(false);
_actualTreeRenderer = renderer;
}
/**
* Create the check box in the cell.
* <p/>
* By default, it creates a TristateCheckBox and set opaque to false.
*
* @return the check box instance.
*/
protected TristateCheckBox createCheckBox() {
TristateCheckBox checkBox = new NullTristateCheckBox();
checkBox.setOpaque(false);
return checkBox;
}
public TreeCellRenderer getActualTreeRenderer() {
return _actualTreeRenderer;
}
public void setActualTreeRenderer(TreeCellRenderer actualTreeRenderer) {
_actualTreeRenderer = actualTreeRenderer;
}
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
removeAll();
- _checkBox.setPreferredSize(new Dimension(_protoType.getPreferredSize().width, 0));
+// _checkBox.setPreferredSize(new Dimension(_protoType.getPreferredSize().width, 0));
_emptyBox.setPreferredSize(new Dimension(_protoType.getPreferredSize().width, 0));
applyComponentOrientation(tree.getComponentOrientation());
TreePath path = tree.getPathForRow(row);
if (path != null && tree instanceof CheckBoxTree) {
CheckBoxTreeSelectionModel selectionModel = ((CheckBoxTree) tree).getCheckBoxTreeSelectionModel();
if (selectionModel != null) {
boolean enabled = tree.isEnabled() && ((CheckBoxTree) tree).isCheckBoxEnabled() && ((CheckBoxTree) tree).isCheckBoxEnabled(path);
if (!enabled && !selected) {
if (getBackground() != null) {
setForeground(getBackground().darker());
}
}
_checkBox.setEnabled(enabled);
updateCheckBoxState(_checkBox, path, selectionModel);
}
}
if (_actualTreeRenderer != null) {
JComponent treeCellRendererComponent = (JComponent) _actualTreeRenderer.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
Border border = treeCellRendererComponent.getBorder();
setBorder(border);
treeCellRendererComponent.setBorder(BorderFactory.createEmptyBorder());
if (path == null || !(tree instanceof CheckBoxTree) || ((CheckBoxTree) tree).isCheckBoxVisible(path)) {
remove(_emptyBox);
add(_checkBox, BorderLayout.BEFORE_LINE_BEGINS);
}
else {
remove(_checkBox);
add(_emptyBox, BorderLayout.AFTER_LINE_ENDS); // expand the tree node size to be the same as the one with check box.
}
add(treeCellRendererComponent);
// copy the background and foreground for the renderer component
setBackground(treeCellRendererComponent.getBackground());
treeCellRendererComponent.setBackground(null);
setForeground(treeCellRendererComponent.getForeground());
treeCellRendererComponent.setForeground(null);
}
return this;
}
/**
* Updates the check box state based on the selection in the selection model. By default, we check if the path is
* selected. If yes, we mark the check box as TristateCheckBox.SELECTED. If not, we will check if the path is
* partially selected, if yes, we set the check box as null or TristateCheckBox.DONT_CARE to indicate the path is
* partially selected. Otherwise, we set it to TristateCheckBox.NOT_SELECTED.
*
* @param checkBox the TristateCheckBox for the particular tree path.
* @param path the tree path.
* @param selectionModel the CheckBoxTreeSelectionModel.
*/
protected void updateCheckBoxState(TristateCheckBox checkBox, TreePath path, CheckBoxTreeSelectionModel selectionModel) {
if (selectionModel.isPathSelected(path, selectionModel.isDigIn()))
checkBox.setState(TristateCheckBox.STATE_SELECTED);
else
checkBox.setState(selectionModel.isDigIn() && selectionModel.isPartiallySelected(path) ? TristateCheckBox.STATE_MIXED : TristateCheckBox.STATE_UNSELECTED);
}
@Override
public String getToolTipText(MouseEvent event) {
if (_actualTreeRenderer instanceof JComponent) {
Point p = event.getPoint();
p.translate(-_checkBox.getWidth(), 0);
MouseEvent newEvent = new MouseEvent(((JComponent) _actualTreeRenderer), event.getID(),
event.getWhen(),
event.getModifiers(),
p.x, p.y, event.getClickCount(),
event.isPopupTrigger());
String tip = ((JComponent) _actualTreeRenderer).getToolTipText(
newEvent);
if (tip != null) {
return tip;
}
}
return super.getToolTipText(event);
}
}
| true | true | public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
removeAll();
_checkBox.setPreferredSize(new Dimension(_protoType.getPreferredSize().width, 0));
_emptyBox.setPreferredSize(new Dimension(_protoType.getPreferredSize().width, 0));
applyComponentOrientation(tree.getComponentOrientation());
TreePath path = tree.getPathForRow(row);
if (path != null && tree instanceof CheckBoxTree) {
CheckBoxTreeSelectionModel selectionModel = ((CheckBoxTree) tree).getCheckBoxTreeSelectionModel();
if (selectionModel != null) {
boolean enabled = tree.isEnabled() && ((CheckBoxTree) tree).isCheckBoxEnabled() && ((CheckBoxTree) tree).isCheckBoxEnabled(path);
if (!enabled && !selected) {
if (getBackground() != null) {
setForeground(getBackground().darker());
}
}
_checkBox.setEnabled(enabled);
updateCheckBoxState(_checkBox, path, selectionModel);
}
}
if (_actualTreeRenderer != null) {
JComponent treeCellRendererComponent = (JComponent) _actualTreeRenderer.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
Border border = treeCellRendererComponent.getBorder();
setBorder(border);
treeCellRendererComponent.setBorder(BorderFactory.createEmptyBorder());
if (path == null || !(tree instanceof CheckBoxTree) || ((CheckBoxTree) tree).isCheckBoxVisible(path)) {
remove(_emptyBox);
add(_checkBox, BorderLayout.BEFORE_LINE_BEGINS);
}
else {
remove(_checkBox);
add(_emptyBox, BorderLayout.AFTER_LINE_ENDS); // expand the tree node size to be the same as the one with check box.
}
add(treeCellRendererComponent);
// copy the background and foreground for the renderer component
setBackground(treeCellRendererComponent.getBackground());
treeCellRendererComponent.setBackground(null);
setForeground(treeCellRendererComponent.getForeground());
treeCellRendererComponent.setForeground(null);
}
return this;
}
| public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
removeAll();
// _checkBox.setPreferredSize(new Dimension(_protoType.getPreferredSize().width, 0));
_emptyBox.setPreferredSize(new Dimension(_protoType.getPreferredSize().width, 0));
applyComponentOrientation(tree.getComponentOrientation());
TreePath path = tree.getPathForRow(row);
if (path != null && tree instanceof CheckBoxTree) {
CheckBoxTreeSelectionModel selectionModel = ((CheckBoxTree) tree).getCheckBoxTreeSelectionModel();
if (selectionModel != null) {
boolean enabled = tree.isEnabled() && ((CheckBoxTree) tree).isCheckBoxEnabled() && ((CheckBoxTree) tree).isCheckBoxEnabled(path);
if (!enabled && !selected) {
if (getBackground() != null) {
setForeground(getBackground().darker());
}
}
_checkBox.setEnabled(enabled);
updateCheckBoxState(_checkBox, path, selectionModel);
}
}
if (_actualTreeRenderer != null) {
JComponent treeCellRendererComponent = (JComponent) _actualTreeRenderer.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
Border border = treeCellRendererComponent.getBorder();
setBorder(border);
treeCellRendererComponent.setBorder(BorderFactory.createEmptyBorder());
if (path == null || !(tree instanceof CheckBoxTree) || ((CheckBoxTree) tree).isCheckBoxVisible(path)) {
remove(_emptyBox);
add(_checkBox, BorderLayout.BEFORE_LINE_BEGINS);
}
else {
remove(_checkBox);
add(_emptyBox, BorderLayout.AFTER_LINE_ENDS); // expand the tree node size to be the same as the one with check box.
}
add(treeCellRendererComponent);
// copy the background and foreground for the renderer component
setBackground(treeCellRendererComponent.getBackground());
treeCellRendererComponent.setBackground(null);
setForeground(treeCellRendererComponent.getForeground());
treeCellRendererComponent.setForeground(null);
}
return this;
}
|
diff --git a/src/main/java/org/sagebionetworks/web/client/widget/login/LoginWidget.java b/src/main/java/org/sagebionetworks/web/client/widget/login/LoginWidget.java
index 53689d3bf..0adfd7e33 100644
--- a/src/main/java/org/sagebionetworks/web/client/widget/login/LoginWidget.java
+++ b/src/main/java/org/sagebionetworks/web/client/widget/login/LoginWidget.java
@@ -1,166 +1,168 @@
package org.sagebionetworks.web.client.widget.login;
import java.util.ArrayList;
import java.util.List;
import org.sagebionetworks.repo.model.UserSessionData;
import org.sagebionetworks.schema.adapter.JSONObjectAdapterException;
import org.sagebionetworks.web.client.DisplayConstants;
import org.sagebionetworks.web.client.GlobalApplicationState;
import org.sagebionetworks.web.client.security.AuthenticationController;
import org.sagebionetworks.web.client.transform.NodeModelCreator;
import org.sagebionetworks.web.shared.exceptions.UnknownErrorException;
import com.google.gwt.place.shared.Place;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;
public class LoginWidget implements LoginWidgetView.Presenter {
private LoginWidgetView view;
private AuthenticationController authenticationController;
private List<UserListener> listeners = new ArrayList<UserListener>();
private String openIdActionUrl;
private String openIdReturnUrl;
private NodeModelCreator nodeModelCreator;
private GlobalApplicationState globalApplicationState;
@Inject
public LoginWidget(LoginWidgetView view, AuthenticationController controller, NodeModelCreator nodeModelCreator, GlobalApplicationState globalApplicationState) {
this.view = view;
view.setPresenter(this);
this.authenticationController = controller;
this.nodeModelCreator = nodeModelCreator;
this.globalApplicationState = globalApplicationState;
}
public Widget asWidget() {
view.setPresenter(this);
return view.asWidget();
}
public void addUserListener(UserListener listener){
listeners.add(listener);
}
@Override
public void setUsernameAndPassword(final String username, final String password) {
authenticationController.loginUser(username, password, new AsyncCallback<String>() {
@Override
public void onSuccess(String result) {
view.clear();
UserSessionData toBeParsed = null;
if (result != null){
try {
toBeParsed = nodeModelCreator.createJSONEntity(result, UserSessionData.class);
} catch (JSONObjectAdapterException e) {
onFailure(new UnknownErrorException(DisplayConstants.ERROR_INCOMPATIBLE_CLIENT_VERSION));
}
}
final UserSessionData userSessionData = toBeParsed;
if (!userSessionData.getSession().getAcceptsTermsOfUse()) {
authenticationController.getTermsOfUse(new AsyncCallback<String>() {
public void onSuccess(String termsOfUseContent) {
view.showTermsOfUse(termsOfUseContent,
new AcceptTermsOfUseCallback() {
public void accepted() {
authenticationController.signTermsOfUse(true, new AsyncCallback<Void> () {
@Override
public void onFailure(Throwable caught) {
view.showError("An error occurred. Please try logging in again.");
}
@Override
public void onSuccess(Void result) {
// Have to get the UserSessionData again,
// since it won't contain the UserProfile if the terms haven't been signed
authenticationController.loginUserSSO(userSessionData.getSession().getSessionToken(), new AsyncCallback<String>() {
@Override
public void onFailure(
Throwable caught) {
view.showError("An error occurred. Please try logging in again.");
}
@Override
public void onSuccess(
String result) {
// All setup complete
fireUserChange(userSessionData);
}
});
}
});
}
public void rejected() {
authenticationController.signTermsOfUse(false, new AsyncCallback<Void> () {
@Override
public void onFailure(Throwable caught) {
view.showError("An error occurred. Please try logging in again.");
}
@Override
public void onSuccess(Void result) {
authenticationController.logoutUser();
}
});
}
});
}
public void onFailure(Throwable t) {
view.showTermsOfUseDownloadFailed();
}
});
+ } else {
+ fireUserChange(userSessionData);
}
}
@Override
public void onFailure(Throwable caught) {
view.clear();
view.showAuthenticationFailed();
}
});
}
public void clear() {
view.clear();
}
// needed?
private void fireUserChange(UserSessionData user) {
for(UserListener listener: listeners){
listener.userChanged(user);
}
}
public void setOpenIdActionUrl(String url) {
this.openIdActionUrl = url;
}
public void setOpenIdReturnUrl(String url) {
this.openIdReturnUrl = url;
}
@Override
public String getOpenIdActionUrl() {
return openIdActionUrl;
}
@Override
public String getOpenIdReturnUrl() {
return openIdReturnUrl;
}
@Override
public void goTo(Place place) {
globalApplicationState.getPlaceChanger().goTo(place);
}
}
| true | true | public void setUsernameAndPassword(final String username, final String password) {
authenticationController.loginUser(username, password, new AsyncCallback<String>() {
@Override
public void onSuccess(String result) {
view.clear();
UserSessionData toBeParsed = null;
if (result != null){
try {
toBeParsed = nodeModelCreator.createJSONEntity(result, UserSessionData.class);
} catch (JSONObjectAdapterException e) {
onFailure(new UnknownErrorException(DisplayConstants.ERROR_INCOMPATIBLE_CLIENT_VERSION));
}
}
final UserSessionData userSessionData = toBeParsed;
if (!userSessionData.getSession().getAcceptsTermsOfUse()) {
authenticationController.getTermsOfUse(new AsyncCallback<String>() {
public void onSuccess(String termsOfUseContent) {
view.showTermsOfUse(termsOfUseContent,
new AcceptTermsOfUseCallback() {
public void accepted() {
authenticationController.signTermsOfUse(true, new AsyncCallback<Void> () {
@Override
public void onFailure(Throwable caught) {
view.showError("An error occurred. Please try logging in again.");
}
@Override
public void onSuccess(Void result) {
// Have to get the UserSessionData again,
// since it won't contain the UserProfile if the terms haven't been signed
authenticationController.loginUserSSO(userSessionData.getSession().getSessionToken(), new AsyncCallback<String>() {
@Override
public void onFailure(
Throwable caught) {
view.showError("An error occurred. Please try logging in again.");
}
@Override
public void onSuccess(
String result) {
// All setup complete
fireUserChange(userSessionData);
}
});
}
});
}
public void rejected() {
authenticationController.signTermsOfUse(false, new AsyncCallback<Void> () {
@Override
public void onFailure(Throwable caught) {
view.showError("An error occurred. Please try logging in again.");
}
@Override
public void onSuccess(Void result) {
authenticationController.logoutUser();
}
});
}
});
}
public void onFailure(Throwable t) {
view.showTermsOfUseDownloadFailed();
}
});
}
}
@Override
public void onFailure(Throwable caught) {
view.clear();
view.showAuthenticationFailed();
}
});
}
| public void setUsernameAndPassword(final String username, final String password) {
authenticationController.loginUser(username, password, new AsyncCallback<String>() {
@Override
public void onSuccess(String result) {
view.clear();
UserSessionData toBeParsed = null;
if (result != null){
try {
toBeParsed = nodeModelCreator.createJSONEntity(result, UserSessionData.class);
} catch (JSONObjectAdapterException e) {
onFailure(new UnknownErrorException(DisplayConstants.ERROR_INCOMPATIBLE_CLIENT_VERSION));
}
}
final UserSessionData userSessionData = toBeParsed;
if (!userSessionData.getSession().getAcceptsTermsOfUse()) {
authenticationController.getTermsOfUse(new AsyncCallback<String>() {
public void onSuccess(String termsOfUseContent) {
view.showTermsOfUse(termsOfUseContent,
new AcceptTermsOfUseCallback() {
public void accepted() {
authenticationController.signTermsOfUse(true, new AsyncCallback<Void> () {
@Override
public void onFailure(Throwable caught) {
view.showError("An error occurred. Please try logging in again.");
}
@Override
public void onSuccess(Void result) {
// Have to get the UserSessionData again,
// since it won't contain the UserProfile if the terms haven't been signed
authenticationController.loginUserSSO(userSessionData.getSession().getSessionToken(), new AsyncCallback<String>() {
@Override
public void onFailure(
Throwable caught) {
view.showError("An error occurred. Please try logging in again.");
}
@Override
public void onSuccess(
String result) {
// All setup complete
fireUserChange(userSessionData);
}
});
}
});
}
public void rejected() {
authenticationController.signTermsOfUse(false, new AsyncCallback<Void> () {
@Override
public void onFailure(Throwable caught) {
view.showError("An error occurred. Please try logging in again.");
}
@Override
public void onSuccess(Void result) {
authenticationController.logoutUser();
}
});
}
});
}
public void onFailure(Throwable t) {
view.showTermsOfUseDownloadFailed();
}
});
} else {
fireUserChange(userSessionData);
}
}
@Override
public void onFailure(Throwable caught) {
view.clear();
view.showAuthenticationFailed();
}
});
}
|
diff --git a/src/Menu/RosterItemActions.java b/src/Menu/RosterItemActions.java
index 584e0856..d5e72a70 100644
--- a/src/Menu/RosterItemActions.java
+++ b/src/Menu/RosterItemActions.java
@@ -1,670 +1,670 @@
/*
* RosterItemActions.java
*
* Created on 11.12.2005, 19:05
* Copyright (c) 2005-2008, Eugene Stahov (evgs), http://bombus-im.org
*
* 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.
*
* You can also redistribute and/or modify this program under the
* terms of the Psi License, specified in the accompanied COPYING
* file, as published by the Psi Project; either dated January 1st,
* 2005, 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 library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
package Menu;
import Client.Groups;
import Client.*;
import Colors.ColorTheme;
import Conference.ConferenceGroup;
import Conference.InviteForm;
import Conference.MucContact;
import Conference.QueryConfigForm;
import Conference.affiliation.Affiliations;
import Conference.affiliation.ConferenceQuickPrivelegeModify;
import ServiceDiscovery.ServiceDiscovery;
import VCard.VCard;
import VCard.VCardEdit;
import VCard.VCardView;
import com.alsutton.jabber.datablocks.Presence;
import images.RosterIcons;
//#ifdef FILE_TRANSFER
//#ifndef NOMMEDIA
//# import io.file.transfer.TransferImage;
//#endif
//# import io.file.transfer.TransferSendFile;
//#endif
import java.util.Enumeration;
import locale.SR;
import ui.controls.AlertBox;
import xmpp.JidUtils;
import xmpp.extensions.IqLast;
import xmpp.extensions.IqPing;
import xmpp.extensions.IqTimeReply;
import xmpp.extensions.IqVersionReply;
/**
*
* @author EvgS
*/
public class RosterItemActions extends Menu {
Object item;
RosterIcons menuIcons = RosterIcons.getInstance();
/**
* Creates a new instance of RosterItemActions
*
* @param item
* @param action
*/
public RosterItemActions(Object item) {
super(item.toString(), RosterIcons.getInstance());
this.item = item;
if (!sd.roster.isLoggedIn()) {
return;
}
if (item == null) {
return;
}
boolean isContact = (item instanceof Contact);
if (isContact) {
Contact contact = (Contact) item;
if (JidUtils.isTransport(contact.jid)) {
addItem(SR.MS_LOGON, 5, RosterIcons.ICON_ON);
addItem(SR.MS_LOGOFF, 6, RosterIcons.ICON_OFF);
addItem(SR.MS_RESOLVE_NICKNAMES, 7, RosterIcons.ICON_NICK_RESOLVE);
//#if CHANGE_TRANSPORT
//# addItem("Change transport", 915, RosterIcons.ICON_COMMAND);
//#endif
}
addItem(SR.MS_VCARD, 1, RosterIcons.ICON_VCARD);
//#ifdef POPUPS
//# addItem(SR.MS_INFO, 86, RosterIcons.ICON_INFO);
//#endif
//#ifdef STATUSES_WINDOW
//# addItem("Statuses", 87, RosterIcons.ICON_INFO);
//#endif
addItem(SR.MS_CLIENT_INFO, 0, RosterIcons.ICON_VERSION);
//#ifdef SERVICE_DISCOVERY
//# addItem(SR.MS_COMMANDS, 30, RosterIcons.ICON_COMMAND);
//#endif
//#ifdef CLIPBOARD
//# if (!sd.clipboard.isEmpty()) {
//# addItem(SR.MS_SEND_BUFFER, 914, RosterIcons.ICON_SEND_BUFFER);
//# }
//# addItem(SR.MS_COPY_JID, 892, RosterIcons.ICON_COPY_JID);
//#
//#endif
addItem(SR.MS_SEND_COLOR_SCHEME, 912, RosterIcons.ICON_SEND_COLORS);
if (contact.status < Presence.PRESENCE_OFFLINE) {
addItem(SR.MS_TIME, 891, RosterIcons.ICON_TIME);
addItem(SR.MS_IDLE, 889, RosterIcons.ICON_IDLE);
addItem(SR.MS_PING, 893, RosterIcons.ICON_PING);
}
if (contact.getGroupType() != Groups.TYPE_SELF && contact.getGroupType() != Groups.TYPE_SEARCH_RESULT && contact.origin < Contact.ORIGIN_GROUPCHAT) {
if (contact.status < Presence.PRESENCE_OFFLINE) {
addItem(SR.MS_ONLINE_TIME, 890, RosterIcons.ICON_ONLINE);
} else {
addItem(SR.MS_SEEN, 894, RosterIcons.ICON_ONLINE);
}
if (!JidUtils.isTransport(contact.jid)) {
addItem(SR.MS_EDIT, 2, RosterIcons.ICON_RENAME);
}
addItem(SR.MS_SUBSCRIPTION, 3, RosterIcons.ICON_SUBSCR);
// addItem(SR.MS_MOVE,1003, menuIcons.ICON_MOVE);
addItem(SR.MS_DELETE, 4, RosterIcons.ICON_DELETE);
addItem(SR.MS_DIRECT_PRESENCE, 45, RosterIcons.ICON_SET_STATUS);
}
if (contact.origin == Contact.ORIGIN_GROUPCHAT) {
return;
}
//#ifndef WMUC
boolean onlineConferences = false;
for (Enumeration cI = sd.roster.hContacts.elements(); cI.hasMoreElements();) {
try {
MucContact mcI = (MucContact) cI.nextElement();
if (mcI.origin == Contact.ORIGIN_GROUPCHAT && mcI.status == Presence.PRESENCE_ONLINE) {
onlineConferences = true;
}
} catch (Exception e) {
}
}
if (contact instanceof MucContact) {
MucContact selfContact = ((ConferenceGroup) contact.group).selfContact;
MucContact mc = (MucContact) contact;
//invite
if (mc.realJid != null) {
if (onlineConferences) {
addItem(SR.MS_INVITE, 40, RosterIcons.ICON_INVITE);
}
}
//invite
int myAffiliation = selfContact.affiliationCode;
if (myAffiliation == MucContact.AFFILIATION_OWNER) {
myAffiliation++; // allow owner to change owner's affiliation
}
//addItem(SR.MS_TIME,891);
if (selfContact.roleCode == MucContact.ROLE_MODERATOR) {
if (mc.roleCode < MucContact.ROLE_MODERATOR) {
addItem(SR.MS_KICK, 8, RosterIcons.ICON_KICK);
}
if (myAffiliation >= MucContact.AFFILIATION_ADMIN && mc.affiliationCode < myAffiliation) {
addItem(SR.MS_BAN, 9, RosterIcons.ICON_BAN);
}
if (mc.affiliationCode < MucContact.AFFILIATION_ADMIN) /*
* 5.1.1 *** A moderator MUST NOT be able to revoke voice
* privileges from an admin or owner.
*/ {
if (mc.roleCode == MucContact.ROLE_VISITOR) {
addItem(SR.MS_GRANT_VOICE, 31, RosterIcons.ICON_VOICE);
} else {
addItem(SR.MS_REVOKE_VOICE, 32, RosterIcons.ICON_DEVOICE);
}
}
}
//#ifdef REQUEST_VOICE
//# if (selfContact.roleCode==MucContact.ROLE_VISITOR) {
//# //System.out.println("im visitor");
//# if (mc.roleCode==MucContact.ROLE_MODERATOR) {
//# //System.out.println(mc.getJid()+" is a moderator");
//# addItem(SR.MS_REQUEST_PARTICIPANT_ROLE,39);
//# }
//# }
//#endif
if (myAffiliation >= MucContact.AFFILIATION_ADMIN) {
// admin use cases
//roles
if (mc.affiliationCode < MucContact.AFFILIATION_ADMIN) /*
* 5.2.1 ** An admin or owner MUST NOT be able to revoke
* moderation privileges from another admin or owner.
*/ {
if (mc.roleCode == MucContact.ROLE_MODERATOR) {
addItem(SR.MS_REVOKE_MODERATOR, 31, RosterIcons.ICON_MEMBER);
} else {
addItem(SR.MS_GRANT_MODERATOR, 33, RosterIcons.ICON_ADMIN);
}
}
//affiliations
if (mc.affiliationCode < myAffiliation) {
if (mc.affiliationCode != MucContact.AFFILIATION_NONE) {
addItem(SR.MS_UNAFFILIATE, 36, RosterIcons.ICON_DEMEMBER);
}
/*
* 5.2.2
*/
if (mc.affiliationCode != MucContact.AFFILIATION_MEMBER) {
addItem(SR.MS_GRANT_MEMBERSHIP, 35, RosterIcons.ICON_MEMBER);
}
}
//m.addItem(new MenuItem("Set Affiliation",15));
}
if (myAffiliation >= MucContact.AFFILIATION_OWNER) {
// owner use cases
if (mc.affiliationCode != MucContact.AFFILIATION_ADMIN) {
addItem(SR.MS_GRANT_ADMIN, 37, RosterIcons.ICON_ADMIN);
}
if (mc.affiliationCode != MucContact.AFFILIATION_OWNER) {
addItem(SR.MS_GRANT_OWNERSHIP, 38, RosterIcons.ICON_OWNER);
}
}
if (mc.realJid != null && mc.status < Presence.PRESENCE_OFFLINE) {
}
} else if (contact.getGroupType() != Groups.TYPE_TRANSP && contact.getGroupType() != Groups.TYPE_SEARCH_RESULT) {
// usual contact - invite item check
if (onlineConferences) {
addItem(SR.MS_INVITE, 40, RosterIcons.ICON_INVITE);
}
}
//#endif
//#if (FILE_IO && FILE_TRANSFER)
//# if (cf.fileTransfer) {
//# if (contact != sd.roster.selfContact()) {
//# addItem(SR.MS_SEND_FILE, 50, RosterIcons.ICON_SEND_FILE);
//# }
//# }
//#
//#endif
//#if FILE_TRANSFER
//# if (!JidUtils.isTransport(contact.jid) && cf.fileTransfer) {
//# if (contact != sd.roster.selfContact()) {
//# String cameraAvailable = System.getProperty("supports.video.capture");
//# if (cameraAvailable != null) {
//# if (cameraAvailable.startsWith("true")) {
//# addItem(SR.MS_SEND_PHOTO, 51, RosterIcons.ICON_SENDPHOTO);
//# }
//# }
//# }
//# }
//#endif
} else {
Group group = (Group) item;
if (group.type == Groups.TYPE_SEARCH_RESULT) {
addItem(SR.MS_DISCARD, 21, RosterIcons.ICON_BAN);
}
//#ifndef WMUC
if (group instanceof ConferenceGroup) {
MucContact self = ((ConferenceGroup) group).selfContact;
addItem(SR.MS_LEAVE_ROOM, 22, RosterIcons.ICON_LEAVE);
//#ifdef CLIPBOARD
//# addItem(SR.MS_COPY_JID, 892, RosterIcons.ICON_COPY_JID);
//# addItem(SR.MS_COPY_TOPIC, 993, RosterIcons.ICON_COPY_TOPIC);
//#
//#endif
if (self.status >= Presence.PRESENCE_OFFLINE) {// offline or error
addItem(SR.MS_REENTER, 23, RosterIcons.ICON_CHANGE_NICK);
} else {
addItem(SR.MS_DIRECT_PRESENCE, 46, RosterIcons.ICON_SET_STATUS);
addItem(SR.MS_CHANGE_NICKNAME, 23, RosterIcons.ICON_CHANGE_NICK);
if (self.affiliationCode >= MucContact.AFFILIATION_OWNER) {
addItem(SR.MS_CONFIG_ROOM, 10, RosterIcons.ICON_CONFIGURE);
}
if (self.affiliationCode >= MucContact.AFFILIATION_ADMIN) {
addItem(SR.MS_OWNERS, 11, RosterIcons.ICON_OWNERS);
addItem(SR.MS_ADMINS, 12, RosterIcons.ICON_ADMINS);
addItem(SR.MS_MEMBERS, 13, RosterIcons.ICON_MEMBERS);
addItem(SR.MS_BANNED, 14, RosterIcons.ICON_OUTCASTS);
}
addItem(SR.MS_COLLAPSE_ALL, 1005, RosterIcons.ICON_COMMAND);
}
} else {
//#endif
if (group.type != Groups.TYPE_IGNORE
&& group.type != Groups.TYPE_NOT_IN_LIST
&& group.type != Groups.TYPE_SEARCH_RESULT
&& group.type != Groups.TYPE_SELF
&& group.type != Groups.TYPE_TRANSP) {
addItem(SR.MS_RENAME, 1001, RosterIcons.ICON_RENAME);
addItem(SR.MS_DELETE, 1004, RosterIcons.ICON_DELETE);
addItem(SR.MS_COLLAPSE_ALL, 1005, RosterIcons.ICON_COMMAND);
}
//#ifndef WMUC
}
//#endif
}
if (getItemCount() > 0) {
show();
}
}
public void eventOk() {
try {
MenuItem me = (MenuItem) getFocusedObject();
destroyView();
if (me == null) {
return;
}
doAction(me.index);
} catch (Exception e) {
}
}
private void doAction(final int index) {
boolean isContact = (item instanceof Contact);
Contact c = null;
Group g = null;
if (isContact) {
c = (Contact) item;
} else {
g = (Group) item;
}
String to = null;
if (isContact) {
to = (index < 3) ? c.getJid().toString() : c.jid.getBare();
}
switch (index) {
case 0: // version
sd.roster.setQuerySign(true);
sd.theStream.send(IqVersionReply.query(to));
break;
case 86: // info
//#ifdef POPUPS
//# sd.roster.showInfo();
//#endif
break;
//#ifdef STATUSES_WINDOW
//# case 87:
//# new ContactStatusesList(c);
//# return;
//#endif
case 1: // vCard
if (c.vcard != null) {
if (c.getGroupType() == Groups.TYPE_SELF) {
new VCardEdit(c.vcard);
} else {
new VCardView(c);
}
return;
}
- VCard.request(c.jid.getBare(), c.getJid().toString());
+ VCard.request((c instanceof MucContact)? c.getJid().toString(): c.jid.getBare(), c.getJid().toString());
break;
case 2:
new ContactEdit(c);
return; //break;
case 3: //subscription
new SubscriptionEdit(c);
return; //break;
case 4:
new AlertBox(SR.MS_DELETE_ASK, c.getNickJid()) {
public void yes() {
sd.roster.deleteContact((Contact) item);
}
public void no() {
}
};
return;
case 6: // logoff
sd.roster.blockNotify(-111, 10000); //block sounds to 10 sec
Presence presence = new Presence(
Presence.PRESENCE_OFFLINE, -1, "", null);
presence.setTo(c.getJid().toString());
sd.theStream.send(presence);
break;
case 5: // logon
sd.roster.blockNotify(-111, 10000); //block sounds to 10 sec
//querysign=true; displayStatus();
Presence presence2 = new Presence(sd.roster.myStatus, 0, "", null);
presence2.setTo(c.getJid().toString());
sd.theStream.send(presence2);
break;
case 7: // Nick resolver
sd.roster.resolveNicknames(c.jid.getBare());
break;
//#if CHANGE_TRANSPORT
//# case 915: // change transport
//# new ChangeTransport(c.jid.getBare());
//# return;
//#endif
case 21:
sd.roster.cleanupSearch();
break;
//#ifdef SERVICE_DISCOVERY
//# case 30:
//# new ServiceDiscovery(c.getJid().toString(), "http://jabber.org/protocol/commands", false);
//# return;
//#endif
/*
* case 1003: new RenameGroup( null, c); return;
*/
case 889: //idle
sd.roster.setQuerySign(true);
sd.theStream.send(IqLast.query(c.getJid().toString(), "idle"));
break;
case 890: //online
sd.roster.setQuerySign(true);
sd.theStream.send(IqLast.query(c.jid.getBare(), "online_" + c.getResource()));
break;
case 894: //seen
sd.roster.setQuerySign(true);
sd.theStream.send(IqLast.query(c.jid.getBare(), "seen"));
break;
case 891: //time
sd.roster.setQuerySign(true);
sd.theStream.send(IqTimeReply.query(c.getJid().toString()));
break;
//#ifdef CLIPBOARD
//#ifndef WMUC
//# case 892: //Copy JID
//# String jid = null;
//# if (isContact) {
//# jid = c.getJid().toString();
//# } else {
//# jid = ((ConferenceGroup) g).jid.toString();
//# }
//#
//# if (jid != null) {
//# sd.clipboard.setClipBoard(jid);
//# }
//# break;
//# case 993:
//# String topic = ((ConferenceGroup) g).confContact.statusString;
//# if (topic != null) {
//# sd.clipboard.setClipBoard(topic);
//# }
//# break;
//#endif
//#endif
case 893: //ping
try {
sd.roster.setQuerySign(true);
//c.setPing();
sd.theStream.send(IqPing.query(c.getJid().toString(), null));
} catch (Exception e) {/*
* no messages
*/
}
break;
case 912: //send color scheme
String from = sd.account.toString();
//System.out.println(from);
String body = ColorTheme.getSkin();
//System.out.println(body);
String id = String.valueOf((int) System.currentTimeMillis());
try {
sd.roster.sendMessage(c, id, body, null, null);
c.addMessage(new Msg(Msg.MESSAGE_TYPE_OUT, from, null, "scheme sended"));
} catch (Exception e) {
c.addMessage(new Msg(Msg.MESSAGE_TYPE_OUT, from, null, "scheme NOT sended"));
//e.printStackTrace();
}
break;
//#ifdef CLIPBOARD
//# case 914: //send message from buffer
//# String body2 = sd.clipboard.getClipBoard();
//# if (body2.length() == 0) {
//# return;
//# }
//#
//# String from2 = sd.account.toString();
//#
//# String id2 = String.valueOf((int) System.currentTimeMillis());
//# Msg msg2 = new Msg(Msg.MESSAGE_TYPE_OUT, from2, null, body2);
//# msg2.id = id2;
//# msg2.itemCollapsed = true;
//#
//# try {
//# if (body2 != null && body2.length() > 0) {
//# sd.roster.sendMessage(c, id2, body2, null, null);
//#
//# if (c.origin < Contact.ORIGIN_GROUPCHAT) {
//# c.addMessage(msg2);
//# }
//# }
//# } catch (Exception e) {
//# c.addMessage(new Msg(Msg.MESSAGE_TYPE_OUT, from2, null, "clipboard NOT sended"));
//# }
//# break;
//#endif
//#ifndef WMUC
case 40: //invite
//new InviteForm(c, display);
if (c.jid != null) {
new InviteForm(c);
} else {
MucContact mcJ = (MucContact) c;
if (mcJ.realJid != null) {
boolean onlineConferences = false;
for (Enumeration cJ = sd.roster.hContacts.elements(); cJ.hasMoreElements();) {
try {
MucContact mcN = (MucContact) cJ.nextElement();
if (mcN.origin == Contact.ORIGIN_GROUPCHAT && mcN.status == Presence.PRESENCE_ONLINE) {
onlineConferences = true;
}
} catch (Exception e) {
}
}
if (onlineConferences) {
new InviteForm(mcJ);
}
}
}
return;
//#endif
case 45: //direct presence
new StatusSelect(c);
return;
//#if (FILE_IO && FILE_TRANSFER)
//# case 50: //send file
//# new TransferSendFile(c.getJid());
//# return;
//#endif
//#if FILE_TRANSFER
//#ifndef NOMMEDIA
//# case 51: //send photo
//# new TransferImage(c.getJid());
//# return;
//#endif
//#endif
}
//#ifndef WMUC
if (c instanceof MucContact || g instanceof ConferenceGroup) {
MucContact mc = (MucContact) c;
String roomJid = "";
if (g instanceof ConferenceGroup) {
roomJid = ((ConferenceGroup) g).confContact.getJid().toString();
}
String myNick = "";
if (c instanceof MucContact) {
myNick = ((ConferenceGroup) c.group).selfContact.getName();
}
switch (index) { // muc contact actions
case 10: // room config
new QueryConfigForm(roomJid);
break;
case 11: // owners
case 12: // admins
case 13: // members
case 14: // outcasts
new Affiliations(roomJid, (short) (index - 10));
return;
case 22:
sd.roster.leaveRoom(g);
break;
case 23:
sd.roster.reEnterRoom(g);
return; //break;
case 46: //conference presence
new StatusSelect(((ConferenceGroup) g).confContact);
return;
case 8: // kick
new ConferenceQuickPrivelegeModify(mc, ConferenceQuickPrivelegeModify.KICK, myNick);
return;
case 9: // ban
new ConferenceQuickPrivelegeModify(mc, ConferenceQuickPrivelegeModify.OUTCAST, myNick);
return;
case 31: //grant voice and revoke moderator
new ConferenceQuickPrivelegeModify(mc, ConferenceQuickPrivelegeModify.PARTICIPANT, null); //
return;
case 32: //revoke voice
new ConferenceQuickPrivelegeModify(mc, ConferenceQuickPrivelegeModify.VISITOR, null);
return;
case 33: //grant moderator
new ConferenceQuickPrivelegeModify(mc, ConferenceQuickPrivelegeModify.MODERATOR, null); //
return;
case 35: //grant membership and revoke admin
new ConferenceQuickPrivelegeModify(mc, ConferenceQuickPrivelegeModify.MEMBER, null); //
return;
case 36: //revoke membership
new ConferenceQuickPrivelegeModify(mc, ConferenceQuickPrivelegeModify.NONE, null); //
return;
case 37: //grant admin and revoke owner
new ConferenceQuickPrivelegeModify(mc, ConferenceQuickPrivelegeModify.ADMIN, null); //
return;
case 38: //grant owner
new ConferenceQuickPrivelegeModify(mc, ConferenceQuickPrivelegeModify.OWNER, null); //
return;
//#ifdef REQUEST_VOICE
//# case 39: //request voice
//# new QueryRequestVoice( sd.roster, mc, ConferenceQuickPrivelegeModify.PARTICIPANT);
//# return;
//#endif
//#ifdef CLIPBOARD
//# case 892: //Copy JID
//# try {
//# if (mc.realJid != null) {
//# sd.clipboard.setClipBoard(mc.realJid.toString());
//# }
//# } catch (Exception e) {
//# }
//# break;
//#endif
case 1005: //collapse
sd.roster.collapseAllGroup();
return;
}
} else {
//#endif
Group sg = (Group) item;
if (sg.type != Groups.TYPE_IGNORE
&& sg.type != Groups.TYPE_NOT_IN_LIST
&& sg.type != Groups.TYPE_SEARCH_RESULT
&& sg.type != Groups.TYPE_SELF
&& sg.type != Groups.TYPE_TRANSP) {
switch (index) {
case 1001: //rename
new RenameGroup(sg/*
* , null
*/);
return;
case 1004: //delete
new AlertBox(SR.MS_DELETE_GROUP_ASK, sg.name) {
public void yes() {
sd.roster.deleteGroup((Group) item);
}
public void no() {
}
};
return;
case 1005: //collapse
sd.roster.collapseAllGroup();
return;
}
}
//#ifndef WMUC
}
//#endif
}
}
| true | true | private void doAction(final int index) {
boolean isContact = (item instanceof Contact);
Contact c = null;
Group g = null;
if (isContact) {
c = (Contact) item;
} else {
g = (Group) item;
}
String to = null;
if (isContact) {
to = (index < 3) ? c.getJid().toString() : c.jid.getBare();
}
switch (index) {
case 0: // version
sd.roster.setQuerySign(true);
sd.theStream.send(IqVersionReply.query(to));
break;
case 86: // info
//#ifdef POPUPS
//# sd.roster.showInfo();
//#endif
break;
//#ifdef STATUSES_WINDOW
//# case 87:
//# new ContactStatusesList(c);
//# return;
//#endif
case 1: // vCard
if (c.vcard != null) {
if (c.getGroupType() == Groups.TYPE_SELF) {
new VCardEdit(c.vcard);
} else {
new VCardView(c);
}
return;
}
VCard.request(c.jid.getBare(), c.getJid().toString());
break;
case 2:
new ContactEdit(c);
return; //break;
case 3: //subscription
new SubscriptionEdit(c);
return; //break;
case 4:
new AlertBox(SR.MS_DELETE_ASK, c.getNickJid()) {
public void yes() {
sd.roster.deleteContact((Contact) item);
}
public void no() {
}
};
return;
case 6: // logoff
sd.roster.blockNotify(-111, 10000); //block sounds to 10 sec
Presence presence = new Presence(
Presence.PRESENCE_OFFLINE, -1, "", null);
presence.setTo(c.getJid().toString());
sd.theStream.send(presence);
break;
case 5: // logon
sd.roster.blockNotify(-111, 10000); //block sounds to 10 sec
//querysign=true; displayStatus();
Presence presence2 = new Presence(sd.roster.myStatus, 0, "", null);
presence2.setTo(c.getJid().toString());
sd.theStream.send(presence2);
break;
case 7: // Nick resolver
sd.roster.resolveNicknames(c.jid.getBare());
break;
//#if CHANGE_TRANSPORT
//# case 915: // change transport
//# new ChangeTransport(c.jid.getBare());
//# return;
//#endif
case 21:
sd.roster.cleanupSearch();
break;
//#ifdef SERVICE_DISCOVERY
//# case 30:
//# new ServiceDiscovery(c.getJid().toString(), "http://jabber.org/protocol/commands", false);
//# return;
//#endif
/*
* case 1003: new RenameGroup( null, c); return;
*/
case 889: //idle
sd.roster.setQuerySign(true);
sd.theStream.send(IqLast.query(c.getJid().toString(), "idle"));
break;
case 890: //online
sd.roster.setQuerySign(true);
sd.theStream.send(IqLast.query(c.jid.getBare(), "online_" + c.getResource()));
break;
case 894: //seen
sd.roster.setQuerySign(true);
sd.theStream.send(IqLast.query(c.jid.getBare(), "seen"));
break;
case 891: //time
sd.roster.setQuerySign(true);
sd.theStream.send(IqTimeReply.query(c.getJid().toString()));
break;
//#ifdef CLIPBOARD
//#ifndef WMUC
//# case 892: //Copy JID
//# String jid = null;
//# if (isContact) {
//# jid = c.getJid().toString();
//# } else {
//# jid = ((ConferenceGroup) g).jid.toString();
//# }
//#
//# if (jid != null) {
//# sd.clipboard.setClipBoard(jid);
//# }
//# break;
//# case 993:
//# String topic = ((ConferenceGroup) g).confContact.statusString;
//# if (topic != null) {
//# sd.clipboard.setClipBoard(topic);
//# }
//# break;
//#endif
//#endif
case 893: //ping
try {
sd.roster.setQuerySign(true);
//c.setPing();
sd.theStream.send(IqPing.query(c.getJid().toString(), null));
} catch (Exception e) {/*
* no messages
*/
}
break;
case 912: //send color scheme
String from = sd.account.toString();
//System.out.println(from);
String body = ColorTheme.getSkin();
//System.out.println(body);
String id = String.valueOf((int) System.currentTimeMillis());
try {
sd.roster.sendMessage(c, id, body, null, null);
c.addMessage(new Msg(Msg.MESSAGE_TYPE_OUT, from, null, "scheme sended"));
} catch (Exception e) {
c.addMessage(new Msg(Msg.MESSAGE_TYPE_OUT, from, null, "scheme NOT sended"));
//e.printStackTrace();
}
break;
//#ifdef CLIPBOARD
//# case 914: //send message from buffer
//# String body2 = sd.clipboard.getClipBoard();
//# if (body2.length() == 0) {
//# return;
//# }
//#
//# String from2 = sd.account.toString();
//#
//# String id2 = String.valueOf((int) System.currentTimeMillis());
//# Msg msg2 = new Msg(Msg.MESSAGE_TYPE_OUT, from2, null, body2);
//# msg2.id = id2;
//# msg2.itemCollapsed = true;
//#
//# try {
//# if (body2 != null && body2.length() > 0) {
//# sd.roster.sendMessage(c, id2, body2, null, null);
//#
//# if (c.origin < Contact.ORIGIN_GROUPCHAT) {
//# c.addMessage(msg2);
//# }
//# }
//# } catch (Exception e) {
//# c.addMessage(new Msg(Msg.MESSAGE_TYPE_OUT, from2, null, "clipboard NOT sended"));
//# }
//# break;
//#endif
//#ifndef WMUC
case 40: //invite
//new InviteForm(c, display);
if (c.jid != null) {
new InviteForm(c);
} else {
MucContact mcJ = (MucContact) c;
if (mcJ.realJid != null) {
boolean onlineConferences = false;
for (Enumeration cJ = sd.roster.hContacts.elements(); cJ.hasMoreElements();) {
try {
MucContact mcN = (MucContact) cJ.nextElement();
if (mcN.origin == Contact.ORIGIN_GROUPCHAT && mcN.status == Presence.PRESENCE_ONLINE) {
onlineConferences = true;
}
} catch (Exception e) {
}
}
if (onlineConferences) {
new InviteForm(mcJ);
}
}
}
return;
//#endif
case 45: //direct presence
new StatusSelect(c);
return;
//#if (FILE_IO && FILE_TRANSFER)
//# case 50: //send file
//# new TransferSendFile(c.getJid());
//# return;
//#endif
//#if FILE_TRANSFER
//#ifndef NOMMEDIA
//# case 51: //send photo
//# new TransferImage(c.getJid());
//# return;
//#endif
//#endif
}
//#ifndef WMUC
if (c instanceof MucContact || g instanceof ConferenceGroup) {
MucContact mc = (MucContact) c;
String roomJid = "";
if (g instanceof ConferenceGroup) {
roomJid = ((ConferenceGroup) g).confContact.getJid().toString();
}
String myNick = "";
if (c instanceof MucContact) {
myNick = ((ConferenceGroup) c.group).selfContact.getName();
}
switch (index) { // muc contact actions
case 10: // room config
new QueryConfigForm(roomJid);
break;
case 11: // owners
case 12: // admins
case 13: // members
case 14: // outcasts
new Affiliations(roomJid, (short) (index - 10));
return;
case 22:
sd.roster.leaveRoom(g);
break;
case 23:
sd.roster.reEnterRoom(g);
return; //break;
case 46: //conference presence
new StatusSelect(((ConferenceGroup) g).confContact);
return;
case 8: // kick
new ConferenceQuickPrivelegeModify(mc, ConferenceQuickPrivelegeModify.KICK, myNick);
return;
case 9: // ban
new ConferenceQuickPrivelegeModify(mc, ConferenceQuickPrivelegeModify.OUTCAST, myNick);
return;
case 31: //grant voice and revoke moderator
new ConferenceQuickPrivelegeModify(mc, ConferenceQuickPrivelegeModify.PARTICIPANT, null); //
return;
case 32: //revoke voice
new ConferenceQuickPrivelegeModify(mc, ConferenceQuickPrivelegeModify.VISITOR, null);
return;
case 33: //grant moderator
new ConferenceQuickPrivelegeModify(mc, ConferenceQuickPrivelegeModify.MODERATOR, null); //
return;
case 35: //grant membership and revoke admin
new ConferenceQuickPrivelegeModify(mc, ConferenceQuickPrivelegeModify.MEMBER, null); //
return;
case 36: //revoke membership
new ConferenceQuickPrivelegeModify(mc, ConferenceQuickPrivelegeModify.NONE, null); //
return;
case 37: //grant admin and revoke owner
new ConferenceQuickPrivelegeModify(mc, ConferenceQuickPrivelegeModify.ADMIN, null); //
return;
case 38: //grant owner
new ConferenceQuickPrivelegeModify(mc, ConferenceQuickPrivelegeModify.OWNER, null); //
return;
//#ifdef REQUEST_VOICE
//# case 39: //request voice
//# new QueryRequestVoice( sd.roster, mc, ConferenceQuickPrivelegeModify.PARTICIPANT);
//# return;
//#endif
//#ifdef CLIPBOARD
//# case 892: //Copy JID
//# try {
//# if (mc.realJid != null) {
//# sd.clipboard.setClipBoard(mc.realJid.toString());
//# }
//# } catch (Exception e) {
//# }
//# break;
//#endif
case 1005: //collapse
sd.roster.collapseAllGroup();
return;
}
} else {
//#endif
Group sg = (Group) item;
if (sg.type != Groups.TYPE_IGNORE
&& sg.type != Groups.TYPE_NOT_IN_LIST
&& sg.type != Groups.TYPE_SEARCH_RESULT
&& sg.type != Groups.TYPE_SELF
&& sg.type != Groups.TYPE_TRANSP) {
switch (index) {
case 1001: //rename
new RenameGroup(sg/*
* , null
*/);
return;
case 1004: //delete
new AlertBox(SR.MS_DELETE_GROUP_ASK, sg.name) {
public void yes() {
sd.roster.deleteGroup((Group) item);
}
public void no() {
}
};
return;
case 1005: //collapse
sd.roster.collapseAllGroup();
return;
}
}
//#ifndef WMUC
}
//#endif
}
| private void doAction(final int index) {
boolean isContact = (item instanceof Contact);
Contact c = null;
Group g = null;
if (isContact) {
c = (Contact) item;
} else {
g = (Group) item;
}
String to = null;
if (isContact) {
to = (index < 3) ? c.getJid().toString() : c.jid.getBare();
}
switch (index) {
case 0: // version
sd.roster.setQuerySign(true);
sd.theStream.send(IqVersionReply.query(to));
break;
case 86: // info
//#ifdef POPUPS
//# sd.roster.showInfo();
//#endif
break;
//#ifdef STATUSES_WINDOW
//# case 87:
//# new ContactStatusesList(c);
//# return;
//#endif
case 1: // vCard
if (c.vcard != null) {
if (c.getGroupType() == Groups.TYPE_SELF) {
new VCardEdit(c.vcard);
} else {
new VCardView(c);
}
return;
}
VCard.request((c instanceof MucContact)? c.getJid().toString(): c.jid.getBare(), c.getJid().toString());
break;
case 2:
new ContactEdit(c);
return; //break;
case 3: //subscription
new SubscriptionEdit(c);
return; //break;
case 4:
new AlertBox(SR.MS_DELETE_ASK, c.getNickJid()) {
public void yes() {
sd.roster.deleteContact((Contact) item);
}
public void no() {
}
};
return;
case 6: // logoff
sd.roster.blockNotify(-111, 10000); //block sounds to 10 sec
Presence presence = new Presence(
Presence.PRESENCE_OFFLINE, -1, "", null);
presence.setTo(c.getJid().toString());
sd.theStream.send(presence);
break;
case 5: // logon
sd.roster.blockNotify(-111, 10000); //block sounds to 10 sec
//querysign=true; displayStatus();
Presence presence2 = new Presence(sd.roster.myStatus, 0, "", null);
presence2.setTo(c.getJid().toString());
sd.theStream.send(presence2);
break;
case 7: // Nick resolver
sd.roster.resolveNicknames(c.jid.getBare());
break;
//#if CHANGE_TRANSPORT
//# case 915: // change transport
//# new ChangeTransport(c.jid.getBare());
//# return;
//#endif
case 21:
sd.roster.cleanupSearch();
break;
//#ifdef SERVICE_DISCOVERY
//# case 30:
//# new ServiceDiscovery(c.getJid().toString(), "http://jabber.org/protocol/commands", false);
//# return;
//#endif
/*
* case 1003: new RenameGroup( null, c); return;
*/
case 889: //idle
sd.roster.setQuerySign(true);
sd.theStream.send(IqLast.query(c.getJid().toString(), "idle"));
break;
case 890: //online
sd.roster.setQuerySign(true);
sd.theStream.send(IqLast.query(c.jid.getBare(), "online_" + c.getResource()));
break;
case 894: //seen
sd.roster.setQuerySign(true);
sd.theStream.send(IqLast.query(c.jid.getBare(), "seen"));
break;
case 891: //time
sd.roster.setQuerySign(true);
sd.theStream.send(IqTimeReply.query(c.getJid().toString()));
break;
//#ifdef CLIPBOARD
//#ifndef WMUC
//# case 892: //Copy JID
//# String jid = null;
//# if (isContact) {
//# jid = c.getJid().toString();
//# } else {
//# jid = ((ConferenceGroup) g).jid.toString();
//# }
//#
//# if (jid != null) {
//# sd.clipboard.setClipBoard(jid);
//# }
//# break;
//# case 993:
//# String topic = ((ConferenceGroup) g).confContact.statusString;
//# if (topic != null) {
//# sd.clipboard.setClipBoard(topic);
//# }
//# break;
//#endif
//#endif
case 893: //ping
try {
sd.roster.setQuerySign(true);
//c.setPing();
sd.theStream.send(IqPing.query(c.getJid().toString(), null));
} catch (Exception e) {/*
* no messages
*/
}
break;
case 912: //send color scheme
String from = sd.account.toString();
//System.out.println(from);
String body = ColorTheme.getSkin();
//System.out.println(body);
String id = String.valueOf((int) System.currentTimeMillis());
try {
sd.roster.sendMessage(c, id, body, null, null);
c.addMessage(new Msg(Msg.MESSAGE_TYPE_OUT, from, null, "scheme sended"));
} catch (Exception e) {
c.addMessage(new Msg(Msg.MESSAGE_TYPE_OUT, from, null, "scheme NOT sended"));
//e.printStackTrace();
}
break;
//#ifdef CLIPBOARD
//# case 914: //send message from buffer
//# String body2 = sd.clipboard.getClipBoard();
//# if (body2.length() == 0) {
//# return;
//# }
//#
//# String from2 = sd.account.toString();
//#
//# String id2 = String.valueOf((int) System.currentTimeMillis());
//# Msg msg2 = new Msg(Msg.MESSAGE_TYPE_OUT, from2, null, body2);
//# msg2.id = id2;
//# msg2.itemCollapsed = true;
//#
//# try {
//# if (body2 != null && body2.length() > 0) {
//# sd.roster.sendMessage(c, id2, body2, null, null);
//#
//# if (c.origin < Contact.ORIGIN_GROUPCHAT) {
//# c.addMessage(msg2);
//# }
//# }
//# } catch (Exception e) {
//# c.addMessage(new Msg(Msg.MESSAGE_TYPE_OUT, from2, null, "clipboard NOT sended"));
//# }
//# break;
//#endif
//#ifndef WMUC
case 40: //invite
//new InviteForm(c, display);
if (c.jid != null) {
new InviteForm(c);
} else {
MucContact mcJ = (MucContact) c;
if (mcJ.realJid != null) {
boolean onlineConferences = false;
for (Enumeration cJ = sd.roster.hContacts.elements(); cJ.hasMoreElements();) {
try {
MucContact mcN = (MucContact) cJ.nextElement();
if (mcN.origin == Contact.ORIGIN_GROUPCHAT && mcN.status == Presence.PRESENCE_ONLINE) {
onlineConferences = true;
}
} catch (Exception e) {
}
}
if (onlineConferences) {
new InviteForm(mcJ);
}
}
}
return;
//#endif
case 45: //direct presence
new StatusSelect(c);
return;
//#if (FILE_IO && FILE_TRANSFER)
//# case 50: //send file
//# new TransferSendFile(c.getJid());
//# return;
//#endif
//#if FILE_TRANSFER
//#ifndef NOMMEDIA
//# case 51: //send photo
//# new TransferImage(c.getJid());
//# return;
//#endif
//#endif
}
//#ifndef WMUC
if (c instanceof MucContact || g instanceof ConferenceGroup) {
MucContact mc = (MucContact) c;
String roomJid = "";
if (g instanceof ConferenceGroup) {
roomJid = ((ConferenceGroup) g).confContact.getJid().toString();
}
String myNick = "";
if (c instanceof MucContact) {
myNick = ((ConferenceGroup) c.group).selfContact.getName();
}
switch (index) { // muc contact actions
case 10: // room config
new QueryConfigForm(roomJid);
break;
case 11: // owners
case 12: // admins
case 13: // members
case 14: // outcasts
new Affiliations(roomJid, (short) (index - 10));
return;
case 22:
sd.roster.leaveRoom(g);
break;
case 23:
sd.roster.reEnterRoom(g);
return; //break;
case 46: //conference presence
new StatusSelect(((ConferenceGroup) g).confContact);
return;
case 8: // kick
new ConferenceQuickPrivelegeModify(mc, ConferenceQuickPrivelegeModify.KICK, myNick);
return;
case 9: // ban
new ConferenceQuickPrivelegeModify(mc, ConferenceQuickPrivelegeModify.OUTCAST, myNick);
return;
case 31: //grant voice and revoke moderator
new ConferenceQuickPrivelegeModify(mc, ConferenceQuickPrivelegeModify.PARTICIPANT, null); //
return;
case 32: //revoke voice
new ConferenceQuickPrivelegeModify(mc, ConferenceQuickPrivelegeModify.VISITOR, null);
return;
case 33: //grant moderator
new ConferenceQuickPrivelegeModify(mc, ConferenceQuickPrivelegeModify.MODERATOR, null); //
return;
case 35: //grant membership and revoke admin
new ConferenceQuickPrivelegeModify(mc, ConferenceQuickPrivelegeModify.MEMBER, null); //
return;
case 36: //revoke membership
new ConferenceQuickPrivelegeModify(mc, ConferenceQuickPrivelegeModify.NONE, null); //
return;
case 37: //grant admin and revoke owner
new ConferenceQuickPrivelegeModify(mc, ConferenceQuickPrivelegeModify.ADMIN, null); //
return;
case 38: //grant owner
new ConferenceQuickPrivelegeModify(mc, ConferenceQuickPrivelegeModify.OWNER, null); //
return;
//#ifdef REQUEST_VOICE
//# case 39: //request voice
//# new QueryRequestVoice( sd.roster, mc, ConferenceQuickPrivelegeModify.PARTICIPANT);
//# return;
//#endif
//#ifdef CLIPBOARD
//# case 892: //Copy JID
//# try {
//# if (mc.realJid != null) {
//# sd.clipboard.setClipBoard(mc.realJid.toString());
//# }
//# } catch (Exception e) {
//# }
//# break;
//#endif
case 1005: //collapse
sd.roster.collapseAllGroup();
return;
}
} else {
//#endif
Group sg = (Group) item;
if (sg.type != Groups.TYPE_IGNORE
&& sg.type != Groups.TYPE_NOT_IN_LIST
&& sg.type != Groups.TYPE_SEARCH_RESULT
&& sg.type != Groups.TYPE_SELF
&& sg.type != Groups.TYPE_TRANSP) {
switch (index) {
case 1001: //rename
new RenameGroup(sg/*
* , null
*/);
return;
case 1004: //delete
new AlertBox(SR.MS_DELETE_GROUP_ASK, sg.name) {
public void yes() {
sd.roster.deleteGroup((Group) item);
}
public void no() {
}
};
return;
case 1005: //collapse
sd.roster.collapseAllGroup();
return;
}
}
//#ifndef WMUC
}
//#endif
}
|
diff --git a/src/org/netbeans/modules/php/fuel/modules/FuelPhpModuleImpl.java b/src/org/netbeans/modules/php/fuel/modules/FuelPhpModuleImpl.java
index 57e4051..562736f 100644
--- a/src/org/netbeans/modules/php/fuel/modules/FuelPhpModuleImpl.java
+++ b/src/org/netbeans/modules/php/fuel/modules/FuelPhpModuleImpl.java
@@ -1,254 +1,254 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2013 Oracle and/or its affiliates. All rights reserved.
*
* Oracle and Java are registered trademarks of Oracle and/or its affiliates.
* Other names may be trademarks of their respective owners.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*
* Contributor(s):
*
* Portions Copyrighted 2013 Sun Microsystems, Inc.
*/
package org.netbeans.modules.php.fuel.modules;
import java.io.File;
import java.io.IOException;
import org.netbeans.modules.php.api.phpmodule.PhpModule;
import org.netbeans.modules.php.api.util.StringUtils;
import org.netbeans.modules.php.fuel.modules.FuelPhpModule.DIR_TYPE;
import org.netbeans.modules.php.fuel.modules.FuelPhpModule.FILE_TYPE;
import org.netbeans.modules.php.fuel.preferences.FuelPhpPreferences;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
/**
*
* @author junichi11
*/
public abstract class FuelPhpModuleImpl {
protected PhpModule phpModule;
public FuelPhpModuleImpl(PhpModule phpModule) {
this.phpModule = phpModule;
}
/**
* Get specific directory for directory type.
*
* @param dirType
* @return directory
*/
public abstract FileObject getDirectory(FuelPhpModule.DIR_TYPE dirType);
/**
* Get directory for directory type, file type, and module, package name.
*
* @param dirType directory type
* @param fileType file type
* @param dirName module or package name
* @return directory
*/
public abstract FileObject getDirectory(FuelPhpModule.DIR_TYPE dirType, FuelPhpModule.FILE_TYPE fileType, String dirName);
/**
* Get specific directory for current file.
*
* @param currentFile target file
* @param fileType file type
* @return directory
*/
public abstract FileObject getDirectory(FileObject currentFile, FuelPhpModule.FILE_TYPE fileType);
/**
* Check whether target file is in app directory.
*
* @param currentFile target file
* @return true if the file is in app, otherwise false.
*/
public abstract boolean isInApp(FileObject currentFile);
/**
* Check whether target file is in core directory.
*
* @param currentFile target file
* @return true if the file is in core, otherwise false.
*/
public abstract boolean isInCore(FileObject currentFile);
/**
* Check whether target file is in moodules directory.
*
* @param currentFile target file
* @return true if the file is in modules, otherwise false.
*/
public abstract boolean isInModules(FileObject currentFile);
/**
* Check whether target file is in packages directory.
*
* @param currentFile target file
* @return true if the file is in packages, otherwise false.
*/
public abstract boolean isInPackages(FileObject currentFile);
/**
* Check whether target file is in public directory.
*
* @param currentFile target file
* @return true if the file is in public, otherwise false.
*/
public abstract boolean isInPublic(FileObject currentFile);
/**
* Get DIR_TYPE for target file.
*
* @param currentFile target file
* @return DIR_TYPE
*/
public abstract DIR_TYPE getDirType(FileObject currentFile);
/**
* Get FILE_TYPE for target file.
*
* @param currentFile target file
* @return FILE_TYPE
*/
public abstract FILE_TYPE getFileType(FileObject currentFile);
/**
* Get fuel directory name (default is fuel).
*
* @return fuel directory name.
*/
public String getFuelDirectoryName() {
if (phpModule == null) {
return ""; // NOI18N
}
return FuelPhpPreferences.getFuelName(phpModule);
}
/**
* Get module name.
*
* @param fileObject
* @return module name if module exists, otherwise empty string.
*/
public String getModuelName(FileObject fileObject) {
if (!isInModules(fileObject)) {
return ""; // NOI18N
}
String path = getPath(fileObject);
if (path.isEmpty()) {
return ""; // NOI18N
}
path = path.replaceAll(".+/modules/", ""); // NOI18N
int indexOfSlash = path.indexOf("/"); // NOI18N
if (indexOfSlash == -1) {
return ""; // NOI18N
}
return path.substring(0, indexOfSlash); // NOI18N
}
/**
* Get package name.
*
* @param fileObject
* @return module name if package exists, otherwise empty string.
*/
public String getPackageName(FileObject fileObject) {
if (!isInPackages(fileObject)) {
return ""; // NOI18N
}
String path = getPath(fileObject);
if (path.isEmpty()) {
return ""; // NOI18N
}
path = path.replaceAll(".+/packages/", ""); // NOI18N
int indexOfSlash = path.indexOf("/"); // NOI18N
if (indexOfSlash == -1) {
return ""; // NOI18N
}
return path.substring(0, indexOfSlash); // NOI18N
}
/**
* Get source directory path.
*
* @return
*/
public String getSourceDirectoryPath() {
FileObject sourceDirectory = phpModule.getSourceDirectory();
if (sourceDirectory == null) {
return ""; // NOI18N
}
return sourceDirectory.getPath();
}
/**
* Get file path.
*
* @param currentFile
* @return
*/
public String getPath(FileObject currentFile) {
if (currentFile == null) {
return ""; // NOI18N
}
return currentFile.getPath();
}
/**
* Create a new file.
*
* @param baseDirectory base directory
* @param path path from base directory
* @return true if a file is created, otherwise false.
*/
public boolean createNewFile(FileObject baseDirectory, String path) throws IOException {
if (baseDirectory == null || StringUtils.isEmpty(path)) {
return false;
}
File baseDir = FileUtil.toFile(baseDirectory);
File targetFile = new File(baseDir, path);
if (targetFile.exists()) {
return false;
}
File parentFile = targetFile.getParentFile();
- if (parentFile.exists() && parentFile.isDirectory()) {
+ if (!parentFile.exists()) {
// mkdirs
parentFile.mkdirs();
}
return targetFile.createNewFile();
}
}
| true | true | public boolean createNewFile(FileObject baseDirectory, String path) throws IOException {
if (baseDirectory == null || StringUtils.isEmpty(path)) {
return false;
}
File baseDir = FileUtil.toFile(baseDirectory);
File targetFile = new File(baseDir, path);
if (targetFile.exists()) {
return false;
}
File parentFile = targetFile.getParentFile();
if (parentFile.exists() && parentFile.isDirectory()) {
// mkdirs
parentFile.mkdirs();
}
return targetFile.createNewFile();
}
| public boolean createNewFile(FileObject baseDirectory, String path) throws IOException {
if (baseDirectory == null || StringUtils.isEmpty(path)) {
return false;
}
File baseDir = FileUtil.toFile(baseDirectory);
File targetFile = new File(baseDir, path);
if (targetFile.exists()) {
return false;
}
File parentFile = targetFile.getParentFile();
if (!parentFile.exists()) {
// mkdirs
parentFile.mkdirs();
}
return targetFile.createNewFile();
}
|
diff --git a/us7638/sapisync/src/main/java/com/funambol/sapisync/SapiSyncManager.java b/us7638/sapisync/src/main/java/com/funambol/sapisync/SapiSyncManager.java
index 77b18bc5..4a27712f 100755
--- a/us7638/sapisync/src/main/java/com/funambol/sapisync/SapiSyncManager.java
+++ b/us7638/sapisync/src/main/java/com/funambol/sapisync/SapiSyncManager.java
@@ -1,815 +1,815 @@
/*
* Funambol is a mobile platform developed by Funambol, Inc.
* Copyright (C) 2003 - 2007 Funambol, Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by
* the Free Software Foundation with the addition of the following permission
* added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
* WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE
* WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* 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 Affero General Public License
* along with this program; if not, see http://www.gnu.org/licenses or write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA.
*
* You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite
* 305, Redwood City, CA 94063, USA, or at email address [email protected].
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License
* version 3, these Appropriate Legal Notices must retain the display of the
* "Powered by Funambol" logo. If the display of the logo is not reasonably
* feasible for technical reasons, the Appropriate Legal Notices must display
* the words "Powered by Funambol".
*/
package com.funambol.sapisync;
import java.util.Vector;
import java.util.Date;
import java.io.OutputStream;
import java.io.IOException;
import org.json.me.JSONException;
import org.json.me.JSONObject;
import org.json.me.JSONArray;
import com.funambol.sync.BasicSyncListener;
import com.funambol.sync.ItemStatus;
import com.funambol.sync.SyncAnchor;
import com.funambol.sync.SyncConfig;
import com.funambol.sync.SyncException;
import com.funambol.sync.SyncItem;
import com.funambol.sync.SyncListener;
import com.funambol.sync.SyncSource;
import com.funambol.sync.SyncManagerI;
import com.funambol.sync.TwinDetectionSource;
import com.funambol.sapisync.source.JSONSyncSource;
import com.funambol.storage.StringKeyValueStoreFactory;
import com.funambol.storage.StringKeyValueStore;
import com.funambol.sync.ItemDownloadInterruptionException;
import com.funambol.sync.Filter;
import com.funambol.sync.SyncFilter;
import com.funambol.util.Log;
import com.funambol.util.StringUtil;
/**
* <code>SapiSyncManager</code> represents the synchronization engine performed
* via SAPI.
*/
public class SapiSyncManager implements SyncManagerI {
private static final String TAG_LOG = "SapiSyncManager";
private static final int MAX_ITEMS_PER_BLOCK = 100;
private static final int FULL_SYNC_DOWNLOAD_LIMIT = 300;
private SyncConfig syncConfig = null;
private SapiSyncHandler sapiSyncHandler = null;
private SapiSyncStatus syncStatus = null;
/**
* Unique instance of a BasicSyncListener which is used when the user does
* not set up a listener in the SyncSource. In order to avoid the creation
* of multiple instances of this class we use this static variable
*/
private static SyncListener basicListener = null;
/**
* <code>SapiSyncManager</code> constructor
* @param config
*/
public SapiSyncManager(SyncConfig config) {
this.syncConfig = config;
this.sapiSyncHandler = new SapiSyncHandler(
StringUtil.extractAddressFromUrl(syncConfig.getSyncUrl()),
syncConfig.getUserName(),
syncConfig.getPassword());
}
/**
* Force a specific SapiSyncHandler to be used for testing purposes.
* @param sapiSyncHandler
*/
public void setSapiSyncHandler(SapiSyncHandler sapiSyncHandler) {
this.sapiSyncHandler = sapiSyncHandler;
}
/**
* Synchronizes the given source, using the preferred sync mode defined for
* that SyncSource.
*
* @param source the SyncSource to synchronize
*
* @throws SyncException If an error occurs during synchronization
*
*/
public void sync(SyncSource source) throws SyncException {
sync(source, source.getSyncMode(), false);
}
public void sync(SyncSource source, boolean askServerDevInf) throws SyncException {
sync(source, source.getSyncMode(), askServerDevInf);
}
public void sync(SyncSource src, int syncMode) {
sync(src, syncMode, false);
}
/**
* Synchronizes the given source, using the given sync mode.
*
* @param source the SyncSource to synchronize
* @param syncMode the sync mode
* @param askServerDevInf true if the engine shall ask for server caps
*
* @throws SyncException If an error occurs during synchronization
*/
public synchronized void sync(SyncSource src, int syncMode, boolean askServerDevInf)
throws SyncException {
if (Log.isLoggable(Log.DEBUG)) {
Log.debug(TAG_LOG, "Starting sync");
}
if (basicListener == null) {
basicListener = new BasicSyncListener();
}
// JSONSyncSource require an updated sync config, therefore we update it
// at the beginning of each sync
if (src instanceof JSONSyncSource) {
JSONSyncSource jsonSyncSource = (JSONSyncSource)src;
jsonSyncSource.updateSyncConfig(syncConfig);
}
// TODO FIXME: check if resume is needed
boolean resume = false;
syncStatus = new SapiSyncStatus(src.getName());
try {
syncStatus.load();
} catch (Exception e) {
if (Log.isLoggable(Log.INFO)) {
Log.info(TAG_LOG, "Cannot load sync status, use an empty one");
}
}
// If we are not resuming, then we can reset the status
if (!resume) {
try {
syncStatus.reset();
} catch (IOException ioe) {
Log.error(TAG_LOG, "Cannot reset status", ioe);
}
}
try {
// Set the basic properties in the sync status
syncStatus.setRemoteUri(src.getConfig().getRemoteUri());
syncStatus.setInterrupted(true);
syncStatus.setLocUri(src.getName());
syncStatus.setRequestedSyncMode(syncMode);
syncStatus.setStartTime(System.currentTimeMillis());
syncStatus.save();
getSyncListenerFromSource(src).startSession();
getSyncListenerFromSource(src).startConnecting();
performInitializationPhase(src, getActualSyncMode(src, syncMode), resume);
getSyncListenerFromSource(src).syncStarted(getActualSyncMode(src, syncMode));
if(isDownloadPhaseNeeded(syncMode)) {
// Get ready to update the download anchor
performDownloadPhase(src, getActualDownloadSyncMode(src), resume);
}
/*
if(isUploadPhaseNeeded(syncMode)) {
long newUploadAnchor = (new Date()).getTime();
performUploadPhase(src, getActualUploadSyncMode(src), resume);
// If we had no error so far, then we update the anchor
SapiSyncAnchor anchor = (SapiSyncAnchor)src.getSyncAnchor();
anchor.setUploadAnchor(newUploadAnchor);
}
*/
performFinalizationPhase(src);
syncStatus.setInterrupted(false);
syncStatus.setStatusCode(SyncListener.SUCCESS);
} catch (Throwable t) {
Log.error(TAG_LOG, "Error while synchronizing", t);
syncStatus.setSyncException(t);
SyncException se;
if (t instanceof SyncException) {
se = (SyncException)t;
} else {
se = new SyncException(SyncException.CLIENT_ERROR, "Generic error");
}
throw se;
} finally {
syncStatus.setEndTime(System.currentTimeMillis());
try {
syncStatus.save();
} catch (IOException ioe) {
Log.error(TAG_LOG, "Cannot save sync status", ioe);
}
// We must guarantee this method is invoked in all cases
getSyncListenerFromSource(src).endSession(syncStatus);
}
}
public void cancel() {
// TODO FIXME
performFinalizationPhase(null);
}
private void performInitializationPhase(SyncSource src, int syncMode,
boolean resume) {
src.beginSync(syncMode, resume);
sapiSyncHandler.login();
}
private void performUploadPhase(SyncSource src, int syncMode, boolean resume) {
Vector sourceStatus = new Vector();
boolean incremental = isIncrementalSync(syncMode);
int uploadedCount = 0;
SyncItem item = getNextItemToUpload(src, incremental, uploadedCount);
while(item != null) {
try {
// Upload the item to the server
sapiSyncHandler.uploadItem(item, getSyncListenerFromSource(src));
// Set the item status
sourceStatus.addElement(new ItemStatus(item.getKey(),
SyncSource.SUCCESS_STATUS));
} catch(Exception ex) {
if(Log.isLoggable(Log.ERROR)) {
Log.error(TAG_LOG, "Failed to upload item with key: " +
item.getKey(), ex);
}
sourceStatus.addElement(new ItemStatus(item.getKey(),
SyncSource.STATUS_SEND_ERROR));
}
uploadedCount++;
item = getNextItemToUpload(src, incremental, uploadedCount);
}
src.applyItemsStatus(sourceStatus);
}
private SyncItem getNextItemToUpload(SyncSource src, boolean incremental,
int uploadedCount) {
SyncItem nextItem = getNextItem(src, incremental);
SyncFilter syncFilter = src.getFilter();
if(syncFilter != null) {
Filter filter = incremental ? syncFilter.getIncrementalUploadFilter() :
syncFilter.getFullUploadFilter();
if(filter != null) {
if(filter.getType() == Filter.ITEMS_COUNT_TYPE) {
if(uploadedCount >= filter.getCount()) {
// No further items shall be uploaded
nextItem = null;
}
} else {
throw new UnsupportedOperationException("Not supported yet.");
}
}
}
return nextItem;
}
private SyncItem getNextItem(SyncSource src, boolean incremental) {
if(incremental) {
SyncItem next = src.getNextNewItem();
if(next == null) {
next = src.getNextUpdatedItem();
}
return next;
} else {
return src.getNextItem();
}
}
private void performDownloadPhase(SyncSource src, int syncMode,
boolean resume) throws SyncException {
if (Log.isLoggable(Log.INFO)) {
Log.info(TAG_LOG, "Starting download phase " + syncMode);
}
StringKeyValueStoreFactory mappingFactory =
StringKeyValueStoreFactory.getInstance();
StringKeyValueStore mapping = mappingFactory.getStringKeyValueStore(
"mapping_" + src.getName());
try {
mapping.load();
} catch (Exception e) {
if (Log.isLoggable(Log.INFO)) {
Log.info(TAG_LOG, "The mapping store does not exist, use an empty one");
}
}
String remoteUri = src.getConfig().getRemoteUri();
SyncFilter syncFilter = src.getFilter();
if (syncMode == SyncSource.FULL_DOWNLOAD) {
int totalCount = -1;
int filterMaxCount = -1;
Date filterFrom = null;
Filter fullDownloadFilter = null;
if(syncFilter != null) {
fullDownloadFilter = syncFilter.getFullDownloadFilter();
}
if(fullDownloadFilter != null) {
if(fullDownloadFilter != null && fullDownloadFilter.getType()
== Filter.ITEMS_COUNT_TYPE) {
filterMaxCount = fullDownloadFilter.getCount();
} else if(fullDownloadFilter != null && fullDownloadFilter.getType()
== Filter.DATE_RECENT_TYPE) {
filterFrom = new Date(fullDownloadFilter.getDate());
} else {
throw new UnsupportedOperationException("Not implemented yet");
}
}
// Get the number of items and notify the listener
try {
totalCount = sapiSyncHandler.getItemsCount(remoteUri, filterFrom);
if (totalCount != -1) {
- if(filterMaxCount > 0) {
+ if(filterMaxCount > 0 && filterMaxCount < totalCount) {
getSyncListenerFromSource(src).startReceiving(filterMaxCount);
} else {
getSyncListenerFromSource(src).startReceiving(totalCount);
}
}
} catch (Exception e) {
Log.error(TAG_LOG, "Cannot get the number of items on server", e);
// We ignore this exception and try to get the content
}
int downloadLimit = FULL_SYNC_DOWNLOAD_LIMIT;
String dataTag = getDataTag(src);
int offset = 0;
boolean done = false;
try {
long newDownloadAnchor = -1;
do {
// Update the download limit given the total amount of items
// to download
if((offset + downloadLimit) > totalCount) {
downloadLimit = totalCount - offset;
}
SapiSyncHandler.FullSet fullSet = sapiSyncHandler.getItems(remoteUri, dataTag, null,
Integer.toString(downloadLimit),
Integer.toString(offset), filterFrom);
if (newDownloadAnchor == -1) {
newDownloadAnchor = fullSet.timeStamp;
}
if (fullSet != null && fullSet.items != null && fullSet.items.length() > 0) {
if (Log.isLoggable(Log.TRACE)) {
Log.trace(TAG_LOG, "items = " + fullSet.items.toString());
}
done = applyNewUpdToSyncSource(src, fullSet.items, SyncItem.STATE_NEW,
filterMaxCount, offset, mapping, true);
offset += fullSet.items.length();
if ((fullSet.items.length() < FULL_SYNC_DOWNLOAD_LIMIT)) {
done = true;
}
} else {
done = true;
}
} while(!done);
// Update the download anchor
SapiSyncAnchor sapiAnchor = (SapiSyncAnchor)src.getConfig().getSyncAnchor();
if (Log.isLoggable(Log.TRACE)) {
Log.trace(TAG_LOG, "Updating download anchor to " + newDownloadAnchor);
}
sapiAnchor.setDownloadAnchor(newDownloadAnchor);
} catch (JSONException je) {
Log.error(TAG_LOG, "Cannot parse server data", je);
} catch (ItemDownloadInterruptionException ide) {
// An item could not be downloaded
if (Log.isLoggable(Log.INFO)) {
Log.info(TAG_LOG, "");
}
// TODO FIXME: handle the suspend/resume
}
} else if (syncMode == SyncSource.INCREMENTAL_DOWNLOAD) {
if (Log.isLoggable(Log.TRACE)) {
Log.trace(TAG_LOG, "Performing incremental download");
}
if(syncFilter != null && syncFilter.getIncrementalDownloadFilter() != null) {
throw new UnsupportedOperationException("Not implemented yet");
}
SapiSyncAnchor sapiAnchor = (SapiSyncAnchor)src.getConfig().getSyncAnchor();
if (Log.isLoggable(Log.TRACE)) {
Log.trace(TAG_LOG, "Last download anchor is: " + sapiAnchor.getDownloadAnchor());
}
Date anchor = new Date(sapiAnchor.getDownloadAnchor());
try {
SapiSyncHandler.ChangesSet changesSet =
sapiSyncHandler.getIncrementalChanges(anchor, remoteUri);
if (changesSet != null) {
// Count the number of items to be received and notify the
// listener
int total = 0;
if (changesSet.added != null) {
total += changesSet.added.length();
}
if (changesSet.updated != null) {
total += changesSet.updated.length();
}
if (changesSet.deleted != null) {
total += changesSet.deleted.length();
}
getSyncListenerFromSource(src).startReceiving(total);
// We must pass all of the items to the sync source, but for each
// item we need to retrieve the complete information
if (changesSet.added != null) {
applyNewUpdItems(src, changesSet.added,
SyncItem.STATE_NEW, mapping);
}
if (changesSet.updated != null) {
applyNewUpdItems(src, changesSet.updated,
SyncItem.STATE_UPDATED, mapping);
}
if (changesSet.deleted != null) {
applyDelItems(src, changesSet.deleted, mapping);
}
// Update the anchor if everything went well
if (changesSet.timeStamp != -1) {
if (Log.isLoggable(Log.TRACE)) {
Log.trace(TAG_LOG, "Updating download anchor to " + changesSet.timeStamp);
}
sapiAnchor.setDownloadAnchor(changesSet.timeStamp);
}
}
} catch (JSONException je) {
Log.error(TAG_LOG, "Cannot apply changes", je);
}
}
try {
mapping.save();
} catch (Exception e) {
Log.error(TAG_LOG, "Cannot save mapping store", e);
}
}
private void applyNewUpdItems(SyncSource src, JSONArray added, char state,
StringKeyValueStore mapping) throws SyncException, JSONException {
// The JSONArray contains the "id" of the new items, we still need to
// download their complete meta information. We get the new items in
// pages to make sure we don't use too much memory. Each page of items
// is then passed to the sync source
if (Log.isLoggable(Log.TRACE)) {
Log.trace(TAG_LOG, "apply new update items " + state);
}
int i = 0;
String dataTag = getDataTag(src);
while(i < added.length()) {
// Fetch a single page of items
JSONArray itemsId = new JSONArray();
for(int j=0;j<MAX_ITEMS_PER_BLOCK && i < added.length();++j) {
int id = Integer.parseInt(added.getString(i++));
itemsId.put(id);
}
if (itemsId.length() > 0) {
// Ask for these items
SapiSyncHandler.FullSet fullSet = sapiSyncHandler.getItems(
src.getConfig().getRemoteUri(), dataTag,
itemsId, null, null, null);
if (fullSet != null && fullSet.items != null) {
if (Log.isLoggable(Log.TRACE)) {
Log.trace(TAG_LOG, "items = " + fullSet.items.toString());
}
applyNewUpdToSyncSource(src, fullSet.items, state, -1, -1,
mapping, true);
}
}
}
}
/**
* Apply the given items to the source, returning whether the source can
* accept further items.
*
* @param src
* @param items
* @param state
* @param mapping
* @param deepTwinSearch
* @return
* @throws SyncException
* @throws JSONException
*/
private boolean applyNewUpdToSyncSource(SyncSource src, JSONArray items,
char state, int maxItemsCount, int appliedItemsCount,
StringKeyValueStore mapping, boolean deepTwinSearch)
throws SyncException, JSONException {
if (Log.isLoggable(Log.TRACE)) {
Log.trace(TAG_LOG, "apply new update items to source" + state);
}
boolean done = false;
// Apply these changes into the sync source
Vector sourceItems = new Vector();
for(int k=0; k<items.length() && !done; ++k) {
JSONObject item = items.getJSONObject(k);
String guid = item.getString("id");
long size = Long.parseLong(item.getString("size"));
String luid;
if (state == SyncItem.STATE_UPDATED) {
luid = mapping.get(guid);
} else {
luid = guid;
}
// Notify the listener
if (state == SyncItem.STATE_NEW) {
getSyncListenerFromSource(src).itemAddReceivingStarted(luid, null, size);
} else if(state == SyncItem.STATE_UPDATED) {
getSyncListenerFromSource(src).itemReplaceReceivingStarted(luid, null, size);
}
// If the client doesn't have the luid we change the state to new
if(StringUtil.isNullOrEmpty(luid)) {
state = SyncItem.STATE_NEW;
}
// Create the item
SyncItem syncItem = createSyncItem(src, luid, state, size, item);
syncItem.setGuid(guid);
if (deepTwinSearch) {
// In this case we cannot rely on mappings to detect twins, we
// rather perform a content analysis to determine twins
if (src instanceof TwinDetectionSource) {
TwinDetectionSource twinSource = (TwinDetectionSource)src;
SyncItem twinItem = twinSource.findTwin(syncItem);
if (twinItem != null) {
if (Log.isLoggable(Log.INFO)) {
Log.info(TAG_LOG, "Found twin for item: " + guid);
}
// Skip the processing of this item
continue;
}
} else {
Log.error(TAG_LOG, "Source does not implement TwinDetection, "
+ "possible creation of duplicates");
}
} else {
// In this case we only check if an item with the same guid
// already exists. In such a case we turn the command into a
// replace
if (state == SyncItem.STATE_NEW && mapping.get(guid) != null) {
if (Log.isLoggable(Log.INFO)) {
Log.info(TAG_LOG, "Turning add into replace as item "
+ "already exists " + guid);
}
state = SyncItem.STATE_UPDATED;
}
}
// Filter downloaded items for JSONSyncSources only
if(src instanceof JSONSyncSource) {
if(((JSONSyncSource)src).filterSyncItem(syncItem)) {
sourceItems.addElement(syncItem);
} else {
if (Log.isLoggable(Log.DEBUG)) {
Log.debug(TAG_LOG, "Item rejected by the source: " + luid);
}
}
} else {
sourceItems.addElement(syncItem);
}
// Apply items count filter
if(maxItemsCount > 0) {
if((appliedItemsCount + sourceItems.size()) >= maxItemsCount) {
if (Log.isLoggable(Log.DEBUG)) {
Log.debug(TAG_LOG, "The source doesn't accept more items");
}
done = true;
}
}
// Notify the listener
if (state == SyncItem.STATE_NEW) {
getSyncListenerFromSource(src).itemAddReceivingEnded(luid, null);
} else if(state == SyncItem.STATE_UPDATED) {
getSyncListenerFromSource(src).itemReplaceReceivingEnded(luid, null);
}
}
// Apply the items in the sync source
sourceItems = src.applyChanges(sourceItems);
// The sourceItems returned by the call contains the LUID,
// so we can create the luid/guid map here
try {
for(int l=0;l<sourceItems.size();++l) {
SyncItem newItem = (SyncItem)sourceItems.elementAt(l);
// Update the sync status
syncStatus.addReceivedItem(newItem.getGuid(), newItem.getKey(),
newItem.getState(), newItem.getSyncStatus());
// and the mapping table
if (state == SyncItem.STATE_NEW) {
if (Log.isLoggable(Log.TRACE)) {
Log.trace(TAG_LOG, "Updating mapping info for: " +
newItem.getGuid() + "," + newItem.getKey());
}
mapping.add(newItem.getGuid(), newItem.getKey());
}
}
syncStatus.save();
} catch (Exception e) {
Log.error(TAG_LOG, "Cannot save mappings", e);
}
return done;
}
private SyncItem createSyncItem(SyncSource src, String luid, char state,
long size, JSONObject item) throws JSONException {
SyncItem syncItem = null;
if(src instanceof JSONSyncSource) {
syncItem = ((JSONSyncSource)src).createSyncItem(
luid, src.getType(), state, null, item);
} else {
// A generic sync item needs to be filled with the json item content
syncItem = src.createSyncItem(luid, src.getType(), state, null, size);
OutputStream os = null;
try {
os = syncItem.getOutputStream();
os.write(item.toString().getBytes());
os.close();
} catch (IOException ioe) {
Log.error(TAG_LOG, "Cannot write into sync item stream", ioe);
// Ignore this item and continue
} finally {
try {
if (os != null) {
os.close();
}
} catch (IOException ioe) {
}
}
}
return syncItem;
}
private void applyDelItems(SyncSource src, JSONArray removed,
StringKeyValueStore mapping) throws SyncException, JSONException {
Vector delItems = new Vector();
for(int i=0;i < removed.length();++i) {
String guid = removed.getString(i);
String luid = mapping.get(guid);
if (luid == null) {
luid = guid;
}
SyncItem delItem = new SyncItem(luid, src.getType(),
SyncItem.STATE_DELETED, null);
delItem.setGuid(guid);
delItems.addElement(delItem);
getSyncListenerFromSource(src).itemDeleted(delItem);
}
if (delItems.size() > 0) {
src.applyChanges(delItems);
}
}
private void performFinalizationPhase(SyncSource src) {
sapiSyncHandler.logout();
if(src != null) {
src.endSync();
}
}
private SyncListener getSyncListenerFromSource(SyncSource source) {
SyncListener slistener = source.getListener();
if(slistener != null) {
return slistener;
} else {
return basicListener;
}
}
private int getActualSyncMode(SyncSource src, int syncMode) {
SyncAnchor anchor = src.getSyncAnchor();
if(anchor instanceof SapiSyncAnchor) {
SapiSyncAnchor sapiAnchor = (SapiSyncAnchor)anchor;
if(syncMode == SyncSource.INCREMENTAL_SYNC) {
if(sapiAnchor.getUploadAnchor() == 0) {
return SyncSource.FULL_SYNC;
}
} else if(syncMode == SyncSource.INCREMENTAL_UPLOAD) {
if(sapiAnchor.getUploadAnchor() == 0) {
return SyncSource.FULL_UPLOAD;
}
} else if(syncMode == SyncSource.INCREMENTAL_DOWNLOAD) {
if(sapiAnchor.getDownloadAnchor() == 0) {
return SyncSource.FULL_DOWNLOAD;
}
}
return syncMode;
} else {
throw new SyncException(SyncException.ILLEGAL_ARGUMENT,
"Invalid source anchor format");
}
}
private int getActualDownloadSyncMode(SyncSource src) {
SyncAnchor anchor = src.getSyncAnchor();
if(anchor instanceof SapiSyncAnchor) {
SapiSyncAnchor sapiAnchor = (SapiSyncAnchor)anchor;
if(sapiAnchor.getDownloadAnchor() > 0) {
return SyncSource.INCREMENTAL_DOWNLOAD;
} else {
return SyncSource.FULL_DOWNLOAD;
}
} else {
throw new SyncException(SyncException.ILLEGAL_ARGUMENT,
"Invalid source anchor format");
}
}
private int getActualUploadSyncMode(SyncSource src) {
SyncAnchor anchor = src.getSyncAnchor();
if(anchor instanceof SapiSyncAnchor) {
SapiSyncAnchor sapiAnchor = (SapiSyncAnchor)anchor;
if(sapiAnchor.getUploadAnchor() > 0) {
return SyncSource.INCREMENTAL_UPLOAD;
} else {
return SyncSource.FULL_UPLOAD;
}
} else {
throw new SyncException(SyncException.ILLEGAL_ARGUMENT,
"Invalid source anchor format");
}
}
private boolean isIncrementalSync(int syncMode) {
return (syncMode == SyncSource.INCREMENTAL_SYNC) ||
(syncMode == SyncSource.INCREMENTAL_DOWNLOAD) ||
(syncMode == SyncSource.INCREMENTAL_UPLOAD);
}
private boolean isDownloadPhaseNeeded(int syncMode) {
return ((syncMode == SyncSource.FULL_DOWNLOAD) ||
(syncMode == SyncSource.FULL_SYNC) ||
(syncMode == SyncSource.INCREMENTAL_SYNC) ||
(syncMode == SyncSource.INCREMENTAL_DOWNLOAD));
}
private boolean isUploadPhaseNeeded(int syncMode) {
return (syncMode == SyncSource.FULL_SYNC) ||
(syncMode == SyncSource.FULL_UPLOAD) ||
(syncMode == SyncSource.INCREMENTAL_SYNC) ||
(syncMode == SyncSource.INCREMENTAL_UPLOAD);
}
private String getDataTag(SyncSource src) {
String dataTag = null;
if (src instanceof JSONSyncSource) {
JSONSyncSource jsonSyncSource = (JSONSyncSource)src;
dataTag = jsonSyncSource.getDataTag();
}
if (dataTag == null) {
// This is the default value
dataTag = src.getConfig().getRemoteUri() + "s";
}
return dataTag;
}
}
| true | true | private void performDownloadPhase(SyncSource src, int syncMode,
boolean resume) throws SyncException {
if (Log.isLoggable(Log.INFO)) {
Log.info(TAG_LOG, "Starting download phase " + syncMode);
}
StringKeyValueStoreFactory mappingFactory =
StringKeyValueStoreFactory.getInstance();
StringKeyValueStore mapping = mappingFactory.getStringKeyValueStore(
"mapping_" + src.getName());
try {
mapping.load();
} catch (Exception e) {
if (Log.isLoggable(Log.INFO)) {
Log.info(TAG_LOG, "The mapping store does not exist, use an empty one");
}
}
String remoteUri = src.getConfig().getRemoteUri();
SyncFilter syncFilter = src.getFilter();
if (syncMode == SyncSource.FULL_DOWNLOAD) {
int totalCount = -1;
int filterMaxCount = -1;
Date filterFrom = null;
Filter fullDownloadFilter = null;
if(syncFilter != null) {
fullDownloadFilter = syncFilter.getFullDownloadFilter();
}
if(fullDownloadFilter != null) {
if(fullDownloadFilter != null && fullDownloadFilter.getType()
== Filter.ITEMS_COUNT_TYPE) {
filterMaxCount = fullDownloadFilter.getCount();
} else if(fullDownloadFilter != null && fullDownloadFilter.getType()
== Filter.DATE_RECENT_TYPE) {
filterFrom = new Date(fullDownloadFilter.getDate());
} else {
throw new UnsupportedOperationException("Not implemented yet");
}
}
// Get the number of items and notify the listener
try {
totalCount = sapiSyncHandler.getItemsCount(remoteUri, filterFrom);
if (totalCount != -1) {
if(filterMaxCount > 0) {
getSyncListenerFromSource(src).startReceiving(filterMaxCount);
} else {
getSyncListenerFromSource(src).startReceiving(totalCount);
}
}
} catch (Exception e) {
Log.error(TAG_LOG, "Cannot get the number of items on server", e);
// We ignore this exception and try to get the content
}
int downloadLimit = FULL_SYNC_DOWNLOAD_LIMIT;
String dataTag = getDataTag(src);
int offset = 0;
boolean done = false;
try {
long newDownloadAnchor = -1;
do {
// Update the download limit given the total amount of items
// to download
if((offset + downloadLimit) > totalCount) {
downloadLimit = totalCount - offset;
}
SapiSyncHandler.FullSet fullSet = sapiSyncHandler.getItems(remoteUri, dataTag, null,
Integer.toString(downloadLimit),
Integer.toString(offset), filterFrom);
if (newDownloadAnchor == -1) {
newDownloadAnchor = fullSet.timeStamp;
}
if (fullSet != null && fullSet.items != null && fullSet.items.length() > 0) {
if (Log.isLoggable(Log.TRACE)) {
Log.trace(TAG_LOG, "items = " + fullSet.items.toString());
}
done = applyNewUpdToSyncSource(src, fullSet.items, SyncItem.STATE_NEW,
filterMaxCount, offset, mapping, true);
offset += fullSet.items.length();
if ((fullSet.items.length() < FULL_SYNC_DOWNLOAD_LIMIT)) {
done = true;
}
} else {
done = true;
}
} while(!done);
// Update the download anchor
SapiSyncAnchor sapiAnchor = (SapiSyncAnchor)src.getConfig().getSyncAnchor();
if (Log.isLoggable(Log.TRACE)) {
Log.trace(TAG_LOG, "Updating download anchor to " + newDownloadAnchor);
}
sapiAnchor.setDownloadAnchor(newDownloadAnchor);
} catch (JSONException je) {
Log.error(TAG_LOG, "Cannot parse server data", je);
} catch (ItemDownloadInterruptionException ide) {
// An item could not be downloaded
if (Log.isLoggable(Log.INFO)) {
Log.info(TAG_LOG, "");
}
// TODO FIXME: handle the suspend/resume
}
} else if (syncMode == SyncSource.INCREMENTAL_DOWNLOAD) {
if (Log.isLoggable(Log.TRACE)) {
Log.trace(TAG_LOG, "Performing incremental download");
}
if(syncFilter != null && syncFilter.getIncrementalDownloadFilter() != null) {
throw new UnsupportedOperationException("Not implemented yet");
}
SapiSyncAnchor sapiAnchor = (SapiSyncAnchor)src.getConfig().getSyncAnchor();
if (Log.isLoggable(Log.TRACE)) {
Log.trace(TAG_LOG, "Last download anchor is: " + sapiAnchor.getDownloadAnchor());
}
Date anchor = new Date(sapiAnchor.getDownloadAnchor());
try {
SapiSyncHandler.ChangesSet changesSet =
sapiSyncHandler.getIncrementalChanges(anchor, remoteUri);
if (changesSet != null) {
// Count the number of items to be received and notify the
// listener
int total = 0;
if (changesSet.added != null) {
total += changesSet.added.length();
}
if (changesSet.updated != null) {
total += changesSet.updated.length();
}
if (changesSet.deleted != null) {
total += changesSet.deleted.length();
}
getSyncListenerFromSource(src).startReceiving(total);
// We must pass all of the items to the sync source, but for each
// item we need to retrieve the complete information
if (changesSet.added != null) {
applyNewUpdItems(src, changesSet.added,
SyncItem.STATE_NEW, mapping);
}
if (changesSet.updated != null) {
applyNewUpdItems(src, changesSet.updated,
SyncItem.STATE_UPDATED, mapping);
}
if (changesSet.deleted != null) {
applyDelItems(src, changesSet.deleted, mapping);
}
// Update the anchor if everything went well
if (changesSet.timeStamp != -1) {
if (Log.isLoggable(Log.TRACE)) {
Log.trace(TAG_LOG, "Updating download anchor to " + changesSet.timeStamp);
}
sapiAnchor.setDownloadAnchor(changesSet.timeStamp);
}
}
} catch (JSONException je) {
Log.error(TAG_LOG, "Cannot apply changes", je);
}
}
try {
mapping.save();
} catch (Exception e) {
Log.error(TAG_LOG, "Cannot save mapping store", e);
}
}
| private void performDownloadPhase(SyncSource src, int syncMode,
boolean resume) throws SyncException {
if (Log.isLoggable(Log.INFO)) {
Log.info(TAG_LOG, "Starting download phase " + syncMode);
}
StringKeyValueStoreFactory mappingFactory =
StringKeyValueStoreFactory.getInstance();
StringKeyValueStore mapping = mappingFactory.getStringKeyValueStore(
"mapping_" + src.getName());
try {
mapping.load();
} catch (Exception e) {
if (Log.isLoggable(Log.INFO)) {
Log.info(TAG_LOG, "The mapping store does not exist, use an empty one");
}
}
String remoteUri = src.getConfig().getRemoteUri();
SyncFilter syncFilter = src.getFilter();
if (syncMode == SyncSource.FULL_DOWNLOAD) {
int totalCount = -1;
int filterMaxCount = -1;
Date filterFrom = null;
Filter fullDownloadFilter = null;
if(syncFilter != null) {
fullDownloadFilter = syncFilter.getFullDownloadFilter();
}
if(fullDownloadFilter != null) {
if(fullDownloadFilter != null && fullDownloadFilter.getType()
== Filter.ITEMS_COUNT_TYPE) {
filterMaxCount = fullDownloadFilter.getCount();
} else if(fullDownloadFilter != null && fullDownloadFilter.getType()
== Filter.DATE_RECENT_TYPE) {
filterFrom = new Date(fullDownloadFilter.getDate());
} else {
throw new UnsupportedOperationException("Not implemented yet");
}
}
// Get the number of items and notify the listener
try {
totalCount = sapiSyncHandler.getItemsCount(remoteUri, filterFrom);
if (totalCount != -1) {
if(filterMaxCount > 0 && filterMaxCount < totalCount) {
getSyncListenerFromSource(src).startReceiving(filterMaxCount);
} else {
getSyncListenerFromSource(src).startReceiving(totalCount);
}
}
} catch (Exception e) {
Log.error(TAG_LOG, "Cannot get the number of items on server", e);
// We ignore this exception and try to get the content
}
int downloadLimit = FULL_SYNC_DOWNLOAD_LIMIT;
String dataTag = getDataTag(src);
int offset = 0;
boolean done = false;
try {
long newDownloadAnchor = -1;
do {
// Update the download limit given the total amount of items
// to download
if((offset + downloadLimit) > totalCount) {
downloadLimit = totalCount - offset;
}
SapiSyncHandler.FullSet fullSet = sapiSyncHandler.getItems(remoteUri, dataTag, null,
Integer.toString(downloadLimit),
Integer.toString(offset), filterFrom);
if (newDownloadAnchor == -1) {
newDownloadAnchor = fullSet.timeStamp;
}
if (fullSet != null && fullSet.items != null && fullSet.items.length() > 0) {
if (Log.isLoggable(Log.TRACE)) {
Log.trace(TAG_LOG, "items = " + fullSet.items.toString());
}
done = applyNewUpdToSyncSource(src, fullSet.items, SyncItem.STATE_NEW,
filterMaxCount, offset, mapping, true);
offset += fullSet.items.length();
if ((fullSet.items.length() < FULL_SYNC_DOWNLOAD_LIMIT)) {
done = true;
}
} else {
done = true;
}
} while(!done);
// Update the download anchor
SapiSyncAnchor sapiAnchor = (SapiSyncAnchor)src.getConfig().getSyncAnchor();
if (Log.isLoggable(Log.TRACE)) {
Log.trace(TAG_LOG, "Updating download anchor to " + newDownloadAnchor);
}
sapiAnchor.setDownloadAnchor(newDownloadAnchor);
} catch (JSONException je) {
Log.error(TAG_LOG, "Cannot parse server data", je);
} catch (ItemDownloadInterruptionException ide) {
// An item could not be downloaded
if (Log.isLoggable(Log.INFO)) {
Log.info(TAG_LOG, "");
}
// TODO FIXME: handle the suspend/resume
}
} else if (syncMode == SyncSource.INCREMENTAL_DOWNLOAD) {
if (Log.isLoggable(Log.TRACE)) {
Log.trace(TAG_LOG, "Performing incremental download");
}
if(syncFilter != null && syncFilter.getIncrementalDownloadFilter() != null) {
throw new UnsupportedOperationException("Not implemented yet");
}
SapiSyncAnchor sapiAnchor = (SapiSyncAnchor)src.getConfig().getSyncAnchor();
if (Log.isLoggable(Log.TRACE)) {
Log.trace(TAG_LOG, "Last download anchor is: " + sapiAnchor.getDownloadAnchor());
}
Date anchor = new Date(sapiAnchor.getDownloadAnchor());
try {
SapiSyncHandler.ChangesSet changesSet =
sapiSyncHandler.getIncrementalChanges(anchor, remoteUri);
if (changesSet != null) {
// Count the number of items to be received and notify the
// listener
int total = 0;
if (changesSet.added != null) {
total += changesSet.added.length();
}
if (changesSet.updated != null) {
total += changesSet.updated.length();
}
if (changesSet.deleted != null) {
total += changesSet.deleted.length();
}
getSyncListenerFromSource(src).startReceiving(total);
// We must pass all of the items to the sync source, but for each
// item we need to retrieve the complete information
if (changesSet.added != null) {
applyNewUpdItems(src, changesSet.added,
SyncItem.STATE_NEW, mapping);
}
if (changesSet.updated != null) {
applyNewUpdItems(src, changesSet.updated,
SyncItem.STATE_UPDATED, mapping);
}
if (changesSet.deleted != null) {
applyDelItems(src, changesSet.deleted, mapping);
}
// Update the anchor if everything went well
if (changesSet.timeStamp != -1) {
if (Log.isLoggable(Log.TRACE)) {
Log.trace(TAG_LOG, "Updating download anchor to " + changesSet.timeStamp);
}
sapiAnchor.setDownloadAnchor(changesSet.timeStamp);
}
}
} catch (JSONException je) {
Log.error(TAG_LOG, "Cannot apply changes", je);
}
}
try {
mapping.save();
} catch (Exception e) {
Log.error(TAG_LOG, "Cannot save mapping store", e);
}
}
|
diff --git a/core/src/main/java/hudson/model/Resource.java b/core/src/main/java/hudson/model/Resource.java
index 25c034cd5..f641510b3 100644
--- a/core/src/main/java/hudson/model/Resource.java
+++ b/core/src/main/java/hudson/model/Resource.java
@@ -1,94 +1,94 @@
package hudson.model;
/**
* Represents things that {@link Queue.Executable} uses while running.
*
* <p>
* This is used in {@link Queue} to support basic mutual exclusion/locks. If two
* {@link Queue.Task}s require the same {@link Resource}, they will not
* be run at the same time.
*
* <p>
* Resources are compared by using their {@link #displayName names}, and
* need not have the "same object" semantics.
*
* @since 1.121
*/
public final class Resource {
/**
* Human-readable name of this resource.
* Used for rendering HTML.
*/
public final String displayName;
/**
* Parent resource.
*
* <p>
* A child resource is considered a part of the parent resource,
* so acquiring the parent resource always imply acquiring all
* the child resources.
*/
public final Resource parent;
/**
* Maximum number of concurrent write.
*/
public final int numConcurrentWrite;
public Resource(Resource parent, String displayName) {
this(parent,displayName,1);
}
/**
* @since 1.155
*/
public Resource(Resource parent, String displayName, int numConcurrentWrite) {
if(numConcurrentWrite<1)
throw new IllegalArgumentException();
this.parent = parent;
this.displayName = displayName;
this.numConcurrentWrite = numConcurrentWrite;
}
public Resource(String displayName) {
this(null,displayName);
}
/**
* Checks the resource collision.
*
* @param count
* If we are testing W/W conflict, total # of write counts.
* For R/W conflict test, this value should be set to {@link Integer#MAX_VALUE}.
*/
public boolean isCollidingWith(Resource that, int count) {
assert that!=null;
for(Resource r=that; r!=null; r=r.parent)
- if(this.equals(r) && r.numConcurrentWrite>count)
+ if(this.equals(r) && r.numConcurrentWrite<count)
return true;
for(Resource r=this; r!=null; r=r.parent)
- if(that.equals(r) && r.numConcurrentWrite>count)
+ if(that.equals(r) && r.numConcurrentWrite<count)
return true;
return false;
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Resource that = (Resource) o;
return displayName.equals(that.displayName) && eq(this.parent,that.parent);
}
private static boolean eq(Object lhs,Object rhs) {
if(lhs==rhs) return true;
if(lhs==null || rhs==null) return false;
return lhs.equals(rhs);
}
public int hashCode() {
return displayName.hashCode();
}
}
| false | true | public boolean isCollidingWith(Resource that, int count) {
assert that!=null;
for(Resource r=that; r!=null; r=r.parent)
if(this.equals(r) && r.numConcurrentWrite>count)
return true;
for(Resource r=this; r!=null; r=r.parent)
if(that.equals(r) && r.numConcurrentWrite>count)
return true;
return false;
}
| public boolean isCollidingWith(Resource that, int count) {
assert that!=null;
for(Resource r=that; r!=null; r=r.parent)
if(this.equals(r) && r.numConcurrentWrite<count)
return true;
for(Resource r=this; r!=null; r=r.parent)
if(that.equals(r) && r.numConcurrentWrite<count)
return true;
return false;
}
|
diff --git a/components/PluginUnzip/src/cz/zcu/kiv/kc/plugin/unzip/UnzipFilePlugin.java b/components/PluginUnzip/src/cz/zcu/kiv/kc/plugin/unzip/UnzipFilePlugin.java
index 113e0a1..060ed05 100644
--- a/components/PluginUnzip/src/cz/zcu/kiv/kc/plugin/unzip/UnzipFilePlugin.java
+++ b/components/PluginUnzip/src/cz/zcu/kiv/kc/plugin/unzip/UnzipFilePlugin.java
@@ -1,276 +1,276 @@
package cz.zcu.kiv.kc.plugin.unzip;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.SwingWorker;
import javax.swing.UIManager;
import javax.swing.SwingWorker.StateValue;
import cz.zcu.kiv.kc.plugin.AbstractPlugin;
import cz.zcu.kiv.kc.plugin.I18N;
/**
* UnZip decompression plug-in. Executes compression in separate SwingWorker thread. Provides progress dialog and cancellation.
* @author Michal
*
*/
public class UnzipFilePlugin extends AbstractPlugin implements PropertyChangeListener
{
private class DecompressionTask extends SwingWorker<Void, Void>
{
private File fileToDecompress;
private File destinationDirectory;
public DecompressionTask(
File fileToDecompress,
File destinationDirectory
)
{
this.fileToDecompress = fileToDecompress;
this.destinationDirectory = destinationDirectory;
}
@Override
protected Void doInBackground() throws Exception
{
this.exec(
this.fileToDecompress,
this.destinationDirectory.getAbsolutePath()
);
return null;
}
private void exec(
File fileToDecompress,
String destinationPath)
{
byte[] buffer = new byte[1024];
try (ZipFile zif = new ZipFile(fileToDecompress))
{
int totalEntries = zif.size();
int processedEntries = 0;
Enumeration<? extends ZipEntry> entries = zif.entries();
while (entries.hasMoreElements() && !this.isCancelled())
{
ZipEntry entry = entries.nextElement();
try (InputStream is = zif.getInputStream(entry))
{
File newFile = new File(destinationPath + File.separator + entry.getName());
if (entry.isDirectory())
{ // entry is directory, create and continue with other entry
newFile.mkdirs();
}
else
{ // entry is file, create parent directories and write content
if (newFile.exists())
{ // trying to overwrite existing file
int res = JOptionPane.showConfirmDialog(
UnzipFilePlugin.this.mainWindow,
- "Soubor ji� existuje. P�epsat?",
- "P�epsat?",
+ I18N.getText("overwriteExisting", newFile),
+ I18N.getText("overwriteExistingTitle"),
JOptionPane.YES_NO_CANCEL_OPTION
);
if (res == JOptionPane.NO_OPTION)
{ // skip current file
continue;
}
else if (res == JOptionPane.CANCEL_OPTION)
{ // cancel whole operation
break;
}
}
File parentDirs = new File(newFile.getParent());
parentDirs.mkdirs();
this.firePropertyChange("file", null, newFile);
try (FileOutputStream fos = new FileOutputStream(newFile))
{
int len;
while ((len = is.read(buffer)) > 0)
{
fos.write(buffer, 0, len);
}
}
catch (FileNotFoundException ex)
{ // should not occur
System.out.println("chyba zapisu: " + ex.getMessage());
}
}
this.setProgress((int) ( (float) ++processedEntries / totalEntries * 100) );
}
}
}
catch (ZipException e) { }
catch (IOException e) { }
finally
{
this.firePropertyChange("done", false, true);
}
}
}
JDialog progressDialog = new JDialog(this.mainWindow);
JProgressBar pb = new JProgressBar();
JLabel jl = new JLabel(I18N.getText("status") + " ");
DecompressionTask worker = null;
String destinationPath;
boolean canceled = false;
public UnzipFilePlugin()
{
super();
UIManager.put("ClassLoader", getClass().getClassLoader());
}
private Action exitAction = new AbstractAction()
{
private static final long serialVersionUID = 5409574734727190161L;
{
putValue(NAME, I18N.getText("cancelTitle"));
}
@Override
public void actionPerformed(ActionEvent e) {
if (UnzipFilePlugin.this.worker == null) return;
if (!UnzipFilePlugin.this.worker.isDone())
{
int res = JOptionPane.showConfirmDialog(
UnzipFilePlugin.this.mainWindow,
I18N.getText("cancelCurrentOperation"),
I18N.getText("cancelCurrentOperationTitle"),
JOptionPane.YES_NO_OPTION
);
if (res == JOptionPane.NO_OPTION)
{
return;
}
else
{
System.out.println("canceled: " + UnzipFilePlugin.this.worker.cancel(true));
}
}
UnzipFilePlugin.this.canceled = true;
UnzipFilePlugin.this.progressDialog.dispose();
}
};
@Override
public void executeAction(
List<File> selectedFiles,
String destinationPath,
String sourcePath)
{
this.destinationPath = destinationPath;
for (File file : selectedFiles)
{
if (this.canceled) break;
destinationPath = JOptionPane.showInputDialog(
UnzipFilePlugin.this.mainWindow,
I18N.getText("targetFolder"),
destinationPath
+ (destinationPath.endsWith(File.separator) ? "" : File.separator)
+ file.getName().substring(0, file.getName().lastIndexOf('.'))
);
if (destinationPath == null || destinationPath.trim().isEmpty())
{
JOptionPane.showMessageDialog(
UnzipFilePlugin.this.mainWindow,
I18N.getText("canceledByUser")
);
return;
}
this.jl.setPreferredSize(new Dimension(480, -1));
this.pb.setStringPainted(true);
JPanel panel = new JPanel(new GridLayout(3, 1));
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
panel.add(this.jl);
panel.add(this.pb);
panel.add(new JButton(this.exitAction));
this.progressDialog.add(panel);
this.progressDialog.pack();
this.progressDialog.setResizable(false);
this.progressDialog.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
this.progressDialog.addWindowListener(
new WindowAdapter()
{
@Override
public void windowClosing(java.awt.event.WindowEvent arg0)
{
UnzipFilePlugin.this.exitAction.actionPerformed(null);
}
}
);
this.worker = new DecompressionTask(
file,
new File(destinationPath)
);
worker.addPropertyChangeListener(this);
worker.execute();
this.progressDialog.setVisible(true);
}
}
@Override
public String getName() {
return "unzip";
}
@Override
public void propertyChange(PropertyChangeEvent evt)
{
if (evt.getPropertyName() == "state" && evt.getNewValue() == StateValue.STARTED)
{
this.pb.setValue(0);
}
if (evt.getPropertyName() == "file")
{
this.jl.setText(evt.getNewValue().toString() + I18N.getText("extracted"));
}
if (evt.getPropertyName() == "progress")
{
this.pb.setValue((int) evt.getNewValue());
}
if (evt.getPropertyName() == "done")
{
System.out.println("refreshing: " + this.destinationPath);
this.sendEvent(destinationPath);
this.progressDialog.dispose();
}
}
}
| true | true | private void exec(
File fileToDecompress,
String destinationPath)
{
byte[] buffer = new byte[1024];
try (ZipFile zif = new ZipFile(fileToDecompress))
{
int totalEntries = zif.size();
int processedEntries = 0;
Enumeration<? extends ZipEntry> entries = zif.entries();
while (entries.hasMoreElements() && !this.isCancelled())
{
ZipEntry entry = entries.nextElement();
try (InputStream is = zif.getInputStream(entry))
{
File newFile = new File(destinationPath + File.separator + entry.getName());
if (entry.isDirectory())
{ // entry is directory, create and continue with other entry
newFile.mkdirs();
}
else
{ // entry is file, create parent directories and write content
if (newFile.exists())
{ // trying to overwrite existing file
int res = JOptionPane.showConfirmDialog(
UnzipFilePlugin.this.mainWindow,
"Soubor ji� existuje. P�epsat?",
"P�epsat?",
JOptionPane.YES_NO_CANCEL_OPTION
);
if (res == JOptionPane.NO_OPTION)
{ // skip current file
continue;
}
else if (res == JOptionPane.CANCEL_OPTION)
{ // cancel whole operation
break;
}
}
File parentDirs = new File(newFile.getParent());
parentDirs.mkdirs();
this.firePropertyChange("file", null, newFile);
try (FileOutputStream fos = new FileOutputStream(newFile))
{
int len;
while ((len = is.read(buffer)) > 0)
{
fos.write(buffer, 0, len);
}
}
catch (FileNotFoundException ex)
{ // should not occur
System.out.println("chyba zapisu: " + ex.getMessage());
}
}
this.setProgress((int) ( (float) ++processedEntries / totalEntries * 100) );
}
}
}
catch (ZipException e) { }
catch (IOException e) { }
finally
{
this.firePropertyChange("done", false, true);
}
}
| private void exec(
File fileToDecompress,
String destinationPath)
{
byte[] buffer = new byte[1024];
try (ZipFile zif = new ZipFile(fileToDecompress))
{
int totalEntries = zif.size();
int processedEntries = 0;
Enumeration<? extends ZipEntry> entries = zif.entries();
while (entries.hasMoreElements() && !this.isCancelled())
{
ZipEntry entry = entries.nextElement();
try (InputStream is = zif.getInputStream(entry))
{
File newFile = new File(destinationPath + File.separator + entry.getName());
if (entry.isDirectory())
{ // entry is directory, create and continue with other entry
newFile.mkdirs();
}
else
{ // entry is file, create parent directories and write content
if (newFile.exists())
{ // trying to overwrite existing file
int res = JOptionPane.showConfirmDialog(
UnzipFilePlugin.this.mainWindow,
I18N.getText("overwriteExisting", newFile),
I18N.getText("overwriteExistingTitle"),
JOptionPane.YES_NO_CANCEL_OPTION
);
if (res == JOptionPane.NO_OPTION)
{ // skip current file
continue;
}
else if (res == JOptionPane.CANCEL_OPTION)
{ // cancel whole operation
break;
}
}
File parentDirs = new File(newFile.getParent());
parentDirs.mkdirs();
this.firePropertyChange("file", null, newFile);
try (FileOutputStream fos = new FileOutputStream(newFile))
{
int len;
while ((len = is.read(buffer)) > 0)
{
fos.write(buffer, 0, len);
}
}
catch (FileNotFoundException ex)
{ // should not occur
System.out.println("chyba zapisu: " + ex.getMessage());
}
}
this.setProgress((int) ( (float) ++processedEntries / totalEntries * 100) );
}
}
}
catch (ZipException e) { }
catch (IOException e) { }
finally
{
this.firePropertyChange("done", false, true);
}
}
|
diff --git a/src/de/fuberlin/projecta/analysis/SemanticAnalyzer.java b/src/de/fuberlin/projecta/analysis/SemanticAnalyzer.java
index 5b478b0c..74b87af6 100644
--- a/src/de/fuberlin/projecta/analysis/SemanticAnalyzer.java
+++ b/src/de/fuberlin/projecta/analysis/SemanticAnalyzer.java
@@ -1,445 +1,450 @@
package de.fuberlin.projecta.analysis;
import de.fuberlin.commons.lexer.TokenType;
import de.fuberlin.commons.parser.ISymbol;
import de.fuberlin.commons.parser.ISyntaxTree;
import de.fuberlin.projecta.analysis.ast.nodes.AbstractSyntaxTree;
import de.fuberlin.projecta.analysis.ast.nodes.Args;
import de.fuberlin.projecta.analysis.ast.nodes.Array;
import de.fuberlin.projecta.analysis.ast.nodes.ArrayCall;
import de.fuberlin.projecta.analysis.ast.nodes.BasicType;
import de.fuberlin.projecta.analysis.ast.nodes.BinaryOp;
import de.fuberlin.projecta.analysis.ast.nodes.Block;
import de.fuberlin.projecta.analysis.ast.nodes.BoolLiteral;
import de.fuberlin.projecta.analysis.ast.nodes.Break;
import de.fuberlin.projecta.analysis.ast.nodes.Declaration;
import de.fuberlin.projecta.analysis.ast.nodes.Do;
import de.fuberlin.projecta.analysis.ast.nodes.FuncCall;
import de.fuberlin.projecta.analysis.ast.nodes.FuncDef;
import de.fuberlin.projecta.analysis.ast.nodes.Id;
import de.fuberlin.projecta.analysis.ast.nodes.If;
import de.fuberlin.projecta.analysis.ast.nodes.IfElse;
import de.fuberlin.projecta.analysis.ast.nodes.IntLiteral;
import de.fuberlin.projecta.analysis.ast.nodes.Params;
import de.fuberlin.projecta.analysis.ast.nodes.Print;
import de.fuberlin.projecta.analysis.ast.nodes.Program;
import de.fuberlin.projecta.analysis.ast.nodes.RealLiteral;
import de.fuberlin.projecta.analysis.ast.nodes.Record;
import de.fuberlin.projecta.analysis.ast.nodes.RecordVarCall;
import de.fuberlin.projecta.analysis.ast.nodes.Return;
import de.fuberlin.projecta.analysis.ast.nodes.Statement;
import de.fuberlin.projecta.analysis.ast.nodes.StringLiteral;
import de.fuberlin.projecta.analysis.ast.nodes.Type;
import de.fuberlin.projecta.analysis.ast.nodes.UnaryOp;
import de.fuberlin.projecta.analysis.ast.nodes.While;
import de.fuberlin.projecta.lexer.BasicTokenType;
import de.fuberlin.projecta.parser.NonTerminal;
import de.fuberlin.projecta.parser.Parser;
import de.fuberlin.projecta.parser.Symbol;
import de.fuberlin.projecta.parser.Symbol.Reserved;
public class SemanticAnalyzer {
private static final String LAttribute = "LAttribute";
private ISyntaxTree parseTree;
private SymbolTableStack tables;
private AbstractSyntaxTree AST;
public SemanticAnalyzer(ISyntaxTree tree) {
this.parseTree = tree;
tables = new SymbolTableStack();
}
public void analyze() throws SemanticException {
toAST(parseTree);
parseTreeForRemoval();
parseTreeForBuildingSymbolTable();
AST.printTree();
checkForValidity(AST);
}
public void toAST(ISyntaxTree tree) {
toAST(tree, null);
}
private Symbol translate(ISymbol symbol) {
if (symbol instanceof Symbol)
return (Symbol) symbol;
else {
// let Symbol figure out which type this is
return new Symbol(symbol.getName());
}
}
/**
* Traverses through the parseTree in depth-first-search and adds new nodes
* to the given insertNode. Only l-attributed nodes must be passed through
* node-attributes!
*
* The idea is that one node knows where it should get added to.
*
* @param tree
* current parseTree-node (with symbol)
* @param insertNode
* syntaxTree-Node, in which new nodes get added
*/
public void toAST(ISyntaxTree tree, ISyntaxTree insertNode) {
Symbol symbol = translate(tree.getSymbol());
if (symbol.isNonTerminal()) {
NonTerminal nonT = symbol.asNonTerminal();
switch (nonT) {
case program:
AST = new Program();
toAST(tree.getChild(0), AST);
return;
case funcs:
for (int i = 0; i < tree.getChildrenCount(); i++) {
toAST(tree.getChild(i), insertNode);
}
return;
case func:
FuncDef func = new FuncDef();
for (int i = 0; i < tree.getChildrenCount(); i++) {
toAST(tree.getChild(i), func);
}
insertNode.addChild(func);
return;
case type:
if (translate(tree.getChild(0).getSymbol()).asTerminal() == TokenType.BASIC) {
// this is type_ and it must exist!
if (tree.getChild(1).getChildrenCount() != 0) {
Type array = new Array();
// the basic node gets added to this temporary node
// and is passed to the new array
// it doesn't matter which node to take as long as
// it is a treenode.
ISyntaxTree tmp = new Program();
toAST(tree.getChild(0), tmp);
array.addAttribute(LAttribute);
// this is already the BasicType node
boolean success = array.setAttribute(LAttribute,
tmp.getChild(0));
assert (success);
insertNode.addChild(array);
toAST(tree.getChild(1), array);
} else
// type_ is empty, hook the basic node in the parent
toAST(tree.getChild(0), insertNode);
} else { // we have a record! *CONGRATS*
Record record = new Record();
// test if we have an array of this record
if (tree.getChild(4).getChildrenCount() != 0) {
Type array = new Array();
toAST(tree.getChild(2), record); // <-- decls!!!
array.addAttribute(LAttribute);
array.setAttribute(LAttribute, record);
toAST(tree.getChild(4), array);
insertNode.addChild(array);
} else // this is simply one record
{
toAST(tree.getChild(2), record); // <-- decls!!!
insertNode.addChild(record);
}
}
return;
case type_:
// TODO: Width of array!!!
toAST(tree.getChild(1), insertNode);
if (tree.getChild(3).getChildrenCount() != 0) {
Array array = new Array();
array.addAttribute(LAttribute);
array.setAttribute(LAttribute,
insertNode.getAttribute(LAttribute));
toAST(tree.getChild(3), array);
insertNode.addChild(array);
} else // array declaration stopped here...
{
insertNode.addChild((ISyntaxTree) insertNode
.getAttribute(LAttribute));
}
return;
case optparams:
Params params = new Params();
for (int i = 0; i < tree.getChildrenCount(); i++) {
toAST(tree.getChild(i), params);
}
insertNode.addChild(params);
return;
case block:
Block block = new Block();
for (int i = 0; i < tree.getChildrenCount(); i++) {
toAST(tree.getChild(i), block);
}
if (block.getChildrenCount() != 0) {
insertNode.addChild(block);
} // else func_ -> ;
return;
case decl:
Declaration decl = new Declaration();
for (int i = 0; i < tree.getChildrenCount(); i++) {
toAST(tree.getChild(i), decl);
}
insertNode.addChild(decl);
return;
case stmt: {
Statement stmt = null;
ISyntaxTree firstChild = tree.getChild(0);
Symbol firstChildSymbol = translate(firstChild.getSymbol());
if (firstChildSymbol.isTerminal()) {
TokenType terminal = translate(firstChild.getSymbol())
.asTerminal();
if (terminal == TokenType.IF) {
ISyntaxTree stmt_ = tree.getChild(5); //
if (stmt_.getChildrenCount() == 0)
stmt = new If();
else
stmt = new IfElse();
} else if (terminal == TokenType.WHILE) {
stmt = new While();
} else if (terminal == TokenType.DO) {
stmt = new Do();
} else if (terminal == TokenType.BREAK) {
stmt = new Break();
} else if (terminal == TokenType.RETURN) {
stmt = new Return();
} else if (terminal == TokenType.PRINT) {
stmt = new Print();
}
} else if (firstChildSymbol.isNonTerminal()) {
toAST(firstChild, insertNode);
}
if (stmt != null) {
for (int i = 0; i < tree.getChildrenCount(); i++) {
toAST(tree.getChild(i), stmt);
}
insertNode.addChild(stmt);
}
return;
}
case assign:
case bool:
case join:
case equality:
case rel:
case expr:
case term:
if (tree.getChild(1).getChildrenCount() == 0) {
toAST(tree.getChild(0), insertNode);
} else {
BinaryOp bOp = new BinaryOp(translate(
tree.getChild(1).getChild(0).getSymbol())
.asTerminal());
- if (bOp != null) {
- // simply hang in both children trees
- toAST(tree.getChild(0), bOp); // rel
- toAST(tree.getChild(1), bOp); // equality'
- insertNode.addChild(bOp);
- }
+ // simply hang in both children trees
+ toAST(tree.getChild(0), bOp); // rel
+ toAST(tree.getChild(1), bOp); // equality'
+ insertNode.addChild(bOp);
+ }
+ return;
+ case expr_:
+ if (tree.getChildrenCount() != 0) {
+ // simply hang in both children trees
+ toAST(tree.getChild(1), insertNode);
+ toAST(tree.getChild(2), insertNode);
}
return;
case unary: {
Symbol firstChildSymbol = translate(tree.getChild(0)
.getSymbol());
if (firstChildSymbol.isNonTerminal()) {
toAST(tree.getChild(0), insertNode);
} else {
UnaryOp uOp = new UnaryOp(firstChildSymbol.asTerminal());
if (uOp != null) {
// simply hang in both children trees
toAST(tree.getChild(1), uOp); // unary
insertNode.addChild(uOp);
}
}
}
case factor:
if (translate(tree.getChild(0).getSymbol()).isNonTerminal()) {
if (tree.getChildrenCount() >= 2) {
if (tree.getChild(1).getChildrenCount() == 0) {
toAST(tree.getChild(0), insertNode);
} else {
FuncCall call = new FuncCall();
for (ISyntaxTree tmp : tree.getChildren()) {
toAST(tmp, call);
}
insertNode.addChild(call);
}
}
} else {
for (ISyntaxTree tmp : tree.getChildren()) {
toAST(tmp, insertNode);
}
}
return;
case factor_:
if (tree.getChild(1).getChildrenCount() != 0) {
Args args = new Args();
toAST(tree.getChild(1), args);
insertNode.addChild(args);
}
return;
case loc:
if (tree.getChild(1).getChildrenCount() == 0) {
toAST(tree.getChild(0), insertNode);
} else {
ISyntaxTree tmp = new Program();
toAST(tree.getChild(0), tmp);
tree.getChild(1).addAttribute(LAttribute);
// there is only one child (the id itself)!
tree.getChild(1).setAttribute(LAttribute, tmp.getChild(0));
toAST(tree.getChild(1), insertNode);
}
return;
case loc__:
tree.getChild(0).addAttribute(LAttribute);
tree.getChild(0).setAttribute(LAttribute,
tree.getAttribute(LAttribute));
if (tree.getChild(1).getChildrenCount() == 0) {
toAST(tree.getChild(0), insertNode);
} else {
ISyntaxTree tmp = new Program();
toAST(tree.getChild(0), tmp);
if (tmp.getChildrenCount() == 1) {
tree.getChild(1).addAttribute(LAttribute);
tree.getChild(1).setAttribute(LAttribute,
tmp.getChild(0));
toAST(tree.getChild(1), insertNode);
}
}
return;
case loc_:
// TODO: not everything is well thought atm...
if (translate(tree.getChild(0).getSymbol()).asTerminal() == TokenType.OP_DOT) {
RecordVarCall varCall = new RecordVarCall();
varCall.addChild((ISyntaxTree) tree
.getAttribute(LAttribute));
toAST(tree.getChild(1), varCall);
insertNode.addChild(varCall);
} else {
ArrayCall array = new ArrayCall();
toAST(tree.getChild(1), array);
array.addChild((ISyntaxTree) tree.getAttribute(LAttribute));
insertNode.addChild(array);
}
return;
// list of nodes which use the default case:
// assign_, bool_, decls, equality_, expr_, factor_,
// func_, join_,
// params, params_, rel_, stmt_, stmt__, stmts,
default:
// nothing to do here just pass it through
for (ISyntaxTree tmp : tree.getChildren()) {
toAST(tmp, insertNode);
}
}
} else if (symbol.isTerminal()) {
TokenType t = symbol.asTerminal();
switch (t) {
case BASIC:
BasicTokenType type = (BasicTokenType) tree
.getAttribute(Parser.TOKEN_VALUE);
insertNode.addChild(new BasicType(type));
return;
case INT_LITERAL:
insertNode.addChild(new IntLiteral((Integer) tree
.getAttribute(Parser.TOKEN_VALUE)));
return;
case STRING_LITERAL:
insertNode.addChild(new StringLiteral((String) tree
.getAttribute(Parser.TOKEN_VALUE)));
return;
case REAL_LITERAL:
insertNode.addChild(new RealLiteral((Double) tree
.getAttribute(Parser.TOKEN_VALUE)));
return;
case BOOL_LITERAL:
insertNode.addChild(new BoolLiteral((Boolean) tree
.getAttribute(Parser.TOKEN_VALUE)));
return;
case ID:
insertNode.addChild(new Id((String) tree
.getAttribute(Parser.TOKEN_VALUE)));
return;
default:// everything, which has no class member in its node uses
// the default.
}
} else if (symbol.isReservedTerminal()) {
Reserved res = symbol.asReservedTerminal();
switch (res) {
case EPSILON:
if (tree.getChildrenCount() == 1) {
toAST(tree.getChild(0));
} else {
// this should never occur
throw new SemanticException(
"Epsilon in other position than head?");
}
case SP:
// this should never occur
// throw new SemanticException("Stack pointer in parsetree?");
}
}
}
/**
* Should find productions which are semantically nonsense. Like double
* assignment, funcCalls which aren't declared in this scope, assessing
* record members which aren't existing or where the record does not exist,
* ...
*
* @param tree
* @return
*/
private boolean checkForValidity(ISyntaxTree tree) {
return true;
}
/**
* Runs every nodes run method in depth-first-left-to-right order.
*
* @param tree
*/
private void parseTreeForBuildingSymbolTable() {
AST.buildSymbolTable(tables);
}
/**
* Checks whether the tree contains disallowed semantic.
*/
private void parseTreeForRemoval() {
// TODO: think about how to smartly encode disallowed trees
}
public SymbolTableStack getTables() {
return tables;
}
public AbstractSyntaxTree getAST() {
return AST;
}
}
| true | true | public void toAST(ISyntaxTree tree, ISyntaxTree insertNode) {
Symbol symbol = translate(tree.getSymbol());
if (symbol.isNonTerminal()) {
NonTerminal nonT = symbol.asNonTerminal();
switch (nonT) {
case program:
AST = new Program();
toAST(tree.getChild(0), AST);
return;
case funcs:
for (int i = 0; i < tree.getChildrenCount(); i++) {
toAST(tree.getChild(i), insertNode);
}
return;
case func:
FuncDef func = new FuncDef();
for (int i = 0; i < tree.getChildrenCount(); i++) {
toAST(tree.getChild(i), func);
}
insertNode.addChild(func);
return;
case type:
if (translate(tree.getChild(0).getSymbol()).asTerminal() == TokenType.BASIC) {
// this is type_ and it must exist!
if (tree.getChild(1).getChildrenCount() != 0) {
Type array = new Array();
// the basic node gets added to this temporary node
// and is passed to the new array
// it doesn't matter which node to take as long as
// it is a treenode.
ISyntaxTree tmp = new Program();
toAST(tree.getChild(0), tmp);
array.addAttribute(LAttribute);
// this is already the BasicType node
boolean success = array.setAttribute(LAttribute,
tmp.getChild(0));
assert (success);
insertNode.addChild(array);
toAST(tree.getChild(1), array);
} else
// type_ is empty, hook the basic node in the parent
toAST(tree.getChild(0), insertNode);
} else { // we have a record! *CONGRATS*
Record record = new Record();
// test if we have an array of this record
if (tree.getChild(4).getChildrenCount() != 0) {
Type array = new Array();
toAST(tree.getChild(2), record); // <-- decls!!!
array.addAttribute(LAttribute);
array.setAttribute(LAttribute, record);
toAST(tree.getChild(4), array);
insertNode.addChild(array);
} else // this is simply one record
{
toAST(tree.getChild(2), record); // <-- decls!!!
insertNode.addChild(record);
}
}
return;
case type_:
// TODO: Width of array!!!
toAST(tree.getChild(1), insertNode);
if (tree.getChild(3).getChildrenCount() != 0) {
Array array = new Array();
array.addAttribute(LAttribute);
array.setAttribute(LAttribute,
insertNode.getAttribute(LAttribute));
toAST(tree.getChild(3), array);
insertNode.addChild(array);
} else // array declaration stopped here...
{
insertNode.addChild((ISyntaxTree) insertNode
.getAttribute(LAttribute));
}
return;
case optparams:
Params params = new Params();
for (int i = 0; i < tree.getChildrenCount(); i++) {
toAST(tree.getChild(i), params);
}
insertNode.addChild(params);
return;
case block:
Block block = new Block();
for (int i = 0; i < tree.getChildrenCount(); i++) {
toAST(tree.getChild(i), block);
}
if (block.getChildrenCount() != 0) {
insertNode.addChild(block);
} // else func_ -> ;
return;
case decl:
Declaration decl = new Declaration();
for (int i = 0; i < tree.getChildrenCount(); i++) {
toAST(tree.getChild(i), decl);
}
insertNode.addChild(decl);
return;
case stmt: {
Statement stmt = null;
ISyntaxTree firstChild = tree.getChild(0);
Symbol firstChildSymbol = translate(firstChild.getSymbol());
if (firstChildSymbol.isTerminal()) {
TokenType terminal = translate(firstChild.getSymbol())
.asTerminal();
if (terminal == TokenType.IF) {
ISyntaxTree stmt_ = tree.getChild(5); //
if (stmt_.getChildrenCount() == 0)
stmt = new If();
else
stmt = new IfElse();
} else if (terminal == TokenType.WHILE) {
stmt = new While();
} else if (terminal == TokenType.DO) {
stmt = new Do();
} else if (terminal == TokenType.BREAK) {
stmt = new Break();
} else if (terminal == TokenType.RETURN) {
stmt = new Return();
} else if (terminal == TokenType.PRINT) {
stmt = new Print();
}
} else if (firstChildSymbol.isNonTerminal()) {
toAST(firstChild, insertNode);
}
if (stmt != null) {
for (int i = 0; i < tree.getChildrenCount(); i++) {
toAST(tree.getChild(i), stmt);
}
insertNode.addChild(stmt);
}
return;
}
case assign:
case bool:
case join:
case equality:
case rel:
case expr:
case term:
if (tree.getChild(1).getChildrenCount() == 0) {
toAST(tree.getChild(0), insertNode);
} else {
BinaryOp bOp = new BinaryOp(translate(
tree.getChild(1).getChild(0).getSymbol())
.asTerminal());
if (bOp != null) {
// simply hang in both children trees
toAST(tree.getChild(0), bOp); // rel
toAST(tree.getChild(1), bOp); // equality'
insertNode.addChild(bOp);
}
}
return;
case unary: {
Symbol firstChildSymbol = translate(tree.getChild(0)
.getSymbol());
if (firstChildSymbol.isNonTerminal()) {
toAST(tree.getChild(0), insertNode);
} else {
UnaryOp uOp = new UnaryOp(firstChildSymbol.asTerminal());
if (uOp != null) {
// simply hang in both children trees
toAST(tree.getChild(1), uOp); // unary
insertNode.addChild(uOp);
}
}
}
case factor:
if (translate(tree.getChild(0).getSymbol()).isNonTerminal()) {
if (tree.getChildrenCount() >= 2) {
if (tree.getChild(1).getChildrenCount() == 0) {
toAST(tree.getChild(0), insertNode);
} else {
FuncCall call = new FuncCall();
for (ISyntaxTree tmp : tree.getChildren()) {
toAST(tmp, call);
}
insertNode.addChild(call);
}
}
} else {
for (ISyntaxTree tmp : tree.getChildren()) {
toAST(tmp, insertNode);
}
}
return;
case factor_:
if (tree.getChild(1).getChildrenCount() != 0) {
Args args = new Args();
toAST(tree.getChild(1), args);
insertNode.addChild(args);
}
return;
case loc:
if (tree.getChild(1).getChildrenCount() == 0) {
toAST(tree.getChild(0), insertNode);
} else {
ISyntaxTree tmp = new Program();
toAST(tree.getChild(0), tmp);
tree.getChild(1).addAttribute(LAttribute);
// there is only one child (the id itself)!
tree.getChild(1).setAttribute(LAttribute, tmp.getChild(0));
toAST(tree.getChild(1), insertNode);
}
return;
case loc__:
tree.getChild(0).addAttribute(LAttribute);
tree.getChild(0).setAttribute(LAttribute,
tree.getAttribute(LAttribute));
if (tree.getChild(1).getChildrenCount() == 0) {
toAST(tree.getChild(0), insertNode);
} else {
ISyntaxTree tmp = new Program();
toAST(tree.getChild(0), tmp);
if (tmp.getChildrenCount() == 1) {
tree.getChild(1).addAttribute(LAttribute);
tree.getChild(1).setAttribute(LAttribute,
tmp.getChild(0));
toAST(tree.getChild(1), insertNode);
}
}
return;
case loc_:
// TODO: not everything is well thought atm...
if (translate(tree.getChild(0).getSymbol()).asTerminal() == TokenType.OP_DOT) {
RecordVarCall varCall = new RecordVarCall();
varCall.addChild((ISyntaxTree) tree
.getAttribute(LAttribute));
toAST(tree.getChild(1), varCall);
insertNode.addChild(varCall);
} else {
ArrayCall array = new ArrayCall();
toAST(tree.getChild(1), array);
array.addChild((ISyntaxTree) tree.getAttribute(LAttribute));
insertNode.addChild(array);
}
return;
// list of nodes which use the default case:
// assign_, bool_, decls, equality_, expr_, factor_,
// func_, join_,
// params, params_, rel_, stmt_, stmt__, stmts,
default:
// nothing to do here just pass it through
for (ISyntaxTree tmp : tree.getChildren()) {
toAST(tmp, insertNode);
}
}
} else if (symbol.isTerminal()) {
TokenType t = symbol.asTerminal();
switch (t) {
case BASIC:
BasicTokenType type = (BasicTokenType) tree
.getAttribute(Parser.TOKEN_VALUE);
insertNode.addChild(new BasicType(type));
return;
case INT_LITERAL:
insertNode.addChild(new IntLiteral((Integer) tree
.getAttribute(Parser.TOKEN_VALUE)));
return;
case STRING_LITERAL:
insertNode.addChild(new StringLiteral((String) tree
.getAttribute(Parser.TOKEN_VALUE)));
return;
case REAL_LITERAL:
insertNode.addChild(new RealLiteral((Double) tree
.getAttribute(Parser.TOKEN_VALUE)));
return;
case BOOL_LITERAL:
insertNode.addChild(new BoolLiteral((Boolean) tree
.getAttribute(Parser.TOKEN_VALUE)));
return;
case ID:
insertNode.addChild(new Id((String) tree
.getAttribute(Parser.TOKEN_VALUE)));
return;
default:// everything, which has no class member in its node uses
// the default.
}
} else if (symbol.isReservedTerminal()) {
Reserved res = symbol.asReservedTerminal();
switch (res) {
case EPSILON:
if (tree.getChildrenCount() == 1) {
toAST(tree.getChild(0));
} else {
// this should never occur
throw new SemanticException(
"Epsilon in other position than head?");
}
case SP:
// this should never occur
// throw new SemanticException("Stack pointer in parsetree?");
}
}
}
| public void toAST(ISyntaxTree tree, ISyntaxTree insertNode) {
Symbol symbol = translate(tree.getSymbol());
if (symbol.isNonTerminal()) {
NonTerminal nonT = symbol.asNonTerminal();
switch (nonT) {
case program:
AST = new Program();
toAST(tree.getChild(0), AST);
return;
case funcs:
for (int i = 0; i < tree.getChildrenCount(); i++) {
toAST(tree.getChild(i), insertNode);
}
return;
case func:
FuncDef func = new FuncDef();
for (int i = 0; i < tree.getChildrenCount(); i++) {
toAST(tree.getChild(i), func);
}
insertNode.addChild(func);
return;
case type:
if (translate(tree.getChild(0).getSymbol()).asTerminal() == TokenType.BASIC) {
// this is type_ and it must exist!
if (tree.getChild(1).getChildrenCount() != 0) {
Type array = new Array();
// the basic node gets added to this temporary node
// and is passed to the new array
// it doesn't matter which node to take as long as
// it is a treenode.
ISyntaxTree tmp = new Program();
toAST(tree.getChild(0), tmp);
array.addAttribute(LAttribute);
// this is already the BasicType node
boolean success = array.setAttribute(LAttribute,
tmp.getChild(0));
assert (success);
insertNode.addChild(array);
toAST(tree.getChild(1), array);
} else
// type_ is empty, hook the basic node in the parent
toAST(tree.getChild(0), insertNode);
} else { // we have a record! *CONGRATS*
Record record = new Record();
// test if we have an array of this record
if (tree.getChild(4).getChildrenCount() != 0) {
Type array = new Array();
toAST(tree.getChild(2), record); // <-- decls!!!
array.addAttribute(LAttribute);
array.setAttribute(LAttribute, record);
toAST(tree.getChild(4), array);
insertNode.addChild(array);
} else // this is simply one record
{
toAST(tree.getChild(2), record); // <-- decls!!!
insertNode.addChild(record);
}
}
return;
case type_:
// TODO: Width of array!!!
toAST(tree.getChild(1), insertNode);
if (tree.getChild(3).getChildrenCount() != 0) {
Array array = new Array();
array.addAttribute(LAttribute);
array.setAttribute(LAttribute,
insertNode.getAttribute(LAttribute));
toAST(tree.getChild(3), array);
insertNode.addChild(array);
} else // array declaration stopped here...
{
insertNode.addChild((ISyntaxTree) insertNode
.getAttribute(LAttribute));
}
return;
case optparams:
Params params = new Params();
for (int i = 0; i < tree.getChildrenCount(); i++) {
toAST(tree.getChild(i), params);
}
insertNode.addChild(params);
return;
case block:
Block block = new Block();
for (int i = 0; i < tree.getChildrenCount(); i++) {
toAST(tree.getChild(i), block);
}
if (block.getChildrenCount() != 0) {
insertNode.addChild(block);
} // else func_ -> ;
return;
case decl:
Declaration decl = new Declaration();
for (int i = 0; i < tree.getChildrenCount(); i++) {
toAST(tree.getChild(i), decl);
}
insertNode.addChild(decl);
return;
case stmt: {
Statement stmt = null;
ISyntaxTree firstChild = tree.getChild(0);
Symbol firstChildSymbol = translate(firstChild.getSymbol());
if (firstChildSymbol.isTerminal()) {
TokenType terminal = translate(firstChild.getSymbol())
.asTerminal();
if (terminal == TokenType.IF) {
ISyntaxTree stmt_ = tree.getChild(5); //
if (stmt_.getChildrenCount() == 0)
stmt = new If();
else
stmt = new IfElse();
} else if (terminal == TokenType.WHILE) {
stmt = new While();
} else if (terminal == TokenType.DO) {
stmt = new Do();
} else if (terminal == TokenType.BREAK) {
stmt = new Break();
} else if (terminal == TokenType.RETURN) {
stmt = new Return();
} else if (terminal == TokenType.PRINT) {
stmt = new Print();
}
} else if (firstChildSymbol.isNonTerminal()) {
toAST(firstChild, insertNode);
}
if (stmt != null) {
for (int i = 0; i < tree.getChildrenCount(); i++) {
toAST(tree.getChild(i), stmt);
}
insertNode.addChild(stmt);
}
return;
}
case assign:
case bool:
case join:
case equality:
case rel:
case expr:
case term:
if (tree.getChild(1).getChildrenCount() == 0) {
toAST(tree.getChild(0), insertNode);
} else {
BinaryOp bOp = new BinaryOp(translate(
tree.getChild(1).getChild(0).getSymbol())
.asTerminal());
// simply hang in both children trees
toAST(tree.getChild(0), bOp); // rel
toAST(tree.getChild(1), bOp); // equality'
insertNode.addChild(bOp);
}
return;
case expr_:
if (tree.getChildrenCount() != 0) {
// simply hang in both children trees
toAST(tree.getChild(1), insertNode);
toAST(tree.getChild(2), insertNode);
}
return;
case unary: {
Symbol firstChildSymbol = translate(tree.getChild(0)
.getSymbol());
if (firstChildSymbol.isNonTerminal()) {
toAST(tree.getChild(0), insertNode);
} else {
UnaryOp uOp = new UnaryOp(firstChildSymbol.asTerminal());
if (uOp != null) {
// simply hang in both children trees
toAST(tree.getChild(1), uOp); // unary
insertNode.addChild(uOp);
}
}
}
case factor:
if (translate(tree.getChild(0).getSymbol()).isNonTerminal()) {
if (tree.getChildrenCount() >= 2) {
if (tree.getChild(1).getChildrenCount() == 0) {
toAST(tree.getChild(0), insertNode);
} else {
FuncCall call = new FuncCall();
for (ISyntaxTree tmp : tree.getChildren()) {
toAST(tmp, call);
}
insertNode.addChild(call);
}
}
} else {
for (ISyntaxTree tmp : tree.getChildren()) {
toAST(tmp, insertNode);
}
}
return;
case factor_:
if (tree.getChild(1).getChildrenCount() != 0) {
Args args = new Args();
toAST(tree.getChild(1), args);
insertNode.addChild(args);
}
return;
case loc:
if (tree.getChild(1).getChildrenCount() == 0) {
toAST(tree.getChild(0), insertNode);
} else {
ISyntaxTree tmp = new Program();
toAST(tree.getChild(0), tmp);
tree.getChild(1).addAttribute(LAttribute);
// there is only one child (the id itself)!
tree.getChild(1).setAttribute(LAttribute, tmp.getChild(0));
toAST(tree.getChild(1), insertNode);
}
return;
case loc__:
tree.getChild(0).addAttribute(LAttribute);
tree.getChild(0).setAttribute(LAttribute,
tree.getAttribute(LAttribute));
if (tree.getChild(1).getChildrenCount() == 0) {
toAST(tree.getChild(0), insertNode);
} else {
ISyntaxTree tmp = new Program();
toAST(tree.getChild(0), tmp);
if (tmp.getChildrenCount() == 1) {
tree.getChild(1).addAttribute(LAttribute);
tree.getChild(1).setAttribute(LAttribute,
tmp.getChild(0));
toAST(tree.getChild(1), insertNode);
}
}
return;
case loc_:
// TODO: not everything is well thought atm...
if (translate(tree.getChild(0).getSymbol()).asTerminal() == TokenType.OP_DOT) {
RecordVarCall varCall = new RecordVarCall();
varCall.addChild((ISyntaxTree) tree
.getAttribute(LAttribute));
toAST(tree.getChild(1), varCall);
insertNode.addChild(varCall);
} else {
ArrayCall array = new ArrayCall();
toAST(tree.getChild(1), array);
array.addChild((ISyntaxTree) tree.getAttribute(LAttribute));
insertNode.addChild(array);
}
return;
// list of nodes which use the default case:
// assign_, bool_, decls, equality_, expr_, factor_,
// func_, join_,
// params, params_, rel_, stmt_, stmt__, stmts,
default:
// nothing to do here just pass it through
for (ISyntaxTree tmp : tree.getChildren()) {
toAST(tmp, insertNode);
}
}
} else if (symbol.isTerminal()) {
TokenType t = symbol.asTerminal();
switch (t) {
case BASIC:
BasicTokenType type = (BasicTokenType) tree
.getAttribute(Parser.TOKEN_VALUE);
insertNode.addChild(new BasicType(type));
return;
case INT_LITERAL:
insertNode.addChild(new IntLiteral((Integer) tree
.getAttribute(Parser.TOKEN_VALUE)));
return;
case STRING_LITERAL:
insertNode.addChild(new StringLiteral((String) tree
.getAttribute(Parser.TOKEN_VALUE)));
return;
case REAL_LITERAL:
insertNode.addChild(new RealLiteral((Double) tree
.getAttribute(Parser.TOKEN_VALUE)));
return;
case BOOL_LITERAL:
insertNode.addChild(new BoolLiteral((Boolean) tree
.getAttribute(Parser.TOKEN_VALUE)));
return;
case ID:
insertNode.addChild(new Id((String) tree
.getAttribute(Parser.TOKEN_VALUE)));
return;
default:// everything, which has no class member in its node uses
// the default.
}
} else if (symbol.isReservedTerminal()) {
Reserved res = symbol.asReservedTerminal();
switch (res) {
case EPSILON:
if (tree.getChildrenCount() == 1) {
toAST(tree.getChild(0));
} else {
// this should never occur
throw new SemanticException(
"Epsilon in other position than head?");
}
case SP:
// this should never occur
// throw new SemanticException("Stack pointer in parsetree?");
}
}
}
|
diff --git a/izpack-src/branches/3.10/src/lib/com/izforge/izpack/installer/GUIInstaller.java b/izpack-src/branches/3.10/src/lib/com/izforge/izpack/installer/GUIInstaller.java
index f0ad7484..fc7591e3 100644
--- a/izpack-src/branches/3.10/src/lib/com/izforge/izpack/installer/GUIInstaller.java
+++ b/izpack-src/branches/3.10/src/lib/com/izforge/izpack/installer/GUIInstaller.java
@@ -1,813 +1,819 @@
/*
* $Id$
* IzPack - Copyright 2001-2007 Julien Ponge, All Rights Reserved.
*
* http://www.izforge.com/izpack/
* http://developer.berlios.de/projects/izpack/
*
* 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.izforge.izpack.installer;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GraphicsEnvironment;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TreeMap;
import javax.swing.GrayFilter;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.ListCellRenderer;
import javax.swing.LookAndFeel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.plaf.metal.MetalLookAndFeel;
import javax.swing.plaf.metal.MetalTheme;
import com.izforge.izpack.GUIPrefs;
import com.izforge.izpack.LocaleDatabase;
import com.izforge.izpack.gui.ButtonFactory;
import com.izforge.izpack.gui.IzPackMetalTheme;
import com.izforge.izpack.gui.LabelFactory;
import com.izforge.izpack.util.Debug;
import com.izforge.izpack.util.OsVersion;
import com.izforge.izpack.util.VariableSubstitutor;
/**
* The IzPack graphical installer class.
*
* @author Julien Ponge
*/
public class GUIInstaller extends InstallerBase
{
/** The installation data. */
private InstallData installdata;
/** The L&F. */
protected String lnf;
/** defined modifier for language display type. */
private static final String[] LANGUAGE_DISPLAY_TYPES = { "iso3", "native", "default"};
private static final String[][] LANG_CODES = { { "cat", "ca"}, { "chn", "zh"}, { "cze", "cs"},
{ "dan", "da"}, { "deu", "de"}, { "eng", "en"}, { "fin", "fi"}, { "fra", "fr"},
{ "hun", "hu"}, { "ita", "it"}, { "jpn", "ja"}, { "mys", "ms"}, { "ned", "nl"},
{ "nor", "no"}, { "pol", "pl"}, { "por", "pt"}, { "rom", "or"}, { "rus", "ru"},
{ "spa", "es"}, { "svk", "sk"}, { "swe", "sv"}, { "tur", "tr"}, { "ukr", "uk"}};
/** holds language to ISO-3 language code translation */
private static HashMap isoTable;
/**
* The constructor.
*
* @exception Exception Description of the Exception
*/
public GUIInstaller() throws Exception
{
this.installdata = new InstallData();
// Loads the installation data
loadInstallData(installdata);
// add the GUI install data
loadGUIInstallData();
// Sets up the GUI L&F
loadLookAndFeel();
// Checks the Java version
checkJavaVersion();
// Loads the suitable langpack
SwingUtilities.invokeAndWait(new Runnable() {
public void run()
{
try
{
loadLangPack();
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
// create the resource manager (after the language selection!)
ResourceManager.create(this.installdata);
// Load custom langpack if exist.
addCustomLangpack(installdata);
// We launch the installer GUI
SwingUtilities.invokeLater(new Runnable() {
public void run()
{
try
{
loadGUI();
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
}
/**
* Load GUI preference information.
*
* @throws Exception
*/
public void loadGUIInstallData() throws Exception
{
InputStream in = GUIInstaller.class.getResourceAsStream("/GUIPrefs");
ObjectInputStream objIn = new ObjectInputStream(in);
this.installdata.guiPrefs = (GUIPrefs) objIn.readObject();
objIn.close();
}
/**
* Checks the Java version.
*
* @exception Exception Description of the Exception
*/
private void checkJavaVersion() throws Exception
{
String version = System.getProperty("java.version");
String required = this.installdata.info.getJavaVersion();
if (version.compareTo(required) < 0)
{
StringBuffer msg = new StringBuffer();
msg.append("The application that you are trying to install requires a ");
msg.append(required);
msg.append(" version or later of the Java platform.\n");
msg.append("You are running a ");
msg.append(version);
msg.append(" version of the Java platform.\n");
msg.append("Please upgrade to a newer version.");
System.out.println(msg.toString());
JOptionPane.showMessageDialog(null, msg.toString(), "Error", JOptionPane.ERROR_MESSAGE);
System.exit(1);
}
}
/**
* Loads the suitable langpack.
*
* @exception Exception Description of the Exception
*/
private void loadLangPack() throws Exception
{
// Initialisations
List availableLangPacks = getAvailableLangPacks();
int npacks = availableLangPacks.size();
if (npacks == 0) throw new Exception("no language pack available");
String selectedPack;
// Dummy Frame
JFrame frame = new JFrame();
frame.setIconImage(new ImageIcon(this.getClass().getResource("/img/JFrameIcon.png"))
.getImage());
Dimension frameSize = frame.getSize();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
frame.setLocation((screenSize.width - frameSize.width) / 2,
(screenSize.height - frameSize.height) / 2 - 10);
// We get the langpack name
if (npacks != 1)
{
LanguageDialog picker = new LanguageDialog(frame, availableLangPacks.toArray());
picker.setSelection(Locale.getDefault().getISO3Country().toLowerCase());
picker.setModal(true);
picker.toFront();
//frame.setVisible(true);
frame.setVisible(false);
picker.setVisible(true);
selectedPack = (String) picker.getSelection();
if (selectedPack == null) throw new Exception("installation canceled");
}
else
selectedPack = (String) availableLangPacks.get(0);
// We add an xml data information
this.installdata.xmlData.setAttribute("langpack", selectedPack);
// We load the langpack
installdata.localeISO3 = selectedPack;
installdata.setVariable(ScriptParser.ISO3_LANG, installdata.localeISO3);
InputStream in = getClass().getResourceAsStream("/langpacks/" + selectedPack + ".xml");
this.installdata.langpack = new LocaleDatabase(in);
}
/**
* Returns an ArrayList of the available langpacks ISO3 codes.
*
* @return The available langpacks list.
* @exception Exception Description of the Exception
*/
private List getAvailableLangPacks() throws Exception
{
// We read from the langpacks file in the jar
InputStream in = getClass().getResourceAsStream("/langpacks.info");
ObjectInputStream objIn = new ObjectInputStream(in);
List available = (List) objIn.readObject();
objIn.close();
return available;
}
/**
* Loads the suitable L&F.
*
* @exception Exception Description of the Exception
*/
protected void loadLookAndFeel() throws Exception
{
// Do we have any preference for this OS ?
String syskey = "unix";
if (OsVersion.IS_WINDOWS)
{
syskey = "windows";
}
else if (OsVersion.IS_OSX)
{
syskey = "mac";
}
String laf = null;
if (installdata.guiPrefs.lookAndFeelMapping.containsKey(syskey))
{
laf = (String) installdata.guiPrefs.lookAndFeelMapping.get(syskey);
}
// Let's use the system LAF
// Resolve whether button icons should be used or not.
boolean useButtonIcons = true;
if (installdata.guiPrefs.modifier.containsKey("useButtonIcons")
&& "no".equalsIgnoreCase((String) installdata.guiPrefs.modifier.get("useButtonIcons"))) useButtonIcons = false;
ButtonFactory.useButtonIcons(useButtonIcons);
boolean useLabelIcons = true;
if (installdata.guiPrefs.modifier.containsKey("useLabelIcons")
&& "no".equalsIgnoreCase((String) installdata.guiPrefs.modifier.get("useLabelIcons"))) useLabelIcons = false;
LabelFactory.setUseLabelIcons(useLabelIcons);
if (laf == null)
{
if (!"mac".equals(syskey))
{
+ // In Linux we will use the English locale, because of a bug in
+ // JRE6. In Korean, Persian, Chinese, japanese and some other
+ // locales the installer throws and exception and doesn't load
+ // at all. See http://jira.jboss.com/jira/browse/JBINSTALL-232.
+ // This is a workaround until this bug gets fixed.
+ if("unix".equals(syskey)) Locale.setDefault(Locale.ENGLISH);
String syslaf = UIManager.getSystemLookAndFeelClassName();
UIManager.setLookAndFeel(syslaf);
if (UIManager.getLookAndFeel() instanceof MetalLookAndFeel)
{
MetalLookAndFeel.setCurrentTheme(new IzPackMetalTheme());
ButtonFactory.useHighlightButtons();
// Reset the use button icons state because
// useHighlightButtons
// make it always true.
ButtonFactory.useButtonIcons(useButtonIcons);
installdata.buttonsHColor = new Color(182, 182, 204);
}
}
lnf = "swing";
return;
}
// Kunststoff (http://www.incors.org/)
if ("kunststoff".equals(laf))
{
ButtonFactory.useHighlightButtons();
// Reset the use button icons state because useHighlightButtons
// make it always true.
ButtonFactory.useButtonIcons(useButtonIcons);
installdata.buttonsHColor = new Color(255, 255, 255);
Class lafClass = Class.forName("com.incors.plaf.kunststoff.KunststoffLookAndFeel");
Class mtheme = Class.forName("javax.swing.plaf.metal.MetalTheme");
Class[] params = { mtheme};
Class theme = Class.forName("com.izforge.izpack.gui.IzPackKMetalTheme");
Method setCurrentThemeMethod = lafClass.getMethod("setCurrentTheme", params);
// We invoke and place Kunststoff as our L&F
LookAndFeel kunststoff = (LookAndFeel) lafClass.newInstance();
MetalTheme ktheme = (MetalTheme) theme.newInstance();
Object[] kparams = { ktheme};
UIManager.setLookAndFeel(kunststoff);
setCurrentThemeMethod.invoke(kunststoff, kparams);
lnf = "kunststoff";
return;
}
// Liquid (http://liquidlnf.sourceforge.net/)
if ("liquid".equals(laf))
{
UIManager.setLookAndFeel("com.birosoft.liquid.LiquidLookAndFeel");
lnf = "liquid";
Map params = (Map) installdata.guiPrefs.lookAndFeelParams.get(laf);
if (params.containsKey("decorate.frames"))
{
String value = (String) params.get("decorate.frames");
if ("yes".equals(value))
{
JFrame.setDefaultLookAndFeelDecorated(true);
}
}
if (params.containsKey("decorate.dialogs"))
{
String value = (String) params.get("decorate.dialogs");
if ("yes".equals(value))
{
JDialog.setDefaultLookAndFeelDecorated(true);
}
}
return;
}
// Metouia (http://mlf.sourceforge.net/)
if ("metouia".equals(laf))
{
UIManager.setLookAndFeel("net.sourceforge.mlf.metouia.MetouiaLookAndFeel");
lnf = "metouia";
return;
}
// JGoodies Looks (http://looks.dev.java.net/)
if ("looks".equals(laf))
{
Map variants = new TreeMap();
variants.put("extwin", "com.jgoodies.plaf.windows.ExtWindowsLookAndFeel");
variants.put("plastic", "com.jgoodies.plaf.plastic.PlasticLookAndFeel");
variants.put("plastic3D", "com.jgoodies.plaf.plastic.Plastic3DLookAndFeel");
variants.put("plasticXP", "com.jgoodies.plaf.plastic.PlasticXPLookAndFeel");
String variant = (String) variants.get("plasticXP");
Map params = (Map) installdata.guiPrefs.lookAndFeelParams.get(laf);
if (params.containsKey("variant"))
{
String param = (String) params.get("variant");
if (variants.containsKey(param))
{
variant = (String) variants.get(param);
}
}
UIManager.setLookAndFeel(variant);
}
}
/**
* Loads the GUI.
*
* @exception Exception Description of the Exception
*/
private void loadGUI() throws Exception
{
UIManager.put("OptionPane.yesButtonText", installdata.langpack.getString("installer.yes"));
UIManager.put("OptionPane.noButtonText", installdata.langpack.getString("installer.no"));
UIManager.put("OptionPane.cancelButtonText", installdata.langpack
.getString("installer.cancel"));
String title;
// Use a alternate message if defined.
final String key = "installer.reversetitle";
String message = installdata.langpack.getString(key);
// message equal to key -> no message defined.
if (message.indexOf(key) > -1)
title = installdata.langpack.getString("installer.title")
+ installdata.info.getAppName();
else
{ // Attention! The alternate message has to contain the hole message including
// $APP_NAME and may be $APP_VER.
VariableSubstitutor vs = new VariableSubstitutor(installdata.getVariables());
title = vs.substitute(message, null);
}
new InstallerFrame(title, this.installdata);
}
/**
* Returns whether flags should be used in the language selection dialog or not.
*
* @return whether flags should be used in the language selection dialog or not
*/
protected boolean useFlags()
{
if (installdata.guiPrefs.modifier.containsKey("useFlags")
&& "no".equalsIgnoreCase((String) installdata.guiPrefs.modifier.get("useFlags")))
return (false);
return (true);
}
/**
* Returns the type in which the language should be displayed in the language selction dialog.
* Possible are "iso3", "native" and "usingDefault".
*
* @return language display type
*/
protected String getLangType()
{
if (installdata.guiPrefs.modifier.containsKey("langDisplayType"))
{
String val = (String) installdata.guiPrefs.modifier.get("langDisplayType");
val = val.toLowerCase();
// Verify that the value is valid, else return the default.
for (int i = 0; i < LANGUAGE_DISPLAY_TYPES.length; ++i)
if (val.equalsIgnoreCase(LANGUAGE_DISPLAY_TYPES[i])) return (val);
Debug.trace("Value for language display type not valid; value: " + val);
}
return (LANGUAGE_DISPLAY_TYPES[0]);
}
/**
* Used to prompt the user for the language. Languages can be displayed in iso3 or the native
* notation or the notation of the default locale. Revising to native notation is based on code
* from Christian Murphy (patch #395).
*
* @author Julien Ponge
* @author Christian Murphy
* @author Klaus Bartz
*/
private final class LanguageDialog extends JDialog implements ActionListener
{
private static final long serialVersionUID = 3256443616359887667L;
/** The combo box. */
private JComboBox comboBox;
/** The ISO3 to ISO2 HashMap */
private HashMap iso3Toiso2 = null;
/** iso3Toiso2 expanded ? */
private boolean isoMapExpanded = false;
/**
* The constructor.
*
* @param items The items to display in the box.
*/
public LanguageDialog(JFrame frame, Object[] items)
{
super(frame);
try
{
loadLookAndFeel();
}
catch (Exception err)
{
err.printStackTrace();
}
// We build the GUI
addWindowListener(new WindowHandler());
JPanel contentPane = (JPanel) getContentPane();
setTitle("Language selection");
GridBagLayout layout = new GridBagLayout();
contentPane.setLayout(layout);
GridBagConstraints gbConstraints = new GridBagConstraints();
gbConstraints.anchor = GridBagConstraints.CENTER;
gbConstraints.insets = new Insets(5, 5, 5, 5);
gbConstraints.fill = GridBagConstraints.NONE;
gbConstraints.gridx = 0;
gbConstraints.weightx = 1.0;
gbConstraints.weighty = 1.0;
ImageIcon img = getImage();
JLabel imgLabel = new JLabel(img);
gbConstraints.gridy = 0;
contentPane.add(imgLabel);
gbConstraints.fill = GridBagConstraints.HORIZONTAL;
String firstMessage = "Please select your language";
if (getLangType().equals(LANGUAGE_DISPLAY_TYPES[0]))
// iso3
firstMessage = "Please select your language (ISO3 code)";
JLabel label1 = new JLabel(firstMessage, SwingConstants.CENTER);
gbConstraints.gridy = 1;
gbConstraints.insets = new Insets(5, 5, 0, 5);
layout.addLayoutComponent(label1, gbConstraints);
contentPane.add(label1);
JLabel label2 = new JLabel("for install instructions:", SwingConstants.CENTER);
gbConstraints.gridy = 2;
gbConstraints.insets = new Insets(0, 5, 5, 5);
layout.addLayoutComponent(label2, gbConstraints);
contentPane.add(label2);
gbConstraints.insets = new Insets(5, 5, 5, 5);
items = reviseItems(items);
comboBox = new JComboBox(items);
if (useFlags()) comboBox.setRenderer(new FlagRenderer());
gbConstraints.fill = GridBagConstraints.HORIZONTAL;
gbConstraints.gridy = 3;
layout.addLayoutComponent(comboBox, gbConstraints);
contentPane.add(comboBox);
JButton okButton = new JButton("OK");
okButton.addActionListener(this);
gbConstraints.fill = GridBagConstraints.NONE;
gbConstraints.gridy = 4;
gbConstraints.anchor = GridBagConstraints.CENTER;
layout.addLayoutComponent(okButton, gbConstraints);
contentPane.add(okButton);
getRootPane().setDefaultButton(okButton);
// Packs and centers
// Fix for bug "Installer won't show anything on OSX"
if (System.getProperty("mrj.version") == null)
pack();
else
setSize(getPreferredSize());
Dimension frameSize = getSize();
Point center = GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint();
setLocation(center.x - frameSize.width / 2,
center.y - frameSize.height / 2 - 10);
setResizable(true);
}
/**
* Revises iso3 language items depending on the language display type.
*
* @param items item array to be revised
* @return the revised array
*/
private Object[] reviseItems(Object[] items)
{
String langType = getLangType();
// iso3: nothing todo.
if (langType.equals(LANGUAGE_DISPLAY_TYPES[0])) return (items);
// native: get the names as they are written in that language.
if (langType.equals(LANGUAGE_DISPLAY_TYPES[1]))
return (expandItems(items, (new JComboBox()).getFont()));
// default: get the names as they are written in the default
// language.
if (langType.equals(LANGUAGE_DISPLAY_TYPES[2])) return (expandItems(items, null));
// Should never be.
return (items);
}
/**
* Expands the given iso3 codes to language names. If a testFont is given, the codes are
* tested whether they can displayed or not. If not, or no font given, the language name
* will be returned as written in the default language of this VM.
*
* @param items item array to be expanded to the language name
* @param testFont font to test wheter a name is displayable
* @return aray of expanded items
*/
private Object[] expandItems(Object[] items, Font testFont)
{
int i;
if (iso3Toiso2 == null)
{ // Loasd predefined langs into HashMap.
iso3Toiso2 = new HashMap(32);
isoTable = new HashMap();
for (i = 0; i < LANG_CODES.length; ++i)
iso3Toiso2.put(LANG_CODES[i][0], LANG_CODES[i][1]);
}
for (i = 0; i < items.length; i++)
{
Object it = expandItem(items[i], testFont);
isoTable.put(it, items[i]);
items[i] = it;
}
return items;
}
/**
* Expands the given iso3 code to a language name. If a testFont is given, the code will be
* tested whether it is displayable or not. If not, or no font given, the language name will
* be returned as written in the default language of this VM.
*
* @param item item to be expanded to the language name
* @param testFont font to test wheter the name is displayable
* @return expanded item
*/
private Object expandItem(Object item, Font testFont)
{
Object iso2Str = iso3Toiso2.get(item);
int i;
if (iso2Str == null && !isoMapExpanded)
{ // Expand iso3toiso2 only if needed because it needs some time.
isoMapExpanded = true;
Locale[] loc = Locale.getAvailableLocales();
for (i = 0; i < loc.length; ++i)
iso3Toiso2.put(loc[i].getISO3Language(), loc[i].getLanguage());
iso2Str = iso3Toiso2.get(item);
}
if (iso2Str == null)
// Unknown item, return it self.
return (item);
Locale locale = new Locale((String) iso2Str);
if (testFont == null)
// Return the language name in the spelling of the default locale.
return (locale.getDisplayLanguage());
// Get the language name in the spelling of that language.
String str = locale.getDisplayLanguage(locale);
int cdut = testFont.canDisplayUpTo(str);
if (cdut > -1)
// Test font cannot render it;
// use language name in the spelling of the default locale.
str = locale.getDisplayLanguage();
return (str);
}
/**
* Loads an image.
*
* @return The image icon.
*/
public ImageIcon getImage()
{
ImageIcon img;
try
{
img = new ImageIcon(LanguageDialog.class.getResource("/res/installer.langsel.img"));
}
catch (NullPointerException err)
{
img = null;
}
return img;
}
/**
* Gets the selected object.
*
* @return The selected item.
*/
public Object getSelection()
{
Object retval = null;
if (isoTable != null) retval = isoTable.get(comboBox.getSelectedItem());
return (retval != null) ? retval : comboBox.getSelectedItem();
}
/**
* Sets the selection.
*
* @param item The item to be selected.
*/
public void setSelection(Object item)
{
Object mapped = null;
if (isoTable != null)
{
Iterator iter = isoTable.keySet().iterator();
while (iter.hasNext())
{
Object key = iter.next();
if (isoTable.get(key).equals(item))
{
mapped = key;
break;
}
}
}
if (mapped == null) mapped = item;
comboBox.setSelectedItem(mapped);
}
/**
* Closer.
*
* @param e The event.
*/
public void actionPerformed(ActionEvent e)
{
dispose();
}
/**
* The window events handler.
*
* @author Julien Ponge
*/
private class WindowHandler extends WindowAdapter
{
/**
* We can't avoid the exit here, so don't call exit anywhere else.
*
* @param e the event.
*/
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
}
/**
* A list cell renderer that adds the flags on the display.
*
* @author Julien Ponge
*/
private static class FlagRenderer extends JLabel implements ListCellRenderer
{
private static final long serialVersionUID = 3832899961942782769L;
/** Icons cache. */
private TreeMap icons = new TreeMap();
/** Grayed icons cache. */
private TreeMap grayIcons = new TreeMap();
public FlagRenderer()
{
setOpaque(true);
}
/**
* Returns a suitable cell.
*
* @param list The list.
* @param value The object.
* @param index The index.
* @param isSelected true if it is selected.
* @param cellHasFocus Description of the Parameter
* @return The cell.
*/
public Component getListCellRendererComponent(JList list, Object value, int index,
boolean isSelected, boolean cellHasFocus)
{
// We put the label
String iso3 = (String) value;
setText(iso3);
if (isoTable != null) iso3 = (String) isoTable.get(iso3);
if (isSelected)
{
setForeground(list.getSelectionForeground());
setBackground(list.getSelectionBackground());
}
else
{
setForeground(list.getForeground());
setBackground(list.getBackground());
}
// We put the icon
if (!icons.containsKey(iso3))
{
ImageIcon icon;
icon = new ImageIcon(this.getClass().getResource("/res/flag." + iso3));
icons.put(iso3, icon);
icon = new ImageIcon(GrayFilter.createDisabledImage(icon.getImage()));
grayIcons.put(iso3, icon);
}
if (isSelected || index == -1)
setIcon((ImageIcon) icons.get(iso3));
else
setIcon((ImageIcon) grayIcons.get(iso3));
// We return
return this;
}
}
}
| true | true | protected void loadLookAndFeel() throws Exception
{
// Do we have any preference for this OS ?
String syskey = "unix";
if (OsVersion.IS_WINDOWS)
{
syskey = "windows";
}
else if (OsVersion.IS_OSX)
{
syskey = "mac";
}
String laf = null;
if (installdata.guiPrefs.lookAndFeelMapping.containsKey(syskey))
{
laf = (String) installdata.guiPrefs.lookAndFeelMapping.get(syskey);
}
// Let's use the system LAF
// Resolve whether button icons should be used or not.
boolean useButtonIcons = true;
if (installdata.guiPrefs.modifier.containsKey("useButtonIcons")
&& "no".equalsIgnoreCase((String) installdata.guiPrefs.modifier.get("useButtonIcons"))) useButtonIcons = false;
ButtonFactory.useButtonIcons(useButtonIcons);
boolean useLabelIcons = true;
if (installdata.guiPrefs.modifier.containsKey("useLabelIcons")
&& "no".equalsIgnoreCase((String) installdata.guiPrefs.modifier.get("useLabelIcons"))) useLabelIcons = false;
LabelFactory.setUseLabelIcons(useLabelIcons);
if (laf == null)
{
if (!"mac".equals(syskey))
{
String syslaf = UIManager.getSystemLookAndFeelClassName();
UIManager.setLookAndFeel(syslaf);
if (UIManager.getLookAndFeel() instanceof MetalLookAndFeel)
{
MetalLookAndFeel.setCurrentTheme(new IzPackMetalTheme());
ButtonFactory.useHighlightButtons();
// Reset the use button icons state because
// useHighlightButtons
// make it always true.
ButtonFactory.useButtonIcons(useButtonIcons);
installdata.buttonsHColor = new Color(182, 182, 204);
}
}
lnf = "swing";
return;
}
// Kunststoff (http://www.incors.org/)
if ("kunststoff".equals(laf))
{
ButtonFactory.useHighlightButtons();
// Reset the use button icons state because useHighlightButtons
// make it always true.
ButtonFactory.useButtonIcons(useButtonIcons);
installdata.buttonsHColor = new Color(255, 255, 255);
Class lafClass = Class.forName("com.incors.plaf.kunststoff.KunststoffLookAndFeel");
Class mtheme = Class.forName("javax.swing.plaf.metal.MetalTheme");
Class[] params = { mtheme};
Class theme = Class.forName("com.izforge.izpack.gui.IzPackKMetalTheme");
Method setCurrentThemeMethod = lafClass.getMethod("setCurrentTheme", params);
// We invoke and place Kunststoff as our L&F
LookAndFeel kunststoff = (LookAndFeel) lafClass.newInstance();
MetalTheme ktheme = (MetalTheme) theme.newInstance();
Object[] kparams = { ktheme};
UIManager.setLookAndFeel(kunststoff);
setCurrentThemeMethod.invoke(kunststoff, kparams);
lnf = "kunststoff";
return;
}
// Liquid (http://liquidlnf.sourceforge.net/)
if ("liquid".equals(laf))
{
UIManager.setLookAndFeel("com.birosoft.liquid.LiquidLookAndFeel");
lnf = "liquid";
Map params = (Map) installdata.guiPrefs.lookAndFeelParams.get(laf);
if (params.containsKey("decorate.frames"))
{
String value = (String) params.get("decorate.frames");
if ("yes".equals(value))
{
JFrame.setDefaultLookAndFeelDecorated(true);
}
}
if (params.containsKey("decorate.dialogs"))
{
String value = (String) params.get("decorate.dialogs");
if ("yes".equals(value))
{
JDialog.setDefaultLookAndFeelDecorated(true);
}
}
return;
}
// Metouia (http://mlf.sourceforge.net/)
if ("metouia".equals(laf))
{
UIManager.setLookAndFeel("net.sourceforge.mlf.metouia.MetouiaLookAndFeel");
lnf = "metouia";
return;
}
// JGoodies Looks (http://looks.dev.java.net/)
if ("looks".equals(laf))
{
Map variants = new TreeMap();
variants.put("extwin", "com.jgoodies.plaf.windows.ExtWindowsLookAndFeel");
variants.put("plastic", "com.jgoodies.plaf.plastic.PlasticLookAndFeel");
variants.put("plastic3D", "com.jgoodies.plaf.plastic.Plastic3DLookAndFeel");
variants.put("plasticXP", "com.jgoodies.plaf.plastic.PlasticXPLookAndFeel");
String variant = (String) variants.get("plasticXP");
Map params = (Map) installdata.guiPrefs.lookAndFeelParams.get(laf);
if (params.containsKey("variant"))
{
String param = (String) params.get("variant");
if (variants.containsKey(param))
{
variant = (String) variants.get(param);
}
}
UIManager.setLookAndFeel(variant);
}
}
| protected void loadLookAndFeel() throws Exception
{
// Do we have any preference for this OS ?
String syskey = "unix";
if (OsVersion.IS_WINDOWS)
{
syskey = "windows";
}
else if (OsVersion.IS_OSX)
{
syskey = "mac";
}
String laf = null;
if (installdata.guiPrefs.lookAndFeelMapping.containsKey(syskey))
{
laf = (String) installdata.guiPrefs.lookAndFeelMapping.get(syskey);
}
// Let's use the system LAF
// Resolve whether button icons should be used or not.
boolean useButtonIcons = true;
if (installdata.guiPrefs.modifier.containsKey("useButtonIcons")
&& "no".equalsIgnoreCase((String) installdata.guiPrefs.modifier.get("useButtonIcons"))) useButtonIcons = false;
ButtonFactory.useButtonIcons(useButtonIcons);
boolean useLabelIcons = true;
if (installdata.guiPrefs.modifier.containsKey("useLabelIcons")
&& "no".equalsIgnoreCase((String) installdata.guiPrefs.modifier.get("useLabelIcons"))) useLabelIcons = false;
LabelFactory.setUseLabelIcons(useLabelIcons);
if (laf == null)
{
if (!"mac".equals(syskey))
{
// In Linux we will use the English locale, because of a bug in
// JRE6. In Korean, Persian, Chinese, japanese and some other
// locales the installer throws and exception and doesn't load
// at all. See http://jira.jboss.com/jira/browse/JBINSTALL-232.
// This is a workaround until this bug gets fixed.
if("unix".equals(syskey)) Locale.setDefault(Locale.ENGLISH);
String syslaf = UIManager.getSystemLookAndFeelClassName();
UIManager.setLookAndFeel(syslaf);
if (UIManager.getLookAndFeel() instanceof MetalLookAndFeel)
{
MetalLookAndFeel.setCurrentTheme(new IzPackMetalTheme());
ButtonFactory.useHighlightButtons();
// Reset the use button icons state because
// useHighlightButtons
// make it always true.
ButtonFactory.useButtonIcons(useButtonIcons);
installdata.buttonsHColor = new Color(182, 182, 204);
}
}
lnf = "swing";
return;
}
// Kunststoff (http://www.incors.org/)
if ("kunststoff".equals(laf))
{
ButtonFactory.useHighlightButtons();
// Reset the use button icons state because useHighlightButtons
// make it always true.
ButtonFactory.useButtonIcons(useButtonIcons);
installdata.buttonsHColor = new Color(255, 255, 255);
Class lafClass = Class.forName("com.incors.plaf.kunststoff.KunststoffLookAndFeel");
Class mtheme = Class.forName("javax.swing.plaf.metal.MetalTheme");
Class[] params = { mtheme};
Class theme = Class.forName("com.izforge.izpack.gui.IzPackKMetalTheme");
Method setCurrentThemeMethod = lafClass.getMethod("setCurrentTheme", params);
// We invoke and place Kunststoff as our L&F
LookAndFeel kunststoff = (LookAndFeel) lafClass.newInstance();
MetalTheme ktheme = (MetalTheme) theme.newInstance();
Object[] kparams = { ktheme};
UIManager.setLookAndFeel(kunststoff);
setCurrentThemeMethod.invoke(kunststoff, kparams);
lnf = "kunststoff";
return;
}
// Liquid (http://liquidlnf.sourceforge.net/)
if ("liquid".equals(laf))
{
UIManager.setLookAndFeel("com.birosoft.liquid.LiquidLookAndFeel");
lnf = "liquid";
Map params = (Map) installdata.guiPrefs.lookAndFeelParams.get(laf);
if (params.containsKey("decorate.frames"))
{
String value = (String) params.get("decorate.frames");
if ("yes".equals(value))
{
JFrame.setDefaultLookAndFeelDecorated(true);
}
}
if (params.containsKey("decorate.dialogs"))
{
String value = (String) params.get("decorate.dialogs");
if ("yes".equals(value))
{
JDialog.setDefaultLookAndFeelDecorated(true);
}
}
return;
}
// Metouia (http://mlf.sourceforge.net/)
if ("metouia".equals(laf))
{
UIManager.setLookAndFeel("net.sourceforge.mlf.metouia.MetouiaLookAndFeel");
lnf = "metouia";
return;
}
// JGoodies Looks (http://looks.dev.java.net/)
if ("looks".equals(laf))
{
Map variants = new TreeMap();
variants.put("extwin", "com.jgoodies.plaf.windows.ExtWindowsLookAndFeel");
variants.put("plastic", "com.jgoodies.plaf.plastic.PlasticLookAndFeel");
variants.put("plastic3D", "com.jgoodies.plaf.plastic.Plastic3DLookAndFeel");
variants.put("plasticXP", "com.jgoodies.plaf.plastic.PlasticXPLookAndFeel");
String variant = (String) variants.get("plasticXP");
Map params = (Map) installdata.guiPrefs.lookAndFeelParams.get(laf);
if (params.containsKey("variant"))
{
String param = (String) params.get("variant");
if (variants.containsKey(param))
{
variant = (String) variants.get(param);
}
}
UIManager.setLookAndFeel(variant);
}
}
|
diff --git a/src/main/java/com/jcabi/dynamodb/maven/plugin/Instances.java b/src/main/java/com/jcabi/dynamodb/maven/plugin/Instances.java
index 1dcbf0f..2e387ec 100644
--- a/src/main/java/com/jcabi/dynamodb/maven/plugin/Instances.java
+++ b/src/main/java/com/jcabi/dynamodb/maven/plugin/Instances.java
@@ -1,142 +1,146 @@
/**
* Copyright (c) 2012-2013, JCabi.com
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met: 1) Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer. 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution. 3) Neither the name of the jcabi.com 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.
*/
package com.jcabi.dynamodb.maven.plugin;
import com.jcabi.aspects.Loggable;
import com.jcabi.log.VerboseProcess;
import com.jcabi.log.VerboseRunnable;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import javax.validation.constraints.NotNull;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.codehaus.plexus.util.FileUtils;
import org.rauschig.jarchivelib.ArchiveFormat;
import org.rauschig.jarchivelib.Archiver;
import org.rauschig.jarchivelib.ArchiverFactory;
import org.rauschig.jarchivelib.CompressionType;
/**
* Running instances of DynamoDB Local.
*
* @author Yegor Bugayenko ([email protected])
* @version $Id$
* @since 0.1
* @see <a href="http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Tools.html">DynamoDB Local</a>
*/
@ToString
@EqualsAndHashCode(of = "processes")
@Loggable(Loggable.INFO)
@SuppressWarnings("PMD.DoNotUseThreads")
final class Instances {
/**
* Directory where to run.
*/
private final transient File dir;
/**
* Running processes.
*/
private final transient ConcurrentMap<Integer, Process> processes =
new ConcurrentHashMap<Integer, Process>(0);
/**
* Public ctor.
* @param tgz Path to DynamoDBLocal.zip
* @param temp Temp directory to unpack TGZ into
* @throws IOException If fails
*/
protected Instances(@NotNull final File tgz,
@NotNull final File temp) throws IOException {
FileUtils.deleteDirectory(temp);
temp.mkdirs();
final Archiver archiver = ArchiverFactory.createArchiver(
ArchiveFormat.TAR, CompressionType.GZIP
);
archiver.extract(tgz, temp);
this.dir = temp.listFiles()[0];
}
/**
* Start a new one at this port.
* @param port The port to start at
* @throws IOException If fails to start
*/
public void start(final int port) throws IOException {
final Process proc = new ProcessBuilder().command(
new String[] {
String.format(
"%s%sbin%<sjava",
System.getProperty("java.home"),
System.getProperty("file.separator")
),
+ String.format(
+ "-Djava.library.path=%s",
+ this.dir.getAbsolutePath()
+ ),
"-jar",
- new File(this.dir, "DynamoDBLocal.jar").getAbsolutePath(),
+ "DynamoDBLocal.jar",
"--port",
Integer.toString(port),
}
- ).directory(Instances.this.dir).redirectErrorStream(true).start();
+ ).directory(this.dir).redirectErrorStream(true).start();
final Thread thread = new Thread(
new VerboseRunnable(
new Callable<Void>() {
@Override
public Void call() throws Exception {
new VerboseProcess(proc).stdout();
return null;
}
}
)
);
thread.setDaemon(true);
thread.start();
this.processes.put(port, proc);
}
/**
* Stop a running one at this port.
* @param port The port to stop at
*/
public void stop(final int port) {
final Process proc = this.processes.get(port);
if (proc == null) {
throw new IllegalArgumentException(
String.format(
"No DynamoDB Local instances running on port %d", port
)
);
}
proc.destroy();
}
}
| false | true | public void start(final int port) throws IOException {
final Process proc = new ProcessBuilder().command(
new String[] {
String.format(
"%s%sbin%<sjava",
System.getProperty("java.home"),
System.getProperty("file.separator")
),
"-jar",
new File(this.dir, "DynamoDBLocal.jar").getAbsolutePath(),
"--port",
Integer.toString(port),
}
).directory(Instances.this.dir).redirectErrorStream(true).start();
final Thread thread = new Thread(
new VerboseRunnable(
new Callable<Void>() {
@Override
public Void call() throws Exception {
new VerboseProcess(proc).stdout();
return null;
}
}
)
);
thread.setDaemon(true);
thread.start();
this.processes.put(port, proc);
}
| public void start(final int port) throws IOException {
final Process proc = new ProcessBuilder().command(
new String[] {
String.format(
"%s%sbin%<sjava",
System.getProperty("java.home"),
System.getProperty("file.separator")
),
String.format(
"-Djava.library.path=%s",
this.dir.getAbsolutePath()
),
"-jar",
"DynamoDBLocal.jar",
"--port",
Integer.toString(port),
}
).directory(this.dir).redirectErrorStream(true).start();
final Thread thread = new Thread(
new VerboseRunnable(
new Callable<Void>() {
@Override
public Void call() throws Exception {
new VerboseProcess(proc).stdout();
return null;
}
}
)
);
thread.setDaemon(true);
thread.start();
this.processes.put(port, proc);
}
|
diff --git a/Compiler/tst/cs444/acceptance/TestHelper.java b/Compiler/tst/cs444/acceptance/TestHelper.java
index 999365e9..bc48c13b 100644
--- a/Compiler/tst/cs444/acceptance/TestHelper.java
+++ b/Compiler/tst/cs444/acceptance/TestHelper.java
@@ -1,193 +1,193 @@
package cs444.acceptance;
import static org.junit.Assert.assertEquals;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.Map.Entry;
import cs444.Compiler;
import cs444.CompilerSettings;
import cs444.codegen.CodeGenVisitor;
import cs444.codegen.Platform;
import cs444.codegen.tiles.TileSet;
import cs444.types.APkgClassResolver;
import cs444.types.PkgClassInfo;
import cs444.types.PkgClassResolver;
public class TestHelper {
private static ITestCallbacks callbacks;
private static boolean outputAsmFiles;
private static Set<Platform<?, ?>> platforms;
public static final String TEST_LOCATION = Compiler.BASE_DIRECTORY + "JoosPrograms/";
//Holds stdlib so that it can be reused
private static boolean hasStdlib = false;
private static Map<String, Map<String, PkgClassResolver>> nameSpaces;
private static Map<String, APkgClassResolver> symbolMap;
private static List<APkgClassResolver> pkgs;
public static void assertReturnCodeForFiles(final String path, final int expectedReturnCode, final boolean printErrors, final boolean includeStdLib,
final boolean outputAsmFiles, final List<String> ignoreList, final ITestCallbacks testCallbacks) throws IOException, InterruptedException {
TestHelper.callbacks = testCallbacks;
TestHelper.outputAsmFiles = outputAsmFiles;
final File folder = new File(path);
int totalTests = 0;
int filesSkipped = 0;
final List<String> failFiles = new ArrayList<String>();
for (final File file : folder.listFiles()) {
final String fileName = file.getName();
// Use this line to test a single file
- //if (!fileName.equals("ArithProgram")) continue;
+ //if (!fileName.equals("DivZero")) continue;
//Use this line to stop when there are infinite loops
//if(totalTests == 20) break;
if (ignoreList.contains(fileName)){
System.out.print("*"); // skip file
filesSkipped++;
continue;
}
if (file.isFile() && fileName.toLowerCase().endsWith(".java") ||
(file.isDirectory() && !fileName.toLowerCase().endsWith(".skip"))){
runTestCase(path, expectedReturnCode, printErrors, includeStdLib, failFiles, file, fileName);
totalTests++;
} else {
System.out.print("*"); // skip file
filesSkipped++;
}
}
printSummary(totalTests, filesSkipped, failFiles);
final int failures = failFiles.size();
assertEquals("Unexpected return code compiling or running " + failures + " files. Expected return code was: " + expectedReturnCode, 0, failures);
}
private static void runTestCase(final String path, final int expectedReturnCode,
final boolean printErrors, final boolean includeStdLib, final List<String> failFiles,
final File file, final String fileName) throws IOException, InterruptedException {
final List<String> sourceFiles = getAllFiles(file);
final String[] array = new String[sourceFiles.size()];
sourceFiles.toArray(array);
if (!(callbacks.beforeCompile(file)
&& compileAndTest(array, printErrors, includeStdLib) == expectedReturnCode
&& callbacks.afterCompile(file, platforms))) {
failFiles.add(path + fileName);
}
}
public static void assertReturnCodeForFiles(final String path, final int expectedReturnCode, final boolean printErrors, final boolean includeStdLib,
final List<String> ignoreList) throws IOException, InterruptedException {
assertReturnCodeForFiles(path, expectedReturnCode, printErrors, includeStdLib, false, ignoreList, new EmptyCallbacks());
}
public static void assertReturnCodeForFiles(final String path, final int expectedReturnCode, final boolean printErrors) throws IOException, InterruptedException {
assertReturnCodeForFiles(path, expectedReturnCode, printErrors, true);
}
public static void assertReturnCodeForFiles(final String path, final int expectedReturnCode, final boolean printErrors, final boolean includeStdLib)
throws IOException, InterruptedException {
assertReturnCodeForFiles(path, expectedReturnCode, printErrors, includeStdLib, Collections.<String>emptyList());
}
public static void assertReturnCodeForFiles(final String path,
final int expectedReturnCode, final boolean printErrors, final List<String> ignoreList) throws IOException, InterruptedException {
assertReturnCodeForFiles(path, expectedReturnCode, printErrors, true, ignoreList);
}
private static List<String> getAllFiles(final File root) {
final ArrayList<String> result = new ArrayList<String>();
final Stack<File> toVisit = new Stack<File>();
toVisit.push(root);
while (!toVisit.isEmpty()) {
final File currentFile = toVisit.pop();
if (currentFile.isFile()) {
final String fileName = currentFile.getAbsolutePath();
if (fileName.endsWith(".java"))
if(fileName.endsWith("Main.java"))result.add(0, fileName);
else result.add(fileName);
} else if (currentFile.isDirectory()) {
for (final File sourceFile : currentFile.listFiles())
toVisit.push(sourceFile);
}
}
return result;
}
private static void printSummary(final int totalTests, final int filesSkipped, final List<String> failFiles) {
System.out.println("\nNumber of tests: " + totalTests);
if(filesSkipped > 0) System.out.println("Number of files skipped: " + filesSkipped);
if (failFiles.size() != 0){
System.out.println("Failed " + failFiles.size());
for (final String fileName: failFiles) {
System.out.println("\t" + fileName);
}
}
}
public static void setupMaps(){
if(!hasStdlib){
PkgClassInfo.instance.clear();
PkgClassResolver.reset();
TileSet.reset();
CodeGenVisitor.reset();
final List<String> files = getAllFiles(new File(TEST_LOCATION + "StdLib"));
platforms = new HashSet<>();
final Set<String> opts = Collections.emptySet();
for(final String platformStr : Compiler.defaultPlatforms){
platforms.add(CompilerSettings.platformMap.get(platformStr).getPlatform(opts));
}
Compiler.compile(files, true, false, platforms);
final PkgClassInfo info = PkgClassInfo.instance;
nameSpaces = new HashMap<>();
//because each entry is a map, we need to clone the maps or they will have entries put into them.
for(final Entry<String, Map<String, PkgClassResolver>> entry : info.nameSpaces.entrySet()){
final Map<String, PkgClassResolver> resolverClone = new HashMap<>(entry.getValue());
nameSpaces.put(entry.getKey(), resolverClone);
}
symbolMap = new HashMap<>(info.symbolMap);
pkgs = new ArrayList<>(info.pkgs);
hasStdlib = true;
}
}
private static int compileAndTest(final String[] files, final boolean printErrors, final boolean includeStdlib)
throws IOException, InterruptedException {
if(includeStdlib){
setupMaps();
PkgClassInfo.instance.clear(nameSpaces, symbolMap, pkgs);
}else{
PkgClassInfo.instance.clear();
}
PkgClassResolver.reset();
TileSet.reset();
CodeGenVisitor.reset();
final Set<String> opts = Collections.emptySet();
platforms = new HashSet<>();
for(final String platformStr : Compiler.defaultPlatforms){
platforms.add(CompilerSettings.platformMap.get(platformStr).getPlatform(opts));
}
return Compiler.compile(Arrays.asList(files), printErrors, TestHelper.outputAsmFiles, platforms);
}
}
| true | true | public static void assertReturnCodeForFiles(final String path, final int expectedReturnCode, final boolean printErrors, final boolean includeStdLib,
final boolean outputAsmFiles, final List<String> ignoreList, final ITestCallbacks testCallbacks) throws IOException, InterruptedException {
TestHelper.callbacks = testCallbacks;
TestHelper.outputAsmFiles = outputAsmFiles;
final File folder = new File(path);
int totalTests = 0;
int filesSkipped = 0;
final List<String> failFiles = new ArrayList<String>();
for (final File file : folder.listFiles()) {
final String fileName = file.getName();
// Use this line to test a single file
//if (!fileName.equals("ArithProgram")) continue;
//Use this line to stop when there are infinite loops
//if(totalTests == 20) break;
if (ignoreList.contains(fileName)){
System.out.print("*"); // skip file
filesSkipped++;
continue;
}
if (file.isFile() && fileName.toLowerCase().endsWith(".java") ||
(file.isDirectory() && !fileName.toLowerCase().endsWith(".skip"))){
runTestCase(path, expectedReturnCode, printErrors, includeStdLib, failFiles, file, fileName);
totalTests++;
} else {
System.out.print("*"); // skip file
filesSkipped++;
}
}
printSummary(totalTests, filesSkipped, failFiles);
final int failures = failFiles.size();
assertEquals("Unexpected return code compiling or running " + failures + " files. Expected return code was: " + expectedReturnCode, 0, failures);
}
| public static void assertReturnCodeForFiles(final String path, final int expectedReturnCode, final boolean printErrors, final boolean includeStdLib,
final boolean outputAsmFiles, final List<String> ignoreList, final ITestCallbacks testCallbacks) throws IOException, InterruptedException {
TestHelper.callbacks = testCallbacks;
TestHelper.outputAsmFiles = outputAsmFiles;
final File folder = new File(path);
int totalTests = 0;
int filesSkipped = 0;
final List<String> failFiles = new ArrayList<String>();
for (final File file : folder.listFiles()) {
final String fileName = file.getName();
// Use this line to test a single file
//if (!fileName.equals("DivZero")) continue;
//Use this line to stop when there are infinite loops
//if(totalTests == 20) break;
if (ignoreList.contains(fileName)){
System.out.print("*"); // skip file
filesSkipped++;
continue;
}
if (file.isFile() && fileName.toLowerCase().endsWith(".java") ||
(file.isDirectory() && !fileName.toLowerCase().endsWith(".skip"))){
runTestCase(path, expectedReturnCode, printErrors, includeStdLib, failFiles, file, fileName);
totalTests++;
} else {
System.out.print("*"); // skip file
filesSkipped++;
}
}
printSummary(totalTests, filesSkipped, failFiles);
final int failures = failFiles.size();
assertEquals("Unexpected return code compiling or running " + failures + " files. Expected return code was: " + expectedReturnCode, 0, failures);
}
|
diff --git a/prototype/face/src/main/java/com/lisasoft/face/data/FaceDAO.java b/prototype/face/src/main/java/com/lisasoft/face/data/FaceDAO.java
index 5d77cc5..14215f0 100644
--- a/prototype/face/src/main/java/com/lisasoft/face/data/FaceDAO.java
+++ b/prototype/face/src/main/java/com/lisasoft/face/data/FaceDAO.java
@@ -1,271 +1,271 @@
/**
* GeoTools Example
*
* (C) 2011 LISAsoft
*
* 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; version 2.1 of the License.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*/
package com.lisasoft.face.data;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import javax.swing.event.EventListenerList;
import org.geotools.data.csv.CSVDataStore;
import org.geotools.geometry.jts.JTSFactoryFinder;
import org.opengis.feature.simple.SimpleFeature;
import com.csvreader.CsvReader;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.Point;
/**
* This is a little mock up of a traditional data acecss object.
* <p>
* Internally this just reads a CSV file and creates objects. This is used to show how we can wrap
* up an object as a feature for visual display.
*
* @author Jody Garnett (LISAsoft)
*/
public class FaceDAO {
/**
* Change this to match the EPSG code for your spatial reference system.
*
* See: http://spatialreference.org/ref/?search=ch1903
*/
public static String EPSG_CODE = "EPSG:2056";
static GeometryFactory gf = JTSFactoryFinder.getGeometryFactory(null);
/**
* This represents the contents - use CopyOnWriteArrayList to account for concurrent access
*/
private CopyOnWriteArrayList<FaceImpl> contents;
/**
* This is a global list allowing outside party to listen to all of the java beans.
*/
EventListenerList listeners = null;
/**
* Used to watch the contents of the FaceImpls; the resulting event can be used to update a
* DataStore or MapComponent in the event something changes.
*/
private PropertyChangeListener watcher = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
firePropertyChange(evt);
}
};
public FaceDAO(List<FaceImpl> faceList) throws IOException {
contents = new CopyOnWriteArrayList<FaceImpl>(faceList);
}
/** Hook up watcher to beans contained; any changes
* should be passed on as feature events to the GIS; or listeners etc...
*/
protected void listen( boolean listen ){
if( listen ){
for( FaceImpl face : contents ){
face.addPropertyChangeListener(watcher);
}
}
else {
for( FaceImpl face : contents ){
face.removePropertyChangeListener(watcher);
}
}
}
/**
* Listen to all of the java beans managed by this data access object.
* @param listener
*/
synchronized public void addPropertyChangeListener(PropertyChangeListener listener) {
if (listeners == null) {
listeners = new EventListenerList();
listen( true );
}
listeners.add(PropertyChangeListener.class, listener);
}
/**
* Remove a listener from the java beans managed by this data access object.
* @param listener
*/
synchronized public void removePropertyChangeListener(PropertyChangeListener listener) {
if (listeners == null)
return;
listeners.remove(PropertyChangeListener.class, listener);
if( listeners.getListenerCount(PropertyChangeListener.class) == 0 ){
listen( false );
}
}
/**
* Used to notify any PropertyChange listeners that a specific face has changed.
* <p>
* event.getSource() is the Face that has changed
*
* @param evt
*/
synchronized protected void firePropertyChange(PropertyChangeEvent evt) {
for (PropertyChangeListener listener : listeners.getListeners(PropertyChangeListener.class)) {
try {
listener.propertyChange(evt);
} catch (Throwable t) {
System.err.println("Unable to deliver property change event to " + t);
t.printStackTrace(System.err);
}
}
}
public FaceDAO(File csvFile) throws IOException {
contents = new CopyOnWriteArrayList<FaceImpl>(load(csvFile));
}
static Point getLocation(Face face) {
double x = face.getWestOstKoordinate().doubleValue();
double y = face.getSuedNordKoordinate().doubleValue();
Coordinate coordinate = new Coordinate(x, y);
return gf.createPoint(coordinate);
}
/** Thread-safe access to the data objects */
public CopyOnWriteArrayList<FaceImpl> contents() {
return contents;
}
/**
* Look up face with the provided nummber/identifier. This is used to sort out selection
* when a selection is made from the GIS.
*
* @param nummber
* @return Face, or null if not found
*/
FaceImpl lookup(long nummber) {
for (FaceImpl face : contents) {
if (nummber == face.getNummer()) {
return face; // found!
}
}
return null;
}
/**
* Look up face with the provided nummber/identifier. This is used to sort out selection
* when a selection is made from the GIS.
*
* @param nummber
* @return Face, or null if not found
*/
List<FaceImpl> lookup(long nummbers[]) {
Set<Long> lookup = new HashSet<Long>();
for( Long nummber : nummbers ){
lookup.add( nummber );
}
List<FaceImpl> found = new ArrayList<FaceImpl>();
for (FaceImpl face : contents) {
if (lookup.contains( face.getNummer() )) {
found.add( face );
}
}
return found;
}
/**
* Used to access the bean info; this information is used to dynamically generate the
* FeatureType and Features.
*
* @return bean info for Face interface
*/
public BeanInfo getBeanInfo() {
BeanInfo info;
try {
info = Introspector.getBeanInfo(Face.class);
} catch (IntrospectionException e) {
return null;
}
return info;
}
/**
* Used to read in from a CSV file; created as a static method for ease of testing.
*
* @param csvFile
* @return
* @throws FileNotFoundException
*/
public static List<FaceImpl> load(File csvFile) throws IOException {
CsvReader reader = new CsvReader(new FileReader(csvFile));
boolean header = reader.readHeaders();
if (!header) {
throw new IOException("Unable to read csv header");
}
List<FaceImpl> faceList = new ArrayList<FaceImpl>();
while (reader.readRecord()) {
// we have content let us make a Face
// double latitude = Double.parseDouble(tokens[0]);
// double longitude = Double.parseDouble(tokens[1]);
//
// String name = tokens[2].trim();
// int number = Integer.parseInt(tokens[3].trim());
// Nummer
// int identifier = Integer.parseInt(tokens[0].trim());
long identifier = Long.parseLong(reader.get(0));
FaceImpl face = new FaceImpl(identifier);
face.setType(reader.get(1));
face.setFaceFormat(reader.get(2));
face.setProductFormat(reader.get(3));
face.setStatus(reader.get(4));
face.setInstalled(reader.get(5));
face.setPeriod(reader.get(6));
- face.setPosting(reader.get(7));
- face.setArea(reader.get(8));
- face.setStreet(reader.get(9));
- face.setNumber(reader.get(10));
+// face.setPosting(reader.get(7));
+ face.setArea(reader.get(7));
+ face.setStreet(reader.get(8));
+ face.setNumber(reader.get(9));
- double x = Double.parseDouble(reader.get(11));
+ double x = Double.parseDouble(reader.get(10));
face.setWestOstKoordinate(new BigDecimal(x));
- double y = Double.parseDouble(reader.get(12));
+ double y = Double.parseDouble(reader.get(11));
face.setSuedNordKoordinate(new BigDecimal(y));
- face.setAngle(reader.get(13));
- face.setCategory(reader.get(14));
+ face.setAngle(reader.get(12));
+ face.setCategory(reader.get(13));
faceList.add(face);
}
return faceList;
}
}
| false | true | public static List<FaceImpl> load(File csvFile) throws IOException {
CsvReader reader = new CsvReader(new FileReader(csvFile));
boolean header = reader.readHeaders();
if (!header) {
throw new IOException("Unable to read csv header");
}
List<FaceImpl> faceList = new ArrayList<FaceImpl>();
while (reader.readRecord()) {
// we have content let us make a Face
// double latitude = Double.parseDouble(tokens[0]);
// double longitude = Double.parseDouble(tokens[1]);
//
// String name = tokens[2].trim();
// int number = Integer.parseInt(tokens[3].trim());
// Nummer
// int identifier = Integer.parseInt(tokens[0].trim());
long identifier = Long.parseLong(reader.get(0));
FaceImpl face = new FaceImpl(identifier);
face.setType(reader.get(1));
face.setFaceFormat(reader.get(2));
face.setProductFormat(reader.get(3));
face.setStatus(reader.get(4));
face.setInstalled(reader.get(5));
face.setPeriod(reader.get(6));
face.setPosting(reader.get(7));
face.setArea(reader.get(8));
face.setStreet(reader.get(9));
face.setNumber(reader.get(10));
double x = Double.parseDouble(reader.get(11));
face.setWestOstKoordinate(new BigDecimal(x));
double y = Double.parseDouble(reader.get(12));
face.setSuedNordKoordinate(new BigDecimal(y));
face.setAngle(reader.get(13));
face.setCategory(reader.get(14));
faceList.add(face);
}
return faceList;
}
| public static List<FaceImpl> load(File csvFile) throws IOException {
CsvReader reader = new CsvReader(new FileReader(csvFile));
boolean header = reader.readHeaders();
if (!header) {
throw new IOException("Unable to read csv header");
}
List<FaceImpl> faceList = new ArrayList<FaceImpl>();
while (reader.readRecord()) {
// we have content let us make a Face
// double latitude = Double.parseDouble(tokens[0]);
// double longitude = Double.parseDouble(tokens[1]);
//
// String name = tokens[2].trim();
// int number = Integer.parseInt(tokens[3].trim());
// Nummer
// int identifier = Integer.parseInt(tokens[0].trim());
long identifier = Long.parseLong(reader.get(0));
FaceImpl face = new FaceImpl(identifier);
face.setType(reader.get(1));
face.setFaceFormat(reader.get(2));
face.setProductFormat(reader.get(3));
face.setStatus(reader.get(4));
face.setInstalled(reader.get(5));
face.setPeriod(reader.get(6));
// face.setPosting(reader.get(7));
face.setArea(reader.get(7));
face.setStreet(reader.get(8));
face.setNumber(reader.get(9));
double x = Double.parseDouble(reader.get(10));
face.setWestOstKoordinate(new BigDecimal(x));
double y = Double.parseDouble(reader.get(11));
face.setSuedNordKoordinate(new BigDecimal(y));
face.setAngle(reader.get(12));
face.setCategory(reader.get(13));
faceList.add(face);
}
return faceList;
}
|
diff --git a/src/test/java/org/gagravarr/tika/TestProjectParsers.java b/src/test/java/org/gagravarr/tika/TestProjectParsers.java
index 59b82ca..5bbf6ae 100644
--- a/src/test/java/org/gagravarr/tika/TestProjectParsers.java
+++ b/src/test/java/org/gagravarr/tika/TestProjectParsers.java
@@ -1,137 +1,137 @@
/*
* 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.gagravarr.tika;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.InputStream;
import java.util.Set;
import org.apache.tika.config.TikaConfig;
import org.apache.tika.metadata.DublinCore;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.metadata.TikaMetadataKeys;
import org.apache.tika.mime.MediaType;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.Parser;
import org.apache.tika.sax.BodyContentHandler;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.xml.sax.ContentHandler;
@RunWith(JUnit4.class)
public class TestProjectParsers {
public static MediaType MPP_TYPE = MediaType.application("vnd.ms-project");
public static MediaType MPX_TYPE = MediaType.application("x-project");
@Test
public void BasicProcessing() throws Exception {
InputStream mpx = getTestFile("testPROJECT.mpx", null);
InputStream mpp2003 = getTestFile("testPROJECT2003.mpp", null);
InputStream mpp2007 = getTestFile("testPROJECT2007.mpp", null);
MPPParser mppParser = new MPPParser();
MPXParser mpxParser = new MPXParser();
ContentHandler handler = new BodyContentHandler();
// Call Tika on the mpx file
mpxParser.parse(mpx, handler, new Metadata(), new ParseContext());
// Call Tika on the 2003 file
mppParser.parse(mpp2003, handler, new Metadata(), new ParseContext());
// Call Tika on the 2007 file
mppParser.parse(mpp2007, handler, new Metadata(), new ParseContext());
}
@Test
public void AutoDetectParsing() throws Exception {
Set<MediaType> types;
// Check the parsers claims to support the right things
MPPParser mppParser = new MPPParser();
types = mppParser.getSupportedTypes(new ParseContext());
assertTrue("Not found in " + types, types.contains(MPP_TYPE));
assertFalse("Shouldn't be in " + types, types.contains(MPX_TYPE));
MPXParser mpxParser = new MPXParser();
types = mpxParser.getSupportedTypes(new ParseContext());
assertTrue("Not found in " + types, types.contains(MPX_TYPE));
assertFalse("Shouldn't be in " + types, types.contains(MPP_TYPE));
// Check that the Default Parser claims to support them both
Parser baseParser = TikaConfig.getDefaultConfig().getParser();
types = baseParser.getSupportedTypes(new ParseContext());
assertTrue("Not found in " + types, types.contains(MPP_TYPE));
assertTrue("Not found in " + types, types.contains(MPX_TYPE));
Parser autoDetectParser = new AutoDetectParser(baseParser);
// Check the parsing works
Metadata metadata;
ContentHandler handler = new BodyContentHandler();
// Ask for a MPP to be processed
metadata = new Metadata();
InputStream mpp2003 = getTestFile("testPROJECT2003.mpp", metadata);
autoDetectParser.parse(mpp2003, handler, metadata, new ParseContext());
// Check it worked
assertEquals(
"The quick brown fox jumps over the lazy dog",
metadata.get(DublinCore.TITLE)
);
- assertTrue(handler.toString().contains("Fox does his jump"));
- assertTrue(handler.toString().contains("Obtain Dog"));
- assertTrue(handler.toString().contains("from 2011-11-25T08:00:00"));
- assertTrue(handler.toString().contains("to 2011-11-24T17:00:00"));
- assertTrue(handler.toString().contains("taking 1 Day"));
+ assertContains("Fox does his jump", handler.toString());
+ assertContains("Obtain Dog", handler.toString());
+ assertContains("from 2011-11-25T08:00:00", handler.toString());
+ assertContains("to 2011-11-24T17:00:00", handler.toString());
+ assertContains("taking 1 Day", handler.toString());
// Ask for a MPX to be processed
metadata = new Metadata();
handler = new BodyContentHandler();
InputStream mpx = getTestFile("testPROJECT.mpx", metadata);
autoDetectParser.parse(mpx, handler, metadata, new ParseContext());
// Check it worked (Note - no metadata for MPX)
assertTrue(handler.toString().contains("Fox does his jump"));
assertTrue(handler.toString().contains("Obtain Dog"));
// assertContains("from 2011-11-25T08:00:00", handler.toString());
// assertContains("to 2011-11-24T17:00:00", handler.toString());
assertContains("from 2011-11-25T", handler.toString());
assertContains("to 2011-11-24T", handler.toString());
assertContains("taking 1 Day", handler.toString());
}
protected static InputStream getTestFile(String name, Metadata metadata) throws Exception {
InputStream s = TestProjectParsers.class.getResourceAsStream("/test-files/" + name);
assertNotNull("Test file not found: " + name, s);
if (metadata != null) {
metadata.add(TikaMetadataKeys.RESOURCE_NAME_KEY, name);
}
return s;
}
protected static void assertContains(String needle, String haystack) {
assertTrue("'" + needle + "' not found in:\n" + haystack, haystack.contains(needle));
}
}
| true | true | public void AutoDetectParsing() throws Exception {
Set<MediaType> types;
// Check the parsers claims to support the right things
MPPParser mppParser = new MPPParser();
types = mppParser.getSupportedTypes(new ParseContext());
assertTrue("Not found in " + types, types.contains(MPP_TYPE));
assertFalse("Shouldn't be in " + types, types.contains(MPX_TYPE));
MPXParser mpxParser = new MPXParser();
types = mpxParser.getSupportedTypes(new ParseContext());
assertTrue("Not found in " + types, types.contains(MPX_TYPE));
assertFalse("Shouldn't be in " + types, types.contains(MPP_TYPE));
// Check that the Default Parser claims to support them both
Parser baseParser = TikaConfig.getDefaultConfig().getParser();
types = baseParser.getSupportedTypes(new ParseContext());
assertTrue("Not found in " + types, types.contains(MPP_TYPE));
assertTrue("Not found in " + types, types.contains(MPX_TYPE));
Parser autoDetectParser = new AutoDetectParser(baseParser);
// Check the parsing works
Metadata metadata;
ContentHandler handler = new BodyContentHandler();
// Ask for a MPP to be processed
metadata = new Metadata();
InputStream mpp2003 = getTestFile("testPROJECT2003.mpp", metadata);
autoDetectParser.parse(mpp2003, handler, metadata, new ParseContext());
// Check it worked
assertEquals(
"The quick brown fox jumps over the lazy dog",
metadata.get(DublinCore.TITLE)
);
assertTrue(handler.toString().contains("Fox does his jump"));
assertTrue(handler.toString().contains("Obtain Dog"));
assertTrue(handler.toString().contains("from 2011-11-25T08:00:00"));
assertTrue(handler.toString().contains("to 2011-11-24T17:00:00"));
assertTrue(handler.toString().contains("taking 1 Day"));
// Ask for a MPX to be processed
metadata = new Metadata();
handler = new BodyContentHandler();
InputStream mpx = getTestFile("testPROJECT.mpx", metadata);
autoDetectParser.parse(mpx, handler, metadata, new ParseContext());
// Check it worked (Note - no metadata for MPX)
assertTrue(handler.toString().contains("Fox does his jump"));
assertTrue(handler.toString().contains("Obtain Dog"));
// assertContains("from 2011-11-25T08:00:00", handler.toString());
// assertContains("to 2011-11-24T17:00:00", handler.toString());
assertContains("from 2011-11-25T", handler.toString());
assertContains("to 2011-11-24T", handler.toString());
assertContains("taking 1 Day", handler.toString());
}
| public void AutoDetectParsing() throws Exception {
Set<MediaType> types;
// Check the parsers claims to support the right things
MPPParser mppParser = new MPPParser();
types = mppParser.getSupportedTypes(new ParseContext());
assertTrue("Not found in " + types, types.contains(MPP_TYPE));
assertFalse("Shouldn't be in " + types, types.contains(MPX_TYPE));
MPXParser mpxParser = new MPXParser();
types = mpxParser.getSupportedTypes(new ParseContext());
assertTrue("Not found in " + types, types.contains(MPX_TYPE));
assertFalse("Shouldn't be in " + types, types.contains(MPP_TYPE));
// Check that the Default Parser claims to support them both
Parser baseParser = TikaConfig.getDefaultConfig().getParser();
types = baseParser.getSupportedTypes(new ParseContext());
assertTrue("Not found in " + types, types.contains(MPP_TYPE));
assertTrue("Not found in " + types, types.contains(MPX_TYPE));
Parser autoDetectParser = new AutoDetectParser(baseParser);
// Check the parsing works
Metadata metadata;
ContentHandler handler = new BodyContentHandler();
// Ask for a MPP to be processed
metadata = new Metadata();
InputStream mpp2003 = getTestFile("testPROJECT2003.mpp", metadata);
autoDetectParser.parse(mpp2003, handler, metadata, new ParseContext());
// Check it worked
assertEquals(
"The quick brown fox jumps over the lazy dog",
metadata.get(DublinCore.TITLE)
);
assertContains("Fox does his jump", handler.toString());
assertContains("Obtain Dog", handler.toString());
assertContains("from 2011-11-25T08:00:00", handler.toString());
assertContains("to 2011-11-24T17:00:00", handler.toString());
assertContains("taking 1 Day", handler.toString());
// Ask for a MPX to be processed
metadata = new Metadata();
handler = new BodyContentHandler();
InputStream mpx = getTestFile("testPROJECT.mpx", metadata);
autoDetectParser.parse(mpx, handler, metadata, new ParseContext());
// Check it worked (Note - no metadata for MPX)
assertTrue(handler.toString().contains("Fox does his jump"));
assertTrue(handler.toString().contains("Obtain Dog"));
// assertContains("from 2011-11-25T08:00:00", handler.toString());
// assertContains("to 2011-11-24T17:00:00", handler.toString());
assertContains("from 2011-11-25T", handler.toString());
assertContains("to 2011-11-24T", handler.toString());
assertContains("taking 1 Day", handler.toString());
}
|
diff --git a/src/com/android/launcher2/BubbleTextView.java b/src/com/android/launcher2/BubbleTextView.java
index d02f597b..ad01fac4 100644
--- a/src/com/android/launcher2/BubbleTextView.java
+++ b/src/com/android/launcher2/BubbleTextView.java
@@ -1,313 +1,313 @@
/*
* Copyright (C) 2008 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.launcher2;
import com.android.launcher.R;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Region;
import android.graphics.Region.Op;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
/**
* TextView that draws a bubble behind the text. We cannot use a LineBackgroundSpan
* because we want to make the bubble taller than the text and TextView's clip is
* too aggressive.
*/
public class BubbleTextView extends TextView implements VisibilityChangedBroadcaster {
static final float CORNER_RADIUS = 4.0f;
static final float SHADOW_LARGE_RADIUS = 4.0f;
static final float SHADOW_SMALL_RADIUS = 1.75f;
static final float SHADOW_Y_OFFSET = 2.0f;
static final int SHADOW_LARGE_COLOUR = 0xCC000000;
static final int SHADOW_SMALL_COLOUR = 0xBB000000;
static final float PADDING_H = 8.0f;
static final float PADDING_V = 3.0f;
private Paint mPaint;
private float mBubbleColorAlpha;
private int mPrevAlpha = -1;
private final HolographicOutlineHelper mOutlineHelper = new HolographicOutlineHelper();
private final Canvas mTempCanvas = new Canvas();
private final Rect mTempRect = new Rect();
private final Paint mTempPaint = new Paint();
private boolean mDidInvalidateForPressedState;
private Bitmap mPressedOrFocusedBackground;
private int mFocusedOutlineColor;
private int mFocusedGlowColor;
private int mPressedOutlineColor;
private int mPressedGlowColor;
private boolean mBackgroundSizeChanged;
private Drawable mBackground;
private VisibilityChangedListener mOnVisibilityChangedListener;
public BubbleTextView(Context context) {
super(context);
init();
}
public BubbleTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public BubbleTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
mBackground = getBackground();
setFocusable(true);
setBackgroundDrawable(null);
final Resources res = getContext().getResources();
int bubbleColor = res.getColor(R.color.bubble_dark_background);
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setColor(bubbleColor);
mBubbleColorAlpha = Color.alpha(bubbleColor) / 255.0f;
mFocusedOutlineColor = res.getColor(R.color.workspace_item_focused_outline_color);
mFocusedGlowColor = res.getColor(R.color.workspace_item_focused_glow_color);
mPressedOutlineColor = res.getColor(R.color.workspace_item_pressed_outline_color);
mPressedGlowColor = res.getColor(R.color.workspace_item_pressed_glow_color);
setShadowLayer(SHADOW_LARGE_RADIUS, 0.0f, SHADOW_Y_OFFSET, SHADOW_LARGE_COLOUR);
}
public void applyFromShortcutInfo(ShortcutInfo info, IconCache iconCache) {
Bitmap b = info.getIcon(iconCache);
setCompoundDrawablesWithIntrinsicBounds(null,
new FastBitmapDrawable(b),
null, null);
setText(info.title);
setTag(info);
}
@Override
protected boolean setFrame(int left, int top, int right, int bottom) {
if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
mBackgroundSizeChanged = true;
}
return super.setFrame(left, top, right, bottom);
}
@Override
protected boolean verifyDrawable(Drawable who) {
return who == mBackground || super.verifyDrawable(who);
}
@Override
protected void drawableStateChanged() {
if (isPressed()) {
// In this case, we have already created the pressed outline on ACTION_DOWN,
// so we just need to do an invalidate to trigger draw
if (!mDidInvalidateForPressedState) {
invalidate();
}
} else {
// Otherwise, either clear the pressed/focused background, or create a background
// for the focused state
final boolean backgroundEmptyBefore = mPressedOrFocusedBackground == null;
mPressedOrFocusedBackground = null;
if (isFocused()) {
mPressedOrFocusedBackground = createGlowingOutline(
mTempCanvas, mFocusedGlowColor, mFocusedOutlineColor);
invalidate();
}
final boolean backgroundEmptyNow = mPressedOrFocusedBackground == null;
if (!backgroundEmptyBefore && backgroundEmptyNow) {
invalidate();
}
}
Drawable d = mBackground;
if (d != null && d.isStateful()) {
d.setState(getDrawableState());
}
super.drawableStateChanged();
}
/**
* Draw the View v into the given Canvas.
*
* @param v the view to draw
* @param destCanvas the canvas to draw on
* @param padding the horizontal and vertical padding to use when drawing
*/
private void drawWithPadding(Canvas destCanvas, int padding) {
final Rect clipRect = mTempRect;
getDrawingRect(clipRect);
// adjust the clip rect so that we don't include the text label
clipRect.bottom =
getExtendedPaddingTop() - (int) BubbleTextView.PADDING_V + getLayout().getLineTop(0);
// Draw the View into the bitmap.
// The translate of scrollX and scrollY is necessary when drawing TextViews, because
// they set scrollX and scrollY to large values to achieve centered text
destCanvas.save();
destCanvas.translate(-getScrollX() + padding / 2, -getScrollY() + padding / 2);
destCanvas.clipRect(clipRect, Op.REPLACE);
draw(destCanvas);
destCanvas.restore();
}
/**
* Returns a new bitmap to be used as the object outline, e.g. to visualize the drop location.
* Responsibility for the bitmap is transferred to the caller.
*/
private Bitmap createGlowingOutline(Canvas canvas, int outlineColor, int glowColor) {
final int padding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS;
final Bitmap b = Bitmap.createBitmap(
getWidth() + padding, getHeight() + padding, Bitmap.Config.ARGB_8888);
canvas.setBitmap(b);
drawWithPadding(canvas, padding);
mOutlineHelper.applyExtraThickExpensiveOutlineWithBlur(b, canvas, glowColor, outlineColor);
return b;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// Call the superclass onTouchEvent first, because sometimes it changes the state to
// isPressed() on an ACTION_UP
boolean result = super.onTouchEvent(event);
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// So that the pressed outline is visible immediately when isPressed() is true,
// we pre-create it on ACTION_DOWN (it takes a small but perceptible amount of time
// to create it)
if (mPressedOrFocusedBackground == null) {
mPressedOrFocusedBackground = createGlowingOutline(
mTempCanvas, mPressedGlowColor, mPressedOutlineColor);
}
// Invalidate so the pressed state is visible, or set a flag so we know that we
// have to call invalidate as soon as the state is "pressed"
if (isPressed()) {
mDidInvalidateForPressedState = true;
invalidate();
} else {
mDidInvalidateForPressedState = false;
}
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
// If we've touched down and up on an item, and it's still not "pressed", then
// destroy the pressed outline
if (!isPressed()) {
mPressedOrFocusedBackground = null;
}
break;
}
return result;
}
public void setVisibilityChangedListener(VisibilityChangedListener listener) {
mOnVisibilityChangedListener = listener;
}
@Override
protected void onVisibilityChanged(View changedView, int visibility) {
if (mOnVisibilityChangedListener != null) {
mOnVisibilityChangedListener.receiveVisibilityChangedMessage(this);
}
super.onVisibilityChanged(changedView, visibility);
}
@Override
public void draw(Canvas canvas) {
if (mPressedOrFocusedBackground != null && (isPressed() || isFocused())) {
// The blue glow can extend outside of our clip region, so we first temporarily expand
// the canvas's clip region
canvas.save(Canvas.CLIP_SAVE_FLAG);
int padding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS / 2;
canvas.clipRect(-padding + mScrollX, -padding + mScrollY,
getWidth() + padding + mScrollX, getHeight() + padding + mScrollY,
Region.Op.REPLACE);
// draw blue glow
canvas.drawBitmap(mPressedOrFocusedBackground,
mScrollX - padding, mScrollY - padding, mTempPaint);
canvas.restore();
}
final Drawable background = mBackground;
if (background != null) {
final int scrollX = mScrollX;
final int scrollY = mScrollY;
if (mBackgroundSizeChanged) {
background.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
mBackgroundSizeChanged = false;
}
if ((scrollX | scrollY) == 0) {
background.draw(canvas);
} else {
canvas.translate(scrollX, scrollY);
background.draw(canvas);
canvas.translate(-scrollX, -scrollY);
}
}
// We enhance the shadow by drawing the shadow twice
getPaint().setShadowLayer(SHADOW_LARGE_RADIUS, 0.0f, SHADOW_Y_OFFSET, SHADOW_LARGE_COLOUR);
super.draw(canvas);
canvas.save(Canvas.CLIP_SAVE_FLAG);
canvas.clipRect(mScrollX, mScrollY + getExtendedPaddingTop(), mScrollX + getWidth(),
- mScrollY + getHeight(), Region.Op.REPLACE);
+ mScrollY + getHeight(), Region.Op.INTERSECT);
getPaint().setShadowLayer(SHADOW_SMALL_RADIUS, 0.0f, 0.0f, SHADOW_SMALL_COLOUR);
super.draw(canvas);
canvas.restore();
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
if (mBackground != null) mBackground.setCallback(this);
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
if (mBackground != null) mBackground.setCallback(null);
}
@Override
protected boolean onSetAlpha(int alpha) {
if (mPrevAlpha != alpha) {
mPrevAlpha = alpha;
mPaint.setAlpha((int) (alpha * mBubbleColorAlpha));
super.onSetAlpha(alpha);
}
return true;
}
}
| true | true | public void draw(Canvas canvas) {
if (mPressedOrFocusedBackground != null && (isPressed() || isFocused())) {
// The blue glow can extend outside of our clip region, so we first temporarily expand
// the canvas's clip region
canvas.save(Canvas.CLIP_SAVE_FLAG);
int padding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS / 2;
canvas.clipRect(-padding + mScrollX, -padding + mScrollY,
getWidth() + padding + mScrollX, getHeight() + padding + mScrollY,
Region.Op.REPLACE);
// draw blue glow
canvas.drawBitmap(mPressedOrFocusedBackground,
mScrollX - padding, mScrollY - padding, mTempPaint);
canvas.restore();
}
final Drawable background = mBackground;
if (background != null) {
final int scrollX = mScrollX;
final int scrollY = mScrollY;
if (mBackgroundSizeChanged) {
background.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
mBackgroundSizeChanged = false;
}
if ((scrollX | scrollY) == 0) {
background.draw(canvas);
} else {
canvas.translate(scrollX, scrollY);
background.draw(canvas);
canvas.translate(-scrollX, -scrollY);
}
}
// We enhance the shadow by drawing the shadow twice
getPaint().setShadowLayer(SHADOW_LARGE_RADIUS, 0.0f, SHADOW_Y_OFFSET, SHADOW_LARGE_COLOUR);
super.draw(canvas);
canvas.save(Canvas.CLIP_SAVE_FLAG);
canvas.clipRect(mScrollX, mScrollY + getExtendedPaddingTop(), mScrollX + getWidth(),
mScrollY + getHeight(), Region.Op.REPLACE);
getPaint().setShadowLayer(SHADOW_SMALL_RADIUS, 0.0f, 0.0f, SHADOW_SMALL_COLOUR);
super.draw(canvas);
canvas.restore();
}
| public void draw(Canvas canvas) {
if (mPressedOrFocusedBackground != null && (isPressed() || isFocused())) {
// The blue glow can extend outside of our clip region, so we first temporarily expand
// the canvas's clip region
canvas.save(Canvas.CLIP_SAVE_FLAG);
int padding = HolographicOutlineHelper.MAX_OUTER_BLUR_RADIUS / 2;
canvas.clipRect(-padding + mScrollX, -padding + mScrollY,
getWidth() + padding + mScrollX, getHeight() + padding + mScrollY,
Region.Op.REPLACE);
// draw blue glow
canvas.drawBitmap(mPressedOrFocusedBackground,
mScrollX - padding, mScrollY - padding, mTempPaint);
canvas.restore();
}
final Drawable background = mBackground;
if (background != null) {
final int scrollX = mScrollX;
final int scrollY = mScrollY;
if (mBackgroundSizeChanged) {
background.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
mBackgroundSizeChanged = false;
}
if ((scrollX | scrollY) == 0) {
background.draw(canvas);
} else {
canvas.translate(scrollX, scrollY);
background.draw(canvas);
canvas.translate(-scrollX, -scrollY);
}
}
// We enhance the shadow by drawing the shadow twice
getPaint().setShadowLayer(SHADOW_LARGE_RADIUS, 0.0f, SHADOW_Y_OFFSET, SHADOW_LARGE_COLOUR);
super.draw(canvas);
canvas.save(Canvas.CLIP_SAVE_FLAG);
canvas.clipRect(mScrollX, mScrollY + getExtendedPaddingTop(), mScrollX + getWidth(),
mScrollY + getHeight(), Region.Op.INTERSECT);
getPaint().setShadowLayer(SHADOW_SMALL_RADIUS, 0.0f, 0.0f, SHADOW_SMALL_COLOUR);
super.draw(canvas);
canvas.restore();
}
|
diff --git a/hibernate-core/src/main/java/org/hibernate/collection/internal/AbstractPersistentCollection.java b/hibernate-core/src/main/java/org/hibernate/collection/internal/AbstractPersistentCollection.java
index 75323d23d6..4ed942faf1 100644
--- a/hibernate-core/src/main/java/org/hibernate/collection/internal/AbstractPersistentCollection.java
+++ b/hibernate-core/src/main/java/org/hibernate/collection/internal/AbstractPersistentCollection.java
@@ -1,1171 +1,1171 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008-2011, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, 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 Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.collection.internal;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import javax.naming.NamingException;
import org.hibernate.AssertionFailure;
import org.hibernate.HibernateException;
import org.hibernate.LazyInitializationException;
import org.hibernate.Session;
import org.hibernate.collection.spi.PersistentCollection;
import org.hibernate.engine.internal.ForeignKeys;
import org.hibernate.engine.spi.CollectionEntry;
import org.hibernate.engine.spi.EntityEntry;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.engine.spi.Status;
import org.hibernate.engine.spi.TypedValue;
import org.hibernate.internal.SessionFactoryRegistry;
import org.hibernate.internal.util.MarkerObject;
import org.hibernate.internal.util.collections.EmptyIterator;
import org.hibernate.internal.util.collections.IdentitySet;
import org.hibernate.persister.collection.CollectionPersister;
import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.pretty.MessageHelper;
import org.hibernate.type.Type;
import org.jboss.logging.Logger;
/**
* Base class implementing {@link org.hibernate.collection.spi.PersistentCollection}
*
* @author Gavin King
*/
public abstract class AbstractPersistentCollection implements Serializable, PersistentCollection {
private static final Logger log = Logger.getLogger( AbstractPersistentCollection.class );
private transient SessionImplementor session;
private boolean initialized;
private transient List<DelayedOperation> operationQueue;
private transient boolean directlyAccessible;
private transient boolean initializing;
private Object owner;
private int cachedSize = -1;
private String role;
private Serializable key;
// collections detect changes made via their public interface and mark
// themselves as dirty as a performance optimization
private boolean dirty;
private Serializable storedSnapshot;
private String sessionFactoryUuid;
private boolean specjLazyLoad = false;
public final String getRole() {
return role;
}
public final Serializable getKey() {
return key;
}
public final boolean isUnreferenced() {
return role == null;
}
public final boolean isDirty() {
return dirty;
}
public final void clearDirty() {
dirty = false;
}
public final void dirty() {
dirty = true;
}
public final Serializable getStoredSnapshot() {
return storedSnapshot;
}
//Careful: these methods do not initialize the collection.
/**
* Is the initialized collection empty?
*/
public abstract boolean empty();
/**
* Called by any read-only method of the collection interface
*/
protected final void read() {
initialize( false );
}
/**
* Called by the {@link Collection#size} method
*/
@SuppressWarnings({"JavaDoc"})
protected boolean readSize() {
if ( !initialized ) {
if ( cachedSize != -1 && !hasQueuedOperations() ) {
return true;
}
else {
boolean isExtraLazy = withTemporarySessionIfNeeded(
new LazyInitializationWork<Boolean>() {
@Override
public Boolean doWork() {
CollectionEntry entry = session.getPersistenceContext().getCollectionEntry( AbstractPersistentCollection.this );
if ( entry != null ) {
CollectionPersister persister = entry.getLoadedPersister();
if ( persister.isExtraLazy() ) {
if ( hasQueuedOperations() ) {
session.flush();
}
cachedSize = persister.getSize( entry.getLoadedKey(), session );
return true;
}
else {
read();
}
}
else{
throwLazyInitializationExceptionIfNotConnected();
}
return false;
}
}
);
if ( isExtraLazy ) {
return true;
}
}
}
return false;
}
public static interface LazyInitializationWork<T> {
public T doWork();
}
private <T> T withTemporarySessionIfNeeded(LazyInitializationWork<T> lazyInitializationWork) {
SessionImplementor originalSession = null;
boolean isTempSession = false;
boolean isJTA = false;
if ( session == null ) {
if ( specjLazyLoad ) {
session = openTemporarySessionForLoading();
isTempSession = true;
}
else {
- throw new LazyInitializationException( "could not initialize proxy - no Session" );
+ throwLazyInitializationException( "could not initialize proxy - no Session" );
}
}
else if ( !session.isOpen() ) {
if ( specjLazyLoad ) {
originalSession = session;
session = openTemporarySessionForLoading();
isTempSession = true;
}
else {
- throw new LazyInitializationException( "could not initialize proxy - the owning Session was closed" );
+ throwLazyInitializationException( "could not initialize proxy - the owning Session was closed" );
}
}
else if ( !session.isConnected() ) {
if ( specjLazyLoad ) {
originalSession = session;
session = openTemporarySessionForLoading();
isTempSession = true;
}
else {
- throw new LazyInitializationException( "could not initialize proxy - the owning Session is disconnected" );
+ throwLazyInitializationException( "could not initialize proxy - the owning Session is disconnected" );
}
}
if ( isTempSession ) {
// TODO: On the next major release, add an
// 'isJTA' or 'getTransactionFactory' method to Session.
isJTA = session.getTransactionCoordinator()
.getTransactionContext().getTransactionEnvironment()
.getTransactionFactory()
.compatibleWithJtaSynchronization();
if ( !isJTA ) {
// Explicitly handle the transactions only if we're not in
// a JTA environment. A lazy loading temporary session can
// be created even if a current session and transaction are
// open (ex: session.clear() was used). We must prevent
// multiple transactions.
( ( Session) session ).beginTransaction();
}
session.getPersistenceContext().addUninitializedDetachedCollection(
session.getFactory().getCollectionPersister( getRole() ),
this
);
}
try {
return lazyInitializationWork.doWork();
}
finally {
if ( isTempSession ) {
// make sure the just opened temp session gets closed!
try {
if ( !isJTA ) {
( ( Session) session ).getTransaction().commit();
}
( (Session) session ).close();
}
catch (Exception e) {
log.warn( "Unable to close temporary session used to load lazy collection associated to no session" );
}
session = originalSession;
}
}
}
private SessionImplementor openTemporarySessionForLoading() {
if ( sessionFactoryUuid == null ) {
throwLazyInitializationException( "SessionFactory UUID not known to create temporary Session for loading" );
}
SessionFactoryImplementor sf = (SessionFactoryImplementor)
SessionFactoryRegistry.INSTANCE.getSessionFactory( sessionFactoryUuid );
return (SessionImplementor) sf.openSession();
}
protected Boolean readIndexExistence(final Object index) {
if ( !initialized ) {
Boolean extraLazyExistenceCheck = withTemporarySessionIfNeeded(
new LazyInitializationWork<Boolean>() {
@Override
public Boolean doWork() {
CollectionEntry entry = session.getPersistenceContext().getCollectionEntry( AbstractPersistentCollection.this );
CollectionPersister persister = entry.getLoadedPersister();
if ( persister.isExtraLazy() ) {
if ( hasQueuedOperations() ) {
session.flush();
}
return persister.indexExists( entry.getLoadedKey(), index, session );
}
else {
read();
}
return null;
}
}
);
if ( extraLazyExistenceCheck != null ) {
return extraLazyExistenceCheck;
}
}
return null;
}
protected Boolean readElementExistence(final Object element) {
if ( !initialized ) {
Boolean extraLazyExistenceCheck = withTemporarySessionIfNeeded(
new LazyInitializationWork<Boolean>() {
@Override
public Boolean doWork() {
CollectionEntry entry = session.getPersistenceContext().getCollectionEntry( AbstractPersistentCollection.this );
CollectionPersister persister = entry.getLoadedPersister();
if ( persister.isExtraLazy() ) {
if ( hasQueuedOperations() ) {
session.flush();
}
return persister.elementExists( entry.getLoadedKey(), element, session );
}
else {
read();
}
return null;
}
}
);
if ( extraLazyExistenceCheck != null ) {
return extraLazyExistenceCheck;
}
}
return null;
}
protected static final Object UNKNOWN = new MarkerObject( "UNKNOWN" );
protected Object readElementByIndex(final Object index) {
if ( !initialized ) {
class ExtraLazyElementByIndexReader implements LazyInitializationWork {
private boolean isExtraLazy;
private Object element;
@Override
public Object doWork() {
CollectionEntry entry = session.getPersistenceContext().getCollectionEntry( AbstractPersistentCollection.this );
CollectionPersister persister = entry.getLoadedPersister();
isExtraLazy = persister.isExtraLazy();
if ( isExtraLazy ) {
if ( hasQueuedOperations() ) {
session.flush();
}
element = persister.getElementByIndex( entry.getLoadedKey(), index, session, owner );
}
else {
read();
}
return null;
}
}
ExtraLazyElementByIndexReader reader = new ExtraLazyElementByIndexReader();
//noinspection unchecked
withTemporarySessionIfNeeded( reader );
if ( reader.isExtraLazy ) {
return reader.element;
}
}
return UNKNOWN;
}
protected int getCachedSize() {
return cachedSize;
}
private boolean isConnectedToSession() {
return session != null &&
session.isOpen() &&
session.getPersistenceContext().containsCollection( this );
}
/**
* Called by any writer method of the collection interface
*/
protected final void write() {
initialize( true );
dirty();
}
/**
* Is this collection in a state that would allow us to
* "queue" operations?
*/
@SuppressWarnings({"JavaDoc"})
protected boolean isOperationQueueEnabled() {
return !initialized &&
isConnectedToSession() &&
isInverseCollection();
}
/**
* Is this collection in a state that would allow us to
* "queue" puts? This is a special case, because of orphan
* delete.
*/
@SuppressWarnings({"JavaDoc"})
protected boolean isPutQueueEnabled() {
return !initialized &&
isConnectedToSession() &&
isInverseOneToManyOrNoOrphanDelete();
}
/**
* Is this collection in a state that would allow us to
* "queue" clear? This is a special case, because of orphan
* delete.
*/
@SuppressWarnings({"JavaDoc"})
protected boolean isClearQueueEnabled() {
return !initialized &&
isConnectedToSession() &&
isInverseCollectionNoOrphanDelete();
}
/**
* Is this the "inverse" end of a bidirectional association?
*/
@SuppressWarnings({"JavaDoc"})
private boolean isInverseCollection() {
CollectionEntry ce = session.getPersistenceContext().getCollectionEntry( this );
return ce != null && ce.getLoadedPersister().isInverse();
}
/**
* Is this the "inverse" end of a bidirectional association with
* no orphan delete enabled?
*/
@SuppressWarnings({"JavaDoc"})
private boolean isInverseCollectionNoOrphanDelete() {
CollectionEntry ce = session.getPersistenceContext().getCollectionEntry( this );
return ce != null &&
ce.getLoadedPersister().isInverse() &&
!ce.getLoadedPersister().hasOrphanDelete();
}
/**
* Is this the "inverse" end of a bidirectional one-to-many, or
* of a collection with no orphan delete?
*/
@SuppressWarnings({"JavaDoc"})
private boolean isInverseOneToManyOrNoOrphanDelete() {
CollectionEntry ce = session.getPersistenceContext().getCollectionEntry( this );
return ce != null && ce.getLoadedPersister().isInverse() && (
ce.getLoadedPersister().isOneToMany() ||
!ce.getLoadedPersister().hasOrphanDelete()
);
}
/**
* Queue an addition
*/
@SuppressWarnings({"JavaDoc"})
protected final void queueOperation(DelayedOperation operation) {
if ( operationQueue == null ) {
operationQueue = new ArrayList<DelayedOperation>( 10 );
}
operationQueue.add( operation );
dirty = true; //needed so that we remove this collection from the second-level cache
}
/**
* After reading all existing elements from the database,
* add the queued elements to the underlying collection.
*/
protected final void performQueuedOperations() {
for ( DelayedOperation operation : operationQueue ) {
operation.operate();
}
}
/**
* After flushing, re-init snapshot state.
*/
public void setSnapshot(Serializable key, String role, Serializable snapshot) {
this.key = key;
this.role = role;
this.storedSnapshot = snapshot;
}
/**
* After flushing, clear any "queued" additions, since the
* database state is now synchronized with the memory state.
*/
public void postAction() {
operationQueue = null;
cachedSize = -1;
clearDirty();
}
/**
* Not called by Hibernate, but used by non-JDK serialization,
* eg. SOAP libraries.
*/
public AbstractPersistentCollection() {
}
protected AbstractPersistentCollection(SessionImplementor session) {
this.session = session;
}
/**
* return the user-visible collection (or array) instance
*/
public Object getValue() {
return this;
}
/**
* Called just before reading any rows from the JDBC result set
*/
public void beginRead() {
// override on some subclasses
initializing = true;
}
/**
* Called after reading all rows from the JDBC result set
*/
public boolean endRead() {
//override on some subclasses
return afterInitialize();
}
public boolean afterInitialize() {
setInitialized();
//do this bit after setting initialized to true or it will recurse
if ( operationQueue != null ) {
performQueuedOperations();
operationQueue = null;
cachedSize = -1;
return false;
}
else {
return true;
}
}
/**
* Initialize the collection, if possible, wrapping any exceptions
* in a runtime exception
*
* @param writing currently obsolete
*
* @throws LazyInitializationException if we cannot initialize
*/
protected final void initialize(final boolean writing) {
if ( initialized ) {
return;
}
withTemporarySessionIfNeeded(
new LazyInitializationWork<Object>() {
@Override
public Object doWork() {
session.initializeCollection( AbstractPersistentCollection.this, writing );
return null;
}
}
);
}
private void throwLazyInitializationExceptionIfNotConnected() {
if ( !isConnectedToSession() ) {
throwLazyInitializationException( "no session or session was closed" );
}
if ( !session.isConnected() ) {
throwLazyInitializationException( "session is disconnected" );
}
}
private void throwLazyInitializationException(String message) {
throw new LazyInitializationException(
"failed to lazily initialize a collection" +
(role == null ? "" : " of role: " + role) +
", " + message
);
}
protected final void setInitialized() {
this.initializing = false;
this.initialized = true;
}
protected final void setDirectlyAccessible(boolean directlyAccessible) {
this.directlyAccessible = directlyAccessible;
}
/**
* Could the application possibly have a direct reference to
* the underlying collection implementation?
*/
public boolean isDirectlyAccessible() {
return directlyAccessible;
}
/**
* Disassociate this collection from the given session.
*
* @return true if this was currently associated with the given session
*/
public final boolean unsetSession(SessionImplementor currentSession) {
prepareForPossibleSpecialSpecjInitialization();
if ( currentSession == this.session ) {
this.session = null;
return true;
}
else {
return false;
}
}
protected void prepareForPossibleSpecialSpecjInitialization() {
if ( session != null ) {
specjLazyLoad = session.getFactory().getSettings().isInitializeLazyStateOutsideTransactionsEnabled();
if ( specjLazyLoad && sessionFactoryUuid == null ) {
try {
sessionFactoryUuid = (String) session.getFactory().getReference().get( "uuid" ).getContent();
}
catch (NamingException e) {
//not much we can do if this fails...
}
}
}
}
/**
* Associate the collection with the given session.
*
* @return false if the collection was already associated with the session
*
* @throws HibernateException if the collection was already associated
* with another open session
*/
public final boolean setCurrentSession(SessionImplementor session) throws HibernateException {
if ( session == this.session ) {
return false;
}
else {
if ( isConnectedToSession() ) {
CollectionEntry ce = session.getPersistenceContext().getCollectionEntry( this );
if ( ce == null ) {
throw new HibernateException(
"Illegal attempt to associate a collection with two open sessions"
);
}
else {
throw new HibernateException(
"Illegal attempt to associate a collection with two open sessions: " +
MessageHelper.collectionInfoString(
ce.getLoadedPersister(), this,
ce.getLoadedKey(), session
)
);
}
}
else {
this.session = session;
return true;
}
}
}
/**
* Do we need to completely recreate this collection when it changes?
*/
public boolean needsRecreate(CollectionPersister persister) {
return false;
}
/**
* To be called internally by the session, forcing
* immediate initialization.
*/
public final void forceInitialization() throws HibernateException {
if ( !initialized ) {
if ( initializing ) {
throw new AssertionFailure( "force initialize loading collection" );
}
if ( session == null ) {
throw new HibernateException( "collection is not associated with any session" );
}
if ( !session.isConnected() ) {
throw new HibernateException( "disconnected session" );
}
session.initializeCollection( this, false );
}
}
/**
* Get the current snapshot from the session
*/
@SuppressWarnings({"JavaDoc"})
protected final Serializable getSnapshot() {
return session.getPersistenceContext().getSnapshot( this );
}
/**
* Is this instance initialized?
*/
public final boolean wasInitialized() {
return initialized;
}
public boolean isRowUpdatePossible() {
return true;
}
/**
* Does this instance have any "queued" additions?
*/
public final boolean hasQueuedOperations() {
return operationQueue != null;
}
/**
* Iterate the "queued" additions
*/
public final Iterator queuedAdditionIterator() {
if ( hasQueuedOperations() ) {
return new Iterator() {
int i = 0;
public Object next() {
return operationQueue.get( i++ ).getAddedInstance();
}
public boolean hasNext() {
return i < operationQueue.size();
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
else {
return EmptyIterator.INSTANCE;
}
}
/**
* Iterate the "queued" additions
*/
@SuppressWarnings({"unchecked"})
public final Collection getQueuedOrphans(String entityName) {
if ( hasQueuedOperations() ) {
Collection additions = new ArrayList( operationQueue.size() );
Collection removals = new ArrayList( operationQueue.size() );
for ( DelayedOperation operation : operationQueue ) {
additions.add( operation.getAddedInstance() );
removals.add( operation.getOrphan() );
}
return getOrphans( removals, additions, entityName, session );
}
else {
return Collections.EMPTY_LIST;
}
}
/**
* Called before inserting rows, to ensure that any surrogate keys
* are fully generated
*/
public void preInsert(CollectionPersister persister) throws HibernateException {
}
/**
* Called after inserting a row, to fetch the natively generated id
*/
public void afterRowInsert(CollectionPersister persister, Object entry, int i) throws HibernateException {
}
/**
* get all "orphaned" elements
*/
public abstract Collection getOrphans(Serializable snapshot, String entityName) throws HibernateException;
/**
* Get the current session
*/
@SuppressWarnings({"JavaDoc"})
public final SessionImplementor getSession() {
return session;
}
protected final class IteratorProxy implements Iterator {
protected final Iterator itr;
public IteratorProxy(Iterator itr) {
this.itr = itr;
}
public boolean hasNext() {
return itr.hasNext();
}
public Object next() {
return itr.next();
}
public void remove() {
write();
itr.remove();
}
}
protected final class ListIteratorProxy implements ListIterator {
protected final ListIterator itr;
public ListIteratorProxy(ListIterator itr) {
this.itr = itr;
}
@SuppressWarnings({"unchecked"})
public void add(Object o) {
write();
itr.add( o );
}
public boolean hasNext() {
return itr.hasNext();
}
public boolean hasPrevious() {
return itr.hasPrevious();
}
public Object next() {
return itr.next();
}
public int nextIndex() {
return itr.nextIndex();
}
public Object previous() {
return itr.previous();
}
public int previousIndex() {
return itr.previousIndex();
}
public void remove() {
write();
itr.remove();
}
@SuppressWarnings({"unchecked"})
public void set(Object o) {
write();
itr.set( o );
}
}
protected class SetProxy implements java.util.Set {
protected final Collection set;
public SetProxy(Collection set) {
this.set = set;
}
@SuppressWarnings({"unchecked"})
public boolean add(Object o) {
write();
return set.add( o );
}
@SuppressWarnings({"unchecked"})
public boolean addAll(Collection c) {
write();
return set.addAll( c );
}
public void clear() {
write();
set.clear();
}
public boolean contains(Object o) {
return set.contains( o );
}
public boolean containsAll(Collection c) {
return set.containsAll( c );
}
public boolean isEmpty() {
return set.isEmpty();
}
public Iterator iterator() {
return new IteratorProxy( set.iterator() );
}
public boolean remove(Object o) {
write();
return set.remove( o );
}
public boolean removeAll(Collection c) {
write();
return set.removeAll( c );
}
public boolean retainAll(Collection c) {
write();
return set.retainAll( c );
}
public int size() {
return set.size();
}
public Object[] toArray() {
return set.toArray();
}
@SuppressWarnings({"unchecked"})
public Object[] toArray(Object[] array) {
return set.toArray( array );
}
}
protected final class ListProxy implements java.util.List {
protected final List list;
public ListProxy(List list) {
this.list = list;
}
@Override
@SuppressWarnings({"unchecked"})
public void add(int index, Object value) {
write();
list.add( index, value );
}
@Override
@SuppressWarnings({"unchecked"})
public boolean add(Object o) {
write();
return list.add( o );
}
@Override
@SuppressWarnings({"unchecked"})
public boolean addAll(Collection c) {
write();
return list.addAll( c );
}
@Override
@SuppressWarnings({"unchecked"})
public boolean addAll(int i, Collection c) {
write();
return list.addAll( i, c );
}
@Override
public void clear() {
write();
list.clear();
}
@Override
public boolean contains(Object o) {
return list.contains( o );
}
@Override
public boolean containsAll(Collection c) {
return list.containsAll( c );
}
@Override
public Object get(int i) {
return list.get( i );
}
@Override
public int indexOf(Object o) {
return list.indexOf( o );
}
@Override
public boolean isEmpty() {
return list.isEmpty();
}
@Override
public Iterator iterator() {
return new IteratorProxy( list.iterator() );
}
@Override
public int lastIndexOf(Object o) {
return list.lastIndexOf( o );
}
@Override
public ListIterator listIterator() {
return new ListIteratorProxy( list.listIterator() );
}
@Override
public ListIterator listIterator(int i) {
return new ListIteratorProxy( list.listIterator( i ) );
}
@Override
public Object remove(int i) {
write();
return list.remove( i );
}
@Override
public boolean remove(Object o) {
write();
return list.remove( o );
}
@Override
public boolean removeAll(Collection c) {
write();
return list.removeAll( c );
}
@Override
public boolean retainAll(Collection c) {
write();
return list.retainAll( c );
}
@Override
@SuppressWarnings({"unchecked"})
public Object set(int i, Object o) {
write();
return list.set( i, o );
}
@Override
public int size() {
return list.size();
}
@Override
public List subList(int i, int j) {
return list.subList( i, j );
}
@Override
public Object[] toArray() {
return list.toArray();
}
@Override
@SuppressWarnings({"unchecked"})
public Object[] toArray(Object[] array) {
return list.toArray( array );
}
}
/**
* Contract for operations which are part of a collection's operation queue.
*/
protected interface DelayedOperation {
public void operate();
public Object getAddedInstance();
public Object getOrphan();
}
/**
* Given a collection of entity instances that used to
* belong to the collection, and a collection of instances
* that currently belong, return a collection of orphans
*/
@SuppressWarnings({"JavaDoc", "unchecked"})
protected static Collection getOrphans(
Collection oldElements,
Collection currentElements,
String entityName,
SessionImplementor session) throws HibernateException {
// short-circuit(s)
if ( currentElements.size() == 0 ) {
return oldElements; // no new elements, the old list contains only Orphans
}
if ( oldElements.size() == 0 ) {
return oldElements; // no old elements, so no Orphans neither
}
final EntityPersister entityPersister = session.getFactory().getEntityPersister( entityName );
final Type idType = entityPersister.getIdentifierType();
// create the collection holding the Orphans
Collection res = new ArrayList();
// collect EntityIdentifier(s) of the *current* elements - add them into a HashSet for fast access
java.util.Set currentIds = new HashSet();
java.util.Set currentSaving = new IdentitySet();
for ( Object current : currentElements ) {
if ( current != null && ForeignKeys.isNotTransient( entityName, current, null, session ) ) {
EntityEntry ee = session.getPersistenceContext().getEntry( current );
if ( ee != null && ee.getStatus() == Status.SAVING ) {
currentSaving.add( current );
}
else {
Serializable currentId = ForeignKeys.getEntityIdentifierIfNotUnsaved(
entityName,
current,
session
);
currentIds.add( new TypedValue( idType, currentId, entityPersister.getEntityMode() ) );
}
}
}
// iterate over the *old* list
for ( Object old : oldElements ) {
if ( !currentSaving.contains( old ) ) {
Serializable oldId = ForeignKeys.getEntityIdentifierIfNotUnsaved( entityName, old, session );
if ( !currentIds.contains( new TypedValue( idType, oldId, entityPersister.getEntityMode() ) ) ) {
res.add( old );
}
}
}
return res;
}
public static void identityRemove(
Collection list,
Object object,
String entityName,
SessionImplementor session) throws HibernateException {
if ( object != null && ForeignKeys.isNotTransient( entityName, object, null, session ) ) {
final EntityPersister entityPersister = session.getFactory().getEntityPersister( entityName );
Type idType = entityPersister.getIdentifierType();
Serializable idOfCurrent = ForeignKeys.getEntityIdentifierIfNotUnsaved( entityName, object, session );
Iterator itr = list.iterator();
while ( itr.hasNext() ) {
Serializable idOfOld = ForeignKeys.getEntityIdentifierIfNotUnsaved( entityName, itr.next(), session );
if ( idType.isEqual( idOfCurrent, idOfOld, session.getFactory() ) ) {
itr.remove();
break;
}
}
}
}
public Object getIdentifier(Object entry, int i) {
throw new UnsupportedOperationException();
}
public Object getOwner() {
return owner;
}
public void setOwner(Object owner) {
this.owner = owner;
}
}
| false | true | private <T> T withTemporarySessionIfNeeded(LazyInitializationWork<T> lazyInitializationWork) {
SessionImplementor originalSession = null;
boolean isTempSession = false;
boolean isJTA = false;
if ( session == null ) {
if ( specjLazyLoad ) {
session = openTemporarySessionForLoading();
isTempSession = true;
}
else {
throw new LazyInitializationException( "could not initialize proxy - no Session" );
}
}
else if ( !session.isOpen() ) {
if ( specjLazyLoad ) {
originalSession = session;
session = openTemporarySessionForLoading();
isTempSession = true;
}
else {
throw new LazyInitializationException( "could not initialize proxy - the owning Session was closed" );
}
}
else if ( !session.isConnected() ) {
if ( specjLazyLoad ) {
originalSession = session;
session = openTemporarySessionForLoading();
isTempSession = true;
}
else {
throw new LazyInitializationException( "could not initialize proxy - the owning Session is disconnected" );
}
}
if ( isTempSession ) {
// TODO: On the next major release, add an
// 'isJTA' or 'getTransactionFactory' method to Session.
isJTA = session.getTransactionCoordinator()
.getTransactionContext().getTransactionEnvironment()
.getTransactionFactory()
.compatibleWithJtaSynchronization();
if ( !isJTA ) {
// Explicitly handle the transactions only if we're not in
// a JTA environment. A lazy loading temporary session can
// be created even if a current session and transaction are
// open (ex: session.clear() was used). We must prevent
// multiple transactions.
( ( Session) session ).beginTransaction();
}
session.getPersistenceContext().addUninitializedDetachedCollection(
session.getFactory().getCollectionPersister( getRole() ),
this
);
}
try {
return lazyInitializationWork.doWork();
}
finally {
if ( isTempSession ) {
// make sure the just opened temp session gets closed!
try {
if ( !isJTA ) {
( ( Session) session ).getTransaction().commit();
}
( (Session) session ).close();
}
catch (Exception e) {
log.warn( "Unable to close temporary session used to load lazy collection associated to no session" );
}
session = originalSession;
}
}
}
| private <T> T withTemporarySessionIfNeeded(LazyInitializationWork<T> lazyInitializationWork) {
SessionImplementor originalSession = null;
boolean isTempSession = false;
boolean isJTA = false;
if ( session == null ) {
if ( specjLazyLoad ) {
session = openTemporarySessionForLoading();
isTempSession = true;
}
else {
throwLazyInitializationException( "could not initialize proxy - no Session" );
}
}
else if ( !session.isOpen() ) {
if ( specjLazyLoad ) {
originalSession = session;
session = openTemporarySessionForLoading();
isTempSession = true;
}
else {
throwLazyInitializationException( "could not initialize proxy - the owning Session was closed" );
}
}
else if ( !session.isConnected() ) {
if ( specjLazyLoad ) {
originalSession = session;
session = openTemporarySessionForLoading();
isTempSession = true;
}
else {
throwLazyInitializationException( "could not initialize proxy - the owning Session is disconnected" );
}
}
if ( isTempSession ) {
// TODO: On the next major release, add an
// 'isJTA' or 'getTransactionFactory' method to Session.
isJTA = session.getTransactionCoordinator()
.getTransactionContext().getTransactionEnvironment()
.getTransactionFactory()
.compatibleWithJtaSynchronization();
if ( !isJTA ) {
// Explicitly handle the transactions only if we're not in
// a JTA environment. A lazy loading temporary session can
// be created even if a current session and transaction are
// open (ex: session.clear() was used). We must prevent
// multiple transactions.
( ( Session) session ).beginTransaction();
}
session.getPersistenceContext().addUninitializedDetachedCollection(
session.getFactory().getCollectionPersister( getRole() ),
this
);
}
try {
return lazyInitializationWork.doWork();
}
finally {
if ( isTempSession ) {
// make sure the just opened temp session gets closed!
try {
if ( !isJTA ) {
( ( Session) session ).getTransaction().commit();
}
( (Session) session ).close();
}
catch (Exception e) {
log.warn( "Unable to close temporary session used to load lazy collection associated to no session" );
}
session = originalSession;
}
}
}
|
diff --git a/test-modules/functional-tests/src/test/java/org/openlmis/functional/InitiateRnR.java b/test-modules/functional-tests/src/test/java/org/openlmis/functional/InitiateRnR.java
index c4b6046057..1b2f2219c0 100644
--- a/test-modules/functional-tests/src/test/java/org/openlmis/functional/InitiateRnR.java
+++ b/test-modules/functional-tests/src/test/java/org/openlmis/functional/InitiateRnR.java
@@ -1,226 +1,228 @@
/*
* Copyright © 2013 VillageReach. All Rights Reserved. This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
*
* If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package org.openlmis.functional;
import org.openlmis.UiUtils.CaptureScreenshotOnFailureListener;
import org.openlmis.UiUtils.TestCaseHelper;
import org.openlmis.pageobjects.ApprovePage;
import org.openlmis.pageobjects.HomePage;
import org.openlmis.pageobjects.InitiateRnRPage;
import org.openlmis.pageobjects.LoginPage;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;
import org.testng.annotations.*;
import java.util.ArrayList;
import java.util.List;
import static com.thoughtworks.selenium.SeleneseTestBase.*;
@TransactionConfiguration(defaultRollback = true)
@Transactional
@Listeners(CaptureScreenshotOnFailureListener.class)
public class InitiateRnR extends TestCaseHelper {
public static final String STORE_IN_CHARGE = "store in-charge";
public static final String APPROVE_REQUISITION = "APPROVE_REQUISITION";
public static final String CREATE_REQUISITION = "CREATE_REQUISITION";
public static final String SUBMITTED = "SUBMITTED";
public static final String AUTHORIZED = "AUTHORIZED";
public static final String IN_APPROVAL = "IN_APPROVAL";
public static final String AUTHORIZE_REQUISITION = "AUTHORIZE_REQUISITION";
public static final String VIEW_REQUISITION = "VIEW_REQUISITION";
@BeforeMethod(groups = {"functional", "smoke"})
public void setUp() throws Exception {
super.setup();
}
@Test(groups = {"smoke"}, dataProvider = "Data-Provider-Function-Positive")
public void testVerifyRegimensColumnsAndShouldSaveData(String program, String userSIC, String categoryCode, String password, String regimenCode, String regimenName, String regimenCode2, String regimenName2) throws Exception {
List<String> rightsList = new ArrayList<String>();
rightsList.add(CREATE_REQUISITION);
rightsList.add(VIEW_REQUISITION);
setupTestDataToInitiateRnR(true, program, userSIC, "200", "openLmis", rightsList);
dbWrapper.insertRegimenTemplateConfiguredForProgram(program, categoryCode, regimenCode, regimenName, true);
dbWrapper.insertRegimenTemplateConfiguredForProgram(program, categoryCode, regimenCode2, regimenName2, false);
dbWrapper.insertRegimenTemplateColumnsForProgram(program);
LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal);
HomePage homePage = loginPage.loginAs(userSIC, password);
homePage.navigateAndInitiateRnr(program);
InitiateRnRPage initiateRnRPage = homePage.clickProceed();
dbWrapper.insertValuesInRequisition();
homePage.navigateAndInitiateRnr(program);
InitiateRnRPage initiateRnRPage1 = homePage.clickProceed();
initiateRnRPage1.clickRegimenTab();
verifyRegimenFieldsPresentOnRegimenTab(regimenCode, regimenName, initiateRnRPage, initiateRnRPage1);
initiateRnRPage1.enterValuesOnRegimenScreen(3, 2, 100);
initiateRnRPage1.enterValuesOnRegimenScreen(4, 2, 200);
initiateRnRPage1.enterValuesOnRegimenScreen(5, 2, 300);
initiateRnRPage1.enterValuesOnRegimenScreen(6, 2, 400);
initiateRnRPage1.clickSaveButton();
initiateRnRPage1.verifySaveSuccessMsg();
initiateRnRPage1.clickSubmitButton();
initiateRnRPage1.clickOk();
initiateRnRPage1.verifySubmitSuccessMsg();
}
@Test(groups = {"functional"}, dataProvider = "Data-Provider-Function-Positive")
public void testSubmitAndAuthorizeRegimen(String program, String userSIC, String categoryCode, String password, String regimenCode, String regimenName, String regimenCode2, String regimenName2) throws Exception {
List<String> rightsList = new ArrayList<String>();
rightsList.add(CREATE_REQUISITION);
rightsList.add(VIEW_REQUISITION);
rightsList.add(AUTHORIZE_REQUISITION);
setupTestDataToInitiateRnR(true, program, userSIC, "200", "openLmis", rightsList);
dbWrapper.insertRegimenTemplateConfiguredForProgram(program, categoryCode, regimenCode, regimenName, true);
dbWrapper.insertRegimenTemplateConfiguredForProgram(program, categoryCode, regimenCode2, regimenName2, false);
dbWrapper.insertRegimenTemplateColumnsForProgram(program);
LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal);
HomePage homePage = loginPage.loginAs(userSIC, password);
homePage.navigateAndInitiateRnr(program);
InitiateRnRPage initiateRnRPage = homePage.clickProceed();
dbWrapper.insertValuesInRequisition();
homePage.navigateAndInitiateRnr(program);
InitiateRnRPage initiateRnRPage1 = homePage.clickProceed();
initiateRnRPage1.clickRegimenTab();
verifyRegimenFieldsPresentOnRegimenTab(regimenCode, regimenName, initiateRnRPage, initiateRnRPage1);
initiateRnRPage1.enterValuesOnRegimenScreen(3, 2, 100);
initiateRnRPage1.enterValuesOnRegimenScreen(4, 2, 200);
- initiateRnRPage1.enterValuesOnRegimenScreen(5, 2, 300);
initiateRnRPage1.enterValuesOnRegimenScreen(6, 2, 400);
initiateRnRPage1.clickSubmitButton();
+ initiateRnRPage1.verifySubmitRnrErrorMsg();
+ initiateRnRPage1.enterValuesOnRegimenScreen(5, 2, 300);
+ initiateRnRPage1.clickSubmitButton();
initiateRnRPage1.clickOk();
initiateRnRPage1.verifySubmitSuccessMsg();
homePage.navigateAndInitiateRnr(program);
InitiateRnRPage initiateRnRPage2 = homePage.clickProceed();
initiateRnRPage2.clickRegimenTab();
verifyValuesOnRegimenScreen(initiateRnRPage2,"100","200","300","400");
- initiateRnRPage1.clickAuthorizeButton();
- initiateRnRPage1.clickOk();
- initiateRnRPage1.verifyAuthorizeRnrSuccessMsg();
+ initiateRnRPage2.clickAuthorizeButton();
+ initiateRnRPage2.clickOk();
+ initiateRnRPage2.verifyAuthorizeRnrSuccessMsg();
}
@Test(groups = {"functional"}, dataProvider = "Data-Provider-Function-Positive")
public void testApproveRegimen(String program, String userSIC, String categoryCode, String password, String regimenCode, String regimenName, String regimenCode2, String regimenName2) throws Exception {
List<String> rightsList = new ArrayList<String>();
rightsList.add(CREATE_REQUISITION);
rightsList.add(VIEW_REQUISITION);
rightsList.add(AUTHORIZE_REQUISITION);
rightsList.add(APPROVE_REQUISITION);
setupTestDataToInitiateRnR(true, program, userSIC, "200", "openLmis", rightsList);
dbWrapper.insertRegimenTemplateConfiguredForProgram(program, categoryCode, regimenCode, regimenName, true);
dbWrapper.insertRegimenTemplateConfiguredForProgram(program, categoryCode, regimenCode2, regimenName2, false);
dbWrapper.insertRegimenTemplateColumnsForProgram(program);
LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal);
HomePage homePage = loginPage.loginAs(userSIC, password);
homePage.navigateAndInitiateRnr(program);
InitiateRnRPage initiateRnRPage = homePage.clickProceed();
dbWrapper.insertValuesInRequisition();
dbWrapper.insertValuesInRegimenLineItems("100","200","300","testing");
dbWrapper.updateRequisitionStatus(SUBMITTED);
dbWrapper.insertApprovedQuantity(10);
dbWrapper.updateRequisitionStatus(AUTHORIZED);
ApprovePage approvePageLowerSNUser = homePage.navigateToApprove();
approvePageLowerSNUser.verifyAndClickRequisitionPresentForApproval();
approvePageLowerSNUser.clickRegimenTab();
verifyValuesOnRegimenScreen(initiateRnRPage,"100","200","300","testing");
approvePageLowerSNUser.clickSaveButton();
approvePageLowerSNUser.clickApproveButton();
approvePageLowerSNUser.clickOk();
approvePageLowerSNUser.verifyNoRequisitionPendingMessage();
}
@Test(groups = {"functional"}, dataProvider = "Data-Provider-Function-Positive")
public void testRnRWithInvisibleProgramRegimenColumn(String program, String userSIC, String categoryCode, String password, String regimenCode, String regimenName, String regimenCode2, String regimenName2) throws Exception {
List<String> rightsList = new ArrayList<String>();
rightsList.add(CREATE_REQUISITION);
rightsList.add(VIEW_REQUISITION);
setupTestDataToInitiateRnR(true, program, userSIC, "200", "openLmis", rightsList);
dbWrapper.insertRegimenTemplateConfiguredForProgram(program, categoryCode, regimenCode, regimenName, true);
dbWrapper.insertRegimenTemplateConfiguredForProgram(program, categoryCode, regimenCode2, regimenName2, false);
dbWrapper.insertRegimenTemplateColumnsForProgram(program);
dbWrapper.updateProgramRegimenColumns(program, "remarks", false);
LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal);
HomePage homePage = loginPage.loginAs(userSIC, password);
homePage.navigateAndInitiateRnr(program);
InitiateRnRPage initiateRnRPage = homePage.clickProceed();
testWebDriver.sleep(2000);
initiateRnRPage.clickRegimenTab();
assertEquals(initiateRnRPage.getRegimenTableColumnCount(), 6);
}
@Test(groups = {"functional"}, dataProvider = "Data-Provider-Function-Positive")
public void testRnRWithInActiveRegimen(String program, String userSIC, String categoryCode, String password, String regimenCode, String regimenName, String regimenCode2, String regimenName2) throws Exception {
List<String> rightsList = new ArrayList<String>();
rightsList.add(CREATE_REQUISITION);
rightsList.add(VIEW_REQUISITION);
setupTestDataToInitiateRnR(true, program, userSIC, "200", "openLmis", rightsList);
dbWrapper.insertRegimenTemplateConfiguredForProgram(program, categoryCode, regimenCode, regimenName, false);
dbWrapper.insertRegimenTemplateConfiguredForProgram(program, categoryCode, regimenCode2, regimenName2, false);
dbWrapper.insertRegimenTemplateColumnsForProgram(program);
LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal);
HomePage homePage = loginPage.loginAs(userSIC, password);
homePage.navigateAndInitiateRnr(program);
InitiateRnRPage initiateRnRPage = homePage.clickProceed();
testWebDriver.sleep(2000);
assertFalse("Regimen tab should not be displayed.", initiateRnRPage.existRegimenTab());
}
private void verifyRegimenFieldsPresentOnRegimenTab(String regimenCode, String regimenName, InitiateRnRPage initiateRnRPage, InitiateRnRPage initiateRnRPage1) {
assertTrue("Regimen tab should be displayed.", initiateRnRPage.existRegimenTab());
assertEquals(initiateRnRPage1.getRegimenTableRowCount(), 2);
assertTrue("Regimen Code should be displayed.", initiateRnRPage1.existRegimenCode(regimenCode, 2));
assertTrue("Regimen Name should be displayed.", initiateRnRPage1.existRegimenName(regimenName, 2));
assertTrue("Reporting Field 1 should be displayed.", initiateRnRPage1.existRegimenReportingField(3, 2));
assertTrue("Reporting Field 2 should be displayed.", initiateRnRPage1.existRegimenReportingField(4, 2));
assertTrue("Reporting Field 3 should be displayed.", initiateRnRPage1.existRegimenReportingField(5, 2));
assertTrue("Reporting Field 4 should be displayed.", initiateRnRPage1.existRegimenReportingField(6, 2));
}
private void verifyValuesOnRegimenScreen(InitiateRnRPage initiateRnRPage, String patientsontreatment, String patientstoinitiatetreatment, String patientsstoppedtreatment, String remarks )
{
assertEquals(patientsontreatment,initiateRnRPage.getPatientsOnTreatmentValue());
assertEquals(patientstoinitiatetreatment,initiateRnRPage.getPatientsToInitiateTreatmentValue());
assertEquals(patientsstoppedtreatment,initiateRnRPage.getPatientsStoppedTreatmentValue());
assertEquals(remarks,initiateRnRPage.getRemarksValue());
}
@AfterMethod(groups = {"functional", "smoke"})
public void tearDown() throws Exception {
HomePage homePage = new HomePage(testWebDriver);
homePage.logout(baseUrlGlobal);
dbWrapper.deleteData();
dbWrapper.closeConnection();
}
@DataProvider(name = "Data-Provider-Function-Positive")
public Object[][] parameterIntTestProviderPositive() {
return new Object[][]{
{"HIV", "storeincharge", "ADULTS", "Admin123", "RegimenCode1", "RegimenName1", "RegimenCode2", "RegimenName2"}
};
}
}
| false | true | public void testSubmitAndAuthorizeRegimen(String program, String userSIC, String categoryCode, String password, String regimenCode, String regimenName, String regimenCode2, String regimenName2) throws Exception {
List<String> rightsList = new ArrayList<String>();
rightsList.add(CREATE_REQUISITION);
rightsList.add(VIEW_REQUISITION);
rightsList.add(AUTHORIZE_REQUISITION);
setupTestDataToInitiateRnR(true, program, userSIC, "200", "openLmis", rightsList);
dbWrapper.insertRegimenTemplateConfiguredForProgram(program, categoryCode, regimenCode, regimenName, true);
dbWrapper.insertRegimenTemplateConfiguredForProgram(program, categoryCode, regimenCode2, regimenName2, false);
dbWrapper.insertRegimenTemplateColumnsForProgram(program);
LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal);
HomePage homePage = loginPage.loginAs(userSIC, password);
homePage.navigateAndInitiateRnr(program);
InitiateRnRPage initiateRnRPage = homePage.clickProceed();
dbWrapper.insertValuesInRequisition();
homePage.navigateAndInitiateRnr(program);
InitiateRnRPage initiateRnRPage1 = homePage.clickProceed();
initiateRnRPage1.clickRegimenTab();
verifyRegimenFieldsPresentOnRegimenTab(regimenCode, regimenName, initiateRnRPage, initiateRnRPage1);
initiateRnRPage1.enterValuesOnRegimenScreen(3, 2, 100);
initiateRnRPage1.enterValuesOnRegimenScreen(4, 2, 200);
initiateRnRPage1.enterValuesOnRegimenScreen(5, 2, 300);
initiateRnRPage1.enterValuesOnRegimenScreen(6, 2, 400);
initiateRnRPage1.clickSubmitButton();
initiateRnRPage1.clickOk();
initiateRnRPage1.verifySubmitSuccessMsg();
homePage.navigateAndInitiateRnr(program);
InitiateRnRPage initiateRnRPage2 = homePage.clickProceed();
initiateRnRPage2.clickRegimenTab();
verifyValuesOnRegimenScreen(initiateRnRPage2,"100","200","300","400");
initiateRnRPage1.clickAuthorizeButton();
initiateRnRPage1.clickOk();
initiateRnRPage1.verifyAuthorizeRnrSuccessMsg();
}
| public void testSubmitAndAuthorizeRegimen(String program, String userSIC, String categoryCode, String password, String regimenCode, String regimenName, String regimenCode2, String regimenName2) throws Exception {
List<String> rightsList = new ArrayList<String>();
rightsList.add(CREATE_REQUISITION);
rightsList.add(VIEW_REQUISITION);
rightsList.add(AUTHORIZE_REQUISITION);
setupTestDataToInitiateRnR(true, program, userSIC, "200", "openLmis", rightsList);
dbWrapper.insertRegimenTemplateConfiguredForProgram(program, categoryCode, regimenCode, regimenName, true);
dbWrapper.insertRegimenTemplateConfiguredForProgram(program, categoryCode, regimenCode2, regimenName2, false);
dbWrapper.insertRegimenTemplateColumnsForProgram(program);
LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal);
HomePage homePage = loginPage.loginAs(userSIC, password);
homePage.navigateAndInitiateRnr(program);
InitiateRnRPage initiateRnRPage = homePage.clickProceed();
dbWrapper.insertValuesInRequisition();
homePage.navigateAndInitiateRnr(program);
InitiateRnRPage initiateRnRPage1 = homePage.clickProceed();
initiateRnRPage1.clickRegimenTab();
verifyRegimenFieldsPresentOnRegimenTab(regimenCode, regimenName, initiateRnRPage, initiateRnRPage1);
initiateRnRPage1.enterValuesOnRegimenScreen(3, 2, 100);
initiateRnRPage1.enterValuesOnRegimenScreen(4, 2, 200);
initiateRnRPage1.enterValuesOnRegimenScreen(6, 2, 400);
initiateRnRPage1.clickSubmitButton();
initiateRnRPage1.verifySubmitRnrErrorMsg();
initiateRnRPage1.enterValuesOnRegimenScreen(5, 2, 300);
initiateRnRPage1.clickSubmitButton();
initiateRnRPage1.clickOk();
initiateRnRPage1.verifySubmitSuccessMsg();
homePage.navigateAndInitiateRnr(program);
InitiateRnRPage initiateRnRPage2 = homePage.clickProceed();
initiateRnRPage2.clickRegimenTab();
verifyValuesOnRegimenScreen(initiateRnRPage2,"100","200","300","400");
initiateRnRPage2.clickAuthorizeButton();
initiateRnRPage2.clickOk();
initiateRnRPage2.verifyAuthorizeRnrSuccessMsg();
}
|
diff --git a/src/com/android/bluetooth/hid/HidService.java b/src/com/android/bluetooth/hid/HidService.java
index e0d7be7..5cccb09 100755
--- a/src/com/android/bluetooth/hid/HidService.java
+++ b/src/com/android/bluetooth/hid/HidService.java
@@ -1,560 +1,572 @@
/*
* Copyright (C) 2012 Google Inc.
*/
package com.android.bluetooth.hid;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothInputDevice;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.IBluetooth;
import android.bluetooth.IBluetoothInputDevice;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.provider.Settings;
import android.util.Log;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.android.bluetooth.Utils;
import android.content.pm.PackageManager;
import com.android.bluetooth.btservice.ProfileService;
/**
* Provides Bluetooth Hid Host profile, as a service in
* the Bluetooth application.
* @hide
*/
public class HidService extends ProfileService {
private static final boolean DBG = true;
private static final String TAG = "HidService";
private Map<BluetoothDevice, Integer> mInputDevices;
private boolean mNativeAvailable;
private static final int MESSAGE_CONNECT = 1;
private static final int MESSAGE_DISCONNECT = 2;
private static final int MESSAGE_CONNECT_STATE_CHANGED = 3;
private static final int MESSAGE_GET_PROTOCOL_MODE = 4;
private static final int MESSAGE_VIRTUAL_UNPLUG = 5;
private static final int MESSAGE_ON_GET_PROTOCOL_MODE = 6;
private static final int MESSAGE_SET_PROTOCOL_MODE = 7;
private static final int MESSAGE_GET_REPORT = 8;
private static final int MESSAGE_ON_GET_REPORT = 9;
private static final int MESSAGE_SET_REPORT = 10;
private static final int MESSAGE_SEND_DATA = 11;
private static final int MESSAGE_ON_VIRTUAL_UNPLUG = 12;
static {
classInitNative();
}
public String getName() {
return TAG;
}
public IProfileServiceBinder initBinder() {
return new BluetoothInputDeviceBinder(this);
}
protected boolean start() {
mInputDevices = Collections.synchronizedMap(new HashMap<BluetoothDevice, Integer>());
initializeNative();
mNativeAvailable=true;
return true;
}
protected boolean stop() {
if (DBG) log("Stopping Bluetooth HidService");
return true;
}
protected boolean cleanup() {
if (mNativeAvailable) {
cleanupNative();
mNativeAvailable=false;
}
if(mInputDevices != null) {
mInputDevices.clear();
mInputDevices = null;
}
return true;
}
private final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_CONNECT:
{
BluetoothDevice device = (BluetoothDevice) msg.obj;
if (!connectHidNative(Utils.getByteAddress(device)) ) {
broadcastConnectionState(device, BluetoothProfile.STATE_DISCONNECTING);
broadcastConnectionState(device, BluetoothProfile.STATE_DISCONNECTED);
break;
}
}
break;
case MESSAGE_DISCONNECT:
{
BluetoothDevice device = (BluetoothDevice) msg.obj;
if (!disconnectHidNative(Utils.getByteAddress(device)) ) {
broadcastConnectionState(device, BluetoothProfile.STATE_DISCONNECTING);
broadcastConnectionState(device, BluetoothProfile.STATE_DISCONNECTED);
break;
}
}
break;
case MESSAGE_CONNECT_STATE_CHANGED:
{
BluetoothDevice device = getDevice((byte[]) msg.obj);
int halState = msg.arg1;
- broadcastConnectionState(device, convertHalState(halState));
+ Integer prevStateInteger = mInputDevices.get(device);
+ int prevState = (prevStateInteger == null) ?
+ BluetoothInputDevice.STATE_DISCONNECTED :prevStateInteger;
+ if(DBG) Log.d(TAG, "MESSAGE_CONNECT_STATE_CHANGED newState:"+
+ convertHalState(halState)+", prevState:"+prevState);
+ if(halState == CONN_STATE_CONNECTED &&
+ prevState == BluetoothInputDevice.STATE_DISCONNECTED &&
+ BluetoothProfile.PRIORITY_OFF >= getPriority(device)) {
+ Log.d(TAG,"Incoming HID connection rejected");
+ disconnectHidNative(Utils.getByteAddress(device));
+ } else {
+ broadcastConnectionState(device, convertHalState(halState));
+ }
}
break;
case MESSAGE_GET_PROTOCOL_MODE:
{
BluetoothDevice device = (BluetoothDevice) msg.obj;
if(!getProtocolModeNative(Utils.getByteAddress(device)) ) {
Log.e(TAG, "Error: get protocol mode native returns false");
}
}
break;
case MESSAGE_ON_GET_PROTOCOL_MODE:
{
BluetoothDevice device = getDevice((byte[]) msg.obj);
int protocolMode = msg.arg1;
broadcastProtocolMode(device, protocolMode);
}
break;
case MESSAGE_VIRTUAL_UNPLUG:
{
BluetoothDevice device = (BluetoothDevice) msg.obj;
if(!virtualUnPlugNative(Utils.getByteAddress(device))) {
Log.e(TAG, "Error: virtual unplug native returns false");
}
}
break;
case MESSAGE_SET_PROTOCOL_MODE:
{
BluetoothDevice device = (BluetoothDevice) msg.obj;
byte protocolMode = (byte) msg.arg1;
log("sending set protocol mode(" + protocolMode + ")");
if(!setProtocolModeNative(Utils.getByteAddress(device), protocolMode)) {
Log.e(TAG, "Error: set protocol mode native returns false");
}
}
break;
case MESSAGE_GET_REPORT:
{
BluetoothDevice device = (BluetoothDevice) msg.obj;
Bundle data = msg.getData();
byte reportType = data.getByte(BluetoothInputDevice.EXTRA_REPORT_TYPE);
byte reportId = data.getByte(BluetoothInputDevice.EXTRA_REPORT_ID);
int bufferSize = data.getInt(BluetoothInputDevice.EXTRA_REPORT_BUFFER_SIZE);
if(!getReportNative(Utils.getByteAddress(device), reportType, reportId, bufferSize)) {
Log.e(TAG, "Error: get report native returns false");
}
}
break;
case MESSAGE_SET_REPORT:
{
BluetoothDevice device = (BluetoothDevice) msg.obj;
Bundle data = msg.getData();
byte reportType = data.getByte(BluetoothInputDevice.EXTRA_REPORT_TYPE);
String report = data.getString(BluetoothInputDevice.EXTRA_REPORT);
if(!setReportNative(Utils.getByteAddress(device), reportType, report)) {
Log.e(TAG, "Error: set report native returns false");
}
}
break;
case MESSAGE_SEND_DATA:
{
BluetoothDevice device = (BluetoothDevice) msg.obj;
Bundle data = msg.getData();
String report = data.getString(BluetoothInputDevice.EXTRA_REPORT);
if(!sendDataNative(Utils.getByteAddress(device), report)) {
Log.e(TAG, "Error: send data native returns false");
}
}
break;
case MESSAGE_ON_VIRTUAL_UNPLUG:
{
BluetoothDevice device = getDevice((byte[]) msg.obj);
int status = msg.arg1;
broadcastVirtualUnplugStatus(device, status);
}
break;
}
}
};
/**
* Handlers for incoming service calls
*/
private static class BluetoothInputDeviceBinder extends IBluetoothInputDevice.Stub implements IProfileServiceBinder{
private HidService mService;
public BluetoothInputDeviceBinder(HidService svc) {
mService = svc;
}
public boolean cleanup() {
mService = null;
return true;
}
private HidService getService() {
if (mService != null && mService.isAvailable()) {
return mService;
}
return null;
}
public boolean connect(BluetoothDevice device) {
HidService service = getService();
if (service == null) return false;
return service.connect(device);
}
public boolean disconnect(BluetoothDevice device) {
HidService service = getService();
if (service == null) return false;
return service.disconnect(device);
}
public int getConnectionState(BluetoothDevice device) {
HidService service = getService();
if (service == null) return BluetoothInputDevice.STATE_DISCONNECTED;
return service.getConnectionState(device);
}
public List<BluetoothDevice> getConnectedDevices() {
return getDevicesMatchingConnectionStates(
new int[] {BluetoothProfile.STATE_CONNECTED});
}
public List<BluetoothDevice> getDevicesMatchingConnectionStates(int[] states) {
HidService service = getService();
if (service == null) return new ArrayList<BluetoothDevice>(0);
return service.getDevicesMatchingConnectionStates(states);
}
public boolean setPriority(BluetoothDevice device, int priority) {
HidService service = getService();
if (service == null) return false;
return service.setPriority(device, priority);
}
public int getPriority(BluetoothDevice device) {
HidService service = getService();
if (service == null) return BluetoothProfile.PRIORITY_UNDEFINED;
return service.getPriority(device);
}
/* The following APIs regarding test app for compliance */
public boolean getProtocolMode(BluetoothDevice device) {
HidService service = getService();
if (service == null) return false;
return service.getProtocolMode(device);
}
public boolean virtualUnplug(BluetoothDevice device) {
HidService service = getService();
if (service == null) return false;
return service.virtualUnplug(device);
}
public boolean setProtocolMode(BluetoothDevice device, int protocolMode) {
HidService service = getService();
if (service == null) return false;
return service.setProtocolMode(device, protocolMode);
}
public boolean getReport(BluetoothDevice device, byte reportType, byte reportId, int bufferSize) {
HidService service = getService();
if (service == null) return false;
return service.getReport(device, reportType, reportId, bufferSize) ;
}
public boolean setReport(BluetoothDevice device, byte reportType, String report) {
HidService service = getService();
if (service == null) return false;
return service.setReport(device, reportType, report);
}
public boolean sendData(BluetoothDevice device, String report) {
HidService service = getService();
if (service == null) return false;
return service.sendData(device, report);
}
};
//APIs
boolean connect(BluetoothDevice device) {
enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");
if (getConnectionState(device) != BluetoothInputDevice.STATE_DISCONNECTED) {
Log.e(TAG, "Hid Device not disconnected: " + device);
return false;
}
if (getPriority(device) == BluetoothInputDevice.PRIORITY_OFF) {
Log.e(TAG, "Hid Device PRIORITY_OFF: " + device);
return false;
}
Message msg = mHandler.obtainMessage(MESSAGE_CONNECT, device);
mHandler.sendMessage(msg);
return true;
}
boolean disconnect(BluetoothDevice device) {
enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");
Message msg = mHandler.obtainMessage(MESSAGE_DISCONNECT,device);
mHandler.sendMessage(msg);
return true;
}
int getConnectionState(BluetoothDevice device) {
if (mInputDevices.get(device) == null) {
return BluetoothInputDevice.STATE_DISCONNECTED;
}
return mInputDevices.get(device);
}
List<BluetoothDevice> getDevicesMatchingConnectionStates(int[] states) {
enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");
List<BluetoothDevice> inputDevices = new ArrayList<BluetoothDevice>();
for (BluetoothDevice device: mInputDevices.keySet()) {
int inputDeviceState = getConnectionState(device);
for (int state : states) {
if (state == inputDeviceState) {
inputDevices.add(device);
break;
}
}
}
return inputDevices;
}
boolean setPriority(BluetoothDevice device, int priority) {
enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
"Need BLUETOOTH_ADMIN permission");
Settings.Secure.putInt(getContentResolver(),
Settings.Secure.getBluetoothInputDevicePriorityKey(device.getAddress()),
priority);
if (DBG) Log.d(TAG,"Saved priority " + device + " = " + priority);
return true;
}
int getPriority(BluetoothDevice device) {
enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
"Need BLUETOOTH_ADMIN permission");
int priority = Settings.Secure.getInt(getContentResolver(),
Settings.Secure.getBluetoothInputDevicePriorityKey(device.getAddress()),
BluetoothProfile.PRIORITY_UNDEFINED);
return priority;
}
/* The following APIs regarding test app for compliance */
boolean getProtocolMode(BluetoothDevice device) {
enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
"Need BLUETOOTH_ADMIN permission");
int state = this.getConnectionState(device);
if (state != BluetoothInputDevice.STATE_CONNECTED) {
return false;
}
Message msg = mHandler.obtainMessage(MESSAGE_GET_PROTOCOL_MODE,device);
mHandler.sendMessage(msg);
return true;
/* String objectPath = getObjectPathFromAddress(device.getAddress());
return getProtocolModeInputDeviceNative(objectPath);*/
}
boolean virtualUnplug(BluetoothDevice device) {
enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
"Need BLUETOOTH_ADMIN permission");
int state = this.getConnectionState(device);
if (state != BluetoothInputDevice.STATE_CONNECTED) {
return false;
}
Message msg = mHandler.obtainMessage(MESSAGE_VIRTUAL_UNPLUG,device);
mHandler.sendMessage(msg);
return true;
}
boolean setProtocolMode(BluetoothDevice device, int protocolMode) {
enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
"Need BLUETOOTH_ADMIN permission");
int state = this.getConnectionState(device);
if (state != BluetoothInputDevice.STATE_CONNECTED) {
return false;
}
Message msg = mHandler.obtainMessage(MESSAGE_SET_PROTOCOL_MODE);
msg.obj = device;
msg.arg1 = protocolMode;
mHandler.sendMessage(msg);
return true ;
}
boolean getReport(BluetoothDevice device, byte reportType, byte reportId, int bufferSize) {
enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
"Need BLUETOOTH_ADMIN permission");
int state = this.getConnectionState(device);
if (state != BluetoothInputDevice.STATE_CONNECTED) {
return false;
}
Message msg = mHandler.obtainMessage(MESSAGE_GET_REPORT);
msg.obj = device;
Bundle data = new Bundle();
data.putByte(BluetoothInputDevice.EXTRA_REPORT_TYPE, reportType);
data.putByte(BluetoothInputDevice.EXTRA_REPORT_ID, reportId);
data.putInt(BluetoothInputDevice.EXTRA_REPORT_BUFFER_SIZE, bufferSize);
msg.setData(data);
mHandler.sendMessage(msg);
return true ;
}
boolean setReport(BluetoothDevice device, byte reportType, String report) {
enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
"Need BLUETOOTH_ADMIN permission");
int state = this.getConnectionState(device);
if (state != BluetoothInputDevice.STATE_CONNECTED) {
return false;
}
Message msg = mHandler.obtainMessage(MESSAGE_SET_REPORT);
msg.obj = device;
Bundle data = new Bundle();
data.putByte(BluetoothInputDevice.EXTRA_REPORT_TYPE, reportType);
data.putString(BluetoothInputDevice.EXTRA_REPORT, report);
msg.setData(data);
mHandler.sendMessage(msg);
return true ;
}
boolean sendData(BluetoothDevice device, String report) {
enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
"Need BLUETOOTH_ADMIN permission");
int state = this.getConnectionState(device);
if (state != BluetoothInputDevice.STATE_CONNECTED) {
return false;
}
return sendDataNative(Utils.getByteAddress(device), report);
/*Message msg = mHandler.obtainMessage(MESSAGE_SEND_DATA);
msg.obj = device;
Bundle data = new Bundle();
data.putString(BluetoothInputDevice.EXTRA_REPORT, report);
msg.setData(data);
mHandler.sendMessage(msg);
return true ;*/
}
private void onGetProtocolMode(byte[] address, int mode) {
Message msg = mHandler.obtainMessage(MESSAGE_ON_GET_PROTOCOL_MODE);
msg.obj = address;
msg.arg1 = mode;
mHandler.sendMessage(msg);
}
private void onVirtualUnplug(byte[] address, int status) {
Message msg = mHandler.obtainMessage(MESSAGE_ON_VIRTUAL_UNPLUG);
msg.obj = address;
msg.arg1 = status;
mHandler.sendMessage(msg);
}
private void onConnectStateChanged(byte[] address, int state) {
Message msg = mHandler.obtainMessage(MESSAGE_CONNECT_STATE_CHANGED);
msg.obj = address;
msg.arg1 = state;
mHandler.sendMessage(msg);
}
// This method does not check for error conditon (newState == prevState)
private void broadcastConnectionState(BluetoothDevice device, int newState) {
Integer prevStateInteger = mInputDevices.get(device);
int prevState = (prevStateInteger == null) ? BluetoothInputDevice.STATE_DISCONNECTED :
prevStateInteger;
if (prevState == newState) {
Log.w(TAG, "no state change: " + newState);
return;
}
mInputDevices.put(device, newState);
/* Notifying the connection state change of the profile before sending the intent for
connection state change, as it was causing a race condition, with the UI not being
updated with the correct connection state. */
if (DBG) log("Connection state " + device + ": " + prevState + "->" + newState);
notifyProfileConnectionStateChanged(device, BluetoothProfile.INPUT_DEVICE,
newState, prevState);
Intent intent = new Intent(BluetoothInputDevice.ACTION_CONNECTION_STATE_CHANGED);
intent.putExtra(BluetoothProfile.EXTRA_PREVIOUS_STATE, prevState);
intent.putExtra(BluetoothProfile.EXTRA_STATE, newState);
intent.putExtra(BluetoothDevice.EXTRA_DEVICE, device);
intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
sendBroadcast(intent, BLUETOOTH_PERM);
}
private void broadcastProtocolMode(BluetoothDevice device, int protocolMode) {
Intent intent = new Intent(BluetoothInputDevice.ACTION_PROTOCOL_MODE_CHANGED);
intent.putExtra(BluetoothDevice.EXTRA_DEVICE, device);
intent.putExtra(BluetoothInputDevice.EXTRA_PROTOCOL_MODE, protocolMode);
intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
sendBroadcast(intent, BLUETOOTH_PERM);
if (DBG) log("Protocol Mode (" + device + "): " + protocolMode);
}
private void broadcastVirtualUnplugStatus(BluetoothDevice device, int status) {
Intent intent = new Intent(BluetoothInputDevice.ACTION_VIRTUAL_UNPLUG_STATUS);
intent.putExtra(BluetoothDevice.EXTRA_DEVICE, device);
intent.putExtra(BluetoothInputDevice.EXTRA_VIRTUAL_UNPLUG_STATUS, status);
intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
sendBroadcast(intent, BLUETOOTH_PERM);
}
private static int convertHalState(int halState) {
switch (halState) {
case CONN_STATE_CONNECTED:
return BluetoothProfile.STATE_CONNECTED;
case CONN_STATE_CONNECTING:
return BluetoothProfile.STATE_CONNECTING;
case CONN_STATE_DISCONNECTED:
return BluetoothProfile.STATE_DISCONNECTED;
case CONN_STATE_DISCONNECTING:
return BluetoothProfile.STATE_DISCONNECTING;
default:
Log.e(TAG, "bad hid connection state: " + halState);
return BluetoothProfile.STATE_DISCONNECTED;
}
}
// Constants matching Hal header file bt_hh.h
// bthh_connection_state_t
private final static int CONN_STATE_CONNECTED = 0;
private final static int CONN_STATE_CONNECTING = 1;
private final static int CONN_STATE_DISCONNECTED = 2;
private final static int CONN_STATE_DISCONNECTING = 3;
private native static void classInitNative();
private native void initializeNative();
private native void cleanupNative();
private native boolean connectHidNative(byte[] btAddress);
private native boolean disconnectHidNative(byte[] btAddress);
private native boolean getProtocolModeNative(byte[] btAddress);
private native boolean virtualUnPlugNative(byte[] btAddress);
private native boolean setProtocolModeNative(byte[] btAddress, byte protocolMode);
private native boolean getReportNative(byte[]btAddress, byte reportType, byte reportId, int bufferSize);
private native boolean setReportNative(byte[] btAddress, byte reportType, String report);
private native boolean sendDataNative(byte[] btAddress, String report);
}
| true | true | public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_CONNECT:
{
BluetoothDevice device = (BluetoothDevice) msg.obj;
if (!connectHidNative(Utils.getByteAddress(device)) ) {
broadcastConnectionState(device, BluetoothProfile.STATE_DISCONNECTING);
broadcastConnectionState(device, BluetoothProfile.STATE_DISCONNECTED);
break;
}
}
break;
case MESSAGE_DISCONNECT:
{
BluetoothDevice device = (BluetoothDevice) msg.obj;
if (!disconnectHidNative(Utils.getByteAddress(device)) ) {
broadcastConnectionState(device, BluetoothProfile.STATE_DISCONNECTING);
broadcastConnectionState(device, BluetoothProfile.STATE_DISCONNECTED);
break;
}
}
break;
case MESSAGE_CONNECT_STATE_CHANGED:
{
BluetoothDevice device = getDevice((byte[]) msg.obj);
int halState = msg.arg1;
broadcastConnectionState(device, convertHalState(halState));
}
break;
case MESSAGE_GET_PROTOCOL_MODE:
{
BluetoothDevice device = (BluetoothDevice) msg.obj;
if(!getProtocolModeNative(Utils.getByteAddress(device)) ) {
Log.e(TAG, "Error: get protocol mode native returns false");
}
}
break;
case MESSAGE_ON_GET_PROTOCOL_MODE:
{
BluetoothDevice device = getDevice((byte[]) msg.obj);
int protocolMode = msg.arg1;
broadcastProtocolMode(device, protocolMode);
}
break;
case MESSAGE_VIRTUAL_UNPLUG:
{
BluetoothDevice device = (BluetoothDevice) msg.obj;
if(!virtualUnPlugNative(Utils.getByteAddress(device))) {
Log.e(TAG, "Error: virtual unplug native returns false");
}
}
break;
case MESSAGE_SET_PROTOCOL_MODE:
{
BluetoothDevice device = (BluetoothDevice) msg.obj;
byte protocolMode = (byte) msg.arg1;
log("sending set protocol mode(" + protocolMode + ")");
if(!setProtocolModeNative(Utils.getByteAddress(device), protocolMode)) {
Log.e(TAG, "Error: set protocol mode native returns false");
}
}
break;
case MESSAGE_GET_REPORT:
{
BluetoothDevice device = (BluetoothDevice) msg.obj;
Bundle data = msg.getData();
byte reportType = data.getByte(BluetoothInputDevice.EXTRA_REPORT_TYPE);
byte reportId = data.getByte(BluetoothInputDevice.EXTRA_REPORT_ID);
int bufferSize = data.getInt(BluetoothInputDevice.EXTRA_REPORT_BUFFER_SIZE);
if(!getReportNative(Utils.getByteAddress(device), reportType, reportId, bufferSize)) {
Log.e(TAG, "Error: get report native returns false");
}
}
break;
case MESSAGE_SET_REPORT:
{
BluetoothDevice device = (BluetoothDevice) msg.obj;
Bundle data = msg.getData();
byte reportType = data.getByte(BluetoothInputDevice.EXTRA_REPORT_TYPE);
String report = data.getString(BluetoothInputDevice.EXTRA_REPORT);
if(!setReportNative(Utils.getByteAddress(device), reportType, report)) {
Log.e(TAG, "Error: set report native returns false");
}
}
break;
case MESSAGE_SEND_DATA:
{
BluetoothDevice device = (BluetoothDevice) msg.obj;
Bundle data = msg.getData();
String report = data.getString(BluetoothInputDevice.EXTRA_REPORT);
if(!sendDataNative(Utils.getByteAddress(device), report)) {
Log.e(TAG, "Error: send data native returns false");
}
}
break;
case MESSAGE_ON_VIRTUAL_UNPLUG:
{
BluetoothDevice device = getDevice((byte[]) msg.obj);
int status = msg.arg1;
broadcastVirtualUnplugStatus(device, status);
}
break;
}
}
| public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_CONNECT:
{
BluetoothDevice device = (BluetoothDevice) msg.obj;
if (!connectHidNative(Utils.getByteAddress(device)) ) {
broadcastConnectionState(device, BluetoothProfile.STATE_DISCONNECTING);
broadcastConnectionState(device, BluetoothProfile.STATE_DISCONNECTED);
break;
}
}
break;
case MESSAGE_DISCONNECT:
{
BluetoothDevice device = (BluetoothDevice) msg.obj;
if (!disconnectHidNative(Utils.getByteAddress(device)) ) {
broadcastConnectionState(device, BluetoothProfile.STATE_DISCONNECTING);
broadcastConnectionState(device, BluetoothProfile.STATE_DISCONNECTED);
break;
}
}
break;
case MESSAGE_CONNECT_STATE_CHANGED:
{
BluetoothDevice device = getDevice((byte[]) msg.obj);
int halState = msg.arg1;
Integer prevStateInteger = mInputDevices.get(device);
int prevState = (prevStateInteger == null) ?
BluetoothInputDevice.STATE_DISCONNECTED :prevStateInteger;
if(DBG) Log.d(TAG, "MESSAGE_CONNECT_STATE_CHANGED newState:"+
convertHalState(halState)+", prevState:"+prevState);
if(halState == CONN_STATE_CONNECTED &&
prevState == BluetoothInputDevice.STATE_DISCONNECTED &&
BluetoothProfile.PRIORITY_OFF >= getPriority(device)) {
Log.d(TAG,"Incoming HID connection rejected");
disconnectHidNative(Utils.getByteAddress(device));
} else {
broadcastConnectionState(device, convertHalState(halState));
}
}
break;
case MESSAGE_GET_PROTOCOL_MODE:
{
BluetoothDevice device = (BluetoothDevice) msg.obj;
if(!getProtocolModeNative(Utils.getByteAddress(device)) ) {
Log.e(TAG, "Error: get protocol mode native returns false");
}
}
break;
case MESSAGE_ON_GET_PROTOCOL_MODE:
{
BluetoothDevice device = getDevice((byte[]) msg.obj);
int protocolMode = msg.arg1;
broadcastProtocolMode(device, protocolMode);
}
break;
case MESSAGE_VIRTUAL_UNPLUG:
{
BluetoothDevice device = (BluetoothDevice) msg.obj;
if(!virtualUnPlugNative(Utils.getByteAddress(device))) {
Log.e(TAG, "Error: virtual unplug native returns false");
}
}
break;
case MESSAGE_SET_PROTOCOL_MODE:
{
BluetoothDevice device = (BluetoothDevice) msg.obj;
byte protocolMode = (byte) msg.arg1;
log("sending set protocol mode(" + protocolMode + ")");
if(!setProtocolModeNative(Utils.getByteAddress(device), protocolMode)) {
Log.e(TAG, "Error: set protocol mode native returns false");
}
}
break;
case MESSAGE_GET_REPORT:
{
BluetoothDevice device = (BluetoothDevice) msg.obj;
Bundle data = msg.getData();
byte reportType = data.getByte(BluetoothInputDevice.EXTRA_REPORT_TYPE);
byte reportId = data.getByte(BluetoothInputDevice.EXTRA_REPORT_ID);
int bufferSize = data.getInt(BluetoothInputDevice.EXTRA_REPORT_BUFFER_SIZE);
if(!getReportNative(Utils.getByteAddress(device), reportType, reportId, bufferSize)) {
Log.e(TAG, "Error: get report native returns false");
}
}
break;
case MESSAGE_SET_REPORT:
{
BluetoothDevice device = (BluetoothDevice) msg.obj;
Bundle data = msg.getData();
byte reportType = data.getByte(BluetoothInputDevice.EXTRA_REPORT_TYPE);
String report = data.getString(BluetoothInputDevice.EXTRA_REPORT);
if(!setReportNative(Utils.getByteAddress(device), reportType, report)) {
Log.e(TAG, "Error: set report native returns false");
}
}
break;
case MESSAGE_SEND_DATA:
{
BluetoothDevice device = (BluetoothDevice) msg.obj;
Bundle data = msg.getData();
String report = data.getString(BluetoothInputDevice.EXTRA_REPORT);
if(!sendDataNative(Utils.getByteAddress(device), report)) {
Log.e(TAG, "Error: send data native returns false");
}
}
break;
case MESSAGE_ON_VIRTUAL_UNPLUG:
{
BluetoothDevice device = getDevice((byte[]) msg.obj);
int status = msg.arg1;
broadcastVirtualUnplugStatus(device, status);
}
break;
}
}
|
diff --git a/src/main/java/com/github/sebhoss/reguloj/LimitedRuleEngine.java b/src/main/java/com/github/sebhoss/reguloj/LimitedRuleEngine.java
index cf966e4..fc88bd9 100644
--- a/src/main/java/com/github/sebhoss/reguloj/LimitedRuleEngine.java
+++ b/src/main/java/com/github/sebhoss/reguloj/LimitedRuleEngine.java
@@ -1,37 +1,37 @@
/*
* Copyright © 2010 Sebastian Hoß <[email protected]>
* This work is free. You can redistribute it and/or modify it under the
* terms of the Do What The Fuck You Want To Public License, Version 2,
* as published by Sam Hocevar. See http://www.wtfpl.net/ for more details.
*/
package com.github.sebhoss.reguloj;
import com.google.common.base.Preconditions;
final class LimitedRuleEngine<CONTEXT extends Context<?>> extends AbstractRuleEngine<CONTEXT> {
private final int maximumNumberOfRuns;
LimitedRuleEngine(final int maximumNumberOfRuns) {
Preconditions.checkArgument(maximumNumberOfRuns > 0);
this.maximumNumberOfRuns = maximumNumberOfRuns;
}
@Override
public boolean infer(final Iterable<Rule<CONTEXT>> rules, final CONTEXT context) {
boolean changeOccured = false;
int currentRuns = 0;
while (performSinglePass(rules, context)) {
changeOccured = true;
- if (++currentRuns > maximumNumberOfRuns) {
+ if (++currentRuns >= maximumNumberOfRuns) {
break;
}
}
return changeOccured;
}
}
| true | true | public boolean infer(final Iterable<Rule<CONTEXT>> rules, final CONTEXT context) {
boolean changeOccured = false;
int currentRuns = 0;
while (performSinglePass(rules, context)) {
changeOccured = true;
if (++currentRuns > maximumNumberOfRuns) {
break;
}
}
return changeOccured;
}
| public boolean infer(final Iterable<Rule<CONTEXT>> rules, final CONTEXT context) {
boolean changeOccured = false;
int currentRuns = 0;
while (performSinglePass(rules, context)) {
changeOccured = true;
if (++currentRuns >= maximumNumberOfRuns) {
break;
}
}
return changeOccured;
}
|
diff --git a/plugins/org.bonitasoft.studio.properties/src/org/bonitasoft/studio/properties/sections/timer/wizard/TimerConditionWizardPage.java b/plugins/org.bonitasoft.studio.properties/src/org/bonitasoft/studio/properties/sections/timer/wizard/TimerConditionWizardPage.java
index 87d484058c..650da49ace 100644
--- a/plugins/org.bonitasoft.studio.properties/src/org/bonitasoft/studio/properties/sections/timer/wizard/TimerConditionWizardPage.java
+++ b/plugins/org.bonitasoft.studio.properties/src/org/bonitasoft/studio/properties/sections/timer/wizard/TimerConditionWizardPage.java
@@ -1,239 +1,239 @@
/**
* Copyright (C) 2009 BonitaSoft S.A.
* BonitaSoft, 31 rue Gustave Eiffel - 38000 Grenoble
* 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.0 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, see <http://www.gnu.org/licenses/>.
*/
package org.bonitasoft.studio.properties.sections.timer.wizard;
import org.bonitasoft.studio.common.DateUtil;
import org.bonitasoft.studio.common.ExpressionConstants;
import org.bonitasoft.studio.common.emf.tools.ExpressionHelper;
import org.bonitasoft.studio.expression.editor.filter.AvailableExpressionTypeFilter;
import org.bonitasoft.studio.expression.editor.viewer.ExpressionViewer;
import org.bonitasoft.studio.model.expression.Expression;
import org.bonitasoft.studio.model.process.AbstractTimerEvent;
import org.bonitasoft.studio.model.process.ProcessPackage;
import org.bonitasoft.studio.pics.Pics;
import org.bonitasoft.studio.properties.i18n.Messages;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StackLayout;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Spinner;
/**
* @author Romain Bioteau
*/
public class TimerConditionWizardPage extends WizardPage {
private Expression condition;
private Spinner hourSpinner;
private Spinner daySpinner;
private Spinner minutesSpinner;
private Spinner secondsSpinner;
private final AbstractTimerEvent event;
private final SelectionAdapter updateConditionListener = new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
setCondition(ExpressionHelper.createConstantExpression(DateUtil.getWidgetMillisecond(null, null, daySpinner, hourSpinner, minutesSpinner, secondsSpinner),Long.class.getName()));
getContainer().updateButtons();
}
};
private ExpressionViewer dataChooser;
protected TimerConditionWizardPage(AbstractTimerEvent event, Expression condition) {
super("timerWizard");//$NON-NLS-1$
setImageDescriptor(Pics.getWizban());
setTitle(Messages.timerConditionWizardTitle);
this.condition = condition;
this.event = event;
}
@Override
public void createControl(Composite parent) {
parent.setLayout(new GridLayout(2, false));
Label deadlineTypeLabel = new Label(parent, SWT.NONE);
deadlineTypeLabel.setText(Messages.deadlineTypeLabel);
Composite radioDeadlineGroup = new Composite(parent, SWT.NONE);
radioDeadlineGroup.setLayout(new GridLayout(2, false));
final Button durationChoice;
durationChoice = new Button(radioDeadlineGroup, SWT.RADIO);
durationChoice.setText(Messages.durationLabel);
final Button varChoice = new Button(radioDeadlineGroup, SWT.RADIO);
varChoice.setText(Messages.varDataType);
final Composite deadlineComposite = new Composite(parent, SWT.NONE);
deadlineComposite.setLayout(new GridLayout(2, false));
GridData gd4 = new GridData();
gd4.horizontalSpan = 2;
deadlineComposite.setLayoutData(gd4);
final Composite parentDeadlineLayer = new Composite(deadlineComposite, SWT.NONE);
final StackLayout stack = new StackLayout();
parentDeadlineLayer.setLayout(stack);
GridData gd1 = new GridData();
gd1.horizontalSpan = 2;
gd1.horizontalIndent = -5;
parentDeadlineLayer.setLayoutData(gd1);
final Composite variableComposite = new Composite(parentDeadlineLayer, SWT.NONE);
variableComposite.setLayout(new GridLayout(2, false));
Label varLabel = new Label(variableComposite, SWT.NONE);
varLabel.setText(Messages.deadlineVarNameLabel);
gd1 = new GridData();
gd1.horizontalIndent = 10;
varLabel.setLayoutData(gd1);
dataChooser = new ExpressionViewer(variableComposite,SWT.BORDER, ProcessPackage.Literals.ABSTRACT_TIMER_EVENT__CONDITION);
dataChooser.getControl().setLayoutData(GridDataFactory.fillDefaults().grab(true, false).hint(250, SWT.DEFAULT).create());
dataChooser.addFilter(new AvailableExpressionTypeFilter(new String[]{ExpressionConstants.CONSTANT_TYPE,ExpressionConstants.SCRIPT_TYPE,ExpressionConstants.VARIABLE_TYPE}));
dataChooser.setInput(event);
dataChooser.setSelection(new StructuredSelection(condition));
final Composite durationComposite = new Composite(parentDeadlineLayer, SWT.NONE);
durationComposite.setLayout(new GridLayout(8, false));
Label dayLabel = new Label(durationComposite, SWT.NONE);
GridData gd3 = new GridData();
gd3.horizontalIndent = 100;
dayLabel.setLayoutData(gd3);
dayLabel.setText(org.bonitasoft.studio.common.Messages.daysLabel);
daySpinner = new Spinner(durationComposite, SWT.BORDER);
daySpinner.setMaximum(999);
Label hoursLabel = new Label(durationComposite, SWT.NONE);
hoursLabel.setText(org.bonitasoft.studio.common.Messages.hoursLabel);
hourSpinner = new Spinner(durationComposite, SWT.BORDER);
hourSpinner.setMaximum(999);
Label minutesLabel = new Label(durationComposite, SWT.NONE);
minutesLabel.setText(org.bonitasoft.studio.common.Messages.minutesLabel);
minutesSpinner = new Spinner(durationComposite, SWT.BORDER);
minutesSpinner.setMaximum(999);
Label secondsLabel = new Label(durationComposite, SWT.NONE);
secondsLabel.setText(org.bonitasoft.studio.common.Messages.secondsLabel);
secondsSpinner = new Spinner(durationComposite, SWT.BORDER);
secondsSpinner.setMaximum(999);
daySpinner.addSelectionListener(updateConditionListener);
hourSpinner.addSelectionListener(updateConditionListener);
minutesSpinner.addSelectionListener(updateConditionListener);
secondsSpinner.addSelectionListener(updateConditionListener);
durationChoice.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (durationChoice.getSelection()) {
setCondition(ExpressionHelper.createConstantExpression(DateUtil.getWidgetMillisecond(null, null, daySpinner, hourSpinner, minutesSpinner, secondsSpinner), Long.class.getName()));
stack.topControl = durationComposite;
parentDeadlineLayer.layout();
getContainer().updateButtons();
}
}
});
varChoice.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (varChoice.getSelection()) {
stack.topControl = variableComposite;
parentDeadlineLayer.layout();
getContainer().updateButtons();
}
}
});
if (condition == null) {
hourSpinner.setSelection(0);
daySpinner.setSelection(0);
minutesSpinner.setSelection(0);
secondsSpinner.setSelection(0);
}
String conditionContent = null;
if (getCondition() != null) {
conditionContent = getCondition().getContent();
}
- if (conditionContent != null) {
+ if (conditionContent != null && !conditionContent.isEmpty()) {
if (DateUtil.isDuration(conditionContent) && !ExpressionConstants.SCRIPT_TYPE.equals(getCondition().getType())) {
durationChoice.setSelection(true);
stack.topControl = durationComposite;
DateUtil.setWidgetDisplayDuration(null, null, daySpinner, hourSpinner, minutesSpinner, secondsSpinner, Long.parseLong(conditionContent));
} else {
varChoice.setSelection(true);
stack.topControl = variableComposite;
}
} else {
stack.topControl = durationComposite;
durationChoice.setSelection(true);
setCondition(ExpressionHelper.createConstantExpression("0",Long.class.getName())); //$NON-NLS-1$
}
parentDeadlineLayer.layout();
setControl(parent);
}
@Override
public boolean isPageComplete() {
return condition != null;
}
public void setCondition(Expression expressionCondition) {
condition = expressionCondition;
if(dataChooser != null && !dataChooser.getControl().isDisposed()){
dataChooser.setSelection(new StructuredSelection(condition));
}
}
public Expression getCondition() {
return condition;
}
}
| true | true | public void createControl(Composite parent) {
parent.setLayout(new GridLayout(2, false));
Label deadlineTypeLabel = new Label(parent, SWT.NONE);
deadlineTypeLabel.setText(Messages.deadlineTypeLabel);
Composite radioDeadlineGroup = new Composite(parent, SWT.NONE);
radioDeadlineGroup.setLayout(new GridLayout(2, false));
final Button durationChoice;
durationChoice = new Button(radioDeadlineGroup, SWT.RADIO);
durationChoice.setText(Messages.durationLabel);
final Button varChoice = new Button(radioDeadlineGroup, SWT.RADIO);
varChoice.setText(Messages.varDataType);
final Composite deadlineComposite = new Composite(parent, SWT.NONE);
deadlineComposite.setLayout(new GridLayout(2, false));
GridData gd4 = new GridData();
gd4.horizontalSpan = 2;
deadlineComposite.setLayoutData(gd4);
final Composite parentDeadlineLayer = new Composite(deadlineComposite, SWT.NONE);
final StackLayout stack = new StackLayout();
parentDeadlineLayer.setLayout(stack);
GridData gd1 = new GridData();
gd1.horizontalSpan = 2;
gd1.horizontalIndent = -5;
parentDeadlineLayer.setLayoutData(gd1);
final Composite variableComposite = new Composite(parentDeadlineLayer, SWT.NONE);
variableComposite.setLayout(new GridLayout(2, false));
Label varLabel = new Label(variableComposite, SWT.NONE);
varLabel.setText(Messages.deadlineVarNameLabel);
gd1 = new GridData();
gd1.horizontalIndent = 10;
varLabel.setLayoutData(gd1);
dataChooser = new ExpressionViewer(variableComposite,SWT.BORDER, ProcessPackage.Literals.ABSTRACT_TIMER_EVENT__CONDITION);
dataChooser.getControl().setLayoutData(GridDataFactory.fillDefaults().grab(true, false).hint(250, SWT.DEFAULT).create());
dataChooser.addFilter(new AvailableExpressionTypeFilter(new String[]{ExpressionConstants.CONSTANT_TYPE,ExpressionConstants.SCRIPT_TYPE,ExpressionConstants.VARIABLE_TYPE}));
dataChooser.setInput(event);
dataChooser.setSelection(new StructuredSelection(condition));
final Composite durationComposite = new Composite(parentDeadlineLayer, SWT.NONE);
durationComposite.setLayout(new GridLayout(8, false));
Label dayLabel = new Label(durationComposite, SWT.NONE);
GridData gd3 = new GridData();
gd3.horizontalIndent = 100;
dayLabel.setLayoutData(gd3);
dayLabel.setText(org.bonitasoft.studio.common.Messages.daysLabel);
daySpinner = new Spinner(durationComposite, SWT.BORDER);
daySpinner.setMaximum(999);
Label hoursLabel = new Label(durationComposite, SWT.NONE);
hoursLabel.setText(org.bonitasoft.studio.common.Messages.hoursLabel);
hourSpinner = new Spinner(durationComposite, SWT.BORDER);
hourSpinner.setMaximum(999);
Label minutesLabel = new Label(durationComposite, SWT.NONE);
minutesLabel.setText(org.bonitasoft.studio.common.Messages.minutesLabel);
minutesSpinner = new Spinner(durationComposite, SWT.BORDER);
minutesSpinner.setMaximum(999);
Label secondsLabel = new Label(durationComposite, SWT.NONE);
secondsLabel.setText(org.bonitasoft.studio.common.Messages.secondsLabel);
secondsSpinner = new Spinner(durationComposite, SWT.BORDER);
secondsSpinner.setMaximum(999);
daySpinner.addSelectionListener(updateConditionListener);
hourSpinner.addSelectionListener(updateConditionListener);
minutesSpinner.addSelectionListener(updateConditionListener);
secondsSpinner.addSelectionListener(updateConditionListener);
durationChoice.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (durationChoice.getSelection()) {
setCondition(ExpressionHelper.createConstantExpression(DateUtil.getWidgetMillisecond(null, null, daySpinner, hourSpinner, minutesSpinner, secondsSpinner), Long.class.getName()));
stack.topControl = durationComposite;
parentDeadlineLayer.layout();
getContainer().updateButtons();
}
}
});
varChoice.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (varChoice.getSelection()) {
stack.topControl = variableComposite;
parentDeadlineLayer.layout();
getContainer().updateButtons();
}
}
});
if (condition == null) {
hourSpinner.setSelection(0);
daySpinner.setSelection(0);
minutesSpinner.setSelection(0);
secondsSpinner.setSelection(0);
}
String conditionContent = null;
if (getCondition() != null) {
conditionContent = getCondition().getContent();
}
if (conditionContent != null) {
if (DateUtil.isDuration(conditionContent) && !ExpressionConstants.SCRIPT_TYPE.equals(getCondition().getType())) {
durationChoice.setSelection(true);
stack.topControl = durationComposite;
DateUtil.setWidgetDisplayDuration(null, null, daySpinner, hourSpinner, minutesSpinner, secondsSpinner, Long.parseLong(conditionContent));
} else {
varChoice.setSelection(true);
stack.topControl = variableComposite;
}
} else {
stack.topControl = durationComposite;
durationChoice.setSelection(true);
setCondition(ExpressionHelper.createConstantExpression("0",Long.class.getName())); //$NON-NLS-1$
}
parentDeadlineLayer.layout();
setControl(parent);
}
| public void createControl(Composite parent) {
parent.setLayout(new GridLayout(2, false));
Label deadlineTypeLabel = new Label(parent, SWT.NONE);
deadlineTypeLabel.setText(Messages.deadlineTypeLabel);
Composite radioDeadlineGroup = new Composite(parent, SWT.NONE);
radioDeadlineGroup.setLayout(new GridLayout(2, false));
final Button durationChoice;
durationChoice = new Button(radioDeadlineGroup, SWT.RADIO);
durationChoice.setText(Messages.durationLabel);
final Button varChoice = new Button(radioDeadlineGroup, SWT.RADIO);
varChoice.setText(Messages.varDataType);
final Composite deadlineComposite = new Composite(parent, SWT.NONE);
deadlineComposite.setLayout(new GridLayout(2, false));
GridData gd4 = new GridData();
gd4.horizontalSpan = 2;
deadlineComposite.setLayoutData(gd4);
final Composite parentDeadlineLayer = new Composite(deadlineComposite, SWT.NONE);
final StackLayout stack = new StackLayout();
parentDeadlineLayer.setLayout(stack);
GridData gd1 = new GridData();
gd1.horizontalSpan = 2;
gd1.horizontalIndent = -5;
parentDeadlineLayer.setLayoutData(gd1);
final Composite variableComposite = new Composite(parentDeadlineLayer, SWT.NONE);
variableComposite.setLayout(new GridLayout(2, false));
Label varLabel = new Label(variableComposite, SWT.NONE);
varLabel.setText(Messages.deadlineVarNameLabel);
gd1 = new GridData();
gd1.horizontalIndent = 10;
varLabel.setLayoutData(gd1);
dataChooser = new ExpressionViewer(variableComposite,SWT.BORDER, ProcessPackage.Literals.ABSTRACT_TIMER_EVENT__CONDITION);
dataChooser.getControl().setLayoutData(GridDataFactory.fillDefaults().grab(true, false).hint(250, SWT.DEFAULT).create());
dataChooser.addFilter(new AvailableExpressionTypeFilter(new String[]{ExpressionConstants.CONSTANT_TYPE,ExpressionConstants.SCRIPT_TYPE,ExpressionConstants.VARIABLE_TYPE}));
dataChooser.setInput(event);
dataChooser.setSelection(new StructuredSelection(condition));
final Composite durationComposite = new Composite(parentDeadlineLayer, SWT.NONE);
durationComposite.setLayout(new GridLayout(8, false));
Label dayLabel = new Label(durationComposite, SWT.NONE);
GridData gd3 = new GridData();
gd3.horizontalIndent = 100;
dayLabel.setLayoutData(gd3);
dayLabel.setText(org.bonitasoft.studio.common.Messages.daysLabel);
daySpinner = new Spinner(durationComposite, SWT.BORDER);
daySpinner.setMaximum(999);
Label hoursLabel = new Label(durationComposite, SWT.NONE);
hoursLabel.setText(org.bonitasoft.studio.common.Messages.hoursLabel);
hourSpinner = new Spinner(durationComposite, SWT.BORDER);
hourSpinner.setMaximum(999);
Label minutesLabel = new Label(durationComposite, SWT.NONE);
minutesLabel.setText(org.bonitasoft.studio.common.Messages.minutesLabel);
minutesSpinner = new Spinner(durationComposite, SWT.BORDER);
minutesSpinner.setMaximum(999);
Label secondsLabel = new Label(durationComposite, SWT.NONE);
secondsLabel.setText(org.bonitasoft.studio.common.Messages.secondsLabel);
secondsSpinner = new Spinner(durationComposite, SWT.BORDER);
secondsSpinner.setMaximum(999);
daySpinner.addSelectionListener(updateConditionListener);
hourSpinner.addSelectionListener(updateConditionListener);
minutesSpinner.addSelectionListener(updateConditionListener);
secondsSpinner.addSelectionListener(updateConditionListener);
durationChoice.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (durationChoice.getSelection()) {
setCondition(ExpressionHelper.createConstantExpression(DateUtil.getWidgetMillisecond(null, null, daySpinner, hourSpinner, minutesSpinner, secondsSpinner), Long.class.getName()));
stack.topControl = durationComposite;
parentDeadlineLayer.layout();
getContainer().updateButtons();
}
}
});
varChoice.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (varChoice.getSelection()) {
stack.topControl = variableComposite;
parentDeadlineLayer.layout();
getContainer().updateButtons();
}
}
});
if (condition == null) {
hourSpinner.setSelection(0);
daySpinner.setSelection(0);
minutesSpinner.setSelection(0);
secondsSpinner.setSelection(0);
}
String conditionContent = null;
if (getCondition() != null) {
conditionContent = getCondition().getContent();
}
if (conditionContent != null && !conditionContent.isEmpty()) {
if (DateUtil.isDuration(conditionContent) && !ExpressionConstants.SCRIPT_TYPE.equals(getCondition().getType())) {
durationChoice.setSelection(true);
stack.topControl = durationComposite;
DateUtil.setWidgetDisplayDuration(null, null, daySpinner, hourSpinner, minutesSpinner, secondsSpinner, Long.parseLong(conditionContent));
} else {
varChoice.setSelection(true);
stack.topControl = variableComposite;
}
} else {
stack.topControl = durationComposite;
durationChoice.setSelection(true);
setCondition(ExpressionHelper.createConstantExpression("0",Long.class.getName())); //$NON-NLS-1$
}
parentDeadlineLayer.layout();
setControl(parent);
}
|
diff --git a/org.openscada.hd.server.storage/src/org/openscada/hd/server/storage/osgi/ShiService.java b/org.openscada.hd.server.storage/src/org/openscada/hd/server/storage/osgi/ShiService.java
index c308bc8a0..55a00a420 100644
--- a/org.openscada.hd.server.storage/src/org/openscada/hd/server/storage/osgi/ShiService.java
+++ b/org.openscada.hd.server.storage/src/org/openscada/hd/server/storage/osgi/ShiService.java
@@ -1,210 +1,207 @@
package org.openscada.hd.server.storage.osgi;
import java.util.Calendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.Map.Entry;
import org.openscada.core.Variant;
import org.openscada.da.client.DataItemValue;
import org.openscada.hd.HistoricalItemInformation;
import org.openscada.hd.Query;
import org.openscada.hd.QueryListener;
import org.openscada.hd.QueryParameters;
import org.openscada.hd.Value;
import org.openscada.hd.ValueInformation;
import org.openscada.hd.server.common.StorageHistoricalItem;
import org.openscada.hd.server.storage.ConfigurationImpl;
import org.openscada.hd.server.storage.ExtendedStorageChannel;
import org.openscada.hd.server.storage.calculation.CalculationMethod;
import org.openscada.hd.server.storage.datatypes.DoubleValue;
import org.openscada.hd.server.storage.datatypes.LongValue;
import org.openscada.hd.server.storage.relict.RelictCleaner;
import org.openscada.hd.server.storage.relict.RelictCleanerCallerTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Implementation of StorageHistoricalItem as OSGi service.
* @author Ludwig Straub
*/
public class ShiService implements StorageHistoricalItem, RelictCleaner
{
/** The default logger. */
private final static Logger logger = LoggerFactory.getLogger ( ShiService.class );
/** Delay in milliseconds after that old data is deleted for the first time after initialization of the class. */
private final static long CLEANER_TASK_DELAY = 1000 * 60;
/** Period in milliseconds between two consecutive attemps to delete old data. */
private final static long CLEANER_TASK_PERIOD = 1000 * 60 * 10;
private final ConfigurationImpl configuration;
private final Map<CalculationMethod, ExtendedStorageChannel> storageChannels;
private ExtendedStorageChannel rootStorageChannel;
/** Flag indicating whether the service is currently running or not. */
private boolean started;
/** Timer that is used for deleting old data. */
private Timer deleteRelictsTimer;
public ShiService ( ConfigurationImpl configuration )
{
this.configuration = configuration;
storageChannels = new HashMap<CalculationMethod, ExtendedStorageChannel> ();
rootStorageChannel = null;
started = false;
}
public ConfigurationImpl getConfiguration ()
{
return configuration;
}
/**
* @see org.openscada.hd.server.common.StorageHistoricalItem#createQuery
*/
public Query createQuery ( final QueryParameters parameters, final QueryListener listener, final boolean updateData )
{
try
{
final Map<String, Value[]> map = new HashMap<String, Value[]> ();
ValueInformation[] valueInformations = null;
Set<String> calculationMethods = new HashSet<String> ();
for ( Entry<CalculationMethod, ExtendedStorageChannel> entry : storageChannels.entrySet () )
{
CalculationMethod calculationMethod = entry.getKey ();
DoubleValue[] dvs = entry.getValue ().getDoubleValues ( parameters.getStartTimestamp ().getTimeInMillis (), parameters.getEndTimestamp ().getTimeInMillis () );
Value[] values = new Value[dvs.length];
- if ( calculationMethod == CalculationMethod.NATIVE )
- {
- valueInformations = new ValueInformation[dvs.length];
- }
for ( int i = 0; i < dvs.length; i++ )
{
DoubleValue doubleValue = dvs[i];
values[i] = new Value ( doubleValue.getValue () );
- if ( calculationMethod == CalculationMethod.NATIVE )
+ if ( calculationMethod == CalculationMethod.AVERAGE )
{
+ valueInformations = new ValueInformation[dvs.length];
valueInformations[i] = new ValueInformation ( parameters.getStartTimestamp (), parameters.getEndTimestamp (), doubleValue.getQualityIndicator (), doubleValue.getBaseValueCount () );
}
}
- if ( calculationMethod != CalculationMethod.NATIVE )
+ if ( calculationMethod == CalculationMethod.AVERAGE )
{
- map.put ( CalculationMethod.convertCalculationMethodToString ( calculationMethod ), values );
+ map.put ( CalculationMethod.convertCalculationMethodToShortString ( calculationMethod ), values );
calculationMethods.add ( CalculationMethod.convertCalculationMethodToShortString ( calculationMethod ) );
}
}
listener.updateParameters ( parameters, calculationMethods );
listener.updateData ( 0, map, valueInformations );
}
catch ( Exception e )
{
}
return new Query () {
public void changeParameters ( QueryParameters parameters )
{
}
public void close ()
{
}
};
}
/**
* @see org.openscada.hd.server.common.StorageHistoricalItem#getInformation
*/
public HistoricalItemInformation getInformation ()
{
// FIXME: remove the whole method
return null;
}
/**
* @see org.openscada.hd.server.common.StorageHistoricalItem#updateData
*/
public synchronized void updateData ( DataItemValue value )
{
if ( !started || ( rootStorageChannel == null ) || ( value == null ) )
{
return;
}
Variant variant = value.getValue ();
if ( variant == null )
{
return;
}
final Calendar calendar = value.getTimestamp ();
final long time = calendar == null ? System.currentTimeMillis () : calendar.getTimeInMillis ();
final double qualityIndicator = !value.isConnected () || value.isError () ? 0 : 1;
try
{
if ( variant.isLong () || variant.isInteger () || variant.isBoolean () )
{
rootStorageChannel.updateLong ( new LongValue ( time, qualityIndicator, 1, variant.asLong ( 0L ) ) );
}
else
{
rootStorageChannel.updateDouble ( new DoubleValue ( time, qualityIndicator, 1, variant.asDouble ( 0.0 ) ) );
}
}
catch ( Exception e )
{
logger.error ( String.format ( "could not process value (%s)", variant ), e );
}
}
public synchronized void addStorageChannel ( ExtendedStorageChannel storageChannel, CalculationMethod calculationMethod )
{
storageChannels.put ( calculationMethod, storageChannel );
if ( calculationMethod == CalculationMethod.NATIVE )
{
rootStorageChannel = storageChannel;
}
}
/**
* This method activates the service processing.
* The methods updateData and createQuery only have effect after calling this method.
*/
public synchronized void start ()
{
deleteRelictsTimer = new Timer ();
deleteRelictsTimer.schedule ( new RelictCleanerCallerTask ( this ), CLEANER_TASK_DELAY, CLEANER_TASK_PERIOD );
started = true;
}
/**
* This method stops the service from processing and destroys its internal structure.
* The service cannot be started again, after stop has been called.
* After calling this method, no further call to this service can be made.
*/
public synchronized void stop ()
{
started = false;
if ( deleteRelictsTimer != null )
{
deleteRelictsTimer.cancel ();
deleteRelictsTimer.purge ();
deleteRelictsTimer = null;
}
}
/**
* @see org.openscada.hd.server.storage.relict.RelictCleaner#cleanupRelicts
*/
public synchronized void cleanupRelicts () throws Exception
{
if ( rootStorageChannel != null )
{
rootStorageChannel.cleanupRelicts ();
}
}
}
| false | true | public Query createQuery ( final QueryParameters parameters, final QueryListener listener, final boolean updateData )
{
try
{
final Map<String, Value[]> map = new HashMap<String, Value[]> ();
ValueInformation[] valueInformations = null;
Set<String> calculationMethods = new HashSet<String> ();
for ( Entry<CalculationMethod, ExtendedStorageChannel> entry : storageChannels.entrySet () )
{
CalculationMethod calculationMethod = entry.getKey ();
DoubleValue[] dvs = entry.getValue ().getDoubleValues ( parameters.getStartTimestamp ().getTimeInMillis (), parameters.getEndTimestamp ().getTimeInMillis () );
Value[] values = new Value[dvs.length];
if ( calculationMethod == CalculationMethod.NATIVE )
{
valueInformations = new ValueInformation[dvs.length];
}
for ( int i = 0; i < dvs.length; i++ )
{
DoubleValue doubleValue = dvs[i];
values[i] = new Value ( doubleValue.getValue () );
if ( calculationMethod == CalculationMethod.NATIVE )
{
valueInformations[i] = new ValueInformation ( parameters.getStartTimestamp (), parameters.getEndTimestamp (), doubleValue.getQualityIndicator (), doubleValue.getBaseValueCount () );
}
}
if ( calculationMethod != CalculationMethod.NATIVE )
{
map.put ( CalculationMethod.convertCalculationMethodToString ( calculationMethod ), values );
calculationMethods.add ( CalculationMethod.convertCalculationMethodToShortString ( calculationMethod ) );
}
}
listener.updateParameters ( parameters, calculationMethods );
listener.updateData ( 0, map, valueInformations );
}
catch ( Exception e )
{
}
return new Query () {
public void changeParameters ( QueryParameters parameters )
{
}
public void close ()
{
}
};
}
| public Query createQuery ( final QueryParameters parameters, final QueryListener listener, final boolean updateData )
{
try
{
final Map<String, Value[]> map = new HashMap<String, Value[]> ();
ValueInformation[] valueInformations = null;
Set<String> calculationMethods = new HashSet<String> ();
for ( Entry<CalculationMethod, ExtendedStorageChannel> entry : storageChannels.entrySet () )
{
CalculationMethod calculationMethod = entry.getKey ();
DoubleValue[] dvs = entry.getValue ().getDoubleValues ( parameters.getStartTimestamp ().getTimeInMillis (), parameters.getEndTimestamp ().getTimeInMillis () );
Value[] values = new Value[dvs.length];
for ( int i = 0; i < dvs.length; i++ )
{
DoubleValue doubleValue = dvs[i];
values[i] = new Value ( doubleValue.getValue () );
if ( calculationMethod == CalculationMethod.AVERAGE )
{
valueInformations = new ValueInformation[dvs.length];
valueInformations[i] = new ValueInformation ( parameters.getStartTimestamp (), parameters.getEndTimestamp (), doubleValue.getQualityIndicator (), doubleValue.getBaseValueCount () );
}
}
if ( calculationMethod == CalculationMethod.AVERAGE )
{
map.put ( CalculationMethod.convertCalculationMethodToShortString ( calculationMethod ), values );
calculationMethods.add ( CalculationMethod.convertCalculationMethodToShortString ( calculationMethod ) );
}
}
listener.updateParameters ( parameters, calculationMethods );
listener.updateData ( 0, map, valueInformations );
}
catch ( Exception e )
{
}
return new Query () {
public void changeParameters ( QueryParameters parameters )
{
}
public void close ()
{
}
};
}
|
diff --git a/src/main/java/com/nesscomputing/jdbc/C3P0DataSourceProvider.java b/src/main/java/com/nesscomputing/jdbc/C3P0DataSourceProvider.java
index 58189b9..27d6393 100644
--- a/src/main/java/com/nesscomputing/jdbc/C3P0DataSourceProvider.java
+++ b/src/main/java/com/nesscomputing/jdbc/C3P0DataSourceProvider.java
@@ -1,173 +1,172 @@
/**
* Copyright (C) 2012 Ness Computing, 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.nesscomputing.jdbc;
import java.lang.annotation.Annotation;
import java.net.URI;
import java.sql.SQLException;
import java.util.Properties;
import java.util.Set;
import javax.sql.DataSource;
import org.apache.commons.configuration.CombinedConfiguration;
import org.apache.commons.configuration.ConfigurationConverter;
import org.apache.commons.configuration.tree.OverrideCombiner;
import com.google.common.base.Function;
import com.google.common.base.Functions;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.inject.Binding;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.Provider;
import com.google.inject.ProvisionException;
import com.google.inject.TypeLiteral;
import com.mchange.v2.c3p0.DataSources;
import com.nesscomputing.config.Config;
import com.nesscomputing.config.util.ImmutableConfiguration;
import com.nesscomputing.lifecycle.LifecycleStage;
import com.nesscomputing.lifecycle.guice.AbstractLifecycleProvider;
import com.nesscomputing.lifecycle.guice.LifecycleAction;
import com.nesscomputing.logging.Log;
public class C3P0DataSourceProvider extends AbstractLifecycleProvider<DataSource> implements Provider<DataSource>
{
public static final String PREFIX = "ness.db.";
public static final String DEFAULTS_PREFIX = "ness.db.defaults";
private static final Log LOG = Log.findLog();
private Config config;
private Function<DataSource, DataSource> dataSourceWrapper = Functions.identity();
private final String dbName;
private URI uri = null;
private Properties props = null;
private final Annotation annotation;
private final String propertiesPrefix;
C3P0DataSourceProvider(final String dbName, final Annotation annotation)
{
this.dbName = dbName;
this.annotation = annotation;
this.propertiesPrefix = PREFIX + dbName;
addAction(LifecycleStage.STOP_STAGE, new LifecycleAction<DataSource>() {
@Override
public void performAction(final DataSource dataSource)
{
LOG.info("Destroying datasource %s", dbName);
try {
DataSources.destroy(dataSource);
}
catch (SQLException e) {
LOG.error(e, "Could not destroy pool %s", dbName);
}
}
});
}
@Inject(optional=true)
void setUpConfig(final Config config)
{
this.config = config;
}
@Inject(optional = true)
void injectDependencies(final Injector injector)
{
final Binding<Set<Function<DataSource, DataSource>>> datasourceBindings = injector.getExistingBinding(Key.get(new TypeLiteral<Set<Function<DataSource, DataSource>>> () { }, annotation));
if (datasourceBindings != null) {
for (Function<DataSource, DataSource> fn : datasourceBindings.getProvider().get()) {
dataSourceWrapper = Functions.compose(dataSourceWrapper, fn);
}
}
final Binding<Properties> propertiesBinding = injector.getExistingBinding(Key.get(Properties.class, annotation));
if (propertiesBinding != null) {
props = propertiesBinding.getProvider().get();
}
final Binding<URI> uriBinding = injector.getExistingBinding(Key.get(URI.class, annotation));
if (uriBinding != null) {
uri = uriBinding.getProvider().get();
Preconditions.checkArgument(uri != null, "the preset database URI must not be null!");
}
}
@Override
public DataSource internalGet()
{
try {
DataSource pool = createC3P0Pool();
DatabaseChecker.checkPool(pool);
return dataSourceWrapper.apply(pool);
} catch (SQLException e) {
throw new ProvisionException(String.format("Could not start DB pool %s", dbName), e);
}
}
private DataSource createC3P0Pool() throws SQLException
{
Preconditions.checkState(config != null, "Config object was never injected!");
final DatabaseConfig databaseConfig;
if (uri == null) {
LOG.info("Creating datasource %s via C3P0", dbName);
final DatabaseConfig dbConfig = config.getBean(DatabaseConfig.class, ImmutableMap.of("dbName", dbName));
databaseConfig = dbConfig;
}
else {
LOG.info("Using preset URI %s for %s via C3P0", uri, dbName);
databaseConfig = new ImmutableDatabaseConfig(uri);
}
final Properties poolProps = getProperties("pool");
LOG.info("Setting pool properties for %s to %s", dbName, poolProps);
final Properties driverProps = getProperties("ds");
LOG.info("Setting driver properties for %s to %s", dbName, driverProps);
DataSource unpooledDataSource = DataSources.unpooledDataSource(databaseConfig.getDbUri().toString(), driverProps);
DatabaseChecker.checkConnection(unpooledDataSource);
- final DataSource dataSource = DataSources.pooledDataSource(unpooledDataSource, poolProps);
- return dataSource;
+ return DataSources.pooledDataSource(unpooledDataSource, poolProps);
}
private Properties getProperties(final String suffix)
{
final CombinedConfiguration cc = new CombinedConfiguration(new OverrideCombiner());
if (props != null) {
// Allow setting of internal defaults by using "ds.xxx" and "pool.xxx" if a properties
// object is present.
cc.addConfiguration(new ImmutableConfiguration(ConfigurationConverter.getConfiguration(props).subset(suffix)));
}
if (config != null) {
cc.addConfiguration(config.getConfiguration(propertiesPrefix + "." + suffix));
cc.addConfiguration(config.getConfiguration(DEFAULTS_PREFIX + "." + suffix));
}
return ConfigurationConverter.getProperties(cc);
}
}
| true | true | private DataSource createC3P0Pool() throws SQLException
{
Preconditions.checkState(config != null, "Config object was never injected!");
final DatabaseConfig databaseConfig;
if (uri == null) {
LOG.info("Creating datasource %s via C3P0", dbName);
final DatabaseConfig dbConfig = config.getBean(DatabaseConfig.class, ImmutableMap.of("dbName", dbName));
databaseConfig = dbConfig;
}
else {
LOG.info("Using preset URI %s for %s via C3P0", uri, dbName);
databaseConfig = new ImmutableDatabaseConfig(uri);
}
final Properties poolProps = getProperties("pool");
LOG.info("Setting pool properties for %s to %s", dbName, poolProps);
final Properties driverProps = getProperties("ds");
LOG.info("Setting driver properties for %s to %s", dbName, driverProps);
DataSource unpooledDataSource = DataSources.unpooledDataSource(databaseConfig.getDbUri().toString(), driverProps);
DatabaseChecker.checkConnection(unpooledDataSource);
final DataSource dataSource = DataSources.pooledDataSource(unpooledDataSource, poolProps);
return dataSource;
}
| private DataSource createC3P0Pool() throws SQLException
{
Preconditions.checkState(config != null, "Config object was never injected!");
final DatabaseConfig databaseConfig;
if (uri == null) {
LOG.info("Creating datasource %s via C3P0", dbName);
final DatabaseConfig dbConfig = config.getBean(DatabaseConfig.class, ImmutableMap.of("dbName", dbName));
databaseConfig = dbConfig;
}
else {
LOG.info("Using preset URI %s for %s via C3P0", uri, dbName);
databaseConfig = new ImmutableDatabaseConfig(uri);
}
final Properties poolProps = getProperties("pool");
LOG.info("Setting pool properties for %s to %s", dbName, poolProps);
final Properties driverProps = getProperties("ds");
LOG.info("Setting driver properties for %s to %s", dbName, driverProps);
DataSource unpooledDataSource = DataSources.unpooledDataSource(databaseConfig.getDbUri().toString(), driverProps);
DatabaseChecker.checkConnection(unpooledDataSource);
return DataSources.pooledDataSource(unpooledDataSource, poolProps);
}
|
diff --git a/src/FE_SRC_COMMON/com/ForgeEssentials/WorldControl/TickTasks/TickTaskTopManipulator.java b/src/FE_SRC_COMMON/com/ForgeEssentials/WorldControl/TickTasks/TickTaskTopManipulator.java
index 48bb0cfe5..2209b92e6 100644
--- a/src/FE_SRC_COMMON/com/ForgeEssentials/WorldControl/TickTasks/TickTaskTopManipulator.java
+++ b/src/FE_SRC_COMMON/com/ForgeEssentials/WorldControl/TickTasks/TickTaskTopManipulator.java
@@ -1,91 +1,92 @@
package com.ForgeEssentials.WorldControl.TickTasks;
import net.minecraft.block.Block;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.world.World;
import com.ForgeEssentials.WorldControl.BlockArrayBackup;
import com.ForgeEssentials.WorldControl.ConfigWorldControl;
import com.ForgeEssentials.core.PlayerInfo;
import com.ForgeEssentials.util.BackupArea;
import com.ForgeEssentials.util.BlockSaveable;
import com.ForgeEssentials.util.ITickTask;
import com.ForgeEssentials.util.Localization;
import com.ForgeEssentials.util.OutputHandler;
import com.ForgeEssentials.util.AreaSelector.AreaBase;
import com.ForgeEssentials.util.AreaSelector.Point;
public class TickTaskTopManipulator extends TickTaskLoadBlocks
{
public enum Mode
{
THAW, // Removes top snow/ice block. Replaces ice with water.
FREEZE, // Replaces exposed water with ice.
SNOW, // Adds a dusting of snow to exposed non-liquid blocks.
TILL, // Transforms exposed grass & dirt into tilled farmland.
UNTILL, // Replaces farmland with bare dirt.
GREEN, // Turns dirt into grass.
}
private Mode effectMode;
public TickTaskTopManipulator(EntityPlayer player, AreaBase area, Mode mode)
{
super(player, area);
effectMode = mode;
}
protected boolean placeBlock() {
int blockID = world.getBlockId(x, y, z);
int aboveID = world.getBlockId(x, y+1, z);
int belowID = world.getBlockId(x, y-1, z);
boolean blockAbove = false;
boolean blockBelow = false;
if(Block.blocksList[aboveID]!=null&&!Block.blocksList[aboveID].isOpaqueCube()) blockAbove = true;
if(Block.blocksList[belowID]!=null&&!Block.blocksList[belowID].isOpaqueCube()) blockBelow = true;
switch (effectMode)
{
case THAW:
if (blockID == Block.ice.blockID)
{
return place(x, y, z, Block.waterMoving.blockID, 0);
}
else if (blockID == Block.snow.blockID)
{
return place(x, y, z, 0, 0);
}
break;
case FREEZE:
if (blockID == Block.waterMoving.blockID || blockID == Block.waterStill.blockID && !blockAbove)
{
return place(x, y, z, Block.ice.blockID, 0);
}
break;
case SNOW:
- if (blockID == 0 && blockBelow && (!Block.blocksList[belowID].isOpaqueCube() || Block.blocksList[belowID].isLeaves(world, x, y, z)))
- {
- return place(x, y, z, Block.snow.blockID, 0);
+ if (blockID == 0) {
+ if(blockBelow && (!Block.blocksList[belowID].isOpaqueCube() || Block.blocksList[belowID].isLeaves(world, x, y, z))) {
+ return place(x, y, z, Block.snow.blockID, 0);
+ }
}
break;
case TILL:
if ((blockID == Block.dirt.blockID || blockID == Block.grass.blockID) && !blockAbove)
{
return place(x, y, z, Block.tilledField.blockID, 0);
}
break;
case UNTILL:
if (blockID == Block.tilledField.blockID)
{
return place(x, y, z, Block.dirt.blockID, 0);
}
break;
case GREEN:
if (blockID == Block.dirt.blockID && !blockAbove)
{
return place(x, y, z, Block.grass.blockID, 0);
}
break;
}
return false;
}
}
| true | true | protected boolean placeBlock() {
int blockID = world.getBlockId(x, y, z);
int aboveID = world.getBlockId(x, y+1, z);
int belowID = world.getBlockId(x, y-1, z);
boolean blockAbove = false;
boolean blockBelow = false;
if(Block.blocksList[aboveID]!=null&&!Block.blocksList[aboveID].isOpaqueCube()) blockAbove = true;
if(Block.blocksList[belowID]!=null&&!Block.blocksList[belowID].isOpaqueCube()) blockBelow = true;
switch (effectMode)
{
case THAW:
if (blockID == Block.ice.blockID)
{
return place(x, y, z, Block.waterMoving.blockID, 0);
}
else if (blockID == Block.snow.blockID)
{
return place(x, y, z, 0, 0);
}
break;
case FREEZE:
if (blockID == Block.waterMoving.blockID || blockID == Block.waterStill.blockID && !blockAbove)
{
return place(x, y, z, Block.ice.blockID, 0);
}
break;
case SNOW:
if (blockID == 0 && blockBelow && (!Block.blocksList[belowID].isOpaqueCube() || Block.blocksList[belowID].isLeaves(world, x, y, z)))
{
return place(x, y, z, Block.snow.blockID, 0);
}
break;
case TILL:
if ((blockID == Block.dirt.blockID || blockID == Block.grass.blockID) && !blockAbove)
{
return place(x, y, z, Block.tilledField.blockID, 0);
}
break;
case UNTILL:
if (blockID == Block.tilledField.blockID)
{
return place(x, y, z, Block.dirt.blockID, 0);
}
break;
case GREEN:
if (blockID == Block.dirt.blockID && !blockAbove)
{
return place(x, y, z, Block.grass.blockID, 0);
}
break;
}
return false;
}
| protected boolean placeBlock() {
int blockID = world.getBlockId(x, y, z);
int aboveID = world.getBlockId(x, y+1, z);
int belowID = world.getBlockId(x, y-1, z);
boolean blockAbove = false;
boolean blockBelow = false;
if(Block.blocksList[aboveID]!=null&&!Block.blocksList[aboveID].isOpaqueCube()) blockAbove = true;
if(Block.blocksList[belowID]!=null&&!Block.blocksList[belowID].isOpaqueCube()) blockBelow = true;
switch (effectMode)
{
case THAW:
if (blockID == Block.ice.blockID)
{
return place(x, y, z, Block.waterMoving.blockID, 0);
}
else if (blockID == Block.snow.blockID)
{
return place(x, y, z, 0, 0);
}
break;
case FREEZE:
if (blockID == Block.waterMoving.blockID || blockID == Block.waterStill.blockID && !blockAbove)
{
return place(x, y, z, Block.ice.blockID, 0);
}
break;
case SNOW:
if (blockID == 0) {
if(blockBelow && (!Block.blocksList[belowID].isOpaqueCube() || Block.blocksList[belowID].isLeaves(world, x, y, z))) {
return place(x, y, z, Block.snow.blockID, 0);
}
}
break;
case TILL:
if ((blockID == Block.dirt.blockID || blockID == Block.grass.blockID) && !blockAbove)
{
return place(x, y, z, Block.tilledField.blockID, 0);
}
break;
case UNTILL:
if (blockID == Block.tilledField.blockID)
{
return place(x, y, z, Block.dirt.blockID, 0);
}
break;
case GREEN:
if (blockID == Block.dirt.blockID && !blockAbove)
{
return place(x, y, z, Block.grass.blockID, 0);
}
break;
}
return false;
}
|
diff --git a/runtime/src/main/java/org/qi4j/runtime/composite/AbstractModelFactory.java b/runtime/src/main/java/org/qi4j/runtime/composite/AbstractModelFactory.java
index b77c641ae..39b23179c 100644
--- a/runtime/src/main/java/org/qi4j/runtime/composite/AbstractModelFactory.java
+++ b/runtime/src/main/java/org/qi4j/runtime/composite/AbstractModelFactory.java
@@ -1,291 +1,292 @@
package org.qi4j.runtime.composite;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import net.sf.cglib.proxy.Factory;
import org.qi4j.composite.ConstraintDeclaration;
import org.qi4j.composite.scope.AssociationField;
import org.qi4j.composite.scope.AssociationParameter;
import org.qi4j.composite.scope.PropertyField;
import org.qi4j.composite.scope.PropertyParameter;
import org.qi4j.injection.InjectionScope;
import org.qi4j.injection.Optional;
import org.qi4j.spi.composite.ConstructorModel;
import org.qi4j.spi.composite.FieldModel;
import org.qi4j.spi.composite.InvalidCompositeException;
import org.qi4j.spi.composite.MethodModel;
import org.qi4j.spi.composite.ParameterConstraintsModel;
import org.qi4j.spi.composite.ParameterModel;
import org.qi4j.spi.injection.AssociationInjectionModel;
import org.qi4j.spi.injection.DependencyInjectionModel;
import org.qi4j.spi.injection.InjectionModel;
import org.qi4j.spi.injection.PropertyInjectionModel;
/**
* TODO
*/
public abstract class AbstractModelFactory
{
protected void getFieldModels( Class fragmentClass, Class fieldClass, Class compositeType, List<FieldModel> fieldModels )
{
Field[] fields = fieldClass.getDeclaredFields();
for( Field field : fields )
{
field.setAccessible( true );
Annotation[] annotations = field.getAnnotations();
InjectionModel injectionModel = null;
Annotation annotation = getInjectionAnnotation( annotations );
if( annotation != null )
{
// Only add fields which have injections
injectionModel = newInjectionModel( annotation, field.getGenericType(), fragmentClass, field );
FieldModel dependencyModel = new FieldModel( field, injectionModel );
fieldModels.add( dependencyModel );
}
}
// Add fields in superclass
Class<?> parent = fieldClass.getSuperclass();
if( parent != null && parent != Object.class )
{
getFieldModels( fragmentClass, parent, compositeType, fieldModels );
}
}
protected void getConstructorModels( Class mixinClass, Class compositeType, List<ConstructorModel> constructorModels )
{
Constructor[] constructors = mixinClass.getConstructors();
for( Constructor constructor : constructors )
{
Type[] parameterTypes = constructor.getGenericParameterTypes();
Constructor realConstructor;
if( Factory.class.isAssignableFrom( mixinClass ) )
{
// Abstract mixin - get annotations from superclass
try
{
realConstructor = mixinClass.getSuperclass().getConstructor( constructor.getParameterTypes() );
}
catch( NoSuchMethodException e )
{
throw new InvalidCompositeException( "Could not get constructor from abstract fragment of type" + mixinClass.getSuperclass(), compositeType );
}
}
else
{
realConstructor = constructor;
}
// This is required to be able to instantiate package protected class
realConstructor.setAccessible( true );
Annotation[][] parameterAnnotations = realConstructor.getParameterAnnotations();
List<ParameterModel> parameterModels = new ArrayList<ParameterModel>();
int idx = 0;
boolean hasInjections = false;
boolean hasNonInjectedParameters = false;
for( Type parameterType : parameterTypes )
{
Annotation[] parameterAnnotation = parameterAnnotations[ idx ];
ParameterModel parameterModel = getParameterModel( parameterAnnotation, mixinClass, parameterType );
if( parameterModel.getInjectionModel() == null )
{
hasNonInjectedParameters = true;
}
else
{
hasInjections = true;
}
parameterModels.add( parameterModel );
+ idx++;
}
if( hasInjections && hasNonInjectedParameters )
{
if( compositeType != null )
{
throw new InvalidCompositeException( "All parameters in constructor for " + mixinClass.getName() + " must be injected", compositeType );
}
}
else if( !hasNonInjectedParameters )
{
ConstructorModel constructorModel = new ConstructorModel( constructor, parameterModels, hasInjections );
constructorModels.add( constructorModel );
}
}
}
protected Collection<MethodModel> getMethodModels( Class fragmentClass )
{
List<MethodModel> models = new ArrayList<MethodModel>();
Class methodClass = fragmentClass;
while( !methodClass.equals( Object.class ) )
{
Method[] methods = methodClass.getDeclaredMethods();
for( Method method : methods )
{
MethodModel methodModel = newMethodModel( method, fragmentClass );
models.add( methodModel );
}
methodClass = methodClass.getSuperclass();
}
return models;
}
private MethodModel newMethodModel( Method method, Class fragmentClass )
{
Type[] parameterTypes = method.getGenericParameterTypes();
Annotation[][] parameterAnnotations = method.getParameterAnnotations();
List<ParameterModel> parameterModels = new ArrayList<ParameterModel>();
int idx = 0;
boolean hasInjections = false;
for( Type parameterType : parameterTypes )
{
Annotation[] parameterAnnotation = parameterAnnotations[ idx ];
ParameterModel parameterModel = getParameterModel( parameterAnnotation, fragmentClass, parameterType );
if( parameterModel.getInjectionModel() != null )
{
hasInjections = true;
}
parameterModels.add( parameterModel );
}
if( hasInjections )
{
method.setAccessible( true );
}
MethodModel methodModel = new MethodModel( method, parameterModels, hasInjections );
return methodModel;
}
protected ParameterModel getParameterModel( Annotation[] parameterAnnotation, Class methodClass, Type parameterType )
{
InjectionModel injectionModel = null;
List<Annotation> parameterConstraints = new ArrayList<Annotation>();
for( Annotation annotation : parameterAnnotation )
{
if( annotation.annotationType().getAnnotation( ConstraintDeclaration.class ) != null )
{
parameterConstraints.add( annotation );
}
else if( annotation.annotationType().getAnnotation( InjectionScope.class ) != null )
{
if( methodClass.isInterface() )
{
throw new InvalidCompositeException( "Not allowed to have injection annotations on interface parameters", methodClass );
}
if( injectionModel != null )
{
throw new InvalidCompositeException( "Not allowed to have multiple injection annotations on a single parameter", methodClass );
}
injectionModel = newInjectionModel( annotation, parameterType, methodClass, null );
}
}
ParameterConstraintsModel parameterConstraintsModel = null;
if( parameterConstraints.size() > 0 )
{
parameterConstraintsModel = new ParameterConstraintsModel( parameterConstraints );
}
ParameterModel parameterModel = new ParameterModel( parameterType, parameterConstraintsModel, injectionModel );
return parameterModel;
}
private InjectionModel newInjectionModel( Annotation annotation, Type injectionType, Class injectedType, Field field )
{
InjectionModel model;
if( annotation.annotationType().equals( PropertyField.class ) )
{
String name = ( (PropertyField) annotation ).value();
if( name.equals( "" ) )
{
name = field.getName();
}
boolean optional = ( (PropertyField) annotation ).optional();
model = new PropertyInjectionModel( annotation.annotationType(), injectionType, injectedType, optional, name );
}
else if( annotation.annotationType().equals( AssociationField.class ) )
{
String name = ( (AssociationField) annotation ).value();
if( name.equals( "" ) )
{
name = field.getName();
}
boolean optional = ( (AssociationField) annotation ).optional();
model = new AssociationInjectionModel( annotation.annotationType(), injectionType, injectedType, optional, name );
}
else if( annotation.annotationType().equals( PropertyParameter.class ) )
{
String name = ( (PropertyParameter) annotation ).value();
model = new PropertyInjectionModel( annotation.annotationType(), injectionType, injectedType, false, name );
}
else if( annotation.annotationType().equals( AssociationParameter.class ) )
{
String name = ( (AssociationParameter) annotation ).value();
model = new AssociationInjectionModel( annotation.annotationType(), injectionType, injectedType, false, name );
}
else
{
boolean optional = isOptional( annotation );
model = new DependencyInjectionModel( annotation.annotationType(), injectionType, injectedType, optional );
}
return model;
}
private boolean isOptional( Annotation annotation )
{
Method optionalMethod = getAnnotationMethod( Optional.class, annotation.annotationType() );
if( optionalMethod != null )
{
try
{
return Boolean.class.cast( optionalMethod.invoke( annotation ) );
}
catch( Exception e )
{
throw new InvalidCompositeException( "Could not get optional flag from annotation", annotation.getClass() );
}
}
return false;
}
private Method getAnnotationMethod( Class<? extends Annotation> anAnnotationClass, Class<? extends Annotation> aClass )
{
Method[] methods = aClass.getMethods();
for( Method method : methods )
{
if( method.getAnnotation( anAnnotationClass ) != null )
{
return method;
}
}
return null;
}
private Annotation getInjectionAnnotation( Annotation[] parameterAnnotation )
{
for( Annotation annotation : parameterAnnotation )
{
if( isDependencyAnnotation( annotation ) )
{
return annotation;
}
}
return null;
}
private boolean isDependencyAnnotation( Annotation annotation )
{
return annotation.annotationType().getAnnotation( InjectionScope.class ) != null;
}
}
| true | true | protected void getConstructorModels( Class mixinClass, Class compositeType, List<ConstructorModel> constructorModels )
{
Constructor[] constructors = mixinClass.getConstructors();
for( Constructor constructor : constructors )
{
Type[] parameterTypes = constructor.getGenericParameterTypes();
Constructor realConstructor;
if( Factory.class.isAssignableFrom( mixinClass ) )
{
// Abstract mixin - get annotations from superclass
try
{
realConstructor = mixinClass.getSuperclass().getConstructor( constructor.getParameterTypes() );
}
catch( NoSuchMethodException e )
{
throw new InvalidCompositeException( "Could not get constructor from abstract fragment of type" + mixinClass.getSuperclass(), compositeType );
}
}
else
{
realConstructor = constructor;
}
// This is required to be able to instantiate package protected class
realConstructor.setAccessible( true );
Annotation[][] parameterAnnotations = realConstructor.getParameterAnnotations();
List<ParameterModel> parameterModels = new ArrayList<ParameterModel>();
int idx = 0;
boolean hasInjections = false;
boolean hasNonInjectedParameters = false;
for( Type parameterType : parameterTypes )
{
Annotation[] parameterAnnotation = parameterAnnotations[ idx ];
ParameterModel parameterModel = getParameterModel( parameterAnnotation, mixinClass, parameterType );
if( parameterModel.getInjectionModel() == null )
{
hasNonInjectedParameters = true;
}
else
{
hasInjections = true;
}
parameterModels.add( parameterModel );
}
if( hasInjections && hasNonInjectedParameters )
{
if( compositeType != null )
{
throw new InvalidCompositeException( "All parameters in constructor for " + mixinClass.getName() + " must be injected", compositeType );
}
}
else if( !hasNonInjectedParameters )
{
ConstructorModel constructorModel = new ConstructorModel( constructor, parameterModels, hasInjections );
constructorModels.add( constructorModel );
}
}
}
| protected void getConstructorModels( Class mixinClass, Class compositeType, List<ConstructorModel> constructorModels )
{
Constructor[] constructors = mixinClass.getConstructors();
for( Constructor constructor : constructors )
{
Type[] parameterTypes = constructor.getGenericParameterTypes();
Constructor realConstructor;
if( Factory.class.isAssignableFrom( mixinClass ) )
{
// Abstract mixin - get annotations from superclass
try
{
realConstructor = mixinClass.getSuperclass().getConstructor( constructor.getParameterTypes() );
}
catch( NoSuchMethodException e )
{
throw new InvalidCompositeException( "Could not get constructor from abstract fragment of type" + mixinClass.getSuperclass(), compositeType );
}
}
else
{
realConstructor = constructor;
}
// This is required to be able to instantiate package protected class
realConstructor.setAccessible( true );
Annotation[][] parameterAnnotations = realConstructor.getParameterAnnotations();
List<ParameterModel> parameterModels = new ArrayList<ParameterModel>();
int idx = 0;
boolean hasInjections = false;
boolean hasNonInjectedParameters = false;
for( Type parameterType : parameterTypes )
{
Annotation[] parameterAnnotation = parameterAnnotations[ idx ];
ParameterModel parameterModel = getParameterModel( parameterAnnotation, mixinClass, parameterType );
if( parameterModel.getInjectionModel() == null )
{
hasNonInjectedParameters = true;
}
else
{
hasInjections = true;
}
parameterModels.add( parameterModel );
idx++;
}
if( hasInjections && hasNonInjectedParameters )
{
if( compositeType != null )
{
throw new InvalidCompositeException( "All parameters in constructor for " + mixinClass.getName() + " must be injected", compositeType );
}
}
else if( !hasNonInjectedParameters )
{
ConstructorModel constructorModel = new ConstructorModel( constructor, parameterModels, hasInjections );
constructorModels.add( constructorModel );
}
}
}
|
diff --git a/tmc-plugin/src/fi/helsinki/cs/tmc/model/LocalExerciseStatus.java b/tmc-plugin/src/fi/helsinki/cs/tmc/model/LocalExerciseStatus.java
index 22e28ff..04fd681 100644
--- a/tmc-plugin/src/fi/helsinki/cs/tmc/model/LocalExerciseStatus.java
+++ b/tmc-plugin/src/fi/helsinki/cs/tmc/model/LocalExerciseStatus.java
@@ -1,76 +1,76 @@
package fi.helsinki.cs.tmc.model;
import fi.helsinki.cs.tmc.data.Exercise;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.ObjectUtils;
/**
* Groups exercises by their statuses.
*/
public class LocalExerciseStatus {
public ArrayList<Exercise> open;
public ArrayList<Exercise> closed;
public ArrayList<Exercise> downloadableUncompleted;
public ArrayList<Exercise> downloadableCompleted;
public ArrayList<Exercise> updateable;
public ArrayList<Exercise> unlockable;
public static LocalExerciseStatus get(List<Exercise> allExercises) {
return new LocalExerciseStatus(CourseDb.getInstance(), ProjectMediator.getInstance(), allExercises);
}
private LocalExerciseStatus(CourseDb courseDb, ProjectMediator projectMediator, List<Exercise> allExercises) {
open = new ArrayList<Exercise>();
closed = new ArrayList<Exercise>();
downloadableUncompleted = new ArrayList<Exercise>();
downloadableCompleted = new ArrayList<Exercise>();
updateable = new ArrayList<Exercise>();
unlockable = new ArrayList<Exercise>();
for (Exercise ex : allExercises) {
if (!ex.hasDeadlinePassed()) {
TmcProjectInfo proj = projectMediator.tryGetProjectForExercise(ex);
boolean isDownloaded = proj != null;
if (courseDb.isUnlockable(ex)) {
unlockable.add(ex);
} else if (!isDownloaded && !ex.isLocked()) {
if (ex.isCompleted()) {
downloadableCompleted.add(ex);
} else {
downloadableUncompleted.add(ex);
}
- } else if (projectMediator.isProjectOpen(proj)) {
+ } else if (isDownloaded && projectMediator.isProjectOpen(proj)) {
open.add(ex);
} else {
closed.add(ex); // TODO: all projects may end up here if this is queried too early
}
String downloadedChecksum = courseDb.getDownloadedExerciseChecksum(ex.getKey());
if (isDownloaded && ObjectUtils.notEqual(downloadedChecksum, ex.getChecksum())) {
updateable.add(ex);
}
}
}
}
public boolean thereIsSomethingToDownload(boolean includeCompleted) {
return !unlockable.isEmpty() ||
!downloadableUncompleted.isEmpty() ||
!updateable.isEmpty() ||
(includeCompleted && !downloadableCompleted.isEmpty());
}
@Override
public String toString() {
return
"Unlockable: " + unlockable + "\n" +
"Open: " + open + "\n" +
"Closed: " + closed + "\n" +
"Downloadable uncompleted: " + downloadableUncompleted + "\n" +
"Downloadable completed: " + downloadableCompleted + "\n" +
"Updateable: " + updateable + "\n";
}
}
| true | true | private LocalExerciseStatus(CourseDb courseDb, ProjectMediator projectMediator, List<Exercise> allExercises) {
open = new ArrayList<Exercise>();
closed = new ArrayList<Exercise>();
downloadableUncompleted = new ArrayList<Exercise>();
downloadableCompleted = new ArrayList<Exercise>();
updateable = new ArrayList<Exercise>();
unlockable = new ArrayList<Exercise>();
for (Exercise ex : allExercises) {
if (!ex.hasDeadlinePassed()) {
TmcProjectInfo proj = projectMediator.tryGetProjectForExercise(ex);
boolean isDownloaded = proj != null;
if (courseDb.isUnlockable(ex)) {
unlockable.add(ex);
} else if (!isDownloaded && !ex.isLocked()) {
if (ex.isCompleted()) {
downloadableCompleted.add(ex);
} else {
downloadableUncompleted.add(ex);
}
} else if (projectMediator.isProjectOpen(proj)) {
open.add(ex);
} else {
closed.add(ex); // TODO: all projects may end up here if this is queried too early
}
String downloadedChecksum = courseDb.getDownloadedExerciseChecksum(ex.getKey());
if (isDownloaded && ObjectUtils.notEqual(downloadedChecksum, ex.getChecksum())) {
updateable.add(ex);
}
}
}
}
| private LocalExerciseStatus(CourseDb courseDb, ProjectMediator projectMediator, List<Exercise> allExercises) {
open = new ArrayList<Exercise>();
closed = new ArrayList<Exercise>();
downloadableUncompleted = new ArrayList<Exercise>();
downloadableCompleted = new ArrayList<Exercise>();
updateable = new ArrayList<Exercise>();
unlockable = new ArrayList<Exercise>();
for (Exercise ex : allExercises) {
if (!ex.hasDeadlinePassed()) {
TmcProjectInfo proj = projectMediator.tryGetProjectForExercise(ex);
boolean isDownloaded = proj != null;
if (courseDb.isUnlockable(ex)) {
unlockable.add(ex);
} else if (!isDownloaded && !ex.isLocked()) {
if (ex.isCompleted()) {
downloadableCompleted.add(ex);
} else {
downloadableUncompleted.add(ex);
}
} else if (isDownloaded && projectMediator.isProjectOpen(proj)) {
open.add(ex);
} else {
closed.add(ex); // TODO: all projects may end up here if this is queried too early
}
String downloadedChecksum = courseDb.getDownloadedExerciseChecksum(ex.getKey());
if (isDownloaded && ObjectUtils.notEqual(downloadedChecksum, ex.getChecksum())) {
updateable.add(ex);
}
}
}
}
|
diff --git a/axis2/src/main/java/org/apache/ode/axis2/service/DeploymentWebService.java b/axis2/src/main/java/org/apache/ode/axis2/service/DeploymentWebService.java
index 97f2c87fc..d16981c03 100644
--- a/axis2/src/main/java/org/apache/ode/axis2/service/DeploymentWebService.java
+++ b/axis2/src/main/java/org/apache/ode/axis2/service/DeploymentWebService.java
@@ -1,288 +1,288 @@
/*
* 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.ode.axis2.service;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collection;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import javax.activation.DataHandler;
import javax.wsdl.Definition;
import javax.wsdl.WSDLException;
import javax.wsdl.factory.WSDLFactory;
import javax.wsdl.xml.WSDLReader;
import javax.xml.namespace.QName;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMNamespace;
import org.apache.axiom.om.OMText;
import org.apache.axiom.soap.SOAPEnvelope;
import org.apache.axiom.soap.SOAPFactory;
import org.apache.axis2.AxisFault;
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.description.AxisService;
import org.apache.axis2.engine.AxisConfiguration;
import org.apache.axis2.engine.AxisEngine;
import org.apache.axis2.receivers.AbstractMessageReceiver;
import org.apache.axis2.util.Utils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ode.axis2.OdeFault;
import org.apache.ode.axis2.deploy.DeploymentPoller;
import org.apache.ode.axis2.hooks.ODEAxisService;
import org.apache.ode.bpel.iapi.BpelServer;
import org.apache.ode.bpel.iapi.ProcessConf;
import org.apache.ode.bpel.iapi.ProcessStore;
import org.apache.ode.il.OMUtils;
import org.apache.ode.utils.fs.FileUtils;
/**
* Axis wrapper for process deployment.
*/
public class DeploymentWebService {
private static final Log __log = LogFactory.getLog(DeploymentWebService.class);
private final OMNamespace _pmapi;
private final OMNamespace _deployapi;
private File _deployPath;
private DeploymentPoller _poller;
private ProcessStore _store;
public DeploymentWebService() {
_pmapi = OMAbstractFactory.getOMFactory().createOMNamespace("http://www.apache.org/ode/pmapi","pmapi");
_deployapi = OMAbstractFactory.getOMFactory().createOMNamespace("http://www.apache.org/ode/deployapi","deployapi");
}
public void enableService(AxisConfiguration axisConfig, ProcessStore store,
DeploymentPoller poller, String rootpath, String workPath) throws AxisFault, WSDLException {
_deployPath = new File(workPath, "processes");
_store = store;
_poller = poller;
Definition def;
WSDLReader wsdlReader = WSDLFactory.newInstance().newWSDLReader();
wsdlReader.setFeature("javax.wsdl.verbose", false);
File wsdlFile = new File(rootpath + "/deploy.wsdl");
def = wsdlReader.readWSDL(wsdlFile.toURI().toString());
AxisService deployService = ODEAxisService.createService(
axisConfig, new QName("http://www.apache.org/ode/deployapi", "DeploymentService"),
"DeploymentPort", "DeploymentService", def, new DeploymentMessageReceiver());
axisConfig.addService(deployService);
}
class DeploymentMessageReceiver extends AbstractMessageReceiver {
public void invokeBusinessLogic(MessageContext messageContext) throws AxisFault {
String operation = messageContext.getAxisOperation().getName().getLocalPart();
SOAPFactory factory = getSOAPFactory(messageContext);
boolean unknown = false;
try {
if (operation.equals("deploy")) {
OMElement namePart = messageContext.getEnvelope().getBody().getFirstElement().getFirstElement();
- OMElement zipPart = (OMElement) namePart.getNextOMSibling();
+ OMElement zipPart = namePart.getFirstElement();
OMElement zip = (zipPart == null) ? null : zipPart.getFirstElement();
if (zip == null || !zipPart.getQName().getLocalPart().equals("package")
|| !zip.getQName().getLocalPart().equals("zip"))
throw new OdeFault("Your message should contain an element named 'package' with a 'zip' element");
OMText binaryNode = (OMText) zip.getFirstOMChild();
if (binaryNode == null) {
throw new OdeFault("Empty binary node under <zip> element");
}
binaryNode.setOptimize(true);
try {
// We're going to create a directory under the deployment root and put
// files in there. The poller shouldn't pick them up so we're asking
// it to hold on for a while.
_poller.hold();
File dest = new File(_deployPath, namePart.getText() + "-" + _store.getCurrentVersion());
dest.mkdir();
unzip(dest, (DataHandler) binaryNode.getDataHandler());
// Check that we have a deploy.xml
File deployXml = new File(dest, "deploy.xml");
if (!deployXml.exists())
throw new OdeFault("The deployment doesn't appear to contain a deployment " +
"descriptor in its root directory named deploy.xml, aborting.");
Collection<QName> deployed = _store.deploy(dest);
File deployedMarker = new File(_deployPath, dest.getName() + ".deployed");
deployedMarker.createNewFile();
// Telling the poller what we deployed so that it doesn't try to deploy it again
_poller.markAsDeployed(dest);
__log.info("Deployment of artifact " + dest.getName() + " successful.");
OMElement response = factory.createOMElement("response", null);
if (__log.isDebugEnabled()) __log.debug("Deployed package: "+dest.getName());
OMElement d = factory.createOMElement("name", _deployapi);
d.setText(dest.getName());
response.addChild(d);
for (QName pid : deployed) {
if (__log.isDebugEnabled()) __log.debug("Deployed PID: "+pid);
d = factory.createOMElement("id", _deployapi);
d.setText(pid);
response.addChild(d);
}
sendResponse(factory, messageContext, "deployResponse", response);
} finally {
_poller.release();
}
} else if (operation.equals("undeploy")) {
OMElement part = messageContext.getEnvelope().getBody().getFirstElement().getFirstElement();
String pkg = part.getText();
File deploymentDir = new File(_deployPath, pkg);
if (!deploymentDir.exists())
throw new OdeFault("Couldn't find deployment package " + pkg + " in directory " + _deployPath);
try {
// We're going to delete files & directories under the deployment root.
// Put the poller on hold to avoid undesired side effects
_poller.hold();
Collection<QName> undeployed = _store.undeploy(deploymentDir);
File deployedMarker = new File(_deployPath, pkg + ".deployed");
deployedMarker.delete();
FileUtils.deepDelete(new File(_deployPath, pkg));
OMElement response = factory.createOMElement("response", null);
response.setText("" + (undeployed.size() > 0));
sendResponse(factory, messageContext, "undeployResponse", response);
_poller.markAsUndeployed(deploymentDir);
} finally {
_poller.release();
}
} else if (operation.equals("listDeployedPackages")) {
Collection<String> packageNames = _store.getPackages();
OMElement response = factory.createOMElement("deployedPackages", null);
for (String name : packageNames) {
OMElement nameElmt = factory.createOMElement("name", _deployapi);
nameElmt.setText(name);
response.addChild(nameElmt);
}
sendResponse(factory, messageContext, "listDeployedPackagesResponse", response);
} else if (operation.equals("listProcesses")) {
OMElement namePart = messageContext.getEnvelope().getBody().getFirstElement().getFirstElement();
List<QName> processIds = _store.listProcesses(namePart.getText());
OMElement response = factory.createOMElement("processIds", null);
for (QName qname : processIds) {
OMElement nameElmt = factory.createOMElement("id", _deployapi);
nameElmt.setText(qname);
response.addChild(nameElmt);
}
sendResponse(factory, messageContext, "listProcessesResponse", response);
} else if (operation.equals("getProcessPackage")) {
OMElement qnamePart = messageContext.getEnvelope().getBody().getFirstElement().getFirstElement();
ProcessConf process = _store.getProcessConfiguration(OMUtils.getTextAsQName(qnamePart));
if (process == null) {
throw new OdeFault("Could not find process: " + qnamePart.getTextAsQName());
}
String packageName = _store.getProcessConfiguration(OMUtils.getTextAsQName(qnamePart)).getPackage();
OMElement response = factory.createOMElement("packageName", null);
response.setText(packageName);
sendResponse(factory, messageContext, "getProcessPackageResponse", response);
} else unknown = true;
} catch (Throwable t) {
// Trying to extract a meaningful message
Throwable source = t;
while (source.getCause() != null && source.getCause() != source) source = source.getCause();
__log.warn("Invocation of operation " + operation + " failed", t);
throw new OdeFault("Invocation of operation " + operation + " failed: " + source.toString(), t);
}
if (unknown) throw new OdeFault("Unknown operation: '"
+ messageContext.getAxisOperation().getName() + "'");
}
private File buildUnusedDir(File deployPath, String dirName) {
int v = 1;
while (new File(deployPath, dirName + "-" + v).exists()) v++;
return new File(deployPath, dirName + "-" + v);
}
private void unzip(File dest, DataHandler dataHandler) throws AxisFault {
try {
ZipInputStream zis = new ZipInputStream(dataHandler.getDataSource().getInputStream());
ZipEntry entry;
// Processing the package
while((entry = zis.getNextEntry()) != null) {
if(entry.isDirectory()) {
__log.debug("Extracting directory: " + entry.getName());
new File(dest, entry.getName()).mkdir();
continue;
}
__log.debug("Extracting file: " + entry.getName());
File destFile = new File(dest, entry.getName());
if (!destFile.getParentFile().exists()) destFile.getParentFile().mkdirs();
copyInputStream(zis, new BufferedOutputStream(
new FileOutputStream(destFile)));
}
zis.close();
} catch (IOException e) {
throw new OdeFault("An error occured on deployment.", e);
}
}
private void sendResponse(SOAPFactory factory, MessageContext messageContext, String op,
OMElement response) throws AxisFault {
MessageContext outMsgContext = Utils.createOutMessageContext(messageContext);
outMsgContext.getOperationContext().addMessageContext(outMsgContext);
SOAPEnvelope envelope = factory.getDefaultEnvelope();
outMsgContext.setEnvelope(envelope);
OMElement responseOp = factory.createOMElement(op, _pmapi);
responseOp.addChild(response);
envelope.getBody().addChild(responseOp);
AxisEngine.send(outMsgContext);
}
}
private static void copyInputStream(InputStream in, OutputStream out)
throws IOException {
byte[] buffer = new byte[1024];
int len;
while((len = in.read(buffer)) >= 0)
out.write(buffer, 0, len);
out.close();
}
}
| true | true | public void invokeBusinessLogic(MessageContext messageContext) throws AxisFault {
String operation = messageContext.getAxisOperation().getName().getLocalPart();
SOAPFactory factory = getSOAPFactory(messageContext);
boolean unknown = false;
try {
if (operation.equals("deploy")) {
OMElement namePart = messageContext.getEnvelope().getBody().getFirstElement().getFirstElement();
OMElement zipPart = (OMElement) namePart.getNextOMSibling();
OMElement zip = (zipPart == null) ? null : zipPart.getFirstElement();
if (zip == null || !zipPart.getQName().getLocalPart().equals("package")
|| !zip.getQName().getLocalPart().equals("zip"))
throw new OdeFault("Your message should contain an element named 'package' with a 'zip' element");
OMText binaryNode = (OMText) zip.getFirstOMChild();
if (binaryNode == null) {
throw new OdeFault("Empty binary node under <zip> element");
}
binaryNode.setOptimize(true);
try {
// We're going to create a directory under the deployment root and put
// files in there. The poller shouldn't pick them up so we're asking
// it to hold on for a while.
_poller.hold();
File dest = new File(_deployPath, namePart.getText() + "-" + _store.getCurrentVersion());
dest.mkdir();
unzip(dest, (DataHandler) binaryNode.getDataHandler());
// Check that we have a deploy.xml
File deployXml = new File(dest, "deploy.xml");
if (!deployXml.exists())
throw new OdeFault("The deployment doesn't appear to contain a deployment " +
"descriptor in its root directory named deploy.xml, aborting.");
Collection<QName> deployed = _store.deploy(dest);
File deployedMarker = new File(_deployPath, dest.getName() + ".deployed");
deployedMarker.createNewFile();
// Telling the poller what we deployed so that it doesn't try to deploy it again
_poller.markAsDeployed(dest);
__log.info("Deployment of artifact " + dest.getName() + " successful.");
OMElement response = factory.createOMElement("response", null);
if (__log.isDebugEnabled()) __log.debug("Deployed package: "+dest.getName());
OMElement d = factory.createOMElement("name", _deployapi);
d.setText(dest.getName());
response.addChild(d);
for (QName pid : deployed) {
if (__log.isDebugEnabled()) __log.debug("Deployed PID: "+pid);
d = factory.createOMElement("id", _deployapi);
d.setText(pid);
response.addChild(d);
}
sendResponse(factory, messageContext, "deployResponse", response);
} finally {
_poller.release();
}
} else if (operation.equals("undeploy")) {
OMElement part = messageContext.getEnvelope().getBody().getFirstElement().getFirstElement();
String pkg = part.getText();
File deploymentDir = new File(_deployPath, pkg);
if (!deploymentDir.exists())
throw new OdeFault("Couldn't find deployment package " + pkg + " in directory " + _deployPath);
try {
// We're going to delete files & directories under the deployment root.
// Put the poller on hold to avoid undesired side effects
_poller.hold();
Collection<QName> undeployed = _store.undeploy(deploymentDir);
File deployedMarker = new File(_deployPath, pkg + ".deployed");
deployedMarker.delete();
FileUtils.deepDelete(new File(_deployPath, pkg));
OMElement response = factory.createOMElement("response", null);
response.setText("" + (undeployed.size() > 0));
sendResponse(factory, messageContext, "undeployResponse", response);
_poller.markAsUndeployed(deploymentDir);
} finally {
_poller.release();
}
} else if (operation.equals("listDeployedPackages")) {
Collection<String> packageNames = _store.getPackages();
OMElement response = factory.createOMElement("deployedPackages", null);
for (String name : packageNames) {
OMElement nameElmt = factory.createOMElement("name", _deployapi);
nameElmt.setText(name);
response.addChild(nameElmt);
}
sendResponse(factory, messageContext, "listDeployedPackagesResponse", response);
} else if (operation.equals("listProcesses")) {
OMElement namePart = messageContext.getEnvelope().getBody().getFirstElement().getFirstElement();
List<QName> processIds = _store.listProcesses(namePart.getText());
OMElement response = factory.createOMElement("processIds", null);
for (QName qname : processIds) {
OMElement nameElmt = factory.createOMElement("id", _deployapi);
nameElmt.setText(qname);
response.addChild(nameElmt);
}
sendResponse(factory, messageContext, "listProcessesResponse", response);
} else if (operation.equals("getProcessPackage")) {
OMElement qnamePart = messageContext.getEnvelope().getBody().getFirstElement().getFirstElement();
ProcessConf process = _store.getProcessConfiguration(OMUtils.getTextAsQName(qnamePart));
if (process == null) {
throw new OdeFault("Could not find process: " + qnamePart.getTextAsQName());
}
String packageName = _store.getProcessConfiguration(OMUtils.getTextAsQName(qnamePart)).getPackage();
OMElement response = factory.createOMElement("packageName", null);
response.setText(packageName);
sendResponse(factory, messageContext, "getProcessPackageResponse", response);
} else unknown = true;
} catch (Throwable t) {
// Trying to extract a meaningful message
Throwable source = t;
while (source.getCause() != null && source.getCause() != source) source = source.getCause();
__log.warn("Invocation of operation " + operation + " failed", t);
throw new OdeFault("Invocation of operation " + operation + " failed: " + source.toString(), t);
}
if (unknown) throw new OdeFault("Unknown operation: '"
+ messageContext.getAxisOperation().getName() + "'");
}
| public void invokeBusinessLogic(MessageContext messageContext) throws AxisFault {
String operation = messageContext.getAxisOperation().getName().getLocalPart();
SOAPFactory factory = getSOAPFactory(messageContext);
boolean unknown = false;
try {
if (operation.equals("deploy")) {
OMElement namePart = messageContext.getEnvelope().getBody().getFirstElement().getFirstElement();
OMElement zipPart = namePart.getFirstElement();
OMElement zip = (zipPart == null) ? null : zipPart.getFirstElement();
if (zip == null || !zipPart.getQName().getLocalPart().equals("package")
|| !zip.getQName().getLocalPart().equals("zip"))
throw new OdeFault("Your message should contain an element named 'package' with a 'zip' element");
OMText binaryNode = (OMText) zip.getFirstOMChild();
if (binaryNode == null) {
throw new OdeFault("Empty binary node under <zip> element");
}
binaryNode.setOptimize(true);
try {
// We're going to create a directory under the deployment root and put
// files in there. The poller shouldn't pick them up so we're asking
// it to hold on for a while.
_poller.hold();
File dest = new File(_deployPath, namePart.getText() + "-" + _store.getCurrentVersion());
dest.mkdir();
unzip(dest, (DataHandler) binaryNode.getDataHandler());
// Check that we have a deploy.xml
File deployXml = new File(dest, "deploy.xml");
if (!deployXml.exists())
throw new OdeFault("The deployment doesn't appear to contain a deployment " +
"descriptor in its root directory named deploy.xml, aborting.");
Collection<QName> deployed = _store.deploy(dest);
File deployedMarker = new File(_deployPath, dest.getName() + ".deployed");
deployedMarker.createNewFile();
// Telling the poller what we deployed so that it doesn't try to deploy it again
_poller.markAsDeployed(dest);
__log.info("Deployment of artifact " + dest.getName() + " successful.");
OMElement response = factory.createOMElement("response", null);
if (__log.isDebugEnabled()) __log.debug("Deployed package: "+dest.getName());
OMElement d = factory.createOMElement("name", _deployapi);
d.setText(dest.getName());
response.addChild(d);
for (QName pid : deployed) {
if (__log.isDebugEnabled()) __log.debug("Deployed PID: "+pid);
d = factory.createOMElement("id", _deployapi);
d.setText(pid);
response.addChild(d);
}
sendResponse(factory, messageContext, "deployResponse", response);
} finally {
_poller.release();
}
} else if (operation.equals("undeploy")) {
OMElement part = messageContext.getEnvelope().getBody().getFirstElement().getFirstElement();
String pkg = part.getText();
File deploymentDir = new File(_deployPath, pkg);
if (!deploymentDir.exists())
throw new OdeFault("Couldn't find deployment package " + pkg + " in directory " + _deployPath);
try {
// We're going to delete files & directories under the deployment root.
// Put the poller on hold to avoid undesired side effects
_poller.hold();
Collection<QName> undeployed = _store.undeploy(deploymentDir);
File deployedMarker = new File(_deployPath, pkg + ".deployed");
deployedMarker.delete();
FileUtils.deepDelete(new File(_deployPath, pkg));
OMElement response = factory.createOMElement("response", null);
response.setText("" + (undeployed.size() > 0));
sendResponse(factory, messageContext, "undeployResponse", response);
_poller.markAsUndeployed(deploymentDir);
} finally {
_poller.release();
}
} else if (operation.equals("listDeployedPackages")) {
Collection<String> packageNames = _store.getPackages();
OMElement response = factory.createOMElement("deployedPackages", null);
for (String name : packageNames) {
OMElement nameElmt = factory.createOMElement("name", _deployapi);
nameElmt.setText(name);
response.addChild(nameElmt);
}
sendResponse(factory, messageContext, "listDeployedPackagesResponse", response);
} else if (operation.equals("listProcesses")) {
OMElement namePart = messageContext.getEnvelope().getBody().getFirstElement().getFirstElement();
List<QName> processIds = _store.listProcesses(namePart.getText());
OMElement response = factory.createOMElement("processIds", null);
for (QName qname : processIds) {
OMElement nameElmt = factory.createOMElement("id", _deployapi);
nameElmt.setText(qname);
response.addChild(nameElmt);
}
sendResponse(factory, messageContext, "listProcessesResponse", response);
} else if (operation.equals("getProcessPackage")) {
OMElement qnamePart = messageContext.getEnvelope().getBody().getFirstElement().getFirstElement();
ProcessConf process = _store.getProcessConfiguration(OMUtils.getTextAsQName(qnamePart));
if (process == null) {
throw new OdeFault("Could not find process: " + qnamePart.getTextAsQName());
}
String packageName = _store.getProcessConfiguration(OMUtils.getTextAsQName(qnamePart)).getPackage();
OMElement response = factory.createOMElement("packageName", null);
response.setText(packageName);
sendResponse(factory, messageContext, "getProcessPackageResponse", response);
} else unknown = true;
} catch (Throwable t) {
// Trying to extract a meaningful message
Throwable source = t;
while (source.getCause() != null && source.getCause() != source) source = source.getCause();
__log.warn("Invocation of operation " + operation + " failed", t);
throw new OdeFault("Invocation of operation " + operation + " failed: " + source.toString(), t);
}
if (unknown) throw new OdeFault("Unknown operation: '"
+ messageContext.getAxisOperation().getName() + "'");
}
|
diff --git a/src/sts/src/com/vangent/hieos/services/sts/serviceimpl/STS.java b/src/sts/src/com/vangent/hieos/services/sts/serviceimpl/STS.java
index d7b9a5b6..cbb499fa 100644
--- a/src/sts/src/com/vangent/hieos/services/sts/serviceimpl/STS.java
+++ b/src/sts/src/com/vangent/hieos/services/sts/serviceimpl/STS.java
@@ -1,122 +1,123 @@
/*
* This code is subject to the HIEOS License, Version 1.0
*
* Copyright(c) 2011 Vangent, Inc. All rights reserved.
*
* 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.vangent.hieos.services.sts.serviceimpl;
import com.vangent.hieos.services.sts.exception.STSException;
import com.vangent.hieos.services.sts.model.STSConstants;
import com.vangent.hieos.services.sts.transactions.STSRequestHandler;
import com.vangent.hieos.services.sts.util.STSUtil;
import com.vangent.hieos.xutil.services.framework.XAbstractService;
import org.apache.log4j.Logger;
// Axis2 LifeCycle support.
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.description.AxisService;
// XATNA
import com.vangent.hieos.xutil.atna.XATNALogger;
import com.vangent.hieos.xutil.exception.SOAPFaultException;
import com.vangent.hieos.xutil.xconfig.XConfig;
import com.vangent.hieos.xutil.xconfig.XConfigActor;
import com.vangent.hieos.xutil.xconfig.XConfigObject;
import org.apache.axiom.om.OMElement;
import org.apache.axis2.AxisFault;
import org.apache.axis2.context.MessageContext;
/**
* STS WS-Trust web service implementation.
*
* @author Bernie Thuman
*/
public class STS extends XAbstractService {
private final static Logger logger = Logger.getLogger(STS.class);
private static XConfigActor config = null; // Singleton.
@Override
protected XConfigActor getConfigActor() {
return config;
}
/**
*
* @param request
* @return
* @throws AxisFault
*/
public OMElement RequestSecurityToken(OMElement request) throws AxisFault {
+ OMElement response = null;
try {
beginTransaction(this.getRequestType(request), request);
validateWS();
validateNoMTOM();
STSRequestHandler handler = new STSRequestHandler(this.log_message, MessageContext.getCurrentMessageContext());
handler.setConfigActor(config);
- OMElement response = handler.run(request);
+ response = handler.run(request);
endTransaction(handler.getStatus());
- return response;
} catch (SOAPFaultException ex) {
- throw new AxisFault(ex.getMessage()); // Rethrow.
+ throwAxisFault(ex);
}
+ return response;
}
/**
*
* @param request
* @return
*/
private String getRequestType(OMElement request) {
try {
String requestType = STSUtil.getRequestType(request);
if (requestType.equalsIgnoreCase(STSConstants.ISSUE_REQUEST_TYPE)) {
return "STS:RST:Issue";
} else if (requestType.equalsIgnoreCase(STSConstants.VALIDATE_REQUEST_TYPE)) {
return "STS:RST:Validate";
} else {
return "STS:RST:Unknown";
}
} catch (STSException ex) {
return "STS:RST:Unknown";
}
}
/**
* This will be called during the deployment time of the service.
* Irrespective of the service scope this method will be called
* @param configctx
* @param service
*/
@Override
public void startUp(ConfigurationContext configctx, AxisService service) {
logger.info("STS::startUp()");
try {
XConfig xconf;
xconf = XConfig.getInstance();
XConfigObject homeCommunity = xconf.getHomeCommunityConfig();
config = (XConfigActor) homeCommunity.getXConfigObjectWithName("sts", XConfig.STS_TYPE);
} catch (Exception ex) {
logger.fatal("Unable to get configuration for service", ex);
}
}
/**
* This will be called during the system shut down time. Irrespective
* of the service scope this method will be called
* @param configctx
* @param service
*/
@Override
public void shutDown(ConfigurationContext configctx, AxisService service) {
logger.info("STS::shutDown()");
}
}
| false | true | public OMElement RequestSecurityToken(OMElement request) throws AxisFault {
try {
beginTransaction(this.getRequestType(request), request);
validateWS();
validateNoMTOM();
STSRequestHandler handler = new STSRequestHandler(this.log_message, MessageContext.getCurrentMessageContext());
handler.setConfigActor(config);
OMElement response = handler.run(request);
endTransaction(handler.getStatus());
return response;
} catch (SOAPFaultException ex) {
throw new AxisFault(ex.getMessage()); // Rethrow.
}
}
| public OMElement RequestSecurityToken(OMElement request) throws AxisFault {
OMElement response = null;
try {
beginTransaction(this.getRequestType(request), request);
validateWS();
validateNoMTOM();
STSRequestHandler handler = new STSRequestHandler(this.log_message, MessageContext.getCurrentMessageContext());
handler.setConfigActor(config);
response = handler.run(request);
endTransaction(handler.getStatus());
} catch (SOAPFaultException ex) {
throwAxisFault(ex);
}
return response;
}
|
diff --git a/editor/tools/plugins/com.google.dart.tools.search/src/com/google/dart/tools/search/internal/ui/text/TextSearchScopeFilter.java b/editor/tools/plugins/com.google.dart.tools.search/src/com/google/dart/tools/search/internal/ui/text/TextSearchScopeFilter.java
index c2463d0bc..36fcf8534 100644
--- a/editor/tools/plugins/com.google.dart.tools.search/src/com/google/dart/tools/search/internal/ui/text/TextSearchScopeFilter.java
+++ b/editor/tools/plugins/com.google.dart.tools.search/src/com/google/dart/tools/search/internal/ui/text/TextSearchScopeFilter.java
@@ -1,68 +1,72 @@
/*
* Copyright (c) 2012, the Dart project authors.
*
* Licensed under the Eclipse Public License v1.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.eclipse.org/legal/epl-v10.html
*
* 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.dart.tools.search.internal.ui.text;
import org.eclipse.core.resources.IResourceProxy;
import java.io.File;
/**
* Identifies file types that should be filtered from dart search scopes.
*/
public class TextSearchScopeFilter {
private static final String LIB_CONFIG_PATH = "dart-sdk" + File.separator + "lib"
+ File.separator + "config";
/**
* Checks if the given file should be filtered out of a search scope.
*
* @param file the file name to check
* @return <code>true</code> if the file should be excluded, <code>false</code> otherwise
*/
public static boolean isFiltered(File file) {
//dart-sdk/lib/config
if (file.getAbsolutePath().endsWith(LIB_CONFIG_PATH)) {
return true;
}
return isFiltered(file.getName());
}
/**
* Checks if the given file should be filtered out of a search scope.
*
* @param file the file to check
* @return <code>true</code> if the file should be excluded, <code>false</code> otherwise
*/
public static boolean isFiltered(IResourceProxy file) {
return isFiltered(file.getName());
}
/**
* Checks if the given file name should be filtered out of a search scope.
*
* @param fileName the file name to check
* @return <code>true</code> if the file should be excluded, <code>false</code> otherwise
*/
private static boolean isFiltered(String fileName) {
//ignore .files (and avoid traversing into folders prefixed with a '.')
if (fileName.startsWith(".")) {
return true;
}
if (fileName.endsWith(".dart.js")) {
return true;
}
+ //dart2js-gened file (temporary)
+ if (fileName.endsWith(".dart.js_")) {
+ return true;
+ }
return false;
}
}
| true | true | private static boolean isFiltered(String fileName) {
//ignore .files (and avoid traversing into folders prefixed with a '.')
if (fileName.startsWith(".")) {
return true;
}
if (fileName.endsWith(".dart.js")) {
return true;
}
return false;
}
| private static boolean isFiltered(String fileName) {
//ignore .files (and avoid traversing into folders prefixed with a '.')
if (fileName.startsWith(".")) {
return true;
}
if (fileName.endsWith(".dart.js")) {
return true;
}
//dart2js-gened file (temporary)
if (fileName.endsWith(".dart.js_")) {
return true;
}
return false;
}
|
diff --git a/src/com/koushikdutta/klaxon/AlarmEditActivity.java b/src/com/koushikdutta/klaxon/AlarmEditActivity.java
index 265059d..5b26a64 100755
--- a/src/com/koushikdutta/klaxon/AlarmEditActivity.java
+++ b/src/com/koushikdutta/klaxon/AlarmEditActivity.java
@@ -1,486 +1,486 @@
package com.koushikdutta.klaxon;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceScreen;
import android.provider.MediaStore;
import android.provider.Settings;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TimePicker;
import android.widget.Toast;
import com.koushikdutta.klaxon.RepeatPreference.OnRepeatChangeListener;
import com.koushikdutta.klaxon.SnoozePreference.OnSnoozeChangeListener;
import com.koushikdutta.klaxon.VolumePreference.OnVolumeChangeListener;
import com.koushikdutta.klaxon.VolumeRampPreference.OnVolumeRampChangeListener;
public class AlarmEditActivity extends PreferenceActivity
{
MenuItem mDeleteAlarm;
MenuItem mTestAlarm;
AlarmSettings mSettings;
Preference mTimePref;
Preference mRingtonePref;
Preference mNamePref;
RepeatPreference mRepeatPref;
SnoozePreference mSnoozePref;
CheckBoxPreference mEnabledPref;
VolumePreference mVolumePref;
VolumeRampPreference mVolumeRampPref;
CheckBoxPreference mVibrateEnabledPref;
boolean mIs24HourMode = false;
SQLiteDatabase mDatabase;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.alarm_prefs);
Intent i = getIntent();
mDatabase = AlarmSettings.getDatabase(this);
mSettings = AlarmSettings.getAlarmSettingsById(this, mDatabase, i.getLongExtra(AlarmSettings.GEN_FIELD__ID, -1));
setResult(Activity.RESULT_OK, i);
mNamePref = findPreference("alarmname");
mTimePref = findPreference("time");
mRingtonePref = findPreference("alarm");
mRepeatPref = (RepeatPreference) findPreference("repeat");
mRepeatPref.setAlarmSettings(mSettings);
mSnoozePref = (SnoozePreference) findPreference("snooze");
mSnoozePref.setAlarmSettings(mSettings);
mEnabledPref = (CheckBoxPreference) findPreference("enabled");
mEnabledPref.setChecked(mSettings.getEnabled());
mVolumePref = (VolumePreference) findPreference("volume");
mVolumePref.setAlarmSettings(mSettings);
mVolumeRampPref = (VolumeRampPreference) findPreference("volumeramp");
mVolumeRampPref.setAlarmSettings(mSettings);
mVibrateEnabledPref = (CheckBoxPreference) findPreference("VibrateEnabled");
mVibrateEnabledPref.setChecked(mSettings.getVibrateEnabled());
refreshNameSummary();
refreshTimeSummary();
refreshRingtoneSummary();
refreshRepeatSummary();
refreshSnoozeSummary();
refreshVolumeSummary();
refreshVolumeRampSummary();
mRepeatPref.setOnRepeatChangeListener(new OnRepeatChangeListener()
{
public void onRepeatChanged()
{
scheduleNextAlarm();
refreshRepeatSummary();
}
});
mSnoozePref.setOnSnoozeChangeListener(new OnSnoozeChangeListener()
{
public void onSnoozeChanged()
{
scheduleNextAlarm();
refreshSnoozeSummary();
}
});
mVolumePref.setOnVolumeChangeListener(new OnVolumeChangeListener()
{
public void onVolumeChanged()
{
mSettings.update();
refreshVolumeSummary();
}
});
mVolumeRampPref.setOnVolumeRampChangeListener(new OnVolumeRampChangeListener()
{
public void onVolumeRampChanged()
{
mSettings.update();
refreshVolumeRampSummary();
}
});
String value = Settings.System.getString(getContentResolver(), Settings.System.TIME_12_24);
mIs24HourMode = !(value == null || value.equals("12"));
Toast tipToast = Toast.makeText(this, "Tip: You can create a one shot alarm by not selecting any Repeat days.", Toast.LENGTH_LONG);
tipToast.show();
}
void refreshRepeatSummary()
{
boolean[] days = mSettings.getAlarmDays();
boolean oneShot = AlarmSettings.isOneShot(days);
String summary = "";
if (oneShot)
{
summary = "One-Shot Alarm";
}
else
{
final String[] dayNames = { "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun" };
for (int i = 0; i < days.length; i++)
{
if (days[i])
summary += dayNames[i] + " ";
}
}
mRepeatPref.setSummary(summary);
}
void refreshVolumeSummary()
{
String volumeText = String.format("%d Percent", mSettings.getVolume());
mVolumePref.setSummary(volumeText);
}
void refreshVolumeRampSummary()
{
int volumeRamp = mSettings.getVolumeRamp();
if (volumeRamp != 0)
{
String volumeRampText = String.format("%d Seconds", volumeRamp);
mVolumeRampPref.setSummary(volumeRampText);
}
else
{
mVolumeRampPref.setSummary("Immediately");
}
}
void refreshSnoozeSummary()
{
String snoozeText = String.format("%d Minutes", mSettings.getSnoozeTime());
mSnoozePref.setSummary(snoozeText);
}
void refreshTimeSummary()
{
SimpleDateFormat df;
if (mIs24HourMode)
df = new SimpleDateFormat("H:mm");
else
df = new SimpleDateFormat("h:mm a");
String time = df.format(new Date(2008, 1, 1, mSettings.getHour(), mSettings.getMinutes()));
mTimePref.setSummary(time);
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
mDeleteAlarm = menu.add(0, 0, 0, "Delete Alarm");
mDeleteAlarm.setIcon(android.R.drawable.ic_menu_delete);
mTestAlarm = menu.add(0, 0, 0, "Test Alarm");
mTestAlarm.setIcon(R.drawable.ic_menu_clock_face);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item)
{
if (item == mDeleteAlarm)
{
mSettings.delete();
Intent ret = getIntent();
ret.putExtra("Deleted", true);
finish();
}
else if (item == mTestAlarm)
{
Intent i = new Intent(this, AlarmActivity.class);
i.putExtra(AlarmSettings.GEN_FIELD__ID, mSettings.get_Id());
startActivity(i);
}
return super.onMenuItemSelected(featureId, item);
}
void scheduleNextAlarm()
{
mSettings.update();
AlarmSettings.scheduleNextAlarm(AlarmEditActivity.this);
Long next = mSettings.getNextAlarmTime();
String toastText;
if (next == null)
{
toastText = "This Alarm is disabled.";
}
else
{
GregorianCalendar now = new GregorianCalendar();
long nowMs = now.getTimeInMillis();
long delta = next - nowMs;
long hours = delta / (1000 * 60 * 60) % 24;
long minutes = delta / (1000 * 60) % 60;
long days = delta / (1000 * 60 * 60 * 24);
if (mSettings.isOneShot())
toastText = String.format("This one shot alarm will fire in %d days, %d hours, and %d minutes.", days, hours, minutes);
else
toastText = String.format("This alarm will fire in %d days, %d hours, and %d minutes.", days, hours, minutes);
}
Toast toast = Toast.makeText(this, toastText, Toast.LENGTH_LONG);
toast.show();
}
@Override
protected Dialog onCreateDialog(int id)
{
Dialog d;
switch (id)
{
case DIALOG_TIMEPICKER:
d = new TimePickerDialog(AlarmEditActivity.this, new OnTimeSetListener()
{
public void onTimeSet(TimePicker view, int hourOfDay, int minute)
{
mSettings.setHour(hourOfDay);
mSettings.setMinutes(minute);
mSettings.setEnabled(true);
- mEnabledPref.setEnabled(true);
+ mEnabledPref.setChecked(true);
refreshTimeSummary();
scheduleNextAlarm();
}
}, 0, 0, false);
d.setTitle("Time");
break;
case DIALOG_NAMEEDITOR:
final View layout = View.inflate(this, R.layout.alertname, null);
final EditText input = (EditText) layout.findViewById(R.id.AlarmName);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setIcon(0);
builder.setTitle("Edit Alarm Name");
builder.setCancelable(true);
builder.setPositiveButton("OK", new Dialog.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
mSettings.setName(input.getText().toString());
mSettings.update();
refreshNameSummary();
}
});
builder.setView(layout);
d = builder.create();
break;
case DIALOG_RINGTONEPICKER:
{
d = new Dialog(this)
{
Button mRingtoneButton;
Button mMusicButton;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.alerttype);
setTitle("Sound Type");
mRingtoneButton = (Button) findViewById(R.id.RingtoneButton);
mMusicButton = (Button) findViewById(R.id.SongButton);
mRingtoneButton.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View v)
{
dismiss();
Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, mSettings.getRingtone());
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, false);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_SILENT, false);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_ALL);
startActivityForResult(intent, REQUEST_RINGTONE);
}
});
mMusicButton.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View v)
{
dismiss();
try
{
Intent intent = new Intent();
intent.setAction(Intent.ACTION_PICK);
intent.setClassName("com.android.music", "com.android.music.MusicPicker");
intent.setData(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);
Uri ringtone = mSettings.getRingtone();
if (ringtone != null)
{
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, ringtone);
}
startActivityForResult(intent, REQUEST_MUSIC);
}
catch (Exception ex)
{
Intent intent = new Intent(AlarmEditActivity.this, TrackBrowserActivity.class);
Uri ringtone = mSettings.getRingtone();
if (ringtone != null)
{
String titleUri = ringtone.toString();
intent.putExtra("TitleUri", titleUri);
}
startActivityForResult(intent, REQUEST_MUSIC);
}
}
});
}
};
break;
}
default:
d = null;
}
return d;
}
@Override
protected void onPrepareDialog(int id, Dialog dialog)
{
super.onPrepareDialog(id, dialog);
switch (id)
{
case DIALOG_TIMEPICKER:
TimePickerDialog timePicker = (TimePickerDialog) dialog;
timePicker.updateTime(mSettings.getHour(), mSettings.getMinutes());
break;
case DIALOG_NAMEEDITOR:
final EditText input = (EditText) dialog.findViewById(R.id.AlarmName);
input.setText(mSettings.getName());
break;
}
}
final static int DIALOG_TIMEPICKER = 0;
final static int DIALOG_RINGTONEPICKER = 1;
final static int DIALOG_NAMEEDITOR = 2;
final static int REQUEST_RINGTONE = 0;
final static int REQUEST_MUSIC = 1;
@Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference)
{
if (preference == mTimePref)
{
showDialog(DIALOG_TIMEPICKER);
}
else if (preference == mRingtonePref)
{
showDialog(DIALOG_RINGTONEPICKER);
}
else if (preference == mEnabledPref)
{
mSettings.setEnabled(mEnabledPref.isChecked());
scheduleNextAlarm();
}
else if (preference == mVibrateEnabledPref)
{
mSettings.setVibrateEnabled(mVibrateEnabledPref.isChecked());
mSettings.update();
}
else if (preference == mNamePref)
{
showDialog(DIALOG_NAMEEDITOR);
}
return super.onPreferenceTreeClick(preferenceScreen, preference);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == REQUEST_RINGTONE)
{
if (resultCode != RESULT_CANCELED)
{
Uri uri = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
if (uri != null)
{
mSettings.setRingtone(uri);
mSettings.update();
Ringtone rt = RingtoneManager.getRingtone(this, uri);
mRingtonePref.setSummary(rt.getTitle(this));
}
}
}
else if (requestCode == REQUEST_MUSIC)
{
if (data != null)
{
Uri uri = data.getData();
if (uri != null)
{
mSettings.setRingtone(uri);
mSettings.update();
refreshRingtoneSummary();
}
}
}
super.onActivityResult(requestCode, resultCode, data);
}
void refreshNameSummary()
{
mNamePref.setSummary(mSettings.getName());
}
void refreshRingtoneSummary()
{
Uri ringtone = mSettings.getRingtone();
if (ringtone != null)
{
Cursor c = getContentResolver().query(ringtone, null, null, null, null);
if (c != null)
{
if (!c.isLast())
{
c.moveToNext();
int titleIndex = c.getColumnIndex(MediaStore.Audio.Media.TITLE);
try
{
mRingtonePref.setSummary(c.getString(titleIndex));
}
catch(Exception ex)
{
}
startManagingCursor(c);
}
}
}
}
@Override
protected void onDestroy() {
super.onDestroy();
mDatabase.close();
}
}
| true | true | protected Dialog onCreateDialog(int id)
{
Dialog d;
switch (id)
{
case DIALOG_TIMEPICKER:
d = new TimePickerDialog(AlarmEditActivity.this, new OnTimeSetListener()
{
public void onTimeSet(TimePicker view, int hourOfDay, int minute)
{
mSettings.setHour(hourOfDay);
mSettings.setMinutes(minute);
mSettings.setEnabled(true);
mEnabledPref.setEnabled(true);
refreshTimeSummary();
scheduleNextAlarm();
}
}, 0, 0, false);
d.setTitle("Time");
break;
case DIALOG_NAMEEDITOR:
final View layout = View.inflate(this, R.layout.alertname, null);
final EditText input = (EditText) layout.findViewById(R.id.AlarmName);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setIcon(0);
builder.setTitle("Edit Alarm Name");
builder.setCancelable(true);
builder.setPositiveButton("OK", new Dialog.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
mSettings.setName(input.getText().toString());
mSettings.update();
refreshNameSummary();
}
});
builder.setView(layout);
d = builder.create();
break;
case DIALOG_RINGTONEPICKER:
{
d = new Dialog(this)
{
Button mRingtoneButton;
Button mMusicButton;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.alerttype);
setTitle("Sound Type");
mRingtoneButton = (Button) findViewById(R.id.RingtoneButton);
mMusicButton = (Button) findViewById(R.id.SongButton);
mRingtoneButton.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View v)
{
dismiss();
Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, mSettings.getRingtone());
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, false);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_SILENT, false);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_ALL);
startActivityForResult(intent, REQUEST_RINGTONE);
}
});
mMusicButton.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View v)
{
dismiss();
try
{
Intent intent = new Intent();
intent.setAction(Intent.ACTION_PICK);
intent.setClassName("com.android.music", "com.android.music.MusicPicker");
intent.setData(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);
Uri ringtone = mSettings.getRingtone();
if (ringtone != null)
{
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, ringtone);
}
startActivityForResult(intent, REQUEST_MUSIC);
}
catch (Exception ex)
{
Intent intent = new Intent(AlarmEditActivity.this, TrackBrowserActivity.class);
Uri ringtone = mSettings.getRingtone();
if (ringtone != null)
{
String titleUri = ringtone.toString();
intent.putExtra("TitleUri", titleUri);
}
startActivityForResult(intent, REQUEST_MUSIC);
}
}
});
}
};
break;
}
default:
d = null;
}
return d;
}
| protected Dialog onCreateDialog(int id)
{
Dialog d;
switch (id)
{
case DIALOG_TIMEPICKER:
d = new TimePickerDialog(AlarmEditActivity.this, new OnTimeSetListener()
{
public void onTimeSet(TimePicker view, int hourOfDay, int minute)
{
mSettings.setHour(hourOfDay);
mSettings.setMinutes(minute);
mSettings.setEnabled(true);
mEnabledPref.setChecked(true);
refreshTimeSummary();
scheduleNextAlarm();
}
}, 0, 0, false);
d.setTitle("Time");
break;
case DIALOG_NAMEEDITOR:
final View layout = View.inflate(this, R.layout.alertname, null);
final EditText input = (EditText) layout.findViewById(R.id.AlarmName);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setIcon(0);
builder.setTitle("Edit Alarm Name");
builder.setCancelable(true);
builder.setPositiveButton("OK", new Dialog.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
mSettings.setName(input.getText().toString());
mSettings.update();
refreshNameSummary();
}
});
builder.setView(layout);
d = builder.create();
break;
case DIALOG_RINGTONEPICKER:
{
d = new Dialog(this)
{
Button mRingtoneButton;
Button mMusicButton;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.alerttype);
setTitle("Sound Type");
mRingtoneButton = (Button) findViewById(R.id.RingtoneButton);
mMusicButton = (Button) findViewById(R.id.SongButton);
mRingtoneButton.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View v)
{
dismiss();
Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, mSettings.getRingtone());
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, false);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_SILENT, false);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_ALL);
startActivityForResult(intent, REQUEST_RINGTONE);
}
});
mMusicButton.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View v)
{
dismiss();
try
{
Intent intent = new Intent();
intent.setAction(Intent.ACTION_PICK);
intent.setClassName("com.android.music", "com.android.music.MusicPicker");
intent.setData(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);
Uri ringtone = mSettings.getRingtone();
if (ringtone != null)
{
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, ringtone);
}
startActivityForResult(intent, REQUEST_MUSIC);
}
catch (Exception ex)
{
Intent intent = new Intent(AlarmEditActivity.this, TrackBrowserActivity.class);
Uri ringtone = mSettings.getRingtone();
if (ringtone != null)
{
String titleUri = ringtone.toString();
intent.putExtra("TitleUri", titleUri);
}
startActivityForResult(intent, REQUEST_MUSIC);
}
}
});
}
};
break;
}
default:
d = null;
}
return d;
}
|
diff --git a/cagrid-portal/portlets/test/src/java/gov/nih/nci/cagrid/portal/portlet/SummaryContentViewControllerTest.java b/cagrid-portal/portlets/test/src/java/gov/nih/nci/cagrid/portal/portlet/SummaryContentViewControllerTest.java
index 31f5d492a..40adccef4 100644
--- a/cagrid-portal/portlets/test/src/java/gov/nih/nci/cagrid/portal/portlet/SummaryContentViewControllerTest.java
+++ b/cagrid-portal/portlets/test/src/java/gov/nih/nci/cagrid/portal/portlet/SummaryContentViewControllerTest.java
@@ -1,31 +1,30 @@
package gov.nih.nci.cagrid.portal.portlet;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.springframework.mock.web.portlet.MockRenderRequest;
import org.springframework.mock.web.portlet.MockRenderResponse;
import org.springframework.web.portlet.ModelAndView;
/**
* User: kherm
*
* @author kherm [email protected]
*/
public class SummaryContentViewControllerTest {
protected MockRenderRequest request = new MockRenderRequest();
protected MockRenderResponse response = new MockRenderResponse();
@Test
public void handleRenderRequestInternal() throws Exception {
SummaryContentViewController controller = new SummaryContentViewController();
- controller.setSolrServiceUrl("url");
ModelAndView mav = controller.handleRenderRequest(request, response);
assertNotNull(response.getContentAsString());
assertTrue(mav.getModel().size() > 0);
}
}
| true | true | public void handleRenderRequestInternal() throws Exception {
SummaryContentViewController controller = new SummaryContentViewController();
controller.setSolrServiceUrl("url");
ModelAndView mav = controller.handleRenderRequest(request, response);
assertNotNull(response.getContentAsString());
assertTrue(mav.getModel().size() > 0);
}
| public void handleRenderRequestInternal() throws Exception {
SummaryContentViewController controller = new SummaryContentViewController();
ModelAndView mav = controller.handleRenderRequest(request, response);
assertNotNull(response.getContentAsString());
assertTrue(mav.getModel().size() > 0);
}
|
diff --git a/src/main/java/org/spout/vanilla/inventory/block/BrewingStandInventory.java b/src/main/java/org/spout/vanilla/inventory/block/BrewingStandInventory.java
index afa4d598..16152363 100644
--- a/src/main/java/org/spout/vanilla/inventory/block/BrewingStandInventory.java
+++ b/src/main/java/org/spout/vanilla/inventory/block/BrewingStandInventory.java
@@ -1,60 +1,60 @@
/*
* This file is part of Vanilla.
*
* Copyright (c) 2011-2012, VanillaDev <http://www.spout.org/>
* Vanilla is licensed under the SpoutDev License Version 1.
*
* Vanilla 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.
*
* In addition, 180 days after any changes are published, you can use the
* software, incorporating those changes, under the terms of the MIT license,
* as described in the SpoutDev License Version 1.
*
* Vanilla 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,
* the MIT license and the SpoutDev License Version 1 along with this program.
* If not, see <http://www.gnu.org/licenses/> for the GNU Lesser General Public
* License and see <http://www.spout.org/SpoutDevLicenseV1.txt> for the full license,
* including the MIT license.
*/
package org.spout.vanilla.inventory.block;
import org.spout.api.inventory.Inventory;
import org.spout.api.inventory.ItemStack;
import org.spout.vanilla.inventory.VanillaInventory;
public class BrewingStandInventory extends Inventory implements VanillaInventory {
private static final long serialVersionUID = 1L;
public BrewingStandInventory() {
super(4);
}
/**
* Gets the output slot at the given index. There are three output slots; the index given must be between 0 and 3.
* @param index of the output slot
* @return {@link ItemStack} in the output
*/
public ItemStack getOutput(int index) {
- if (index < 0 || index > 3) {
- throw new IllegalArgumentException("The output index of the brewing stand must be between 0 and 3.");
+ if (index < 0 || index > 2) {
+ throw new IllegalArgumentException("The output index of the brewing stand must be between 0 and 2.");
}
return getItem(index);
}
/**
* Gets the input of the brewing stand
* @return {@link ItemStack} in input of brewing stand.
*/
public ItemStack getInput() {
return getItem(3);
}
}
| true | true | public ItemStack getOutput(int index) {
if (index < 0 || index > 3) {
throw new IllegalArgumentException("The output index of the brewing stand must be between 0 and 3.");
}
return getItem(index);
}
| public ItemStack getOutput(int index) {
if (index < 0 || index > 2) {
throw new IllegalArgumentException("The output index of the brewing stand must be between 0 and 2.");
}
return getItem(index);
}
|
diff --git a/lucene/core/src/test/org/apache/lucene/util/TestVersion.java b/lucene/core/src/test/org/apache/lucene/util/TestVersion.java
index 2a62fca5e3..867caaf6e3 100644
--- a/lucene/core/src/test/org/apache/lucene/util/TestVersion.java
+++ b/lucene/core/src/test/org/apache/lucene/util/TestVersion.java
@@ -1,44 +1,44 @@
/*
* 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.util;
public class TestVersion extends LuceneTestCase {
public void test() {
for (Version v : Version.values()) {
assertTrue("LUCENE_CURRENT must be always onOrAfter("+v+")", Version.LUCENE_CURRENT.onOrAfter(v));
}
assertTrue(Version.LUCENE_50.onOrAfter(Version.LUCENE_40));
assertFalse(Version.LUCENE_40.onOrAfter(Version.LUCENE_50));
}
public void testParseLeniently() {
assertEquals(Version.LUCENE_40, Version.parseLeniently("4.0"));
assertEquals(Version.LUCENE_40, Version.parseLeniently("LUCENE_40"));
assertEquals(Version.LUCENE_CURRENT, Version.parseLeniently("LUCENE_CURRENT"));
}
public void testDeprecations() throws Exception {
Version values[] = Version.values();
// all but the latest version should be deprecated
for (int i = 0; i < values.length-2; i++) {
- assertTrue(values[i].name() + " should be deprecated",
- Version.class.getField(values[i].name()).isAnnotationPresent(Deprecated.class));
+ assertNotNull(values[i].name() + " should be deprecated",
+ Version.class.getField(values[i].name()).getAnnotation(Deprecated.class));
}
}
}
| true | true | public void testDeprecations() throws Exception {
Version values[] = Version.values();
// all but the latest version should be deprecated
for (int i = 0; i < values.length-2; i++) {
assertTrue(values[i].name() + " should be deprecated",
Version.class.getField(values[i].name()).isAnnotationPresent(Deprecated.class));
}
}
| public void testDeprecations() throws Exception {
Version values[] = Version.values();
// all but the latest version should be deprecated
for (int i = 0; i < values.length-2; i++) {
assertNotNull(values[i].name() + " should be deprecated",
Version.class.getField(values[i].name()).getAnnotation(Deprecated.class));
}
}
|
diff --git a/src/edu/wheaton/simulator/gui/IconGridPanel.java b/src/edu/wheaton/simulator/gui/IconGridPanel.java
index b6c5bc84..5d081d06 100644
--- a/src/edu/wheaton/simulator/gui/IconGridPanel.java
+++ b/src/edu/wheaton/simulator/gui/IconGridPanel.java
@@ -1,137 +1,137 @@
package edu.wheaton.simulator.gui;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import edu.wheaton.simulator.gui.screen.EditEntityScreen;
public class IconGridPanel extends GridPanel {
private static final long serialVersionUID = 8466121263560126226L;
private ScreenManager sm;
private int width;
private int height;
private int gridDimension;
private int pixelWidth;
private int pixelHeight;
private int squareSize;
private boolean[][] icon;
public IconGridPanel(final SimulatorFacade gm) {
super(gm);
sm = Gui.getScreenManager();
gridDimension = 7;
icon = new boolean[gridDimension][gridDimension];
for (int i = 0; i < gridDimension; i++){
for( int j = 0; j < gridDimension; j++){
icon[i][j] = false;
}
}
this.addMouseListener(new MouseListener(){
@Override
public void mouseClicked(MouseEvent me) {
width = getWidth();
height = getHeight();
pixelWidth = width / gridDimension;
pixelHeight = height / gridDimension;
squareSize = Math.min(pixelWidth, pixelHeight);
int x = me.getX();
int y = me.getY();
int xIndex = x/squareSize;
int yIndex = y/squareSize;
- if(xIndex > 0 && xIndex < 7 && yIndex > 0 && yIndex < 7){
+ if(xIndex > -1 && xIndex < 7 && yIndex > -1 && yIndex < 7){
icon[xIndex][yIndex] = !icon[xIndex][yIndex];
}
repaint();
}
@Override
public void mouseEntered(MouseEvent arg0) {}
@Override
public void mouseExited(MouseEvent arg0) {}
@Override
public void mousePressed(MouseEvent arg0) {}
@Override
public void mouseReleased(MouseEvent arg0) {}
});
}
@Override
public void paint(Graphics g) {
width = getWidth();
height = getHeight();
pixelWidth = width / gridDimension;
pixelHeight = height / gridDimension;
squareSize = Math.min(pixelWidth, pixelHeight);
g.setColor(Color.BLACK);
for (int i = 0; i < gridDimension; i++) {
for (int j = 0; j < gridDimension; j++) {
g.drawRect(squareSize * i, squareSize * j,
squareSize, squareSize);
}
}
clearAgents(g);
agentPaint(g);
}
@Override
public void agentPaint(Graphics g){
width = getWidth();
height = getHeight();
pixelWidth = width / gridDimension;
pixelHeight = height / gridDimension;
squareSize = Math.min(pixelWidth, pixelHeight);
Color color = ((EditEntityScreen)sm.getScreen("Edit Entities")).getColor();
g.setColor(color);
for (int i = 0; i < gridDimension; i++) {
for (int j = 0; j < gridDimension; j++) {
if(icon[i][j] == true){
g.fillRect(squareSize * i + 1, squareSize * j + 1,
squareSize - 1, squareSize - 1);
}
}
}
}
@Override
public void clearAgents(Graphics g) {
width = getWidth();
height = getHeight();
pixelWidth = width / gridDimension;
pixelHeight = height / gridDimension;
squareSize = Math.min(pixelWidth, pixelHeight);
squareSize = Math.min(pixelWidth, pixelHeight) - 1;
g.setColor(Color.WHITE);
for (int x = 0; x < gridDimension; x++) {
for (int y = 0; y < gridDimension; y++) {
g.fillRect(squareSize * x + (x + 1), squareSize * y + (y + 1), squareSize, squareSize);
}
}
}
public void setIcon(boolean[][] icon){
this.icon = icon;
}
}
| true | true | public IconGridPanel(final SimulatorFacade gm) {
super(gm);
sm = Gui.getScreenManager();
gridDimension = 7;
icon = new boolean[gridDimension][gridDimension];
for (int i = 0; i < gridDimension; i++){
for( int j = 0; j < gridDimension; j++){
icon[i][j] = false;
}
}
this.addMouseListener(new MouseListener(){
@Override
public void mouseClicked(MouseEvent me) {
width = getWidth();
height = getHeight();
pixelWidth = width / gridDimension;
pixelHeight = height / gridDimension;
squareSize = Math.min(pixelWidth, pixelHeight);
int x = me.getX();
int y = me.getY();
int xIndex = x/squareSize;
int yIndex = y/squareSize;
if(xIndex > 0 && xIndex < 7 && yIndex > 0 && yIndex < 7){
icon[xIndex][yIndex] = !icon[xIndex][yIndex];
}
repaint();
}
@Override
public void mouseEntered(MouseEvent arg0) {}
@Override
public void mouseExited(MouseEvent arg0) {}
@Override
public void mousePressed(MouseEvent arg0) {}
@Override
public void mouseReleased(MouseEvent arg0) {}
});
}
| public IconGridPanel(final SimulatorFacade gm) {
super(gm);
sm = Gui.getScreenManager();
gridDimension = 7;
icon = new boolean[gridDimension][gridDimension];
for (int i = 0; i < gridDimension; i++){
for( int j = 0; j < gridDimension; j++){
icon[i][j] = false;
}
}
this.addMouseListener(new MouseListener(){
@Override
public void mouseClicked(MouseEvent me) {
width = getWidth();
height = getHeight();
pixelWidth = width / gridDimension;
pixelHeight = height / gridDimension;
squareSize = Math.min(pixelWidth, pixelHeight);
int x = me.getX();
int y = me.getY();
int xIndex = x/squareSize;
int yIndex = y/squareSize;
if(xIndex > -1 && xIndex < 7 && yIndex > -1 && yIndex < 7){
icon[xIndex][yIndex] = !icon[xIndex][yIndex];
}
repaint();
}
@Override
public void mouseEntered(MouseEvent arg0) {}
@Override
public void mouseExited(MouseEvent arg0) {}
@Override
public void mousePressed(MouseEvent arg0) {}
@Override
public void mouseReleased(MouseEvent arg0) {}
});
}
|
diff --git a/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/ConstantNameCheck.java b/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/ConstantNameCheck.java
index 1208828c..ac99545d 100644
--- a/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/ConstantNameCheck.java
+++ b/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/ConstantNameCheck.java
@@ -1,70 +1,71 @@
////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2002 Oliver Burn
//
// 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 com.puppycrawl.tools.checkstyle.checks;
import com.puppycrawl.tools.checkstyle.api.DetailAST;
import com.puppycrawl.tools.checkstyle.api.ScopeUtils;
import com.puppycrawl.tools.checkstyle.api.TokenTypes;
/**
* Checks that constant names conform to a specified format.
*
* @author Rick Giles
* @version 1.0
*/
public class ConstantNameCheck
extends AbstractNameCheck
{
/** Creates a new <code>ConstantNameCheck</code> instance. */
public ConstantNameCheck()
{
super("^[A-Z](_?[A-Z0-9]+)*$");
}
/** @see com.puppycrawl.tools.checkstyle.api.Check */
public int[] getDefaultTokens()
{
return new int[] {TokenTypes.VARIABLE_DEF};
}
/** @see com.puppycrawl.tools.checkstyle.checks.AbstractNameCheck */
protected final boolean mustCheckName(DetailAST aAST)
{
boolean retVal = false;
DetailAST modifiersAST = aAST.findFirstToken(TokenTypes.MODIFIERS);
final boolean isStatic = modifiersAST != null
&& modifiersAST.branchContains(TokenTypes.LITERAL_STATIC);
final boolean isFinal = modifiersAST != null
&& modifiersAST.branchContains(TokenTypes.FINAL);
if ((isStatic && isFinal) || ScopeUtils.inInterfaceBlock(aAST)) {
// Handle the serialVersionUID constant which is used for
// Serialization. Cannot enforce rules on it. :-)
final DetailAST nameAST = aAST.findFirstToken(TokenTypes.IDENT);
if ((nameAST != null)
- && !("serialVersionUID".equals(nameAST.getText()))) {
+ && !("serialVersionUID".equals(nameAST.getText())))
+ {
retVal = true;
}
}
return retVal;
}
}
| true | true | protected final boolean mustCheckName(DetailAST aAST)
{
boolean retVal = false;
DetailAST modifiersAST = aAST.findFirstToken(TokenTypes.MODIFIERS);
final boolean isStatic = modifiersAST != null
&& modifiersAST.branchContains(TokenTypes.LITERAL_STATIC);
final boolean isFinal = modifiersAST != null
&& modifiersAST.branchContains(TokenTypes.FINAL);
if ((isStatic && isFinal) || ScopeUtils.inInterfaceBlock(aAST)) {
// Handle the serialVersionUID constant which is used for
// Serialization. Cannot enforce rules on it. :-)
final DetailAST nameAST = aAST.findFirstToken(TokenTypes.IDENT);
if ((nameAST != null)
&& !("serialVersionUID".equals(nameAST.getText()))) {
retVal = true;
}
}
return retVal;
}
| protected final boolean mustCheckName(DetailAST aAST)
{
boolean retVal = false;
DetailAST modifiersAST = aAST.findFirstToken(TokenTypes.MODIFIERS);
final boolean isStatic = modifiersAST != null
&& modifiersAST.branchContains(TokenTypes.LITERAL_STATIC);
final boolean isFinal = modifiersAST != null
&& modifiersAST.branchContains(TokenTypes.FINAL);
if ((isStatic && isFinal) || ScopeUtils.inInterfaceBlock(aAST)) {
// Handle the serialVersionUID constant which is used for
// Serialization. Cannot enforce rules on it. :-)
final DetailAST nameAST = aAST.findFirstToken(TokenTypes.IDENT);
if ((nameAST != null)
&& !("serialVersionUID".equals(nameAST.getText())))
{
retVal = true;
}
}
return retVal;
}
|
diff --git a/micropolis-java/src/micropolisj/engine/TornadoSprite.java b/micropolis-java/src/micropolisj/engine/TornadoSprite.java
index cfdca3d..b6702c8 100644
--- a/micropolis-java/src/micropolisj/engine/TornadoSprite.java
+++ b/micropolis-java/src/micropolisj/engine/TornadoSprite.java
@@ -1,82 +1,86 @@
// This file is part of MicropolisJ.
// Copyright (C) 2013 Jason Long
// Portions Copyright (C) 1989-2007 Electronic Arts Inc.
//
// MicropolisJ is free software; you can redistribute it and/or modify
// it under the terms of the GNU GPLv3, with additional terms.
// See the README file, included in this distribution, for details.
package micropolisj.engine;
public class TornadoSprite extends Sprite
{
static int [] CDx = { 2, 3, 2, 0, -2, -3 };
static int [] CDy = { -2, 0, 2, 3, 2, 0 };
boolean flag;
int count;
public TornadoSprite(Micropolis engine, int xpos, int ypos)
{
super(engine, SpriteKind.TOR);
this.x = xpos * 16 + 8;
this.y = ypos * 16 + 8;
this.width = 48;
this.height = 48;
this.offx = -24;
this.offy = -40;
this.frame = 1;
this.count = 200;
}
@Override
public void moveImpl()
{
int z = this.frame;
if (z == 2) {
//cycle animation
if (this.flag)
z = 3;
else
z = 1;
}
else {
this.flag = (z == 1);
z = 2;
}
if (this.count > 0) {
this.count--;
}
this.frame = z;
for (Sprite s : city.allSprites()) {
if (checkSpriteCollision(s) &&
(s.kind == SpriteKind.AIR ||
s.kind == SpriteKind.COP ||
s.kind == SpriteKind.SHI ||
s.kind == SpriteKind.TRA)
) {
s.explodeSprite();
}
}
int zz = city.PRNG.nextInt(CDx.length);
x += CDx[zz];
y += CDy[zz];
if (!city.testBounds(x/16, y/16)) {
// out of bounds
this.frame = 0;
return;
}
- // FIXME- the original code checks here for an ending condition
+ if (this.count == 0 && city.PRNG.nextInt(501) == 0) {
+ // early termination
+ this.frame = 0;
+ return;
+ }
destroyTile(x/16, y/16);
}
}
| true | true | public void moveImpl()
{
int z = this.frame;
if (z == 2) {
//cycle animation
if (this.flag)
z = 3;
else
z = 1;
}
else {
this.flag = (z == 1);
z = 2;
}
if (this.count > 0) {
this.count--;
}
this.frame = z;
for (Sprite s : city.allSprites()) {
if (checkSpriteCollision(s) &&
(s.kind == SpriteKind.AIR ||
s.kind == SpriteKind.COP ||
s.kind == SpriteKind.SHI ||
s.kind == SpriteKind.TRA)
) {
s.explodeSprite();
}
}
int zz = city.PRNG.nextInt(CDx.length);
x += CDx[zz];
y += CDy[zz];
if (!city.testBounds(x/16, y/16)) {
// out of bounds
this.frame = 0;
return;
}
// FIXME- the original code checks here for an ending condition
destroyTile(x/16, y/16);
}
| public void moveImpl()
{
int z = this.frame;
if (z == 2) {
//cycle animation
if (this.flag)
z = 3;
else
z = 1;
}
else {
this.flag = (z == 1);
z = 2;
}
if (this.count > 0) {
this.count--;
}
this.frame = z;
for (Sprite s : city.allSprites()) {
if (checkSpriteCollision(s) &&
(s.kind == SpriteKind.AIR ||
s.kind == SpriteKind.COP ||
s.kind == SpriteKind.SHI ||
s.kind == SpriteKind.TRA)
) {
s.explodeSprite();
}
}
int zz = city.PRNG.nextInt(CDx.length);
x += CDx[zz];
y += CDy[zz];
if (!city.testBounds(x/16, y/16)) {
// out of bounds
this.frame = 0;
return;
}
if (this.count == 0 && city.PRNG.nextInt(501) == 0) {
// early termination
this.frame = 0;
return;
}
destroyTile(x/16, y/16);
}
|
diff --git a/src/org/jruby/RubyThreadGroup.java b/src/org/jruby/RubyThreadGroup.java
index 66910cf5a..6f27baa1e 100644
--- a/src/org/jruby/RubyThreadGroup.java
+++ b/src/org/jruby/RubyThreadGroup.java
@@ -1,118 +1,119 @@
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* 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.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2004 Charles O Nutter <[email protected]>
* Copyright (C) 2004 Jan Arne Petersen <[email protected]>
* Copyright (C) 2004 Stefan Matthias Aust <[email protected]>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import java.util.HashMap;
import java.util.Map;
import org.jruby.anno.JRubyMethod;
import org.jruby.anno.JRubyClass;
import org.jruby.runtime.Block;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.builtin.IRubyObject;
/**
* Implementation of Ruby's <code>ThreadGroup</code> class. This is currently
* just a stub.
* <p>
*
* @author Charles O Nutter ([email protected])
*/
@JRubyClass(name="ThreadGroup")
public class RubyThreadGroup extends RubyObject {
private Map<Integer, IRubyObject> rubyThreadList = new HashMap<Integer, IRubyObject>();
private boolean enclosed = false;
// ENEBO: Can these be fast?
public static RubyClass createThreadGroupClass(Ruby runtime) {
RubyClass threadGroupClass = runtime.defineClass("ThreadGroup", runtime.getObject(), ObjectAllocator.NOT_ALLOCATABLE_ALLOCATOR);
runtime.setThreadGroup(threadGroupClass);
threadGroupClass.defineAnnotatedMethods(RubyThreadGroup.class);
// create the default thread group
RubyThreadGroup defaultThreadGroup = new RubyThreadGroup(runtime, threadGroupClass);
threadGroupClass.defineConstant("Default", defaultThreadGroup);
return threadGroupClass;
}
@JRubyMethod(name = "new", frame = true, meta = true)
public static IRubyObject newInstance(IRubyObject recv, Block block) {
return new RubyThreadGroup(recv.getRuntime(), (RubyClass)recv);
}
@JRubyMethod(name = "add", required = 1, frame = true)
public synchronized IRubyObject add(IRubyObject rubyThread, Block block) {
if (!(rubyThread instanceof RubyThread)) throw getRuntime().newTypeError(rubyThread, getRuntime().getThread());
if (isFrozen()) {
throw getRuntime().newTypeError("can't add to frozen ThreadGroup");
}
RubyThread thread = (RubyThread)rubyThread;
- if (thread.group() != getRuntime().getNil()) {
- RubyThreadGroup threadGroup = (RubyThreadGroup) thread.group();
+ IRubyObject oldGroup = thread.group();
+ if (oldGroup != getRuntime().getNil()) {
+ RubyThreadGroup threadGroup = (RubyThreadGroup) oldGroup;
threadGroup.rubyThreadList.remove(new Integer(System.identityHashCode(rubyThread)));
}
thread.setThreadGroup(this);
rubyThreadList.put(new Integer(System.identityHashCode(rubyThread)), rubyThread);
return this;
}
public synchronized void remove(RubyThread rubyThread) {
rubyThread.setThreadGroup(null);
rubyThreadList.remove(new Integer(System.identityHashCode(rubyThread)));
}
@JRubyMethod(name = "enclose", frame = true)
public IRubyObject enclose(Block block) {
enclosed = true;
return this;
}
@JRubyMethod(name = "enclosed?", frame = true)
public IRubyObject enclosed_p(Block block) {
return new RubyBoolean(getRuntime(), enclosed);
}
@JRubyMethod(name = "list", frame = true)
public synchronized IRubyObject list(Block block) {
return getRuntime().newArrayNoCopy((IRubyObject[]) rubyThreadList.values().toArray(new IRubyObject[rubyThreadList.size()]));
}
private RubyThreadGroup(Ruby runtime, RubyClass type) {
super(runtime, type);
}
}
| true | true | public synchronized IRubyObject add(IRubyObject rubyThread, Block block) {
if (!(rubyThread instanceof RubyThread)) throw getRuntime().newTypeError(rubyThread, getRuntime().getThread());
if (isFrozen()) {
throw getRuntime().newTypeError("can't add to frozen ThreadGroup");
}
RubyThread thread = (RubyThread)rubyThread;
if (thread.group() != getRuntime().getNil()) {
RubyThreadGroup threadGroup = (RubyThreadGroup) thread.group();
threadGroup.rubyThreadList.remove(new Integer(System.identityHashCode(rubyThread)));
}
thread.setThreadGroup(this);
rubyThreadList.put(new Integer(System.identityHashCode(rubyThread)), rubyThread);
return this;
}
| public synchronized IRubyObject add(IRubyObject rubyThread, Block block) {
if (!(rubyThread instanceof RubyThread)) throw getRuntime().newTypeError(rubyThread, getRuntime().getThread());
if (isFrozen()) {
throw getRuntime().newTypeError("can't add to frozen ThreadGroup");
}
RubyThread thread = (RubyThread)rubyThread;
IRubyObject oldGroup = thread.group();
if (oldGroup != getRuntime().getNil()) {
RubyThreadGroup threadGroup = (RubyThreadGroup) oldGroup;
threadGroup.rubyThreadList.remove(new Integer(System.identityHashCode(rubyThread)));
}
thread.setThreadGroup(this);
rubyThreadList.put(new Integer(System.identityHashCode(rubyThread)), rubyThread);
return this;
}
|
diff --git a/nexus/nexus-rest-api/src/main/java/org/sonatype/nexus/rest/groups/RepositoryGroupListPlexusResource.java b/nexus/nexus-rest-api/src/main/java/org/sonatype/nexus/rest/groups/RepositoryGroupListPlexusResource.java
index 98f1a7149..a59a55ad9 100644
--- a/nexus/nexus-rest-api/src/main/java/org/sonatype/nexus/rest/groups/RepositoryGroupListPlexusResource.java
+++ b/nexus/nexus-rest-api/src/main/java/org/sonatype/nexus/rest/groups/RepositoryGroupListPlexusResource.java
@@ -1,173 +1,173 @@
/**
* Sonatype Nexus (TM) Open Source Version.
* Copyright (c) 2008 Sonatype, Inc. All rights reserved.
* Includes the third-party code listed at http://nexus.sonatype.org/dev/attributions.html
* This program is licensed to you under Version 3 only of the GNU General Public License 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 Version 3 for more details.
* You should have received a copy of the GNU General Public License Version 3 along with this program.
* If not, see http://www.gnu.org/licenses/.
* Sonatype Nexus (TM) Professional Version is available from Sonatype, Inc.
* "Sonatype" and "Sonatype Nexus" are trademarks of Sonatype, Inc.
*/
package org.sonatype.nexus.rest.groups;
import java.util.Collection;
import java.util.List;
import org.codehaus.plexus.component.annotations.Component;
import org.restlet.Context;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.data.Status;
import org.restlet.resource.ResourceException;
import org.restlet.resource.Variant;
import org.sonatype.nexus.configuration.model.CRepositoryGroup;
import org.sonatype.nexus.proxy.NoSuchRepositoryException;
import org.sonatype.nexus.proxy.repository.GroupRepository;
import org.sonatype.nexus.rest.model.RepositoryGroupListResource;
import org.sonatype.nexus.rest.model.RepositoryGroupListResourceResponse;
import org.sonatype.nexus.rest.model.RepositoryGroupMemberRepository;
import org.sonatype.nexus.rest.model.RepositoryGroupResource;
import org.sonatype.nexus.rest.model.RepositoryGroupResourceResponse;
import org.sonatype.plexus.rest.resource.PathProtectionDescriptor;
import org.sonatype.plexus.rest.resource.PlexusResource;
import org.sonatype.plexus.rest.resource.PlexusResourceException;
/**
* A resource list for RepositoryGroup list.
*
* @author cstamas
* @author tstevens
*/
@Component( role = PlexusResource.class, hint = "RepositoryGroupListPlexusResource" )
public class RepositoryGroupListPlexusResource
extends AbstractRepositoryGroupPlexusResource
{
public RepositoryGroupListPlexusResource()
{
this.setModifiable( true );
}
@Override
public Object getPayloadInstance()
{
return new RepositoryGroupResourceResponse();
}
@Override
public String getResourceUri()
{
return "/repo_groups";
}
@Override
public PathProtectionDescriptor getResourceProtection()
{
return new PathProtectionDescriptor( getResourceUri(), "authcBasic,perms[nexus:repogroups]" );
}
@SuppressWarnings("unchecked")
@Override
public Object get( Context context, Request request, Response response, Variant variant )
throws ResourceException
{
RepositoryGroupListResourceResponse result = new RepositoryGroupListResourceResponse();
Collection<CRepositoryGroup> groups = getNexus().listRepositoryGroups();
try
{
for ( CRepositoryGroup group : groups )
{
RepositoryGroupListResource resource = new RepositoryGroupListResource();
- resource.setResourceURI( createChildReference( request, group.getGroupId() ).toString() );
+ resource.setResourceURI( createRepositoryGroupReference( request, group.getGroupId() ).toString() );
resource.setId( group.getGroupId() );
resource.setFormat( getNexus()
.getRepositoryWithFacet( group.getGroupId(), GroupRepository.class ).getRepositoryContentClass()
.getId() );
resource.setName( group.getName() );
// just to trigger list creation, and not stay null coz of XStream serialization
resource.getRepositories();
for ( String repoId : (List<String>) group.getRepositories() )
{
RepositoryGroupMemberRepository member = new RepositoryGroupMemberRepository();
member.setId( repoId );
member.setName( getNexus().getRepository( repoId ).getName() );
member.setResourceURI( createRepositoryReference( request, repoId ).toString() );
resource.addRepository( member );
}
result.addData( resource );
}
}
catch ( NoSuchRepositoryException e )
{
getLogger().warn( "Cannot find a repository group or repository declared within a group!", e );
throw new ResourceException( Status.SERVER_ERROR_INTERNAL );
}
return result;
}
@Override
public Object post( Context context, Request request, Response response, Object payload )
throws ResourceException
{
RepositoryGroupResourceResponse groupRequest = (RepositoryGroupResourceResponse) payload;
if ( groupRequest != null )
{
RepositoryGroupResource resource = groupRequest.getData();
if ( resource.getRepositories() == null || resource.getRepositories().size() == 0 )
{
getLogger()
.info( "The repository group with ID=" + resource.getId() + " have zero repository members!" );
throw new PlexusResourceException(
Status.CLIENT_ERROR_BAD_REQUEST,
"The group cannot have zero repository members!",
getNexusErrorResponse( "repositories", "The group cannot have zero repository members!" ) );
}
try
{
CRepositoryGroup group = getNexus().readRepositoryGroup( resource.getId() );
if ( group != null )
{
getLogger().info( "The repository group with ID=" + group.getGroupId() + " already exists!" );
throw new PlexusResourceException( Status.CLIENT_ERROR_BAD_REQUEST, "The repository group with ID="
+ group.getGroupId() + " already exists!", getNexusErrorResponse(
"id",
"The repository group with id=" + group.getGroupId() + " already exists!" ) );
}
}
catch ( NoSuchRepositoryException ex )
{
createOrUpdateRepositoryGroup( resource, true );
}
}
// TODO: return the group
return null;
}
}
| true | true | public Object get( Context context, Request request, Response response, Variant variant )
throws ResourceException
{
RepositoryGroupListResourceResponse result = new RepositoryGroupListResourceResponse();
Collection<CRepositoryGroup> groups = getNexus().listRepositoryGroups();
try
{
for ( CRepositoryGroup group : groups )
{
RepositoryGroupListResource resource = new RepositoryGroupListResource();
resource.setResourceURI( createChildReference( request, group.getGroupId() ).toString() );
resource.setId( group.getGroupId() );
resource.setFormat( getNexus()
.getRepositoryWithFacet( group.getGroupId(), GroupRepository.class ).getRepositoryContentClass()
.getId() );
resource.setName( group.getName() );
// just to trigger list creation, and not stay null coz of XStream serialization
resource.getRepositories();
for ( String repoId : (List<String>) group.getRepositories() )
{
RepositoryGroupMemberRepository member = new RepositoryGroupMemberRepository();
member.setId( repoId );
member.setName( getNexus().getRepository( repoId ).getName() );
member.setResourceURI( createRepositoryReference( request, repoId ).toString() );
resource.addRepository( member );
}
result.addData( resource );
}
}
catch ( NoSuchRepositoryException e )
{
getLogger().warn( "Cannot find a repository group or repository declared within a group!", e );
throw new ResourceException( Status.SERVER_ERROR_INTERNAL );
}
return result;
}
| public Object get( Context context, Request request, Response response, Variant variant )
throws ResourceException
{
RepositoryGroupListResourceResponse result = new RepositoryGroupListResourceResponse();
Collection<CRepositoryGroup> groups = getNexus().listRepositoryGroups();
try
{
for ( CRepositoryGroup group : groups )
{
RepositoryGroupListResource resource = new RepositoryGroupListResource();
resource.setResourceURI( createRepositoryGroupReference( request, group.getGroupId() ).toString() );
resource.setId( group.getGroupId() );
resource.setFormat( getNexus()
.getRepositoryWithFacet( group.getGroupId(), GroupRepository.class ).getRepositoryContentClass()
.getId() );
resource.setName( group.getName() );
// just to trigger list creation, and not stay null coz of XStream serialization
resource.getRepositories();
for ( String repoId : (List<String>) group.getRepositories() )
{
RepositoryGroupMemberRepository member = new RepositoryGroupMemberRepository();
member.setId( repoId );
member.setName( getNexus().getRepository( repoId ).getName() );
member.setResourceURI( createRepositoryReference( request, repoId ).toString() );
resource.addRepository( member );
}
result.addData( resource );
}
}
catch ( NoSuchRepositoryException e )
{
getLogger().warn( "Cannot find a repository group or repository declared within a group!", e );
throw new ResourceException( Status.SERVER_ERROR_INTERNAL );
}
return result;
}
|
diff --git a/src/main/java/uk/org/cowgill/james/jircd/commands/Part.java b/src/main/java/uk/org/cowgill/james/jircd/commands/Part.java
index b80168a..76e256e 100644
--- a/src/main/java/uk/org/cowgill/james/jircd/commands/Part.java
+++ b/src/main/java/uk/org/cowgill/james/jircd/commands/Part.java
@@ -1,101 +1,101 @@
/*
Copyright 2011 James Cowgill
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 uk.org.cowgill.james.jircd.commands;
import uk.org.cowgill.james.jircd.Channel;
import uk.org.cowgill.james.jircd.Client;
import uk.org.cowgill.james.jircd.Command;
import uk.org.cowgill.james.jircd.Message;
import uk.org.cowgill.james.jircd.Server;
/**
* The PART command - parts a channel
*
* @author James
*/
public class Part implements Command
{
@Override
public void run(Client client, Message msg)
{
//Parse the part parameters
String[] channelStrings = msg.getParam(0).split(",");
String partMsg;
if(msg.paramCount() >= 2)
{
- partMsg = msg.getParam(2);
+ partMsg = msg.getParam(1);
}
else
{
partMsg = client.id.nick;
}
//Process requests
for(int i = 0; i < channelStrings.length; ++i)
{
//Lookup channel
Channel channel = Server.getServer().getChannel(channelStrings[i]);
if(channel == null)
{
client.send(client.newNickMessage("403").appendParam(channelStrings[i]).
appendParam("No such channel"));
continue;
}
//Part
if(!channel.part(client, partMsg))
{
client.send(client.newNickMessage("442").appendParam(channelStrings[i]).
appendParam("You're not on that channel"));
continue;
}
}
}
@Override
public int getMinParameters()
{
return 1;
}
@Override
public String getName()
{
return "PART";
}
@Override
public int getFlags()
{
return FLAG_NORMAL;
}
/**
* The LEAVE command - alias of PART
*
* @author James
*/
public static class Leave extends Part
{
@Override
public String getName()
{
return "LEAVE";
}
}
}
| true | true | public void run(Client client, Message msg)
{
//Parse the part parameters
String[] channelStrings = msg.getParam(0).split(",");
String partMsg;
if(msg.paramCount() >= 2)
{
partMsg = msg.getParam(2);
}
else
{
partMsg = client.id.nick;
}
//Process requests
for(int i = 0; i < channelStrings.length; ++i)
{
//Lookup channel
Channel channel = Server.getServer().getChannel(channelStrings[i]);
if(channel == null)
{
client.send(client.newNickMessage("403").appendParam(channelStrings[i]).
appendParam("No such channel"));
continue;
}
//Part
if(!channel.part(client, partMsg))
{
client.send(client.newNickMessage("442").appendParam(channelStrings[i]).
appendParam("You're not on that channel"));
continue;
}
}
}
| public void run(Client client, Message msg)
{
//Parse the part parameters
String[] channelStrings = msg.getParam(0).split(",");
String partMsg;
if(msg.paramCount() >= 2)
{
partMsg = msg.getParam(1);
}
else
{
partMsg = client.id.nick;
}
//Process requests
for(int i = 0; i < channelStrings.length; ++i)
{
//Lookup channel
Channel channel = Server.getServer().getChannel(channelStrings[i]);
if(channel == null)
{
client.send(client.newNickMessage("403").appendParam(channelStrings[i]).
appendParam("No such channel"));
continue;
}
//Part
if(!channel.part(client, partMsg))
{
client.send(client.newNickMessage("442").appendParam(channelStrings[i]).
appendParam("You're not on that channel"));
continue;
}
}
}
|
diff --git a/src/frontend/edu/brown/markov/containers/MarkovGraphContainersUtil.java b/src/frontend/edu/brown/markov/containers/MarkovGraphContainersUtil.java
index 2fc3fcadd..eb1721e86 100644
--- a/src/frontend/edu/brown/markov/containers/MarkovGraphContainersUtil.java
+++ b/src/frontend/edu/brown/markov/containers/MarkovGraphContainersUtil.java
@@ -1,470 +1,472 @@
package edu.brown.markov.containers;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.log4j.Logger;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONStringer;
import org.voltdb.catalog.Database;
import org.voltdb.catalog.Procedure;
import org.voltdb.utils.Pair;
import edu.brown.catalog.CatalogUtil;
import edu.brown.hashing.AbstractHasher;
import edu.brown.logging.LoggerUtil;
import edu.brown.logging.LoggerUtil.LoggerBoolean;
import edu.brown.markov.MarkovGraph;
import edu.brown.markov.MarkovUtil;
import edu.brown.statistics.Histogram;
import edu.brown.utils.ClassUtil;
import edu.brown.utils.CollectionUtil;
import edu.brown.utils.FileUtil;
import edu.brown.utils.PartitionEstimator;
import edu.brown.utils.ThreadUtil;
import edu.brown.workload.TransactionTrace;
import edu.brown.workload.Workload;
public abstract class MarkovGraphContainersUtil {
public static final Logger LOG = Logger.getLogger(MarkovGraphContainersUtil.class);
public final static LoggerBoolean debug = new LoggerBoolean(LOG.isDebugEnabled());
private static final LoggerBoolean trace = new LoggerBoolean(LOG.isTraceEnabled());
static {
LoggerUtil.attachObserver(LOG, debug, trace);
}
// ----------------------------------------------------------------------------
// INSTANTATION METHODS
// ----------------------------------------------------------------------------
/**
* Create the MarkovGraphsContainers for the given workload
* @param args
* @throws Exception
*/
public static <T extends MarkovGraphsContainer> Map<Integer, MarkovGraphsContainer> createMarkovGraphsContainers(final Database catalog_db, final Workload workload, final PartitionEstimator p_estimator, final Class<T> containerClass) throws Exception {
final Map<Integer, MarkovGraphsContainer> markovs_map = new ConcurrentHashMap<Integer, MarkovGraphsContainer>();
return createMarkovGraphsContainers(catalog_db, workload, p_estimator, containerClass, markovs_map);
}
/**
* Create the MarkovGraphsContainers for the given workload.
* The markovs_map could contain an existing collection MarkovGraphsContainers
* @param catalog_db
* @param workload
* @param p_estimator
* @param containerClass
* @param markovs_map
* @return
* @throws Exception
*/
@SuppressWarnings("unchecked")
public static <T extends MarkovGraphsContainer> Map<Integer, MarkovGraphsContainer> createMarkovGraphsContainers(final Database catalog_db, final Workload workload, final PartitionEstimator p_estimator, final Class<T> containerClass, final Map<Integer, MarkovGraphsContainer> markovs_map) throws Exception {
final String className = containerClass.getSimpleName();
final List<Runnable> runnables = new ArrayList<Runnable>();
final Set<Procedure> procedures = workload.getProcedures(catalog_db);
final Histogram<Procedure> proc_h = new Histogram<Procedure>();
final int num_transactions = workload.getTransactionCount();
final int marker = Math.max(1, (int)(num_transactions * 0.10));
final AtomicInteger finished_ctr = new AtomicInteger(0);
final AtomicInteger txn_ctr = new AtomicInteger(0);
final int num_threads = ThreadUtil.getMaxGlobalThreads();
final Constructor<T> constructor = ClassUtil.getConstructor(containerClass, new Class<?>[]{Collection.class});
final boolean is_global = containerClass.equals(GlobalMarkovGraphsContainer.class);
final List<Thread> processing_threads = new ArrayList<Thread>();
final LinkedBlockingDeque<Pair<Integer, TransactionTrace>> queues[] = (LinkedBlockingDeque<Pair<Integer, TransactionTrace>>[])new LinkedBlockingDeque<?>[num_threads];
for (int i = 0; i < num_threads; i++) {
queues[i] = new LinkedBlockingDeque<Pair<Integer, TransactionTrace>>();
} // FOR
// QUEUING THREAD
final AtomicBoolean queued_all = new AtomicBoolean(false);
runnables.add(new Runnable() {
@Override
public void run() {
List<TransactionTrace> all_txns = new ArrayList<TransactionTrace>(workload.getTransactions());
Collections.shuffle(all_txns);
int ctr = 0;
for (TransactionTrace txn_trace : all_txns) {
// Make sure it goes to the right base partition
Integer partition = null;
try {
partition = p_estimator.getBasePartition(txn_trace);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
assert(partition != null) : "Failed to get base partition for " + txn_trace + "\n" + txn_trace.debug(catalog_db);
queues[ctr % num_threads].add(Pair.of(partition, txn_trace));
if (++ctr % marker == 0) LOG.info(String.format("Queued %d/%d transactions", ctr, num_transactions));
} // FOR
queued_all.set(true);
// Poke all our threads just in case they finished
- for (Thread t : processing_threads) t.interrupt();
+ for (Thread t : processing_threads) {
+ if (t != null) t.interrupt();
+ } // FOR
}
});
// PROCESSING THREADS
for (int i = 0; i < num_threads; i++) {
final int thread_id = i;
runnables.add(new Runnable() {
@Override
public void run() {
Thread self = Thread.currentThread();
processing_threads.add(self);
MarkovGraphsContainer markovs = null;
Pair<Integer, TransactionTrace> pair = null;
while (true) {
try {
if (queued_all.get()) {
pair = queues[thread_id].poll();
} else {
pair = queues[thread_id].take();
// Steal work
if (pair == null) {
for (int i = 0; i < num_threads; i++) {
if (i == thread_id) continue;
pair = queues[i].take();
if (pair != null) break;
} // FOR
}
}
} catch (InterruptedException ex) {
continue;
}
if (pair == null) break;
int partition = pair.getFirst();
TransactionTrace txn_trace = pair.getSecond();
Procedure catalog_proc = txn_trace.getCatalogItem(catalog_db);
long txn_id = txn_trace.getTransactionId();
try {
int map_id = (is_global ? MarkovUtil.GLOBAL_MARKOV_CONTAINER_ID : partition);
Object params[] = txn_trace.getParams();
markovs = markovs_map.get(map_id);
if (markovs == null) {
synchronized (markovs_map) {
markovs = markovs_map.get(map_id);
if (markovs == null) {
markovs = constructor.newInstance(new Object[]{procedures});
markovs.setHasher(p_estimator.getHasher());
markovs_map.put(map_id, markovs);
}
} // SYNCH
}
MarkovGraph markov = markovs.getFromParams(txn_id, map_id, params, catalog_proc);
synchronized (markov) {
markov.processTransaction(txn_trace, p_estimator);
} // SYNCH
} catch (Exception ex) {
LOG.fatal("Failed to process " + txn_trace, ex);
throw new RuntimeException(ex);
}
proc_h.put(catalog_proc);
int global_ctr = txn_ctr.incrementAndGet();
if (debug.get() && global_ctr % marker == 0) {
LOG.debug(String.format("Processed %d/%d transactions",
global_ctr, num_transactions));
}
} // FOR
LOG.info(String.format("Processing thread finished creating %s [%d/%d]",
className, finished_ctr.incrementAndGet(), num_threads));
}
});
} // FOR
LOG.info(String.format("Generating %s for %d partitions using %d threads",
className, CatalogUtil.getNumberOfPartitions(catalog_db), num_threads));
ThreadUtil.runGlobalPool(runnables);
LOG.info("Procedure Histogram:\n" + proc_h);
MarkovGraphContainersUtil.calculateProbabilities(markovs_map);
return (markovs_map);
}
/**
* Construct all of the Markov graphs for a workload+catalog split by the txn's base partition
* @param catalog_db
* @param workload
* @param p_estimator
* @return
*/
public static MarkovGraphsContainer createBasePartitionMarkovGraphsContainer(final Database catalog_db, final Workload workload, final PartitionEstimator p_estimator) {
assert(workload != null);
assert(p_estimator != null);
Map<Integer, MarkovGraphsContainer> markovs_map = null;
try {
markovs_map = createMarkovGraphsContainers(catalog_db, workload, p_estimator, MarkovGraphsContainer.class);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
assert(markovs_map != null);
// Combine in a single Container
final MarkovGraphsContainer combined = new MarkovGraphsContainer();
for (Integer p : markovs_map.keySet()) {
combined.copy(markovs_map.get(p));
} // FOR
return (combined);
}
/**
* Combine multiple MarkovGraphsContainer files into a single file
* @param markovs
* @param output_path
*/
public static void combine(Map<Integer, File> markovs, String output_path, Database catalog_db) {
// Sort the list of partitions so we always iterate over them in the same order
SortedSet<Integer> sorted = new TreeSet<Integer>(markovs.keySet());
// We want all the procedures
Set<Procedure> procedures = (Set<Procedure>)CollectionUtil.addAll(new HashSet<Procedure>(), catalog_db.getProcedures());
File file = new File(output_path);
try {
FileOutputStream out = new FileOutputStream(file);
// First construct an index that allows us to quickly find the partitions that we want
JSONStringer stringer = (JSONStringer)(new JSONStringer().object());
int offset = 1;
for (Integer partition : sorted) {
stringer.key(Integer.toString(partition)).value(offset++);
} // FOR
out.write((stringer.endObject().toString() + "\n").getBytes());
// Now Loop through each file individually so that we only have to load one into memory at a time
for (Integer partition : sorted) {
File in = markovs.get(partition);
try {
JSONObject json_object = new JSONObject(FileUtil.readFile(in));
MarkovGraphsContainer markov = MarkovGraphContainersUtil.createMarkovGraphsContainer(json_object, procedures, catalog_db);
markov.load(in, catalog_db);
stringer = (JSONStringer)new JSONStringer().object();
stringer.key(partition.toString()).object();
markov.toJSON(stringer);
stringer.endObject().endObject();
out.write((stringer.toString() + "\n").getBytes());
} catch (Exception ex) {
throw new Exception(String.format("Failed to copy MarkovGraphsContainer for partition %d from '%s'", partition, in), ex);
}
} // FOR
out.close();
} catch (Exception ex) {
LOG.error("Failed to combine multiple MarkovGraphsContainers into file '" + output_path + "'", ex);
throw new RuntimeException(ex);
}
LOG.info(String.format("Combined %d MarkovGraphsContainers into file '%s'", markovs.size(), output_path));
}
/**
*
* @param json_object
* @param procedures
* @param catalog_db
* @return
* @throws JSONException
*/
public static MarkovGraphsContainer createMarkovGraphsContainer(JSONObject json_object, Collection<Procedure> procedures, Database catalog_db) throws JSONException {
// We should be able to get the classname of the container from JSON
String className = MarkovGraphsContainer.class.getCanonicalName();
if (json_object.has(MarkovGraphsContainer.Members.CLASSNAME.name())) {
className = json_object.getString(MarkovGraphsContainer.Members.CLASSNAME.name());
}
MarkovGraphsContainer markovs = ClassUtil.newInstance(className, new Object[]{procedures},
new Class<?>[]{Collection.class});
assert(markovs != null);
if (debug.get()) LOG.debug(String.format("Instantiated new %s object", markovs.getClass().getSimpleName()));
markovs.fromJSON(json_object, catalog_db);
return (markovs);
}
// ----------------------------------------------------------------------------
// SAVE TO FILE
// ----------------------------------------------------------------------------
/**
* For the given MarkovGraphContainer, serialize them out to a file
* @param markovs
* @param output_path
* @throws Exception
*/
public static void save(Map<Integer, ? extends MarkovGraphsContainer> markovs, String output_path) {
final String className = CollectionUtil.first(markovs.values()).getClass().getSimpleName();
// Sort the list of partitions so we always iterate over them in the same order
SortedSet<Integer> sorted = new TreeSet<Integer>(markovs.keySet());
int graphs_ctr = 0;
File file = new File(output_path);
try {
FileOutputStream out = new FileOutputStream(file);
// First construct an index that allows us to quickly find the partitions that we want
JSONStringer stringer = (JSONStringer)(new JSONStringer().object());
int offset = 1;
for (Integer partition : sorted) {
stringer.key(Integer.toString(partition)).value(offset++);
} // FOR
out.write((stringer.endObject().toString() + "\n").getBytes());
// Now roll through each id and create a single JSONObject on each line
for (Integer partition : sorted) {
MarkovGraphsContainer markov = markovs.get(partition);
assert(markov != null) : "Null MarkovGraphsContainer for partition #" + partition;
graphs_ctr += markov.totalSize();
stringer = (JSONStringer)new JSONStringer().object();
stringer.key(partition.toString()).object();
markov.toJSON(stringer);
stringer.endObject().endObject();
out.write((stringer.toString() + "\n").getBytes());
} // FOR
out.close();
} catch (Exception ex) {
LOG.error("Failed to serialize the " + className + " file '" + output_path + "'", ex);
throw new RuntimeException(ex);
}
LOG.info(String.format("Wrote out %d graphs in %s to '%s'", graphs_ctr, className, output_path));
}
// ----------------------------------------------------------------------------
// LOAD METHODS
// ----------------------------------------------------------------------------
public static Map<Integer, MarkovGraphsContainer> load(Database catalog_db, File input_path) throws Exception {
return (MarkovGraphContainersUtil.load(catalog_db, input_path, null, null));
}
public static Map<Integer, MarkovGraphsContainer> loadIds(Database catalog_db, File input_path, Collection<Integer> ids) throws Exception {
return (MarkovGraphContainersUtil.load(catalog_db, input_path, null, ids));
}
public static Map<Integer, MarkovGraphsContainer> loadProcedures(Database catalog_db, File input_path, Collection<Procedure> procedures) throws Exception {
return (MarkovGraphContainersUtil.load(catalog_db, input_path, procedures, null));
}
/**
*
* @param catalog_db
* @param input_path
* @param ids
* @return
* @throws Exception
*/
public static Map<Integer, MarkovGraphsContainer> load(final Database catalog_db, final File file, Collection<Procedure> procedures, Collection<Integer> ids) throws Exception {
final Map<Integer, MarkovGraphsContainer> ret = new HashMap<Integer, MarkovGraphsContainer>();
LOG.info(String.format("Loading in MarkovGraphContainers from '%s' [procedures=%s, ids=%s]",
file.getName(), (procedures == null ? "*ALL*" : CatalogUtil.debug(procedures)), (ids == null ? "*ALL*" : ids)));
try {
// File Format: One PartitionId per line, each with its own MarkovGraphsContainer
BufferedReader in = FileUtil.getReader(file);
// Line# -> Partition#
final Map<Integer, Integer> line_xref = new HashMap<Integer, Integer>();
int line_ctr = 0;
while (in.ready()) {
final String line = in.readLine();
// If this is the first line, then it is our index
if (line_ctr == 0) {
// Construct our line->partition mapping
JSONObject json_object = new JSONObject(line);
for (String key : CollectionUtil.iterable(json_object.keys())) {
Integer partition = Integer.valueOf(key);
// We want the MarkovGraphContainer pointed to by this line if
// (1) This partition is the same as our GLOBAL_MARKOV_CONTAINER_ID, which means that
// there isn't going to be partition-specific graphs. There should only be one entry
// in this file and we're always going to want to load it
// (2) They didn't pass us any ids, so we'll take everything we see
// (3) They did pass us ids, so check whether its included in the set
if (partition.equals(MarkovUtil.GLOBAL_MARKOV_CONTAINER_ID) || ids == null || ids.contains(partition)) {
Integer offset = json_object.getInt(key);
line_xref.put(offset, partition);
}
} // FOR
if (debug.get()) LOG.debug(String.format("Loading %d MarkovGraphsContainers", line_xref.size()));
// Otherwise check whether this is a line number that we care about
} else if (line_xref.containsKey(Integer.valueOf(line_ctr))) {
Integer partition = line_xref.remove(Integer.valueOf(line_ctr));
JSONObject json_object = new JSONObject(line).getJSONObject(partition.toString());
MarkovGraphsContainer markovs = createMarkovGraphsContainer(json_object, procedures, catalog_db);
if (debug.get()) LOG.debug(String.format("Storing %s for partition %d", markovs.getClass().getSimpleName(), partition));
ret.put(partition, markovs);
if (line_xref.isEmpty()) break;
}
line_ctr++;
} // WHILE
if (line_ctr == 0) throw new IOException("The MarkovGraphsContainer file '" + file + "' is empty");
} catch (Exception ex) {
LOG.error("Failed to deserialize the MarkovGraphsContainer from file '" + file + "'", ex);
throw new IOException(ex);
}
if (debug.get()) LOG.debug("The loading of the MarkovGraphsContainer is complete");
return (ret);
}
// ----------------------------------------------------------------------------
// UTILITY METHODS
// ----------------------------------------------------------------------------
/**
* Utility method to calculate the probabilities at all of the MarkovGraphsContainers
* @param markovs
*/
public static void calculateProbabilities(Map<Integer, ? extends MarkovGraphsContainer> markovs) {
if (debug.get()) LOG.debug(String.format("Calculating probabilities for %d ids", markovs.size()));
for (MarkovGraphsContainer m : markovs.values()) {
m.calculateProbabilities();
}
return;
}
/**
* Utility method
* @param markovs
* @param hasher
*/
public static void setHasher(Map<Integer, ? extends MarkovGraphsContainer> markovs, AbstractHasher hasher) {
if (debug.get()) LOG.debug(String.format("Setting hasher for for %d ids", markovs.size()));
for (MarkovGraphsContainer m : markovs.values()) {
m.setHasher(hasher);
}
return;
}
}
| true | true | public static <T extends MarkovGraphsContainer> Map<Integer, MarkovGraphsContainer> createMarkovGraphsContainers(final Database catalog_db, final Workload workload, final PartitionEstimator p_estimator, final Class<T> containerClass, final Map<Integer, MarkovGraphsContainer> markovs_map) throws Exception {
final String className = containerClass.getSimpleName();
final List<Runnable> runnables = new ArrayList<Runnable>();
final Set<Procedure> procedures = workload.getProcedures(catalog_db);
final Histogram<Procedure> proc_h = new Histogram<Procedure>();
final int num_transactions = workload.getTransactionCount();
final int marker = Math.max(1, (int)(num_transactions * 0.10));
final AtomicInteger finished_ctr = new AtomicInteger(0);
final AtomicInteger txn_ctr = new AtomicInteger(0);
final int num_threads = ThreadUtil.getMaxGlobalThreads();
final Constructor<T> constructor = ClassUtil.getConstructor(containerClass, new Class<?>[]{Collection.class});
final boolean is_global = containerClass.equals(GlobalMarkovGraphsContainer.class);
final List<Thread> processing_threads = new ArrayList<Thread>();
final LinkedBlockingDeque<Pair<Integer, TransactionTrace>> queues[] = (LinkedBlockingDeque<Pair<Integer, TransactionTrace>>[])new LinkedBlockingDeque<?>[num_threads];
for (int i = 0; i < num_threads; i++) {
queues[i] = new LinkedBlockingDeque<Pair<Integer, TransactionTrace>>();
} // FOR
// QUEUING THREAD
final AtomicBoolean queued_all = new AtomicBoolean(false);
runnables.add(new Runnable() {
@Override
public void run() {
List<TransactionTrace> all_txns = new ArrayList<TransactionTrace>(workload.getTransactions());
Collections.shuffle(all_txns);
int ctr = 0;
for (TransactionTrace txn_trace : all_txns) {
// Make sure it goes to the right base partition
Integer partition = null;
try {
partition = p_estimator.getBasePartition(txn_trace);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
assert(partition != null) : "Failed to get base partition for " + txn_trace + "\n" + txn_trace.debug(catalog_db);
queues[ctr % num_threads].add(Pair.of(partition, txn_trace));
if (++ctr % marker == 0) LOG.info(String.format("Queued %d/%d transactions", ctr, num_transactions));
} // FOR
queued_all.set(true);
// Poke all our threads just in case they finished
for (Thread t : processing_threads) t.interrupt();
}
});
// PROCESSING THREADS
for (int i = 0; i < num_threads; i++) {
final int thread_id = i;
runnables.add(new Runnable() {
@Override
public void run() {
Thread self = Thread.currentThread();
processing_threads.add(self);
MarkovGraphsContainer markovs = null;
Pair<Integer, TransactionTrace> pair = null;
while (true) {
try {
if (queued_all.get()) {
pair = queues[thread_id].poll();
} else {
pair = queues[thread_id].take();
// Steal work
if (pair == null) {
for (int i = 0; i < num_threads; i++) {
if (i == thread_id) continue;
pair = queues[i].take();
if (pair != null) break;
} // FOR
}
}
} catch (InterruptedException ex) {
continue;
}
if (pair == null) break;
int partition = pair.getFirst();
TransactionTrace txn_trace = pair.getSecond();
Procedure catalog_proc = txn_trace.getCatalogItem(catalog_db);
long txn_id = txn_trace.getTransactionId();
try {
int map_id = (is_global ? MarkovUtil.GLOBAL_MARKOV_CONTAINER_ID : partition);
Object params[] = txn_trace.getParams();
markovs = markovs_map.get(map_id);
if (markovs == null) {
synchronized (markovs_map) {
markovs = markovs_map.get(map_id);
if (markovs == null) {
markovs = constructor.newInstance(new Object[]{procedures});
markovs.setHasher(p_estimator.getHasher());
markovs_map.put(map_id, markovs);
}
} // SYNCH
}
MarkovGraph markov = markovs.getFromParams(txn_id, map_id, params, catalog_proc);
synchronized (markov) {
markov.processTransaction(txn_trace, p_estimator);
} // SYNCH
} catch (Exception ex) {
LOG.fatal("Failed to process " + txn_trace, ex);
throw new RuntimeException(ex);
}
proc_h.put(catalog_proc);
int global_ctr = txn_ctr.incrementAndGet();
if (debug.get() && global_ctr % marker == 0) {
LOG.debug(String.format("Processed %d/%d transactions",
global_ctr, num_transactions));
}
} // FOR
LOG.info(String.format("Processing thread finished creating %s [%d/%d]",
className, finished_ctr.incrementAndGet(), num_threads));
}
});
} // FOR
LOG.info(String.format("Generating %s for %d partitions using %d threads",
className, CatalogUtil.getNumberOfPartitions(catalog_db), num_threads));
ThreadUtil.runGlobalPool(runnables);
LOG.info("Procedure Histogram:\n" + proc_h);
MarkovGraphContainersUtil.calculateProbabilities(markovs_map);
return (markovs_map);
}
| public static <T extends MarkovGraphsContainer> Map<Integer, MarkovGraphsContainer> createMarkovGraphsContainers(final Database catalog_db, final Workload workload, final PartitionEstimator p_estimator, final Class<T> containerClass, final Map<Integer, MarkovGraphsContainer> markovs_map) throws Exception {
final String className = containerClass.getSimpleName();
final List<Runnable> runnables = new ArrayList<Runnable>();
final Set<Procedure> procedures = workload.getProcedures(catalog_db);
final Histogram<Procedure> proc_h = new Histogram<Procedure>();
final int num_transactions = workload.getTransactionCount();
final int marker = Math.max(1, (int)(num_transactions * 0.10));
final AtomicInteger finished_ctr = new AtomicInteger(0);
final AtomicInteger txn_ctr = new AtomicInteger(0);
final int num_threads = ThreadUtil.getMaxGlobalThreads();
final Constructor<T> constructor = ClassUtil.getConstructor(containerClass, new Class<?>[]{Collection.class});
final boolean is_global = containerClass.equals(GlobalMarkovGraphsContainer.class);
final List<Thread> processing_threads = new ArrayList<Thread>();
final LinkedBlockingDeque<Pair<Integer, TransactionTrace>> queues[] = (LinkedBlockingDeque<Pair<Integer, TransactionTrace>>[])new LinkedBlockingDeque<?>[num_threads];
for (int i = 0; i < num_threads; i++) {
queues[i] = new LinkedBlockingDeque<Pair<Integer, TransactionTrace>>();
} // FOR
// QUEUING THREAD
final AtomicBoolean queued_all = new AtomicBoolean(false);
runnables.add(new Runnable() {
@Override
public void run() {
List<TransactionTrace> all_txns = new ArrayList<TransactionTrace>(workload.getTransactions());
Collections.shuffle(all_txns);
int ctr = 0;
for (TransactionTrace txn_trace : all_txns) {
// Make sure it goes to the right base partition
Integer partition = null;
try {
partition = p_estimator.getBasePartition(txn_trace);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
assert(partition != null) : "Failed to get base partition for " + txn_trace + "\n" + txn_trace.debug(catalog_db);
queues[ctr % num_threads].add(Pair.of(partition, txn_trace));
if (++ctr % marker == 0) LOG.info(String.format("Queued %d/%d transactions", ctr, num_transactions));
} // FOR
queued_all.set(true);
// Poke all our threads just in case they finished
for (Thread t : processing_threads) {
if (t != null) t.interrupt();
} // FOR
}
});
// PROCESSING THREADS
for (int i = 0; i < num_threads; i++) {
final int thread_id = i;
runnables.add(new Runnable() {
@Override
public void run() {
Thread self = Thread.currentThread();
processing_threads.add(self);
MarkovGraphsContainer markovs = null;
Pair<Integer, TransactionTrace> pair = null;
while (true) {
try {
if (queued_all.get()) {
pair = queues[thread_id].poll();
} else {
pair = queues[thread_id].take();
// Steal work
if (pair == null) {
for (int i = 0; i < num_threads; i++) {
if (i == thread_id) continue;
pair = queues[i].take();
if (pair != null) break;
} // FOR
}
}
} catch (InterruptedException ex) {
continue;
}
if (pair == null) break;
int partition = pair.getFirst();
TransactionTrace txn_trace = pair.getSecond();
Procedure catalog_proc = txn_trace.getCatalogItem(catalog_db);
long txn_id = txn_trace.getTransactionId();
try {
int map_id = (is_global ? MarkovUtil.GLOBAL_MARKOV_CONTAINER_ID : partition);
Object params[] = txn_trace.getParams();
markovs = markovs_map.get(map_id);
if (markovs == null) {
synchronized (markovs_map) {
markovs = markovs_map.get(map_id);
if (markovs == null) {
markovs = constructor.newInstance(new Object[]{procedures});
markovs.setHasher(p_estimator.getHasher());
markovs_map.put(map_id, markovs);
}
} // SYNCH
}
MarkovGraph markov = markovs.getFromParams(txn_id, map_id, params, catalog_proc);
synchronized (markov) {
markov.processTransaction(txn_trace, p_estimator);
} // SYNCH
} catch (Exception ex) {
LOG.fatal("Failed to process " + txn_trace, ex);
throw new RuntimeException(ex);
}
proc_h.put(catalog_proc);
int global_ctr = txn_ctr.incrementAndGet();
if (debug.get() && global_ctr % marker == 0) {
LOG.debug(String.format("Processed %d/%d transactions",
global_ctr, num_transactions));
}
} // FOR
LOG.info(String.format("Processing thread finished creating %s [%d/%d]",
className, finished_ctr.incrementAndGet(), num_threads));
}
});
} // FOR
LOG.info(String.format("Generating %s for %d partitions using %d threads",
className, CatalogUtil.getNumberOfPartitions(catalog_db), num_threads));
ThreadUtil.runGlobalPool(runnables);
LOG.info("Procedure Histogram:\n" + proc_h);
MarkovGraphContainersUtil.calculateProbabilities(markovs_map);
return (markovs_map);
}
|
diff --git a/src/main/java/oneapi/client/impl/CustomerProfileClientImpl.java b/src/main/java/oneapi/client/impl/CustomerProfileClientImpl.java
index 9f70b47..43058b9 100644
--- a/src/main/java/oneapi/client/impl/CustomerProfileClientImpl.java
+++ b/src/main/java/oneapi/client/impl/CustomerProfileClientImpl.java
@@ -1,121 +1,121 @@
package oneapi.client.impl;
import java.util.ArrayList;
import java.util.List;
import oneapi.client.CustomerProfileClient;
import oneapi.config.Configuration;
import oneapi.listener.LoginListener;
import oneapi.listener.LogoutListener;
import oneapi.model.LoginRequest;
import oneapi.model.RequestData;
import oneapi.model.RequestData.Method;
import oneapi.model.common.AccountBalance;
import oneapi.model.common.CustomerProfile;
import oneapi.model.common.LoginResponse;
public class CustomerProfileClientImpl extends OneAPIBaseClientImpl implements CustomerProfileClient {
private static final String CUSTOMER_PROFILE_URL_BASE = "/customerProfile";
private List<LoginListener> loginListenersList = null;
private List<LogoutListener> logoutListenerList = null;
//*************************CustomerProfileClientImpl initialization***********************************************************************************************************************************************
public CustomerProfileClientImpl(Configuration configuration, LoginListener loginListner, LogoutListener logoutListener) {
super(configuration);
addLoginListener(loginListner);
addLogoutListener(logoutListener);
}
//*************************CustomerProfileClientImpl public***********************************************************************************************************************************************
@Override
public LoginResponse login() {
LoginRequest loginRequest = new LoginRequest(getConfiguration().getAuthentication().getUsername(), getConfiguration().getAuthentication().getPassword());
- RequestData requestData = new RequestData(CUSTOMER_PROFILE_URL_BASE + "/login", Method.POST, "login", loginRequest, URL_ENCODED_CONTENT_TYPE);
+ RequestData requestData = new RequestData(CUSTOMER_PROFILE_URL_BASE + "/login", Method.POST, "login", loginRequest, JSON_CONTENT_TYPE);
LoginResponse response = executeMethod(requestData, LoginResponse.class);
fireOnLogin(response);
return response;
}
@Override
public void logout() {
RequestData requestData = new RequestData(CUSTOMER_PROFILE_URL_BASE + "/logout", Method.POST);
executeMethod(requestData);
fireOnLogout();
}
@Override
public CustomerProfile getCustomerProfile() {
RequestData requestData = new RequestData(CUSTOMER_PROFILE_URL_BASE, Method.GET);
return executeMethod(requestData, CustomerProfile.class);
}
@Override
public CustomerProfile[] getCustomerProfiles() {
RequestData requestData = new RequestData(CUSTOMER_PROFILE_URL_BASE + "/list", Method.GET);
return executeMethod(requestData, CustomerProfile[].class);
}
@Override
public CustomerProfile getCustomerProfileByUserId(int id) {
StringBuilder urlBuilder = new StringBuilder(CUSTOMER_PROFILE_URL_BASE).append("/");
urlBuilder.append(encodeURLParam(String.valueOf(id)));
RequestData requestData = new RequestData(urlBuilder.toString(), Method.GET);
return executeMethod(requestData, CustomerProfile.class);
}
@Override
public AccountBalance getAccountBalance()
{
RequestData requestData = new RequestData(CUSTOMER_PROFILE_URL_BASE + "/balance", Method.GET);
return executeMethod(requestData, AccountBalance.class);
}
//*************************CustomerProfileClientImpl private******************************************************************************************************************************************************
/**
* Add OneAPI Login listener
* @param listener - (new LoginListener)
*/
private void addLoginListener(LoginListener listener) {
if (listener == null) return;
if (this.loginListenersList == null) {
this.loginListenersList = new ArrayList<LoginListener>();
}
this.loginListenersList.add(listener);
}
/**
* Add OneAPI Logout listener
* @param listener - (new LogoutListener)
*/
private void addLogoutListener(LogoutListener listener) {
if (listener == null) return;
if (this.logoutListenerList == null) {
this.logoutListenerList = new ArrayList<LogoutListener>();
}
this.logoutListenerList.add(listener);
}
/**
* Fire on Login done
* @param response
*/
private void fireOnLogin(LoginResponse response) {
if (loginListenersList != null) {
for (LoginListener listener : loginListenersList) {
listener.onLogin(response);
}
}
}
/**
* Fire on Logout done
*/
private void fireOnLogout() {
if (logoutListenerList != null) {
for (LogoutListener listener : logoutListenerList) {
listener.onLogout();
}
}
}
}
| true | true | public LoginResponse login() {
LoginRequest loginRequest = new LoginRequest(getConfiguration().getAuthentication().getUsername(), getConfiguration().getAuthentication().getPassword());
RequestData requestData = new RequestData(CUSTOMER_PROFILE_URL_BASE + "/login", Method.POST, "login", loginRequest, URL_ENCODED_CONTENT_TYPE);
LoginResponse response = executeMethod(requestData, LoginResponse.class);
fireOnLogin(response);
return response;
}
| public LoginResponse login() {
LoginRequest loginRequest = new LoginRequest(getConfiguration().getAuthentication().getUsername(), getConfiguration().getAuthentication().getPassword());
RequestData requestData = new RequestData(CUSTOMER_PROFILE_URL_BASE + "/login", Method.POST, "login", loginRequest, JSON_CONTENT_TYPE);
LoginResponse response = executeMethod(requestData, LoginResponse.class);
fireOnLogin(response);
return response;
}
|
diff --git a/Server/CustomProtocol.java b/Server/CustomProtocol.java
index bec943e..3c4a693 100644
--- a/Server/CustomProtocol.java
+++ b/Server/CustomProtocol.java
@@ -1,94 +1,94 @@
import java.io.*;
import java.lang.*;
import java.util.Scanner;
public class CustomProtocol{
String usage = "\n\t\tChatter Server Help Menu\nAccepted Inputs:\n\t<exit/quit/:q>: This will disconnect you from the server.\n\t<help>: Brings up the help menu.\n\t<connection>: Returns the address that you are connected to.";
static ChatterServerMain server = new ChatterServerMain();
public String processInput(String input){
if(input==null){
return "Hello, you are chattin with chatter!";
}
if(input.equals("hello")){
return "Hello there!";
}
if(input.equals("who are you")){
return "I am the chatter server. \n You can send me commands and I will respond.";
}
if(input.matches("read number [\\d]+")){
input = input.replaceAll("[^\\d]","");//replaces any non-numeric characters with nothing leaving only the number
System.out.println(input);
try{
int i=Integer.parseInt(input);
return "The number you entered was " + i + ".";
}catch(Exception e){
return "Invalid parse: " + input;
}
}
/*
* Checking or changin the status of the lights
* Possible make these into some sort of method for easy modding?
*
*/
- if(input.matches("[^\t\n]*(l|Li|Ig|Gh|Ht|T)[^\n\t]*")) {
+ if(input.matches("[^\t\n]*(light)[^\n\t]*")) {
System.out.println("Something about lights?");
//THe user refrenced lights
- if(input.matches("[^\n\t]*(a|Ar|Re|E)[^\n\t]*")) {
+ if(input.matches("[^\n\t]*(are)[^\n\t]*")) {
//Are the lights on or off?
System.out.println("Asking about?");
- if(input.matches("[^\n\t]*(o|On|N)[^\n\t]*")) {
+ if(input.matches("[^\n\t]*(on)[^\n\t]*")) {
return "I'm not sure really...";
- }else if (input.matches("[^\t\n]*(o|Of|Ff|F)[^\n\t]*")) {
+ }else if (input.matches("[^\t\n]*(off)[^\n\t]*")) {
return "Can't say.";
}
- }else if (input.matches("[^\t\n]*(t|Tu|Ur|Rn|N)[^\n\t]*")) {
+ }else if (input.matches("[^\t\n]*(turn)[^\n\t]*")) {
//turn the lights on
System.out.println("changing the lights about?");
- if(input.matches("[^\n\t]*(o|On|N)[^\n\t]*")) {
+ if(input.matches("[^\n\t]*(on)[^\n\t]*")) {
return "I'm turning the lights ON!";
- }else if (input.matches("[^\t\n]*(o|Of|Ff|F)[^\n\t]*")) {
+ }else if (input.matches("[^\t\n]*(of)[^\n\t]*")) {
return "I'm turning the lights OFF!";
}
}else {
//you mentioned the lights but waht about them?
}
}
if(input.equals("exit") || input.equals("quit") || input.equals(":q")){
return("Goodbye.");
}
if(input.equals("help")) {
return usage;
}
if(input.equals("connection")) {
return server.theToString();
}
return "Did not understand the command.";
}
public static void main(String args[]) {
//ChatterServerMain server = new ChatterServerMain();
try {
int port = 4444;
System.out.print("Run Server on port: ");
Scanner in = new Scanner(System.in);
port = in.nextInt();
server.startServer(port);
}catch (Exception e) {
System.out.print(e);
}
}
}
| false | true | public String processInput(String input){
if(input==null){
return "Hello, you are chattin with chatter!";
}
if(input.equals("hello")){
return "Hello there!";
}
if(input.equals("who are you")){
return "I am the chatter server. \n You can send me commands and I will respond.";
}
if(input.matches("read number [\\d]+")){
input = input.replaceAll("[^\\d]","");//replaces any non-numeric characters with nothing leaving only the number
System.out.println(input);
try{
int i=Integer.parseInt(input);
return "The number you entered was " + i + ".";
}catch(Exception e){
return "Invalid parse: " + input;
}
}
/*
* Checking or changin the status of the lights
* Possible make these into some sort of method for easy modding?
*
*/
if(input.matches("[^\t\n]*(l|Li|Ig|Gh|Ht|T)[^\n\t]*")) {
System.out.println("Something about lights?");
//THe user refrenced lights
if(input.matches("[^\n\t]*(a|Ar|Re|E)[^\n\t]*")) {
//Are the lights on or off?
System.out.println("Asking about?");
if(input.matches("[^\n\t]*(o|On|N)[^\n\t]*")) {
return "I'm not sure really...";
}else if (input.matches("[^\t\n]*(o|Of|Ff|F)[^\n\t]*")) {
return "Can't say.";
}
}else if (input.matches("[^\t\n]*(t|Tu|Ur|Rn|N)[^\n\t]*")) {
//turn the lights on
System.out.println("changing the lights about?");
if(input.matches("[^\n\t]*(o|On|N)[^\n\t]*")) {
return "I'm turning the lights ON!";
}else if (input.matches("[^\t\n]*(o|Of|Ff|F)[^\n\t]*")) {
return "I'm turning the lights OFF!";
}
}else {
//you mentioned the lights but waht about them?
}
}
if(input.equals("exit") || input.equals("quit") || input.equals(":q")){
return("Goodbye.");
}
if(input.equals("help")) {
return usage;
}
if(input.equals("connection")) {
return server.theToString();
}
return "Did not understand the command.";
}
| public String processInput(String input){
if(input==null){
return "Hello, you are chattin with chatter!";
}
if(input.equals("hello")){
return "Hello there!";
}
if(input.equals("who are you")){
return "I am the chatter server. \n You can send me commands and I will respond.";
}
if(input.matches("read number [\\d]+")){
input = input.replaceAll("[^\\d]","");//replaces any non-numeric characters with nothing leaving only the number
System.out.println(input);
try{
int i=Integer.parseInt(input);
return "The number you entered was " + i + ".";
}catch(Exception e){
return "Invalid parse: " + input;
}
}
/*
* Checking or changin the status of the lights
* Possible make these into some sort of method for easy modding?
*
*/
if(input.matches("[^\t\n]*(light)[^\n\t]*")) {
System.out.println("Something about lights?");
//THe user refrenced lights
if(input.matches("[^\n\t]*(are)[^\n\t]*")) {
//Are the lights on or off?
System.out.println("Asking about?");
if(input.matches("[^\n\t]*(on)[^\n\t]*")) {
return "I'm not sure really...";
}else if (input.matches("[^\t\n]*(off)[^\n\t]*")) {
return "Can't say.";
}
}else if (input.matches("[^\t\n]*(turn)[^\n\t]*")) {
//turn the lights on
System.out.println("changing the lights about?");
if(input.matches("[^\n\t]*(on)[^\n\t]*")) {
return "I'm turning the lights ON!";
}else if (input.matches("[^\t\n]*(of)[^\n\t]*")) {
return "I'm turning the lights OFF!";
}
}else {
//you mentioned the lights but waht about them?
}
}
if(input.equals("exit") || input.equals("quit") || input.equals(":q")){
return("Goodbye.");
}
if(input.equals("help")) {
return usage;
}
if(input.equals("connection")) {
return server.theToString();
}
return "Did not understand the command.";
}
|
diff --git a/modules/org.restlet/src/org/restlet/util/Template.java b/modules/org.restlet/src/org/restlet/util/Template.java
index de0e7e6f9..0151097b8 100644
--- a/modules/org.restlet/src/org/restlet/util/Template.java
+++ b/modules/org.restlet/src/org/restlet/util/Template.java
@@ -1,867 +1,867 @@
/**
* Copyright 2005-2009 Noelios Technologies.
*
* The contents of this file are subject to the terms of the following open
* source licenses: LGPL 3.0 or LGPL 2.1 or CDDL 1.0 (the "Licenses"). You can
* select the license that you prefer but you may not use this file except in
* compliance with one of these Licenses.
*
* You can obtain a copy of the LGPL 3.0 license at
* http://www.gnu.org/licenses/lgpl-3.0.html
*
* You can obtain a copy of the LGPL 2.1 license at
* http://www.gnu.org/licenses/lgpl-2.1.html
*
* You can obtain a copy of the CDDL 1.0 license at
* http://www.sun.com/cddl/cddl.html
*
* See the Licenses for the specific language governing permissions and
* limitations under the Licenses.
*
* Alternatively, you can obtain a royalty free commercial license with less
* limitations, transferable or non-transferable, directly at
* http://www.noelios.com/products/restlet-engine
*
* Restlet is a registered trademark of Noelios Technologies.
*/
package org.restlet.util;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.restlet.data.Reference;
import org.restlet.data.Request;
import org.restlet.data.Response;
/**
* String template with a pluggable model. Supports both formatting and parsing.
* The template variables can be inserted using the "{name}" syntax and
* described using the modifiable map of variable descriptors. When no
* descriptor is found for a given variable, the template logic uses its default
* variable property initialized using the default {@link Variable} constructor.<br>
* <br>
* Note that the variable descriptors can be changed before the first parsing or
* matching call. After that point, changes won't be taken into account.<br>
* <br>
* Format and parsing methods are specially available to deal with requests and
* response. See {@link #format(Request, Response)} and
* {@link #parse(String, Request)}.
*
* @see Resolver
* @see <a href="http://bitworking.org/projects/URI-Templates/">URI Template specification</a>
* @author Jerome Louvel
*/
public class Template {
public static final int MODE_EQUALS = 2;
public static final int MODE_STARTS_WITH = 1;
/**
* Appends to a pattern a repeating group of a given content based on a
* class of characters.
*
* @param pattern
* The pattern to append to.
* @param content
* The content of the group.
* @param required
* Indicates if the group is required.
*/
private static void appendClass(StringBuilder pattern, String content,
boolean required) {
pattern.append("(");
if (content.equals(".")) {
// Special case for the TYPE_ALL variable type because the
// dot looses its meaning inside a character class
pattern.append(content);
} else {
pattern.append("[").append(content).append(']');
}
if (required) {
pattern.append("+");
} else {
pattern.append("*");
}
pattern.append(")");
}
/**
* Appends to a pattern a repeating group of a given content based on a
* non-capturing group.
*
* @param pattern
* The pattern to append to.
* @param content
* The content of the group.
* @param required
* Indicates if the group is required.
*/
private static void appendGroup(StringBuilder pattern, String content,
boolean required) {
pattern.append("((?:").append(content).append(')');
if (required) {
pattern.append("+");
} else {
pattern.append("*");
}
pattern.append(")");
}
/**
* Returns the Regex pattern string corresponding to a variable.
*
* @param variable
* The variable.
* @return The Regex pattern string corresponding to a variable.
*/
private static String getVariableRegex(Variable variable) {
String result = null;
if (variable.isFixed()) {
- result = Pattern.quote(variable.getDefaultValue());
+ result = "(" + Pattern.quote(variable.getDefaultValue()) + ")";
} else {
// Expressions to create character classes
final String ALL = ".";
final String ALPHA = "a-zA-Z";
final String DIGIT = "0-9";
final String ALPHA_DIGIT = ALPHA + DIGIT;
final String HEXA = DIGIT + "ABCDEFabcdef";
final String URI_UNRESERVED = ALPHA_DIGIT + "\\-\\.\\_\\~";
final String URI_GEN_DELIMS = "\\:\\/\\?\\#\\[\\]\\@";
final String URI_SUB_DELIMS = "\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=";
final String URI_RESERVED = URI_GEN_DELIMS + URI_SUB_DELIMS;
final String WORD = "\\w";
// Basic rules expressed by the HTTP rfc.
final String CRLF = "\\r\\n";
final String CTL = "\\p{Cntrl}";
final String LWS = CRLF + "\\ \\t";
final String SEPARATOR = "\\(\\)\\<\\>\\@\\,\\;\\:\\[\\]\"\\/\\\\?\\=\\{\\}\\ \\t";
final String TOKEN = "[^" + SEPARATOR + "]";
final String COMMENT = "[^" + CTL + "]" + "[^\\(\\)]" + LWS;
final String COMMENT_ATTRIBUTE = "[^\\;\\(\\)]";
// Expressions to create non-capturing groups
final String PCT_ENCODED = "\\%[" + HEXA + "][" + HEXA + "]";
// final String PCHAR = "[" + URI_UNRESERVED + "]|(?:" + PCT_ENCODED
// + ")|[" + URI_SUB_DELIMS + "]|\\:|\\@";
final String PCHAR = "[" + URI_UNRESERVED + URI_SUB_DELIMS
+ "\\:\\@]|(?:" + PCT_ENCODED + ")";
final String QUERY = PCHAR + "|\\/|\\?";
final String FRAGMENT = QUERY;
final String URI_PATH = PCHAR + "|\\/";
final String URI_ALL = "[" + URI_RESERVED + URI_UNRESERVED
+ "]|(?:" + PCT_ENCODED + ")";
final StringBuilder coreRegex = new StringBuilder();
switch (variable.getType()) {
case Variable.TYPE_ALL:
appendClass(coreRegex, ALL, variable.isRequired());
break;
case Variable.TYPE_ALPHA:
appendClass(coreRegex, ALPHA, variable.isRequired());
break;
case Variable.TYPE_DIGIT:
appendClass(coreRegex, DIGIT, variable.isRequired());
break;
case Variable.TYPE_ALPHA_DIGIT:
appendClass(coreRegex, ALPHA_DIGIT, variable.isRequired());
break;
case Variable.TYPE_URI_ALL:
appendGroup(coreRegex, URI_ALL, variable.isRequired());
break;
case Variable.TYPE_URI_UNRESERVED:
appendClass(coreRegex, URI_UNRESERVED, variable.isRequired());
break;
case Variable.TYPE_WORD:
appendClass(coreRegex, WORD, variable.isRequired());
break;
case Variable.TYPE_URI_FRAGMENT:
appendGroup(coreRegex, FRAGMENT, variable.isRequired());
break;
case Variable.TYPE_URI_PATH:
appendGroup(coreRegex, URI_PATH, variable.isRequired());
break;
case Variable.TYPE_URI_QUERY:
appendGroup(coreRegex, QUERY, variable.isRequired());
break;
case Variable.TYPE_URI_SEGMENT:
appendGroup(coreRegex, PCHAR, variable.isRequired());
break;
case Variable.TYPE_TOKEN:
appendClass(coreRegex, TOKEN, variable.isRequired());
break;
case Variable.TYPE_COMMENT:
appendClass(coreRegex, COMMENT, variable.isRequired());
break;
case Variable.TYPE_COMMENT_ATTRIBUTE:
appendClass(coreRegex, COMMENT_ATTRIBUTE, variable.isRequired());
break;
}
result = coreRegex.toString();
}
return result;
}
/** The default variable to use when no matching variable descriptor exists. */
private volatile Variable defaultVariable;
/** True if the variables must be encoded when formatting the template. */
private volatile boolean encodeVariables;
/** The logger to use. */
private volatile Logger logger;
/** The matching mode to use when parsing a formatted reference. */
private volatile int matchingMode;
/** The pattern to use for formatting or parsing. */
private volatile String pattern;
/** The internal Regex pattern. */
private volatile Pattern regexPattern;
/** The sequence of Regex variable names as found in the pattern string. */
private volatile List<String> regexVariables;
/** The map of variables associated to the route's template. */
private final Map<String, Variable> variables;
/**
* Constructor.
*
* @param pattern
* The pattern to use for formatting or parsing.
* @param matchingMode
* The matching mode to use when parsing a formatted reference.
* @param defaultType
* The default type of variables with no descriptor.
* @param defaultDefaultValue
* The default value for null variables with no descriptor.
* @param defaultRequired
* The default required flag for variables with no descriptor.
* @param defaultFixed
* The default fixed value for variables with no descriptor.
* @param encodeVariables
* True if the variables must be encoded when formatting the
* template.
*/
public Template(String pattern, int matchingMode,
int defaultType, String defaultDefaultValue,
boolean defaultRequired, boolean defaultFixed,
boolean encodeVariables) {
this.logger = (logger == null) ? Logger.getLogger(getClass()
.getCanonicalName()) : logger;
this.pattern = pattern;
this.defaultVariable = new Variable(defaultType, defaultDefaultValue,
defaultRequired, defaultFixed);
this.matchingMode = matchingMode;
this.variables = new ConcurrentHashMap<String, Variable>();
this.regexPattern = null;
this.encodeVariables = encodeVariables;
}
/**
* Default constructor. Each variable matches any sequence of characters by
* default. When parsing, the template will attempt to match the whole
* template. When formatting, the variable are replaced by an empty string
* if they don't exist in the model.
*
* @param pattern
* The pattern to use for formatting or parsing.
*/
public Template(String pattern) {
this(pattern, MODE_EQUALS, Variable.TYPE_ALL, "", true, false);
}
/**
* Constructor.
*
* @param pattern
* The pattern to use for formatting or parsing.
* @param matchingMode
* The matching mode to use when parsing a formatted reference.
*/
public Template(String pattern, int matchingMode) {
this(pattern, matchingMode, Variable.TYPE_ALL, "", true, false);
}
/**
* Constructor.
*
* @param pattern
* The pattern to use for formatting or parsing.
* @param matchingMode
* The matching mode to use when parsing a formatted reference.
* @param defaultType
* The default type of variables with no descriptor.
* @param defaultDefaultValue
* The default value for null variables with no descriptor.
* @param defaultRequired
* The default required flag for variables with no descriptor.
* @param defaultFixed
* The default fixed value for variables with no descriptor.
*/
public Template(String pattern, int matchingMode, int defaultType,
String defaultDefaultValue, boolean defaultRequired,
boolean defaultFixed) {
this(pattern, matchingMode, defaultType, defaultDefaultValue,
defaultRequired, defaultFixed, false);
}
/**
* Creates a formatted string based on the given map of values.
*
* @param values
* The values to use when formatting.
* @return The formatted string.
* @see Resolver#createResolver(Map)
*/
public String format(Map<String, ?> values) {
return format(Resolver.createResolver(values));
}
/**
* Creates a formatted string based on the given request and response.
*
* @param request
* The request to use as a model.
* @param response
* The response to use as a model.
* @return The formatted string.
* @see Resolver#createResolver(Request, Response)
*/
public String format(Request request, Response response) {
return format(Resolver.createResolver(request, response));
}
/**
* Creates a formatted string based on the given variable resolver.
*
* @param resolver
* The variable resolver to use.
* @return The formatted string.
*/
public String format(Resolver<String> resolver) {
final StringBuilder result = new StringBuilder();
StringBuilder varBuffer = null;
char next;
boolean inVariable = false;
final int patternLength = getPattern().length();
for (int i = 0; i < patternLength; i++) {
next = getPattern().charAt(i);
if (inVariable) {
if (Reference.isUnreserved(next)) {
// Append to the variable name
varBuffer.append(next);
} else if (next == '}') {
// End of variable detected
if (varBuffer.length() == 0) {
getLogger().warning(
"Empty pattern variables are not allowed : "
+ this.regexPattern);
} else {
final String varName = varBuffer.toString();
String varValue = resolver.resolve(varName);
Variable var = getVariables().get(varName);
// Use the default values instead
if (varValue == null) {
if (var == null) {
var = getDefaultVariable();
}
if (var != null) {
varValue = var.getDefaultValue();
}
}
if (this.encodeVariables) {
// In case the values must be encoded.
if (var != null) {
result.append(var.encode(varValue));
} else {
result.append(Reference.encode(varValue));
}
} else {
if ((var != null) && var.isEncodedOnFormat()) {
result.append(Reference.encode(varValue));
} else {
result.append(varValue);
}
}
// Reset the variable name buffer
varBuffer = new StringBuilder();
}
inVariable = false;
} else {
getLogger().warning(
"An invalid character was detected inside a pattern variable : "
+ this.regexPattern);
}
} else {
if (next == '{') {
inVariable = true;
varBuffer = new StringBuilder();
} else if (next == '}') {
getLogger().warning(
"An invalid character was detected inside a pattern variable : "
+ this.regexPattern);
} else {
result.append(next);
}
}
}
return result.toString();
}
/**
* Returns the default variable.
*
* @return The default variable.
*/
public Variable getDefaultVariable() {
return this.defaultVariable;
}
/**
* Returns the logger to use.
*
* @return The logger to use.
*/
public Logger getLogger() {
return this.logger;
}
/**
* Returns the matching mode to use when parsing a formatted reference.
*
* @return The matching mode to use when parsing a formatted reference.
*/
public int getMatchingMode() {
return this.matchingMode;
}
/**
* Returns the pattern to use for formatting or parsing.
*
* @return The pattern to use for formatting or parsing.
*/
public String getPattern() {
return this.pattern;
}
/**
* Compiles the URI pattern into a Regex pattern.
*
* @return The Regex pattern.
*/
private Pattern getRegexPattern() {
if (this.regexPattern == null) {
synchronized (this) {
if (this.regexPattern == null) {
final StringBuilder patternBuffer = new StringBuilder();
StringBuilder varBuffer = null;
char next;
boolean inVariable = false;
for (int i = 0; i < getPattern().length(); i++) {
next = getPattern().charAt(i);
if (inVariable) {
if (Reference.isUnreserved(next)) {
// Append to the variable name
varBuffer.append(next);
} else if (next == '}') {
// End of variable detected
if (varBuffer.length() == 0) {
getLogger().warning(
"Empty pattern variables are not allowed : "
+ this.regexPattern);
} else {
final String varName = varBuffer.toString();
final int varIndex = getRegexVariables()
.indexOf(varName);
if (varIndex != -1) {
// The variable is used several times in
// the pattern, ensure that this
// constraint is enforced when parsing.
patternBuffer.append("\\"
+ (varIndex + 1));
} else {
// New variable detected. Insert a
// capturing group.
getRegexVariables().add(varName);
Variable var = getVariables().get(
varName);
if (var == null) {
var = getDefaultVariable();
}
patternBuffer
.append(getVariableRegex(var));
}
// Reset the variable name buffer
varBuffer = new StringBuilder();
}
inVariable = false;
} else {
getLogger().warning(
"An invalid character was detected inside a pattern variable : "
+ this.regexPattern);
}
} else {
if (next == '{') {
inVariable = true;
varBuffer = new StringBuilder();
} else if (next == '}') {
getLogger().warning(
"An invalid character was detected inside a pattern variable : "
+ this.regexPattern);
} else {
patternBuffer.append(quote(next));
}
}
}
this.regexPattern = Pattern.compile(patternBuffer
.toString());
}
}
}
return this.regexPattern;
}
/**
* Returns the sequence of Regex variable names as found in the pattern
* string.
*
* @return The sequence of Regex variable names as found in the pattern
* string.
*/
private List<String> getRegexVariables() {
// Lazy initialization with double-check.
List<String> rv = this.regexVariables;
if (rv == null) {
synchronized (this) {
rv = this.regexVariables;
if (rv == null) {
this.regexVariables = rv = new CopyOnWriteArrayList<String>();
}
}
}
return rv;
}
/**
* Returns the list of variable names in the template.
*
* @return The list of variable names.
*/
public List<String> getVariableNames() {
final List<String> result = new ArrayList<String>();
StringBuilder varBuffer = null;
char next;
boolean inVariable = false;
final String pattern = getPattern();
for (int i = 0; i < pattern.length(); i++) {
next = pattern.charAt(i);
if (inVariable) {
if (Reference.isUnreserved(next)) {
// Append to the variable name
varBuffer.append(next);
} else if (next == '}') {
// End of variable detected
if (varBuffer.length() == 0) {
getLogger().warning(
"Empty pattern variables are not allowed : "
+ this.pattern);
} else {
result.add(varBuffer.toString());
// Reset the variable name buffer
varBuffer = new StringBuilder();
}
inVariable = false;
} else {
getLogger().warning(
"An invalid character was detected inside a pattern variable : "
+ this.pattern);
}
} else {
if (next == '{') {
inVariable = true;
varBuffer = new StringBuilder();
} else if (next == '}') {
getLogger().warning(
"An invalid character was detected inside a pattern variable : "
+ this.pattern);
}
}
}
return result;
}
/**
* Returns the modifiable map of variable descriptors. Creates a new
* instance if no one has been set. Note that those variables are only
* descriptors that can influence the way parsing and formatting is done,
* they don't contain the actual value parsed.
*
* @return The modifiable map of variables.
*/
public synchronized Map<String, Variable> getVariables() {
return this.variables;
}
/**
* Indicates if the variables must be encoded when formatting the template.
*
* @return True if the variables must be encoded when formatting the
* template, false otherwise.
*/
public boolean isEncodeVariables() {
return this.encodeVariables;
}
/**
* Indicates if the current pattern matches the given formatted string.
*
* @param formattedString
* The formatted string to match.
* @return The number of matched characters or -1 if the match failed.
*/
public int match(String formattedString) {
int result = -1;
try {
if (formattedString != null) {
final Matcher matcher = getRegexPattern().matcher(
formattedString);
if ((getMatchingMode() == MODE_EQUALS) && matcher.matches()) {
result = matcher.end();
} else if ((getMatchingMode() == MODE_STARTS_WITH)
&& matcher.lookingAt()) {
result = matcher.end();
}
}
} catch (StackOverflowError soe) {
getLogger().warning(
"StackOverflowError exception encountered while matching this string : "
+ formattedString);
}
return result;
}
/**
* Attempts to parse a formatted reference. If the parsing succeeds, the
* given request's attributes are updated.<br>
* Note that the values parsed are directly extracted from the formatted
* reference and are therefore not percent-decoded.
*
* @see Reference#decode(String)
*
* @param formattedString
* The string to parse.
* @param variables
* The map of variables to update.
* @return The number of matched characters or -1 if no character matched.
*/
public int parse(String formattedString, Map<String, Object> variables) {
int result = -1;
if (formattedString != null) {
try {
final Matcher matcher = getRegexPattern().matcher(
formattedString);
final boolean matched = ((getMatchingMode() == MODE_EQUALS) && matcher
.matches())
|| ((getMatchingMode() == MODE_STARTS_WITH) && matcher
.lookingAt());
if (matched) {
// Update the number of matched characters
result = matcher.end();
// Update the attributes with the variables value
String attributeName = null;
String attributeValue = null;
for (int i = 0; i < getRegexVariables().size(); i++) {
attributeName = getRegexVariables().get(i);
attributeValue = matcher.group(i + 1);
final Variable var = getVariables().get(attributeName);
if ((var != null) && var.isDecodedOnParse()) {
variables.put(attributeName, Reference
.decode(attributeValue));
} else {
variables.put(attributeName, attributeValue);
}
}
}
} catch (StackOverflowError soe) {
getLogger().warning(
"StackOverflowError exception encountered while matching this string : "
+ formattedString);
}
}
return result;
}
/**
* Attempts to parse a formatted reference. If the parsing succeeds, the
* given request's attributes are updated.<br>
* Note that the values parsed are directly extracted from the formatted
* reference and are therefore not percent-decoded.
*
* @see Reference#decode(String)
*
* @param formattedString
* The string to parse.
* @param request
* The request to update.
* @return The number of matched characters or -1 if no character matched.
*/
public int parse(String formattedString, Request request) {
return parse(formattedString, request.getAttributes());
}
/**
* Quotes special characters that could be taken for special Regex
* characters.
*
* @param character
* The character to quote if necessary.
* @return The quoted character.
*/
private String quote(char character) {
switch (character) {
case '[':
return "\\[";
case ']':
return "\\]";
case '.':
return "\\.";
case '\\':
return "\\\\";
case '$':
return "\\$";
case '^':
return "\\^";
case '?':
return "\\?";
case '*':
return "\\*";
case '|':
return "\\|";
case '(':
return "\\(";
case ')':
return "\\)";
case ':':
return "\\:";
case '-':
return "\\-";
case '!':
return "\\!";
case '<':
return "\\<";
case '>':
return "\\>";
default:
return Character.toString(character);
}
}
/**
* Sets the variable to use, if no variable is given.
*
* @param defaultVariable
*/
public void setDefaultVariable(Variable defaultVariable) {
this.defaultVariable = defaultVariable;
}
/**
* Indicates if the variables must be encoded when formatting the template.
*
* @param encodeVariables
* True if the variables must be encoded when formatting the
* template.
*/
public void setEncodeVariables(boolean encodeVariables) {
this.encodeVariables = encodeVariables;
}
/**
* Sets the logger to use.
*
* @param logger
* The logger to use.
*/
public void setLogger(Logger logger) {
this.logger = logger;
}
/**
* Sets the matching mode to use when parsing a formatted reference.
*
* @param matchingMode
* The matching mode to use when parsing a formatted reference.
*/
public void setMatchingMode(int matchingMode) {
this.matchingMode = matchingMode;
}
/**
* Sets the pattern to use for formatting or parsing.
*
* @param pattern
* The pattern to use for formatting or parsing.
*/
public void setPattern(String pattern) {
this.pattern = pattern;
}
/**
* Sets the modifiable map of variables.
*
* @param variables
* The modifiable map of variables.
*/
public synchronized void setVariables(Map<String, Variable> variables) {
this.variables.clear();
this.variables.putAll(variables);
}
}
| true | true | private static String getVariableRegex(Variable variable) {
String result = null;
if (variable.isFixed()) {
result = Pattern.quote(variable.getDefaultValue());
} else {
// Expressions to create character classes
final String ALL = ".";
final String ALPHA = "a-zA-Z";
final String DIGIT = "0-9";
final String ALPHA_DIGIT = ALPHA + DIGIT;
final String HEXA = DIGIT + "ABCDEFabcdef";
final String URI_UNRESERVED = ALPHA_DIGIT + "\\-\\.\\_\\~";
final String URI_GEN_DELIMS = "\\:\\/\\?\\#\\[\\]\\@";
final String URI_SUB_DELIMS = "\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=";
final String URI_RESERVED = URI_GEN_DELIMS + URI_SUB_DELIMS;
final String WORD = "\\w";
// Basic rules expressed by the HTTP rfc.
final String CRLF = "\\r\\n";
final String CTL = "\\p{Cntrl}";
final String LWS = CRLF + "\\ \\t";
final String SEPARATOR = "\\(\\)\\<\\>\\@\\,\\;\\:\\[\\]\"\\/\\\\?\\=\\{\\}\\ \\t";
final String TOKEN = "[^" + SEPARATOR + "]";
final String COMMENT = "[^" + CTL + "]" + "[^\\(\\)]" + LWS;
final String COMMENT_ATTRIBUTE = "[^\\;\\(\\)]";
// Expressions to create non-capturing groups
final String PCT_ENCODED = "\\%[" + HEXA + "][" + HEXA + "]";
// final String PCHAR = "[" + URI_UNRESERVED + "]|(?:" + PCT_ENCODED
// + ")|[" + URI_SUB_DELIMS + "]|\\:|\\@";
final String PCHAR = "[" + URI_UNRESERVED + URI_SUB_DELIMS
+ "\\:\\@]|(?:" + PCT_ENCODED + ")";
final String QUERY = PCHAR + "|\\/|\\?";
final String FRAGMENT = QUERY;
final String URI_PATH = PCHAR + "|\\/";
final String URI_ALL = "[" + URI_RESERVED + URI_UNRESERVED
+ "]|(?:" + PCT_ENCODED + ")";
final StringBuilder coreRegex = new StringBuilder();
switch (variable.getType()) {
case Variable.TYPE_ALL:
appendClass(coreRegex, ALL, variable.isRequired());
break;
case Variable.TYPE_ALPHA:
appendClass(coreRegex, ALPHA, variable.isRequired());
break;
case Variable.TYPE_DIGIT:
appendClass(coreRegex, DIGIT, variable.isRequired());
break;
case Variable.TYPE_ALPHA_DIGIT:
appendClass(coreRegex, ALPHA_DIGIT, variable.isRequired());
break;
case Variable.TYPE_URI_ALL:
appendGroup(coreRegex, URI_ALL, variable.isRequired());
break;
case Variable.TYPE_URI_UNRESERVED:
appendClass(coreRegex, URI_UNRESERVED, variable.isRequired());
break;
case Variable.TYPE_WORD:
appendClass(coreRegex, WORD, variable.isRequired());
break;
case Variable.TYPE_URI_FRAGMENT:
appendGroup(coreRegex, FRAGMENT, variable.isRequired());
break;
case Variable.TYPE_URI_PATH:
appendGroup(coreRegex, URI_PATH, variable.isRequired());
break;
case Variable.TYPE_URI_QUERY:
appendGroup(coreRegex, QUERY, variable.isRequired());
break;
case Variable.TYPE_URI_SEGMENT:
appendGroup(coreRegex, PCHAR, variable.isRequired());
break;
case Variable.TYPE_TOKEN:
appendClass(coreRegex, TOKEN, variable.isRequired());
break;
case Variable.TYPE_COMMENT:
appendClass(coreRegex, COMMENT, variable.isRequired());
break;
case Variable.TYPE_COMMENT_ATTRIBUTE:
appendClass(coreRegex, COMMENT_ATTRIBUTE, variable.isRequired());
break;
}
result = coreRegex.toString();
}
return result;
}
| private static String getVariableRegex(Variable variable) {
String result = null;
if (variable.isFixed()) {
result = "(" + Pattern.quote(variable.getDefaultValue()) + ")";
} else {
// Expressions to create character classes
final String ALL = ".";
final String ALPHA = "a-zA-Z";
final String DIGIT = "0-9";
final String ALPHA_DIGIT = ALPHA + DIGIT;
final String HEXA = DIGIT + "ABCDEFabcdef";
final String URI_UNRESERVED = ALPHA_DIGIT + "\\-\\.\\_\\~";
final String URI_GEN_DELIMS = "\\:\\/\\?\\#\\[\\]\\@";
final String URI_SUB_DELIMS = "\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=";
final String URI_RESERVED = URI_GEN_DELIMS + URI_SUB_DELIMS;
final String WORD = "\\w";
// Basic rules expressed by the HTTP rfc.
final String CRLF = "\\r\\n";
final String CTL = "\\p{Cntrl}";
final String LWS = CRLF + "\\ \\t";
final String SEPARATOR = "\\(\\)\\<\\>\\@\\,\\;\\:\\[\\]\"\\/\\\\?\\=\\{\\}\\ \\t";
final String TOKEN = "[^" + SEPARATOR + "]";
final String COMMENT = "[^" + CTL + "]" + "[^\\(\\)]" + LWS;
final String COMMENT_ATTRIBUTE = "[^\\;\\(\\)]";
// Expressions to create non-capturing groups
final String PCT_ENCODED = "\\%[" + HEXA + "][" + HEXA + "]";
// final String PCHAR = "[" + URI_UNRESERVED + "]|(?:" + PCT_ENCODED
// + ")|[" + URI_SUB_DELIMS + "]|\\:|\\@";
final String PCHAR = "[" + URI_UNRESERVED + URI_SUB_DELIMS
+ "\\:\\@]|(?:" + PCT_ENCODED + ")";
final String QUERY = PCHAR + "|\\/|\\?";
final String FRAGMENT = QUERY;
final String URI_PATH = PCHAR + "|\\/";
final String URI_ALL = "[" + URI_RESERVED + URI_UNRESERVED
+ "]|(?:" + PCT_ENCODED + ")";
final StringBuilder coreRegex = new StringBuilder();
switch (variable.getType()) {
case Variable.TYPE_ALL:
appendClass(coreRegex, ALL, variable.isRequired());
break;
case Variable.TYPE_ALPHA:
appendClass(coreRegex, ALPHA, variable.isRequired());
break;
case Variable.TYPE_DIGIT:
appendClass(coreRegex, DIGIT, variable.isRequired());
break;
case Variable.TYPE_ALPHA_DIGIT:
appendClass(coreRegex, ALPHA_DIGIT, variable.isRequired());
break;
case Variable.TYPE_URI_ALL:
appendGroup(coreRegex, URI_ALL, variable.isRequired());
break;
case Variable.TYPE_URI_UNRESERVED:
appendClass(coreRegex, URI_UNRESERVED, variable.isRequired());
break;
case Variable.TYPE_WORD:
appendClass(coreRegex, WORD, variable.isRequired());
break;
case Variable.TYPE_URI_FRAGMENT:
appendGroup(coreRegex, FRAGMENT, variable.isRequired());
break;
case Variable.TYPE_URI_PATH:
appendGroup(coreRegex, URI_PATH, variable.isRequired());
break;
case Variable.TYPE_URI_QUERY:
appendGroup(coreRegex, QUERY, variable.isRequired());
break;
case Variable.TYPE_URI_SEGMENT:
appendGroup(coreRegex, PCHAR, variable.isRequired());
break;
case Variable.TYPE_TOKEN:
appendClass(coreRegex, TOKEN, variable.isRequired());
break;
case Variable.TYPE_COMMENT:
appendClass(coreRegex, COMMENT, variable.isRequired());
break;
case Variable.TYPE_COMMENT_ATTRIBUTE:
appendClass(coreRegex, COMMENT_ATTRIBUTE, variable.isRequired());
break;
}
result = coreRegex.toString();
}
return result;
}
|
diff --git a/src/main/java/ch/o2it/weblounge/taglib/content/ComposerTag.java b/src/main/java/ch/o2it/weblounge/taglib/content/ComposerTag.java
index 65d627f17..3b248740d 100644
--- a/src/main/java/ch/o2it/weblounge/taglib/content/ComposerTag.java
+++ b/src/main/java/ch/o2it/weblounge/taglib/content/ComposerTag.java
@@ -1,145 +1,145 @@
/*
* Weblounge: Web Content Management System
* Copyright (c) 2010 The Weblounge Team
* http://weblounge.o2it.ch
*
* 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
* 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser 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 ch.o2it.weblounge.taglib.content;
import ch.o2it.weblounge.common.content.Resource;
import ch.o2it.weblounge.common.content.page.Page;
import ch.o2it.weblounge.common.content.page.Pagelet;
import ch.o2it.weblounge.common.impl.util.config.ConfigurationUtils;
import ch.o2it.weblounge.common.user.User;
import ch.o2it.weblounge.taglib.ComposerTagSupport;
import java.io.IOException;
import javax.servlet.jsp.JspWriter;
/**
* <code>ComposerTag</code> implements the handler for <code>module</code> tags
* embedded in a jsp file. The handler will request the specified module to
* return some resources using the requested view.
*/
public class ComposerTag extends ComposerTagSupport {
/** Serial version uid */
private static final long serialVersionUID = 3832079623323702494L;
/** True if the composer should not be editable */
protected boolean isLocked = false;
/**
* Sets the composer to a locked state, preventing editing at all.
*
* @param value
* <code>true</code> to lock the composer
*/
public void setLocked(String value) {
isLocked = ConfigurationUtils.isTrue(value);
}
/**
* {@inheritDoc}
*
* @see ch.o2it.weblounge.taglib.ComposerTagSupport#beforeComposer(javax.servlet.jsp.JspWriter)
*/
@Override
protected void beforeComposer(JspWriter writer) throws IOException {
User user = request.getUser();
long version = request.getVersion();
Page targetPage = getTargetPage();
Page contentPage = getContentProvider();
- boolean isLocked = targetPage.isLocked();
- boolean isLockedByCurrentUser = isLocked && user.equals(targetPage.getLockOwner());
+ boolean isLocked = targetPage != null && targetPage.isLocked();
+ boolean isLockedByCurrentUser = targetPage != null && isLocked && user.equals(targetPage.getLockOwner());
boolean isWorkVersion = version == Resource.WORK;
boolean allowContentInheritance = !isLockedByCurrentUser && !isWorkVersion;
// Enable / disable content inheritance for this composer
setInherit(allowContentInheritance);
// Mark inherited composer and ghost content in locked work mode
if (isWorkVersion && isLockedByCurrentUser) {
if (allowContentInheritance)
addCssClass(CLASS_INHERIT_CONTENT);
- if (!targetPage.equals(contentPage))
+ if (targetPage != null && !targetPage.equals(contentPage))
addCssClass(CLASS_GHOST_CONTENT);
}
// Let the default implementation kick in
super.beforeComposer(writer);
// Add first handle
// if (version == Page.WORK && isLockedByCurrentUser) {
// request.setAttribute(WebloungeRequest.COMPOSER, composer);
// PageletEditorTag editorTag = new PageletEditorTag();
// editorTag.showPageletEditor(getRequest(), getResponse(), writer);
// writer.flush();
// }
}
/**
* {@inheritDoc}
*
* @see ch.o2it.weblounge.taglib.ComposerTagSupport#beforePagelet(ch.o2it.weblounge.common.content.page.Pagelet, int, javax.servlet.jsp.JspWriter)
*/
@Override
protected int beforePagelet(Pagelet pagelet, int position, JspWriter writer)
throws IOException {
// Start editing support
// if (version == Page.WORK && isLockedByCurrentUser) {
// writer.println("<div class=\"pagelet\">");
// writer.flush();
// }
return super.beforePagelet(pagelet, position, writer);
}
/**
* {@inheritDoc}
*
* @see ch.o2it.weblounge.taglib.ComposerTagSupport#afterPagelet(ch.o2it.weblounge.common.content.page.Pagelet, int, javax.servlet.jsp.JspWriter)
*/
@Override
protected void afterPagelet(Pagelet pagelet, int position, JspWriter writer)
throws IOException {
// If user is not editing this page, then we are finished with
// the current pagelet.
// finally {
// if (version == Page.WORK && isLockedByCurrentUser &&
// request.getAttribute(PageletEditorTag.ID) == null) {
// request.setAttribute(WebloungeRequest.PAGE, targetPage);
// request.setAttribute(WebloungeRequest.PAGELET, pagelet);
// request.setAttribute(WebloungeRequest.COMPOSER, composer);
// PageletEditorTag editorTag = new PageletEditorTag();
// editorTag.showPageletEditor(getRequest(), getResponse(), writer);
// writer.println("</div>");
// }
// }
// Remove temporary request attributes
// request.removeAttribute(PageletEditorTag.ID);
super.afterPagelet(pagelet, position, writer);
}
}
| false | true | protected void beforeComposer(JspWriter writer) throws IOException {
User user = request.getUser();
long version = request.getVersion();
Page targetPage = getTargetPage();
Page contentPage = getContentProvider();
boolean isLocked = targetPage.isLocked();
boolean isLockedByCurrentUser = isLocked && user.equals(targetPage.getLockOwner());
boolean isWorkVersion = version == Resource.WORK;
boolean allowContentInheritance = !isLockedByCurrentUser && !isWorkVersion;
// Enable / disable content inheritance for this composer
setInherit(allowContentInheritance);
// Mark inherited composer and ghost content in locked work mode
if (isWorkVersion && isLockedByCurrentUser) {
if (allowContentInheritance)
addCssClass(CLASS_INHERIT_CONTENT);
if (!targetPage.equals(contentPage))
addCssClass(CLASS_GHOST_CONTENT);
}
// Let the default implementation kick in
super.beforeComposer(writer);
// Add first handle
// if (version == Page.WORK && isLockedByCurrentUser) {
// request.setAttribute(WebloungeRequest.COMPOSER, composer);
// PageletEditorTag editorTag = new PageletEditorTag();
// editorTag.showPageletEditor(getRequest(), getResponse(), writer);
// writer.flush();
// }
}
| protected void beforeComposer(JspWriter writer) throws IOException {
User user = request.getUser();
long version = request.getVersion();
Page targetPage = getTargetPage();
Page contentPage = getContentProvider();
boolean isLocked = targetPage != null && targetPage.isLocked();
boolean isLockedByCurrentUser = targetPage != null && isLocked && user.equals(targetPage.getLockOwner());
boolean isWorkVersion = version == Resource.WORK;
boolean allowContentInheritance = !isLockedByCurrentUser && !isWorkVersion;
// Enable / disable content inheritance for this composer
setInherit(allowContentInheritance);
// Mark inherited composer and ghost content in locked work mode
if (isWorkVersion && isLockedByCurrentUser) {
if (allowContentInheritance)
addCssClass(CLASS_INHERIT_CONTENT);
if (targetPage != null && !targetPage.equals(contentPage))
addCssClass(CLASS_GHOST_CONTENT);
}
// Let the default implementation kick in
super.beforeComposer(writer);
// Add first handle
// if (version == Page.WORK && isLockedByCurrentUser) {
// request.setAttribute(WebloungeRequest.COMPOSER, composer);
// PageletEditorTag editorTag = new PageletEditorTag();
// editorTag.showPageletEditor(getRequest(), getResponse(), writer);
// writer.flush();
// }
}
|
diff --git a/optaplanner-core/src/main/java/org/optaplanner/core/impl/score/buildin/bendable/BendableScoreDefinition.java b/optaplanner-core/src/main/java/org/optaplanner/core/impl/score/buildin/bendable/BendableScoreDefinition.java
index 76c66593a..f94af4e9d 100644
--- a/optaplanner-core/src/main/java/org/optaplanner/core/impl/score/buildin/bendable/BendableScoreDefinition.java
+++ b/optaplanner-core/src/main/java/org/optaplanner/core/impl/score/buildin/bendable/BendableScoreDefinition.java
@@ -1,160 +1,164 @@
/*
* Copyright 2013 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.optaplanner.core.impl.score.buildin.bendable;
import java.util.Arrays;
import org.optaplanner.core.api.score.Score;
import org.optaplanner.core.api.score.buildin.bendable.BendableScore;
import org.optaplanner.core.api.score.buildin.bendable.BendableScoreHolder;
import org.optaplanner.core.impl.score.definition.AbstractScoreDefinition;
import org.optaplanner.core.api.score.holder.ScoreHolder;
public class BendableScoreDefinition extends AbstractScoreDefinition<BendableScore> {
private final int hardLevelCount;
private final int softLevelCount;
private double recursiveTimeGradientWeight = 0.50; // TODO this is a guess
private BendableScore perfectMaximumScore = null;
private BendableScore perfectMinimumScore = null;
/**
* To make Java serialization happy.
*/
private BendableScoreDefinition() {
hardLevelCount = -1; // Java serialization still changes it
softLevelCount = -1; // Java serialization still changes it
}
public BendableScoreDefinition(int hardLevelCount, int softLevelCount) {
this.hardLevelCount = hardLevelCount;
this.softLevelCount = softLevelCount;
}
public int getHardLevelCount() {
return hardLevelCount;
}
public int getSoftLevelCount() {
return softLevelCount;
}
public double getRecursiveTimeGradientWeight() {
return recursiveTimeGradientWeight;
}
/**
* It's recommended to use a number which can be exactly represented as a double,
* such as 0.5, 0.25, 0.75, 0.125, ... but not 0.1, 0.2, ...
* @param recursiveTimeGradientWeight 0.0 <= recursiveTimeGradientWeight <= 1.0
*/
public void setRecursiveTimeGradientWeight(double recursiveTimeGradientWeight) {
this.recursiveTimeGradientWeight = recursiveTimeGradientWeight;
if (recursiveTimeGradientWeight < 0.0 || recursiveTimeGradientWeight > 1.0) {
throw new IllegalArgumentException("Property recursiveTimeGradientWeight (" + recursiveTimeGradientWeight
+ ") must be greater or equal to 0.0 and smaller or equal to 1.0.");
}
}
@Override
public BendableScore getPerfectMaximumScore() {
return perfectMaximumScore;
}
public void setPerfectMaximumScore(BendableScore perfectMaximumScore) {
this.perfectMaximumScore = perfectMaximumScore;
}
@Override
public BendableScore getPerfectMinimumScore() {
return perfectMinimumScore;
}
public void setPerfectMinimumScore(BendableScore perfectMinimumScore) {
this.perfectMinimumScore = perfectMinimumScore;
}
// ************************************************************************
// Worker methods
// ************************************************************************
public Class<BendableScore> getScoreClass() {
return BendableScore.class;
}
public Score parseScore(String scoreString) {
return BendableScore.parseScore(hardLevelCount, softLevelCount, scoreString);
}
public BendableScore createScore(int... scores) {
int levelCount = hardLevelCount + softLevelCount;
if (scores.length != levelCount) {
throw new IllegalArgumentException("The scores (" + Arrays.toString(scores)
+ ")'s length (" + scores.length
+ ") is not levelCount (" + levelCount + ").");
}
return BendableScore.valueOf(Arrays.copyOfRange(scores, 0, hardLevelCount),
Arrays.copyOfRange(scores, hardLevelCount, levelCount));
}
public double calculateTimeGradient(BendableScore startScore, BendableScore endScore,
BendableScore score) {
startScore.validateCompatible(score);
score.validateCompatible(endScore);
if (score.compareTo(endScore) > 0) {
return 1.0;
} else if (score.compareTo(startScore) < 0) {
return 0.0;
}
double timeGradient = 0.0;
- double levelTimeGradientWeight = 1.0;
+ double remainingTimeGradient = 1.0;
int levelCount = hardLevelCount + softLevelCount;
for (int i = 0; i < levelCount; i++) {
+ double levelTimeGradientWeight;
if (i != (levelCount - 1)) {
- levelTimeGradientWeight *= recursiveTimeGradientWeight;
+ levelTimeGradientWeight = remainingTimeGradient * recursiveTimeGradientWeight;
+ remainingTimeGradient -= levelTimeGradientWeight;
+ } else {
+ levelTimeGradientWeight = remainingTimeGradient;
}
int startScoreLevel = (i < hardLevelCount) ? startScore.getHardScore(i) : startScore.getSoftScore(i - hardLevelCount);
int endScoreLevel = (i < hardLevelCount) ? endScore.getHardScore(i) : endScore.getSoftScore(i - hardLevelCount);
int scoreLevel = (i < hardLevelCount) ? score.getHardScore(i) : score.getSoftScore(i - hardLevelCount);
if (scoreLevel >= endScoreLevel) {
timeGradient += levelTimeGradientWeight;
} else {
if (scoreLevel <= startScoreLevel) {
// No change: timeGradient += 0.0
} else {
int levelTotal = endScoreLevel - startScoreLevel;
int levelDelta = scoreLevel - startScoreLevel;
double levelTimeGradient = (double) levelDelta / (double) levelTotal;
timeGradient += levelTimeGradient * levelTimeGradientWeight;
}
}
}
if (timeGradient > 1.0) {
// Rounding error due to calculating with doubles
timeGradient = 1.0;
}
return timeGradient;
}
public ScoreHolder buildScoreHolder(boolean constraintMatchEnabled) {
return new BendableScoreHolder(constraintMatchEnabled, hardLevelCount, softLevelCount);
}
}
| false | true | public double calculateTimeGradient(BendableScore startScore, BendableScore endScore,
BendableScore score) {
startScore.validateCompatible(score);
score.validateCompatible(endScore);
if (score.compareTo(endScore) > 0) {
return 1.0;
} else if (score.compareTo(startScore) < 0) {
return 0.0;
}
double timeGradient = 0.0;
double levelTimeGradientWeight = 1.0;
int levelCount = hardLevelCount + softLevelCount;
for (int i = 0; i < levelCount; i++) {
if (i != (levelCount - 1)) {
levelTimeGradientWeight *= recursiveTimeGradientWeight;
}
int startScoreLevel = (i < hardLevelCount) ? startScore.getHardScore(i) : startScore.getSoftScore(i - hardLevelCount);
int endScoreLevel = (i < hardLevelCount) ? endScore.getHardScore(i) : endScore.getSoftScore(i - hardLevelCount);
int scoreLevel = (i < hardLevelCount) ? score.getHardScore(i) : score.getSoftScore(i - hardLevelCount);
if (scoreLevel >= endScoreLevel) {
timeGradient += levelTimeGradientWeight;
} else {
if (scoreLevel <= startScoreLevel) {
// No change: timeGradient += 0.0
} else {
int levelTotal = endScoreLevel - startScoreLevel;
int levelDelta = scoreLevel - startScoreLevel;
double levelTimeGradient = (double) levelDelta / (double) levelTotal;
timeGradient += levelTimeGradient * levelTimeGradientWeight;
}
}
}
if (timeGradient > 1.0) {
// Rounding error due to calculating with doubles
timeGradient = 1.0;
}
return timeGradient;
}
| public double calculateTimeGradient(BendableScore startScore, BendableScore endScore,
BendableScore score) {
startScore.validateCompatible(score);
score.validateCompatible(endScore);
if (score.compareTo(endScore) > 0) {
return 1.0;
} else if (score.compareTo(startScore) < 0) {
return 0.0;
}
double timeGradient = 0.0;
double remainingTimeGradient = 1.0;
int levelCount = hardLevelCount + softLevelCount;
for (int i = 0; i < levelCount; i++) {
double levelTimeGradientWeight;
if (i != (levelCount - 1)) {
levelTimeGradientWeight = remainingTimeGradient * recursiveTimeGradientWeight;
remainingTimeGradient -= levelTimeGradientWeight;
} else {
levelTimeGradientWeight = remainingTimeGradient;
}
int startScoreLevel = (i < hardLevelCount) ? startScore.getHardScore(i) : startScore.getSoftScore(i - hardLevelCount);
int endScoreLevel = (i < hardLevelCount) ? endScore.getHardScore(i) : endScore.getSoftScore(i - hardLevelCount);
int scoreLevel = (i < hardLevelCount) ? score.getHardScore(i) : score.getSoftScore(i - hardLevelCount);
if (scoreLevel >= endScoreLevel) {
timeGradient += levelTimeGradientWeight;
} else {
if (scoreLevel <= startScoreLevel) {
// No change: timeGradient += 0.0
} else {
int levelTotal = endScoreLevel - startScoreLevel;
int levelDelta = scoreLevel - startScoreLevel;
double levelTimeGradient = (double) levelDelta / (double) levelTotal;
timeGradient += levelTimeGradient * levelTimeGradientWeight;
}
}
}
if (timeGradient > 1.0) {
// Rounding error due to calculating with doubles
timeGradient = 1.0;
}
return timeGradient;
}
|
diff --git a/plugins/eu.udig.tools.jgrass/src/eu/udig/tools/jgrass/kml/wizard/KmlExportWizardPage.java b/plugins/eu.udig.tools.jgrass/src/eu/udig/tools/jgrass/kml/wizard/KmlExportWizardPage.java
index 15da5a4cc..72237a1d4 100644
--- a/plugins/eu.udig.tools.jgrass/src/eu/udig/tools/jgrass/kml/wizard/KmlExportWizardPage.java
+++ b/plugins/eu.udig.tools.jgrass/src/eu/udig/tools/jgrass/kml/wizard/KmlExportWizardPage.java
@@ -1,133 +1,133 @@
/*
* JGrass - Free Open Source Java GIS http://www.jgrass.org
* (C) HydroloGIS - www.hydrologis.com
*
* 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 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package eu.udig.tools.jgrass.kml.wizard;
import java.io.File;
import net.refractions.udig.catalog.IGeoResource;
import net.refractions.udig.project.ILayer;
import net.refractions.udig.project.ui.ApplicationGIS;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
/**
* @author Andrea Antonello (www.hydrologis.com)
*/
public class KmlExportWizardPage extends WizardPage {
public static final String ID = "eu.udig.tools.jgrass.kml.wizard.KmlExportWizardPage"; //$NON-NLS-1$
private Text outFileText;
private IGeoResource geoResource;
private String filePath;
public KmlExportWizardPage() {
super(ID);
setTitle("Export kml");
setDescription("Export feature layer to kml");
}
public void createControl( Composite parent ) {
Composite mainComposite = new Composite(parent, SWT.NONE);
GridLayout gridLayout = new GridLayout(3, false);
gridLayout.verticalSpacing = 10;
mainComposite.setLayout(gridLayout);
ILayer selectedLayer = ApplicationGIS.getActiveMap().getEditManager().getSelectedLayer();
geoResource = selectedLayer.getGeoResource();
/*
* layer selected
*/
Label selectedLayerLabel = new Label(mainComposite, SWT.NONE);
GridData selectedLayerLabelGd = new GridData(SWT.BEGINNING, SWT.CENTER, false, false);
selectedLayerLabelGd.horizontalSpan = 3;
selectedLayerLabel.setLayoutData(selectedLayerLabelGd);
selectedLayerLabel.setText("Selected layer to export: " + selectedLayer.getName());
/*
* output file
*/
Label outFileLabel = new Label(mainComposite, SWT.NONE);
outFileLabel.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false));
outFileLabel.setText("Kml file to save");
outFileText = new Text(mainComposite, SWT.BORDER);
outFileText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
outFileText.setEditable(false);
final Button outFolderButton = new Button(mainComposite, SWT.PUSH);
outFolderButton.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false));
outFolderButton.setText("..."); //$NON-NLS-1$
outFolderButton.addSelectionListener(new org.eclipse.swt.events.SelectionAdapter(){
public void widgetSelected( org.eclipse.swt.events.SelectionEvent e ) {
- FileDialog saveKmlDialog = new FileDialog(outFolderButton.getShell(), SWT.OPEN);
+ FileDialog saveKmlDialog = new FileDialog(outFolderButton.getShell(), SWT.SAVE);
saveKmlDialog.setFilterExtensions(new String[]{"*.kml"}); //$NON-NLS-1$
String path = saveKmlDialog.open();
if (path == null || path.length() < 1) {
outFileText.setText(""); //$NON-NLS-1$
} else {
outFileText.setText(path);
filePath = path;
}
checkFinish();
}
});
setControl(mainComposite);
}
public String getFilePath() {
return filePath;
}
public IGeoResource getGeoResource() {
return geoResource;
}
public void dispose() {
super.dispose();
}
private void checkFinish() {
if (filePath == null) {
KmlExportWizard.canFinish = false;
} else {
File file = new File(filePath);
File parentFolder = file.getParentFile();
if (parentFolder.isDirectory()) {
KmlExportWizard.canFinish = true;
} else {
KmlExportWizard.canFinish = false;
}
}
getWizard().getContainer().updateButtons();
}
}
| true | true | public void createControl( Composite parent ) {
Composite mainComposite = new Composite(parent, SWT.NONE);
GridLayout gridLayout = new GridLayout(3, false);
gridLayout.verticalSpacing = 10;
mainComposite.setLayout(gridLayout);
ILayer selectedLayer = ApplicationGIS.getActiveMap().getEditManager().getSelectedLayer();
geoResource = selectedLayer.getGeoResource();
/*
* layer selected
*/
Label selectedLayerLabel = new Label(mainComposite, SWT.NONE);
GridData selectedLayerLabelGd = new GridData(SWT.BEGINNING, SWT.CENTER, false, false);
selectedLayerLabelGd.horizontalSpan = 3;
selectedLayerLabel.setLayoutData(selectedLayerLabelGd);
selectedLayerLabel.setText("Selected layer to export: " + selectedLayer.getName());
/*
* output file
*/
Label outFileLabel = new Label(mainComposite, SWT.NONE);
outFileLabel.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false));
outFileLabel.setText("Kml file to save");
outFileText = new Text(mainComposite, SWT.BORDER);
outFileText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
outFileText.setEditable(false);
final Button outFolderButton = new Button(mainComposite, SWT.PUSH);
outFolderButton.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false));
outFolderButton.setText("..."); //$NON-NLS-1$
outFolderButton.addSelectionListener(new org.eclipse.swt.events.SelectionAdapter(){
public void widgetSelected( org.eclipse.swt.events.SelectionEvent e ) {
FileDialog saveKmlDialog = new FileDialog(outFolderButton.getShell(), SWT.OPEN);
saveKmlDialog.setFilterExtensions(new String[]{"*.kml"}); //$NON-NLS-1$
String path = saveKmlDialog.open();
if (path == null || path.length() < 1) {
outFileText.setText(""); //$NON-NLS-1$
} else {
outFileText.setText(path);
filePath = path;
}
checkFinish();
}
});
setControl(mainComposite);
}
| public void createControl( Composite parent ) {
Composite mainComposite = new Composite(parent, SWT.NONE);
GridLayout gridLayout = new GridLayout(3, false);
gridLayout.verticalSpacing = 10;
mainComposite.setLayout(gridLayout);
ILayer selectedLayer = ApplicationGIS.getActiveMap().getEditManager().getSelectedLayer();
geoResource = selectedLayer.getGeoResource();
/*
* layer selected
*/
Label selectedLayerLabel = new Label(mainComposite, SWT.NONE);
GridData selectedLayerLabelGd = new GridData(SWT.BEGINNING, SWT.CENTER, false, false);
selectedLayerLabelGd.horizontalSpan = 3;
selectedLayerLabel.setLayoutData(selectedLayerLabelGd);
selectedLayerLabel.setText("Selected layer to export: " + selectedLayer.getName());
/*
* output file
*/
Label outFileLabel = new Label(mainComposite, SWT.NONE);
outFileLabel.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false));
outFileLabel.setText("Kml file to save");
outFileText = new Text(mainComposite, SWT.BORDER);
outFileText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
outFileText.setEditable(false);
final Button outFolderButton = new Button(mainComposite, SWT.PUSH);
outFolderButton.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false));
outFolderButton.setText("..."); //$NON-NLS-1$
outFolderButton.addSelectionListener(new org.eclipse.swt.events.SelectionAdapter(){
public void widgetSelected( org.eclipse.swt.events.SelectionEvent e ) {
FileDialog saveKmlDialog = new FileDialog(outFolderButton.getShell(), SWT.SAVE);
saveKmlDialog.setFilterExtensions(new String[]{"*.kml"}); //$NON-NLS-1$
String path = saveKmlDialog.open();
if (path == null || path.length() < 1) {
outFileText.setText(""); //$NON-NLS-1$
} else {
outFileText.setText(path);
filePath = path;
}
checkFinish();
}
});
setControl(mainComposite);
}
|
diff --git a/src/com/google/inject/DefaultConstructionProxyFactory.java b/src/com/google/inject/DefaultConstructionProxyFactory.java
index 6addfb4f..bf046963 100644
--- a/src/com/google/inject/DefaultConstructionProxyFactory.java
+++ b/src/com/google/inject/DefaultConstructionProxyFactory.java
@@ -1,90 +1,90 @@
/**
* Copyright (C) 2006 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.inject;
import com.google.inject.internal.ErrorHandler;
import com.google.inject.internal.GuiceFastClass;
import net.sf.cglib.reflect.FastClass;
import net.sf.cglib.reflect.FastConstructor;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Member;
import java.lang.reflect.Modifier;
import java.util.List;
/**
* Default {@link ConstructionProxyFactory} implementation. Simply invokes the
* constructor. Can be reused by other {@code ConstructionProxyFactory}
* implementations.
*
* @author [email protected] (Bob Lee)
*/
class DefaultConstructionProxyFactory implements ConstructionProxyFactory {
private final ErrorHandler errorHandler;
DefaultConstructionProxyFactory(ErrorHandler errorHandler) {
this.errorHandler = errorHandler;
}
public <T> ConstructionProxy<T> get(final Constructor<T> constructor) {
// We can't use FastConstructor if the constructor is private or protected.
if (Modifier.isPrivate(constructor.getModifiers())
|| Modifier.isProtected(constructor.getModifiers())) {
constructor.setAccessible(true);
return new ConstructionProxy<T>() {
public T newInstance(Object... arguments) throws
InvocationTargetException {
try {
return constructor.newInstance(arguments);
}
catch (InstantiationException e) {
throw new RuntimeException(e);
}
catch (IllegalAccessException e) {
throw new AssertionError(e);
}
}
public List<Parameter<?>> getParameters() {
return Parameter.forConstructor(errorHandler, constructor);
}
public Member getMember() {
return constructor;
}
};
}
Class<T> classToConstruct = constructor.getDeclaringClass();
FastClass fastClass = GuiceFastClass.create(classToConstruct);
final FastConstructor fastConstructor
= fastClass.getConstructor(constructor);
return new ConstructionProxy<T>() {
@SuppressWarnings("unchecked")
public T newInstance(Object... arguments)
throws InvocationTargetException {
return (T) fastConstructor.newInstance(arguments);
}
public List<Parameter<?>> getParameters() {
- return Parameter.forConstructor(errorHandler, fastConstructor);
+ return Parameter.forConstructor(errorHandler, constructor);
}
public Member getMember() {
- return fastConstructor.getJavaConstructor();
+ return constructor;
}
};
}
}
| false | true | public <T> ConstructionProxy<T> get(final Constructor<T> constructor) {
// We can't use FastConstructor if the constructor is private or protected.
if (Modifier.isPrivate(constructor.getModifiers())
|| Modifier.isProtected(constructor.getModifiers())) {
constructor.setAccessible(true);
return new ConstructionProxy<T>() {
public T newInstance(Object... arguments) throws
InvocationTargetException {
try {
return constructor.newInstance(arguments);
}
catch (InstantiationException e) {
throw new RuntimeException(e);
}
catch (IllegalAccessException e) {
throw new AssertionError(e);
}
}
public List<Parameter<?>> getParameters() {
return Parameter.forConstructor(errorHandler, constructor);
}
public Member getMember() {
return constructor;
}
};
}
Class<T> classToConstruct = constructor.getDeclaringClass();
FastClass fastClass = GuiceFastClass.create(classToConstruct);
final FastConstructor fastConstructor
= fastClass.getConstructor(constructor);
return new ConstructionProxy<T>() {
@SuppressWarnings("unchecked")
public T newInstance(Object... arguments)
throws InvocationTargetException {
return (T) fastConstructor.newInstance(arguments);
}
public List<Parameter<?>> getParameters() {
return Parameter.forConstructor(errorHandler, fastConstructor);
}
public Member getMember() {
return fastConstructor.getJavaConstructor();
}
};
}
| public <T> ConstructionProxy<T> get(final Constructor<T> constructor) {
// We can't use FastConstructor if the constructor is private or protected.
if (Modifier.isPrivate(constructor.getModifiers())
|| Modifier.isProtected(constructor.getModifiers())) {
constructor.setAccessible(true);
return new ConstructionProxy<T>() {
public T newInstance(Object... arguments) throws
InvocationTargetException {
try {
return constructor.newInstance(arguments);
}
catch (InstantiationException e) {
throw new RuntimeException(e);
}
catch (IllegalAccessException e) {
throw new AssertionError(e);
}
}
public List<Parameter<?>> getParameters() {
return Parameter.forConstructor(errorHandler, constructor);
}
public Member getMember() {
return constructor;
}
};
}
Class<T> classToConstruct = constructor.getDeclaringClass();
FastClass fastClass = GuiceFastClass.create(classToConstruct);
final FastConstructor fastConstructor
= fastClass.getConstructor(constructor);
return new ConstructionProxy<T>() {
@SuppressWarnings("unchecked")
public T newInstance(Object... arguments)
throws InvocationTargetException {
return (T) fastConstructor.newInstance(arguments);
}
public List<Parameter<?>> getParameters() {
return Parameter.forConstructor(errorHandler, constructor);
}
public Member getMember() {
return constructor;
}
};
}
|
diff --git a/test/src/com/redhat/ceylon/compiler/java/test/misc/MiscTest.java b/test/src/com/redhat/ceylon/compiler/java/test/misc/MiscTest.java
index b021c8f51..854883006 100755
--- a/test/src/com/redhat/ceylon/compiler/java/test/misc/MiscTest.java
+++ b/test/src/com/redhat/ceylon/compiler/java/test/misc/MiscTest.java
@@ -1,441 +1,441 @@
/*
* Copyright Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the authors tag. All rights reserved.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License version 2.
*
* This particular file is subject to the "Classpath" exception as provided in the
* LICENSE file that accompanied this code.
*
* This program is distributed in the hope that it will be useful, but WITHOUT A
* 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 distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package com.redhat.ceylon.compiler.java.test.misc;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.ProcessBuilder.Redirect;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.tools.JavaFileObject;
import junit.framework.Assert;
import org.junit.Ignore;
import org.junit.Test;
import com.redhat.ceylon.cmr.api.JDKUtils;
import com.redhat.ceylon.compiler.java.test.CompilerTest;
import com.redhat.ceylon.compiler.java.test.ErrorCollector;
import com.redhat.ceylon.compiler.java.tools.CeyloncFileManager;
import com.redhat.ceylon.compiler.java.tools.CeyloncTaskImpl;
import com.redhat.ceylon.compiler.java.tools.CeyloncTool;
public class MiscTest extends CompilerTest {
@Test
public void testDefaultedModel() throws Exception{
compile("defaultedmodel/DefineDefaulted.ceylon");
compile("defaultedmodel/UseDefaulted.ceylon");
}
@Test
public void testHelloWorld(){
compareWithJavaSource("helloworld/helloworld");
}
@Test
public void runHelloWorld() throws Exception{
compileAndRun("com.redhat.ceylon.compiler.java.test.misc.helloworld.helloworld", "helloworld/helloworld.ceylon");
}
@Test
public void testCompileTwoDepdendantClasses() throws Exception{
compile("twoclasses/Two.ceylon");
compile("twoclasses/One.ceylon");
}
@Test
public void testCompileTwoClasses() throws Exception{
compileAndRun("com.redhat.ceylon.compiler.java.test.misc.twoclasses.main", "twoclasses/One.ceylon", "twoclasses/Two.ceylon", "twoclasses/main.ceylon");
}
@Test
public void testEqualsHashOverriding(){
compareWithJavaSource("equalshashoverriding/EqualsHashOverriding");
}
@Test
public void compileRuntime(){
cleanCars("build/classes-runtime");
java.util.List<File> sourceFiles = new ArrayList<File>();
String ceylonSourcePath = "../ceylon.language/src";
String javaSourcePath = "../ceylon.language/runtime";
String[] ceylonPackages = {"ceylon.language", "ceylon.language.model", "ceylon.language.model.declaration"};
// Native files
FileFilter exceptions = new FileFilter() {
@Override
public boolean accept(File pathname) {
String filename = pathname.getName();
filename = filename.substring(0, filename.lastIndexOf('.'));
for (String s : new String[]{"Array", "ArraySequence", "Boolean", "Callable", "Character", "className",
"Exception", "flatten", "Float", "identityHash", "Integer", "internalSort",
"language", "metamodel", "modules", "process", "integerRangeByIterable",
- "SequenceBuilder", "SequenceAppender", "String", "StringBuilder"}) {
+ "SequenceBuilder", "SequenceAppender", "String", "StringBuilder", "Tuple"}) {
if (s.equals(filename)) {
return true;
}
}
if (filename.equals("annotations")
&& pathname.getParentFile().getName().equals("model")) {
return true;
}
return false;
}
};
String[] extras = new String[]{
"array", "arrayOfSize", "false", "infinity",
"parseFloat", "true", "integerRangeByIterable", "unflatten"
};
String[] modelExtras = new String[]{
"annotations", "modules", "type", "typeLiteral"
};
for(String pkg : ceylonPackages){
File pkgDir = new File(ceylonSourcePath, pkg.replaceAll("\\.", "/"));
File javaPkgDir = new File(javaSourcePath, pkg.replaceAll("\\.", "/"));
File[] files = pkgDir.listFiles();
if (files != null) {
for(File src : files) {
if(src.isFile() && src.getName().toLowerCase().endsWith(".ceylon")) {
String baseName = src.getName().substring(0, src.getName().length() - 7);
if (!exceptions.accept(src)) {
sourceFiles.add(src);
} else {
addJavaSourceFile(baseName, sourceFiles, javaPkgDir, false);
}
}
}
}
}
// add extra files that are in Java
File javaPkgDir = new File(javaSourcePath, "ceylon/language");
for(String extra : extras)
addJavaSourceFile(extra, sourceFiles, javaPkgDir, true);
File javaModelPkgDir = new File(javaSourcePath, "ceylon/language/model");
for(String extra : modelExtras)
addJavaSourceFile(extra, sourceFiles, javaModelPkgDir, true);
String[] javaPackages = {
"com/redhat/ceylon/compiler/java",
"com/redhat/ceylon/compiler/java/language",
"com/redhat/ceylon/compiler/java/metadata",
"com/redhat/ceylon/compiler/java/runtime/ide",
"com/redhat/ceylon/compiler/java/runtime/metamodel",
"com/redhat/ceylon/compiler/java/runtime/model",
};
for(String pkg : javaPackages){
File pkgDir = new File(javaSourcePath, pkg.replaceAll("\\.", "/"));
File[] files = pkgDir.listFiles();
if (files != null) {
for(File src : files) {
if(src.isFile() && src.getName().toLowerCase().endsWith(".java")) {
sourceFiles.add(src);
}
}
}
}
CeyloncTool compiler;
try {
compiler = new CeyloncTool();
} catch (VerifyError e) {
System.err.println("ERROR: Cannot run tests! Did you maybe forget to configure the -Xbootclasspath/p: parameter?");
throw e;
}
CeyloncFileManager fileManager = (CeyloncFileManager)compiler.getStandardFileManager(null, null, null);
Iterable<? extends JavaFileObject> compilationUnits1 =
fileManager.getJavaFileObjectsFromFiles(sourceFiles);
String compilerSourcePath = ceylonSourcePath + File.pathSeparator + javaSourcePath;
CeyloncTaskImpl task = (CeyloncTaskImpl) compiler.getTask(null, fileManager, null,
Arrays.asList("-sourcepath", compilerSourcePath, "-d", "build/classes-runtime", "-Xbootstrapceylon"/*, "-verbose"*/),
null, compilationUnits1);
Boolean result = task.call();
Assert.assertEquals("Compilation failed", Boolean.TRUE, result);
}
private void addJavaSourceFile(String baseName, List<File> sourceFiles, File javaPkgDir, boolean required) {
if (Character.isLowerCase(baseName.charAt(0))) {
File file = new File(javaPkgDir, baseName + "_.java");
if(file.exists())
sourceFiles.add(file);
else if(required)
Assert.fail("Required file not found: "+file);
} else {
File file = new File(javaPkgDir, baseName + "_.java");
if(file.exists())
sourceFiles.add(file);
else if(required)
Assert.fail("Required file not found: "+file);
File impl = new File(javaPkgDir, baseName + "$impl.java");
if (impl.exists()) {
sourceFiles.add(impl);
}
}
}
/**
* This test is for when we need to debug an incremental compilation error from the IDE, to make
* sure it is indeed a bug and find which bug it is, do not enable it by default, it's only there
* for debugging purpose. Once the bug is found, add it where it belongs (not here).
*/
@Ignore
@Test
public void debugIncrementalCompilationBug(){
java.util.List<File> sourceFiles = new ArrayList<File>();
String sdkSourcePath = "../ceylon-sdk/source";
String testSourcePath = "../ceylon-sdk/test-source";
for(String s : new String[]{
"../ceylon-sdk/source/ceylon/json/StringPrinter.ceylon",
"../ceylon-sdk/test-source/test/ceylon/json/print.ceylon",
"../ceylon-sdk/source/ceylon/json/Array.ceylon",
"../ceylon-sdk/test-source/test/ceylon/json/use.ceylon",
"../ceylon-sdk/source/ceylon/net/uri/Path.ceylon",
"../ceylon-sdk/test-source/test/ceylon/net/run.ceylon",
"../ceylon-sdk/source/ceylon/json/Printer.ceylon",
"../ceylon-sdk/source/ceylon/json/Object.ceylon",
"../ceylon-sdk/source/ceylon/net/uri/Query.ceylon",
"../ceylon-sdk/test-source/test/ceylon/json/run.ceylon",
"../ceylon-sdk/test-source/test/ceylon/net/connection.ceylon",
"../ceylon-sdk/source/ceylon/json/parse.ceylon",
"../ceylon-sdk/test-source/test/ceylon/json/parse.ceylon",
"../ceylon-sdk/source/ceylon/net/uri/PathSegment.ceylon",
}){
sourceFiles.add(new File(s));
}
CeyloncTool compiler;
try {
compiler = new CeyloncTool();
} catch (VerifyError e) {
System.err.println("ERROR: Cannot run tests! Did you maybe forget to configure the -Xbootclasspath/p: parameter?");
throw e;
}
CeyloncFileManager fileManager = (CeyloncFileManager)compiler.getStandardFileManager(null, null, null);
Iterable<? extends JavaFileObject> compilationUnits1 =
fileManager.getJavaFileObjectsFromFiles(sourceFiles);
String compilerSourcePath = sdkSourcePath + File.pathSeparator + testSourcePath;
CeyloncTaskImpl task = (CeyloncTaskImpl) compiler.getTask(null, fileManager, null,
Arrays.asList("-sourcepath", compilerSourcePath, "-d", "../ceylon-sdk/modules"/*, "-verbose"*/),
null, compilationUnits1);
Boolean result = task.call();
Assert.assertEquals("Compilation failed", Boolean.TRUE, result);
}
@Test
public void compileSDK(){
String[] modules = {
"collection",
"dbc",
"file",
"interop.java",
"io",
"json",
"math",
"net",
"process",
"test",
"time"
};
compileSDKOnly(modules);
compileSDKTests(modules);
}
private void compileSDKOnly(String[] modules){
String sourceDir = "../ceylon-sdk/source";
// don't run this if the SDK is not checked out
File sdkFile = new File(sourceDir);
if(!sdkFile.exists())
return;
java.util.List<String> moduleNames = new ArrayList<String>(modules.length);
for(String module : modules){
moduleNames.add("ceylon." + module);
}
CeyloncTool compiler;
try {
compiler = new CeyloncTool();
} catch (VerifyError e) {
System.err.println("ERROR: Cannot run tests! Did you maybe forget to configure the -Xbootclasspath/p: parameter?");
throw e;
}
ErrorCollector errorCollector = new ErrorCollector();
CeyloncFileManager fileManager = (CeyloncFileManager)compiler.getStandardFileManager(null, null, null);
CeyloncTaskImpl task = (CeyloncTaskImpl) compiler.getTask(null, fileManager, errorCollector,
Arrays.asList("-sourcepath", sourceDir, "-d", "build/classes-sdk"),
moduleNames, null);
Boolean result = task.call();
Assert.assertEquals("Compilation of SDK itself failed: " + errorCollector.getAssertionFailureMessage(), Boolean.TRUE, result);
}
private void compileSDKTests(String[] modules){
String sourceDir = "../ceylon-sdk/test-source";
String depsDir = "../ceylon-sdk/test-deps";
// don't run this if the SDK is not checked out
File sdkFile = new File(sourceDir);
if(!sdkFile.exists())
return;
java.util.List<String> moduleNames = new ArrayList<String>(modules.length);
for(String module : modules){
moduleNames.add("test.ceylon." + module);
}
CeyloncTool compiler;
try {
compiler = new CeyloncTool();
} catch (VerifyError e) {
System.err.println("ERROR: Cannot run tests! Did you maybe forget to configure the -Xbootclasspath/p: parameter?");
throw e;
}
ErrorCollector errorCollector = new ErrorCollector();
CeyloncFileManager fileManager = (CeyloncFileManager)compiler.getStandardFileManager(null, null, null);
CeyloncTaskImpl task = (CeyloncTaskImpl) compiler.getTask(null, fileManager, errorCollector,
Arrays.asList("-sourcepath", sourceDir, "-rep", depsDir, "-d", "build/classes-sdk"),
moduleNames, null);
Boolean result = task.call();
Assert.assertEquals("Compilation of SDK tests failed:" + errorCollector.getAssertionFailureMessage(), Boolean.TRUE, result);
}
//
// Java keyword avoidance
// Note class names and generic type arguments are not a problem because
// in Ceylon they must begin with an upper case latter, but the Java
// keywords are all lowercase
@Test
public void testKeywordVariable(){
compareWithJavaSource("keyword/Variable");
}
@Test
public void testKeywordAttribute(){
compareWithJavaSource("keyword/Attribute");
}
@Test
public void testKeywordMethod(){
compareWithJavaSource("keyword/Method");
}
@Test
public void testKeywordParameter(){
compareWithJavaSource("keyword/Parameter");
}
@Test
public void testJDKModules(){
Assert.assertTrue(JDKUtils.isJDKModule("java.base"));
Assert.assertTrue(JDKUtils.isJDKModule("java.desktop"));
Assert.assertTrue(JDKUtils.isJDKModule("java.compiler")); // last one
Assert.assertFalse(JDKUtils.isJDKModule("java.stef"));
}
@Test
public void testJDKPackages(){
Assert.assertTrue(JDKUtils.isJDKAnyPackage("java.awt"));
Assert.assertTrue(JDKUtils.isJDKAnyPackage("java.lang"));
Assert.assertTrue(JDKUtils.isJDKAnyPackage("java.util"));
Assert.assertTrue(JDKUtils.isJDKAnyPackage("javax.swing"));
Assert.assertTrue(JDKUtils.isJDKAnyPackage("org.w3c.dom"));
Assert.assertTrue(JDKUtils.isJDKAnyPackage("org.xml.sax.helpers"));// last one
Assert.assertFalse(JDKUtils.isJDKAnyPackage("fr.epardaud"));
}
@Test
public void testOracleJDKModules(){
Assert.assertTrue(JDKUtils.isOracleJDKModule("oracle.jdk.base"));
Assert.assertTrue(JDKUtils.isOracleJDKModule("oracle.jdk.desktop"));
Assert.assertTrue(JDKUtils.isOracleJDKModule("oracle.jdk.httpserver"));
Assert.assertTrue(JDKUtils.isOracleJDKModule("oracle.jdk.tools.base")); // last one
Assert.assertFalse(JDKUtils.isOracleJDKModule("oracle.jdk.stef"));
Assert.assertFalse(JDKUtils.isOracleJDKModule("jdk.base"));
}
@Test
public void testOracleJDKPackages(){
Assert.assertTrue(JDKUtils.isOracleJDKAnyPackage("com.oracle.net"));
Assert.assertTrue(JDKUtils.isOracleJDKAnyPackage("com.sun.awt"));
Assert.assertTrue(JDKUtils.isOracleJDKAnyPackage("com.sun.imageio.plugins.bmp"));
Assert.assertTrue(JDKUtils.isOracleJDKAnyPackage("com.sun.java.swing.plaf.gtk"));
Assert.assertTrue(JDKUtils.isOracleJDKAnyPackage("com.sun.nio.sctp"));
Assert.assertTrue(JDKUtils.isOracleJDKAnyPackage("sun.nio"));
Assert.assertTrue(JDKUtils.isOracleJDKAnyPackage("sunw.util"));// last one
Assert.assertFalse(JDKUtils.isOracleJDKAnyPackage("fr.epardaud"));
}
@Test
public void testLaunchDistCeylon() throws IOException, InterruptedException {
String[] args1 = {
"../ceylon-dist/dist/bin/ceylon",
"compile",
"--src",
"../ceylon-dist/dist/samples/helloworld/source",
"--out",
"build/test-cars",
"com.example.helloworld"
};
launchCeylon(args1);
String[] args2 = {
"../ceylon-dist/dist/bin/ceylon",
"doc",
"--src",
"../ceylon-dist/dist/samples/helloworld/source",
"--out",
"build/test-cars",
"com.example.helloworld"
};
launchCeylon(args2);
String[] args3 = {
"../ceylon-dist/dist/bin/ceylon",
"run",
"--rep",
"build/test-cars",
"com.example.helloworld/1.0.0"
};
launchCeylon(args3);
}
public void launchCeylon(String[] args) throws IOException, InterruptedException {
ProcessBuilder pb = new ProcessBuilder(args);
pb.redirectInput(Redirect.INHERIT);
pb.redirectOutput(Redirect.INHERIT);
pb.redirectError(Redirect.INHERIT);
Process p = pb.start();
p.waitFor();
if (p.exitValue() > 0) {
Assert.fail("Ceylon script execution failed");
}
}
}
| true | true | public void compileRuntime(){
cleanCars("build/classes-runtime");
java.util.List<File> sourceFiles = new ArrayList<File>();
String ceylonSourcePath = "../ceylon.language/src";
String javaSourcePath = "../ceylon.language/runtime";
String[] ceylonPackages = {"ceylon.language", "ceylon.language.model", "ceylon.language.model.declaration"};
// Native files
FileFilter exceptions = new FileFilter() {
@Override
public boolean accept(File pathname) {
String filename = pathname.getName();
filename = filename.substring(0, filename.lastIndexOf('.'));
for (String s : new String[]{"Array", "ArraySequence", "Boolean", "Callable", "Character", "className",
"Exception", "flatten", "Float", "identityHash", "Integer", "internalSort",
"language", "metamodel", "modules", "process", "integerRangeByIterable",
"SequenceBuilder", "SequenceAppender", "String", "StringBuilder"}) {
if (s.equals(filename)) {
return true;
}
}
if (filename.equals("annotations")
&& pathname.getParentFile().getName().equals("model")) {
return true;
}
return false;
}
};
String[] extras = new String[]{
"array", "arrayOfSize", "false", "infinity",
"parseFloat", "true", "integerRangeByIterable", "unflatten"
};
String[] modelExtras = new String[]{
"annotations", "modules", "type", "typeLiteral"
};
for(String pkg : ceylonPackages){
File pkgDir = new File(ceylonSourcePath, pkg.replaceAll("\\.", "/"));
File javaPkgDir = new File(javaSourcePath, pkg.replaceAll("\\.", "/"));
File[] files = pkgDir.listFiles();
if (files != null) {
for(File src : files) {
if(src.isFile() && src.getName().toLowerCase().endsWith(".ceylon")) {
String baseName = src.getName().substring(0, src.getName().length() - 7);
if (!exceptions.accept(src)) {
sourceFiles.add(src);
} else {
addJavaSourceFile(baseName, sourceFiles, javaPkgDir, false);
}
}
}
}
}
// add extra files that are in Java
File javaPkgDir = new File(javaSourcePath, "ceylon/language");
for(String extra : extras)
addJavaSourceFile(extra, sourceFiles, javaPkgDir, true);
File javaModelPkgDir = new File(javaSourcePath, "ceylon/language/model");
for(String extra : modelExtras)
addJavaSourceFile(extra, sourceFiles, javaModelPkgDir, true);
String[] javaPackages = {
"com/redhat/ceylon/compiler/java",
"com/redhat/ceylon/compiler/java/language",
"com/redhat/ceylon/compiler/java/metadata",
"com/redhat/ceylon/compiler/java/runtime/ide",
"com/redhat/ceylon/compiler/java/runtime/metamodel",
"com/redhat/ceylon/compiler/java/runtime/model",
};
for(String pkg : javaPackages){
File pkgDir = new File(javaSourcePath, pkg.replaceAll("\\.", "/"));
File[] files = pkgDir.listFiles();
if (files != null) {
for(File src : files) {
if(src.isFile() && src.getName().toLowerCase().endsWith(".java")) {
sourceFiles.add(src);
}
}
}
}
CeyloncTool compiler;
try {
compiler = new CeyloncTool();
} catch (VerifyError e) {
System.err.println("ERROR: Cannot run tests! Did you maybe forget to configure the -Xbootclasspath/p: parameter?");
throw e;
}
CeyloncFileManager fileManager = (CeyloncFileManager)compiler.getStandardFileManager(null, null, null);
Iterable<? extends JavaFileObject> compilationUnits1 =
fileManager.getJavaFileObjectsFromFiles(sourceFiles);
String compilerSourcePath = ceylonSourcePath + File.pathSeparator + javaSourcePath;
CeyloncTaskImpl task = (CeyloncTaskImpl) compiler.getTask(null, fileManager, null,
Arrays.asList("-sourcepath", compilerSourcePath, "-d", "build/classes-runtime", "-Xbootstrapceylon"/*, "-verbose"*/),
null, compilationUnits1);
Boolean result = task.call();
Assert.assertEquals("Compilation failed", Boolean.TRUE, result);
}
| public void compileRuntime(){
cleanCars("build/classes-runtime");
java.util.List<File> sourceFiles = new ArrayList<File>();
String ceylonSourcePath = "../ceylon.language/src";
String javaSourcePath = "../ceylon.language/runtime";
String[] ceylonPackages = {"ceylon.language", "ceylon.language.model", "ceylon.language.model.declaration"};
// Native files
FileFilter exceptions = new FileFilter() {
@Override
public boolean accept(File pathname) {
String filename = pathname.getName();
filename = filename.substring(0, filename.lastIndexOf('.'));
for (String s : new String[]{"Array", "ArraySequence", "Boolean", "Callable", "Character", "className",
"Exception", "flatten", "Float", "identityHash", "Integer", "internalSort",
"language", "metamodel", "modules", "process", "integerRangeByIterable",
"SequenceBuilder", "SequenceAppender", "String", "StringBuilder", "Tuple"}) {
if (s.equals(filename)) {
return true;
}
}
if (filename.equals("annotations")
&& pathname.getParentFile().getName().equals("model")) {
return true;
}
return false;
}
};
String[] extras = new String[]{
"array", "arrayOfSize", "false", "infinity",
"parseFloat", "true", "integerRangeByIterable", "unflatten"
};
String[] modelExtras = new String[]{
"annotations", "modules", "type", "typeLiteral"
};
for(String pkg : ceylonPackages){
File pkgDir = new File(ceylonSourcePath, pkg.replaceAll("\\.", "/"));
File javaPkgDir = new File(javaSourcePath, pkg.replaceAll("\\.", "/"));
File[] files = pkgDir.listFiles();
if (files != null) {
for(File src : files) {
if(src.isFile() && src.getName().toLowerCase().endsWith(".ceylon")) {
String baseName = src.getName().substring(0, src.getName().length() - 7);
if (!exceptions.accept(src)) {
sourceFiles.add(src);
} else {
addJavaSourceFile(baseName, sourceFiles, javaPkgDir, false);
}
}
}
}
}
// add extra files that are in Java
File javaPkgDir = new File(javaSourcePath, "ceylon/language");
for(String extra : extras)
addJavaSourceFile(extra, sourceFiles, javaPkgDir, true);
File javaModelPkgDir = new File(javaSourcePath, "ceylon/language/model");
for(String extra : modelExtras)
addJavaSourceFile(extra, sourceFiles, javaModelPkgDir, true);
String[] javaPackages = {
"com/redhat/ceylon/compiler/java",
"com/redhat/ceylon/compiler/java/language",
"com/redhat/ceylon/compiler/java/metadata",
"com/redhat/ceylon/compiler/java/runtime/ide",
"com/redhat/ceylon/compiler/java/runtime/metamodel",
"com/redhat/ceylon/compiler/java/runtime/model",
};
for(String pkg : javaPackages){
File pkgDir = new File(javaSourcePath, pkg.replaceAll("\\.", "/"));
File[] files = pkgDir.listFiles();
if (files != null) {
for(File src : files) {
if(src.isFile() && src.getName().toLowerCase().endsWith(".java")) {
sourceFiles.add(src);
}
}
}
}
CeyloncTool compiler;
try {
compiler = new CeyloncTool();
} catch (VerifyError e) {
System.err.println("ERROR: Cannot run tests! Did you maybe forget to configure the -Xbootclasspath/p: parameter?");
throw e;
}
CeyloncFileManager fileManager = (CeyloncFileManager)compiler.getStandardFileManager(null, null, null);
Iterable<? extends JavaFileObject> compilationUnits1 =
fileManager.getJavaFileObjectsFromFiles(sourceFiles);
String compilerSourcePath = ceylonSourcePath + File.pathSeparator + javaSourcePath;
CeyloncTaskImpl task = (CeyloncTaskImpl) compiler.getTask(null, fileManager, null,
Arrays.asList("-sourcepath", compilerSourcePath, "-d", "build/classes-runtime", "-Xbootstrapceylon"/*, "-verbose"*/),
null, compilationUnits1);
Boolean result = task.call();
Assert.assertEquals("Compilation failed", Boolean.TRUE, result);
}
|
diff --git a/com.uwusoft.timesheet/src/com/uwusoft/timesheet/view/AllDayTasksView.java b/com.uwusoft.timesheet/src/com/uwusoft/timesheet/view/AllDayTasksView.java
index 01d51f2..1f78225 100644
--- a/com.uwusoft.timesheet/src/com/uwusoft/timesheet/view/AllDayTasksView.java
+++ b/com.uwusoft.timesheet/src/com/uwusoft/timesheet/view/AllDayTasksView.java
@@ -1,388 +1,390 @@
package com.uwusoft.timesheet.view;
import java.beans.PropertyChangeEvent;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.DialogCellEditor;
import org.eclipse.jface.viewers.EditingSupport;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import com.uwusoft.timesheet.Activator;
import com.uwusoft.timesheet.TimesheetApp;
import com.uwusoft.timesheet.dialog.AllDayTaskDateDialog;
import com.uwusoft.timesheet.dialog.EndAllDayTaskDateDialog;
import com.uwusoft.timesheet.dialog.ExternalAllDayTaskListDialog;
import com.uwusoft.timesheet.dialog.InternalAllDayTaskListDialog;
import com.uwusoft.timesheet.dialog.StartAllDayTaskDateDialog;
import com.uwusoft.timesheet.dialog.TaskListDialog;
import com.uwusoft.timesheet.extensionpoint.AllDayTaskService;
import com.uwusoft.timesheet.extensionpoint.LocalStorageService;
import com.uwusoft.timesheet.extensionpoint.StorageService;
import com.uwusoft.timesheet.model.AllDayTaskEntry;
import com.uwusoft.timesheet.model.Task;
import com.uwusoft.timesheet.util.BusinessDayUtil;
public class AllDayTasksView extends AbstractTasksView {
public static final String ID = "com.uwusoft.timesheet.view.alldaytasksview";
protected boolean addTaskEntries() {
if (viewer == null) return false;
viewer.setInput(LocalStorageService.getInstance().getAllDayTaskEntries());
return true;
}
protected void createColumns(final Composite parent, final TableViewer viewer) {
final Map<String, Integer> allDayTaskIndex = new HashMap<String, Integer>();
int i = 0;
final List<String> allDayTasks = new ArrayList<String>(storageService.getAllDayTasks());
for(String allDayTask : allDayTasks)
allDayTaskIndex.put(allDayTask, i++);
String[] titles = { "From", "To", "Requested", "Task", "Project", "Issue Key" };
int[] bounds = { 80, 80, 70, 150, 150, 70 };
int colNum = 0;
// First column is for the from date
TableViewerColumn col = createTableViewerColumn(titles[colNum], bounds[colNum], colNum++);
col.setEditingSupport(new EditingSupport(viewer) {
protected boolean canEdit(Object element) {
return true;
}
protected CellEditor getCellEditor(Object element) {
return new DateDialogCellEditor(viewer.getTable(), (AllDayTaskEntry) element) {
@Override
protected AllDayTaskDateDialog getDateDialog(Control cellEditorWindow, AllDayTaskEntry entry) {
return new StartAllDayTaskDateDialog(cellEditorWindow.getDisplay(), "Set start date", entry.getFrom(), entry.getTo(), entry.getId());
}
@Override
protected Date getDate(AllDayTaskEntry entry) {
return entry.getFrom();
}
@Override
protected void setDate(AllDayTaskEntry entry, Timestamp date) {
entry.setFrom(date);
}
};
}
protected Object getValue(Object element) {
return DateFormat.getDateInstance(DateFormat.SHORT).format(((AllDayTaskEntry) element).getFrom());
}
protected void setValue(Object element, Object value) {
}
});
col.setLabelProvider(new AlternatingColumnProvider() {
public String getText(Object element) {
Timestamp date = ((AllDayTaskEntry) element).getFrom();
return DateFormat.getDateInstance(DateFormat.SHORT).format(date);
}
public Image getImage(Object obj) {
return AbstractUIPlugin.imageDescriptorFromPlugin("com.uwusoft.timesheet", "/icons/date.png").createImage();
}
});
// Second column is for the to date
col = createTableViewerColumn(titles[colNum], bounds[colNum], colNum++);
col.setEditingSupport(new EditingSupport(viewer) {
protected boolean canEdit(Object element) {
return true;
}
protected CellEditor getCellEditor(Object element) {
return new DateDialogCellEditor(viewer.getTable(), (AllDayTaskEntry) element) {
@Override
protected AllDayTaskDateDialog getDateDialog(Control cellEditorWindow, AllDayTaskEntry entry) {
return new EndAllDayTaskDateDialog(cellEditorWindow.getDisplay(), "Set end date", entry.getFrom(), entry.getTo(), entry.getId());
}
@Override
protected Date getDate(AllDayTaskEntry entry) {
return entry.getTo();
}
@Override
protected void setDate(AllDayTaskEntry entry, Timestamp date) {
entry.setTo(date);
}
};
}
protected Object getValue(Object element) {
return DateFormat.getDateInstance(DateFormat.SHORT).format(((AllDayTaskEntry) element).getTo());
}
protected void setValue(Object element, Object value) {
}
});
col.setLabelProvider(new AlternatingColumnProvider() {
public String getText(Object element) {
Timestamp date = ((AllDayTaskEntry) element).getTo();
return DateFormat.getDateInstance(DateFormat.SHORT).format(date);
}
public Image getImage(Object obj) {
return AbstractUIPlugin.imageDescriptorFromPlugin("com.uwusoft.timesheet", "/icons/date.png").createImage();
}
});
// Third column is for the requested
col = createTableViewerColumn(titles[colNum], bounds[colNum], colNum++);
col.setEditingSupport(new EditingSupport(viewer) {
protected boolean canEdit(Object element) {
return false;
}
protected CellEditor getCellEditor(Object element) {
return null;
}
protected Object getValue(Object element) {
return getRequestedDays(element);
}
protected void setValue(Object element, Object value) {
}
});
col.setLabelProvider(new AlternatingColumnProvider() {
public String getText(Object element) {
Integer requestedDays = getRequestedDays(element);
if (requestedDays != null) return requestedDays.toString();
return null;
}
public Image getImage(Object obj) {
return null;
}
});
// Fourth column is for the task
col = createTableViewerColumn(titles[colNum], bounds[colNum], colNum++);
col.setEditingSupport(new EditingSupport(viewer) {
protected boolean canEdit(Object element) {
return true;
}
protected CellEditor getCellEditor(Object element) {
return new AllDayTaskListDialogCellEditor(viewer.getTable(), (AllDayTaskEntry) element);
}
protected Object getValue(Object element) {
return ((AllDayTaskEntry) element).getTask().getName();
}
protected void setValue(Object element, Object value) {
}
});
col.setLabelProvider(new AlternatingColumnProvider() {
public String getText(Object element) {
return ((AllDayTaskEntry) element).getTask().getName();
}
public Image getImage(Object obj) {
- return AbstractUIPlugin.imageDescriptorFromPlugin("com.uwusoft.timesheet", "/icons/task_16.png").createImage();
+ if (((AllDayTaskEntry) obj).getTask().equals(TimesheetApp.createTask(AllDayTaskService.PREFIX + AllDayTaskService.VACATION_TASK)))
+ return AbstractUIPlugin.imageDescriptorFromPlugin("com.uwusoft.timesheet", "/icons/vacation_16.gif").createImage();
+ return AbstractUIPlugin.imageDescriptorFromPlugin("com.uwusoft.timesheet", "/icons/genericissue_16.gif").createImage();
}
});
// Fifth column is for the project
col = createTableViewerColumn(titles[colNum], bounds[colNum], colNum++);
col.setEditingSupport(new EditingSupport(viewer) {
protected boolean canEdit(Object element) {
return false;
}
protected CellEditor getCellEditor(Object element) {
return null;
}
protected Object getValue(Object element) {
return ((AllDayTaskEntry) element).getTask().getProject().getName();
}
protected void setValue(Object element, Object value) {
}
});
col.setLabelProvider(new AlternatingColumnProvider() {
public String getText(Object element) {
return ((AllDayTaskEntry) element).getTask().getProject().getName();
}
public Image getImage(Object obj) {
return AbstractUIPlugin.imageDescriptorFromPlugin("com.uwusoft.timesheet", "/icons/task_16.png").createImage();
}
});
// Sixth column is for the issue key
col = createTableViewerColumn(titles[colNum], bounds[colNum], colNum++);
col.setEditingSupport(new EditingSupport(viewer) {
protected boolean canEdit(Object element) {
return !StringUtils.isEmpty(((AllDayTaskEntry) element).getExternalId());
}
protected CellEditor getCellEditor(Object element) {
return new ExternalTaskDialogCellEditor(viewer.getTable(), (AllDayTaskEntry) element);
}
protected Object getValue(Object element) {
return ((AllDayTaskEntry) element).getExternalId();
}
protected void setValue(Object element, Object value) {
}
});
col.setLabelProvider(new AlternatingColumnProvider() {
public String getText(Object element) {
return ((AllDayTaskEntry) element).getExternalId();
}
public Image getImage(Object obj) {
return null;
}
@Override
public Color getBackground(Object element) {
if (storageService.isDue(((AllDayTaskEntry)element)) != null)
return viewer.getTable().getDisplay().getSystemColor(SWT.COLOR_RED);
return super.getBackground(element);
}
@Override
public String getToolTipText(Object element) {
return storageService.isDue(((AllDayTaskEntry)element));
}
});
}
abstract class DateDialogCellEditor extends DialogCellEditor {
private AllDayTaskEntry entry;
/**
* @param parent
*/
public DateDialogCellEditor(Composite parent, AllDayTaskEntry entry) {
super(parent);
this.entry = entry;
}
@Override
protected Object openDialogBox(Control cellEditorWindow) {
AllDayTaskDateDialog dateDialog = getDateDialog(cellEditorWindow, entry);
if (dateDialog.open() == Dialog.OK) {
Date date = dateDialog.getDate();
if (getDate(entry).after(date) || getDate(entry).before(date)) {
setDate(entry, new Timestamp(date.getTime()));
entry.setSyncStatus(false);
storageService.updateAllDayTaskEntry(entry);
storageService.synchronizeAllDayTaskEntries();
if (entry.isSyncStatus()) viewer.refresh(entry);
}
return DateFormat.getDateInstance(DateFormat.SHORT).format(dateDialog.getDate());
}
return null;
}
protected abstract AllDayTaskDateDialog getDateDialog(Control cellEditorWindow, AllDayTaskEntry entry);
protected abstract Date getDate(AllDayTaskEntry entry);
protected abstract void setDate(AllDayTaskEntry entry, Timestamp date);
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (StorageService.PROPERTY_ALLDAYTASK.equals(evt.getPropertyName()) && evt.getNewValue() != null) {
if (addTaskEntries()) viewer.refresh();
}
}
@Override
protected void createPartBeforeViewer(Composite parent) {
}
@Override
protected boolean getConditionForDarkGrey(Object element) {
return false;
}
protected Integer getRequestedDays(Object element) {
Task vacationPlanningTask = TimesheetApp.createTask(AllDayTaskService.PREFIX + AllDayTaskService.VACATION_PLANNING_TASK);
Task vacationTask = TimesheetApp.createTask(AllDayTaskService.PREFIX + AllDayTaskService.VACATION_TASK);
AllDayTaskEntry entry = (AllDayTaskEntry) element;
if (vacationPlanningTask.getName().equals(entry.getTask().getName())
|| vacationTask.getName().equals(entry.getTask().getName()))
return BusinessDayUtil.getRequestedDays(((AllDayTaskEntry) element).getFrom(), ((AllDayTaskEntry) element).getTo());
return null;
}
class AllDayTaskListDialogCellEditor extends DialogCellEditor {
private AllDayTaskEntry entry;
/**
* @param parent
*/
public AllDayTaskListDialogCellEditor(Composite parent, AllDayTaskEntry entry) {
super(parent);
this.entry = entry;
}
@Override
protected Object openDialogBox(Control cellEditorWindow) {
TaskListDialog listDialog;
String system = TimesheetApp.getDescriptiveName(Activator.getDefault().getPreferenceStore().getString(AllDayTaskService.PROPERTY),
AllDayTaskService.SERVICE_NAME);
if (system.equals(entry.getTask().getProject().getSystem()))
listDialog = new ExternalAllDayTaskListDialog(cellEditorWindow.getShell(), entry.getTask());
else
listDialog = new InternalAllDayTaskListDialog(cellEditorWindow.getShell(), entry.getTask());
if (listDialog.open() == Dialog.OK) {
String selectedTask = Arrays.toString(listDialog.getResult());
selectedTask = selectedTask.substring(selectedTask.indexOf("[") + 1, selectedTask.indexOf("]"));
if (StringUtils.isEmpty(selectedTask)) return null;
if (!selectedTask.equals(entry.getTask().getName())) {
entry.setTask(storageService.findTaskByNameProjectAndSystem(selectedTask, listDialog.getProject(), listDialog.getSystem()));
entry.setSyncStatus(false);
storageService.updateAllDayTaskEntry(entry);
storageService.synchronizeAllDayTaskEntries();
if (entry.isSyncStatus()) viewer.refresh(entry);
return selectedTask;
}
}
return null;
}
}
class ExternalTaskDialogCellEditor extends DialogCellEditor {
private AllDayTaskEntry entry;
public ExternalTaskDialogCellEditor(Composite parent, AllDayTaskEntry entry) {
super(parent);
this.entry = entry;
}
@Override
protected Object openDialogBox(Control cellEditorWindow) {
LocalStorageService.getAllDayTaskService().openUrl(entry);
return entry.getExternalId();
}
}
}
| true | true | protected void createColumns(final Composite parent, final TableViewer viewer) {
final Map<String, Integer> allDayTaskIndex = new HashMap<String, Integer>();
int i = 0;
final List<String> allDayTasks = new ArrayList<String>(storageService.getAllDayTasks());
for(String allDayTask : allDayTasks)
allDayTaskIndex.put(allDayTask, i++);
String[] titles = { "From", "To", "Requested", "Task", "Project", "Issue Key" };
int[] bounds = { 80, 80, 70, 150, 150, 70 };
int colNum = 0;
// First column is for the from date
TableViewerColumn col = createTableViewerColumn(titles[colNum], bounds[colNum], colNum++);
col.setEditingSupport(new EditingSupport(viewer) {
protected boolean canEdit(Object element) {
return true;
}
protected CellEditor getCellEditor(Object element) {
return new DateDialogCellEditor(viewer.getTable(), (AllDayTaskEntry) element) {
@Override
protected AllDayTaskDateDialog getDateDialog(Control cellEditorWindow, AllDayTaskEntry entry) {
return new StartAllDayTaskDateDialog(cellEditorWindow.getDisplay(), "Set start date", entry.getFrom(), entry.getTo(), entry.getId());
}
@Override
protected Date getDate(AllDayTaskEntry entry) {
return entry.getFrom();
}
@Override
protected void setDate(AllDayTaskEntry entry, Timestamp date) {
entry.setFrom(date);
}
};
}
protected Object getValue(Object element) {
return DateFormat.getDateInstance(DateFormat.SHORT).format(((AllDayTaskEntry) element).getFrom());
}
protected void setValue(Object element, Object value) {
}
});
col.setLabelProvider(new AlternatingColumnProvider() {
public String getText(Object element) {
Timestamp date = ((AllDayTaskEntry) element).getFrom();
return DateFormat.getDateInstance(DateFormat.SHORT).format(date);
}
public Image getImage(Object obj) {
return AbstractUIPlugin.imageDescriptorFromPlugin("com.uwusoft.timesheet", "/icons/date.png").createImage();
}
});
// Second column is for the to date
col = createTableViewerColumn(titles[colNum], bounds[colNum], colNum++);
col.setEditingSupport(new EditingSupport(viewer) {
protected boolean canEdit(Object element) {
return true;
}
protected CellEditor getCellEditor(Object element) {
return new DateDialogCellEditor(viewer.getTable(), (AllDayTaskEntry) element) {
@Override
protected AllDayTaskDateDialog getDateDialog(Control cellEditorWindow, AllDayTaskEntry entry) {
return new EndAllDayTaskDateDialog(cellEditorWindow.getDisplay(), "Set end date", entry.getFrom(), entry.getTo(), entry.getId());
}
@Override
protected Date getDate(AllDayTaskEntry entry) {
return entry.getTo();
}
@Override
protected void setDate(AllDayTaskEntry entry, Timestamp date) {
entry.setTo(date);
}
};
}
protected Object getValue(Object element) {
return DateFormat.getDateInstance(DateFormat.SHORT).format(((AllDayTaskEntry) element).getTo());
}
protected void setValue(Object element, Object value) {
}
});
col.setLabelProvider(new AlternatingColumnProvider() {
public String getText(Object element) {
Timestamp date = ((AllDayTaskEntry) element).getTo();
return DateFormat.getDateInstance(DateFormat.SHORT).format(date);
}
public Image getImage(Object obj) {
return AbstractUIPlugin.imageDescriptorFromPlugin("com.uwusoft.timesheet", "/icons/date.png").createImage();
}
});
// Third column is for the requested
col = createTableViewerColumn(titles[colNum], bounds[colNum], colNum++);
col.setEditingSupport(new EditingSupport(viewer) {
protected boolean canEdit(Object element) {
return false;
}
protected CellEditor getCellEditor(Object element) {
return null;
}
protected Object getValue(Object element) {
return getRequestedDays(element);
}
protected void setValue(Object element, Object value) {
}
});
col.setLabelProvider(new AlternatingColumnProvider() {
public String getText(Object element) {
Integer requestedDays = getRequestedDays(element);
if (requestedDays != null) return requestedDays.toString();
return null;
}
public Image getImage(Object obj) {
return null;
}
});
// Fourth column is for the task
col = createTableViewerColumn(titles[colNum], bounds[colNum], colNum++);
col.setEditingSupport(new EditingSupport(viewer) {
protected boolean canEdit(Object element) {
return true;
}
protected CellEditor getCellEditor(Object element) {
return new AllDayTaskListDialogCellEditor(viewer.getTable(), (AllDayTaskEntry) element);
}
protected Object getValue(Object element) {
return ((AllDayTaskEntry) element).getTask().getName();
}
protected void setValue(Object element, Object value) {
}
});
col.setLabelProvider(new AlternatingColumnProvider() {
public String getText(Object element) {
return ((AllDayTaskEntry) element).getTask().getName();
}
public Image getImage(Object obj) {
return AbstractUIPlugin.imageDescriptorFromPlugin("com.uwusoft.timesheet", "/icons/task_16.png").createImage();
}
});
// Fifth column is for the project
col = createTableViewerColumn(titles[colNum], bounds[colNum], colNum++);
col.setEditingSupport(new EditingSupport(viewer) {
protected boolean canEdit(Object element) {
return false;
}
protected CellEditor getCellEditor(Object element) {
return null;
}
protected Object getValue(Object element) {
return ((AllDayTaskEntry) element).getTask().getProject().getName();
}
protected void setValue(Object element, Object value) {
}
});
col.setLabelProvider(new AlternatingColumnProvider() {
public String getText(Object element) {
return ((AllDayTaskEntry) element).getTask().getProject().getName();
}
public Image getImage(Object obj) {
return AbstractUIPlugin.imageDescriptorFromPlugin("com.uwusoft.timesheet", "/icons/task_16.png").createImage();
}
});
// Sixth column is for the issue key
col = createTableViewerColumn(titles[colNum], bounds[colNum], colNum++);
col.setEditingSupport(new EditingSupport(viewer) {
protected boolean canEdit(Object element) {
return !StringUtils.isEmpty(((AllDayTaskEntry) element).getExternalId());
}
protected CellEditor getCellEditor(Object element) {
return new ExternalTaskDialogCellEditor(viewer.getTable(), (AllDayTaskEntry) element);
}
protected Object getValue(Object element) {
return ((AllDayTaskEntry) element).getExternalId();
}
protected void setValue(Object element, Object value) {
}
});
col.setLabelProvider(new AlternatingColumnProvider() {
public String getText(Object element) {
return ((AllDayTaskEntry) element).getExternalId();
}
public Image getImage(Object obj) {
return null;
}
@Override
public Color getBackground(Object element) {
if (storageService.isDue(((AllDayTaskEntry)element)) != null)
return viewer.getTable().getDisplay().getSystemColor(SWT.COLOR_RED);
return super.getBackground(element);
}
@Override
public String getToolTipText(Object element) {
return storageService.isDue(((AllDayTaskEntry)element));
}
});
}
| protected void createColumns(final Composite parent, final TableViewer viewer) {
final Map<String, Integer> allDayTaskIndex = new HashMap<String, Integer>();
int i = 0;
final List<String> allDayTasks = new ArrayList<String>(storageService.getAllDayTasks());
for(String allDayTask : allDayTasks)
allDayTaskIndex.put(allDayTask, i++);
String[] titles = { "From", "To", "Requested", "Task", "Project", "Issue Key" };
int[] bounds = { 80, 80, 70, 150, 150, 70 };
int colNum = 0;
// First column is for the from date
TableViewerColumn col = createTableViewerColumn(titles[colNum], bounds[colNum], colNum++);
col.setEditingSupport(new EditingSupport(viewer) {
protected boolean canEdit(Object element) {
return true;
}
protected CellEditor getCellEditor(Object element) {
return new DateDialogCellEditor(viewer.getTable(), (AllDayTaskEntry) element) {
@Override
protected AllDayTaskDateDialog getDateDialog(Control cellEditorWindow, AllDayTaskEntry entry) {
return new StartAllDayTaskDateDialog(cellEditorWindow.getDisplay(), "Set start date", entry.getFrom(), entry.getTo(), entry.getId());
}
@Override
protected Date getDate(AllDayTaskEntry entry) {
return entry.getFrom();
}
@Override
protected void setDate(AllDayTaskEntry entry, Timestamp date) {
entry.setFrom(date);
}
};
}
protected Object getValue(Object element) {
return DateFormat.getDateInstance(DateFormat.SHORT).format(((AllDayTaskEntry) element).getFrom());
}
protected void setValue(Object element, Object value) {
}
});
col.setLabelProvider(new AlternatingColumnProvider() {
public String getText(Object element) {
Timestamp date = ((AllDayTaskEntry) element).getFrom();
return DateFormat.getDateInstance(DateFormat.SHORT).format(date);
}
public Image getImage(Object obj) {
return AbstractUIPlugin.imageDescriptorFromPlugin("com.uwusoft.timesheet", "/icons/date.png").createImage();
}
});
// Second column is for the to date
col = createTableViewerColumn(titles[colNum], bounds[colNum], colNum++);
col.setEditingSupport(new EditingSupport(viewer) {
protected boolean canEdit(Object element) {
return true;
}
protected CellEditor getCellEditor(Object element) {
return new DateDialogCellEditor(viewer.getTable(), (AllDayTaskEntry) element) {
@Override
protected AllDayTaskDateDialog getDateDialog(Control cellEditorWindow, AllDayTaskEntry entry) {
return new EndAllDayTaskDateDialog(cellEditorWindow.getDisplay(), "Set end date", entry.getFrom(), entry.getTo(), entry.getId());
}
@Override
protected Date getDate(AllDayTaskEntry entry) {
return entry.getTo();
}
@Override
protected void setDate(AllDayTaskEntry entry, Timestamp date) {
entry.setTo(date);
}
};
}
protected Object getValue(Object element) {
return DateFormat.getDateInstance(DateFormat.SHORT).format(((AllDayTaskEntry) element).getTo());
}
protected void setValue(Object element, Object value) {
}
});
col.setLabelProvider(new AlternatingColumnProvider() {
public String getText(Object element) {
Timestamp date = ((AllDayTaskEntry) element).getTo();
return DateFormat.getDateInstance(DateFormat.SHORT).format(date);
}
public Image getImage(Object obj) {
return AbstractUIPlugin.imageDescriptorFromPlugin("com.uwusoft.timesheet", "/icons/date.png").createImage();
}
});
// Third column is for the requested
col = createTableViewerColumn(titles[colNum], bounds[colNum], colNum++);
col.setEditingSupport(new EditingSupport(viewer) {
protected boolean canEdit(Object element) {
return false;
}
protected CellEditor getCellEditor(Object element) {
return null;
}
protected Object getValue(Object element) {
return getRequestedDays(element);
}
protected void setValue(Object element, Object value) {
}
});
col.setLabelProvider(new AlternatingColumnProvider() {
public String getText(Object element) {
Integer requestedDays = getRequestedDays(element);
if (requestedDays != null) return requestedDays.toString();
return null;
}
public Image getImage(Object obj) {
return null;
}
});
// Fourth column is for the task
col = createTableViewerColumn(titles[colNum], bounds[colNum], colNum++);
col.setEditingSupport(new EditingSupport(viewer) {
protected boolean canEdit(Object element) {
return true;
}
protected CellEditor getCellEditor(Object element) {
return new AllDayTaskListDialogCellEditor(viewer.getTable(), (AllDayTaskEntry) element);
}
protected Object getValue(Object element) {
return ((AllDayTaskEntry) element).getTask().getName();
}
protected void setValue(Object element, Object value) {
}
});
col.setLabelProvider(new AlternatingColumnProvider() {
public String getText(Object element) {
return ((AllDayTaskEntry) element).getTask().getName();
}
public Image getImage(Object obj) {
if (((AllDayTaskEntry) obj).getTask().equals(TimesheetApp.createTask(AllDayTaskService.PREFIX + AllDayTaskService.VACATION_TASK)))
return AbstractUIPlugin.imageDescriptorFromPlugin("com.uwusoft.timesheet", "/icons/vacation_16.gif").createImage();
return AbstractUIPlugin.imageDescriptorFromPlugin("com.uwusoft.timesheet", "/icons/genericissue_16.gif").createImage();
}
});
// Fifth column is for the project
col = createTableViewerColumn(titles[colNum], bounds[colNum], colNum++);
col.setEditingSupport(new EditingSupport(viewer) {
protected boolean canEdit(Object element) {
return false;
}
protected CellEditor getCellEditor(Object element) {
return null;
}
protected Object getValue(Object element) {
return ((AllDayTaskEntry) element).getTask().getProject().getName();
}
protected void setValue(Object element, Object value) {
}
});
col.setLabelProvider(new AlternatingColumnProvider() {
public String getText(Object element) {
return ((AllDayTaskEntry) element).getTask().getProject().getName();
}
public Image getImage(Object obj) {
return AbstractUIPlugin.imageDescriptorFromPlugin("com.uwusoft.timesheet", "/icons/task_16.png").createImage();
}
});
// Sixth column is for the issue key
col = createTableViewerColumn(titles[colNum], bounds[colNum], colNum++);
col.setEditingSupport(new EditingSupport(viewer) {
protected boolean canEdit(Object element) {
return !StringUtils.isEmpty(((AllDayTaskEntry) element).getExternalId());
}
protected CellEditor getCellEditor(Object element) {
return new ExternalTaskDialogCellEditor(viewer.getTable(), (AllDayTaskEntry) element);
}
protected Object getValue(Object element) {
return ((AllDayTaskEntry) element).getExternalId();
}
protected void setValue(Object element, Object value) {
}
});
col.setLabelProvider(new AlternatingColumnProvider() {
public String getText(Object element) {
return ((AllDayTaskEntry) element).getExternalId();
}
public Image getImage(Object obj) {
return null;
}
@Override
public Color getBackground(Object element) {
if (storageService.isDue(((AllDayTaskEntry)element)) != null)
return viewer.getTable().getDisplay().getSystemColor(SWT.COLOR_RED);
return super.getBackground(element);
}
@Override
public String getToolTipText(Object element) {
return storageService.isDue(((AllDayTaskEntry)element));
}
});
}
|
diff --git a/src/org/intellij/erlang/inspection/ErlangIoFormatInspection.java b/src/org/intellij/erlang/inspection/ErlangIoFormatInspection.java
index 368375ca..7dc81c40 100644
--- a/src/org/intellij/erlang/inspection/ErlangIoFormatInspection.java
+++ b/src/org/intellij/erlang/inspection/ErlangIoFormatInspection.java
@@ -1,112 +1,113 @@
/*
* Copyright 2013 Sergey Ignatov
*
* 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.
*/
/*
* Copyright 2013 Sergey Ignatov
*
* 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.intellij.erlang.inspection;
import com.intellij.codeInspection.ProblemsHolder;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiReference;
import com.intellij.util.containers.ContainerUtil;
import org.intellij.erlang.psi.*;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.Set;
/**
* @author ignatov
*/
public class ErlangIoFormatInspection extends ErlangBaseInspection {
Set<String> MODULE_NAMES = ContainerUtil.set("io", "io_lib");
Set<String> FUNCTION_NAMES = ContainerUtil.set("format", "fwrite");
@Override
protected void checkFile(PsiFile file, final ProblemsHolder problemsHolder) {
if (!(file instanceof ErlangFile)) return;
file.accept(new ErlangRecursiveVisitor() {
@Override
public void visitGlobalFunctionCallExpression(@NotNull ErlangGlobalFunctionCallExpression o) {
ErlangFunctionCallExpression expression = o.getFunctionCallExpression();
List<ErlangExpression> expressionList = expression.getArgumentList().getExpressionList();
int size = expressionList.size();
if (size < 2) return;
ErlangModuleRef moduleRef = o.getModuleRef();
PsiReference moduleReference = moduleRef != null ? moduleRef.getReference() : null;
PsiElement resolve = moduleReference != null ? moduleReference.resolve() : null;
if (resolve instanceof ErlangModule) {
if (MODULE_NAMES.contains(((ErlangModule) resolve).getName())) {
PsiReference reference = expression.getReference();
PsiElement function = reference != null ? reference.resolve() : null;
if (function instanceof ErlangFunction) {
if (FUNCTION_NAMES.contains(((ErlangFunction) function).getName())) {
List<ErlangExpression> reverse = ContainerUtil.reverse(expressionList);
ErlangExpression args = reverse.get(0);
ErlangExpression str = reverse.get(1);
int strLen = str.getText().length();
if (args instanceof ErlangListExpression) {
- if (str instanceof ErlangMaxExpression && strLen >= 2) {
+ if (str instanceof ErlangStringLiteral && strLen >= 2) {
String substring = str.getText().substring(1, strLen - 1);
// todo: rewrite, see: http://www.erlang.org/doc/man/io.html#format-1
int doubleCount = StringUtil.getOccurrenceCount(substring, "~~");
int newLineCount = StringUtil.getOccurrenceCount(substring, "~n");
int occurrenceCount = StringUtil.getOccurrenceCount(substring, "~");
int totalCount = occurrenceCount - doubleCount * 2 - newLineCount;
- if (totalCount != ((ErlangListExpression) args).getExpressionList().size()) {
- problemsHolder.registerProblem(str, "Wrong number of arguments in format call, should be " + totalCount);
+ int agrSize = ((ErlangListExpression) args).getExpressionList().size();
+ if (totalCount != agrSize) {
+ problemsHolder.registerProblem(str, "Wrong number of arguments in format call, should be " + agrSize);
}
}
else {
problemsHolder.registerProblem(str, "Should be a string");
}
}
else {
problemsHolder.registerProblem(args, "Format arguments not a list");
}
}
}
}
}
}
});
}
}
| false | true | protected void checkFile(PsiFile file, final ProblemsHolder problemsHolder) {
if (!(file instanceof ErlangFile)) return;
file.accept(new ErlangRecursiveVisitor() {
@Override
public void visitGlobalFunctionCallExpression(@NotNull ErlangGlobalFunctionCallExpression o) {
ErlangFunctionCallExpression expression = o.getFunctionCallExpression();
List<ErlangExpression> expressionList = expression.getArgumentList().getExpressionList();
int size = expressionList.size();
if (size < 2) return;
ErlangModuleRef moduleRef = o.getModuleRef();
PsiReference moduleReference = moduleRef != null ? moduleRef.getReference() : null;
PsiElement resolve = moduleReference != null ? moduleReference.resolve() : null;
if (resolve instanceof ErlangModule) {
if (MODULE_NAMES.contains(((ErlangModule) resolve).getName())) {
PsiReference reference = expression.getReference();
PsiElement function = reference != null ? reference.resolve() : null;
if (function instanceof ErlangFunction) {
if (FUNCTION_NAMES.contains(((ErlangFunction) function).getName())) {
List<ErlangExpression> reverse = ContainerUtil.reverse(expressionList);
ErlangExpression args = reverse.get(0);
ErlangExpression str = reverse.get(1);
int strLen = str.getText().length();
if (args instanceof ErlangListExpression) {
if (str instanceof ErlangMaxExpression && strLen >= 2) {
String substring = str.getText().substring(1, strLen - 1);
// todo: rewrite, see: http://www.erlang.org/doc/man/io.html#format-1
int doubleCount = StringUtil.getOccurrenceCount(substring, "~~");
int newLineCount = StringUtil.getOccurrenceCount(substring, "~n");
int occurrenceCount = StringUtil.getOccurrenceCount(substring, "~");
int totalCount = occurrenceCount - doubleCount * 2 - newLineCount;
if (totalCount != ((ErlangListExpression) args).getExpressionList().size()) {
problemsHolder.registerProblem(str, "Wrong number of arguments in format call, should be " + totalCount);
}
}
else {
problemsHolder.registerProblem(str, "Should be a string");
}
}
else {
problemsHolder.registerProblem(args, "Format arguments not a list");
}
}
}
}
}
}
});
}
| protected void checkFile(PsiFile file, final ProblemsHolder problemsHolder) {
if (!(file instanceof ErlangFile)) return;
file.accept(new ErlangRecursiveVisitor() {
@Override
public void visitGlobalFunctionCallExpression(@NotNull ErlangGlobalFunctionCallExpression o) {
ErlangFunctionCallExpression expression = o.getFunctionCallExpression();
List<ErlangExpression> expressionList = expression.getArgumentList().getExpressionList();
int size = expressionList.size();
if (size < 2) return;
ErlangModuleRef moduleRef = o.getModuleRef();
PsiReference moduleReference = moduleRef != null ? moduleRef.getReference() : null;
PsiElement resolve = moduleReference != null ? moduleReference.resolve() : null;
if (resolve instanceof ErlangModule) {
if (MODULE_NAMES.contains(((ErlangModule) resolve).getName())) {
PsiReference reference = expression.getReference();
PsiElement function = reference != null ? reference.resolve() : null;
if (function instanceof ErlangFunction) {
if (FUNCTION_NAMES.contains(((ErlangFunction) function).getName())) {
List<ErlangExpression> reverse = ContainerUtil.reverse(expressionList);
ErlangExpression args = reverse.get(0);
ErlangExpression str = reverse.get(1);
int strLen = str.getText().length();
if (args instanceof ErlangListExpression) {
if (str instanceof ErlangStringLiteral && strLen >= 2) {
String substring = str.getText().substring(1, strLen - 1);
// todo: rewrite, see: http://www.erlang.org/doc/man/io.html#format-1
int doubleCount = StringUtil.getOccurrenceCount(substring, "~~");
int newLineCount = StringUtil.getOccurrenceCount(substring, "~n");
int occurrenceCount = StringUtil.getOccurrenceCount(substring, "~");
int totalCount = occurrenceCount - doubleCount * 2 - newLineCount;
int agrSize = ((ErlangListExpression) args).getExpressionList().size();
if (totalCount != agrSize) {
problemsHolder.registerProblem(str, "Wrong number of arguments in format call, should be " + agrSize);
}
}
else {
problemsHolder.registerProblem(str, "Should be a string");
}
}
else {
problemsHolder.registerProblem(args, "Format arguments not a list");
}
}
}
}
}
}
});
}
|
diff --git a/JunkHub/src/edu/unsw/triangle/web/SellFormController.java b/JunkHub/src/edu/unsw/triangle/web/SellFormController.java
index 4c44b15..8a3630c 100644
--- a/JunkHub/src/edu/unsw/triangle/web/SellFormController.java
+++ b/JunkHub/src/edu/unsw/triangle/web/SellFormController.java
@@ -1,87 +1,87 @@
package edu.unsw.triangle.web;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import edu.unsw.triangle.controller.AbstractFormController;
import edu.unsw.triangle.controller.ModelView;
import edu.unsw.triangle.model.Item;
import edu.unsw.triangle.service.ItemService;
import edu.unsw.triangle.util.Errors;
import edu.unsw.triangle.util.ItemValidator;
import edu.unsw.triangle.util.Messages;
import edu.unsw.triangle.util.Validator;
import edu.unsw.triangle.view.ItemBinder;
import edu.unsw.triangle.view.RequestBinder;
public class SellFormController extends AbstractFormController
{
private final Logger logger = Logger.getLogger(SellFormController.class.getName());
@Override
public String getFormView()
{
return "sell.view";
}
@Override
protected Object createBackingObject(HttpServletRequest request)
{
// TODO Auto-generated method stub
return null;
}
@Override
protected ModelView handleFormSubmit(Object command)
{
Item item = (Item) command;
ModelView modelView = null;
// Service operations here
try
{
ItemService.addNewItem(item);
// Success message
Messages message = new Messages();
- message.add("sell.success", "item is saved");
+ message.add("sell.success", "item \"" + item.getTitle() + "\" is now listed");
modelView = new ModelView(getSuccessView()).addModel("messages", message);
}
catch (Exception e)
{
logger.warning("cannot add new item to repository reason: " + e.getMessage());
e.printStackTrace();
Errors errors = new Errors().rejectValue("sell.error", "cannot add new item to repository");
modelView = handleFormError(command, errors);
}
return modelView;
}
@Override
protected Validator getValidator()
{
return new ItemValidator();
}
@Override
protected RequestBinder getBinder()
{
return new ItemBinder();
}
@Override
protected String getSuccessView()
{
return "sell.confirm.view";
}
@Override
protected ModelView handleFormError(Object command, Errors errors)
{
ModelView modelView = new ModelView(getFormView()).forward().
addModel("item", command).addModel("errors", errors);
return modelView;
}
}
| true | true | protected ModelView handleFormSubmit(Object command)
{
Item item = (Item) command;
ModelView modelView = null;
// Service operations here
try
{
ItemService.addNewItem(item);
// Success message
Messages message = new Messages();
message.add("sell.success", "item is saved");
modelView = new ModelView(getSuccessView()).addModel("messages", message);
}
catch (Exception e)
{
logger.warning("cannot add new item to repository reason: " + e.getMessage());
e.printStackTrace();
Errors errors = new Errors().rejectValue("sell.error", "cannot add new item to repository");
modelView = handleFormError(command, errors);
}
return modelView;
}
| protected ModelView handleFormSubmit(Object command)
{
Item item = (Item) command;
ModelView modelView = null;
// Service operations here
try
{
ItemService.addNewItem(item);
// Success message
Messages message = new Messages();
message.add("sell.success", "item \"" + item.getTitle() + "\" is now listed");
modelView = new ModelView(getSuccessView()).addModel("messages", message);
}
catch (Exception e)
{
logger.warning("cannot add new item to repository reason: " + e.getMessage());
e.printStackTrace();
Errors errors = new Errors().rejectValue("sell.error", "cannot add new item to repository");
modelView = handleFormError(command, errors);
}
return modelView;
}
|
diff --git a/src/contrib/streaming/src/java/org/apache/hadoop/streaming/StreamKeyValUtil.java b/src/contrib/streaming/src/java/org/apache/hadoop/streaming/StreamKeyValUtil.java
index 4d575180bb..75e05dc070 100644
--- a/src/contrib/streaming/src/java/org/apache/hadoop/streaming/StreamKeyValUtil.java
+++ b/src/contrib/streaming/src/java/org/apache/hadoop/streaming/StreamKeyValUtil.java
@@ -1,141 +1,137 @@
/**
* 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.hadoop.streaming;
import java.io.IOException;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.util.LineReader;
public class StreamKeyValUtil {
/**
* Find the first occured tab in a UTF-8 encoded string
* @param utf a byte array containing a UTF-8 encoded string
* @param start starting offset
* @param length no. of bytes
* @return position that first tab occures otherwise -1
*/
public static int findTab(byte [] utf, int start, int length) {
for(int i=start; i<(start+length); i++) {
if (utf[i]==(byte)'\t') {
return i;
}
}
return -1;
}
/**
* Find the first occured tab in a UTF-8 encoded string
* @param utf a byte array containing a UTF-8 encoded string
* @return position that first tab occures otherwise -1
*/
public static int findTab(byte [] utf) {
return org.apache.hadoop.util.UTF8ByteArrayUtils.findNthByte(utf, 0,
utf.length, (byte)'\t', 1);
}
/**
* split a UTF-8 byte array into key and value
* assuming that the delimilator is at splitpos.
* @param utf utf-8 encoded string
* @param start starting offset
* @param length no. of bytes
* @param key contains key upon the method is returned
* @param val contains value upon the method is returned
* @param splitPos the split pos
* @param separatorLength the length of the separator between key and value
* @throws IOException
*/
public static void splitKeyVal(byte[] utf, int start, int length,
Text key, Text val, int splitPos,
int separatorLength) throws IOException {
if (splitPos<start || splitPos >= (start+length))
throw new IllegalArgumentException("splitPos must be in the range " +
"[" + start + ", " + (start+length) + "]: " + splitPos);
int keyLen = (splitPos-start);
- byte [] keyBytes = new byte[keyLen];
- System.arraycopy(utf, start, keyBytes, 0, keyLen);
int valLen = (start+length)-splitPos-separatorLength;
- byte [] valBytes = new byte[valLen];
- System.arraycopy(utf, splitPos+separatorLength, valBytes, 0, valLen);
- key.set(keyBytes);
- val.set(valBytes);
+ key.set(utf, start, keyLen);
+ val.set(utf, splitPos+separatorLength, valLen);
}
/**
* split a UTF-8 byte array into key and value
* assuming that the delimilator is at splitpos.
* @param utf utf-8 encoded string
* @param start starting offset
* @param length no. of bytes
* @param key contains key upon the method is returned
* @param val contains value upon the method is returned
* @param splitPos the split pos
* @throws IOException
*/
public static void splitKeyVal(byte[] utf, int start, int length,
Text key, Text val, int splitPos) throws IOException {
splitKeyVal(utf, start, length, key, val, splitPos, 1);
}
/**
* split a UTF-8 byte array into key and value
* assuming that the delimilator is at splitpos.
* @param utf utf-8 encoded string
* @param key contains key upon the method is returned
* @param val contains value upon the method is returned
* @param splitPos the split pos
* @param separatorLength the length of the separator between key and value
* @throws IOException
*/
public static void splitKeyVal(byte[] utf, Text key, Text val, int splitPos,
int separatorLength)
throws IOException {
splitKeyVal(utf, 0, utf.length, key, val, splitPos, separatorLength);
}
/**
* split a UTF-8 byte array into key and value
* assuming that the delimilator is at splitpos.
* @param utf utf-8 encoded string
* @param key contains key upon the method is returned
* @param val contains value upon the method is returned
* @param splitPos the split pos
* @throws IOException
*/
public static void splitKeyVal(byte[] utf, Text key, Text val, int splitPos)
throws IOException {
splitKeyVal(utf, 0, utf.length, key, val, splitPos, 1);
}
/**
* Read a utf8 encoded line from a data input stream.
* @param lineReader LineReader to read the line from.
* @param out Text to read into
* @return number of bytes read
* @throws IOException
*/
public static int readLine(LineReader lineReader, Text out)
throws IOException {
out.clear();
return lineReader.readLine(out);
}
}
| false | true | public static void splitKeyVal(byte[] utf, int start, int length,
Text key, Text val, int splitPos,
int separatorLength) throws IOException {
if (splitPos<start || splitPos >= (start+length))
throw new IllegalArgumentException("splitPos must be in the range " +
"[" + start + ", " + (start+length) + "]: " + splitPos);
int keyLen = (splitPos-start);
byte [] keyBytes = new byte[keyLen];
System.arraycopy(utf, start, keyBytes, 0, keyLen);
int valLen = (start+length)-splitPos-separatorLength;
byte [] valBytes = new byte[valLen];
System.arraycopy(utf, splitPos+separatorLength, valBytes, 0, valLen);
key.set(keyBytes);
val.set(valBytes);
}
| public static void splitKeyVal(byte[] utf, int start, int length,
Text key, Text val, int splitPos,
int separatorLength) throws IOException {
if (splitPos<start || splitPos >= (start+length))
throw new IllegalArgumentException("splitPos must be in the range " +
"[" + start + ", " + (start+length) + "]: " + splitPos);
int keyLen = (splitPos-start);
int valLen = (start+length)-splitPos-separatorLength;
key.set(utf, start, keyLen);
val.set(utf, splitPos+separatorLength, valLen);
}
|
diff --git a/src/carnero/cgeo/cgeotrackable.java b/src/carnero/cgeo/cgeotrackable.java
index 1109f41..e2aabc1 100644
--- a/src/carnero/cgeo/cgeotrackable.java
+++ b/src/carnero/cgeo/cgeotrackable.java
@@ -1,437 +1,437 @@
package carnero.cgeo;
import java.net.URLEncoder;
import java.util.HashMap;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.util.Log;
import android.app.Activity;
import android.app.ProgressDialog;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.view.LayoutInflater;
import android.widget.ScrollView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.view.SubMenu;
import android.widget.ImageView;
public class cgeotrackable extends Activity {
public cgTrackable trackable = null;
public String geocode = null;
public String name = null;
public String guid = null;
private Resources res = null;
private cgeoapplication app = null;
private Activity activity = null;
private LayoutInflater inflater = null;
private cgSettings settings = null;
private cgBase base = null;
private cgWarning warning = null;
private ProgressDialog waitDialog = null;
private Handler loadTrackableHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
RelativeLayout itemLayout;
TextView itemName;
TextView itemValue;
if (trackable != null && trackable.errorRetrieve != 0) {
warning.showToast(res.getString(R.string.err_tb_details_download) + " " + base.errorRetrieve.get(trackable.errorRetrieve) + ".");
finish();
return;
}
if (trackable != null && trackable.error.length() > 0) {
warning.showToast(res.getString(R.string.err_tb_details_download) + " " + trackable.error + ".");
finish();
return;
}
if (trackable == null) {
if (waitDialog != null) {
waitDialog.dismiss();
}
if (geocode != null && geocode.length() > 0) {
warning.showToast(res.getString(R.string.err_tb_find) + " " + geocode + ".");
} else {
warning.showToast(res.getString(R.string.err_tb_find_that));
}
finish();
return;
}
try {
inflater = activity.getLayoutInflater();
geocode = trackable.geocode.toUpperCase();
if (trackable.name != null && trackable.name.length() > 0) {
base.setTitle(activity, Html.fromHtml(trackable.name).toString());
} else {
base.setTitle(activity, trackable.name.toUpperCase());
}
((ScrollView) findViewById(R.id.details_list_box)).setVisibility(View.VISIBLE);
LinearLayout detailsList = (LinearLayout) findViewById(R.id.details_list);
// trackable geocode
itemLayout = (RelativeLayout)inflater.inflate(R.layout.cache_item, null);
itemName = (TextView) itemLayout.findViewById(R.id.name);
itemValue = (TextView) itemLayout.findViewById(R.id.value);
itemName.setText(res.getString(R.string.trackable_code));
itemValue.setText(trackable.geocode.toUpperCase());
detailsList.addView(itemLayout);
// trackable name
itemLayout = (RelativeLayout)inflater.inflate(R.layout.cache_item, null);
itemName = (TextView) itemLayout.findViewById(R.id.name);
itemValue = (TextView) itemLayout.findViewById(R.id.value);
itemName.setText(res.getString(R.string.trackable_name));
if (trackable.name != null) {
itemValue.setText(Html.fromHtml(trackable.name), TextView.BufferType.SPANNABLE);
} else {
itemValue.setText(res.getString(R.string.trackable_unknown));
}
detailsList.addView(itemLayout);
/* disabled by YraFyra, not used
// trackable type
itemLayout = (RelativeLayout)inflater.inflate(R.layout.cache_item, null);
itemName = (TextView) itemLayout.findViewById(R.id.name);
itemValue = (TextView) itemLayout.findViewById(R.id.value);
itemName.setText(res.getString(R.string.trackable_type));
if (trackable.type != null) {
itemValue.setText(Html.fromHtml(trackable.type), TextView.BufferType.SPANNABLE);
} else {
itemValue.setText(res.getString(R.string.trackable_unknown));
}
detailsList.addView(itemLayout);
*/
// trackable owner
itemLayout = (RelativeLayout)inflater.inflate(R.layout.cache_item, null);
itemName = (TextView) itemLayout.findViewById(R.id.name);
itemValue = (TextView) itemLayout.findViewById(R.id.value);
itemName.setText(res.getString(R.string.trackable_owner));
if (trackable.owner != null) {
itemValue.setText(Html.fromHtml(trackable.owner), TextView.BufferType.SPANNABLE);
itemLayout.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
- if (trackable.guid != null) {
+ if (trackable.ownerGuid != null && trackable.ownerGuid.length() > 0) {
activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.geocaching.com/profile/?guid=" + trackable.ownerGuid)));
} else {
activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.geocaching.com/profile/?u=" + URLEncoder.encode(Html.fromHtml(trackable.spottedName).toString()))));
}
}
});
} else {
itemValue.setText(res.getString(R.string.trackable_unknown));
}
detailsList.addView(itemLayout);
// trackable spotted
if (
(trackable.spottedName != null && trackable.spottedName.length() > 0) ||
trackable.spottedType == cgTrackable.SPOTTED_UNKNOWN ||
trackable.spottedType == cgTrackable.SPOTTED_OWNER
) {
itemLayout = (RelativeLayout)inflater.inflate(R.layout.cache_item, null);
itemName = (TextView) itemLayout.findViewById(R.id.name);
itemValue = (TextView) itemLayout.findViewById(R.id.value);
itemName.setText(res.getString(R.string.trackable_spotted));
String text = null;
if (trackable.spottedType == cgTrackable.SPOTTED_CACHE) {
text = res.getString(R.string.trackable_spotted_in_cache) + " " + Html.fromHtml(trackable.spottedName).toString();
} else if (trackable.spottedType == cgTrackable.SPOTTED_USER) {
text = res.getString(R.string.trackable_spotted_at_user) + " " + Html.fromHtml(trackable.spottedName).toString();
} else if (trackable.spottedType == cgTrackable.SPOTTED_UNKNOWN) {
text = res.getString(R.string.trackable_spotted_unknown_location);
} else if (trackable.spottedType == cgTrackable.SPOTTED_OWNER) {
text = res.getString(R.string.trackable_spotted_owner);
} else {
text = "N/A";
}
itemValue.setText(text);
itemLayout.setClickable(true);
itemLayout.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
if (cgTrackable.SPOTTED_CACHE == trackable.spottedType) {
Intent cacheIntent = new Intent(activity, cgeodetail.class);
cacheIntent.putExtra("guid", (String) trackable.spottedGuid);
cacheIntent.putExtra("name", (String) trackable.spottedName);
activity.startActivity(cacheIntent);
} else if (cgTrackable.SPOTTED_USER == trackable.spottedType) {
activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.geocaching.com/profile/?guid=" + trackable.spottedGuid)));
}
}
});
detailsList.addView(itemLayout);
}
// trackable origin
if (trackable.origin != null && trackable.origin.length() > 0) {
itemLayout = (RelativeLayout)inflater.inflate(R.layout.cache_item, null);
itemName = (TextView) itemLayout.findViewById(R.id.name);
itemValue = (TextView) itemLayout.findViewById(R.id.value);
itemName.setText(res.getString(R.string.trackable_origin));
itemValue.setText(Html.fromHtml(trackable.origin), TextView.BufferType.SPANNABLE);
detailsList.addView(itemLayout);
}
// trackable released
if (trackable.released != null) {
itemLayout = (RelativeLayout)inflater.inflate(R.layout.cache_item, null);
itemName = (TextView) itemLayout.findViewById(R.id.name);
itemValue = (TextView) itemLayout.findViewById(R.id.value);
itemName.setText(res.getString(R.string.trackable_released));
itemValue.setText(base.dateOut.format(trackable.released));
detailsList.addView(itemLayout);
}
// trackable goal
if (trackable.goal != null && trackable.goal.length() > 0) {
((LinearLayout) findViewById(R.id.goal_box)).setVisibility(View.VISIBLE);
TextView descView = (TextView) findViewById(R.id.goal);
descView.setVisibility(View.VISIBLE);
descView.setText(Html.fromHtml(trackable.goal, new cgHtmlImg(activity, settings, geocode, true, 0, false), null), TextView.BufferType.SPANNABLE);
descView.setMovementMethod(LinkMovementMethod.getInstance());
}
// trackable details
if (trackable.details != null && trackable.details.length() > 0) {
((LinearLayout) findViewById(R.id.details_box)).setVisibility(View.VISIBLE);
TextView descView = (TextView) findViewById(R.id.details);
descView.setVisibility(View.VISIBLE);
descView.setText(Html.fromHtml(trackable.details, new cgHtmlImg(activity, settings, geocode, true, 0, false), null), TextView.BufferType.SPANNABLE);
descView.setMovementMethod(LinkMovementMethod.getInstance());
}
// trackable image
if (trackable.image != null && trackable.image.length() > 0) {
((LinearLayout) findViewById(R.id.image_box)).setVisibility(View.VISIBLE);
LinearLayout imgView = (LinearLayout) findViewById(R.id.image);
final ImageView trackableImage = (ImageView) inflater.inflate(R.layout.trackable_image, null);
trackableImage.setImageResource(R.drawable.image_not_loaded);
trackableImage.setClickable(true);
trackableImage.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(trackable.image)));
}
});
// try to load image
final Handler handler = new Handler() {
@Override
public void handleMessage(Message message) {
BitmapDrawable image = (BitmapDrawable) message.obj;
if (image != null) {
trackableImage.setImageDrawable((BitmapDrawable) message.obj);
}
}
};
new Thread() {
@Override
public void run() {
BitmapDrawable image = null;
try {
cgHtmlImg imgGetter = new cgHtmlImg(activity, settings, geocode, true, 0, false);
image = imgGetter.getDrawable(trackable.image);
Message message = handler.obtainMessage(0, image);
handler.sendMessage(message);
} catch (Exception e) {
Log.e(cgSettings.tag, "cgeospoilers.onCreate.onClick.run: " + e.toString());
}
}
}.start();
imgView.addView(trackableImage);
}
} catch (Exception e) {
Log.e(cgSettings.tag, "cgeotrackable.loadTrackableHandler: " + e.toString());
}
if (waitDialog != null) {
waitDialog.dismiss();
}
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// init
activity = this;
res = this.getResources();
app = (cgeoapplication) this.getApplication();
settings = new cgSettings(this, getSharedPreferences(cgSettings.preferences, 0));
base = new cgBase(app, settings, getSharedPreferences(cgSettings.preferences, 0));
warning = new cgWarning(this);
// set layout
if (settings.skin == 1) {
setTheme(R.style.light);
} else {
setTheme(R.style.dark);
}
setContentView(R.layout.trackable_detail);
base.setTitle(activity, res.getString(R.string.trackable));
// google analytics
base.sendAnal(activity, "/trackable/detail");
// get parameters
Bundle extras = getIntent().getExtras();
Uri uri = getIntent().getData();
// try to get data from extras
if (extras != null) {
geocode = extras.getString("geocode");
name = extras.getString("name");
guid = extras.getString("guid");
}
// try to get data from URI
if (geocode == null && guid == null && uri != null) {
geocode = uri.getQueryParameter("tracker");
guid = uri.getQueryParameter("guid");
if (geocode != null && geocode.length() > 0) {
geocode = geocode.toUpperCase();
guid = null;
} else if (guid != null && guid.length() > 0) {
geocode = null;
guid = guid.toLowerCase();
} else {
warning.showToast(res.getString(R.string.err_tb_details_open));
finish();
return;
}
}
// no given data
if (geocode == null && guid == null) {
warning.showToast(res.getString(R.string.err_tb_display));
finish();
return;
}
if (name != null && name.length() > 0) {
waitDialog = ProgressDialog.show(this, Html.fromHtml(name).toString(), res.getString(R.string.trackable_details_loading), true);
} else if (geocode != null && geocode.length() > 0) {
waitDialog = ProgressDialog.show(this, geocode.toUpperCase(), res.getString(R.string.trackable_details_loading), true);
} else {
waitDialog = ProgressDialog.show(this, "cache", res.getString(R.string.trackable_details_loading), true);
}
waitDialog.setCancelable(true);
loadTrackable thread;
thread = new loadTrackable(loadTrackableHandler, geocode, guid);
thread.start();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, 1, 0, res.getString(R.string.trackable_log_touch)).setIcon(android.R.drawable.ic_menu_agenda); // log touch
SubMenu subMenu = menu.addSubMenu(1, 0, 0, res.getString(R.string.trackable_more)).setIcon(android.R.drawable.ic_menu_more);
subMenu.add(1, 2, 0, res.getString(R.string.trackable_browser_open)); // browser
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 1:
logTouch();
return true;
case 2:
activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.geocaching.com/track/details.aspx?tracker=" + trackable.geocode)));
return true;
}
return false;
}
private class loadTrackable extends Thread {
private Handler handler = null;
private String geocode = null;
private String guid = null;
public loadTrackable(Handler handlerIn, String geocodeIn, String guidIn) {
handler = handlerIn;
geocode = geocodeIn;
guid = guidIn;
if (geocode == null && guid == null) {
warning.showToast(res.getString(R.string.err_tb_forgot));
stop();
finish();
return;
}
}
@Override
public void run() {
loadTrackableFn(geocode, guid);
handler.sendMessage(new Message());
}
}
public void loadTrackableFn(String geocode, String guid) {
HashMap<String, String> params = new HashMap<String, String>();
if (geocode != null && geocode.length() > 0) {
params.put("geocode", geocode);
} else if (guid != null && guid.length() > 0) {
params.put("guid", guid);
} else {
return;
}
trackable = base.searchTrackable(params);
}
private void logTouch() {
Intent logTouchIntent = new Intent(activity, cgeotouch.class);
logTouchIntent.putExtra("geocode", trackable.geocode.toUpperCase());
logTouchIntent.putExtra("guid", trackable.guid);
activity.startActivity(logTouchIntent);
}
public void goHome(View view) {
base.goHome(activity);
}
}
| true | true | public void handleMessage(Message msg) {
RelativeLayout itemLayout;
TextView itemName;
TextView itemValue;
if (trackable != null && trackable.errorRetrieve != 0) {
warning.showToast(res.getString(R.string.err_tb_details_download) + " " + base.errorRetrieve.get(trackable.errorRetrieve) + ".");
finish();
return;
}
if (trackable != null && trackable.error.length() > 0) {
warning.showToast(res.getString(R.string.err_tb_details_download) + " " + trackable.error + ".");
finish();
return;
}
if (trackable == null) {
if (waitDialog != null) {
waitDialog.dismiss();
}
if (geocode != null && geocode.length() > 0) {
warning.showToast(res.getString(R.string.err_tb_find) + " " + geocode + ".");
} else {
warning.showToast(res.getString(R.string.err_tb_find_that));
}
finish();
return;
}
try {
inflater = activity.getLayoutInflater();
geocode = trackable.geocode.toUpperCase();
if (trackable.name != null && trackable.name.length() > 0) {
base.setTitle(activity, Html.fromHtml(trackable.name).toString());
} else {
base.setTitle(activity, trackable.name.toUpperCase());
}
((ScrollView) findViewById(R.id.details_list_box)).setVisibility(View.VISIBLE);
LinearLayout detailsList = (LinearLayout) findViewById(R.id.details_list);
// trackable geocode
itemLayout = (RelativeLayout)inflater.inflate(R.layout.cache_item, null);
itemName = (TextView) itemLayout.findViewById(R.id.name);
itemValue = (TextView) itemLayout.findViewById(R.id.value);
itemName.setText(res.getString(R.string.trackable_code));
itemValue.setText(trackable.geocode.toUpperCase());
detailsList.addView(itemLayout);
// trackable name
itemLayout = (RelativeLayout)inflater.inflate(R.layout.cache_item, null);
itemName = (TextView) itemLayout.findViewById(R.id.name);
itemValue = (TextView) itemLayout.findViewById(R.id.value);
itemName.setText(res.getString(R.string.trackable_name));
if (trackable.name != null) {
itemValue.setText(Html.fromHtml(trackable.name), TextView.BufferType.SPANNABLE);
} else {
itemValue.setText(res.getString(R.string.trackable_unknown));
}
detailsList.addView(itemLayout);
/* disabled by YraFyra, not used
// trackable type
itemLayout = (RelativeLayout)inflater.inflate(R.layout.cache_item, null);
itemName = (TextView) itemLayout.findViewById(R.id.name);
itemValue = (TextView) itemLayout.findViewById(R.id.value);
itemName.setText(res.getString(R.string.trackable_type));
if (trackable.type != null) {
itemValue.setText(Html.fromHtml(trackable.type), TextView.BufferType.SPANNABLE);
} else {
itemValue.setText(res.getString(R.string.trackable_unknown));
}
detailsList.addView(itemLayout);
*/
// trackable owner
itemLayout = (RelativeLayout)inflater.inflate(R.layout.cache_item, null);
itemName = (TextView) itemLayout.findViewById(R.id.name);
itemValue = (TextView) itemLayout.findViewById(R.id.value);
itemName.setText(res.getString(R.string.trackable_owner));
if (trackable.owner != null) {
itemValue.setText(Html.fromHtml(trackable.owner), TextView.BufferType.SPANNABLE);
itemLayout.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
if (trackable.guid != null) {
activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.geocaching.com/profile/?guid=" + trackable.ownerGuid)));
} else {
activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.geocaching.com/profile/?u=" + URLEncoder.encode(Html.fromHtml(trackable.spottedName).toString()))));
}
}
});
} else {
itemValue.setText(res.getString(R.string.trackable_unknown));
}
detailsList.addView(itemLayout);
// trackable spotted
if (
(trackable.spottedName != null && trackable.spottedName.length() > 0) ||
trackable.spottedType == cgTrackable.SPOTTED_UNKNOWN ||
trackable.spottedType == cgTrackable.SPOTTED_OWNER
) {
itemLayout = (RelativeLayout)inflater.inflate(R.layout.cache_item, null);
itemName = (TextView) itemLayout.findViewById(R.id.name);
itemValue = (TextView) itemLayout.findViewById(R.id.value);
itemName.setText(res.getString(R.string.trackable_spotted));
String text = null;
if (trackable.spottedType == cgTrackable.SPOTTED_CACHE) {
text = res.getString(R.string.trackable_spotted_in_cache) + " " + Html.fromHtml(trackable.spottedName).toString();
} else if (trackable.spottedType == cgTrackable.SPOTTED_USER) {
text = res.getString(R.string.trackable_spotted_at_user) + " " + Html.fromHtml(trackable.spottedName).toString();
} else if (trackable.spottedType == cgTrackable.SPOTTED_UNKNOWN) {
text = res.getString(R.string.trackable_spotted_unknown_location);
} else if (trackable.spottedType == cgTrackable.SPOTTED_OWNER) {
text = res.getString(R.string.trackable_spotted_owner);
} else {
text = "N/A";
}
itemValue.setText(text);
itemLayout.setClickable(true);
itemLayout.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
if (cgTrackable.SPOTTED_CACHE == trackable.spottedType) {
Intent cacheIntent = new Intent(activity, cgeodetail.class);
cacheIntent.putExtra("guid", (String) trackable.spottedGuid);
cacheIntent.putExtra("name", (String) trackable.spottedName);
activity.startActivity(cacheIntent);
} else if (cgTrackable.SPOTTED_USER == trackable.spottedType) {
activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.geocaching.com/profile/?guid=" + trackable.spottedGuid)));
}
}
});
detailsList.addView(itemLayout);
}
// trackable origin
if (trackable.origin != null && trackable.origin.length() > 0) {
itemLayout = (RelativeLayout)inflater.inflate(R.layout.cache_item, null);
itemName = (TextView) itemLayout.findViewById(R.id.name);
itemValue = (TextView) itemLayout.findViewById(R.id.value);
itemName.setText(res.getString(R.string.trackable_origin));
itemValue.setText(Html.fromHtml(trackable.origin), TextView.BufferType.SPANNABLE);
detailsList.addView(itemLayout);
}
// trackable released
if (trackable.released != null) {
itemLayout = (RelativeLayout)inflater.inflate(R.layout.cache_item, null);
itemName = (TextView) itemLayout.findViewById(R.id.name);
itemValue = (TextView) itemLayout.findViewById(R.id.value);
itemName.setText(res.getString(R.string.trackable_released));
itemValue.setText(base.dateOut.format(trackable.released));
detailsList.addView(itemLayout);
}
// trackable goal
if (trackable.goal != null && trackable.goal.length() > 0) {
((LinearLayout) findViewById(R.id.goal_box)).setVisibility(View.VISIBLE);
TextView descView = (TextView) findViewById(R.id.goal);
descView.setVisibility(View.VISIBLE);
descView.setText(Html.fromHtml(trackable.goal, new cgHtmlImg(activity, settings, geocode, true, 0, false), null), TextView.BufferType.SPANNABLE);
descView.setMovementMethod(LinkMovementMethod.getInstance());
}
// trackable details
if (trackable.details != null && trackable.details.length() > 0) {
((LinearLayout) findViewById(R.id.details_box)).setVisibility(View.VISIBLE);
TextView descView = (TextView) findViewById(R.id.details);
descView.setVisibility(View.VISIBLE);
descView.setText(Html.fromHtml(trackable.details, new cgHtmlImg(activity, settings, geocode, true, 0, false), null), TextView.BufferType.SPANNABLE);
descView.setMovementMethod(LinkMovementMethod.getInstance());
}
// trackable image
if (trackable.image != null && trackable.image.length() > 0) {
((LinearLayout) findViewById(R.id.image_box)).setVisibility(View.VISIBLE);
LinearLayout imgView = (LinearLayout) findViewById(R.id.image);
final ImageView trackableImage = (ImageView) inflater.inflate(R.layout.trackable_image, null);
trackableImage.setImageResource(R.drawable.image_not_loaded);
trackableImage.setClickable(true);
trackableImage.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(trackable.image)));
}
});
// try to load image
final Handler handler = new Handler() {
@Override
public void handleMessage(Message message) {
BitmapDrawable image = (BitmapDrawable) message.obj;
if (image != null) {
trackableImage.setImageDrawable((BitmapDrawable) message.obj);
}
}
};
new Thread() {
@Override
public void run() {
BitmapDrawable image = null;
try {
cgHtmlImg imgGetter = new cgHtmlImg(activity, settings, geocode, true, 0, false);
image = imgGetter.getDrawable(trackable.image);
Message message = handler.obtainMessage(0, image);
handler.sendMessage(message);
} catch (Exception e) {
Log.e(cgSettings.tag, "cgeospoilers.onCreate.onClick.run: " + e.toString());
}
}
}.start();
imgView.addView(trackableImage);
}
} catch (Exception e) {
Log.e(cgSettings.tag, "cgeotrackable.loadTrackableHandler: " + e.toString());
}
if (waitDialog != null) {
waitDialog.dismiss();
}
}
| public void handleMessage(Message msg) {
RelativeLayout itemLayout;
TextView itemName;
TextView itemValue;
if (trackable != null && trackable.errorRetrieve != 0) {
warning.showToast(res.getString(R.string.err_tb_details_download) + " " + base.errorRetrieve.get(trackable.errorRetrieve) + ".");
finish();
return;
}
if (trackable != null && trackable.error.length() > 0) {
warning.showToast(res.getString(R.string.err_tb_details_download) + " " + trackable.error + ".");
finish();
return;
}
if (trackable == null) {
if (waitDialog != null) {
waitDialog.dismiss();
}
if (geocode != null && geocode.length() > 0) {
warning.showToast(res.getString(R.string.err_tb_find) + " " + geocode + ".");
} else {
warning.showToast(res.getString(R.string.err_tb_find_that));
}
finish();
return;
}
try {
inflater = activity.getLayoutInflater();
geocode = trackable.geocode.toUpperCase();
if (trackable.name != null && trackable.name.length() > 0) {
base.setTitle(activity, Html.fromHtml(trackable.name).toString());
} else {
base.setTitle(activity, trackable.name.toUpperCase());
}
((ScrollView) findViewById(R.id.details_list_box)).setVisibility(View.VISIBLE);
LinearLayout detailsList = (LinearLayout) findViewById(R.id.details_list);
// trackable geocode
itemLayout = (RelativeLayout)inflater.inflate(R.layout.cache_item, null);
itemName = (TextView) itemLayout.findViewById(R.id.name);
itemValue = (TextView) itemLayout.findViewById(R.id.value);
itemName.setText(res.getString(R.string.trackable_code));
itemValue.setText(trackable.geocode.toUpperCase());
detailsList.addView(itemLayout);
// trackable name
itemLayout = (RelativeLayout)inflater.inflate(R.layout.cache_item, null);
itemName = (TextView) itemLayout.findViewById(R.id.name);
itemValue = (TextView) itemLayout.findViewById(R.id.value);
itemName.setText(res.getString(R.string.trackable_name));
if (trackable.name != null) {
itemValue.setText(Html.fromHtml(trackable.name), TextView.BufferType.SPANNABLE);
} else {
itemValue.setText(res.getString(R.string.trackable_unknown));
}
detailsList.addView(itemLayout);
/* disabled by YraFyra, not used
// trackable type
itemLayout = (RelativeLayout)inflater.inflate(R.layout.cache_item, null);
itemName = (TextView) itemLayout.findViewById(R.id.name);
itemValue = (TextView) itemLayout.findViewById(R.id.value);
itemName.setText(res.getString(R.string.trackable_type));
if (trackable.type != null) {
itemValue.setText(Html.fromHtml(trackable.type), TextView.BufferType.SPANNABLE);
} else {
itemValue.setText(res.getString(R.string.trackable_unknown));
}
detailsList.addView(itemLayout);
*/
// trackable owner
itemLayout = (RelativeLayout)inflater.inflate(R.layout.cache_item, null);
itemName = (TextView) itemLayout.findViewById(R.id.name);
itemValue = (TextView) itemLayout.findViewById(R.id.value);
itemName.setText(res.getString(R.string.trackable_owner));
if (trackable.owner != null) {
itemValue.setText(Html.fromHtml(trackable.owner), TextView.BufferType.SPANNABLE);
itemLayout.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
if (trackable.ownerGuid != null && trackable.ownerGuid.length() > 0) {
activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.geocaching.com/profile/?guid=" + trackable.ownerGuid)));
} else {
activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.geocaching.com/profile/?u=" + URLEncoder.encode(Html.fromHtml(trackable.spottedName).toString()))));
}
}
});
} else {
itemValue.setText(res.getString(R.string.trackable_unknown));
}
detailsList.addView(itemLayout);
// trackable spotted
if (
(trackable.spottedName != null && trackable.spottedName.length() > 0) ||
trackable.spottedType == cgTrackable.SPOTTED_UNKNOWN ||
trackable.spottedType == cgTrackable.SPOTTED_OWNER
) {
itemLayout = (RelativeLayout)inflater.inflate(R.layout.cache_item, null);
itemName = (TextView) itemLayout.findViewById(R.id.name);
itemValue = (TextView) itemLayout.findViewById(R.id.value);
itemName.setText(res.getString(R.string.trackable_spotted));
String text = null;
if (trackable.spottedType == cgTrackable.SPOTTED_CACHE) {
text = res.getString(R.string.trackable_spotted_in_cache) + " " + Html.fromHtml(trackable.spottedName).toString();
} else if (trackable.spottedType == cgTrackable.SPOTTED_USER) {
text = res.getString(R.string.trackable_spotted_at_user) + " " + Html.fromHtml(trackable.spottedName).toString();
} else if (trackable.spottedType == cgTrackable.SPOTTED_UNKNOWN) {
text = res.getString(R.string.trackable_spotted_unknown_location);
} else if (trackable.spottedType == cgTrackable.SPOTTED_OWNER) {
text = res.getString(R.string.trackable_spotted_owner);
} else {
text = "N/A";
}
itemValue.setText(text);
itemLayout.setClickable(true);
itemLayout.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
if (cgTrackable.SPOTTED_CACHE == trackable.spottedType) {
Intent cacheIntent = new Intent(activity, cgeodetail.class);
cacheIntent.putExtra("guid", (String) trackable.spottedGuid);
cacheIntent.putExtra("name", (String) trackable.spottedName);
activity.startActivity(cacheIntent);
} else if (cgTrackable.SPOTTED_USER == trackable.spottedType) {
activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.geocaching.com/profile/?guid=" + trackable.spottedGuid)));
}
}
});
detailsList.addView(itemLayout);
}
// trackable origin
if (trackable.origin != null && trackable.origin.length() > 0) {
itemLayout = (RelativeLayout)inflater.inflate(R.layout.cache_item, null);
itemName = (TextView) itemLayout.findViewById(R.id.name);
itemValue = (TextView) itemLayout.findViewById(R.id.value);
itemName.setText(res.getString(R.string.trackable_origin));
itemValue.setText(Html.fromHtml(trackable.origin), TextView.BufferType.SPANNABLE);
detailsList.addView(itemLayout);
}
// trackable released
if (trackable.released != null) {
itemLayout = (RelativeLayout)inflater.inflate(R.layout.cache_item, null);
itemName = (TextView) itemLayout.findViewById(R.id.name);
itemValue = (TextView) itemLayout.findViewById(R.id.value);
itemName.setText(res.getString(R.string.trackable_released));
itemValue.setText(base.dateOut.format(trackable.released));
detailsList.addView(itemLayout);
}
// trackable goal
if (trackable.goal != null && trackable.goal.length() > 0) {
((LinearLayout) findViewById(R.id.goal_box)).setVisibility(View.VISIBLE);
TextView descView = (TextView) findViewById(R.id.goal);
descView.setVisibility(View.VISIBLE);
descView.setText(Html.fromHtml(trackable.goal, new cgHtmlImg(activity, settings, geocode, true, 0, false), null), TextView.BufferType.SPANNABLE);
descView.setMovementMethod(LinkMovementMethod.getInstance());
}
// trackable details
if (trackable.details != null && trackable.details.length() > 0) {
((LinearLayout) findViewById(R.id.details_box)).setVisibility(View.VISIBLE);
TextView descView = (TextView) findViewById(R.id.details);
descView.setVisibility(View.VISIBLE);
descView.setText(Html.fromHtml(trackable.details, new cgHtmlImg(activity, settings, geocode, true, 0, false), null), TextView.BufferType.SPANNABLE);
descView.setMovementMethod(LinkMovementMethod.getInstance());
}
// trackable image
if (trackable.image != null && trackable.image.length() > 0) {
((LinearLayout) findViewById(R.id.image_box)).setVisibility(View.VISIBLE);
LinearLayout imgView = (LinearLayout) findViewById(R.id.image);
final ImageView trackableImage = (ImageView) inflater.inflate(R.layout.trackable_image, null);
trackableImage.setImageResource(R.drawable.image_not_loaded);
trackableImage.setClickable(true);
trackableImage.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(trackable.image)));
}
});
// try to load image
final Handler handler = new Handler() {
@Override
public void handleMessage(Message message) {
BitmapDrawable image = (BitmapDrawable) message.obj;
if (image != null) {
trackableImage.setImageDrawable((BitmapDrawable) message.obj);
}
}
};
new Thread() {
@Override
public void run() {
BitmapDrawable image = null;
try {
cgHtmlImg imgGetter = new cgHtmlImg(activity, settings, geocode, true, 0, false);
image = imgGetter.getDrawable(trackable.image);
Message message = handler.obtainMessage(0, image);
handler.sendMessage(message);
} catch (Exception e) {
Log.e(cgSettings.tag, "cgeospoilers.onCreate.onClick.run: " + e.toString());
}
}
}.start();
imgView.addView(trackableImage);
}
} catch (Exception e) {
Log.e(cgSettings.tag, "cgeotrackable.loadTrackableHandler: " + e.toString());
}
if (waitDialog != null) {
waitDialog.dismiss();
}
}
|
diff --git a/apps/routerconsole/java/src/net/i2p/router/web/ConfigUIHandler.java b/apps/routerconsole/java/src/net/i2p/router/web/ConfigUIHandler.java
index d7bbe080c..17ca229f7 100644
--- a/apps/routerconsole/java/src/net/i2p/router/web/ConfigUIHandler.java
+++ b/apps/routerconsole/java/src/net/i2p/router/web/ConfigUIHandler.java
@@ -1,31 +1,31 @@
package net.i2p.router.web;
/** set the theme */
public class ConfigUIHandler extends FormHandler {
private boolean _shouldSave;
private String _config;
protected void processForm() {
if (_shouldSave)
saveChanges();
}
public void setShouldsave(String moo) { _shouldSave = true; }
public void setTheme(String val) {
_config = val;
}
private void saveChanges() {
if (_config == null)
return;
if (_config.equals("default"))
- _context.router().removeConfigSetting(ConfigUIHelper.PROP_THEME);
+ _context.router().removeConfigSetting(CSSHelper.PROP_THEME_NAME);
else
- _context.router().setConfigSetting(ConfigUIHelper.PROP_THEME, _config);
+ _context.router().setConfigSetting(CSSHelper.PROP_THEME_NAME, _config);
if (_context.router().saveConfig())
addFormNotice("Configuration saved successfully");
else
addFormNotice("Error saving the configuration (applied but not saved) - please see the error logs");
}
}
| false | true | private void saveChanges() {
if (_config == null)
return;
if (_config.equals("default"))
_context.router().removeConfigSetting(ConfigUIHelper.PROP_THEME);
else
_context.router().setConfigSetting(ConfigUIHelper.PROP_THEME, _config);
if (_context.router().saveConfig())
addFormNotice("Configuration saved successfully");
else
addFormNotice("Error saving the configuration (applied but not saved) - please see the error logs");
}
| private void saveChanges() {
if (_config == null)
return;
if (_config.equals("default"))
_context.router().removeConfigSetting(CSSHelper.PROP_THEME_NAME);
else
_context.router().setConfigSetting(CSSHelper.PROP_THEME_NAME, _config);
if (_context.router().saveConfig())
addFormNotice("Configuration saved successfully");
else
addFormNotice("Error saving the configuration (applied but not saved) - please see the error logs");
}
|
diff --git a/web/src/org/openmrs/module/reporting/web/extension/RunAdminListExt.java b/web/src/org/openmrs/module/reporting/web/extension/RunAdminListExt.java
index 097c2fd3..151779f6 100644
--- a/web/src/org/openmrs/module/reporting/web/extension/RunAdminListExt.java
+++ b/web/src/org/openmrs/module/reporting/web/extension/RunAdminListExt.java
@@ -1,32 +1,32 @@
package org.openmrs.module.reporting.web.extension;
import java.util.LinkedHashMap;
import java.util.Map;
import org.openmrs.module.Extension;
import org.openmrs.module.web.extension.AdministrationSectionExt;
public class RunAdminListExt extends AdministrationSectionExt {
public Extension.MEDIA_TYPE getMediaType() {
return Extension.MEDIA_TYPE.html;
}
public String getTitle() {
return "reporting.run.title";
}
public String getRequiredPrivilege() {
return "Run Reports";
}
public Map<String, String> getLinks() {
Map<String, String> map = new LinkedHashMap<String, String>();
map.put("module/reporting/dashboard/index.form", "reporting.runReport.title");
map.put("module/reporting/reports/reportHistory.form", "reporting.reportHistory.title");
- map.put("module/reporting/indicators/indicatorHistory.form", "reporting.indicatorHistory.title");
- map.put("module/reporting/datasets/viewDataSet.form", "reporting.dataSetViewer.title");
+ //map.put("module/reporting/indicators/indicatorHistory.form", "reporting.indicatorHistory.title");
+ //map.put("module/reporting/datasets/viewDataSet.form", "reporting.dataSetViewer.title");
return map;
}
}
| true | true | public Map<String, String> getLinks() {
Map<String, String> map = new LinkedHashMap<String, String>();
map.put("module/reporting/dashboard/index.form", "reporting.runReport.title");
map.put("module/reporting/reports/reportHistory.form", "reporting.reportHistory.title");
map.put("module/reporting/indicators/indicatorHistory.form", "reporting.indicatorHistory.title");
map.put("module/reporting/datasets/viewDataSet.form", "reporting.dataSetViewer.title");
return map;
}
| public Map<String, String> getLinks() {
Map<String, String> map = new LinkedHashMap<String, String>();
map.put("module/reporting/dashboard/index.form", "reporting.runReport.title");
map.put("module/reporting/reports/reportHistory.form", "reporting.reportHistory.title");
//map.put("module/reporting/indicators/indicatorHistory.form", "reporting.indicatorHistory.title");
//map.put("module/reporting/datasets/viewDataSet.form", "reporting.dataSetViewer.title");
return map;
}
|
diff --git a/net.mysocio.packs/net.mysocio.facebook-pack/src/main/java/net/mysocio/data/messages/facebook/FacebookMessage.java b/net.mysocio.packs/net.mysocio.facebook-pack/src/main/java/net/mysocio/data/messages/facebook/FacebookMessage.java
index 342d7a3..bb05437 100644
--- a/net.mysocio.packs/net.mysocio.facebook-pack/src/main/java/net/mysocio/data/messages/facebook/FacebookMessage.java
+++ b/net.mysocio.packs/net.mysocio.facebook-pack/src/main/java/net/mysocio/data/messages/facebook/FacebookMessage.java
@@ -1,347 +1,350 @@
/**
*
*/
package net.mysocio.data.messages.facebook;
import net.mysocio.data.messages.UserMessage;
import net.mysocio.ui.data.objects.facebook.FacebookUiMessage;
import com.github.jmkgreen.morphia.annotations.Entity;
/**
* @author Aladdin
*
*/
@Entity("messages")
public class FacebookMessage extends UserMessage {
private String fbId = "";
private String message = "";
private String picture = "";
private String link = "";
private String name = "";
private String caption = "";
private String description= "";
private String source = "";
private String properties = "";
private String icon = "";
private String privacy = "";
private String type = "";
private String likes = "";
private String place = "";
private String story = "";
private String application = "";
private String updated_time = "";
private String linkToMessage = "";
private String uiObjectName = FacebookUiMessage.NAME;
/**
*
*/
private static final long serialVersionUID = -5110172305702339723L;
@Override
public String replacePlaceholders(String template) {
String message = super.replacePlaceholders(template);
message = message.replace("message.outer.link", getLinkToMessage());
message = message.replace("message.name", getName());
message = message.replace("message.link", getLink());
String picture = getPicture();
if (getType().equals("video")){
message = message.replace("message.picture", picture);
+ }else if (getType().equals("link") && !picture.isEmpty()){
+ message = message.replace("message.picture", "<img src=\"" + picture + "\">");
}else{
//for some reason pictures shown in FB and ones in api messages are not the same
message = message.replace("message.picture", picture.replace("_s.", "_n."));
}
+ message = message.replace("message.story", getStory());
message = message.replace("message.caption", getCaption());
message = message.replace("message.description", getDescription());
return message;
}
@Override
public String getNetworkIcon() {
return "images/networksIcons/fb.png";
}
@Override
public String getReadenNetworkIcon() {
return "images/networksIcons/fb-gray.png";
}
@Override
public String getLink() {
return link;
}
@Override
public String getUiCategory() {
return FacebookUiMessage.CATEGORY;
}
@Override
public String getUiName() {
return uiObjectName;
}
/**
* @return the message
*/
public String getMessage() {
return message;
}
/**
* @param message the message to set
*/
public void setMessage(String message) {
this.message = message;
}
/**
* @return the picture
*/
public String getPicture() {
return picture;
}
/**
* @param picture the picture to set
*/
public void setPicture(String picture) {
this.picture = picture;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the caption
*/
public String getCaption() {
return caption;
}
/**
* @param caption the caption to set
*/
public void setCaption(String caption) {
this.caption = caption;
}
/**
* @return the description
*/
public String getDescription() {
return description;
}
/**
* @param description the description to set
*/
public void setDescription(String description) {
this.description = description;
}
/**
* @return the source
*/
public String getSource() {
return source;
}
/**
* @param source the source to set
*/
public void setSource(String source) {
this.source = source;
}
/**
* @return the properties
*/
public String getProperties() {
return properties;
}
/**
* @param properties the properties to set
*/
public void setProperties(String properties) {
this.properties = properties;
}
/**
* @return the icon
*/
public String getIcon() {
return icon;
}
/**
* @param icon the icon to set
*/
public void setIcon(String icon) {
this.icon = icon;
}
/**
* @return the privacy
*/
public String getPrivacy() {
return privacy;
}
/**
* @param privacy the privacy to set
*/
public void setPrivacy(String privacy) {
this.privacy = privacy;
}
/**
* @return the type
*/
public String getType() {
return type;
}
/**
* @param type the type to set
*/
public void setType(String type) {
this.type = type;
}
/**
* @return the likes
*/
public String getLikes() {
return likes;
}
/**
* @param likes the likes to set
*/
public void setLikes(String likes) {
this.likes = likes;
}
/**
* @return the place
*/
public String getPlace() {
return place;
}
/**
* @param place the place to set
*/
public void setPlace(String place) {
this.place = place;
}
/**
* @return the story
*/
public String getStory() {
return story;
}
/**
* @param story the story to set
*/
public void setStory(String story) {
this.story = story;
}
/**
* @return the application
*/
public String getApplication() {
return application;
}
/**
* @param application the application to set
*/
public void setApplication(String application) {
this.application = application;
}
/**
* @return the updated_time
*/
public String getUpdated_time() {
return updated_time;
}
/**
* @param updated_time the updated_time to set
*/
public void setUpdated_time(String updated_time) {
this.updated_time = updated_time;
}
/**
* @param link the link to set
*/
public void setLink(String link) {
this.link = link;
}
/**
* @return the uiObjectName
*/
public String getUiObjectName() {
return uiObjectName;
}
/**
* @param uiObjectName the uiObjectName to set
*/
public void setUiObjectName(String uiObjectName) {
this.uiObjectName = uiObjectName;
}
/**
* @return the linkToMessage
*/
public String getLinkToMessage() {
return linkToMessage;
}
/**
* @param linkToMessage the linkToMessage to set
*/
public void setLinkToMessage(String linkToMessage) {
this.linkToMessage = linkToMessage;
}
@Override
public Object getUniqueFieldValue() {
return fbId;
}
@Override
public String getUniqueFieldName() {
return "fbId";
}
public String getFbId() {
return fbId;
}
public void setFbId(String fbId) {
this.fbId = fbId;
}
}
| false | true | public String replacePlaceholders(String template) {
String message = super.replacePlaceholders(template);
message = message.replace("message.outer.link", getLinkToMessage());
message = message.replace("message.name", getName());
message = message.replace("message.link", getLink());
String picture = getPicture();
if (getType().equals("video")){
message = message.replace("message.picture", picture);
}else{
//for some reason pictures shown in FB and ones in api messages are not the same
message = message.replace("message.picture", picture.replace("_s.", "_n."));
}
message = message.replace("message.caption", getCaption());
message = message.replace("message.description", getDescription());
return message;
}
| public String replacePlaceholders(String template) {
String message = super.replacePlaceholders(template);
message = message.replace("message.outer.link", getLinkToMessage());
message = message.replace("message.name", getName());
message = message.replace("message.link", getLink());
String picture = getPicture();
if (getType().equals("video")){
message = message.replace("message.picture", picture);
}else if (getType().equals("link") && !picture.isEmpty()){
message = message.replace("message.picture", "<img src=\"" + picture + "\">");
}else{
//for some reason pictures shown in FB and ones in api messages are not the same
message = message.replace("message.picture", picture.replace("_s.", "_n."));
}
message = message.replace("message.story", getStory());
message = message.replace("message.caption", getCaption());
message = message.replace("message.description", getDescription());
return message;
}
|
diff --git a/src/org/clafer/ig/Util.java b/src/org/clafer/ig/Util.java
index 70d6810..a1ac7fb 100644
--- a/src/org/clafer/ig/Util.java
+++ b/src/org/clafer/ig/Util.java
@@ -1,223 +1,220 @@
package org.clafer.ig;
import edu.mit.csail.sdg.alloy4.Pos;
import edu.mit.csail.sdg.alloy4.SafeList;
import edu.mit.csail.sdg.alloy4compiler.ast.Command;
import edu.mit.csail.sdg.alloy4compiler.ast.Expr;
import edu.mit.csail.sdg.alloy4compiler.ast.ExprList;
import edu.mit.csail.sdg.alloy4compiler.ast.ExprUnary;
import edu.mit.csail.sdg.alloy4compiler.ast.Sig;
import java.io.BufferedReader;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
/**
*
* @author jimmy
*/
public class Util {
private static final BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
private static final PrintStream output = System.out;
private static final Field isOne;
private static final Field isLone;
private static final Field isSome;
private static final Field facts;
static {
try {
isOne = Sig.class.getDeclaredField("isOne");
isLone = Sig.class.getDeclaredField("isLone");
isSome = Sig.class.getDeclaredField("isSome");
facts = Sig.class.getDeclaredField("facts");
isOne.setAccessible(true);
isLone.setAccessible(true);
isSome.setAccessible(true);
facts.setAccessible(true);
} catch (NoSuchFieldException e) {
throw new AlloyIGException(e);
}
}
private static void set(Sig sig, Field field, Object value) {
try {
field.set(sig, value);
} catch (IllegalAccessException e) {
throw new AlloyIGException(e);
}
}
public static <T> T notNull(T t) {
if (t == null) {
throw new NullPointerException();
}
return t;
}
public static class State {
private final SafeList<Expr>[] save;
private State(SafeList[] save) {
this.save = save;
}
}
public static State saveState(SafeList<Sig> sigs) {
SafeList[] save = new SafeList[sigs.size()];
for (int i = 0; i < save.length; i++) {
save[i] = sigs.get(i).getFacts();
}
return new State(save);
}
public static void restoreState(State state, SafeList<Sig> sigs) {
for (int i = 0; i < state.save.length; i++) {
set(sigs.get(i), facts, state.save[i]);
}
}
public static String readMessage() throws IOException {
String line = input.readLine();
if (line == null) {
throw new EOFException();
}
int length = Integer.parseInt(line);
char[] buf = new char[length];
int off = 0;
while (off < length) {
int l = input.read(buf, off, length - off);
if (l == -1) {
throw new EOFException();
}
off += l;
}
return new String(buf);
}
public static void writeMessage(int message) throws IOException {
writeMessage(Integer.toString(message));
}
public static void writeMessage(String message) throws IOException {
output.println(message.length());
output.print(message);
}
public static Sig findSig(String name, Iterable<Sig> sigs) {
for (Sig sig : sigs) {
if (name.equals(sig.label)) {
return sig;
}
}
throw new AlloyIGException("Unknown sig " + name);
}
public static Command removeGlobalConstraint(Pos pos, Command c) {
Expr newFormula = removeSubnode(pos, c.formula);
if (notNull(newFormula) == c.formula) {
return null;
}
return new Command(c.pos, c.label, c.check, c.overall, c.bitwidth, c.maxseq, c.expects, c.scope, c.additionalExactScopes, newFormula, c.parent);
}
private static <T> List<T> asList(Iterable<T> iterable) {
List<T> list = new ArrayList<T>();
for (T item : iterable) {
list.add(item);
}
return list;
}
public static boolean removeLocalConstraint(Pos pos, Iterable<Sig> sigs) {
for (Sig sig : sigs) {
List<Expr> newFacts = new ArrayList<Expr>(asList(sig.getFacts()));
for (ListIterator<Expr> iter = newFacts.listIterator(); iter.hasNext();) {
Expr fact = iter.next();
// Base case
if (pos.equals(fact.span())) {
iter.remove();
set(sig, facts, new SafeList<Expr>(newFacts));
return true;
}
// Recursive case
Expr newFact = removeSubnode(pos, fact);
if (newFact == null) {
iter.remove();
set(sig, facts, new SafeList<Expr>(newFacts));
return true;
}
if (newFact != fact) {
iter.set(newFact);
set(sig, facts, new SafeList<Expr>(newFacts));
return true;
}
}
}
return false;
}
private static Expr removeSubnode(Pos pos, Expr node) {
if (node instanceof ExprList) {
ExprList exprList = (ExprList) node;
List<Expr> newSubNodes = new ArrayList<Expr>(exprList.args);
for (ListIterator<Expr> iter = newSubNodes.listIterator(); iter.hasNext();) {
Expr next = iter.next();
// Base case
if (pos.equals(next.span())) {
iter.remove();
return ExprList.make(exprList.pos, exprList.closingBracket, exprList.op, newSubNodes);
}
// Recursive case
Expr newSubNode = removeSubnode(pos, next);
if (newSubNode == null) {
iter.remove();
return ExprList.make(exprList.pos, exprList.closingBracket, exprList.op, newSubNodes);
} else if (newSubNode != next) {
iter.set(newSubNode);
return ExprList.make(exprList.pos, exprList.closingBracket, exprList.op, newSubNodes);
}
}
} else if (node instanceof ExprUnary) {
ExprUnary expr = (ExprUnary) node;
ExprUnary.Op op = expr.op;
Expr sub = expr.sub;
- // Read ExprUnary.getSubnodes to see why NOOP is special
- if (op != ExprUnary.Op.NOOP) {
- if (pos.equals(sub.span())) {
- return null;
- }
+ if (pos.equals(sub.span())) {
+ return null;
}
Expr newSub = removeSubnode(pos, sub);
if (newSub == null) {
return null;
}
if (newSub != sub) {
return op.make(expr.pos, newSub);
}
}
return node;
}
}
| true | true | private static Expr removeSubnode(Pos pos, Expr node) {
if (node instanceof ExprList) {
ExprList exprList = (ExprList) node;
List<Expr> newSubNodes = new ArrayList<Expr>(exprList.args);
for (ListIterator<Expr> iter = newSubNodes.listIterator(); iter.hasNext();) {
Expr next = iter.next();
// Base case
if (pos.equals(next.span())) {
iter.remove();
return ExprList.make(exprList.pos, exprList.closingBracket, exprList.op, newSubNodes);
}
// Recursive case
Expr newSubNode = removeSubnode(pos, next);
if (newSubNode == null) {
iter.remove();
return ExprList.make(exprList.pos, exprList.closingBracket, exprList.op, newSubNodes);
} else if (newSubNode != next) {
iter.set(newSubNode);
return ExprList.make(exprList.pos, exprList.closingBracket, exprList.op, newSubNodes);
}
}
} else if (node instanceof ExprUnary) {
ExprUnary expr = (ExprUnary) node;
ExprUnary.Op op = expr.op;
Expr sub = expr.sub;
// Read ExprUnary.getSubnodes to see why NOOP is special
if (op != ExprUnary.Op.NOOP) {
if (pos.equals(sub.span())) {
return null;
}
}
Expr newSub = removeSubnode(pos, sub);
if (newSub == null) {
return null;
}
if (newSub != sub) {
return op.make(expr.pos, newSub);
}
}
return node;
}
| private static Expr removeSubnode(Pos pos, Expr node) {
if (node instanceof ExprList) {
ExprList exprList = (ExprList) node;
List<Expr> newSubNodes = new ArrayList<Expr>(exprList.args);
for (ListIterator<Expr> iter = newSubNodes.listIterator(); iter.hasNext();) {
Expr next = iter.next();
// Base case
if (pos.equals(next.span())) {
iter.remove();
return ExprList.make(exprList.pos, exprList.closingBracket, exprList.op, newSubNodes);
}
// Recursive case
Expr newSubNode = removeSubnode(pos, next);
if (newSubNode == null) {
iter.remove();
return ExprList.make(exprList.pos, exprList.closingBracket, exprList.op, newSubNodes);
} else if (newSubNode != next) {
iter.set(newSubNode);
return ExprList.make(exprList.pos, exprList.closingBracket, exprList.op, newSubNodes);
}
}
} else if (node instanceof ExprUnary) {
ExprUnary expr = (ExprUnary) node;
ExprUnary.Op op = expr.op;
Expr sub = expr.sub;
if (pos.equals(sub.span())) {
return null;
}
Expr newSub = removeSubnode(pos, sub);
if (newSub == null) {
return null;
}
if (newSub != sub) {
return op.make(expr.pos, newSub);
}
}
return node;
}
|
diff --git a/src/webapp/src/java/org/wyona/yanel/servlet/YanelGlobalResourceTypeMatcher.java b/src/webapp/src/java/org/wyona/yanel/servlet/YanelGlobalResourceTypeMatcher.java
index 5c11b506f..956da0e5b 100644
--- a/src/webapp/src/java/org/wyona/yanel/servlet/YanelGlobalResourceTypeMatcher.java
+++ b/src/webapp/src/java/org/wyona/yanel/servlet/YanelGlobalResourceTypeMatcher.java
@@ -1,105 +1,106 @@
package org.wyona.yanel.servlet;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.HashMap;
import org.apache.commons.io.IOUtils;
import org.wyona.yanel.core.Environment;
import org.wyona.yanel.core.ResourceConfiguration;
import org.wyona.yanel.core.map.Realm;
import org.apache.log4j.Logger;
/**
* Resource type matcher for all global resources
*/
class YanelGlobalResourceTypeMatcher {
private static Logger log = Logger.getLogger(YanelGlobalResourceTypeMatcher.class);
private String pathPrefix;
private String globalRCsBasePath;
public YanelGlobalResourceTypeMatcher(String pathPrefix, String globalRCsBasePath) {
this.pathPrefix = pathPrefix;
this.globalRCsBasePath = globalRCsBasePath;
}
/**
* Get global resource configuration
*/
public ResourceConfiguration getResourceConfiguration(Environment environment, Realm realm, String path) throws Exception {
log.debug("Get global resource config: " + path);
java.util.Map<String, String> properties = new HashMap<String, String>();
//XXX: maybe we should use a configuration file instead!
java.util.Map<String, String> globalRCmap = new HashMap<String, String>();
globalRCmap.put("search.html", "search_yanel-rc.xml");
globalRCmap.put("data-repository-sitetree.html", "data-repo-sitetree_yanel-rc.xml");
globalRCmap.put("user-forgot-pw.html", "user-forgot-pw_yanel-rc.xml");
final String ADMIN_PREFIX = "admin/";
globalRCmap.put(ADMIN_PREFIX + "list-groups.html", "user-mgmt/list-groups_yanel-rc.xml");
globalRCmap.put(ADMIN_PREFIX + "list-users.html", "user-mgmt/list-users_yanel-rc.xml");
globalRCmap.put(ADMIN_PREFIX + "delete-group.html", "user-mgmt/delete-group_yanel-rc.xml");
globalRCmap.put(ADMIN_PREFIX + "create-group.html", "user-mgmt/create-group_yanel-rc.xml");
globalRCmap.put(ADMIN_PREFIX + "view-group.html", "user-mgmt/view-group_yanel-rc.xml");
globalRCmap.put(ADMIN_PREFIX + "delete-user.html", "user-mgmt/delete-user_yanel-rc.xml");
globalRCmap.put(ADMIN_PREFIX + "update-user.html", "user-mgmt/update-user_yanel-rc.xml");
globalRCmap.put(ADMIN_PREFIX + "create-user.html", "user-mgmt/create-user_yanel-rc.xml");
globalRCmap.put(ADMIN_PREFIX + "update-user-admin.html", "user-mgmt/update-user-admin_yanel-rc.xml");
final String API_PREFIX = "api/";
globalRCmap.put(API_PREFIX + "usermanager", "api/usermanager-api_yanel-rc.xml");
String pathSuffix = path.substring(pathPrefix.length());
String globalRCfilename = globalRCmap.get(pathSuffix);
final String usersPathPrefix = pathPrefix + "users/";
if (path.startsWith(usersPathPrefix)) {
log.debug("Get generic yanel resource config ...");
final String userName = path.substring(usersPathPrefix.length(), path.length() - ".html".length());
properties.put("user", userName);
properties.put("xslt", "rthtdocs:/yanel-user-profile.xsl");
+ properties.put("mime-type", "text/html"); // INFO: Because of IE we use text/html instead application/xhtml+xml
return new ResourceConfiguration("yanel-user", "http://www.wyona.org/yanel/resource/1.0", properties);
} else if (globalRCfilename != null) {
return getGlobalResourceConfiguration(globalRCfilename, realm, globalRCsBasePath);
} else {
log.debug("No such global resource configuration for path (nothing to worry about): " + path);
return null;
}
}
/**
* Get resource configuration from global location of the realm or if not available there, then from global location of Yanel
*
* @param resConfigName Filename of resource configuration
* @param realm Current realm
*/
static ResourceConfiguration getGlobalResourceConfiguration(String resConfigName, Realm realm, String globalRCsBasePath) {
log.debug("Get global resource config, whereas check within realm first ...");
// TODO: Introduce a repository for the Yanel webapp
File realmDir = new File(realm.getConfigFile().getParent());
File globalResConfigFile = org.wyona.commons.io.FileUtil.file(realmDir.getAbsolutePath(), "src" + File.separator + "webapp" + File.separator + "global-resource-configs/" + resConfigName);
if (!globalResConfigFile.isFile()) {
// Fallback to global configuration
globalResConfigFile = org.wyona.commons.io.FileUtil.file(globalRCsBasePath, "global-resource-configs/" + resConfigName);
}
InputStream is;
try {
log.debug("Read resource config: " + globalResConfigFile);
is = new java.io.FileInputStream(globalResConfigFile);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
try {
return new ResourceConfiguration(is);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
IOUtils.closeQuietly(is);
}
}
}
| true | true | public ResourceConfiguration getResourceConfiguration(Environment environment, Realm realm, String path) throws Exception {
log.debug("Get global resource config: " + path);
java.util.Map<String, String> properties = new HashMap<String, String>();
//XXX: maybe we should use a configuration file instead!
java.util.Map<String, String> globalRCmap = new HashMap<String, String>();
globalRCmap.put("search.html", "search_yanel-rc.xml");
globalRCmap.put("data-repository-sitetree.html", "data-repo-sitetree_yanel-rc.xml");
globalRCmap.put("user-forgot-pw.html", "user-forgot-pw_yanel-rc.xml");
final String ADMIN_PREFIX = "admin/";
globalRCmap.put(ADMIN_PREFIX + "list-groups.html", "user-mgmt/list-groups_yanel-rc.xml");
globalRCmap.put(ADMIN_PREFIX + "list-users.html", "user-mgmt/list-users_yanel-rc.xml");
globalRCmap.put(ADMIN_PREFIX + "delete-group.html", "user-mgmt/delete-group_yanel-rc.xml");
globalRCmap.put(ADMIN_PREFIX + "create-group.html", "user-mgmt/create-group_yanel-rc.xml");
globalRCmap.put(ADMIN_PREFIX + "view-group.html", "user-mgmt/view-group_yanel-rc.xml");
globalRCmap.put(ADMIN_PREFIX + "delete-user.html", "user-mgmt/delete-user_yanel-rc.xml");
globalRCmap.put(ADMIN_PREFIX + "update-user.html", "user-mgmt/update-user_yanel-rc.xml");
globalRCmap.put(ADMIN_PREFIX + "create-user.html", "user-mgmt/create-user_yanel-rc.xml");
globalRCmap.put(ADMIN_PREFIX + "update-user-admin.html", "user-mgmt/update-user-admin_yanel-rc.xml");
final String API_PREFIX = "api/";
globalRCmap.put(API_PREFIX + "usermanager", "api/usermanager-api_yanel-rc.xml");
String pathSuffix = path.substring(pathPrefix.length());
String globalRCfilename = globalRCmap.get(pathSuffix);
final String usersPathPrefix = pathPrefix + "users/";
if (path.startsWith(usersPathPrefix)) {
log.debug("Get generic yanel resource config ...");
final String userName = path.substring(usersPathPrefix.length(), path.length() - ".html".length());
properties.put("user", userName);
properties.put("xslt", "rthtdocs:/yanel-user-profile.xsl");
return new ResourceConfiguration("yanel-user", "http://www.wyona.org/yanel/resource/1.0", properties);
} else if (globalRCfilename != null) {
return getGlobalResourceConfiguration(globalRCfilename, realm, globalRCsBasePath);
} else {
log.debug("No such global resource configuration for path (nothing to worry about): " + path);
return null;
}
}
| public ResourceConfiguration getResourceConfiguration(Environment environment, Realm realm, String path) throws Exception {
log.debug("Get global resource config: " + path);
java.util.Map<String, String> properties = new HashMap<String, String>();
//XXX: maybe we should use a configuration file instead!
java.util.Map<String, String> globalRCmap = new HashMap<String, String>();
globalRCmap.put("search.html", "search_yanel-rc.xml");
globalRCmap.put("data-repository-sitetree.html", "data-repo-sitetree_yanel-rc.xml");
globalRCmap.put("user-forgot-pw.html", "user-forgot-pw_yanel-rc.xml");
final String ADMIN_PREFIX = "admin/";
globalRCmap.put(ADMIN_PREFIX + "list-groups.html", "user-mgmt/list-groups_yanel-rc.xml");
globalRCmap.put(ADMIN_PREFIX + "list-users.html", "user-mgmt/list-users_yanel-rc.xml");
globalRCmap.put(ADMIN_PREFIX + "delete-group.html", "user-mgmt/delete-group_yanel-rc.xml");
globalRCmap.put(ADMIN_PREFIX + "create-group.html", "user-mgmt/create-group_yanel-rc.xml");
globalRCmap.put(ADMIN_PREFIX + "view-group.html", "user-mgmt/view-group_yanel-rc.xml");
globalRCmap.put(ADMIN_PREFIX + "delete-user.html", "user-mgmt/delete-user_yanel-rc.xml");
globalRCmap.put(ADMIN_PREFIX + "update-user.html", "user-mgmt/update-user_yanel-rc.xml");
globalRCmap.put(ADMIN_PREFIX + "create-user.html", "user-mgmt/create-user_yanel-rc.xml");
globalRCmap.put(ADMIN_PREFIX + "update-user-admin.html", "user-mgmt/update-user-admin_yanel-rc.xml");
final String API_PREFIX = "api/";
globalRCmap.put(API_PREFIX + "usermanager", "api/usermanager-api_yanel-rc.xml");
String pathSuffix = path.substring(pathPrefix.length());
String globalRCfilename = globalRCmap.get(pathSuffix);
final String usersPathPrefix = pathPrefix + "users/";
if (path.startsWith(usersPathPrefix)) {
log.debug("Get generic yanel resource config ...");
final String userName = path.substring(usersPathPrefix.length(), path.length() - ".html".length());
properties.put("user", userName);
properties.put("xslt", "rthtdocs:/yanel-user-profile.xsl");
properties.put("mime-type", "text/html"); // INFO: Because of IE we use text/html instead application/xhtml+xml
return new ResourceConfiguration("yanel-user", "http://www.wyona.org/yanel/resource/1.0", properties);
} else if (globalRCfilename != null) {
return getGlobalResourceConfiguration(globalRCfilename, realm, globalRCsBasePath);
} else {
log.debug("No such global resource configuration for path (nothing to worry about): " + path);
return null;
}
}
|
diff --git a/src/main/java/org/jscep/transport/UrlConnectionPostTransport.java b/src/main/java/org/jscep/transport/UrlConnectionPostTransport.java
index f5176e7c..e5ed2b33 100644
--- a/src/main/java/org/jscep/transport/UrlConnectionPostTransport.java
+++ b/src/main/java/org/jscep/transport/UrlConnectionPostTransport.java
@@ -1,108 +1,109 @@
package org.jscep.transport;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import net.jcip.annotations.ThreadSafe;
import org.apache.commons.io.Charsets;
import org.apache.commons.io.IOUtils;
import org.bouncycastle.util.encoders.Base64;
import org.jscep.transport.request.PkiOperationRequest;
import org.jscep.transport.request.Request;
import org.jscep.transport.response.ScepResponseHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* AbstractTransport representing the <code>HTTP POST</code> method.
*/
@ThreadSafe
final class UrlConnectionPostTransport extends AbstractTransport {
private static final Logger LOGGER = LoggerFactory
.getLogger(UrlConnectionPostTransport.class);
/**
* Creates a new <tt>HttpPostTransport</tt> for the given <tt>URL</tt>.
*
* @param url
* the <tt>URL</tt> to send <tt>POST</tt> requests to.
*/
public UrlConnectionPostTransport(final URL url) {
super(url);
}
/**
* {@inheritDoc}
*/
@Override
public <T> T sendRequest(final Request msg,
final ScepResponseHandler<T> handler) throws TransportException {
if (!PkiOperationRequest.class.isAssignableFrom(msg.getClass())) {
throw new IllegalArgumentException(
"POST transport may not be used for " + msg.getOperation()
+ " messages.");
}
URL url = getUrl(msg.getOperation());
HttpURLConnection conn;
try {
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
+ conn.setRequestProperty("Content-Type", "application/octet-stream");
} catch (IOException e) {
throw new TransportException(e);
}
conn.setDoOutput(true);
byte[] message;
try {
message = Base64.decode(msg.getMessage().getBytes(
Charsets.US_ASCII.name()));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
OutputStream stream = null;
try {
stream = new BufferedOutputStream(conn.getOutputStream());
stream.write(message);
} catch (IOException e) {
throw new TransportException(e);
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
LOGGER.error("Failed to close output stream", e);
}
}
}
try {
int responseCode = conn.getResponseCode();
String responseMessage = conn.getResponseMessage();
LOGGER.debug("Received '{} {}' when sending {} to {}",
varargs(responseCode, responseMessage, msg, url));
if (responseCode != HttpURLConnection.HTTP_OK) {
throw new TransportException(responseCode + " "
+ responseMessage);
}
} catch (IOException e) {
throw new TransportException("Error connecting to server.", e);
}
byte[] response;
try {
response = IOUtils.toByteArray(conn.getInputStream());
} catch (IOException e) {
throw new TransportException("Error reading response stream", e);
}
return handler.getResponse(response, conn.getContentType());
}
}
| true | true | public <T> T sendRequest(final Request msg,
final ScepResponseHandler<T> handler) throws TransportException {
if (!PkiOperationRequest.class.isAssignableFrom(msg.getClass())) {
throw new IllegalArgumentException(
"POST transport may not be used for " + msg.getOperation()
+ " messages.");
}
URL url = getUrl(msg.getOperation());
HttpURLConnection conn;
try {
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
} catch (IOException e) {
throw new TransportException(e);
}
conn.setDoOutput(true);
byte[] message;
try {
message = Base64.decode(msg.getMessage().getBytes(
Charsets.US_ASCII.name()));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
OutputStream stream = null;
try {
stream = new BufferedOutputStream(conn.getOutputStream());
stream.write(message);
} catch (IOException e) {
throw new TransportException(e);
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
LOGGER.error("Failed to close output stream", e);
}
}
}
try {
int responseCode = conn.getResponseCode();
String responseMessage = conn.getResponseMessage();
LOGGER.debug("Received '{} {}' when sending {} to {}",
varargs(responseCode, responseMessage, msg, url));
if (responseCode != HttpURLConnection.HTTP_OK) {
throw new TransportException(responseCode + " "
+ responseMessage);
}
} catch (IOException e) {
throw new TransportException("Error connecting to server.", e);
}
byte[] response;
try {
response = IOUtils.toByteArray(conn.getInputStream());
} catch (IOException e) {
throw new TransportException("Error reading response stream", e);
}
return handler.getResponse(response, conn.getContentType());
}
| public <T> T sendRequest(final Request msg,
final ScepResponseHandler<T> handler) throws TransportException {
if (!PkiOperationRequest.class.isAssignableFrom(msg.getClass())) {
throw new IllegalArgumentException(
"POST transport may not be used for " + msg.getOperation()
+ " messages.");
}
URL url = getUrl(msg.getOperation());
HttpURLConnection conn;
try {
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/octet-stream");
} catch (IOException e) {
throw new TransportException(e);
}
conn.setDoOutput(true);
byte[] message;
try {
message = Base64.decode(msg.getMessage().getBytes(
Charsets.US_ASCII.name()));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
OutputStream stream = null;
try {
stream = new BufferedOutputStream(conn.getOutputStream());
stream.write(message);
} catch (IOException e) {
throw new TransportException(e);
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
LOGGER.error("Failed to close output stream", e);
}
}
}
try {
int responseCode = conn.getResponseCode();
String responseMessage = conn.getResponseMessage();
LOGGER.debug("Received '{} {}' when sending {} to {}",
varargs(responseCode, responseMessage, msg, url));
if (responseCode != HttpURLConnection.HTTP_OK) {
throw new TransportException(responseCode + " "
+ responseMessage);
}
} catch (IOException e) {
throw new TransportException("Error connecting to server.", e);
}
byte[] response;
try {
response = IOUtils.toByteArray(conn.getInputStream());
} catch (IOException e) {
throw new TransportException("Error reading response stream", e);
}
return handler.getResponse(response, conn.getContentType());
}
|
diff --git a/src/main/java/com/reucon/openfire/plugin/archive/xep0136/IQRetrieveHandler.java b/src/main/java/com/reucon/openfire/plugin/archive/xep0136/IQRetrieveHandler.java
index 014d2c8..0d5a0b2 100644
--- a/src/main/java/com/reucon/openfire/plugin/archive/xep0136/IQRetrieveHandler.java
+++ b/src/main/java/com/reucon/openfire/plugin/archive/xep0136/IQRetrieveHandler.java
@@ -1,111 +1,111 @@
package com.reucon.openfire.plugin.archive.xep0136;
import com.reucon.openfire.plugin.archive.model.ArchivedMessage;
import com.reucon.openfire.plugin.archive.model.Conversation;
import com.reucon.openfire.plugin.archive.util.XmppDateUtil;
import com.reucon.openfire.plugin.archive.xep0059.XmppResultSet;
import org.dom4j.Element;
import org.jivesoftware.openfire.auth.UnauthorizedException;
import org.xmpp.packet.IQ;
import org.xmpp.packet.JID;
import org.xmpp.packet.PacketError;
import java.util.List;
/**
* Message Archiving Retrieve Handler.
*/
public class IQRetrieveHandler extends AbstractIQHandler
{
public IQRetrieveHandler()
{
super("Message Archiving Retrieve Handler", "retrieve");
}
public IQ handleIQ(IQ packet) throws UnauthorizedException
{
final IQ reply = IQ.createResultIQ(packet);
final RetrieveRequest retrieveRequest = new RetrieveRequest(packet.getChildElement());
int fromIndex; // inclusive
int toIndex; // exclusive
int max;
final Conversation conversation = retrieve(packet.getFrom(), retrieveRequest);
if (conversation == null)
{
return error(packet, PacketError.Condition.item_not_found);
}
final Element chatElement = reply.setChildElement("chat", NAMESPACE);
chatElement.addAttribute("with", conversation.getWithJid());
chatElement.addAttribute("start", XmppDateUtil.formatDate(conversation.getStart()));
max = conversation.getMessages().size();
fromIndex = 0;
- toIndex = max > 1 ? max - 1 : 0;
+ toIndex = max > 0 ? max : 0;
final XmppResultSet resultSet = retrieveRequest.getResultSet();
if (resultSet != null)
{
- if (resultSet.getMax() != null && resultSet.getMax() < max)
+ if (resultSet.getMax() != null && resultSet.getMax() <= max)
{
max = resultSet.getMax();
toIndex = fromIndex + max;
}
if (resultSet.getIndex() != null)
{
fromIndex = resultSet.getIndex();
toIndex = fromIndex + max;
}
else if (resultSet.getAfter() != null)
{
fromIndex = resultSet.getAfter().intValue() + 1;
toIndex = fromIndex + max;
}
else if (resultSet.getBefore() != null)
{
toIndex = resultSet.getBefore().intValue();
fromIndex = toIndex - max;
}
}
fromIndex = fromIndex < 0 ? 0 : fromIndex;
toIndex = toIndex > conversation.getMessages().size() ? conversation.getMessages().size() : toIndex;
toIndex = toIndex < fromIndex ? fromIndex : toIndex;
final List<ArchivedMessage> messages = conversation.getMessages().subList(fromIndex, toIndex);
for (ArchivedMessage message : messages)
{
addMessageElement(chatElement, conversation, message);
}
if (resultSet != null && messages.size() > 0)
{
resultSet.setFirst((long) fromIndex);
resultSet.setFirstIndex(fromIndex);
resultSet.setLast((long) toIndex - 1);
resultSet.setCount(conversation.getMessages().size());
chatElement.add(resultSet.createResultElement());
}
return reply;
}
private Conversation retrieve(JID from, RetrieveRequest request)
{
return getPersistenceManager().getConversation(from.toBareJID(), request.getWith(), request.getStart());
}
private Element addMessageElement(Element parentElement, Conversation conversation, ArchivedMessage message)
{
final Element messageElement;
final long secs;
secs = (message.getTime().getTime() - conversation.getStart().getTime()) / 1000;
messageElement = parentElement.addElement(message.getDirection().toString());
messageElement.addAttribute("secs", Long.toString(secs));
messageElement.addElement("body").setText(message.getBody());
return messageElement;
}
}
| false | true | public IQ handleIQ(IQ packet) throws UnauthorizedException
{
final IQ reply = IQ.createResultIQ(packet);
final RetrieveRequest retrieveRequest = new RetrieveRequest(packet.getChildElement());
int fromIndex; // inclusive
int toIndex; // exclusive
int max;
final Conversation conversation = retrieve(packet.getFrom(), retrieveRequest);
if (conversation == null)
{
return error(packet, PacketError.Condition.item_not_found);
}
final Element chatElement = reply.setChildElement("chat", NAMESPACE);
chatElement.addAttribute("with", conversation.getWithJid());
chatElement.addAttribute("start", XmppDateUtil.formatDate(conversation.getStart()));
max = conversation.getMessages().size();
fromIndex = 0;
toIndex = max > 1 ? max - 1 : 0;
final XmppResultSet resultSet = retrieveRequest.getResultSet();
if (resultSet != null)
{
if (resultSet.getMax() != null && resultSet.getMax() < max)
{
max = resultSet.getMax();
toIndex = fromIndex + max;
}
if (resultSet.getIndex() != null)
{
fromIndex = resultSet.getIndex();
toIndex = fromIndex + max;
}
else if (resultSet.getAfter() != null)
{
fromIndex = resultSet.getAfter().intValue() + 1;
toIndex = fromIndex + max;
}
else if (resultSet.getBefore() != null)
{
toIndex = resultSet.getBefore().intValue();
fromIndex = toIndex - max;
}
}
fromIndex = fromIndex < 0 ? 0 : fromIndex;
toIndex = toIndex > conversation.getMessages().size() ? conversation.getMessages().size() : toIndex;
toIndex = toIndex < fromIndex ? fromIndex : toIndex;
final List<ArchivedMessage> messages = conversation.getMessages().subList(fromIndex, toIndex);
for (ArchivedMessage message : messages)
{
addMessageElement(chatElement, conversation, message);
}
if (resultSet != null && messages.size() > 0)
{
resultSet.setFirst((long) fromIndex);
resultSet.setFirstIndex(fromIndex);
resultSet.setLast((long) toIndex - 1);
resultSet.setCount(conversation.getMessages().size());
chatElement.add(resultSet.createResultElement());
}
return reply;
}
| public IQ handleIQ(IQ packet) throws UnauthorizedException
{
final IQ reply = IQ.createResultIQ(packet);
final RetrieveRequest retrieveRequest = new RetrieveRequest(packet.getChildElement());
int fromIndex; // inclusive
int toIndex; // exclusive
int max;
final Conversation conversation = retrieve(packet.getFrom(), retrieveRequest);
if (conversation == null)
{
return error(packet, PacketError.Condition.item_not_found);
}
final Element chatElement = reply.setChildElement("chat", NAMESPACE);
chatElement.addAttribute("with", conversation.getWithJid());
chatElement.addAttribute("start", XmppDateUtil.formatDate(conversation.getStart()));
max = conversation.getMessages().size();
fromIndex = 0;
toIndex = max > 0 ? max : 0;
final XmppResultSet resultSet = retrieveRequest.getResultSet();
if (resultSet != null)
{
if (resultSet.getMax() != null && resultSet.getMax() <= max)
{
max = resultSet.getMax();
toIndex = fromIndex + max;
}
if (resultSet.getIndex() != null)
{
fromIndex = resultSet.getIndex();
toIndex = fromIndex + max;
}
else if (resultSet.getAfter() != null)
{
fromIndex = resultSet.getAfter().intValue() + 1;
toIndex = fromIndex + max;
}
else if (resultSet.getBefore() != null)
{
toIndex = resultSet.getBefore().intValue();
fromIndex = toIndex - max;
}
}
fromIndex = fromIndex < 0 ? 0 : fromIndex;
toIndex = toIndex > conversation.getMessages().size() ? conversation.getMessages().size() : toIndex;
toIndex = toIndex < fromIndex ? fromIndex : toIndex;
final List<ArchivedMessage> messages = conversation.getMessages().subList(fromIndex, toIndex);
for (ArchivedMessage message : messages)
{
addMessageElement(chatElement, conversation, message);
}
if (resultSet != null && messages.size() > 0)
{
resultSet.setFirst((long) fromIndex);
resultSet.setFirstIndex(fromIndex);
resultSet.setLast((long) toIndex - 1);
resultSet.setCount(conversation.getMessages().size());
chatElement.add(resultSet.createResultElement());
}
return reply;
}
|
diff --git a/src/ch/amana/android/cputuner/model/PowerProfiles.java b/src/ch/amana/android/cputuner/model/PowerProfiles.java
index 3fe9a8b9..33ac4be1 100644
--- a/src/ch/amana/android/cputuner/model/PowerProfiles.java
+++ b/src/ch/amana/android/cputuner/model/PowerProfiles.java
@@ -1,644 +1,644 @@
package ch.amana.android.cputuner.model;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import ch.amana.android.cputuner.helper.Logger;
import ch.amana.android.cputuner.helper.Notifier;
import ch.amana.android.cputuner.helper.PulseHelper;
import ch.amana.android.cputuner.helper.SettingsStorage;
import ch.amana.android.cputuner.hw.BatteryHandler;
import ch.amana.android.cputuner.hw.CpuHandler;
import ch.amana.android.cputuner.hw.ServicesHandler;
import ch.amana.android.cputuner.provider.db.DB;
public class PowerProfiles {
public static final String UNKNOWN = "Unknown";
public static final int SERVICE_STATE_LEAVE = 0;
public static final int SERVICE_STATE_ON = 1;
public static final int SERVICE_STATE_OFF = 2;
public static final int SERVICE_STATE_PREV = 3;
public static final int SERVICE_STATE_PULSE = 4;
public static final int SERVICE_STATE_2G = SERVICE_STATE_ON;
public static final int SERVICE_STATE_2G_3G = SERVICE_STATE_OFF;
public static final int SERVICE_STATE_3G = 4;
private static final long MILLIES_TO_HOURS = 1000 * 60 * 60;
private final Context context;
private int batteryLevel;
private int batteryTemperature;
private boolean acPower;
private boolean screenOff;
private boolean batteryHot;
private ProfileModel currentProfile;
private TriggerModel currentTrigger;
private static boolean updateTrigger = true;
private int lastSetStateWifi = -1;
private boolean lastAciveStateWifi;
private int lastSetStateGps = -1;
private boolean lastActiveStateGps;
private int lastSetStateMobiledata3G = -1;
private int lastActiveStateMobileData3G;
private int lastSetStateMobiledataConnection = -1;
private boolean lastActiveStateMobileDataConnection;
private int lastSetStateBluetooth = -1;
private boolean lastActiceStateBluetooth;
private int lastSetStateBackgroundSync = -1;
private boolean lastActiveStateBackgroundSync;
private boolean callInProgress = false;
private boolean lastActiveStateAirplanemode;
private int lastSetStateAirplaneMode = -1;
private int lastBatteryLevel = -1;
private long lastBatteryLevelTimestamp = -1;
private static PowerProfiles instance;
public static void initInstance(Context ctx) {
instance = new PowerProfiles(ctx);
}
public static PowerProfiles getInstance() {
return instance;
}
public PowerProfiles(Context ctx) {
context = ctx;
BatteryHandler batteryHandler = BatteryHandler.getInstance();
batteryLevel = batteryHandler.getBatteryLevel();
acPower = batteryHandler.isOnAcPower();
screenOff = false;
initActiveStates();
resetServiceState();
}
public void initActiveStates() {
lastActiveStateBackgroundSync = ServicesHandler.isBackgroundSyncEnabled(context);
lastActiceStateBluetooth = ServicesHandler.isBlutoothEnabled();
lastActiveStateGps = ServicesHandler.isGpsEnabled(context);
lastActiveStateMobileDataConnection = ServicesHandler.isMobiledataConnectionEnabled(context);
lastActiveStateMobileData3G = ServicesHandler.whichMobiledata3G(context);
lastAciveStateWifi = ServicesHandler.isWifiEnabaled(context);
lastActiveStateAirplanemode = ServicesHandler.isAirplaineModeEnabled(context);
}
private void resetServiceState() {
lastSetStateWifi = -1;
lastSetStateGps = -1;
lastSetStateMobiledataConnection = -1;
lastSetStateMobiledata3G = -1;
lastSetStateBluetooth = -1;
lastSetStateBackgroundSync = -1;
lastSetStateAirplaneMode = -1;
}
public void reapplyProfile(boolean force) {
if (!updateTrigger) {
return;
}
if (force) {
changeTrigger(force);
}
applyPowerProfile(force, force);
}
public void reapplyProfile() {
applyPowerProfile(true, false);
}
private void applyPowerProfile(boolean force, boolean ignoreSettings) {
if (!updateTrigger) {
return;
}
if (!SettingsStorage.getInstance().isEnableProfiles()) {
if (!ignoreSettings) {
return;
}
}
if (currentTrigger == null) {
sendDeviceStatusChangedBroadcast();
return;
}
long profileId = currentTrigger.getBatteryProfileId();
if (callInProgress) {
profileId = currentTrigger.getCallInProgessProfileId();
} else if (isBatteryHot()) {
profileId = currentTrigger.getHotProfileId();
} else if (screenOff) {
profileId = currentTrigger.getScreenOffProfileId();
} else if (acPower) {
profileId = currentTrigger.getPowerProfileId();
}
if (force || currentProfile == null || currentProfile.getDbId() != profileId) {
if (!callInProgress && !SettingsStorage.getInstance().isSwitchProfileWhilePhoneNotIdle() && !ServicesHandler.isPhoneIdle(context)) {
Logger.i("Not switching profile since phone not idle");
return;
}
applyProfile(profileId);
}
}
public void applyProfile(long profileId) {
if (currentProfile != null && currentProfile.getDbId() == profileId) {
Logger.i("Not switching profile since it is the correct one " + currentProfile.getProfileName());
return;
}
Cursor c = null;
try {
c = context.getContentResolver().query(DB.CpuProfile.CONTENT_URI, DB.CpuProfile.PROJECTION_DEFAULT, DB.NAME_ID + "=?", new String[] { profileId + "" },
DB.CpuProfile.SORTORDER_DEFAULT);
if (c != null && c.moveToFirst()) {
currentProfile = new ProfileModel(c);
CpuHandler cpuHandler = new CpuHandler();
cpuHandler.applyCpuSettings(currentProfile);
applyWifiState(currentProfile.getWifiState());
applyGpsState(currentProfile.getGpsState());
applyBluetoothState(currentProfile.getBluetoothState());
applyMobiledata3GState(currentProfile.getMobiledata3GState());
applyMobiledataConnectionState(currentProfile.getMobiledataConnectionState());
applyBackgroundSyncState(currentProfile.getBackgroundSyncState());
applyAirplanemodeState(currentProfile.getAirplainemodeState());
try {
Logger.w("Changed to profile >" + currentProfile.getProfileName() + "< using trigger >" + currentTrigger.getName() + "< on batterylevel " + batteryLevel + "%");
} catch (Exception e) {
Logger.w("Error printing switch profile", e);
}
StringBuilder sb = new StringBuilder(50);
sb.append("Setting power profile to ");
sb.append(currentProfile.getProfileName());
Notifier.notifyProfile(currentProfile.getProfileName());
context.sendBroadcast(new Intent(Notifier.BROADCAST_PROFILE_CHANGED));
}
} finally {
if (c != null && !c.isClosed()) {
try {
c.close();
} catch (Exception e) {
Logger.e("Cannot close cursor", e);
}
}
}
}
private void applyWifiState(int state) {
if (state > SERVICE_STATE_LEAVE && SettingsStorage.getInstance().isEnableSwitchWifi()) {
if (state == SERVICE_STATE_PULSE) {
PulseHelper.getInstance(context).pulseWifiState(true);
lastSetStateWifi = state;
return;
} else {
PulseHelper.getInstance(context).pulseWifiState(false);
}
boolean stateBefore = lastAciveStateWifi;
lastAciveStateWifi = ServicesHandler.isWifiEnabaled(context);
if (state == SERVICE_STATE_PREV) {
Logger.v("Sitching wifi to last state which was " + stateBefore);
ServicesHandler.enableWifi(context, stateBefore);
lastSetStateWifi = -1;
return;
} else if (SettingsStorage.getInstance().isAllowManualServiceChanges()) {
if (lastSetStateWifi > -1 && lastSetStateWifi < SERVICE_STATE_PREV) {
boolean b = lastSetStateWifi == SERVICE_STATE_ON ? true : false;
if (b != stateBefore) {
Logger.v("Not sitching wifi since it changed since last time");
return;
}
}
lastSetStateWifi = state;
}
ServicesHandler.enableWifi(context, state == SERVICE_STATE_ON ? true : false);
}
}
private void applyGpsState(int state) {
if (state > SERVICE_STATE_LEAVE && SettingsStorage.getInstance().isEnableSwitchGps()) {
if (state == SERVICE_STATE_PULSE) {
PulseHelper.getInstance(context).pulseGpsState(true);
lastSetStateGps = state;
return;
} else {
PulseHelper.getInstance(context).pulseGpsState(false);
}
boolean stateBefore = lastActiveStateGps;
lastActiveStateGps = ServicesHandler.isGpsEnabled(context);
if (state == SERVICE_STATE_PREV) {
Logger.v("Sitching GPS to last state which was " + stateBefore);
ServicesHandler.enableGps(context, stateBefore);
lastSetStateGps = -1;
return;
} else if (SettingsStorage.getInstance().isAllowManualServiceChanges()) {
if (lastSetStateGps > -1 && lastSetStateGps < SERVICE_STATE_PREV) {
boolean b = lastSetStateGps == SERVICE_STATE_ON ? true : false;
if (b != stateBefore) {
Logger.v("Not sitching GPS since it changed since last time");
return;
}
}
lastSetStateGps = state;
}
ServicesHandler.enableGps(context, state == SERVICE_STATE_ON ? true : false);
}
}
private void applyBluetoothState(int state) {
if (state > SERVICE_STATE_LEAVE && SettingsStorage.getInstance().isEnableSwitchBluetooth()) {
if (state == SERVICE_STATE_PULSE) {
PulseHelper.getInstance(context).pulseBluetoothState(true);
lastSetStateBluetooth = state;
return;
} else {
PulseHelper.getInstance(context).pulseBluetoothState(false);
}
boolean stateBefore = lastActiceStateBluetooth;
lastActiceStateBluetooth = ServicesHandler.isBlutoothEnabled();
if (state == SERVICE_STATE_PREV) {
Logger.v("Sitching bluetooth to last state which was " + stateBefore);
ServicesHandler.enableBluetooth(stateBefore);
lastSetStateBluetooth = -1;
return;
} else if (SettingsStorage.getInstance().isAllowManualServiceChanges()) {
if (lastSetStateBluetooth > -1 && lastSetStateBluetooth < SERVICE_STATE_PREV) {
boolean b = lastSetStateBluetooth == SERVICE_STATE_ON ? true : false;
if (b != stateBefore) {
Logger.v("Not sitching bluetooth it changed state since last time");
return;
}
}
lastSetStateBluetooth = state;
}
ServicesHandler.enableBluetooth(state == SERVICE_STATE_ON ? true : false);
}
}
private void applyMobiledata3GState(int state) {
if (state > SERVICE_STATE_LEAVE && SettingsStorage.getInstance().isEnableSwitchMobiledata3G()) {
int stateBefore = lastActiveStateMobileData3G;
lastActiveStateMobileData3G = ServicesHandler.whichMobiledata3G(context);
if (state == SERVICE_STATE_PREV) {
Logger.v("Sitching mobiledata 3G to last state which was " + stateBefore);
ServicesHandler.enable2gOnly(context, stateBefore);
lastSetStateMobiledata3G = -1;
return;
} else if (SettingsStorage.getInstance().isAllowManualServiceChanges()) {
if (lastSetStateMobiledata3G > -1) {
if (lastActiveStateMobileData3G != stateBefore) {
Logger.v("Not sitching mobiledata it changed state since last time");
return;
}
}
lastSetStateMobiledata3G = state;
}
ServicesHandler.enable2gOnly(context, state);
}
}
private void applyMobiledataConnectionState(int state) {
if (state > SERVICE_STATE_LEAVE && SettingsStorage.getInstance().isEnableSwitchMobiledataConnection()) {
if (state == SERVICE_STATE_PULSE) {
PulseHelper.getInstance(context).pulseMobiledataConnectionState(true);
lastSetStateMobiledataConnection = state;
return;
} else {
PulseHelper.getInstance(context).pulseMobiledataConnectionState(false);
}
boolean stateBefore = lastActiveStateMobileDataConnection;
lastActiveStateMobileDataConnection = ServicesHandler.isMobiledataConnectionEnabled(context);
if (state == SERVICE_STATE_PREV) {
Logger.v("Sitching mobiledata connection to last state which was " + stateBefore);
ServicesHandler.enableMobileData(context, stateBefore);
lastSetStateMobiledataConnection = -1;
return;
} else if (SettingsStorage.getInstance().isAllowManualServiceChanges()) {
if (lastSetStateMobiledataConnection > -1 && lastSetStateMobiledataConnection < SERVICE_STATE_PREV) {
boolean b = lastSetStateMobiledataConnection == SERVICE_STATE_ON ? true : false;
if (b != stateBefore) {
Logger.v("Not sitching mobiledata connection it changed state since last time");
return;
}
}
lastSetStateMobiledataConnection = state;
}
ServicesHandler.enableMobileData(context, state == SERVICE_STATE_ON ? true : false);
}
}
private void applyBackgroundSyncState(int state) {
if (state > SERVICE_STATE_LEAVE && SettingsStorage.getInstance().isEnableSwitchBackgroundSync()) {
if (state == SERVICE_STATE_PULSE) {
PulseHelper.getInstance(context).pulseBackgroundSyncState(true);
lastSetStateBackgroundSync = state;
return;
} else {
PulseHelper.getInstance(context).pulseBackgroundSyncState(false);
}
boolean stateBefore = lastActiveStateBackgroundSync;
lastActiveStateBackgroundSync = ServicesHandler.isBackgroundSyncEnabled(context);
if (state == SERVICE_STATE_PREV) {
Logger.v("Sitching background sync to last state which was " + stateBefore);
ServicesHandler.enableBackgroundSync(context, stateBefore);
lastSetStateBackgroundSync = -1;
return;
} else if (SettingsStorage.getInstance().isAllowManualServiceChanges()) {
if (lastSetStateBackgroundSync > -1 && lastSetStateBackgroundSync < SERVICE_STATE_PREV) {
boolean b = lastSetStateBackgroundSync == SERVICE_STATE_ON ? true : false;
if (b != stateBefore) {
Logger.v("Not sitching background sync it changed since state since last time");
return;
}
}
lastSetStateBackgroundSync = state;
}
ServicesHandler.enableBackgroundSync(context, state == SERVICE_STATE_ON ? true : false);
}
}
private void applyAirplanemodeState(int state) {
if (state > SERVICE_STATE_LEAVE && SettingsStorage.getInstance().isEnableAirplaneMode()) {
if (state == SERVICE_STATE_PULSE) {
PulseHelper.getInstance(context).pulseAirplanemodeState(true);
lastSetStateAirplaneMode = state;
return;
} else {
PulseHelper.getInstance(context).pulseAirplanemodeState(false);
}
boolean stateBefore = lastActiveStateAirplanemode;
lastActiveStateAirplanemode = ServicesHandler.isAirplaineModeEnabled(context);
if (state == SERVICE_STATE_PREV) {
Logger.v("Sitching airplanemode to last state which was " + stateBefore);
ServicesHandler.enableAirplaneMode(context, stateBefore);
lastSetStateAirplaneMode = -1;
return;
} else if (SettingsStorage.getInstance().isAllowManualServiceChanges()) {
if (lastSetStateAirplaneMode > -1 && lastSetStateAirplaneMode < SERVICE_STATE_PREV) {
boolean b = lastSetStateAirplaneMode == SERVICE_STATE_ON ? true : false;
if (b != stateBefore) {
Logger.v("Not sitching airplanemode it changed since state since last time");
return;
}
}
lastSetStateAirplaneMode = state;
}
ServicesHandler.enableAirplaneMode(context, state == SERVICE_STATE_ON ? true : false);
}
}
private boolean changeTrigger(boolean force) {
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(DB.Trigger.CONTENT_URI, DB.Trigger.PROJECTION_DEFAULT, DB.Trigger.NAME_BATTERY_LEVEL + ">=?",
new String[] { batteryLevel + "" }, DB.Trigger.SORTORDER_REVERSE);
if (cursor != null && cursor.moveToFirst()) {
if (force || currentTrigger == null || currentTrigger.getDbId() != cursor.getLong(DB.INDEX_ID)) {
currentTrigger = new TriggerModel(cursor);
Logger.i("Changed to trigger " + currentTrigger.getName() + " since batterylevel is " + batteryLevel);
context.sendBroadcast(new Intent(Notifier.BROADCAST_TRIGGER_CHANGED));
resetServiceState();
return true;
} else {
// no change
return false;
}
}
} finally {
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
}
try {
cursor = context.getContentResolver().query(DB.Trigger.CONTENT_URI, DB.Trigger.PROJECTION_DEFAULT, null, null, DB.Trigger.SORTORDER_DEFAULT);
if (cursor != null && cursor.moveToFirst()) {
if (force || currentTrigger == null || currentTrigger.getDbId() != cursor.getLong(DB.INDEX_ID)) {
currentTrigger = new TriggerModel(cursor);
Logger.i("Changed to trigger " + currentTrigger.getName() + " since batterylevel is " + batteryLevel);
context.sendBroadcast(new Intent(Notifier.BROADCAST_TRIGGER_CHANGED));
resetServiceState();
return true;
}
}
} finally {
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
}
return false;
}
public void setBatteryLevel(int level) {
if (batteryLevel != level) {
batteryLevel = level;
trackCurrent();
boolean chagned = changeTrigger(false);
if (chagned) {
applyPowerProfile(false, false);
} else {
sendDeviceStatusChangedBroadcast();
}
}
}
private void sendDeviceStatusChangedBroadcast() {
context.sendBroadcast(new Intent(Notifier.BROADCAST_DEVICESTATUS_CHANGED));
}
private void trackCurrent() {
if (currentTrigger == null || SettingsStorage.getInstance().getTrackCurrentType() == SettingsStorage.TRACK_CURRENT_HIDE) {
return;
}
long powerCurrentSum = 0;
long powerCurrentCnt = 0;
if (callInProgress) {
powerCurrentSum = currentTrigger.getPowerCurrentSumCall();
powerCurrentCnt = currentTrigger.getPowerCurrentCntCall();
} else if (isBatteryHot()) {
powerCurrentSum = currentTrigger.getPowerCurrentSumHot();
powerCurrentCnt = currentTrigger.getPowerCurrentCntHot();
} else if (screenOff) {
powerCurrentSum = currentTrigger.getPowerCurrentSumScreenLocked();
powerCurrentCnt = currentTrigger.getPowerCurrentCntScreenLocked();
} else if (acPower) {
powerCurrentSum = currentTrigger.getPowerCurrentSumPower();
powerCurrentCnt = currentTrigger.getPowerCurrentCntPower();
} else {
powerCurrentSum = currentTrigger.getPowerCurrentSumBattery();
powerCurrentCnt = currentTrigger.getPowerCurrentCntBattery();
}
if (powerCurrentSum > Long.MAX_VALUE / 2) {
powerCurrentSum = powerCurrentSum / 2;
powerCurrentCnt = powerCurrentCnt / 2;
}
// powerCurrentSum *= powerCurrentCnt;
switch (SettingsStorage.getInstance().getTrackCurrentType()) {
case SettingsStorage.TRACK_CURRENT_AVG:
powerCurrentSum += BatteryHandler.getInstance().getBatteryCurrentAverage();
break;
case SettingsStorage.TRACK_BATTERY_LEVEL:
if (lastBatteryLevel != batteryLevel) {
if (lastBatteryLevelTimestamp != -1) {
long deltaBat = lastBatteryLevel - batteryLevel;
- if (deltaBat > 0) {
- long deltaT = System.currentTimeMillis() - lastBatteryLevelTimestamp;
+ long deltaT = System.currentTimeMillis() - lastBatteryLevelTimestamp;
+ if (deltaBat > 0 && deltaT > 0) {
double db = (double) deltaBat / (double) deltaT;
db = db * MILLIES_TO_HOURS;
if (powerCurrentCnt > 0) {
powerCurrentCnt = 2;
} else {
powerCurrentCnt = 0;
}
powerCurrentCnt = 2 * powerCurrentSum + Math.round(db);
}
}
lastBatteryLevel = batteryLevel;
lastBatteryLevelTimestamp = System.currentTimeMillis();
}
break;
default:
powerCurrentSum += BatteryHandler.getInstance().getBatteryCurrentNow();
break;
}
powerCurrentCnt++;
if (callInProgress) {
currentTrigger.setPowerCurrentSumCall(powerCurrentSum);
currentTrigger.setPowerCurrentCntCall(powerCurrentCnt);
} else if (batteryHot) {
currentTrigger.setPowerCurrentSumHot(powerCurrentSum);
currentTrigger.setPowerCurrentCntHot(powerCurrentCnt);
} else if (screenOff) {
currentTrigger.setPowerCurrentSumScreenLocked(powerCurrentSum);
currentTrigger.setPowerCurrentCntScreenLocked(powerCurrentCnt);
} else if (acPower) {
currentTrigger.setPowerCurrentSumPower(powerCurrentSum);
currentTrigger.setPowerCurrentCntPower(powerCurrentCnt);
} else {
currentTrigger.setPowerCurrentSumBattery(powerCurrentSum);
currentTrigger.setPowerCurrentCntBattery(powerCurrentCnt);
}
updateTrigger = false;
try {
context.getContentResolver().update(DB.Trigger.CONTENT_URI, currentTrigger.getValues(), DB.NAME_ID + "=?", new String[] { currentTrigger.getDbId() + "" });
} catch (Exception e) {
Logger.w("Error saving power current information", e);
}
updateTrigger = true;
}
public int getBatteryLevel() {
return batteryLevel;
}
public void setAcPower(boolean power) {
if (acPower != power) {
acPower = power;
sendDeviceStatusChangedBroadcast();
trackCurrent();
applyPowerProfile(false, false);
}
}
public void setScreenOff(boolean b) {
if (screenOff != b) {
screenOff = b;
trackCurrent();
applyPowerProfile(false, false);
}
}
public void setBatteryHot(boolean b) {
if (batteryHot != b) {
batteryHot = b;
trackCurrent();
applyPowerProfile(false, false);
}
}
public boolean isBatteryHot() {
return batteryHot || batteryTemperature > SettingsStorage.getInstance().getBatteryHotTemp();
}
public boolean isAcPower() {
return acPower;
}
public CharSequence getCurrentProfileName() {
if (currentProfile == null) {
return UNKNOWN;
}
return currentProfile.getProfileName();
}
public CharSequence getCurrentTriggerName() {
if (currentTrigger == null) {
return UNKNOWN;
}
return currentTrigger.getName();
}
public static void setUpdateTrigger(boolean updateTrigger) {
PowerProfiles.updateTrigger = updateTrigger;
}
public TriggerModel getCurrentTrigger() {
if (currentTrigger == null) {
currentTrigger = new TriggerModel();
}
return currentTrigger;
}
public ProfileModel getCurrentProfile() {
if (currentProfile == null) {
currentProfile = new ProfileModel();
}
return currentProfile;
}
public boolean isScreenOff() {
return screenOff;
}
public void setBatteryTemperature(int temperature) {
if (batteryTemperature != temperature) {
batteryTemperature = temperature;
sendDeviceStatusChangedBroadcast();
applyPowerProfile(false, false);
}
}
public int getBatteryTemperature() {
return batteryTemperature;
}
public void setCallInProgress(boolean b) {
if (callInProgress != b) {
callInProgress = b;
sendDeviceStatusChangedBroadcast();
applyPowerProfile(false, false);
}
}
}
| true | true | private void trackCurrent() {
if (currentTrigger == null || SettingsStorage.getInstance().getTrackCurrentType() == SettingsStorage.TRACK_CURRENT_HIDE) {
return;
}
long powerCurrentSum = 0;
long powerCurrentCnt = 0;
if (callInProgress) {
powerCurrentSum = currentTrigger.getPowerCurrentSumCall();
powerCurrentCnt = currentTrigger.getPowerCurrentCntCall();
} else if (isBatteryHot()) {
powerCurrentSum = currentTrigger.getPowerCurrentSumHot();
powerCurrentCnt = currentTrigger.getPowerCurrentCntHot();
} else if (screenOff) {
powerCurrentSum = currentTrigger.getPowerCurrentSumScreenLocked();
powerCurrentCnt = currentTrigger.getPowerCurrentCntScreenLocked();
} else if (acPower) {
powerCurrentSum = currentTrigger.getPowerCurrentSumPower();
powerCurrentCnt = currentTrigger.getPowerCurrentCntPower();
} else {
powerCurrentSum = currentTrigger.getPowerCurrentSumBattery();
powerCurrentCnt = currentTrigger.getPowerCurrentCntBattery();
}
if (powerCurrentSum > Long.MAX_VALUE / 2) {
powerCurrentSum = powerCurrentSum / 2;
powerCurrentCnt = powerCurrentCnt / 2;
}
// powerCurrentSum *= powerCurrentCnt;
switch (SettingsStorage.getInstance().getTrackCurrentType()) {
case SettingsStorage.TRACK_CURRENT_AVG:
powerCurrentSum += BatteryHandler.getInstance().getBatteryCurrentAverage();
break;
case SettingsStorage.TRACK_BATTERY_LEVEL:
if (lastBatteryLevel != batteryLevel) {
if (lastBatteryLevelTimestamp != -1) {
long deltaBat = lastBatteryLevel - batteryLevel;
if (deltaBat > 0) {
long deltaT = System.currentTimeMillis() - lastBatteryLevelTimestamp;
double db = (double) deltaBat / (double) deltaT;
db = db * MILLIES_TO_HOURS;
if (powerCurrentCnt > 0) {
powerCurrentCnt = 2;
} else {
powerCurrentCnt = 0;
}
powerCurrentCnt = 2 * powerCurrentSum + Math.round(db);
}
}
lastBatteryLevel = batteryLevel;
lastBatteryLevelTimestamp = System.currentTimeMillis();
}
break;
default:
powerCurrentSum += BatteryHandler.getInstance().getBatteryCurrentNow();
break;
}
powerCurrentCnt++;
if (callInProgress) {
currentTrigger.setPowerCurrentSumCall(powerCurrentSum);
currentTrigger.setPowerCurrentCntCall(powerCurrentCnt);
} else if (batteryHot) {
currentTrigger.setPowerCurrentSumHot(powerCurrentSum);
currentTrigger.setPowerCurrentCntHot(powerCurrentCnt);
} else if (screenOff) {
currentTrigger.setPowerCurrentSumScreenLocked(powerCurrentSum);
currentTrigger.setPowerCurrentCntScreenLocked(powerCurrentCnt);
} else if (acPower) {
currentTrigger.setPowerCurrentSumPower(powerCurrentSum);
currentTrigger.setPowerCurrentCntPower(powerCurrentCnt);
} else {
currentTrigger.setPowerCurrentSumBattery(powerCurrentSum);
currentTrigger.setPowerCurrentCntBattery(powerCurrentCnt);
}
updateTrigger = false;
try {
context.getContentResolver().update(DB.Trigger.CONTENT_URI, currentTrigger.getValues(), DB.NAME_ID + "=?", new String[] { currentTrigger.getDbId() + "" });
} catch (Exception e) {
| private void trackCurrent() {
if (currentTrigger == null || SettingsStorage.getInstance().getTrackCurrentType() == SettingsStorage.TRACK_CURRENT_HIDE) {
return;
}
long powerCurrentSum = 0;
long powerCurrentCnt = 0;
if (callInProgress) {
powerCurrentSum = currentTrigger.getPowerCurrentSumCall();
powerCurrentCnt = currentTrigger.getPowerCurrentCntCall();
} else if (isBatteryHot()) {
powerCurrentSum = currentTrigger.getPowerCurrentSumHot();
powerCurrentCnt = currentTrigger.getPowerCurrentCntHot();
} else if (screenOff) {
powerCurrentSum = currentTrigger.getPowerCurrentSumScreenLocked();
powerCurrentCnt = currentTrigger.getPowerCurrentCntScreenLocked();
} else if (acPower) {
powerCurrentSum = currentTrigger.getPowerCurrentSumPower();
powerCurrentCnt = currentTrigger.getPowerCurrentCntPower();
} else {
powerCurrentSum = currentTrigger.getPowerCurrentSumBattery();
powerCurrentCnt = currentTrigger.getPowerCurrentCntBattery();
}
if (powerCurrentSum > Long.MAX_VALUE / 2) {
powerCurrentSum = powerCurrentSum / 2;
powerCurrentCnt = powerCurrentCnt / 2;
}
// powerCurrentSum *= powerCurrentCnt;
switch (SettingsStorage.getInstance().getTrackCurrentType()) {
case SettingsStorage.TRACK_CURRENT_AVG:
powerCurrentSum += BatteryHandler.getInstance().getBatteryCurrentAverage();
break;
case SettingsStorage.TRACK_BATTERY_LEVEL:
if (lastBatteryLevel != batteryLevel) {
if (lastBatteryLevelTimestamp != -1) {
long deltaBat = lastBatteryLevel - batteryLevel;
long deltaT = System.currentTimeMillis() - lastBatteryLevelTimestamp;
if (deltaBat > 0 && deltaT > 0) {
double db = (double) deltaBat / (double) deltaT;
db = db * MILLIES_TO_HOURS;
if (powerCurrentCnt > 0) {
powerCurrentCnt = 2;
} else {
powerCurrentCnt = 0;
}
powerCurrentCnt = 2 * powerCurrentSum + Math.round(db);
}
}
lastBatteryLevel = batteryLevel;
lastBatteryLevelTimestamp = System.currentTimeMillis();
}
break;
default:
powerCurrentSum += BatteryHandler.getInstance().getBatteryCurrentNow();
break;
}
powerCurrentCnt++;
if (callInProgress) {
currentTrigger.setPowerCurrentSumCall(powerCurrentSum);
currentTrigger.setPowerCurrentCntCall(powerCurrentCnt);
} else if (batteryHot) {
currentTrigger.setPowerCurrentSumHot(powerCurrentSum);
currentTrigger.setPowerCurrentCntHot(powerCurrentCnt);
} else if (screenOff) {
currentTrigger.setPowerCurrentSumScreenLocked(powerCurrentSum);
currentTrigger.setPowerCurrentCntScreenLocked(powerCurrentCnt);
} else if (acPower) {
currentTrigger.setPowerCurrentSumPower(powerCurrentSum);
currentTrigger.setPowerCurrentCntPower(powerCurrentCnt);
} else {
currentTrigger.setPowerCurrentSumBattery(powerCurrentSum);
currentTrigger.setPowerCurrentCntBattery(powerCurrentCnt);
}
updateTrigger = false;
try {
context.getContentResolver().update(DB.Trigger.CONTENT_URI, currentTrigger.getValues(), DB.NAME_ID + "=?", new String[] { currentTrigger.getDbId() + "" });
} catch (Exception e) {
|
diff --git a/software/base/src/test/java/brooklyn/entity/software/mysql/DynamicToyMySqlEntityBuilder.java b/software/base/src/test/java/brooklyn/entity/software/mysql/DynamicToyMySqlEntityBuilder.java
index f20916a81..c84b308ae 100644
--- a/software/base/src/test/java/brooklyn/entity/software/mysql/DynamicToyMySqlEntityBuilder.java
+++ b/software/base/src/test/java/brooklyn/entity/software/mysql/DynamicToyMySqlEntityBuilder.java
@@ -1,164 +1,162 @@
package brooklyn.entity.software.mysql;
import java.io.File;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import brooklyn.entity.Entity;
import brooklyn.entity.basic.Attributes;
import brooklyn.entity.basic.BasicStartable;
import brooklyn.entity.basic.BrooklynTasks;
import brooklyn.entity.basic.EntityLocal;
import brooklyn.entity.proxying.EntityInitializer;
import brooklyn.entity.proxying.EntitySpec;
import brooklyn.entity.software.MachineLifecycleEffectorTasks;
import brooklyn.entity.software.SshEffectorTasks;
import brooklyn.location.MachineLocation;
import brooklyn.location.OsDetails;
import brooklyn.location.basic.BasicOsDetails.OsVersions;
import brooklyn.location.basic.LocalhostMachineProvisioningLocation.LocalhostMachine;
import brooklyn.location.basic.SshMachineLocation;
import brooklyn.util.ssh.BashCommands;
import brooklyn.util.task.DynamicTasks;
import brooklyn.util.task.Tasks;
import brooklyn.util.task.ssh.SshTasks;
import brooklyn.util.task.system.ProcessTaskWrapper;
import brooklyn.util.text.ComparableVersion;
import brooklyn.util.time.Duration;
import brooklyn.util.time.Time;
import com.google.common.base.Predicates;
import com.google.common.base.Splitter;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.collect.Iterables;
public class DynamicToyMySqlEntityBuilder {
private static final Logger log = LoggerFactory.getLogger(DynamicToyMySqlEntityBuilder.class);
public static EntitySpec<? extends Entity> spec() {
return EntitySpec.create(BasicStartable.class).addInitializer(MySqlEntityInitializer.class);
}
public static final String downloadUrl(Entity e, boolean isLocalhost) {
if (isLocalhost) {
for (int i=50; i>20; i--) {
String f = System.getProperty("user.home")+"/.brooklyn/repository/MySqlNode/5.5."+i+"/mysql-5.5."+i+"-osx10.6-x86_64.tar.gz";
if (new File(f).exists())
return "file://"+f;
}
}
// download
String version = "5.5.35";
String osTag = getOsTag(e);
String mirrorUrl = "http://www.mirrorservice.org/sites/ftp.mysql.com/";
return "http://dev.mysql.com/get/Downloads/MySQL-5.5/mysql-"+version+"-"+osTag+".tar.gz/from/"+mirrorUrl;
}
public static final String installDir(Entity e, boolean isLocalhost) {
String url = downloadUrl(e, isLocalhost);
String archive = Iterables.find(Splitter.on('/').omitEmptyStrings().split(url), Predicates.containsPattern(".tar.gz"));
return archive.replace(".tar.gz", "");
}
public static final String dir(Entity e) {
return "/tmp/brooklyn-mysql-"+e.getId();
}
// copied from MySqlSshDriver
public static String getOsTag(Entity e) {
// e.g. "osx10.6-x86_64"; see http://www.mysql.com/downloads/mysql/#downloads
OsDetails os = ((SshMachineLocation)Iterables.getOnlyElement(e.getLocations())).getOsDetails();
if (os == null) return "linux2.6-i686";
if (os.isMac()) {
String osp1 = os.getVersion()==null ? "osx10.5" //lowest common denominator
: new ComparableVersion(os.getVersion()).isGreaterThanOrEqualTo(OsVersions.MAC_10_6) ? "osx10.6"
: new ComparableVersion(os.getVersion()).isGreaterThanOrEqualTo(OsVersions.MAC_10_5) ? "osx10.5"
: "osx10.5"; //lowest common denominator
String osp2 = os.is64bit() ? "x86_64" : "x86";
return osp1+"-"+osp2;
}
//assume generic linux
String osp1 = "linux2.6";
String osp2 = os.is64bit() ? "x86_64" : "i686";
return osp1+"-"+osp2;
}
public static class MySqlEntityInitializer implements EntityInitializer {
public void apply(final EntityLocal entity) {
new MachineLifecycleEffectorTasks() {
@Override
protected String startProcessesAtMachine(Supplier<MachineLocation> machineS) {
DynamicTasks.queue(
SshEffectorTasks.ssh(
"mkdir "+dir(entity),
"cd "+dir(entity),
BashCommands.downloadToStdout(downloadUrl(entity, isLocalhost(machineS)))+" | tar xvz"
).summary("download mysql").returning(SshTasks.returningStdoutLoggingInfo(log, true)));
if (isLinux(machineS)) {
DynamicTasks.queue(SshEffectorTasks.ssh(BashCommands.installPackage("libaio1")));
}
DynamicTasks.queue(
SshEffectorTasks.put(".my.cnf")
.contents(String.format("[mysqld]\nbasedir=%s/%s\n", dir(entity), installDir(entity, isLocalhost(machineS)))),
SshEffectorTasks.ssh(
"cd "+dir(entity)+"/*",
"./scripts/mysql_install_db",
"nohup ./support-files/mysql.server start > out.log 2> err.log < /dev/null &"
).summary("setup and run mysql").returning(SshTasks.returningStdoutLoggingInfo(log, true)));
return "submitted start";
}
protected void postStartCustom() {
- // if it's still up after 30s assume we are good
- // remember that the run script *backgrounded* the server start command, so this is the time taken
- // to start the MySQL process, let it initialise, and give it a bit of time to make sure it stays up.
- Time.sleep(Duration.THIRTY_SECONDS);
+ // if it's still up after 5s assume we are good
+ Time.sleep(Duration.FIVE_SECONDS);
if (!DynamicTasks.queue(SshEffectorTasks.isPidFromFileRunning(dir(entity)+"/*/data/*.pid")).get()) {
// but if it's not up add a bunch of other info
log.warn("MySQL did not start: "+dir(entity));
ProcessTaskWrapper<Integer> info = DynamicTasks.queue(SshEffectorTasks.ssh(
"cd "+dir(entity)+"/*",
"cat out.log",
"cat err.log > /dev/stderr")).block();
log.info("STDOUT:\n"+info.getStdout());
log.info("STDERR:\n"+info.getStderr());
BrooklynTasks.addTagsDynamically(Tasks.current(),
BrooklynTasks.tagForStream("console (nohup stdout)", Suppliers.ofInstance(info.getStdout()), null),
BrooklynTasks.tagForStream("console (nohup stderr)", Suppliers.ofInstance(info.getStderr()), null));
throw new IllegalStateException("MySQL appears not to be running");
}
// and set the PID
entity().setAttribute(Attributes.PID,
Integer.parseInt(DynamicTasks.queue(SshEffectorTasks.ssh("cat "+dir(entity)+"/*/data/*.pid")).block().getStdout().trim()));
}
@Override
protected String stopProcessesAtMachine() {
Integer pid = entity().getAttribute(Attributes.PID);
if (pid==null) {
log.info("mysql not running");
return "No pid -- is it running?";
}
DynamicTasks.queue(SshEffectorTasks.ssh(
"cd "+dir(entity)+"/*",
"./support-files/mysql.server stop"
).summary("stop mysql"));
return "submitted stop";
}
}.attachLifecycleEffectors(entity);
}
}
private static boolean isLocalhost(Supplier<MachineLocation> machineS) {
return machineS.get() instanceof LocalhostMachine;
}
private static boolean isLinux(Supplier<MachineLocation> machineS) {
return machineS.get().getOsDetails().isLinux();
}
}
| true | true | public void apply(final EntityLocal entity) {
new MachineLifecycleEffectorTasks() {
@Override
protected String startProcessesAtMachine(Supplier<MachineLocation> machineS) {
DynamicTasks.queue(
SshEffectorTasks.ssh(
"mkdir "+dir(entity),
"cd "+dir(entity),
BashCommands.downloadToStdout(downloadUrl(entity, isLocalhost(machineS)))+" | tar xvz"
).summary("download mysql").returning(SshTasks.returningStdoutLoggingInfo(log, true)));
if (isLinux(machineS)) {
DynamicTasks.queue(SshEffectorTasks.ssh(BashCommands.installPackage("libaio1")));
}
DynamicTasks.queue(
SshEffectorTasks.put(".my.cnf")
.contents(String.format("[mysqld]\nbasedir=%s/%s\n", dir(entity), installDir(entity, isLocalhost(machineS)))),
SshEffectorTasks.ssh(
"cd "+dir(entity)+"/*",
"./scripts/mysql_install_db",
"nohup ./support-files/mysql.server start > out.log 2> err.log < /dev/null &"
).summary("setup and run mysql").returning(SshTasks.returningStdoutLoggingInfo(log, true)));
return "submitted start";
}
protected void postStartCustom() {
// if it's still up after 30s assume we are good
// remember that the run script *backgrounded* the server start command, so this is the time taken
// to start the MySQL process, let it initialise, and give it a bit of time to make sure it stays up.
Time.sleep(Duration.THIRTY_SECONDS);
if (!DynamicTasks.queue(SshEffectorTasks.isPidFromFileRunning(dir(entity)+"/*/data/*.pid")).get()) {
// but if it's not up add a bunch of other info
log.warn("MySQL did not start: "+dir(entity));
ProcessTaskWrapper<Integer> info = DynamicTasks.queue(SshEffectorTasks.ssh(
"cd "+dir(entity)+"/*",
"cat out.log",
"cat err.log > /dev/stderr")).block();
log.info("STDOUT:\n"+info.getStdout());
log.info("STDERR:\n"+info.getStderr());
BrooklynTasks.addTagsDynamically(Tasks.current(),
BrooklynTasks.tagForStream("console (nohup stdout)", Suppliers.ofInstance(info.getStdout()), null),
BrooklynTasks.tagForStream("console (nohup stderr)", Suppliers.ofInstance(info.getStderr()), null));
throw new IllegalStateException("MySQL appears not to be running");
}
// and set the PID
entity().setAttribute(Attributes.PID,
Integer.parseInt(DynamicTasks.queue(SshEffectorTasks.ssh("cat "+dir(entity)+"/*/data/*.pid")).block().getStdout().trim()));
}
@Override
protected String stopProcessesAtMachine() {
Integer pid = entity().getAttribute(Attributes.PID);
if (pid==null) {
log.info("mysql not running");
return "No pid -- is it running?";
}
DynamicTasks.queue(SshEffectorTasks.ssh(
"cd "+dir(entity)+"/*",
"./support-files/mysql.server stop"
).summary("stop mysql"));
return "submitted stop";
}
}.attachLifecycleEffectors(entity);
}
| public void apply(final EntityLocal entity) {
new MachineLifecycleEffectorTasks() {
@Override
protected String startProcessesAtMachine(Supplier<MachineLocation> machineS) {
DynamicTasks.queue(
SshEffectorTasks.ssh(
"mkdir "+dir(entity),
"cd "+dir(entity),
BashCommands.downloadToStdout(downloadUrl(entity, isLocalhost(machineS)))+" | tar xvz"
).summary("download mysql").returning(SshTasks.returningStdoutLoggingInfo(log, true)));
if (isLinux(machineS)) {
DynamicTasks.queue(SshEffectorTasks.ssh(BashCommands.installPackage("libaio1")));
}
DynamicTasks.queue(
SshEffectorTasks.put(".my.cnf")
.contents(String.format("[mysqld]\nbasedir=%s/%s\n", dir(entity), installDir(entity, isLocalhost(machineS)))),
SshEffectorTasks.ssh(
"cd "+dir(entity)+"/*",
"./scripts/mysql_install_db",
"nohup ./support-files/mysql.server start > out.log 2> err.log < /dev/null &"
).summary("setup and run mysql").returning(SshTasks.returningStdoutLoggingInfo(log, true)));
return "submitted start";
}
protected void postStartCustom() {
// if it's still up after 5s assume we are good
Time.sleep(Duration.FIVE_SECONDS);
if (!DynamicTasks.queue(SshEffectorTasks.isPidFromFileRunning(dir(entity)+"/*/data/*.pid")).get()) {
// but if it's not up add a bunch of other info
log.warn("MySQL did not start: "+dir(entity));
ProcessTaskWrapper<Integer> info = DynamicTasks.queue(SshEffectorTasks.ssh(
"cd "+dir(entity)+"/*",
"cat out.log",
"cat err.log > /dev/stderr")).block();
log.info("STDOUT:\n"+info.getStdout());
log.info("STDERR:\n"+info.getStderr());
BrooklynTasks.addTagsDynamically(Tasks.current(),
BrooklynTasks.tagForStream("console (nohup stdout)", Suppliers.ofInstance(info.getStdout()), null),
BrooklynTasks.tagForStream("console (nohup stderr)", Suppliers.ofInstance(info.getStderr()), null));
throw new IllegalStateException("MySQL appears not to be running");
}
// and set the PID
entity().setAttribute(Attributes.PID,
Integer.parseInt(DynamicTasks.queue(SshEffectorTasks.ssh("cat "+dir(entity)+"/*/data/*.pid")).block().getStdout().trim()));
}
@Override
protected String stopProcessesAtMachine() {
Integer pid = entity().getAttribute(Attributes.PID);
if (pid==null) {
log.info("mysql not running");
return "No pid -- is it running?";
}
DynamicTasks.queue(SshEffectorTasks.ssh(
"cd "+dir(entity)+"/*",
"./support-files/mysql.server stop"
).summary("stop mysql"));
return "submitted stop";
}
}.attachLifecycleEffectors(entity);
}
|
diff --git a/src/ch/ubx/startlist/client/ui/FlightEntryListGUI.java b/src/ch/ubx/startlist/client/ui/FlightEntryListGUI.java
index bef8748..c85baf1 100644
--- a/src/ch/ubx/startlist/client/ui/FlightEntryListGUI.java
+++ b/src/ch/ubx/startlist/client/ui/FlightEntryListGUI.java
@@ -1,1100 +1,1101 @@
package ch.ubx.startlist.client.ui;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import ch.ubx.startlist.client.AirfieldServiceDelegate;
import ch.ubx.startlist.client.FlightEntryListeProvider;
import ch.ubx.startlist.client.FlightEntryServiceDelegate;
import ch.ubx.startlist.client.GwtUtil;
import ch.ubx.startlist.client.LoginServiceDelegate;
import ch.ubx.startlist.client.PilotServiceDelegate;
import ch.ubx.startlist.client.RowDoubleclickHandler;
import ch.ubx.startlist.client.RowSelectionHandler;
import ch.ubx.startlist.client.TimeFormat;
import ch.ubx.startlist.client.admin.ui.AdminGUI;
import ch.ubx.startlist.shared.Airfield;
import ch.ubx.startlist.shared.FlightEntry;
import ch.ubx.startlist.shared.LoginInfo;
import ch.ubx.startlist.shared.Pilot;
import ch.ubx.startlist.shared.TextConstants;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.FocusWidget;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.MultiWordSuggestOracle;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.StackPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
public class FlightEntryListGUI implements TimeFormat, TextConstants {
private static final String STATUS_ROOT_PANEL = "flightEntryStatus";
private static final String STACK_ROOT_PANEL = "flightEntryToolBar";
private static final String LOGIN_ROOT_PANEL = "loginrootpanel";
/* GUI Widgets */
public Button newButton;
public Button modifyButton;
public Button deleteButton;
public Button discardButton;
public Button saveButton;
protected TextBox registrationGliderBox;
protected TextBox registrationTowplaneBox;
protected DateBox2 startDateBox;
protected DateBox2 endGliderDateBox;
protected DateBox2 endTowplaneDateBox;
protected Label status;
protected StackPanel stackPanel;
public ListBox placeListBox;
public ListBox yearListBox;
public ListBox dateListBox;
public Button prevDayPushButton;
public Button nextDayPushButton;
public FlexTable flightEntryFlexTable;
protected DateBox2 dateBox;
protected SuggestBox2 pilotNameBox;
protected SuggestBox2 passengerOrInstructorNameBox;
protected SuggestBox2 towplanePilotNameBox;
protected CheckBox trainingCheckBox;
protected TextBox remarksTextBox;
protected SuggestBox2 landingPlacesSuggestBox;
public Button btnClose;
public FlightEntryServiceDelegate flightEntryService;
public LoginServiceDelegate loginServiceDelegate;
public AirfieldServiceDelegate airfieldServiceDelegate;
public PilotServiceDelegate pilotServiceDelegate;
/* Data model */
private FlightEntry currentFlightEntry;
private VerticalPanel mainPanel;
private DynaTableWidget dynaTableWidget;
private FlightEntryListeProvider provider = new FlightEntryListeProvider();
private VerticalPanel verticaPanel_2;
private RowSelectionHandler rowSelectionHandler = null;
private RowDoubleclickHandler rowDoubleclickHandler = null;
private Map<String, Long> strToDate = new LinkedHashMap<String, Long>();
private ListBox allPlacesListBox;
private MultiWordSuggestOracle landingPlacesSuggest = new MultiWordSuggestOracle();
private MultiWordSuggestOracle pilotNamesSuggest = new MultiWordSuggestOracle();
private Set<Airfield> allAirfields;
private DialogBox flightEntryDialogBox;
private FlightEntryValidator validator;
private HorizontalPanel operationNewModDel;
private Anchor signInLink;
private Label loggedInAs;
private LoginInfo currentLoginInfo;
private HTML excelLinkHTML;
private AdminGUI adminGUI;
private FlightEntry lastflightEntry;
// Get preferred place from url. If not defined null
private String prefPlace = Window.Location.getParameter("place");
// Get the current version
//private String version = SystemProperty.version.get(); // TODO -- display somewhere on screen.
/**
* @wbp.parser.entryPoint
*/
public void init() {
placeWidgets();
}
private void placeWidgets() {
// Login panel
HorizontalPanel loginPanel = new HorizontalPanel();
RootPanel.get(LOGIN_ROOT_PANEL).add(loginPanel, 10, 60);
signInLink = new Anchor();
loginPanel.add(signInLink);
loggedInAs = new Label();
loginPanel.add(loggedInAs);
HorizontalPanel statusPanel = new HorizontalPanel();
RootPanel.get(STATUS_ROOT_PANEL).add(statusPanel, 10, 100);
status = new Label();
statusPanel.add(status);
//statusPanel.add(new Label(version)); // TODO -- ???
stackPanel = new StackPanel();
RootPanel.get(STACK_ROOT_PANEL).add(stackPanel, 10, 130);
// main panel
mainPanel = new VerticalPanel();
stackPanel.add(mainPanel, TXT_STARTLIST, false);
HorizontalPanel selectionPanel = new HorizontalPanel();
selectionPanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
selectionPanel.addStyleName("selectionPanel");
mainPanel.add(selectionPanel);
Label yearLabel = new Label(TXT_YEAR);
selectionPanel.add(yearLabel);
yearListBox = new ListBox();
selectionPanel.add(yearListBox);
yearListBox.setVisibleItemCount(1);
Label ortLabel = new Label(TXT_START_PLACE);
selectionPanel.add(ortLabel);
placeListBox = new ListBox();
selectionPanel.add(placeListBox);
placeListBox.setVisibleItemCount(1);
HorizontalPanel datePanel = new HorizontalPanel();
datePanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
datePanel.addStyleName("datePanel");
selectionPanel.add(datePanel);
Label lblDatum = new Label(TXT_FLIGHT_DATUM);
datePanel.add(lblDatum);
prevDayPushButton = new Button(TXT_PREV);
+ prevDayPushButton.setText("<");
datePanel.add(prevDayPushButton);
dateListBox = new ListBox();
datePanel.add(dateListBox);
dateListBox.setVisibleItemCount(1);
nextDayPushButton = new Button(TXT_NEXT);
datePanel.add(nextDayPushButton);
Label dummyLabel = new Label();
dummyLabel.setWidth("20px");
selectionPanel.add(dummyLabel);
excelLinkHTML = new HTML();
selectionPanel.add(excelLinkHTML);
// flight entry table starts here
String[] columns = new String[] { TXT_START_TIME, TXT_LANDING_TIME_TOWPLANE, TXT_DURATION_TOWPLANE, TXT_SHORT_REGISTRATION_TOWPLANE,
TXT_LANDING_TIME_GLIDER, TXT_DURATION_GLIDER, TXT_SHORT_REGISTRATION_GLIDER, TXT_PILOT, TXT_PASSENGER_OR_INSTRUCTOR, TXT_TRAINING, TXT_REMARKS };
String[] styles = new String[] { "starttime", "endtimetowplane", "dauertowplane", "registrationtowplane", "endtimeglider", "dauerglider",
"registrationglider", "pilot", "passengerorinstructor", "schulung", "bemerkungen" };
verticaPanel_2 = new VerticalPanel();
mainPanel.add(verticaPanel_2);
dynaTableWidget = new DynaTableWidget(provider, columns, styles, 20);
dynaTableWidget.setWidth("1200px");
verticaPanel_2.add(dynaTableWidget);
dynaTableWidget.setStatusText("");
operationNewModDel = new HorizontalPanel();
operationNewModDel.setVisible(false);
verticaPanel_2.add(operationNewModDel);
newButton = new Button(TXT_NEW);
newButton.setEnabled(true);
operationNewModDel.add(newButton);
modifyButton = new Button(TXT_MODIFY);
modifyButton.setEnabled(false);
operationNewModDel.add(modifyButton);
deleteButton = new Button(TXT_DELETE);
deleteButton.setEnabled(false);
operationNewModDel.add(deleteButton);
// dialog for adding or modifying flight entrys
flightEntryDialogBox = new DialogBox();
VerticalPanel flightEntryVerticaPanel = new VerticalPanel();
flightEntryDialogBox.add(flightEntryVerticaPanel);
flightEntryDialogBox.hide();
flightEntryDialogBox.setModal(true);
flightEntryFlexTable = new FlexTable();
flightEntryVerticaPanel.add(flightEntryFlexTable);
// row 0: basic information, date and place
Label lblDatum2 = new Label(TXT_FLIGHT_DATUM);
flightEntryFlexTable.setWidget(0, 0, lblDatum2);
dateBox = new DateBox2();
dateBox.setFormat(DD_MMM_YYYY_FORMAT);
flightEntryFlexTable.setWidget(0, 1, dateBox);
Label lblAllPlaces = new Label(TXT_START_PLACE);
flightEntryFlexTable.setWidget(0, 2, lblAllPlaces);
allPlacesListBox = new ListBox();
flightEntryFlexTable.setWidget(0, 3, allPlacesListBox);
Label lblAllSuggestPlaces = new Label(TXT_LANDING_PLACE);
flightEntryFlexTable.setWidget(0, 4, lblAllSuggestPlaces);
landingPlacesSuggestBox = new SuggestBox2(landingPlacesSuggest);
flightEntryFlexTable.setWidget(0, 5, landingPlacesSuggestBox);
// row 1: time information
Label lblStart = new Label(TXT_START_TIME);
flightEntryFlexTable.setWidget(1, 0, lblStart);
startDateBox = new DateBox2();
startDateBox.setFormat(MM_HH_FORMAT);
startDateBox.getDatePicker().setVisible(false);
flightEntryFlexTable.setWidget(1, 1, startDateBox);
Label lblEndeTowplane = new Label(TXT_LANDING_TIME_TOWPLANE);
flightEntryFlexTable.setWidget(1, 2, lblEndeTowplane);
endTowplaneDateBox = new DateBox2();
endTowplaneDateBox.setFormat(MM_HH_FORMAT);
endTowplaneDateBox.getDatePicker().setVisible(false);
flightEntryFlexTable.setWidget(1, 3, endTowplaneDateBox);
Label lblEndeGlider = new Label(TXT_LANDING_TIME_GLIDER);
flightEntryFlexTable.setWidget(1, 4, lblEndeGlider);
endGliderDateBox = new DateBox2();
endGliderDateBox.setFormat(MM_HH_FORMAT);
endGliderDateBox.getDatePicker().setVisible(false);
flightEntryFlexTable.setWidget(1, 5, endGliderDateBox);
// row 2: registration of involved planes and towplane pilot
Label lblTowplane = new Label(TXT_REGISTRATION_TOWPLANE);
flightEntryFlexTable.setWidget(2, 0, lblTowplane);
registrationTowplaneBox = new TextBox();
flightEntryFlexTable.setWidget(2, 1, registrationTowplaneBox);
Label lblGlider = new Label(TXT_REGISTRATION_GLIDER);
flightEntryFlexTable.setWidget(2, 2, lblGlider);
registrationGliderBox = new TextBox();
flightEntryFlexTable.setWidget(2, 3, registrationGliderBox);
Label lblTowplanePilot = new Label(TXT_TOWPLANE_PILOT);
flightEntryFlexTable.setWidget(2, 4, lblTowplanePilot);
towplanePilotNameBox = new SuggestBox2(pilotNamesSuggest);
flightEntryFlexTable.setWidget(2, 5, towplanePilotNameBox);
// row 3: pilot information
Label lblPilot = new Label(TXT_PILOT);
flightEntryFlexTable.setWidget(3, 0, lblPilot);
pilotNameBox = new SuggestBox2(pilotNamesSuggest);
flightEntryFlexTable.setWidget(3, 1, pilotNameBox);
Label lblPassengerOrInstructor = new Label(TXT_PASSENGER_OR_INSTRUCTOR);
flightEntryFlexTable.setWidget(3, 2, lblPassengerOrInstructor);
passengerOrInstructorNameBox = new SuggestBox2(pilotNamesSuggest);
flightEntryFlexTable.setWidget(3, 3, passengerOrInstructorNameBox);
Label lblTraining = new Label(TXT_TRAINING);
flightEntryFlexTable.setWidget(3, 4, lblTraining);
trainingCheckBox = new CheckBox();
flightEntryFlexTable.setWidget(3, 5, trainingCheckBox);
// row 4: remarks
Label lblBemerkungen = new Label(TXT_REMARKS);
flightEntryFlexTable.setWidget(4, 0, lblBemerkungen);
remarksTextBox = new TextBox();
remarksTextBox.setVisibleLength(80);
flightEntryFlexTable.setWidget(4, 1, remarksTextBox);
flightEntryFlexTable.getFlexCellFormatter().setColSpan(4, 1, 5);// TODO - does not work?
HorizontalPanel operationsPanel;
operationsPanel = new HorizontalPanel();
operationsPanel.setSpacing(5);
flightEntryVerticaPanel.add(operationsPanel);
saveButton = new Button(TXT_SAVE);
saveButton.setEnabled(false);
operationsPanel.add(saveButton);
discardButton = new Button(TXT_DISCARD);
discardButton.setEnabled(false);
operationsPanel.add(discardButton);
btnClose = new Button(TXT_CLOSE);
btnClose.setEnabled(true);
operationsPanel.add(btnClose);
// Set tab order
setTabOrder(dateBox, allPlacesListBox, landingPlacesSuggestBox, startDateBox, endTowplaneDateBox, endGliderDateBox, registrationTowplaneBox,
registrationGliderBox, towplanePilotNameBox, pilotNameBox, passengerOrInstructorNameBox, trainingCheckBox, remarksTextBox,
saveButton, discardButton, btnClose);
loadYears();
loadAllPlaces();
loadAllPilots();
enablePilotFields(false);
initLogin();
}
public void loadYears() {
flightEntryService.listYears();
}
private void initLogin() {
loginServiceDelegate.login(GWT.getHostPageBaseURL());
}
private void loadPlaces(int year) {
flightEntryService.listPlaces(year);
}
private void loadAllPlaces() {
airfieldServiceDelegate.listAirfields();
}
private void loadAllPilots() {
pilotServiceDelegate.listPilots();
}
private void reload() {
reload(null);
}
private void reload(FlightEntry flightEntry) {
if (flightEntry != null) {
provider.setCurrentPlace(flightEntry.getPlace());
provider.setCurrentDate(flightEntry.getStartTimeInMillis());
} else {
provider.setCurrentPlace(placeListBox.getItemCount() > 0 ? placeListBox.getItemText(placeListBox.getSelectedIndex()) : "");
provider.setCurrentDate(strToDate.get(dateListBox.getItemText(dateListBox.getSelectedIndex())));
}
lastflightEntry = flightEntry;
dynaTableWidget.reload();
if (rowSelectionHandler == null) {
rowSelectionHandler = new RowSelectionHandler() {
@Override
public void rowSelected(int row, boolean selected) {
enablePilotFields(false);
if (selected) {
FlightEntry flightEntry = provider.getFlightEntry(row);
if (flightEntry == null) {
clearForm();
newButton.setEnabled(true);
} else {
loadForm(flightEntry);
newButton.setEnabled(false);
enableCUDButtons();
}
} else {
newButton.setEnabled(true);
clearForm();
}
}
};
dynaTableWidget.addRowSelectionHandler(rowSelectionHandler);
}
if (rowDoubleclickHandler == null) {
rowDoubleclickHandler = new RowDoubleclickHandler() {
@Override
public void rowDoubleclicked(int row) {
enablePilotFields(false);
FlightEntry flightEntry = provider.getFlightEntry(row);
if (flightEntry == null) {
clearForm();
} else {
// open modify dialog
loadForm(flightEntry);
newButton.setEnabled(false);
modifyFlightEntry();
}
}
};
dynaTableWidget.addRowDoubleclickHandler(rowDoubleclickHandler);
}
}
private void enablePilotFields(boolean enable) {
dateBox.setEnabled(enable);
pilotNameBox.setEnabled(enable);
passengerOrInstructorNameBox.setEnabled(enable);
towplanePilotNameBox.setEnabled(enable);
startDateBox.setEnabled(enable);
endGliderDateBox.setEnabled(enable);
endTowplaneDateBox.setEnabled(enable);
trainingCheckBox.setEnabled(enable);
remarksTextBox.setEnabled(enable);
allPlacesListBox.setEnabled(enable);
landingPlacesSuggestBox.setEnabled(enable);
registrationGliderBox.setEnabled(enable);
registrationTowplaneBox.setEnabled(enable);
}
private void clearForm() {
disableCUDButtons();
currentFlightEntry = null;
dateBox.setValue(null);
pilotNameBox.setValue(null);
passengerOrInstructorNameBox.setValue(null);
towplanePilotNameBox.setValue(null);
startDateBox.setValue(null);
endGliderDateBox.setValue(null);
endTowplaneDateBox.setValue(null);
trainingCheckBox.setValue(false);
remarksTextBox.setValue(null);
allPlacesListBox.clear();
landingPlacesSuggestBox.setValue(null);
registrationGliderBox.setValue(null);
registrationTowplaneBox.setValue(null);
}
private void disableCUDButtons() {
modifyButton.setEnabled(false);
deleteButton.setEnabled(false);
}
private void enableCUDButtons() {
modifyButton.setEnabled(true);
deleteButton.setEnabled(true);
disableSCButtons();
}
private void enableSCButtons(boolean enable) {
saveButton.setEnabled(enable);
discardButton.setEnabled(enable);
btnClose.setEnabled(!enable);
}
private void disableSCButtons() {
saveButton.setEnabled(false);
discardButton.setEnabled(false);
}
private void loadForm(FlightEntry flightEntry) {
boolean newEntry = flightEntry.getId() == null;
currentFlightEntry = flightEntry;
// Date date = newEntry ? new Date() : new
// Date(strToDate.get(dateListBox.getItemText(dateListBox.getSelectedIndex())));
// Get date from current selected
Date date = new Date(strToDate.get(dateListBox.getItemText(dateListBox.getSelectedIndex())));
dateBox.setValue(date);
if (flightEntry.isStartTimeValid()) {
date.setTime(flightEntry.getStartTimeInMillis());
startDateBox.setValue(date);
} else {
Date dateNow = new Date();
startDateBox.setValue(dateNow);
}
if (flightEntry.isEndTimeGliderValid()) {
date.setTime(flightEntry.getEndTimeGliderInMillis());
endGliderDateBox.setValue(date);
} else {
endGliderDateBox.setValue(null);
}
if (flightEntry.isEndTimeTowplaneValid()) {
date.setTime(flightEntry.getEndTimeTowplaneInMillis());
endTowplaneDateBox.setValue(date);
} else {
endTowplaneDateBox.setValue(null);
}
pilotNameBox.setValue(flightEntry.getPilot());
passengerOrInstructorNameBox.setValue(flightEntry.getPassengerOrInstructor());
towplanePilotNameBox.setValue(flightEntry.getTowplanePilot());
trainingCheckBox.setValue(flightEntry.isTraining());
remarksTextBox.setValue(flightEntry.getRemarks());
if (newEntry) {
String pl = placeListBox.getItemCount() > 0 ? placeListBox.getValue(placeListBox.getSelectedIndex()) : "";
flightEntry.setPlace(pl);
pilotNameBox.setValue(""); // don't set pilot name from login info at the moment
// pilotNameBox.setValue(currentLoginInfo.getLastName() + " " + currentLoginInfo.getFirstName());
}
GwtUtil.setItems(allPlacesListBox, GwtUtil.toAirfieldNames(allAirfields));
// TODO - it may be slow if lots of airfields -> optimize!
for (int i = 0; i < allPlacesListBox.getItemCount(); i++) {
if (flightEntry.getPlace().equals(allPlacesListBox.getValue(i))) {
allPlacesListBox.setSelectedIndex(i);
break;
}
}
landingPlacesSuggestBox.setValue(flightEntry.getLandingPlace());
registrationGliderBox.setValue(flightEntry.getRegistrationGlider());
registrationTowplaneBox.setValue(flightEntry.getRegistrationTowplane());
}
private void saveForm(FlightEntry flightEntry) {
// set name of pilot
String pilot = pilotNameBox.getValue();
if (pilot.length() == 0) {
pilot = "<Unknown>";
}
flightEntry.setPilot(pilot);
// set start time
Date date = null;
// TODO - find a better way to check
try {
date = startDateBox.getValue();
} catch (Exception e) {
// TODO: handle exception
}
flightEntry.setStartTimeValid(date != null);
if (flightEntry.isStartTimeValid()) {
toYMD(dateBox.getValue(), date);
flightEntry.setStartTimeInMillis(date.getTime());
} else {
// TODO - very crude workaround for time zone problem
date = dateBox.getValue();
long offset = timeZone.getStandardOffset();
date.setTime(date.getTime() - (offset * 60000));
flightEntry.setStartTimeInMillis(date.getTime());
}
// set landing time glider
date = null;
// TODO - find a better way to check
try {
date = endGliderDateBox.getValue();
} catch (Exception e) {
// TODO: handle exception
}
flightEntry.setEndTimeGliderValid(date != null);
if (flightEntry.isEndTimeGliderValid()) {
toYMD(dateBox.getValue(), date);
flightEntry.setEndTimeGliderInMillis(date.getTime());
} else {
flightEntry.setEndTimeGliderInMillis(0);
}
// set landing time towplane
date = null;
// TODO - find a better way to check
try {
date = endTowplaneDateBox.getValue();
} catch (Exception e) {
// TODO: handle exception
}
flightEntry.setEndTimeTowplaneValid(date != null);
if (flightEntry.isEndTimeTowplaneValid()) {
toYMD(dateBox.getValue(), date);
flightEntry.setEndTimeTowplaneInMillis(date.getTime());
} else {
flightEntry.setEndTimeTowplaneInMillis(0);
}
// set rest of values
flightEntry.setTraining(trainingCheckBox.getValue());
flightEntry.setRemarks(remarksTextBox.getValue());
flightEntry.setPlace(allPlacesListBox.getValue(allPlacesListBox.getSelectedIndex()));
flightEntry.setLandingPlace(landingPlacesSuggestBox.getValue());
flightEntry.setRegistrationGlider(registrationGliderBox.getValue());
flightEntry.setRegistrationTowplane(registrationTowplaneBox.getValue());
flightEntry.setPassengerOrInstructor(passengerOrInstructorNameBox.getValue());
flightEntry.setTowplanePilot(towplanePilotNameBox.getValue());
}
private void modifyFlightEntry() {
if (currentFlightEntry.isModifiable()) {
enablePilotFields(true);
flightEntryDialogBox.setTitle(TXT_TITLE_MODIFY_FLIGHT);
flightEntryDialogBox.setHTML(TXT_MODIFY_FLIGHT);
flightEntryDialogBox.setPopupPosition(modifyButton.getAbsoluteLeft() + modifyButton.getOffsetWidth(),
modifyButton.getAbsoluteTop() - flightEntryDialogBox.getOffsetHeight() - 260);
flightEntryDialogBox.setWidth("800px");
flightEntryDialogBox.show();
// set focus depending on content of current flight entry, optimized for live entry through "Flugdienstleiter"
if (!currentFlightEntry.isStartTimeValid()) {
startDateBox.setFocus(true); // no start time yet, FDL will want to enter it first
} else if (!currentFlightEntry.isEndTimeTowplaneValid()) {
endTowplaneDateBox.setFocus(true); // usecase: towplane landed, FDL wants to enter landing time of towplane
} else if (!currentFlightEntry.isEndTimeGliderValid()) {
endGliderDateBox.setFocus(true); // usecase: glider landed, FDL wants to enter landing time of glider
} else if (currentFlightEntry.getRegistrationTowplane().length() == 0) {
registrationTowplaneBox.setFocus(true);
} else if (currentFlightEntry.getRegistrationGlider().length() == 0) {
registrationGliderBox.setFocus(true);
} else if (currentFlightEntry.getPilot().length() == 0) {
pilotNameBox.setFocus(true);
} else if (currentFlightEntry.getPassengerOrInstructor().length() == 0) {
passengerOrInstructorNameBox.setFocus(true);
} else if (currentFlightEntry.getTowplanePilot().length() == 0) {
towplanePilotNameBox.setFocus(true);
} else if (currentFlightEntry.getRemarks().length() == 0) {
remarksTextBox.setFocus(true);
} else if (currentFlightEntry.getLandingPlace().length() == 0) {
landingPlacesSuggestBox.setFocus(true);
} else {
remarksTextBox.setFocus(true);
}
disableCUDButtons();
saveButton.setEnabled(false);
discardButton.setEnabled(false);
btnClose.setEnabled(true);
} else {// Not the owner and not Admin
showMidifiableDialog(currentFlightEntry, TXT_ERROR_FLIGHTENTRY_MODIFY_OWNER_MISMATCH);
}
}
@SuppressWarnings("deprecation")
private void toYMD(Date srcDate, Date dstDate) {
dstDate.setDate(srcDate.getDate());
dstDate.setMonth(srcDate.getMonth());
dstDate.setYear(srcDate.getYear());
}
public void gui_eventNewButtonClicked() {
disableCUDButtons();
enablePilotFields(true);
FlightEntry flightEntry = new FlightEntry();
loadForm(flightEntry);
flightEntryDialogBox.setTitle(TXT_TITLE_CREATE_NEW_FLIGHT);
flightEntryDialogBox.setText(TXT_CREATE_NEW_FLIGHT);
flightEntryDialogBox.setPopupPosition(newButton.getAbsoluteLeft() + newButton.getOffsetWidth(),
newButton.getAbsoluteTop() - flightEntryDialogBox.getOffsetHeight() - 260);
flightEntryDialogBox.setWidth("800px");
flightEntryDialogBox.show();
startDateBox.setFocus(true);
newButton.setEnabled(false);
saveButton.setEnabled(true);
discardButton.setEnabled(true);
btnClose.setEnabled(false);
}
public void gui_eventModifyButtonClicked() {
modifyFlightEntry();
}
public void gui_eventSaveButtonClicked() {
if (currentFlightEntry == null) {
return;
}
if (validator == null) {
validator = new FlightEntryValidator(this);
}
if (validator.isValid()) {
disableSCButtons();
saveForm(currentFlightEntry);
flightEntryService.createOrUpdateFlightEntry(currentFlightEntry);
clearForm();
enablePilotFields(false);
newButton.setEnabled(true);
flightEntryDialogBox.hide();
}
}
public void gui_eventDiscardClicked() {
disableSCButtons();
clearForm();
enablePilotFields(false);
newButton.setEnabled(true);
dynaTableWidget.resetSelection();
flightEntryDialogBox.hide();
}
public void gui_eventCloseClicked() {
gui_eventDiscardClicked();
}
private boolean hasDate(FlightEntry flightEntry) {
return strToDate.containsKey(DATE_FORMAT.format(new Date(flightEntry.getStartTimeInMillis())));
}
private boolean hasPlace(FlightEntry flightEntry) {
Set<String> items = getItemList(placeListBox);
return items.contains(flightEntry.getPlace());
}
@SuppressWarnings("deprecation")
private boolean hasYear(FlightEntry flightEntry) {
Set<String> items = getItemList(yearListBox);
Date date = new Date(flightEntry.getStartTimeInMillis());
return items.contains(String.valueOf(date.getYear() + 1900));
}
private Set<String> getItemList(ListBox listBox) {
Set<String> items = new TreeSet<String>();
for (int i = 0; i < listBox.getItemCount(); i++) {
items.add(listBox.getValue(i));
}
return items;
}
private void setSelected(ListBox listBox, String item) {
for (int i = 0; i < listBox.getItemCount(); i++) {
if (item.equals(listBox.getValue(i))) {
listBox.setSelectedIndex(i);
break;
}
}
}
public void gui_eventDeleteButtonClicked() {
if (currentFlightEntry == null) {
return;
}
if (currentFlightEntry.isDeletable()) {
final DialogBox deleteDialogBox = new DialogBox();
deleteDialogBox.setModal(true);
deleteDialogBox.setPopupPosition(deleteButton.getAbsoluteLeft() + deleteButton.getOffsetWidth(),
deleteButton.getAbsoluteTop() - deleteDialogBox.getOffsetHeight());
deleteDialogBox.setHTML(TXT_REALLY_DELETE_QUESWTION);
Button yesButton = new Button(TXT_YES);
yesButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
disableCUDButtons();
flightEntryService.removeFlightEntry(currentFlightEntry);
reload();
deleteDialogBox.hide();
}
});
Button noButton = new Button(TXT_NO);
noButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
deleteDialogBox.hide();
}
});
HorizontalPanel hp = new HorizontalPanel();
hp.add(yesButton);
hp.add(noButton);
deleteDialogBox.setWidget(hp);
deleteDialogBox.show();
} else { // Not the owner and not Admin
showMidifiableDialog(currentFlightEntry, TXT_ERROR_FLIGHTENTRY_DELETE_OWNER_MISMATCH);
}
}
private void showMidifiableDialog(FlightEntry flightEntry, String msg) {
final DialogBox notmodDialogBox = new DialogBox();
notmodDialogBox.setModal(true);
notmodDialogBox.setPopupPosition(deleteButton.getAbsoluteLeft() + deleteButton.getOffsetWidth(),
deleteButton.getAbsoluteTop() - notmodDialogBox.getOffsetHeight());
notmodDialogBox.setHTML(msg + " " + flightEntry.getCreator());
Button okButton = new Button(TXT_OK);
okButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
disableCUDButtons();
notmodDialogBox.hide();
}
});
HorizontalPanel hp = new HorizontalPanel();
hp.add(okButton);
notmodDialogBox.setWidget(hp);
notmodDialogBox.show();
}
private void setTabOrder(Widget... widgets) {
int idx = 0;
for (Widget widget : widgets) {
Widget wdg = widget;
if (wdg instanceof SuggestBox2) {
wdg = ((SuggestBox2) wdg).getFocusWidget();
} else {
if (wdg instanceof DateBox2) {
wdg = ((DateBox2) wdg).getFocusWidget();
}
}
if (wdg instanceof FocusWidget) {
((FocusWidget) wdg).setTabIndex(idx++);
}
}
}
@SuppressWarnings("deprecation")
public void service_eventUpdateSuccessful(FlightEntry flightEntry) {
status.setText(TXT_SUCCESS_ADD_FLIGHTENTRY);
if (placeListBox.getItemCount() == 0) {
placeListBox.addItem(flightEntry.getPlace());
}
if (!hasYear(flightEntry)) {
loadYears();
} else {
Date date = new Date(flightEntry.getStartTimeInMillis());
setSelected(yearListBox, String.valueOf(date.getYear() + 1900));
if (!hasPlace(flightEntry)) {
date = new Date(flightEntry.getStartTimeInMillis());
loadPlaces(date.getYear() + 1900);
} else {
setSelected(placeListBox, flightEntry.getPlace());
if (!hasDate(flightEntry)) {
loadDates();
} else {
String dateStr = DATE_FORMAT.format(new Date(flightEntry.getStartTimeInMillis()));
setSelected(dateListBox, dateStr);
reload(flightEntry);
}
}
}
}
public void service_eventRemoveFlightEntrySuccessful(FlightEntry flightEntry) {
status.setText(TXT_SUCCESS_REMOVE_FLIGHTENTRY);
reload();
}
public void service_eventUpdateFlightEntryFailed(Throwable caught) {
status.setText(TXT_ERROR_FLIGHTENTRY_UPDATE);
}
public void service_eventAddFlightEntryFailed(Throwable caught) {
status.setText(TXT_ERROR_FLIGHTENTRY_ADD);
}
public void service_eventRemoveFlightEntryFailed(Throwable caught) {
status.setText(TXT_ERROR_FLIGHTENTRY_DELETE);
}
public void service_eventListFlightEntrysFailed(Throwable caught) {
status.setText(TXT_ERROR_LIST_LOAD);
}
public void gui_eventPlaceListBoxChanged() {
clearForm();
loadDates();
}
public void service_eventListPlacesSuccessful(Set<String> places) {
String oldPlace = "";
if (lastflightEntry != null) {
oldPlace = lastflightEntry.getPlace();
} else {
int oldIdx = placeListBox.getSelectedIndex();
if (oldIdx >= 0) {
oldPlace = placeListBox.getItemText(placeListBox.getSelectedIndex());
}
}
int newOldPlaceIdx = -1;
int homePlaceIdx = -1;
placeListBox.clear();
for (String place : places) {
placeListBox.addItem(place);
if (newOldPlaceIdx == -1 && place.equals(oldPlace)) {
newOldPlaceIdx = placeListBox.getItemCount() - 1;
}
if (currentLoginInfo != null && homePlaceIdx == -1 && currentLoginInfo.getHomeAirfield() != null
&& currentLoginInfo.getHomeAirfield().compareToIgnoreCase(place) == 0) {
homePlaceIdx = placeListBox.getItemCount() - 1;
} else if (prefPlace != null && (prefPlace.compareToIgnoreCase(place) == 0)) {
homePlaceIdx = placeListBox.getItemCount() - 1;
}
}
if (newOldPlaceIdx != -1) {
placeListBox.setSelectedIndex(newOldPlaceIdx);
} else if (homePlaceIdx != -1) {
placeListBox.setSelectedIndex(homePlaceIdx);
} else {
placeListBox.setSelectedIndex(0);
}
loadDates();
}
private void loadDates() {
String place = placeListBox.getItemCount() > 0 ? placeListBox.getItemText(placeListBox.getSelectedIndex()) : "";
int year = Integer.parseInt(yearListBox.getItemText(yearListBox.getSelectedIndex()));
flightEntryService.listDates(place, year);
}
public void service_eventListPlacesFailed(Throwable caught) {
// TODO Auto-generated method stub
}
/*
* Year handling
*/
public void gui_eventYearListBoxChanged() {
clearForm();
int year = Integer.parseInt(yearListBox.getItemText(yearListBox.getSelectedIndex()));
flightEntryService.listPlaces(year);
}
public void service_eventListYearsFailed(Throwable caught) {
// TODO Auto-generated method stub
}
public void service_eventListYearsSuccessful(Set<Integer> years) {
yearListBox.clear();
for (Integer year : years) {
yearListBox.addItem(Integer.toString(year));
}
yearListBox.setSelectedIndex(yearListBox.getItemCount() - 1);
int year = Integer.parseInt(yearListBox.getItemText(yearListBox.getSelectedIndex()));
flightEntryService.listPlaces(year);
}
/*
* Day handling
*/
private void adjustPrevNextDayButtons() {
nextDayPushButton.setEnabled(dateListBox.getSelectedIndex() < dateListBox.getItemCount() - 1);
prevDayPushButton.setEnabled(dateListBox.getSelectedIndex() > 0);
clearForm();
}
@SuppressWarnings("deprecation")
public void gui_eventDateListBoxChanged() {
adjustPrevNextDayButtons();
// adjust link to excel file
Date date = new Date(strToDate.get(dateListBox.getItemText(dateListBox.getSelectedIndex())));
String link = GWT.getModuleBaseURL() + "excelfile" + "/" + yearListBox.getValue(yearListBox.getSelectedIndex()) + "/" + date.getMonth() + "/"
+ date.getDate() + "/" + placeListBox.getValue(placeListBox.getSelectedIndex());
excelLinkHTML.setHTML("<a href=\"" + link + "\">Excel</a>");
// reload table values
reload();
}
public void gui_eventNextDayPushButtonClicked() {
if (dateListBox.getSelectedIndex() < dateListBox.getItemCount() - 1) {
dateListBox.setItemSelected(dateListBox.getSelectedIndex() + 1, true);
}
gui_eventDateListBoxChanged();
}
public void gui_eventPrevDayPushButtonClicked() {
if (dateListBox.getSelectedIndex() > 0) {
dateListBox.setItemSelected(dateListBox.getSelectedIndex() - 1, true);
}
gui_eventDateListBoxChanged();
}
public void service_eventListDatesFailed(Throwable caught) {
// TODO Auto-generated method stub
}
@SuppressWarnings("deprecation")
public void service_eventListDatesSuccessful(Set<Long> dates) {
dateListBox.clear();
strToDate.clear();
for (Long dateInMillies : dates) {
String dateStr = DATE_FORMAT.format(new Date(dateInMillies), timeZone);
dateListBox.addItem(dateStr);
strToDate.put(dateStr, dateInMillies);
}
if (lastflightEntry != null) {
Date feDate = new Date(lastflightEntry.getStartTimeInMillis());
for (int i = 0; i < dateListBox.getItemCount(); i++) {
Date date = new Date(strToDate.get(dateListBox.getValue(i)));
if (date.getYear() == feDate.getYear() && date.getMonth() == feDate.getMonth() && date.getDate() == feDate.getDate()) {
dateListBox.setSelectedIndex(i);
break;
}
}
} else {
dateListBox.setSelectedIndex(dateListBox.getItemCount() - 1);
}
gui_eventDateListBoxChanged();
}
public void service_eventListAllPlacesFailed(Throwable caught) {
// TODO Auto-generated method stub
}
public void service_eventAllListPlacesSuccessful(Set<Airfield> airfields) {
allAirfields = airfields;
GwtUtil.setItems(allPlacesListBox, GwtUtil.toAirfieldNames(airfields));
for (String place : GwtUtil.toAirfieldNames(airfields)) {
landingPlacesSuggest.add(place);
}
}
public void service_eventAllListPilotsSuccessful(Set<Pilot> pilots) {
for (String pilot : GwtUtil.toPilotNames(pilots)){
pilotNamesSuggest.add(pilot);
}
}
public void gui_eventModifyPilotForm() {
if (currentFlightEntry.getId() != null) {
// compare only modified entry
// TODO - should we use tmpFlightEntry for save?
FlightEntry tmpFlightEntry = currentFlightEntry.copy();
saveForm(tmpFlightEntry);
enableSCButtons(tmpFlightEntry.compareTo(currentFlightEntry) != 0);
}
}
public void service_eventLoginSuccessful(LoginInfo loginInfo) {
if (loginInfo.isLoggedIn()) {
currentLoginInfo = loginInfo;
signInLink.setText(TXT_LOGOUT);
signInLink.setHref(loginInfo.getLogoutUrl());
loggedInAs.setText(TXT_LOGGED_IN_AS + loginInfo.getEmail() + ")");
operationNewModDel.setVisible(true);
if (loginInfo.isAdmin()) {
if (adminGUI == null) {
adminGUI = new AdminGUI(this);
RootPanel.get().add(adminGUI);
}
stackPanel.add(adminGUI, TXT_ADMIN, false);
}
} else {
currentLoginInfo = null;
signInLink.setText(TXT_LOGIN);
signInLink.setHref(loginInfo.getLoginUrl());
loggedInAs.setText("");
operationNewModDel.setVisible(false);
if (adminGUI != null) {
adminGUI.removeFromParent();
}
}
}
public void service_eventLoginFailed(Throwable caught) {
status.setText(TXT_ERROR_LOGIN + caught.getMessage());
}
public ListBox getYearListBox() {
return yearListBox;
}
public Set<Airfield> getAllAirfields() {
return allAirfields;
}
}
| true | true | private void placeWidgets() {
// Login panel
HorizontalPanel loginPanel = new HorizontalPanel();
RootPanel.get(LOGIN_ROOT_PANEL).add(loginPanel, 10, 60);
signInLink = new Anchor();
loginPanel.add(signInLink);
loggedInAs = new Label();
loginPanel.add(loggedInAs);
HorizontalPanel statusPanel = new HorizontalPanel();
RootPanel.get(STATUS_ROOT_PANEL).add(statusPanel, 10, 100);
status = new Label();
statusPanel.add(status);
//statusPanel.add(new Label(version)); // TODO -- ???
stackPanel = new StackPanel();
RootPanel.get(STACK_ROOT_PANEL).add(stackPanel, 10, 130);
// main panel
mainPanel = new VerticalPanel();
stackPanel.add(mainPanel, TXT_STARTLIST, false);
HorizontalPanel selectionPanel = new HorizontalPanel();
selectionPanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
selectionPanel.addStyleName("selectionPanel");
mainPanel.add(selectionPanel);
Label yearLabel = new Label(TXT_YEAR);
selectionPanel.add(yearLabel);
yearListBox = new ListBox();
selectionPanel.add(yearListBox);
yearListBox.setVisibleItemCount(1);
Label ortLabel = new Label(TXT_START_PLACE);
selectionPanel.add(ortLabel);
placeListBox = new ListBox();
selectionPanel.add(placeListBox);
placeListBox.setVisibleItemCount(1);
HorizontalPanel datePanel = new HorizontalPanel();
datePanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
datePanel.addStyleName("datePanel");
selectionPanel.add(datePanel);
Label lblDatum = new Label(TXT_FLIGHT_DATUM);
datePanel.add(lblDatum);
prevDayPushButton = new Button(TXT_PREV);
datePanel.add(prevDayPushButton);
dateListBox = new ListBox();
datePanel.add(dateListBox);
dateListBox.setVisibleItemCount(1);
nextDayPushButton = new Button(TXT_NEXT);
datePanel.add(nextDayPushButton);
Label dummyLabel = new Label();
dummyLabel.setWidth("20px");
selectionPanel.add(dummyLabel);
excelLinkHTML = new HTML();
selectionPanel.add(excelLinkHTML);
// flight entry table starts here
String[] columns = new String[] { TXT_START_TIME, TXT_LANDING_TIME_TOWPLANE, TXT_DURATION_TOWPLANE, TXT_SHORT_REGISTRATION_TOWPLANE,
TXT_LANDING_TIME_GLIDER, TXT_DURATION_GLIDER, TXT_SHORT_REGISTRATION_GLIDER, TXT_PILOT, TXT_PASSENGER_OR_INSTRUCTOR, TXT_TRAINING, TXT_REMARKS };
String[] styles = new String[] { "starttime", "endtimetowplane", "dauertowplane", "registrationtowplane", "endtimeglider", "dauerglider",
"registrationglider", "pilot", "passengerorinstructor", "schulung", "bemerkungen" };
verticaPanel_2 = new VerticalPanel();
mainPanel.add(verticaPanel_2);
dynaTableWidget = new DynaTableWidget(provider, columns, styles, 20);
dynaTableWidget.setWidth("1200px");
verticaPanel_2.add(dynaTableWidget);
dynaTableWidget.setStatusText("");
operationNewModDel = new HorizontalPanel();
operationNewModDel.setVisible(false);
verticaPanel_2.add(operationNewModDel);
newButton = new Button(TXT_NEW);
newButton.setEnabled(true);
operationNewModDel.add(newButton);
modifyButton = new Button(TXT_MODIFY);
modifyButton.setEnabled(false);
operationNewModDel.add(modifyButton);
deleteButton = new Button(TXT_DELETE);
deleteButton.setEnabled(false);
operationNewModDel.add(deleteButton);
// dialog for adding or modifying flight entrys
flightEntryDialogBox = new DialogBox();
VerticalPanel flightEntryVerticaPanel = new VerticalPanel();
flightEntryDialogBox.add(flightEntryVerticaPanel);
flightEntryDialogBox.hide();
flightEntryDialogBox.setModal(true);
flightEntryFlexTable = new FlexTable();
flightEntryVerticaPanel.add(flightEntryFlexTable);
// row 0: basic information, date and place
Label lblDatum2 = new Label(TXT_FLIGHT_DATUM);
flightEntryFlexTable.setWidget(0, 0, lblDatum2);
dateBox = new DateBox2();
dateBox.setFormat(DD_MMM_YYYY_FORMAT);
flightEntryFlexTable.setWidget(0, 1, dateBox);
Label lblAllPlaces = new Label(TXT_START_PLACE);
flightEntryFlexTable.setWidget(0, 2, lblAllPlaces);
allPlacesListBox = new ListBox();
flightEntryFlexTable.setWidget(0, 3, allPlacesListBox);
Label lblAllSuggestPlaces = new Label(TXT_LANDING_PLACE);
flightEntryFlexTable.setWidget(0, 4, lblAllSuggestPlaces);
landingPlacesSuggestBox = new SuggestBox2(landingPlacesSuggest);
flightEntryFlexTable.setWidget(0, 5, landingPlacesSuggestBox);
// row 1: time information
Label lblStart = new Label(TXT_START_TIME);
flightEntryFlexTable.setWidget(1, 0, lblStart);
startDateBox = new DateBox2();
startDateBox.setFormat(MM_HH_FORMAT);
startDateBox.getDatePicker().setVisible(false);
flightEntryFlexTable.setWidget(1, 1, startDateBox);
Label lblEndeTowplane = new Label(TXT_LANDING_TIME_TOWPLANE);
flightEntryFlexTable.setWidget(1, 2, lblEndeTowplane);
endTowplaneDateBox = new DateBox2();
endTowplaneDateBox.setFormat(MM_HH_FORMAT);
endTowplaneDateBox.getDatePicker().setVisible(false);
flightEntryFlexTable.setWidget(1, 3, endTowplaneDateBox);
Label lblEndeGlider = new Label(TXT_LANDING_TIME_GLIDER);
flightEntryFlexTable.setWidget(1, 4, lblEndeGlider);
endGliderDateBox = new DateBox2();
endGliderDateBox.setFormat(MM_HH_FORMAT);
endGliderDateBox.getDatePicker().setVisible(false);
flightEntryFlexTable.setWidget(1, 5, endGliderDateBox);
// row 2: registration of involved planes and towplane pilot
Label lblTowplane = new Label(TXT_REGISTRATION_TOWPLANE);
flightEntryFlexTable.setWidget(2, 0, lblTowplane);
registrationTowplaneBox = new TextBox();
flightEntryFlexTable.setWidget(2, 1, registrationTowplaneBox);
Label lblGlider = new Label(TXT_REGISTRATION_GLIDER);
flightEntryFlexTable.setWidget(2, 2, lblGlider);
registrationGliderBox = new TextBox();
flightEntryFlexTable.setWidget(2, 3, registrationGliderBox);
Label lblTowplanePilot = new Label(TXT_TOWPLANE_PILOT);
flightEntryFlexTable.setWidget(2, 4, lblTowplanePilot);
towplanePilotNameBox = new SuggestBox2(pilotNamesSuggest);
flightEntryFlexTable.setWidget(2, 5, towplanePilotNameBox);
// row 3: pilot information
Label lblPilot = new Label(TXT_PILOT);
flightEntryFlexTable.setWidget(3, 0, lblPilot);
pilotNameBox = new SuggestBox2(pilotNamesSuggest);
flightEntryFlexTable.setWidget(3, 1, pilotNameBox);
Label lblPassengerOrInstructor = new Label(TXT_PASSENGER_OR_INSTRUCTOR);
flightEntryFlexTable.setWidget(3, 2, lblPassengerOrInstructor);
passengerOrInstructorNameBox = new SuggestBox2(pilotNamesSuggest);
flightEntryFlexTable.setWidget(3, 3, passengerOrInstructorNameBox);
Label lblTraining = new Label(TXT_TRAINING);
flightEntryFlexTable.setWidget(3, 4, lblTraining);
trainingCheckBox = new CheckBox();
flightEntryFlexTable.setWidget(3, 5, trainingCheckBox);
// row 4: remarks
Label lblBemerkungen = new Label(TXT_REMARKS);
flightEntryFlexTable.setWidget(4, 0, lblBemerkungen);
remarksTextBox = new TextBox();
remarksTextBox.setVisibleLength(80);
flightEntryFlexTable.setWidget(4, 1, remarksTextBox);
flightEntryFlexTable.getFlexCellFormatter().setColSpan(4, 1, 5);// TODO - does not work?
HorizontalPanel operationsPanel;
operationsPanel = new HorizontalPanel();
operationsPanel.setSpacing(5);
flightEntryVerticaPanel.add(operationsPanel);
saveButton = new Button(TXT_SAVE);
saveButton.setEnabled(false);
operationsPanel.add(saveButton);
discardButton = new Button(TXT_DISCARD);
discardButton.setEnabled(false);
operationsPanel.add(discardButton);
btnClose = new Button(TXT_CLOSE);
btnClose.setEnabled(true);
operationsPanel.add(btnClose);
// Set tab order
setTabOrder(dateBox, allPlacesListBox, landingPlacesSuggestBox, startDateBox, endTowplaneDateBox, endGliderDateBox, registrationTowplaneBox,
registrationGliderBox, towplanePilotNameBox, pilotNameBox, passengerOrInstructorNameBox, trainingCheckBox, remarksTextBox,
saveButton, discardButton, btnClose);
loadYears();
loadAllPlaces();
loadAllPilots();
enablePilotFields(false);
initLogin();
}
| private void placeWidgets() {
// Login panel
HorizontalPanel loginPanel = new HorizontalPanel();
RootPanel.get(LOGIN_ROOT_PANEL).add(loginPanel, 10, 60);
signInLink = new Anchor();
loginPanel.add(signInLink);
loggedInAs = new Label();
loginPanel.add(loggedInAs);
HorizontalPanel statusPanel = new HorizontalPanel();
RootPanel.get(STATUS_ROOT_PANEL).add(statusPanel, 10, 100);
status = new Label();
statusPanel.add(status);
//statusPanel.add(new Label(version)); // TODO -- ???
stackPanel = new StackPanel();
RootPanel.get(STACK_ROOT_PANEL).add(stackPanel, 10, 130);
// main panel
mainPanel = new VerticalPanel();
stackPanel.add(mainPanel, TXT_STARTLIST, false);
HorizontalPanel selectionPanel = new HorizontalPanel();
selectionPanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
selectionPanel.addStyleName("selectionPanel");
mainPanel.add(selectionPanel);
Label yearLabel = new Label(TXT_YEAR);
selectionPanel.add(yearLabel);
yearListBox = new ListBox();
selectionPanel.add(yearListBox);
yearListBox.setVisibleItemCount(1);
Label ortLabel = new Label(TXT_START_PLACE);
selectionPanel.add(ortLabel);
placeListBox = new ListBox();
selectionPanel.add(placeListBox);
placeListBox.setVisibleItemCount(1);
HorizontalPanel datePanel = new HorizontalPanel();
datePanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
datePanel.addStyleName("datePanel");
selectionPanel.add(datePanel);
Label lblDatum = new Label(TXT_FLIGHT_DATUM);
datePanel.add(lblDatum);
prevDayPushButton = new Button(TXT_PREV);
prevDayPushButton.setText("<");
datePanel.add(prevDayPushButton);
dateListBox = new ListBox();
datePanel.add(dateListBox);
dateListBox.setVisibleItemCount(1);
nextDayPushButton = new Button(TXT_NEXT);
datePanel.add(nextDayPushButton);
Label dummyLabel = new Label();
dummyLabel.setWidth("20px");
selectionPanel.add(dummyLabel);
excelLinkHTML = new HTML();
selectionPanel.add(excelLinkHTML);
// flight entry table starts here
String[] columns = new String[] { TXT_START_TIME, TXT_LANDING_TIME_TOWPLANE, TXT_DURATION_TOWPLANE, TXT_SHORT_REGISTRATION_TOWPLANE,
TXT_LANDING_TIME_GLIDER, TXT_DURATION_GLIDER, TXT_SHORT_REGISTRATION_GLIDER, TXT_PILOT, TXT_PASSENGER_OR_INSTRUCTOR, TXT_TRAINING, TXT_REMARKS };
String[] styles = new String[] { "starttime", "endtimetowplane", "dauertowplane", "registrationtowplane", "endtimeglider", "dauerglider",
"registrationglider", "pilot", "passengerorinstructor", "schulung", "bemerkungen" };
verticaPanel_2 = new VerticalPanel();
mainPanel.add(verticaPanel_2);
dynaTableWidget = new DynaTableWidget(provider, columns, styles, 20);
dynaTableWidget.setWidth("1200px");
verticaPanel_2.add(dynaTableWidget);
dynaTableWidget.setStatusText("");
operationNewModDel = new HorizontalPanel();
operationNewModDel.setVisible(false);
verticaPanel_2.add(operationNewModDel);
newButton = new Button(TXT_NEW);
newButton.setEnabled(true);
operationNewModDel.add(newButton);
modifyButton = new Button(TXT_MODIFY);
modifyButton.setEnabled(false);
operationNewModDel.add(modifyButton);
deleteButton = new Button(TXT_DELETE);
deleteButton.setEnabled(false);
operationNewModDel.add(deleteButton);
// dialog for adding or modifying flight entrys
flightEntryDialogBox = new DialogBox();
VerticalPanel flightEntryVerticaPanel = new VerticalPanel();
flightEntryDialogBox.add(flightEntryVerticaPanel);
flightEntryDialogBox.hide();
flightEntryDialogBox.setModal(true);
flightEntryFlexTable = new FlexTable();
flightEntryVerticaPanel.add(flightEntryFlexTable);
// row 0: basic information, date and place
Label lblDatum2 = new Label(TXT_FLIGHT_DATUM);
flightEntryFlexTable.setWidget(0, 0, lblDatum2);
dateBox = new DateBox2();
dateBox.setFormat(DD_MMM_YYYY_FORMAT);
flightEntryFlexTable.setWidget(0, 1, dateBox);
Label lblAllPlaces = new Label(TXT_START_PLACE);
flightEntryFlexTable.setWidget(0, 2, lblAllPlaces);
allPlacesListBox = new ListBox();
flightEntryFlexTable.setWidget(0, 3, allPlacesListBox);
Label lblAllSuggestPlaces = new Label(TXT_LANDING_PLACE);
flightEntryFlexTable.setWidget(0, 4, lblAllSuggestPlaces);
landingPlacesSuggestBox = new SuggestBox2(landingPlacesSuggest);
flightEntryFlexTable.setWidget(0, 5, landingPlacesSuggestBox);
// row 1: time information
Label lblStart = new Label(TXT_START_TIME);
flightEntryFlexTable.setWidget(1, 0, lblStart);
startDateBox = new DateBox2();
startDateBox.setFormat(MM_HH_FORMAT);
startDateBox.getDatePicker().setVisible(false);
flightEntryFlexTable.setWidget(1, 1, startDateBox);
Label lblEndeTowplane = new Label(TXT_LANDING_TIME_TOWPLANE);
flightEntryFlexTable.setWidget(1, 2, lblEndeTowplane);
endTowplaneDateBox = new DateBox2();
endTowplaneDateBox.setFormat(MM_HH_FORMAT);
endTowplaneDateBox.getDatePicker().setVisible(false);
flightEntryFlexTable.setWidget(1, 3, endTowplaneDateBox);
Label lblEndeGlider = new Label(TXT_LANDING_TIME_GLIDER);
flightEntryFlexTable.setWidget(1, 4, lblEndeGlider);
endGliderDateBox = new DateBox2();
endGliderDateBox.setFormat(MM_HH_FORMAT);
endGliderDateBox.getDatePicker().setVisible(false);
flightEntryFlexTable.setWidget(1, 5, endGliderDateBox);
// row 2: registration of involved planes and towplane pilot
Label lblTowplane = new Label(TXT_REGISTRATION_TOWPLANE);
flightEntryFlexTable.setWidget(2, 0, lblTowplane);
registrationTowplaneBox = new TextBox();
flightEntryFlexTable.setWidget(2, 1, registrationTowplaneBox);
Label lblGlider = new Label(TXT_REGISTRATION_GLIDER);
flightEntryFlexTable.setWidget(2, 2, lblGlider);
registrationGliderBox = new TextBox();
flightEntryFlexTable.setWidget(2, 3, registrationGliderBox);
Label lblTowplanePilot = new Label(TXT_TOWPLANE_PILOT);
flightEntryFlexTable.setWidget(2, 4, lblTowplanePilot);
towplanePilotNameBox = new SuggestBox2(pilotNamesSuggest);
flightEntryFlexTable.setWidget(2, 5, towplanePilotNameBox);
// row 3: pilot information
Label lblPilot = new Label(TXT_PILOT);
flightEntryFlexTable.setWidget(3, 0, lblPilot);
pilotNameBox = new SuggestBox2(pilotNamesSuggest);
flightEntryFlexTable.setWidget(3, 1, pilotNameBox);
Label lblPassengerOrInstructor = new Label(TXT_PASSENGER_OR_INSTRUCTOR);
flightEntryFlexTable.setWidget(3, 2, lblPassengerOrInstructor);
passengerOrInstructorNameBox = new SuggestBox2(pilotNamesSuggest);
flightEntryFlexTable.setWidget(3, 3, passengerOrInstructorNameBox);
Label lblTraining = new Label(TXT_TRAINING);
flightEntryFlexTable.setWidget(3, 4, lblTraining);
trainingCheckBox = new CheckBox();
flightEntryFlexTable.setWidget(3, 5, trainingCheckBox);
// row 4: remarks
Label lblBemerkungen = new Label(TXT_REMARKS);
flightEntryFlexTable.setWidget(4, 0, lblBemerkungen);
remarksTextBox = new TextBox();
remarksTextBox.setVisibleLength(80);
flightEntryFlexTable.setWidget(4, 1, remarksTextBox);
flightEntryFlexTable.getFlexCellFormatter().setColSpan(4, 1, 5);// TODO - does not work?
HorizontalPanel operationsPanel;
operationsPanel = new HorizontalPanel();
operationsPanel.setSpacing(5);
flightEntryVerticaPanel.add(operationsPanel);
saveButton = new Button(TXT_SAVE);
saveButton.setEnabled(false);
operationsPanel.add(saveButton);
discardButton = new Button(TXT_DISCARD);
discardButton.setEnabled(false);
operationsPanel.add(discardButton);
btnClose = new Button(TXT_CLOSE);
btnClose.setEnabled(true);
operationsPanel.add(btnClose);
// Set tab order
setTabOrder(dateBox, allPlacesListBox, landingPlacesSuggestBox, startDateBox, endTowplaneDateBox, endGliderDateBox, registrationTowplaneBox,
registrationGliderBox, towplanePilotNameBox, pilotNameBox, passengerOrInstructorNameBox, trainingCheckBox, remarksTextBox,
saveButton, discardButton, btnClose);
loadYears();
loadAllPlaces();
loadAllPilots();
enablePilotFields(false);
initLogin();
}
|
diff --git a/tests/org.eclipse.gmf.tests/src/org/eclipse/gmf/tests/gen/CompilationTest.java b/tests/org.eclipse.gmf.tests/src/org/eclipse/gmf/tests/gen/CompilationTest.java
index 92f9d91b3..4f8dabbd9 100644
--- a/tests/org.eclipse.gmf.tests/src/org/eclipse/gmf/tests/gen/CompilationTest.java
+++ b/tests/org.eclipse.gmf.tests/src/org/eclipse/gmf/tests/gen/CompilationTest.java
@@ -1,84 +1,87 @@
/*
* Copyright (c) 2005 Borland Software Corporation
*
* 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:
* Artem Tikhomirov (Borland) - initial API and implementation
*/
package org.eclipse.gmf.tests.gen;
import java.io.IOException;
import java.net.URL;
import junit.framework.TestCase;
import org.eclipse.core.runtime.Platform;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.gmf.codegen.gmfgen.GenDiagram;
import org.eclipse.gmf.codegen.gmfgen.GenLink;
import org.eclipse.gmf.codegen.gmfgen.GenNode;
import org.eclipse.gmf.tests.Plugin;
import org.eclipse.gmf.tests.SessionSetup;
import org.eclipse.gmf.tests.setup.DiaGenSource;
import org.eclipse.gmf.tests.setup.GenProjectBaseSetup;
public class CompilationTest extends TestCase {
public CompilationTest(String name) {
super(name);
}
// TODO EditPartViewer[Source|Setup]
protected void setUp() throws Exception {
super.setUp();
SessionSetup.getRuntimeWorkspaceSetup();
}
public void testCodeCompilation() {
try {
URL gmfgenURL = Plugin.getInstance().getBundle().getEntry("/models/library/library.gmfgen");
String filePath = Platform.asLocalURL(gmfgenURL).toExternalForm();
URI selected = URI.createURI(filePath);
ResourceSet srcResSet = new ResourceSetImpl();
Resource srcRes = srcResSet.getResource(selected, true);
GenDiagram gd = (GenDiagram) srcRes.getContents().get(0);
new GenProjectBaseSetup().generateAndCompile(SessionSetup.getRuntimeWorkspaceSetup(), new FakeDiaGenSource(gd, null, null));
} catch (IOException ex) {
fail(ex.getMessage());
+ } catch (RuntimeException ex) {
+ throw ex;
} catch (Exception ex) {
+ Plugin.logError("Unexpected exception:", ex);
fail("Hm, looks like unexpected..." + ex.getMessage());
}
}
protected void tearDown() throws Exception {
super.tearDown();
}
private static class FakeDiaGenSource implements DiaGenSource {
private final GenDiagram genDiagram;
private final GenNode genNode;
private final GenLink genLink;
FakeDiaGenSource(GenDiagram gd, GenNode gn, GenLink gl) {
genDiagram = gd;
genNode = gn;
genLink = gl;
}
public GenDiagram getGenDiagram() {
return genDiagram;
}
public GenLink getGenLink() {
return genLink;
}
public GenNode getGenNode() {
return genNode;
}
}
}
| false | true | public void testCodeCompilation() {
try {
URL gmfgenURL = Plugin.getInstance().getBundle().getEntry("/models/library/library.gmfgen");
String filePath = Platform.asLocalURL(gmfgenURL).toExternalForm();
URI selected = URI.createURI(filePath);
ResourceSet srcResSet = new ResourceSetImpl();
Resource srcRes = srcResSet.getResource(selected, true);
GenDiagram gd = (GenDiagram) srcRes.getContents().get(0);
new GenProjectBaseSetup().generateAndCompile(SessionSetup.getRuntimeWorkspaceSetup(), new FakeDiaGenSource(gd, null, null));
} catch (IOException ex) {
fail(ex.getMessage());
} catch (Exception ex) {
fail("Hm, looks like unexpected..." + ex.getMessage());
}
}
| public void testCodeCompilation() {
try {
URL gmfgenURL = Plugin.getInstance().getBundle().getEntry("/models/library/library.gmfgen");
String filePath = Platform.asLocalURL(gmfgenURL).toExternalForm();
URI selected = URI.createURI(filePath);
ResourceSet srcResSet = new ResourceSetImpl();
Resource srcRes = srcResSet.getResource(selected, true);
GenDiagram gd = (GenDiagram) srcRes.getContents().get(0);
new GenProjectBaseSetup().generateAndCompile(SessionSetup.getRuntimeWorkspaceSetup(), new FakeDiaGenSource(gd, null, null));
} catch (IOException ex) {
fail(ex.getMessage());
} catch (RuntimeException ex) {
throw ex;
} catch (Exception ex) {
Plugin.logError("Unexpected exception:", ex);
fail("Hm, looks like unexpected..." + ex.getMessage());
}
}
|
diff --git a/modules/weblounge-contentrepository/src/main/java/ch/entwine/weblounge/contentrepository/impl/ImageResourceSerializer.java b/modules/weblounge-contentrepository/src/main/java/ch/entwine/weblounge/contentrepository/impl/ImageResourceSerializer.java
index dadd625c2..44dd9d894 100644
--- a/modules/weblounge-contentrepository/src/main/java/ch/entwine/weblounge/contentrepository/impl/ImageResourceSerializer.java
+++ b/modules/weblounge-contentrepository/src/main/java/ch/entwine/weblounge/contentrepository/impl/ImageResourceSerializer.java
@@ -1,344 +1,344 @@
/*
* Weblounge: Web Content Management System
* Copyright (c) 2003 - 2011 The Weblounge Team
* http://entwinemedia.com/weblounge
*
* 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
* 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser 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 ch.entwine.weblounge.contentrepository.impl;
import static ch.entwine.weblounge.contentrepository.impl.index.IndexSchema.HEADER_XML;
import static ch.entwine.weblounge.contentrepository.impl.index.IndexSchema.PATH;
import static ch.entwine.weblounge.contentrepository.impl.index.IndexSchema.RESOURCE_ID;
import static ch.entwine.weblounge.contentrepository.impl.index.IndexSchema.VERSION;
import static ch.entwine.weblounge.contentrepository.impl.index.IndexSchema.XML;
import ch.entwine.weblounge.common.content.PreviewGenerator;
import ch.entwine.weblounge.common.content.Resource;
import ch.entwine.weblounge.common.content.ResourceContentReader;
import ch.entwine.weblounge.common.content.ResourceMetadata;
import ch.entwine.weblounge.common.content.ResourceReader;
import ch.entwine.weblounge.common.content.ResourceURI;
import ch.entwine.weblounge.common.content.SearchResultItem;
import ch.entwine.weblounge.common.content.image.ImageContent;
import ch.entwine.weblounge.common.content.image.ImagePreviewGenerator;
import ch.entwine.weblounge.common.content.image.ImageResource;
import ch.entwine.weblounge.common.impl.content.image.ImageContentReader;
import ch.entwine.weblounge.common.impl.content.image.ImageMetadata;
import ch.entwine.weblounge.common.impl.content.image.ImageMetadataUtils;
import ch.entwine.weblounge.common.impl.content.image.ImageResourceImpl;
import ch.entwine.weblounge.common.impl.content.image.ImageResourceReader;
import ch.entwine.weblounge.common.impl.content.image.ImageResourceSearchResultItemImpl;
import ch.entwine.weblounge.common.impl.content.image.ImageResourceURIImpl;
import ch.entwine.weblounge.common.impl.url.WebUrlImpl;
import ch.entwine.weblounge.common.language.Language;
import ch.entwine.weblounge.common.security.User;
import ch.entwine.weblounge.common.site.Site;
import ch.entwine.weblounge.common.url.WebUrl;
import ch.entwine.weblounge.contentrepository.impl.index.ImageInputDocument;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.SAXException;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.ParserConfigurationException;
/**
* Implementation of a serializer for image resources.
*/
public class ImageResourceSerializer extends AbstractResourceSerializer<ImageContent, ImageResource> {
/** The logging facility */
private static final Logger logger = LoggerFactory.getLogger(ImageResourceSerializer.class);
/** Alternate uri prefix */
protected static final String URI_PREFIX = "/weblounge-images/";
/** The preview generators */
protected List<ImagePreviewGenerator> previewGenerators = new ArrayList<ImagePreviewGenerator>();
/**
* this gets rid of exception for not using native acceleration
*/
static {
System.setProperty("com.sun.media.jai.disableMediaLib", "true");
}
/**
* Creates a new image resource serializer.
*/
public ImageResourceSerializer() {
super(ImageResource.TYPE);
}
/**
* {@inheritDoc}
*
* @see ch.entwine.weblounge.common.repository.ResourceSerializer#getMimeType(ch.entwine.weblounge.common.content.ResourceContent)
*/
public String getMimeType(ImageContent resourceContent) {
return resourceContent.getMimetype();
}
/**
* {@inheritDoc}
*
* @see ch.entwine.weblounge.common.repository.ResourceSerializer#supports(java.lang.String)
*/
public boolean supports(String mimeType) {
return mimeType != null && mimeType.toLowerCase().startsWith("image/");
}
/**
* {@inheritDoc}
*
* @see ch.entwine.weblounge.common.repository.ResourceSerializer#newResource(ch.entwine.weblounge.common.site.Site)
*/
public Resource<ImageContent> newResource(Site site) {
return new ImageResourceImpl(new ImageResourceURIImpl(site));
}
/**
* {@inheritDoc}
*
* @see ch.entwine.weblounge.common.repository.ResourceSerializer#newResource(ch.entwine.weblounge.common.site.Site,
* java.io.InputStream, ch.entwine.weblounge.common.security.User,
* ch.entwine.weblounge.common.language.Language)
*/
public Resource<ImageContent> newResource(Site site, InputStream is,
User user, Language language) {
ImageMetadata imageMetadata = ImageMetadataUtils.extractMetadata(new BufferedInputStream(is));
ImageResource imageResource = new ImageResourceImpl(new ImageResourceURIImpl(site));
imageResource.setCreated(user, new Date());
if (imageMetadata == null)
return imageResource;
if (!StringUtils.isBlank(imageMetadata.getCaption())) {
imageResource.setTitle(imageMetadata.getCaption(), language);
}
if (!StringUtils.isBlank(imageMetadata.getLegend())) {
imageResource.setDescription(imageMetadata.getLegend(), language);
}
for (String keyword : imageMetadata.getKeywords()) {
imageResource.addSubject(keyword);
}
if (!StringUtils.isBlank(imageMetadata.getCopyright())) {
imageResource.setRights(imageMetadata.getCopyright(), language);
}
return imageResource;
}
/**
* {@inheritDoc}
*
* @see ch.entwine.weblounge.contentrepository.impl.AbstractResourceSerializer#createNewReader()
*/
@Override
protected ImageResourceReader createNewReader()
throws ParserConfigurationException, SAXException {
return new ImageResourceReader();
}
/**
* {@inheritDoc}
*
* @see ch.entwine.weblounge.common.repository.ResourceSerializer#toMetadata(ch.entwine.weblounge.common.content.Resource)
*/
public List<ResourceMetadata<?>> toMetadata(Resource<?> resource) {
if (resource != null) {
return new ImageInputDocument((ImageResource) resource).getMetadata();
}
return null;
}
/**
* {@inheritDoc}
*
* @see ch.entwine.weblounge.common.repository.ResourceSerializer#toResource(ch.entwine.weblounge.common.site.Site,
* java.util.List)
*/
public Resource<?> toResource(Site site, List<ResourceMetadata<?>> metadata) {
for (ResourceMetadata<?> metadataItem : metadata) {
if (XML.equals(metadataItem.getName())) {
String resourceXml = (String) metadataItem.getValues().get(0);
try {
ResourceReader<ImageContent, ImageResource> reader = getReader();
ImageResource image = reader.read(IOUtils.toInputStream(resourceXml, "UTF-8"), site);
return image;
} catch (SAXException e) {
logger.warn("Error parsing image resource from metadata", e);
return null;
} catch (IOException e) {
logger.warn("Error parsing image resource from metadata", e);
return null;
} catch (ParserConfigurationException e) {
logger.warn("Error parsing image resource from metadata", e);
return null;
}
}
}
return null;
}
/**
* {@inheritDoc}
*
* @see ch.entwine.weblounge.common.repository.ResourceSerializer#toSearchResultItem(ch.entwine.weblounge.common.site.Site,
* double, List)
*/
public SearchResultItem toSearchResultItem(Site site, double relevance,
List<ResourceMetadata<?>> metadata) {
Map<String, ResourceMetadata<?>> metadataMap = new HashMap<String, ResourceMetadata<?>>();
for (ResourceMetadata<?> metadataItem : metadata) {
metadataMap.put(metadataItem.getName(), metadataItem);
}
// resource id
String id = (String) metadataMap.get(RESOURCE_ID).getValues().get(0);
// resource version
long version = (Long) metadataMap.get(VERSION).getValues().get(0);
// path
String path = null;
WebUrl url = null;
if (metadataMap.get(PATH) != null) {
try {
path = (String) metadataMap.get(PATH).getValues().get(0);
url = new WebUrlImpl(site, path);
} catch (IllegalArgumentException e) {
- logger.warn("Path {}:/{} for image {} is invalid", new Object[] {
+ logger.warn("Path {}:{} for image {} is invalid", new Object[] {
site.getIdentifier(),
path,
id });
path = URI_PREFIX + "/" + id;
url = new WebUrlImpl(site, path);
}
} else {
path = URI_PREFIX + "/" + id;
url = new WebUrlImpl(site, path);
}
ResourceURI uri = new ImageResourceURIImpl(site, path, id, version);
ImageResourceSearchResultItemImpl result = new ImageResourceSearchResultItemImpl(uri, url, relevance, site, metadata);
if (metadataMap.get(XML) != null)
result.setResourceXml((String) metadataMap.get(XML).getValues().get(0));
if (metadataMap.get(HEADER_XML) != null)
result.setImageHeaderXml((String) metadataMap.get(HEADER_XML).getValues().get(0));
// TODO: Add remaining metadata
return result;
}
/**
* {@inheritDoc}
*
* @see ch.entwine.weblounge.common.repository.ResourceSerializer#getContentReader()
*/
public ResourceContentReader<ImageContent> getContentReader()
throws ParserConfigurationException, SAXException {
return new ImageContentReader();
}
/**
* {@inheritDoc}
*
* @see ch.entwine.weblounge.common.repository.ResourceSerializer#getPreviewGenerator(Resource)
*/
public PreviewGenerator getPreviewGenerator(Resource<?> resource) {
for (ImagePreviewGenerator generator : previewGenerators) {
if (generator.supports(resource)) {
logger.trace("Image preview generator {} agrees to handle {}", generator, resource);
return generator;
}
}
logger.trace("No image preview generator found to handle {}", resource);
return null;
}
/**
* Returns the highest ranked image preview generator that supports the given
* format or <code>null</code> if no preview generator is available.
*
* @param format
* the format
* @return the preview generator
*/
public PreviewGenerator getPreviewGenerator(String format) {
for (ImagePreviewGenerator generator : previewGenerators) {
if (generator.supports(format)) {
logger.trace("Image preview generator {} agrees to handle format '{}'", generator, format);
return generator;
}
}
logger.trace("No image preview generator found to handle format '{}'", format);
return null;
}
/**
* Adds the preview generator to the list of registered preview generators.
*
* @param generator
* the generator
*/
void addPreviewGenerator(ImagePreviewGenerator generator) {
previewGenerators.add(generator);
Collections.sort(previewGenerators, new Comparator<PreviewGenerator>() {
public int compare(PreviewGenerator a, PreviewGenerator b) {
return Integer.valueOf(b.getPriority()).compareTo(a.getPriority());
}
});
}
/**
* Removes the preview generator from the list of registered preview
* generators.
*
* @param generator
* the generator
*/
void removePreviewGenerator(ImagePreviewGenerator generator) {
previewGenerators.remove(generator);
}
/**
* {@inheritDoc}
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Image serializer";
}
}
| true | true | public SearchResultItem toSearchResultItem(Site site, double relevance,
List<ResourceMetadata<?>> metadata) {
Map<String, ResourceMetadata<?>> metadataMap = new HashMap<String, ResourceMetadata<?>>();
for (ResourceMetadata<?> metadataItem : metadata) {
metadataMap.put(metadataItem.getName(), metadataItem);
}
// resource id
String id = (String) metadataMap.get(RESOURCE_ID).getValues().get(0);
// resource version
long version = (Long) metadataMap.get(VERSION).getValues().get(0);
// path
String path = null;
WebUrl url = null;
if (metadataMap.get(PATH) != null) {
try {
path = (String) metadataMap.get(PATH).getValues().get(0);
url = new WebUrlImpl(site, path);
} catch (IllegalArgumentException e) {
logger.warn("Path {}:/{} for image {} is invalid", new Object[] {
site.getIdentifier(),
path,
id });
path = URI_PREFIX + "/" + id;
url = new WebUrlImpl(site, path);
}
} else {
path = URI_PREFIX + "/" + id;
url = new WebUrlImpl(site, path);
}
ResourceURI uri = new ImageResourceURIImpl(site, path, id, version);
ImageResourceSearchResultItemImpl result = new ImageResourceSearchResultItemImpl(uri, url, relevance, site, metadata);
if (metadataMap.get(XML) != null)
result.setResourceXml((String) metadataMap.get(XML).getValues().get(0));
if (metadataMap.get(HEADER_XML) != null)
result.setImageHeaderXml((String) metadataMap.get(HEADER_XML).getValues().get(0));
// TODO: Add remaining metadata
return result;
}
| public SearchResultItem toSearchResultItem(Site site, double relevance,
List<ResourceMetadata<?>> metadata) {
Map<String, ResourceMetadata<?>> metadataMap = new HashMap<String, ResourceMetadata<?>>();
for (ResourceMetadata<?> metadataItem : metadata) {
metadataMap.put(metadataItem.getName(), metadataItem);
}
// resource id
String id = (String) metadataMap.get(RESOURCE_ID).getValues().get(0);
// resource version
long version = (Long) metadataMap.get(VERSION).getValues().get(0);
// path
String path = null;
WebUrl url = null;
if (metadataMap.get(PATH) != null) {
try {
path = (String) metadataMap.get(PATH).getValues().get(0);
url = new WebUrlImpl(site, path);
} catch (IllegalArgumentException e) {
logger.warn("Path {}:{} for image {} is invalid", new Object[] {
site.getIdentifier(),
path,
id });
path = URI_PREFIX + "/" + id;
url = new WebUrlImpl(site, path);
}
} else {
path = URI_PREFIX + "/" + id;
url = new WebUrlImpl(site, path);
}
ResourceURI uri = new ImageResourceURIImpl(site, path, id, version);
ImageResourceSearchResultItemImpl result = new ImageResourceSearchResultItemImpl(uri, url, relevance, site, metadata);
if (metadataMap.get(XML) != null)
result.setResourceXml((String) metadataMap.get(XML).getValues().get(0));
if (metadataMap.get(HEADER_XML) != null)
result.setImageHeaderXml((String) metadataMap.get(HEADER_XML).getValues().get(0));
// TODO: Add remaining metadata
return result;
}
|
diff --git a/plexus-archiver/src/main/java/org/codehaus/plexus/archiver/util/ArchiveEntryUtils.java b/plexus-archiver/src/main/java/org/codehaus/plexus/archiver/util/ArchiveEntryUtils.java
index d574a486..19e60c0e 100644
--- a/plexus-archiver/src/main/java/org/codehaus/plexus/archiver/util/ArchiveEntryUtils.java
+++ b/plexus-archiver/src/main/java/org/codehaus/plexus/archiver/util/ArchiveEntryUtils.java
@@ -1,74 +1,74 @@
package org.codehaus.plexus.archiver.util;
import org.codehaus.plexus.archiver.ArchiverException;
import org.codehaus.plexus.logging.Logger;
import org.codehaus.plexus.util.Os;
import org.codehaus.plexus.util.cli.CommandLineException;
import org.codehaus.plexus.util.cli.CommandLineUtils;
import org.codehaus.plexus.util.cli.Commandline;
import java.io.File;
public final class ArchiveEntryUtils
{
private ArchiveEntryUtils()
{
}
public static void chmod( File file, int mode, Logger logger )
throws ArchiverException
{
if ( !Os.isFamily( "unix" ) )
{
return;
}
String m = Integer.toOctalString( mode & 0xfff );
try
{
Commandline commandline = new Commandline();
commandline.setWorkingDirectory( file.getParentFile().getAbsolutePath() );
commandline.setExecutable( "chmod" );
commandline.createArgument().setValue( m );
String path = file.getAbsolutePath();
- commandline.createArgument().setValue( "\'" + path + "\'" );
+ commandline.createArgument().setValue( path );
// commenting this debug statement, since it can produce VERY verbose output...
// this method is called often during archive creation.
// logger.debug( "Executing:\n\n" + commandline.toString() + "\n\n" );
CommandLineUtils.StringStreamConsumer stderr = new CommandLineUtils.StringStreamConsumer();
CommandLineUtils.StringStreamConsumer stdout = new CommandLineUtils.StringStreamConsumer();
int exitCode = CommandLineUtils.executeCommandLine( commandline, stderr, stdout );
if ( exitCode != 0 )
{
logger.warn( "-------------------------------" );
logger.warn( "Standard error:" );
logger.warn( "-------------------------------" );
logger.warn( stderr.getOutput() );
logger.warn( "-------------------------------" );
logger.warn( "Standard output:" );
logger.warn( "-------------------------------" );
logger.warn( stdout.getOutput() );
logger.warn( "-------------------------------" );
throw new ArchiverException( "chmod exit code was: " + exitCode );
}
}
catch ( CommandLineException e )
{
throw new ArchiverException( "Error while executing chmod.", e );
}
}
}
| true | true | public static void chmod( File file, int mode, Logger logger )
throws ArchiverException
{
if ( !Os.isFamily( "unix" ) )
{
return;
}
String m = Integer.toOctalString( mode & 0xfff );
try
{
Commandline commandline = new Commandline();
commandline.setWorkingDirectory( file.getParentFile().getAbsolutePath() );
commandline.setExecutable( "chmod" );
commandline.createArgument().setValue( m );
String path = file.getAbsolutePath();
commandline.createArgument().setValue( "\'" + path + "\'" );
// commenting this debug statement, since it can produce VERY verbose output...
// this method is called often during archive creation.
// logger.debug( "Executing:\n\n" + commandline.toString() + "\n\n" );
CommandLineUtils.StringStreamConsumer stderr = new CommandLineUtils.StringStreamConsumer();
CommandLineUtils.StringStreamConsumer stdout = new CommandLineUtils.StringStreamConsumer();
int exitCode = CommandLineUtils.executeCommandLine( commandline, stderr, stdout );
if ( exitCode != 0 )
{
logger.warn( "-------------------------------" );
logger.warn( "Standard error:" );
logger.warn( "-------------------------------" );
logger.warn( stderr.getOutput() );
logger.warn( "-------------------------------" );
logger.warn( "Standard output:" );
logger.warn( "-------------------------------" );
logger.warn( stdout.getOutput() );
logger.warn( "-------------------------------" );
throw new ArchiverException( "chmod exit code was: " + exitCode );
}
}
catch ( CommandLineException e )
{
throw new ArchiverException( "Error while executing chmod.", e );
}
}
| public static void chmod( File file, int mode, Logger logger )
throws ArchiverException
{
if ( !Os.isFamily( "unix" ) )
{
return;
}
String m = Integer.toOctalString( mode & 0xfff );
try
{
Commandline commandline = new Commandline();
commandline.setWorkingDirectory( file.getParentFile().getAbsolutePath() );
commandline.setExecutable( "chmod" );
commandline.createArgument().setValue( m );
String path = file.getAbsolutePath();
commandline.createArgument().setValue( path );
// commenting this debug statement, since it can produce VERY verbose output...
// this method is called often during archive creation.
// logger.debug( "Executing:\n\n" + commandline.toString() + "\n\n" );
CommandLineUtils.StringStreamConsumer stderr = new CommandLineUtils.StringStreamConsumer();
CommandLineUtils.StringStreamConsumer stdout = new CommandLineUtils.StringStreamConsumer();
int exitCode = CommandLineUtils.executeCommandLine( commandline, stderr, stdout );
if ( exitCode != 0 )
{
logger.warn( "-------------------------------" );
logger.warn( "Standard error:" );
logger.warn( "-------------------------------" );
logger.warn( stderr.getOutput() );
logger.warn( "-------------------------------" );
logger.warn( "Standard output:" );
logger.warn( "-------------------------------" );
logger.warn( stdout.getOutput() );
logger.warn( "-------------------------------" );
throw new ArchiverException( "chmod exit code was: " + exitCode );
}
}
catch ( CommandLineException e )
{
throw new ArchiverException( "Error while executing chmod.", e );
}
}
|
diff --git a/src/com/tactfactory/harmony/utils/PackageUtils.java b/src/com/tactfactory/harmony/utils/PackageUtils.java
index 4ba9994b..6ff55645 100644
--- a/src/com/tactfactory/harmony/utils/PackageUtils.java
+++ b/src/com/tactfactory/harmony/utils/PackageUtils.java
@@ -1,76 +1,76 @@
/**
* This file is part of the Harmony package.
*
* (c) Mickael Gaillard <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
package com.tactfactory.harmony.utils;
/**
* Utility class for Package manipulations.
*/
public abstract class PackageUtils {
/** Extract NameSpace of a class.
* @param mclass The class
* @return The NameSpace
*/
public static String extractNameSpace(final Class<?> mclass) {
final String mpackage = mclass.getPackage().getName();
return extractNameEntity(mpackage);
}
/** Extract NameSpace of a package.
* @param mpackage The package
* @return The NameSpace
*/
public static String extractNameSpace(final String mpackage) {
final int position = mpackage.lastIndexOf('.');
return mpackage.substring(0, position);
}
/** Extract Name of a class.
* @param mclass The class
* @return The Name
*/
public static String extractNameEntity(final Class<?> mclass) {
final String mname = mclass.getName().toString();
return extractNameEntity(mname);
}
/** Extract ClassName of a String.
* @param mname The String
* @return The Name
*/
public static String extractNameEntity(final String mname) {
final int position = mname.lastIndexOf('.');
return mname.substring(position + 1);
}
/** Converts package to a path.
* @param bundlePackage The package
* @return The path
*/
public static String extractPath(final String bundlePackage) {
return bundlePackage.replace('.', '/');
}
/** Extract a class name from an array.
* @param arrayName The array declaration
* @return The name of the class
*/
public static String extractClassNameFromArray(final String arrayName) {
String cName = arrayName;
- if (arrayName.startsWith("<")) {
+ if (arrayName.contains("<")) {
cName = arrayName.substring(
arrayName.indexOf('<') + 1,
arrayName.indexOf('>'));
} else if (arrayName.contains("[]")) {
cName = arrayName.substring(0, arrayName.indexOf('['));
}
return cName;
}
}
| true | true | public static String extractClassNameFromArray(final String arrayName) {
String cName = arrayName;
if (arrayName.startsWith("<")) {
cName = arrayName.substring(
arrayName.indexOf('<') + 1,
arrayName.indexOf('>'));
} else if (arrayName.contains("[]")) {
cName = arrayName.substring(0, arrayName.indexOf('['));
}
return cName;
}
| public static String extractClassNameFromArray(final String arrayName) {
String cName = arrayName;
if (arrayName.contains("<")) {
cName = arrayName.substring(
arrayName.indexOf('<') + 1,
arrayName.indexOf('>'));
} else if (arrayName.contains("[]")) {
cName = arrayName.substring(0, arrayName.indexOf('['));
}
return cName;
}
|
diff --git a/source/de/tuclausthal/submissioninterface/servlets/view/TaskManagerView.java b/source/de/tuclausthal/submissioninterface/servlets/view/TaskManagerView.java
index 3032d35..950c7b2 100644
--- a/source/de/tuclausthal/submissioninterface/servlets/view/TaskManagerView.java
+++ b/source/de/tuclausthal/submissioninterface/servlets/view/TaskManagerView.java
@@ -1,175 +1,175 @@
/*
* Copyright 2009 - 2010 Sven Strickroth <[email protected]>
*
* This file is part of the SubmissionInterface.
*
* SubmissionInterface is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* SubmissionInterface 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 SubmissionInterface. If not, see <http://www.gnu.org/licenses/>.
*/
package de.tuclausthal.submissioninterface.servlets.view;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import de.tuclausthal.submissioninterface.persistence.datamodel.CompileTest;
import de.tuclausthal.submissioninterface.persistence.datamodel.JUnitTest;
import de.tuclausthal.submissioninterface.persistence.datamodel.Lecture;
import de.tuclausthal.submissioninterface.persistence.datamodel.RegExpTest;
import de.tuclausthal.submissioninterface.persistence.datamodel.SimilarityTest;
import de.tuclausthal.submissioninterface.persistence.datamodel.Task;
import de.tuclausthal.submissioninterface.persistence.datamodel.Test;
import de.tuclausthal.submissioninterface.template.Template;
import de.tuclausthal.submissioninterface.template.TemplateFactory;
import de.tuclausthal.submissioninterface.util.Util;
/**
* View-Servlet for displaying a form for adding/editing a task
* @author Sven Strickroth
*/
public class TaskManagerView extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
Template template = TemplateFactory.getTemplate(request, response);
PrintWriter out = response.getWriter();
Task task = (Task) request.getAttribute("task");
Lecture lecture = task.getLecture();
template.addHead("<script type=\"text/javascript\" src=\"" + getServletContext().getContextPath() + "/tiny_mce/tiny_mce.js\"></script>");
template.addHead("<script type=\"text/javascript\">\ntinyMCE.init({" +
"mode : \"textareas\"," +
"theme : \"advanced\"," +
"plugins : \"safari,style,table,advimage,iespell,contextmenu,paste,nonbreaking\"," +
"theme_advanced_buttons1 : \"newdocument,|,undo,redo,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,formatselect,fontsizeselect\"," +
"theme_advanced_buttons2 : \"paste,pastetext,pasteword,|,bullist,numlist,|,outdent,indent,blockquote,|,link,unlink,anchor,image,cleanup,forecolor,backcolor\"," +
"theme_advanced_buttons3 : \"tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,iespell,advhr,|,nonbreaking,blockquote,code\"," +
"theme_advanced_toolbar_location : \"top\"," +
"theme_advanced_toolbar_align : \"left\"," +
"theme_advanced_statusbar_location : \"bottom\"," +
"theme_advanced_resizing : true," +
"content_css : \"/submissionsystem/si.css\"" +
"});\n</script>");
if (task.getTaskid() != 0) {
template.printTemplateHeader("Aufgabe bearbeiten", task);
} else {
template.printTemplateHeader("neue Aufgabe", lecture);
}
out.println("<form action=\"" + response.encodeURL("?") + "\" method=post>");
if (task.getTaskid() != 0) {
out.println("<input type=hidden name=action value=saveTask>");
out.println("<input type=hidden name=taskid value=\"" + task.getTaskid() + "\">");
} else {
out.println("<input type=hidden name=action value=saveNewTask>");
}
out.println("<input type=hidden name=lecture value=\"" + lecture.getId() + "\">");
out.println("<table class=border>");
out.println("<tr>");
out.println("<th>Titel:</th>");
out.println("<td><input type=text name=title value=\"" + Util.mknohtml(task.getTitle()) + "\"></td>");
out.println("</tr>");
out.println("<tr>");
out.println("<th>Beschreibung:</th>");
out.println("<td><textarea cols=60 rows=10 name=description>" + Util.mknohtml(task.getDescription()) + "</textarea></td>");
out.println("</tr>");
out.println("<tr>");
out.println("<th>Filename Regexp:</th>");
out.println("<td><input type=text name=filenameregexp value=\"" + Util.mknohtml(task.getFilenameRegexp()) + "\"> <b>F�r Java-Dateien: "[A-Z][A-Za-z0-9_]+\\.java", "-" = upload disabled</b></td>");
out.println("</tr>");
out.println("<tr>");
out.println("<th>Text-Eingabefeld:</th>");
out.println("<td><input type=checkbox name=showtextarea " + (task.isShowTextArea() ? "checked" : "") + "></td>");
out.println("</tr>");
out.println("<tr>");
out.println("<th>Startdatum:</th>");
out.println("<td><input type=text name=startdate value=\"" + Util.mknohtml(task.getStart().toLocaleString()) + "\"> (dd.MM.yyyy oder dd.MM.yyyy HH:mm:ss)</td>");
out.println("</tr>");
out.println("<tr>");
out.println("<th>Enddatum:</th>");
out.println("<td><input type=text name=deadline value=\"" + Util.mknohtml(task.getDeadline().toLocaleString()) + "\"> (dd.MM.yyyy oder dd.MM.yyyy HH:mm:ss)</td>");
out.println("</tr>");
out.println("<tr>");
out.println("<th>Punktedatum:</th>");
out.println("<td><input type=text name=pointsdate value=\"" + Util.mknohtml(task.getShowPoints().toLocaleString()) + "\"> (dd.MM.yyyy oder dd.MM.yyyy HH:mm:ss)</td>");
out.println("</tr>");
out.println("<tr>");
out.println("<th>Max. Punkte:</th>");
out.println("<td><input type=text name=maxpoints value=\"" + Util.showPoints(task.getMaxPoints()) + "\"> <b>bei �nderung bereits vergebene Pkts. pr�fen!</b></td>");
out.println("</tr>");
out.println("<tr>");
out.println("<td colspan=2 class=mid><input type=submit value=speichern> <a href=\"");
if (task.getTaskid() != 0) {
out.println(response.encodeURL("ShowTask?taskid=" + task.getTaskid()));
} else {
out.println(response.encodeURL("ShowLecture?lecture=" + lecture.getId()));
}
out.println("\">Abbrechen</a></td>");
out.println("</tr>");
out.println("</table>");
out.println("</form>");
// don't show for new tasks
if (task.getTaskid() != 0 && (task.isShowTextArea() == true || !"-".equals(task.getFilenameRegexp()))) {
out.println("<h2>�hnlichkeitspr�fungen</h2>");
out.println("<ul>");
for (SimilarityTest similarityTest : task.getSimularityTests()) {
out.print(similarityTest + "<br>");
out.print("Status: ");
if (similarityTest.isNeedsToRun()) {
out.println("in Queue, noch nicht ausgef�hrt<br>");
} else {
- out.println("in Ausf�hrung bzw. bereits ausgef�hrt - <a onclick=\"return confirmLink('Wirklich erneut ausf�hren?')\" href=\"" + response.encodeURL("DupeCheck?action=rerunSimilarityTest&testid=" + similarityTest.getSimilarityTestId()) + "&taskid=" + task.getTaskid() + "\">erneut ausf�hren</a><br>");
+ out.println("in Ausf�hrung bzw. bereits ausgef�hrt - <a onclick=\"return confirmLink('Wirklich erneut ausf�hren?')\" href=\"" + response.encodeURL("DupeCheck?action=rerunSimilarityTest&similaritytestid=" + similarityTest.getSimilarityTestId()) + "&taskid=" + task.getTaskid() + "\">erneut ausf�hren</a><br>");
}
out.println("<li><a onclick=\"return confirmLink('Wirklich l�schen?')\" href=\"" + response.encodeURL("DupeCheck?action=deleteSimilarityTest&taskid=" + task.getTaskid() + "&similaritytestid=" + similarityTest.getSimilarityTestId()) + "\">l�schen</a><br>");
}
out.println("</ul>");
out.println("<p class=mid><a href=\"" + response.encodeURL("DupeCheck?taskid=" + task.getTaskid()) + "\">�hnlichkeitspr�fung hinzuf�gen</a><p>");
out.println("<h2>Funktionstests der Abgaben</h2>");
out.println("<p class=mid><a href=\"" + response.encodeURL("TestManager?action=newTest&taskid=" + task.getTaskid()) + "\">Test hinzuf�gen</a></p>");
out.println("<ul>");
for (Test test : task.getTests()) {
out.println("<li>"" + Util.mknohtml(test.getTestTitle()) + "": ");
if (test instanceof RegExpTest) {
RegExpTest regexptest = (RegExpTest) test;
out.println("RegExp-Test:<br>Pr�fpattern: " + Util.mknohtml(regexptest.getRegularExpression()) + "<br>Parameter: " + Util.mknohtml(regexptest.getCommandLineParameter()) + "<br>Main-Klasse: " + Util.mknohtml(regexptest.getMainClass()) + "<br>");
} else if (test instanceof CompileTest) {
out.println("Compile-Test<br>");
} else if (test instanceof JUnitTest) {
out.println("JUnit-Test<br>");
} else {
out.println("unknown<br>");
}
out.println("# Ausf�hrbar f�r Studenten: " + test.getTimesRunnableByStudents() + "<br>");
out.println("Tutortest: " + test.isForTutors() + "<br>");
if (test.isForTutors()) {
out.print("Status: ");
if (test.isNeedsToRun()) {
out.println("in Queue, noch nicht ausgef�hrt<br>");
} else {
out.println("in Ausf�hrung bzw. bereits ausgef�hrt - <a onclick=\"return confirmLink('Wirklich erneut ausf�hren?')\" href=\"" + response.encodeURL("TestManager?action=rerunTest&testid=" + test.getId()) + "&taskid=" + task.getTaskid() + "\">erneut ausf�hren</a><br>");
}
}
out.println("<a onclick=\"return confirmLink('Wirklich l�schen?')\" href=\"" + response.encodeURL("TestManager?action=deleteTest&testid=" + test.getId()) + "&taskid=" + task.getTaskid() + "\">Test l�schen</a>");
out.println("</li>");
}
out.println("</ul>");
}
template.printTemplateFooter();
}
}
| true | true | public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
Template template = TemplateFactory.getTemplate(request, response);
PrintWriter out = response.getWriter();
Task task = (Task) request.getAttribute("task");
Lecture lecture = task.getLecture();
template.addHead("<script type=\"text/javascript\" src=\"" + getServletContext().getContextPath() + "/tiny_mce/tiny_mce.js\"></script>");
template.addHead("<script type=\"text/javascript\">\ntinyMCE.init({" +
"mode : \"textareas\"," +
"theme : \"advanced\"," +
"plugins : \"safari,style,table,advimage,iespell,contextmenu,paste,nonbreaking\"," +
"theme_advanced_buttons1 : \"newdocument,|,undo,redo,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,formatselect,fontsizeselect\"," +
"theme_advanced_buttons2 : \"paste,pastetext,pasteword,|,bullist,numlist,|,outdent,indent,blockquote,|,link,unlink,anchor,image,cleanup,forecolor,backcolor\"," +
"theme_advanced_buttons3 : \"tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,iespell,advhr,|,nonbreaking,blockquote,code\"," +
"theme_advanced_toolbar_location : \"top\"," +
"theme_advanced_toolbar_align : \"left\"," +
"theme_advanced_statusbar_location : \"bottom\"," +
"theme_advanced_resizing : true," +
"content_css : \"/submissionsystem/si.css\"" +
"});\n</script>");
if (task.getTaskid() != 0) {
template.printTemplateHeader("Aufgabe bearbeiten", task);
} else {
template.printTemplateHeader("neue Aufgabe", lecture);
}
out.println("<form action=\"" + response.encodeURL("?") + "\" method=post>");
if (task.getTaskid() != 0) {
out.println("<input type=hidden name=action value=saveTask>");
out.println("<input type=hidden name=taskid value=\"" + task.getTaskid() + "\">");
} else {
out.println("<input type=hidden name=action value=saveNewTask>");
}
out.println("<input type=hidden name=lecture value=\"" + lecture.getId() + "\">");
out.println("<table class=border>");
out.println("<tr>");
out.println("<th>Titel:</th>");
out.println("<td><input type=text name=title value=\"" + Util.mknohtml(task.getTitle()) + "\"></td>");
out.println("</tr>");
out.println("<tr>");
out.println("<th>Beschreibung:</th>");
out.println("<td><textarea cols=60 rows=10 name=description>" + Util.mknohtml(task.getDescription()) + "</textarea></td>");
out.println("</tr>");
out.println("<tr>");
out.println("<th>Filename Regexp:</th>");
out.println("<td><input type=text name=filenameregexp value=\"" + Util.mknohtml(task.getFilenameRegexp()) + "\"> <b>F�r Java-Dateien: "[A-Z][A-Za-z0-9_]+\\.java", "-" = upload disabled</b></td>");
out.println("</tr>");
out.println("<tr>");
out.println("<th>Text-Eingabefeld:</th>");
out.println("<td><input type=checkbox name=showtextarea " + (task.isShowTextArea() ? "checked" : "") + "></td>");
out.println("</tr>");
out.println("<tr>");
out.println("<th>Startdatum:</th>");
out.println("<td><input type=text name=startdate value=\"" + Util.mknohtml(task.getStart().toLocaleString()) + "\"> (dd.MM.yyyy oder dd.MM.yyyy HH:mm:ss)</td>");
out.println("</tr>");
out.println("<tr>");
out.println("<th>Enddatum:</th>");
out.println("<td><input type=text name=deadline value=\"" + Util.mknohtml(task.getDeadline().toLocaleString()) + "\"> (dd.MM.yyyy oder dd.MM.yyyy HH:mm:ss)</td>");
out.println("</tr>");
out.println("<tr>");
out.println("<th>Punktedatum:</th>");
out.println("<td><input type=text name=pointsdate value=\"" + Util.mknohtml(task.getShowPoints().toLocaleString()) + "\"> (dd.MM.yyyy oder dd.MM.yyyy HH:mm:ss)</td>");
out.println("</tr>");
out.println("<tr>");
out.println("<th>Max. Punkte:</th>");
out.println("<td><input type=text name=maxpoints value=\"" + Util.showPoints(task.getMaxPoints()) + "\"> <b>bei �nderung bereits vergebene Pkts. pr�fen!</b></td>");
out.println("</tr>");
out.println("<tr>");
out.println("<td colspan=2 class=mid><input type=submit value=speichern> <a href=\"");
if (task.getTaskid() != 0) {
out.println(response.encodeURL("ShowTask?taskid=" + task.getTaskid()));
} else {
out.println(response.encodeURL("ShowLecture?lecture=" + lecture.getId()));
}
out.println("\">Abbrechen</a></td>");
out.println("</tr>");
out.println("</table>");
out.println("</form>");
// don't show for new tasks
if (task.getTaskid() != 0 && (task.isShowTextArea() == true || !"-".equals(task.getFilenameRegexp()))) {
out.println("<h2>�hnlichkeitspr�fungen</h2>");
out.println("<ul>");
for (SimilarityTest similarityTest : task.getSimularityTests()) {
out.print(similarityTest + "<br>");
out.print("Status: ");
if (similarityTest.isNeedsToRun()) {
out.println("in Queue, noch nicht ausgef�hrt<br>");
} else {
out.println("in Ausf�hrung bzw. bereits ausgef�hrt - <a onclick=\"return confirmLink('Wirklich erneut ausf�hren?')\" href=\"" + response.encodeURL("DupeCheck?action=rerunSimilarityTest&testid=" + similarityTest.getSimilarityTestId()) + "&taskid=" + task.getTaskid() + "\">erneut ausf�hren</a><br>");
}
out.println("<li><a onclick=\"return confirmLink('Wirklich l�schen?')\" href=\"" + response.encodeURL("DupeCheck?action=deleteSimilarityTest&taskid=" + task.getTaskid() + "&similaritytestid=" + similarityTest.getSimilarityTestId()) + "\">l�schen</a><br>");
}
out.println("</ul>");
out.println("<p class=mid><a href=\"" + response.encodeURL("DupeCheck?taskid=" + task.getTaskid()) + "\">�hnlichkeitspr�fung hinzuf�gen</a><p>");
out.println("<h2>Funktionstests der Abgaben</h2>");
out.println("<p class=mid><a href=\"" + response.encodeURL("TestManager?action=newTest&taskid=" + task.getTaskid()) + "\">Test hinzuf�gen</a></p>");
out.println("<ul>");
for (Test test : task.getTests()) {
out.println("<li>"" + Util.mknohtml(test.getTestTitle()) + "": ");
if (test instanceof RegExpTest) {
RegExpTest regexptest = (RegExpTest) test;
out.println("RegExp-Test:<br>Pr�fpattern: " + Util.mknohtml(regexptest.getRegularExpression()) + "<br>Parameter: " + Util.mknohtml(regexptest.getCommandLineParameter()) + "<br>Main-Klasse: " + Util.mknohtml(regexptest.getMainClass()) + "<br>");
} else if (test instanceof CompileTest) {
out.println("Compile-Test<br>");
} else if (test instanceof JUnitTest) {
out.println("JUnit-Test<br>");
} else {
out.println("unknown<br>");
}
out.println("# Ausf�hrbar f�r Studenten: " + test.getTimesRunnableByStudents() + "<br>");
out.println("Tutortest: " + test.isForTutors() + "<br>");
if (test.isForTutors()) {
out.print("Status: ");
if (test.isNeedsToRun()) {
out.println("in Queue, noch nicht ausgef�hrt<br>");
} else {
out.println("in Ausf�hrung bzw. bereits ausgef�hrt - <a onclick=\"return confirmLink('Wirklich erneut ausf�hren?')\" href=\"" + response.encodeURL("TestManager?action=rerunTest&testid=" + test.getId()) + "&taskid=" + task.getTaskid() + "\">erneut ausf�hren</a><br>");
}
}
out.println("<a onclick=\"return confirmLink('Wirklich l�schen?')\" href=\"" + response.encodeURL("TestManager?action=deleteTest&testid=" + test.getId()) + "&taskid=" + task.getTaskid() + "\">Test l�schen</a>");
out.println("</li>");
}
out.println("</ul>");
}
template.printTemplateFooter();
}
| public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
Template template = TemplateFactory.getTemplate(request, response);
PrintWriter out = response.getWriter();
Task task = (Task) request.getAttribute("task");
Lecture lecture = task.getLecture();
template.addHead("<script type=\"text/javascript\" src=\"" + getServletContext().getContextPath() + "/tiny_mce/tiny_mce.js\"></script>");
template.addHead("<script type=\"text/javascript\">\ntinyMCE.init({" +
"mode : \"textareas\"," +
"theme : \"advanced\"," +
"plugins : \"safari,style,table,advimage,iespell,contextmenu,paste,nonbreaking\"," +
"theme_advanced_buttons1 : \"newdocument,|,undo,redo,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,formatselect,fontsizeselect\"," +
"theme_advanced_buttons2 : \"paste,pastetext,pasteword,|,bullist,numlist,|,outdent,indent,blockquote,|,link,unlink,anchor,image,cleanup,forecolor,backcolor\"," +
"theme_advanced_buttons3 : \"tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,iespell,advhr,|,nonbreaking,blockquote,code\"," +
"theme_advanced_toolbar_location : \"top\"," +
"theme_advanced_toolbar_align : \"left\"," +
"theme_advanced_statusbar_location : \"bottom\"," +
"theme_advanced_resizing : true," +
"content_css : \"/submissionsystem/si.css\"" +
"});\n</script>");
if (task.getTaskid() != 0) {
template.printTemplateHeader("Aufgabe bearbeiten", task);
} else {
template.printTemplateHeader("neue Aufgabe", lecture);
}
out.println("<form action=\"" + response.encodeURL("?") + "\" method=post>");
if (task.getTaskid() != 0) {
out.println("<input type=hidden name=action value=saveTask>");
out.println("<input type=hidden name=taskid value=\"" + task.getTaskid() + "\">");
} else {
out.println("<input type=hidden name=action value=saveNewTask>");
}
out.println("<input type=hidden name=lecture value=\"" + lecture.getId() + "\">");
out.println("<table class=border>");
out.println("<tr>");
out.println("<th>Titel:</th>");
out.println("<td><input type=text name=title value=\"" + Util.mknohtml(task.getTitle()) + "\"></td>");
out.println("</tr>");
out.println("<tr>");
out.println("<th>Beschreibung:</th>");
out.println("<td><textarea cols=60 rows=10 name=description>" + Util.mknohtml(task.getDescription()) + "</textarea></td>");
out.println("</tr>");
out.println("<tr>");
out.println("<th>Filename Regexp:</th>");
out.println("<td><input type=text name=filenameregexp value=\"" + Util.mknohtml(task.getFilenameRegexp()) + "\"> <b>F�r Java-Dateien: "[A-Z][A-Za-z0-9_]+\\.java", "-" = upload disabled</b></td>");
out.println("</tr>");
out.println("<tr>");
out.println("<th>Text-Eingabefeld:</th>");
out.println("<td><input type=checkbox name=showtextarea " + (task.isShowTextArea() ? "checked" : "") + "></td>");
out.println("</tr>");
out.println("<tr>");
out.println("<th>Startdatum:</th>");
out.println("<td><input type=text name=startdate value=\"" + Util.mknohtml(task.getStart().toLocaleString()) + "\"> (dd.MM.yyyy oder dd.MM.yyyy HH:mm:ss)</td>");
out.println("</tr>");
out.println("<tr>");
out.println("<th>Enddatum:</th>");
out.println("<td><input type=text name=deadline value=\"" + Util.mknohtml(task.getDeadline().toLocaleString()) + "\"> (dd.MM.yyyy oder dd.MM.yyyy HH:mm:ss)</td>");
out.println("</tr>");
out.println("<tr>");
out.println("<th>Punktedatum:</th>");
out.println("<td><input type=text name=pointsdate value=\"" + Util.mknohtml(task.getShowPoints().toLocaleString()) + "\"> (dd.MM.yyyy oder dd.MM.yyyy HH:mm:ss)</td>");
out.println("</tr>");
out.println("<tr>");
out.println("<th>Max. Punkte:</th>");
out.println("<td><input type=text name=maxpoints value=\"" + Util.showPoints(task.getMaxPoints()) + "\"> <b>bei �nderung bereits vergebene Pkts. pr�fen!</b></td>");
out.println("</tr>");
out.println("<tr>");
out.println("<td colspan=2 class=mid><input type=submit value=speichern> <a href=\"");
if (task.getTaskid() != 0) {
out.println(response.encodeURL("ShowTask?taskid=" + task.getTaskid()));
} else {
out.println(response.encodeURL("ShowLecture?lecture=" + lecture.getId()));
}
out.println("\">Abbrechen</a></td>");
out.println("</tr>");
out.println("</table>");
out.println("</form>");
// don't show for new tasks
if (task.getTaskid() != 0 && (task.isShowTextArea() == true || !"-".equals(task.getFilenameRegexp()))) {
out.println("<h2>�hnlichkeitspr�fungen</h2>");
out.println("<ul>");
for (SimilarityTest similarityTest : task.getSimularityTests()) {
out.print(similarityTest + "<br>");
out.print("Status: ");
if (similarityTest.isNeedsToRun()) {
out.println("in Queue, noch nicht ausgef�hrt<br>");
} else {
out.println("in Ausf�hrung bzw. bereits ausgef�hrt - <a onclick=\"return confirmLink('Wirklich erneut ausf�hren?')\" href=\"" + response.encodeURL("DupeCheck?action=rerunSimilarityTest&similaritytestid=" + similarityTest.getSimilarityTestId()) + "&taskid=" + task.getTaskid() + "\">erneut ausf�hren</a><br>");
}
out.println("<li><a onclick=\"return confirmLink('Wirklich l�schen?')\" href=\"" + response.encodeURL("DupeCheck?action=deleteSimilarityTest&taskid=" + task.getTaskid() + "&similaritytestid=" + similarityTest.getSimilarityTestId()) + "\">l�schen</a><br>");
}
out.println("</ul>");
out.println("<p class=mid><a href=\"" + response.encodeURL("DupeCheck?taskid=" + task.getTaskid()) + "\">�hnlichkeitspr�fung hinzuf�gen</a><p>");
out.println("<h2>Funktionstests der Abgaben</h2>");
out.println("<p class=mid><a href=\"" + response.encodeURL("TestManager?action=newTest&taskid=" + task.getTaskid()) + "\">Test hinzuf�gen</a></p>");
out.println("<ul>");
for (Test test : task.getTests()) {
out.println("<li>"" + Util.mknohtml(test.getTestTitle()) + "": ");
if (test instanceof RegExpTest) {
RegExpTest regexptest = (RegExpTest) test;
out.println("RegExp-Test:<br>Pr�fpattern: " + Util.mknohtml(regexptest.getRegularExpression()) + "<br>Parameter: " + Util.mknohtml(regexptest.getCommandLineParameter()) + "<br>Main-Klasse: " + Util.mknohtml(regexptest.getMainClass()) + "<br>");
} else if (test instanceof CompileTest) {
out.println("Compile-Test<br>");
} else if (test instanceof JUnitTest) {
out.println("JUnit-Test<br>");
} else {
out.println("unknown<br>");
}
out.println("# Ausf�hrbar f�r Studenten: " + test.getTimesRunnableByStudents() + "<br>");
out.println("Tutortest: " + test.isForTutors() + "<br>");
if (test.isForTutors()) {
out.print("Status: ");
if (test.isNeedsToRun()) {
out.println("in Queue, noch nicht ausgef�hrt<br>");
} else {
out.println("in Ausf�hrung bzw. bereits ausgef�hrt - <a onclick=\"return confirmLink('Wirklich erneut ausf�hren?')\" href=\"" + response.encodeURL("TestManager?action=rerunTest&testid=" + test.getId()) + "&taskid=" + task.getTaskid() + "\">erneut ausf�hren</a><br>");
}
}
out.println("<a onclick=\"return confirmLink('Wirklich l�schen?')\" href=\"" + response.encodeURL("TestManager?action=deleteTest&testid=" + test.getId()) + "&taskid=" + task.getTaskid() + "\">Test l�schen</a>");
out.println("</li>");
}
out.println("</ul>");
}
template.printTemplateFooter();
}
|
diff --git a/src/net/rptools/maptool/model/Token.java b/src/net/rptools/maptool/model/Token.java
index f3af18e0..4b47ed3c 100644
--- a/src/net/rptools/maptool/model/Token.java
+++ b/src/net/rptools/maptool/model/Token.java
@@ -1,1086 +1,1087 @@
/* The MIT License
*
* Copyright (c) 2005 David Rice, Trevor Croft
*
* 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 net.rptools.maptool.model;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Set;
import javax.swing.ImageIcon;
import net.rptools.lib.MD5Key;
import net.rptools.lib.image.ImageUtil;
import net.rptools.lib.transferable.TokenTransferData;
import net.rptools.maptool.util.ImageManager;
import net.rptools.maptool.util.StringUtil;
/**
* This object represents the placeable objects on a map. For example an icon
* that represents a character would exist as an {@link Asset} (the image
* itself) and a location and scale.
*/
public class Token extends BaseModel {
private GUID id = new GUID();
public static final String FILE_EXTENSION = "rptok";
public static final String FILE_THUMBNAIL = "thumbnail";
public static final String NAME_USE_FILENAME = "Use Filename";
public static final String NAME_USE_CREATURE = "Use \"Creature\"";
public static final String NUM_INCREMENT = "Increment";
public static final String NUM_RANDOM = "Random 2-digit";
public static final String NUM_ON_NAME = "Name";
public static final String NUM_ON_GM = "GM Name";
public static final String NUM_ON_BOTH = "Both";
public enum TokenShape {
TOP_DOWN("Top down"),
CIRCLE("Circle"),
SQUARE("Square");
private String displayName;
private TokenShape(String displayName) {
this.displayName = displayName;
}
public String toString() {
return displayName;
}
}
public enum Type {
PC,
NPC
}
public static final Comparator<Token> NAME_COMPARATOR = new Comparator<Token>() {
public int compare(Token o1, Token o2) {
return o1.getName().compareToIgnoreCase(o2.getName());
}
};
private Map<String, MD5Key> imageAssetMap;
private String currentImageAsset;
private int x;
private int y;
private int z;
private int anchorX;
private int anchorY;
private double sizeScale = 1;
private int lastX;
private int lastY;
private Path<? extends AbstractPoint> lastPath;
private boolean snapToScale = true; // Whether the scaleX and scaleY
// represent snap-to-grid measurements
// These are the original image width and height
private int width;
private int height;
private double scaleX = 1;
private double scaleY = 1;
private Map<Class<? extends Grid>, GUID> sizeMap;
private boolean snapToGrid = true; // Whether the token snaps to the
// current grid or is free floating
private boolean isVisible = true;
private String name;
private Set<String> ownerList;
private int ownerType;
private static final int OWNER_TYPE_ALL = 1;
private static final int OWNER_TYPE_LIST = 0;
private String tokenShape;
private String tokenType;
private String layer;
private String propertyType = Campaign.DEFAULT_TOKEN_PROPERTY_TYPE;
private Integer facing = null;
private Integer haloColorValue;
private transient Color haloColor;
private Integer visionOverlayColorValue;
private transient Color visionOverlayColor;
private boolean isFlippedX;
private boolean isFlippedY;
private MD5Key charsheetImage;
private MD5Key portraitImage;
private List<AttachedLightSource> lightSourceList;
private String sightType;
private boolean hasSight;
private String label;
/**
* The notes that are displayed for this token.
*/
private String notes;
private String gmNotes;
private String gmName;
/**
* A state properties for this token. This allows state to be added that can
* change appearance of the token.
*/
private Map<String, Object> state;
/**
* Properties
*/
private Map<String, Object> propertyMap;
private Map<String, String> macroMap;
private Map<String, String> speechMap;
// Deprecated, here to allow deserialization
private transient int size; // 1.3b16
private transient List<Vision> visionList; // 1.3b18
public enum ChangeEvent {
name
}
public Token(Token token) {
id = new GUID();
currentImageAsset = token.currentImageAsset;
x = token.x;
y = token.y;
// These properties shouldn't be transferred, they are more transient and relate to token history, not to new tokens
// lastX = token.lastX;
// lastY = token.lastY;
// lastPath = token.lastPath;
snapToScale = token.snapToScale;
width = token.width;
height = token.height;
scaleX = token.scaleX;
scaleY = token.scaleY;
facing = token.facing;
tokenShape = token.tokenShape;
tokenType = token.tokenType;
haloColorValue = token.haloColorValue;
snapToGrid = token.snapToGrid;
isVisible = token.isVisible;
name = token.name;
notes = token.notes;
gmName = token.gmName;
gmNotes = token.gmNotes;
label = token.label;
isFlippedX = token.isFlippedX;
isFlippedY = token.isFlippedY;
layer = token.layer;
visionOverlayColor = token.visionOverlayColor;
charsheetImage = token.charsheetImage;
portraitImage = token.portraitImage;
anchorX = token.anchorX;
anchorY = token.anchorY;
sizeScale = token.sizeScale;
sightType = token.sightType;
hasSight = token.hasSight;
+ propertyType = token.propertyType;
ownerType = token.ownerType;
if (token.ownerList != null) {
ownerList = new HashSet<String>();
ownerList.addAll(token.ownerList);
}
if (token.lightSourceList != null) {
lightSourceList = new ArrayList<AttachedLightSource>(token.lightSourceList);
}
if (token.state != null) {
state = new HashMap<String, Object>(token.state);
}
if (token.propertyMap != null) {
propertyMap = new HashMap<String, Object>(token.propertyMap);
}
if (token.macroMap != null) {
macroMap = new HashMap<String, String>(token.macroMap);
}
if (token.speechMap != null) {
speechMap = new HashMap<String, String>(token.speechMap);
}
if (token.imageAssetMap != null) {
imageAssetMap = new HashMap<String, MD5Key>(token.imageAssetMap);
}
if (token.sizeMap != null) {
sizeMap = new HashMap<Class<? extends Grid>, GUID>(token.sizeMap);
}
}
public Token() {
}
public Token(MD5Key assetID) {
this("", assetID);
}
public Token(String name, MD5Key assetId) {
this.name = name;
state = new HashMap<String, Object>();
imageAssetMap = new HashMap<String, MD5Key>();
// NULL key is the default
imageAssetMap.put(null, assetId);
}
public void setHasSight(boolean hasSight) {
this.hasSight = hasSight;
}
public void setWidth(int width) {
this.width = width;
}
public void setHeight(int height) {
this.height = height;
}
public boolean isMarker() {
return isStamp() && (!StringUtil.isEmpty(notes) || !StringUtil.isEmpty(gmNotes) || portraitImage != null);
}
public String getPropertyType() {
return propertyType;
}
public void setPropertyType(String propertyType) {
this.propertyType = propertyType;
}
public String getGMNotes() {
return gmNotes;
}
public void setGMNotes(String notes) {
gmNotes = notes;
}
public String getGMName() {
return gmName;
}
public void setGMName(String name) {
gmName = name;
}
public boolean hasHalo() {
return haloColorValue != null;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public void setHaloColor(Color color) {
if (color != null) {
haloColorValue = color.getRGB();
} else {
haloColorValue = null;
}
haloColor = color;
}
public Color getHaloColor() {
if (haloColor == null && haloColorValue != null) {
haloColor = new Color(haloColorValue);
}
return haloColor;
}
public boolean isObjectStamp() {
return getLayer() == Zone.Layer.OBJECT;
}
public boolean isGMStamp() {
return getLayer() == Zone.Layer.GM;
}
public boolean isBackgroundStamp() {
return getLayer() == Zone.Layer.BACKGROUND;
}
public boolean isStamp() {
switch(getLayer()) {
case BACKGROUND:
case OBJECT:
case GM:
return true;
}
return false; }
public boolean isToken() {
return getLayer() == Zone.Layer.TOKEN;
}
public TokenShape getShape() {
try {
return tokenShape != null ? TokenShape.valueOf(tokenShape) : TokenShape.SQUARE; // TODO: make this a psf
} catch (IllegalArgumentException iae) {
return TokenShape.SQUARE;
}
}
public void setShape(TokenShape type) {
this.tokenShape = type.name();
}
public Type getType() {
try {
return tokenType != null ? Type.valueOf(tokenType) : Type.NPC; // TODO: make this a psf
} catch (IllegalArgumentException iae) {
return Type.NPC;
}
}
public void setType(Type type) {
this.tokenType = type.name();
}
public Zone.Layer getLayer() {
try {
return layer != null ? Zone.Layer.valueOf(layer) : Zone.Layer.TOKEN;
} catch (IllegalArgumentException iae) {
return Zone.Layer.TOKEN;
}
}
public void setLayer(Zone.Layer layer) {
this.layer = layer.name();
}
public boolean hasFacing() {
return facing != null;
}
public void setFacing(Integer facing) {
this.facing = facing;
}
public Integer getFacing() {
return facing;
}
public boolean getHasSight() {
return getType() == Type.PC || hasSight;
}
public void addLightSource(LightSource source, Direction direction) {
if (lightSourceList == null) {
lightSourceList = new ArrayList<AttachedLightSource>();
}
lightSourceList.add(new AttachedLightSource(source, direction));
}
public void removeLightSource(LightSource source) {
if (lightSourceList == null) {
return;
}
for (ListIterator<AttachedLightSource> i = lightSourceList.listIterator(); i.hasNext();) {
AttachedLightSource als = i.next();
if (als.getLightSourceId().equals(source.getId())) {
i.remove();
break;
}
}
}
public boolean hasLightSource(LightSource source) {
if (lightSourceList == null) {
return false;
}
for (ListIterator<AttachedLightSource> i = lightSourceList.listIterator(); i.hasNext();) {
AttachedLightSource als = i.next();
if (als.getLightSourceId().equals(source.getId())) {
return true;
}
}
return false;
}
public boolean hasLightSources() {
return lightSourceList != null && lightSourceList.size() > 0;
}
public List<AttachedLightSource> getLightSources() {
return lightSourceList != null ? Collections.unmodifiableList(lightSourceList) : new LinkedList<AttachedLightSource>();
}
public synchronized void addOwner(String playerId) {
ownerType = OWNER_TYPE_LIST;
if (ownerList == null) {
ownerList = new HashSet<String>();
}
ownerList.add(playerId);
}
public synchronized boolean hasOwners() {
return ownerType == OWNER_TYPE_ALL || (ownerList != null && !ownerList.isEmpty());
}
public synchronized void removeOwner(String playerId) {
ownerType = OWNER_TYPE_LIST;
if (ownerList == null) {
return;
}
ownerList.remove(playerId);
if (ownerList.size() == 0) {
ownerList = null;
}
}
public synchronized void setOwnedByAll(boolean ownedByAll) {
if (ownedByAll) {
ownerType = OWNER_TYPE_ALL;
ownerList = null;
} else {
ownerType = OWNER_TYPE_LIST;
}
}
public Set<String> getOwners() {
return ownerList != null ? Collections.unmodifiableSet(ownerList) : new HashSet<String>();
}
public boolean isOwnedByAll() {
return ownerType == OWNER_TYPE_ALL;
}
public synchronized void clearAllOwners() {
ownerList = null;
}
public synchronized boolean isOwner(String playerId) {
return /*getType() == Type.PC && */(ownerType == OWNER_TYPE_ALL
|| (ownerList != null && ownerList.contains(playerId)));
}
@Override
public int hashCode() {
return id.hashCode();
}
public boolean equals(Object o) {
if (!(o instanceof Token)) {
return false;
}
return id.equals(((Token) o).id);
}
public void setZOrder(int z) {
this.z = z;
}
public int getZOrder() {
return z;
}
public void setName(String name) {
this.name = name;
fireModelChangeEvent(new ModelChangeEvent(this, ChangeEvent.name, name));
}
public MD5Key getImageAssetId() {
MD5Key assetId = imageAssetMap.get(currentImageAsset);
if (assetId == null) {
assetId = imageAssetMap.get(null); // default image
}
return assetId;
}
public void setImageAsset(String name, MD5Key assetId) {
imageAssetMap.put(name, assetId);
}
public void setImageAsset(String name) {
currentImageAsset = name;
}
public Set<MD5Key> getAllImageAssets() {
Set<MD5Key> assetSet = new HashSet<MD5Key>(imageAssetMap.values());
assetSet.add(charsheetImage);
assetSet.add(portraitImage);
return assetSet;
}
public MD5Key getPortraitImage() {
return portraitImage;
}
public void setPortraitImage(MD5Key image) {
portraitImage = image;
}
public MD5Key getCharsheetImage() {
return charsheetImage;
}
public void setCharsheetImage(MD5Key charsheetImage) {
this.charsheetImage = charsheetImage;
}
public GUID getId() {
return id;
}
public void setId(GUID id) {
this.id = id;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public void setX(int x) {
lastX = this.x;
this.x = x;
}
public void setY(int y) {
lastY = this.y;
this.y = y;
}
public void applyMove(int xOffset, int yOffset, Path<AbstractPoint> path) {
setX(x + xOffset);
setY(y + yOffset);
lastPath = path;
}
public void setLastPath(Path<? extends AbstractPoint> path) {
lastPath = path;
}
public int getLastY() {
return lastY;
}
public int getLastX() {
return lastX;
}
public Path<? extends AbstractPoint> getLastPath() {
return lastPath;
}
public double getScaleX() {
return scaleX;
}
public double getScaleY() {
return scaleY;
}
public void setScaleX(double scaleX) {
this.scaleX = scaleX;
}
public void setScaleY(double scaleY) {
this.scaleY = scaleY;
}
/**
* @return Returns the snapScale.
*/
public boolean isSnapToScale() {
return snapToScale;
}
/**
* @param snapScale
* The snapScale to set.
*/
public void setSnapToScale(boolean snapScale) {
this.snapToScale = snapScale;
}
public void setVisible(boolean visible) {
this.isVisible = visible;
}
public boolean isVisible() {
return isVisible;
}
public String getName() {
return name != null ? name : "";
}
public Rectangle getBounds(Zone zone) {
TokenFootprint footprint = getFootprint(zone.getGrid());
Rectangle footprintBounds = footprint.getBounds(zone.getGrid(), zone.getGrid().convert(new ZonePoint(getX(), getY())));
double width = footprintBounds.width;
double height = footprintBounds.height;
// Sizing
if (!isSnapToScale()) {
width = this.width * getScaleX();
height = this.height * getScaleY();
} else {
width = footprintBounds.width * footprint.getScale() * sizeScale;
height = footprintBounds.height * footprint.getScale() * sizeScale;
}
// Positioning
if (!isSnapToGrid()) {
footprintBounds.x = getX();
footprintBounds.y = getY();
} else {
if (!isBackgroundStamp()) {
// Center it on the footprint
footprintBounds.x -= (width - footprintBounds.width)/2;
footprintBounds.y -= (height - footprintBounds.height)/2;
} else {
// footprintBounds.x -= zone.getGrid().getSize()/2;
// footprintBounds.y -= zone.getGrid().getSize()/2;
}
}
footprintBounds.width = (int)width; // perhaps make this a double
footprintBounds.height = (int)height;
// Offset
footprintBounds.x += anchorX;
footprintBounds.y += anchorY;
return footprintBounds;
}
public String getSightType() {
return sightType;
}
public void setSightType(String sightType) {
this.sightType = sightType;
}
/**
* @return Returns the size.
*/
public TokenFootprint getFootprint(Grid grid) {
return grid.getFootprint(getSizeMap().get(grid.getClass()));
}
public TokenFootprint setFootprint(Grid grid, TokenFootprint footprint) {
return grid.getFootprint(getSizeMap().put(grid.getClass(), footprint.getId()));
}
private Map<Class<? extends Grid>, GUID> getSizeMap() {
if (sizeMap == null) {
sizeMap = new HashMap<Class<? extends Grid>, GUID>();
}
return sizeMap;
}
public boolean isSnapToGrid() {
return snapToGrid;
}
public void setSnapToGrid(boolean snapToGrid) {
this.snapToGrid = snapToGrid;
}
/**
* Get a particular state property for this Token.
*
* @param property
* The name of the property being read.
* @return Returns the current value of property.
*/
public Object getState(String property) {
return state.get(property);
}
/**
* Set the value of state for this Token.
*
* @param aState
* The property to set.
* @param aValue
* The new value for the property.
* @return The original vaoue of the property, if any.
*/
public Object setState(String aState, Object aValue) {
if (aValue == null)
return state.remove(aState);
return state.put(aState, aValue);
}
public void setProperty(String key, Object value) {
getPropertyMap().put(key, value);
}
public Object getProperty(String key) {
return getPropertyMap().get(key);
}
public Set<String> getPropertyNames() {
return getPropertyMap().keySet();
}
private Map<String, Object> getPropertyMap() {
if (propertyMap == null) {
propertyMap = new HashMap<String, Object>();
}
return propertyMap;
}
public void setMacroMap(Map<String, String> map) {
getMacroMap().clear();
getMacroMap().putAll(map);
}
public Set<String> getMacroNames() {
return getMacroMap().keySet();
}
public String getMacro(String key) {
return getMacroMap().get(key);
}
private Map<String, String> getMacroMap() {
if (macroMap == null) {
macroMap = new HashMap<String, String>();
}
return macroMap;
}
public void setSpeechMap(Map<String, String> map) {
getSpeechMap().clear();
getSpeechMap().putAll(map);
}
public Set<String> getSpeechNames() {
return getSpeechMap().keySet();
}
public String getSpeech(String key) {
return getSpeechMap().get(key);
}
private Map<String, String> getSpeechMap() {
if (speechMap == null) {
speechMap = new HashMap<String, String>();
}
return speechMap;
}
/**
* Get a set containing the names of all set properties on this token.
*
* @return The set of state property names that have a value associated with
* them.
*/
public Set<String> getStatePropertyNames() {
return state.keySet();
}
/** @return Getter for notes */
public String getNotes() {
return notes;
}
/**
* @param aNotes
* Setter for notes
*/
public void setNotes(String aNotes) {
notes = aNotes;
}
public boolean isFlippedY() {
return isFlippedY;
}
public void setFlippedY(boolean isFlippedY) {
this.isFlippedY = isFlippedY;
}
public boolean isFlippedX() {
return isFlippedX;
}
public void setFlippedX(boolean isFlippedX) {
this.isFlippedX = isFlippedX;
}
public Color getVisionOverlayColor() {
if (visionOverlayColor == null && visionOverlayColorValue != null) {
visionOverlayColor = new Color(visionOverlayColorValue);
}
return visionOverlayColor;
}
public void setVisionOverlayColor(Color color) {
if (color != null) {
visionOverlayColorValue = color.getRGB();
} else {
visionOverlayColorValue = null;
}
visionOverlayColor = color;
}
@Override
public String toString() {
return "Token: " + id;
}
public void setAnchor(int x, int y) {
anchorX = x;
anchorY = y;
}
public Point getAnchor() {
return new Point(anchorX, anchorY);
}
public double getSizeScale() {
return sizeScale;
}
public void setSizeScale(double scale) {
sizeScale = scale;
}
/**
* Convert the token into a hash map. This is used to ship all of the
* properties for the token to other apps that do need access to the
* <code>Token</code> class.
*
* @return A map containing the properties of the token.
*/
public TokenTransferData toTransferData() {
TokenTransferData td = new TokenTransferData();
td.setName(name);
td.setPlayers(ownerList);
td.setVisible(isVisible);
td.setLocation(new Point(x, y));
td.setFacing(facing);
// Set the properties
td.put(TokenTransferData.ID, id.toString());
td.put(TokenTransferData.ASSET_ID, imageAssetMap.get(null));
td.put(TokenTransferData.Z, z);
td.put(TokenTransferData.SNAP_TO_SCALE, snapToScale);
td.put(TokenTransferData.WIDTH, scaleX);
td.put(TokenTransferData.HEIGHT, scaleY);
// td.put(TokenTransferData.SIZE, size);
td.put(TokenTransferData.SNAP_TO_GRID, snapToGrid);
td.put(TokenTransferData.OWNER_TYPE, ownerType);
td.put(TokenTransferData.TOKEN_TYPE, tokenShape);
td.put(TokenTransferData.NOTES, notes);
td.put(TokenTransferData.GM_NOTES, gmNotes);
td.put(TokenTransferData.GM_NAME, gmName);
// Put all of the serializable state into the map
for (String key : getStatePropertyNames()) {
Object value = getState(key);
if (value instanceof Serializable)
td.put(key, value);
}
td.putAll(state);
// Create the image from the asset and add it to the map
Asset asset = AssetManager.getAsset(imageAssetMap.get(null));
Image image = ImageManager.getImageAndWait(asset);
if (image != null)
td.setToken(new ImageIcon(image)); // Image icon makes it serializable.
return td;
}
/**
* Constructor to create a new token from a transfer object containing its property
* values. This is used to read in a new token from other apps that don't
* have access to the <code>Token</code> class.
*
* @param td
* Read the values from this transfer object.
*/
public Token(TokenTransferData td) {
if (td.getLocation() != null) {
x = td.getLocation().x;
y = td.getLocation().y;
}
snapToScale = getBoolean(td, TokenTransferData.SNAP_TO_SCALE, true);
scaleX = getInt(td, TokenTransferData.WIDTH, 1);
scaleY = getInt(td, TokenTransferData.HEIGHT, 1);
// size = getInt(td, TokenTransferData.SIZE, TokenSize.Size.Medium.value());
snapToGrid = getBoolean(td, TokenTransferData.SNAP_TO_GRID, true);
isVisible = td.isVisible();
name = td.getName();
ownerList = td.getPlayers();
ownerType = getInt(td, TokenTransferData.OWNER_TYPE,
ownerList == null ? OWNER_TYPE_ALL : OWNER_TYPE_LIST);
tokenShape = (String) td.get(TokenTransferData.TOKEN_TYPE);
facing = td.getFacing();
notes = (String) td.get(TokenTransferData.NOTES);
gmNotes = (String) td.get(TokenTransferData.GM_NOTES);
gmName = (String) td.get(TokenTransferData.GM_NAME);
// Get the image for the token
ImageIcon icon = td.getToken();
if (icon != null) {
// Make sure there is a buffered image for it
Image image = icon.getImage();
if (!(image instanceof BufferedImage)) {
image = new BufferedImage(icon.getIconWidth(), icon
.getIconHeight(), Transparency.TRANSLUCENT);
Graphics2D g = ((BufferedImage) image).createGraphics();
icon.paintIcon(null, g, 0, 0);
}
// Create the asset
try {
Asset asset = new Asset(name, ImageUtil
.imageToBytes((BufferedImage) image));
if (!AssetManager.hasAsset(asset))
AssetManager.putAsset(asset);
imageAssetMap.put(null, asset.getId());
} catch (IOException e) {
e.printStackTrace();
}
}
// Get all of the non maptool state
state = new HashMap<String, Object>();
for (String key : td.keySet()) {
if (key.startsWith(TokenTransferData.MAPTOOL))
continue;
setState(key, td.get(key));
} // endfor
}
/**
* Get an integer value from the map or return the default value
*
* @param map
* Get the value from this map
* @param propName
* The name of the property being read.
* @param defaultValue
* The value for the property if it is not set in the map.
* @return The value for the passed property
*/
private static int getInt(Map<String, Object> map, String propName,
int defaultValue) {
Integer integer = (Integer) map.get(propName);
if (integer == null)
return defaultValue;
return integer.intValue();
}
/**
* Get a boolean value from the map or return the default value
*
* @param map
* Get the value from this map
* @param propName
* The name of the property being read.
* @param defaultValue
* The value for the property if it is not set in the map.
* @return The value for the passed property
*/
private static boolean getBoolean(Map<String, Object> map, String propName,
boolean defaultValue) {
Boolean bool = (Boolean) map.get(propName);
if (bool == null)
return defaultValue;
return bool.booleanValue();
}
public static boolean isTokenFile(String filename) {
return filename != null && filename.toLowerCase().endsWith(FILE_EXTENSION);
}
}
| true | true | public Token(Token token) {
id = new GUID();
currentImageAsset = token.currentImageAsset;
x = token.x;
y = token.y;
// These properties shouldn't be transferred, they are more transient and relate to token history, not to new tokens
// lastX = token.lastX;
// lastY = token.lastY;
// lastPath = token.lastPath;
snapToScale = token.snapToScale;
width = token.width;
height = token.height;
scaleX = token.scaleX;
scaleY = token.scaleY;
facing = token.facing;
tokenShape = token.tokenShape;
tokenType = token.tokenType;
haloColorValue = token.haloColorValue;
snapToGrid = token.snapToGrid;
isVisible = token.isVisible;
name = token.name;
notes = token.notes;
gmName = token.gmName;
gmNotes = token.gmNotes;
label = token.label;
isFlippedX = token.isFlippedX;
isFlippedY = token.isFlippedY;
layer = token.layer;
visionOverlayColor = token.visionOverlayColor;
charsheetImage = token.charsheetImage;
portraitImage = token.portraitImage;
anchorX = token.anchorX;
anchorY = token.anchorY;
sizeScale = token.sizeScale;
sightType = token.sightType;
hasSight = token.hasSight;
ownerType = token.ownerType;
if (token.ownerList != null) {
ownerList = new HashSet<String>();
ownerList.addAll(token.ownerList);
}
if (token.lightSourceList != null) {
lightSourceList = new ArrayList<AttachedLightSource>(token.lightSourceList);
}
if (token.state != null) {
state = new HashMap<String, Object>(token.state);
}
if (token.propertyMap != null) {
propertyMap = new HashMap<String, Object>(token.propertyMap);
}
if (token.macroMap != null) {
macroMap = new HashMap<String, String>(token.macroMap);
}
if (token.speechMap != null) {
speechMap = new HashMap<String, String>(token.speechMap);
}
if (token.imageAssetMap != null) {
imageAssetMap = new HashMap<String, MD5Key>(token.imageAssetMap);
}
if (token.sizeMap != null) {
sizeMap = new HashMap<Class<? extends Grid>, GUID>(token.sizeMap);
}
}
| public Token(Token token) {
id = new GUID();
currentImageAsset = token.currentImageAsset;
x = token.x;
y = token.y;
// These properties shouldn't be transferred, they are more transient and relate to token history, not to new tokens
// lastX = token.lastX;
// lastY = token.lastY;
// lastPath = token.lastPath;
snapToScale = token.snapToScale;
width = token.width;
height = token.height;
scaleX = token.scaleX;
scaleY = token.scaleY;
facing = token.facing;
tokenShape = token.tokenShape;
tokenType = token.tokenType;
haloColorValue = token.haloColorValue;
snapToGrid = token.snapToGrid;
isVisible = token.isVisible;
name = token.name;
notes = token.notes;
gmName = token.gmName;
gmNotes = token.gmNotes;
label = token.label;
isFlippedX = token.isFlippedX;
isFlippedY = token.isFlippedY;
layer = token.layer;
visionOverlayColor = token.visionOverlayColor;
charsheetImage = token.charsheetImage;
portraitImage = token.portraitImage;
anchorX = token.anchorX;
anchorY = token.anchorY;
sizeScale = token.sizeScale;
sightType = token.sightType;
hasSight = token.hasSight;
propertyType = token.propertyType;
ownerType = token.ownerType;
if (token.ownerList != null) {
ownerList = new HashSet<String>();
ownerList.addAll(token.ownerList);
}
if (token.lightSourceList != null) {
lightSourceList = new ArrayList<AttachedLightSource>(token.lightSourceList);
}
if (token.state != null) {
state = new HashMap<String, Object>(token.state);
}
if (token.propertyMap != null) {
propertyMap = new HashMap<String, Object>(token.propertyMap);
}
if (token.macroMap != null) {
macroMap = new HashMap<String, String>(token.macroMap);
}
if (token.speechMap != null) {
speechMap = new HashMap<String, String>(token.speechMap);
}
if (token.imageAssetMap != null) {
imageAssetMap = new HashMap<String, MD5Key>(token.imageAssetMap);
}
if (token.sizeMap != null) {
sizeMap = new HashMap<Class<? extends Grid>, GUID>(token.sizeMap);
}
}
|
diff --git a/jacoco/src/test/java/org/sonar/plugins/jacoco/JaCoCoSensorTest.java b/jacoco/src/test/java/org/sonar/plugins/jacoco/JaCoCoSensorTest.java
index 88d69f371..139eb16c9 100644
--- a/jacoco/src/test/java/org/sonar/plugins/jacoco/JaCoCoSensorTest.java
+++ b/jacoco/src/test/java/org/sonar/plugins/jacoco/JaCoCoSensorTest.java
@@ -1,52 +1,52 @@
/*
* Sonar, open source software quality management tool.
* Copyright (C) 2010 SonarSource
* mailto:contact AT sonarsource DOT com
*
* 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.plugins.jacoco;
import org.junit.Before;
import org.junit.Test;
import org.sonar.api.batch.SensorContext;
import java.io.File;
import static org.mockito.Mockito.mock;
/**
* @author Evgeny Mandrikov
*/
public class JaCoCoSensorTest {
private JaCoCoSensor sensor;
@Before
public void setUp() {
sensor = new JaCoCoSensor(null);
}
@Test
public void testReadExecutionData() throws Exception {
File jacocoExecutionData = new File(
- getClass().getResource("/org/sonar/plugins/jacoco/JaCoCoSensorNewTest/jacoco.exec").getFile()
+ getClass().getResource("/org/sonar/plugins/jacoco/JaCoCoSensorTest/jacoco.exec").getFile()
);
File buildOutputDir = jacocoExecutionData.getParentFile();
SensorContext context = mock(SensorContext.class);
sensor.readExecutionData(jacocoExecutionData, buildOutputDir, context);
}
}
| true | true | public void testReadExecutionData() throws Exception {
File jacocoExecutionData = new File(
getClass().getResource("/org/sonar/plugins/jacoco/JaCoCoSensorNewTest/jacoco.exec").getFile()
);
File buildOutputDir = jacocoExecutionData.getParentFile();
SensorContext context = mock(SensorContext.class);
sensor.readExecutionData(jacocoExecutionData, buildOutputDir, context);
}
| public void testReadExecutionData() throws Exception {
File jacocoExecutionData = new File(
getClass().getResource("/org/sonar/plugins/jacoco/JaCoCoSensorTest/jacoco.exec").getFile()
);
File buildOutputDir = jacocoExecutionData.getParentFile();
SensorContext context = mock(SensorContext.class);
sensor.readExecutionData(jacocoExecutionData, buildOutputDir, context);
}
|
diff --git a/src/com/android/launcher/Workspace.java b/src/com/android/launcher/Workspace.java
index a1b9f50..54d088f 100644
--- a/src/com/android/launcher/Workspace.java
+++ b/src/com/android/launcher/Workspace.java
@@ -1,1806 +1,1806 @@
/*
* Copyright (C) 2008 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.launcher;
import android.app.Activity;
import android.app.WallpaperManager;
import android.appwidget.AppWidgetHostView;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.animation.BounceInterpolator;
import android.widget.TextView;
import java.util.ArrayList;
import mobi.intuitit.android.widget.WidgetCellLayout;
import mobi.intuitit.android.widget.WidgetSpace;
import org.metalev.multitouch.controller.MultiTouchController;
import org.metalev.multitouch.controller.MultiTouchController.MultiTouchObjectCanvas;
import org.metalev.multitouch.controller.MultiTouchController.PointInfo;
import org.metalev.multitouch.controller.MultiTouchController.PositionAndScale;
/**
* The workspace is a wide area with a wallpaper and a finite number of screens. Each
* screen contains a number of icons, folders or widgets the user can interact with.
* A workspace is meant to be used with a fixed width only.
*/
public class Workspace extends WidgetSpace implements DropTarget, DragSource, DragScroller, MultiTouchObjectCanvas<Object> {
private static final int INVALID_SCREEN = -1;
/**
* The velocity at which a fling gesture will cause us to snap to the next screen
*/
private static final int SNAP_VELOCITY = 500;
private int mDefaultScreen;
private final WallpaperManager mWallpaperManager;
private boolean mFirstLayout = true;
//private int mCurrentScreen;
private int mNextScreen = INVALID_SCREEN;
private CustomScroller mScroller;
private VelocityTracker mVelocityTracker;
/**
* CellInfo for the cell that is currently being dragged
*/
private CellLayout.CellInfo mDragInfo;
/**
* Target drop area calculated during last acceptDrop call.
*/
private int[] mTargetCell = null;
private float mLastMotionX;
private float mLastMotionY;
private final static int TOUCH_STATE_REST = 0;
private final static int TOUCH_STATE_SCROLLING = 1;
private final static int TOUCH_SWIPE_DOWN_GESTURE = 2;
private final static int TOUCH_SWIPE_UP_GESTURE = 3;
private int mTouchState = TOUCH_STATE_REST;
private OnLongClickListener mLongClickListener;
private Launcher mLauncher;
private DragController mDragger;
/**
* Cache of vacant cells, used during drag events and invalidated as needed.
*/
private CellLayout.CellInfo mVacantCache = null;
private int[] mTempCell = new int[2];
private int[] mTempEstimate = new int[2];
//private boolean mAllowLongPress;
private boolean mLocked;
private int mTouchSlop;
private int mMaximumVelocity;
final Rect mDrawerBounds = new Rect();
final Rect mClipBounds = new Rect();
int mDrawerContentHeight;
int mDrawerContentWidth;
//ADW: Dots Indicators
private Drawable mPreviousIndicator;
private Drawable mNextIndicator;
//rogro82@xda
int mHomeScreens = 0;
int mHomeScreensLoaded = 0;
//ADW: port from donut wallpaper drawing
private Paint mPaint;
//private Bitmap mWallpaper;
private int mWallpaperWidth;
private int mWallpaperHeight;
private float mWallpaperOffset;
private boolean mWallpaperLoaded;
private boolean lwpSupport=true;
private boolean wallpaperHack=true;
private BitmapDrawable mWallpaperDrawable;
//ADW: speed for desktop transitions
private int mScrollingSpeed=600;
//ADW: bounce scroll
private int mScrollingBounce=50;
//ADW: sense zoom constants
private static final int SENSE_OPENING = 1;
private static final int SENSE_CLOSING = 2;
private static final int SENSE_OPEN = 3;
private static final int SENSE_CLOSED = 4;
//ADW: sense zoom variables
private boolean mSensemode=false;
private boolean isAnimating=false;
private long startTime;
private int mStatus=SENSE_CLOSED;
private int mAnimationDuration=400;
private int[][] distro={{1},{2},{1,2},{2,2},{2,1,2},{2,2,2},{2,3,2}};
private int maxPreviewWidth;
private int maxPreviewHeight;
//Wysie: Multitouch controller
private MultiTouchController<Object> multiTouchController;
// Wysie: Values taken from CyanogenMod (Donut era) Browser
private static final double ZOOM_SENSITIVITY = 1.6;
private static final double ZOOM_LOG_BASE_INV = 1.0 / Math.log(2.0 / ZOOM_SENSITIVITY);
//ADW: we don't need bouncing while using the previews
private boolean mRevertInterpolatorOnScrollFinish=false;
//ADW: custom desktop rows/columns
private int mDesktopRows;
private int mDesktopColumns;
//ADW: use drawing cache while scrolling, etc.
//Seems a lot of users with "high end" devices, like to have tons of widgets (the bigger, the better)
//On those devices, a drawing cache of a 4x4widget can be really big
//cause of their screen sizes, so the bitmaps are... huge...
//And as those devices can perform pretty well without cache... let's add an option... one more...
private boolean mDesktopCache=true;
private boolean mTouchedScrollableWidget = false;
/**
* Used to inflate the Workspace from XML.
*
* @param context The application's context.
* @param attrs The attribtues set containing the Workspace's customization values.
*/
public Workspace(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
/**
* Used to inflate the Workspace from XML.
*
* @param context The application's context.
* @param attrs The attribtues set containing the Workspace's customization values.
* @param defStyle Unused.
*/
public Workspace(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mWallpaperManager = WallpaperManager.getInstance(context);
/* Rogro82@xda Extended : Load the default and number of homescreens from the settings database */
mHomeScreens = AlmostNexusSettingsHelper.getDesktopScreens(context);
mDefaultScreen = AlmostNexusSettingsHelper.getDefaultScreen(context);
if(mDefaultScreen>mHomeScreens-1) mDefaultScreen=0;
initWorkspace();
}
/**
* Initializes various states for this workspace.
*/
private void initWorkspace() {
mScroller = new CustomScroller(getContext(), new ElasticInterpolator(5f));
mCurrentScreen = mDefaultScreen;
Launcher.setScreen(mCurrentScreen);
mPaint=new Paint();
mPaint.setDither(false);
final ViewConfiguration configuration = ViewConfiguration.get(getContext());
mTouchSlop = configuration.getScaledTouchSlop();
mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
//Wysie: Use MultiTouchController only for multitouch events
multiTouchController = new MultiTouchController<Object>(this, false);
mDesktopRows=AlmostNexusSettingsHelper.getDesktopRows(getContext());
mDesktopColumns=AlmostNexusSettingsHelper.getDesktopColumns(getContext());
mDesktopCache=AlmostNexusSettingsHelper.getDesktopCache(getContext());
}
@Override
public void addView(View child, int index, LayoutParams params) {
if (!(child instanceof CellLayout)) {
throw new IllegalArgumentException("A Workspace can only have CellLayout children.");
}
/* Rogro82@xda Extended : Only load the number of home screens set */
if(mHomeScreensLoaded < mHomeScreens){
mHomeScreensLoaded++;
super.addView(child, index, params);
}
}
@Override
public void addView(View child) {
if (!(child instanceof CellLayout)) {
throw new IllegalArgumentException("A Workspace can only have CellLayout children.");
}
super.addView(child);
}
@Override
public void addView(View child, int index) {
if (!(child instanceof CellLayout)) {
throw new IllegalArgumentException("A Workspace can only have CellLayout children.");
}
super.addView(child, index);
}
@Override
public void addView(View child, int width, int height) {
if (!(child instanceof CellLayout)) {
throw new IllegalArgumentException("A Workspace can only have CellLayout children.");
}
super.addView(child, width, height);
}
@Override
public void addView(View child, LayoutParams params) {
if (!(child instanceof CellLayout)) {
throw new IllegalArgumentException("A Workspace can only have CellLayout children.");
}
super.addView(child, params);
}
/**
* @return The open folder on the current screen, or null if there is none
*/
Folder getOpenFolder() {
CellLayout currentScreen = (CellLayout) getChildAt(mCurrentScreen);
int count = currentScreen.getChildCount();
for (int i = 0; i < count; i++) {
View child = currentScreen.getChildAt(i);
CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams();
if (lp.cellHSpan == mDesktopColumns && lp.cellVSpan == mDesktopRows && child instanceof Folder) {
return (Folder) child;
}
}
return null;
}
ArrayList<Folder> getOpenFolders() {
final int screens = getChildCount();
ArrayList<Folder> folders = new ArrayList<Folder>(screens);
for (int screen = 0; screen < screens; screen++) {
CellLayout currentScreen = (CellLayout) getChildAt(screen);
int count = currentScreen.getChildCount();
for (int i = 0; i < count; i++) {
View child = currentScreen.getChildAt(i);
CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams();
if (lp.cellHSpan == mDesktopColumns && lp.cellVSpan == mDesktopRows && child instanceof Folder) {
folders.add((Folder) child);
break;
}
}
}
return folders;
}
boolean isDefaultScreenShowing() {
return mCurrentScreen == mDefaultScreen;
}
/**
* Returns the index of the currently displayed screen.
*
* @return The index of the currently displayed screen.
*/
int getCurrentScreen() {
return mCurrentScreen;
}
/**
* Sets the current screen.
*
* @param currentScreen
*/
void setCurrentScreen(int currentScreen) {
clearVacantCache();
mCurrentScreen = Math.max(0, Math.min(currentScreen, getChildCount() - 1));
scrollTo(mCurrentScreen * getWidth(), 0);
//ADW: dots
indicatorLevels(mCurrentScreen);
invalidate();
}
/**
* Adds the specified child in the current screen. The position and dimension of
* the child are defined by x, y, spanX and spanY.
*
* @param child The child to add in one of the workspace's screens.
* @param x The X position of the child in the screen's grid.
* @param y The Y position of the child in the screen's grid.
* @param spanX The number of cells spanned horizontally by the child.
* @param spanY The number of cells spanned vertically by the child.
*/
void addInCurrentScreen(View child, int x, int y, int spanX, int spanY) {
addInScreen(child, mCurrentScreen, x, y, spanX, spanY, false);
}
/**
* Adds the specified child in the current screen. The position and dimension of
* the child are defined by x, y, spanX and spanY.
*
* @param child The child to add in one of the workspace's screens.
* @param x The X position of the child in the screen's grid.
* @param y The Y position of the child in the screen's grid.
* @param spanX The number of cells spanned horizontally by the child.
* @param spanY The number of cells spanned vertically by the child.
* @param insert When true, the child is inserted at the beginning of the children list.
*/
void addInCurrentScreen(View child, int x, int y, int spanX, int spanY, boolean insert) {
addInScreen(child, mCurrentScreen, x, y, spanX, spanY, insert);
}
/**
* Adds the specified child in the specified screen. The position and dimension of
* the child are defined by x, y, spanX and spanY.
*
* @param child The child to add in one of the workspace's screens.
* @param screen The screen in which to add the child.
* @param x The X position of the child in the screen's grid.
* @param y The Y position of the child in the screen's grid.
* @param spanX The number of cells spanned horizontally by the child.
* @param spanY The number of cells spanned vertically by the child.
*/
void addInScreen(View child, int screen, int x, int y, int spanX, int spanY) {
addInScreen(child, screen, x, y, spanX, spanY, false);
}
/**
* Adds the specified child in the specified screen. The position and dimension of
* the child are defined by x, y, spanX and spanY.
*
* @param child The child to add in one of the workspace's screens.
* @param screen The screen in which to add the child.
* @param x The X position of the child in the screen's grid.
* @param y The Y position of the child in the screen's grid.
* @param spanX The number of cells spanned horizontally by the child.
* @param spanY The number of cells spanned vertically by the child.
* @param insert When true, the child is inserted at the beginning of the children list.
*/
void addInScreen(View child, int screen, int x, int y, int spanX, int spanY, boolean insert) {
if (screen < 0 || screen >= getChildCount()) {
/* Rogro82@xda Extended : Do not throw an exception else it will crash when there is an item on a hidden homescreen */
return;
//throw new IllegalStateException("The screen must be >= 0 and < " + getChildCount());
}
//ADW: we cannot accept an item from a position greater that current desktop columns/rows
if(x>=mDesktopColumns || y>=mDesktopRows){
return;
}
clearVacantCache();
final CellLayout group = (CellLayout) getChildAt(screen);
CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams();
if (lp == null) {
lp = new CellLayout.LayoutParams(x, y, spanX, spanY);
} else {
lp.cellX = x;
lp.cellY = y;
lp.cellHSpan = spanX;
lp.cellVSpan = spanY;
}
group.addView(child, insert ? 0 : -1, lp);
if (!(child instanceof Folder)) {
child.setOnLongClickListener(mLongClickListener);
}
}
void addWidget(View view, Widget widget, boolean insert) {
addInScreen(view, widget.screen, widget.cellX, widget.cellY, widget.spanX,
widget.spanY, insert);
}
CellLayout.CellInfo findAllVacantCells(boolean[] occupied) {
CellLayout group = (CellLayout) getChildAt(mCurrentScreen);
if (group != null) {
return group.findAllVacantCells(occupied, null);
}
return null;
}
CellLayout.CellInfo findAllVacantCellsFromModel() {
CellLayout group = (CellLayout) getChildAt(mCurrentScreen);
if (group != null) {
int countX = group.getCountX();
int countY = group.getCountY();
boolean occupied[][] = new boolean[countX][countY];
Launcher.getModel().findAllOccupiedCells(occupied, countX, countY, mCurrentScreen);
return group.findAllVacantCellsFromOccupied(occupied, countX, countY);
}
return null;
}
private void clearVacantCache() {
if (mVacantCache != null) {
mVacantCache.clearVacantCells();
mVacantCache = null;
}
}
/**
* Registers the specified listener on each screen contained in this workspace.
*
* @param l The listener used to respond to long clicks.
*/
@Override
public void setOnLongClickListener(OnLongClickListener l) {
mLongClickListener = l;
final int count = getChildCount();
for (int i = 0; i < count; i++) {
getChildAt(i).setOnLongClickListener(l);
}
}
private void updateWallpaperOffset() {
updateWallpaperOffset(getChildAt(getChildCount() - 1).getRight() - (mRight - mLeft));
}
private void updateWallpaperOffset(int scrollRange) {
//ADW: we set a condition to not move wallpaper beyond the "bounce" zone
if(getScrollX()>0 && getScrollX()<getChildAt(getChildCount() - 1).getLeft()){
mWallpaperManager.setWallpaperOffsetSteps(1.0f / (getChildCount() - 1), 0 );
mWallpaperManager.setWallpaperOffsets(getWindowToken(), mScrollX / (float) scrollRange, 0);
}
}
@Override
public void computeScroll() {
if (mScroller.computeScrollOffset()) {
scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
if(lwpSupport)updateWallpaperOffset();
if(mLauncher.getDesktopIndicator()!=null)mLauncher.getDesktopIndicator().indicate((float)mScroller.getCurrX()/(float)(getChildCount()*getWidth()));
postInvalidate();
} else if (mNextScreen != INVALID_SCREEN) {
int lastScreen = mCurrentScreen;
mCurrentScreen = Math.max(0, Math.min(mNextScreen, getChildCount() - 1));
//ADW: dots
//indicatorLevels(mCurrentScreen);
Launcher.setScreen(mCurrentScreen);
mNextScreen = INVALID_SCREEN;
clearChildrenCache();
if(mLauncher.getDesktopIndicator()!=null)mLauncher.getDesktopIndicator().fullIndicate(mCurrentScreen);
//ADW: Revert back the interpolator when needed
if(mRevertInterpolatorOnScrollFinish)setBounceAmount(mScrollingBounce);
//ADW: use intuit code to allow extended widgets
// notify widget about screen changed
//REMOVED, seems its used for animated widgets, we don't need that yet :P
/*if(mLauncher.isScrollableAllowed()){
View changedView;
if (lastScreen != mCurrentScreen) {
changedView = getChildAt(lastScreen); // A screen get out
if (changedView instanceof WidgetCellLayout)
((WidgetCellLayout) changedView).onViewportOut();
}
changedView = getChildAt(mCurrentScreen); // A screen get in
if (changedView instanceof WidgetCellLayout)
((WidgetCellLayout) changedView).onViewportIn();
}*/
}
}
@Override
public boolean isOpaque() {
//ADW: hack to use old rendering
if(!lwpSupport && mWallpaperLoaded){
//return !mWallpaper.hasAlpha();
return mWallpaperDrawable.getOpacity()==PixelFormat.OPAQUE;
}else{
return false;
}
}
@Override
protected void dispatchDraw(Canvas canvas) {
boolean restore = false;
//ADW: If using old wallpaper rendering method...
if(!lwpSupport && mWallpaperDrawable!=null){
float x = getScrollX() * mWallpaperOffset;
if (x + mWallpaperWidth < getRight() - getLeft()) {
x = getRight() - getLeft() - mWallpaperWidth;
}
//ADW: added tweaks for when scrolling "beyond bounce limits" :P
if (mScrollX<0)x=mScrollX;
if(mScrollX>getChildAt(getChildCount() - 1).getRight() - (mRight - mLeft)){
x=(mScrollX-mWallpaperWidth+(mRight-mLeft));
}
if(getChildCount()==1)x=getScrollX();
canvas.drawBitmap(mWallpaperDrawable.getBitmap(), x, (getBottom() - mWallpaperHeight) / 2, mPaint);
}
if(!mSensemode){
// If the all apps drawer is open and the drawing region for the workspace
// is contained within the drawer's bounds, we skip the drawing. This requires
// the drawer to be fully opaque.
if((mLauncher.isAllAppsVisible()) || mLauncher.isFullScreenPreviewing()){
return;
}
// ViewGroup.dispatchDraw() supports many features we don't need:
// clip to padding, layout animation, animation listener, disappearing
// children, etc. The following implementation attempts to fast-track
// the drawing dispatch by drawing only what we know needs to be drawn.
boolean fastDraw = mTouchState != TOUCH_STATE_SCROLLING && mNextScreen == INVALID_SCREEN;
// If we are not scrolling or flinging, draw only the current screen
if (fastDraw) {
drawChild(canvas, getChildAt(mCurrentScreen), getDrawingTime());
} else {
final long drawingTime = getDrawingTime();
// If we are flinging, draw only the current screen and the target screen
if (mNextScreen >= 0 && mNextScreen < getChildCount() &&
Math.abs(mCurrentScreen - mNextScreen) == 1) {
drawChild(canvas, getChildAt(mCurrentScreen), drawingTime);
drawChild(canvas, getChildAt(mNextScreen), drawingTime);
} else {
// If we are scrolling, draw all of our children
final int count = getChildCount();
for (int i = 0; i < count; i++) {
drawChild(canvas, getChildAt(i), drawingTime);
}
}
}
}else{
long currentTime;
if(startTime==0){
startTime=SystemClock.uptimeMillis();
currentTime=0;
}else{
currentTime=SystemClock.uptimeMillis()-startTime;
}
if(currentTime>=mAnimationDuration){
isAnimating=false;
if(mStatus==SENSE_OPENING){
mStatus=SENSE_OPEN;
}else if(mStatus==SENSE_CLOSING){
mStatus=SENSE_CLOSED;
mSensemode=false;
unlock();
postInvalidate();
}
}else{
postInvalidate();
}
final int count = getChildCount();
for (int i = 0; i < count; i++) {
drawChild(canvas, getChildAt(i), getDrawingTime());
}
}
if (restore) {
canvas.restore();
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
final int width = MeasureSpec.getSize(widthMeasureSpec);
final int widthMode = MeasureSpec.getMode(widthMeasureSpec);
if (widthMode != MeasureSpec.EXACTLY) {
throw new IllegalStateException("Workspace can only be used in EXACTLY mode.");
}
final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
if (heightMode != MeasureSpec.EXACTLY) {
throw new IllegalStateException("Workspace can only be used in EXACTLY mode.");
}
// The children are given the same width and height as the workspace
final int count = getChildCount();
for (int i = 0; i < count; i++) {
getChildAt(i).measure(widthMeasureSpec, heightMeasureSpec);
}
//ADW: measure wallpaper when using old rendering
if(!lwpSupport){
if (mWallpaperLoaded) {
mWallpaperLoaded = false;
mWallpaperWidth = mWallpaperDrawable.getIntrinsicWidth();
mWallpaperHeight = mWallpaperDrawable.getIntrinsicHeight();
}
final int wallpaperWidth = mWallpaperWidth;
mWallpaperOffset = wallpaperWidth > width ? (count * width - wallpaperWidth) /
((count - 1) * (float) width) : 1.0f;
}
if (mFirstLayout) {
scrollTo(mCurrentScreen * width, 0);
mScroller.startScroll(0, 0, mCurrentScreen * width, 0, 0);
if(lwpSupport)updateWallpaperOffset(width * (getChildCount() - 1));
mFirstLayout = false;
}
int max = 3;
int aW = getMeasuredWidth();
float w = aW / max;
maxPreviewWidth=(int) w;
maxPreviewHeight=(int) (getMeasuredHeight()*(w/getMeasuredWidth()));
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
int childLeft = 0;
final int count = getChildCount();
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (child.getVisibility() != View.GONE) {
final int childWidth = child.getMeasuredWidth();
child.layout(childLeft, 0, childLeft + childWidth, child.getMeasuredHeight());
childLeft += childWidth;
}
}
//ADW:updateWallpaperoffset
if(lwpSupport)updateWallpaperOffset();
}
@Override
public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
int screen = indexOfChild(child);
if (screen != mCurrentScreen || !mScroller.isFinished()) {
if (!mLauncher.isWorkspaceLocked()) {
snapToScreen(screen);
}
return true;
}
return false;
}
@Override
protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
if(!mLauncher.isAllAppsVisible()){
final Folder openFolder = getOpenFolder();
if (openFolder != null) {
return openFolder.requestFocus(direction, previouslyFocusedRect);
} else {
int focusableScreen;
if (mNextScreen != INVALID_SCREEN) {
focusableScreen = mNextScreen;
} else {
focusableScreen = mCurrentScreen;
}
getChildAt(focusableScreen).requestFocus(direction, previouslyFocusedRect);
}
}
return false;
}
@Override
public boolean dispatchUnhandledMove(View focused, int direction) {
if (direction == View.FOCUS_LEFT) {
if (getCurrentScreen() > 0) {
snapToScreen(getCurrentScreen() - 1);
return true;
}
} else if (direction == View.FOCUS_RIGHT) {
if (getCurrentScreen() < getChildCount() - 1) {
snapToScreen(getCurrentScreen() + 1);
return true;
}
}
return super.dispatchUnhandledMove(focused, direction);
}
@Override
public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
if (!mLauncher.isAllAppsVisible()) {
final Folder openFolder = getOpenFolder();
if (openFolder == null) {
getChildAt(mCurrentScreen).addFocusables(views, direction);
if (direction == View.FOCUS_LEFT) {
if (mCurrentScreen > 0) {
getChildAt(mCurrentScreen - 1).addFocusables(views, direction);
}
} else if (direction == View.FOCUS_RIGHT){
if (mCurrentScreen < getChildCount() - 1) {
getChildAt(mCurrentScreen + 1).addFocusables(views, direction);
}
}
} else {
openFolder.addFocusables(views, direction);
}
}
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
if(mStatus==SENSE_OPEN){
if(ev.getAction()==MotionEvent.ACTION_DOWN){
findClickedPreview(ev.getX(),ev.getY());
}
return true;
}
//Wysie: If multitouch event is detected
if (multiTouchController.onTouchEvent(ev)) {
return false;
}
if (mLocked || mLauncher.isAllAppsVisible()) {
return true;
}
/*
* This method JUST determines whether we want to intercept the motion.
* If we return true, onTouchEvent will be called and we do the actual
* scrolling there.
*/
/*
* Shortcut the most recurring case: the user is in the dragging
* state and he is moving his finger. We want to intercept this
* motion.
*/
final int action = ev.getAction();
if ((action == MotionEvent.ACTION_MOVE) && (mTouchState != TOUCH_STATE_REST)) {
return true;
}
final float x = ev.getX();
final float y = ev.getY();
switch (action) {
case MotionEvent.ACTION_MOVE:
/*
* mIsBeingDragged == false, otherwise the shortcut would have caught it. Check
* whether the user has moved far enough from his original down touch.
*/
/*
* Locally do absolute value. mLastMotionX is set to the y value
* of the down event.
*/
final int xDiff = (int) Math.abs(x - mLastMotionX);
final int yDiff = (int) Math.abs(y - mLastMotionY);
final int touchSlop = mTouchSlop;
boolean xMoved = xDiff > touchSlop;
boolean yMoved = yDiff > touchSlop;
if (xMoved || yMoved) {
if (xMoved) {
// Scroll if the user moved far enough along the X axis
mTouchState = TOUCH_STATE_SCROLLING;
enableChildrenCache();
- } else if (yMoved)
+ } else if (yMoved && getOpenFolder()==null)
{
// As x scrolling is left untouched, every gesture should start by dragging in Y axis. In fact I only consider useful, swipe up and down.
// Guess if the first Pointer where the user click belongs to where a scrollable widget is.
mTouchedScrollableWidget = isWidgetAtLocationScrollable((int)mLastMotionX,(int)mLastMotionY);
if (!mTouchedScrollableWidget)
{
// Only y axis movement. So may be a Swipe down or up gesture
if ((y - mLastMotionY) > 0)
mTouchState = TOUCH_SWIPE_DOWN_GESTURE;
else
{
mTouchState = TOUCH_SWIPE_UP_GESTURE;
}
}
}
// Either way, cancel any pending longpress
if (mAllowLongPress) {
mAllowLongPress = false;
// Try canceling the long press. It could also have been scheduled
// by a distant descendant, so use the mAllowLongPress flag to block
// everything
final View currentScreen = getChildAt(mCurrentScreen);
currentScreen.cancelLongPress();
}
}
break;
case MotionEvent.ACTION_DOWN:
// Remember location of down touch
mLastMotionX = x;
mLastMotionY = y;
mAllowLongPress = true;
/*
* If being flinged and user touches the screen, initiate drag;
* otherwise don't. mScroller.isFinished should be false when
* being flinged.
*/
mTouchState = mScroller.isFinished() ? TOUCH_STATE_REST : TOUCH_STATE_SCROLLING;
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
if (mTouchState != TOUCH_STATE_SCROLLING && mTouchState != TOUCH_SWIPE_DOWN_GESTURE && mTouchState != TOUCH_SWIPE_UP_GESTURE) {
final CellLayout currentScreen = (CellLayout) getChildAt(mCurrentScreen);
if (!currentScreen.lastDownOnOccupiedCell()) {
getLocationOnScreen(mTempCell);
// Send a tap to the wallpaper if the last down was on empty space
if(lwpSupport)
mWallpaperManager.sendWallpaperCommand(getWindowToken(),
"android.wallpaper.tap",
mTempCell[0] + (int) ev.getX(),
mTempCell[1] + (int) ev.getY(), 0, null);
}
}
// Release the drag
clearChildrenCache();
mTouchState = TOUCH_STATE_REST;
mAllowLongPress = false;
break;
}
/*
* The only time we want to intercept motion events is if we are in the
* drag mode.
*/
return mTouchState != TOUCH_STATE_REST;
}
private boolean isWidgetAtLocationScrollable(int x, int y) {
// will return true if widget at this position is scrollable.
// Get current screen from the whole desktop
CellLayout currentScreen = (CellLayout) getChildAt(mCurrentScreen);
int[] cell_xy = new int[2];
// Get the cell where the user started the touch event
currentScreen.pointToCellExact(x, y, cell_xy);
int count = currentScreen.getChildCount();
// Iterate to find which widget is located at that cell
// Find widget backwards from a cell does not work with (View)currentScreen.getChildAt(cell_xy[0]*currentScreen.getCountX etc etc); As the widget is positioned at the very first cell of the widgetspace
for (int i = 0; i < count; i++) {
View child = (View)currentScreen.getChildAt(i);
if ( child !=null)
{
// Get Layount graphical info about this widget
CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams();
// Calculate Cell Margins
int left_cellmargin = lp.cellX;
int rigth_cellmargin = lp.cellX+lp.cellHSpan;
int top_cellmargin = lp.cellY;
int botton_cellmargin = lp.cellY + lp.cellVSpan;
// See if the cell where we touched is inside the Layout of the widget beeing analized
if (cell_xy[0] >= left_cellmargin && cell_xy[0] < rigth_cellmargin && cell_xy[1] >= top_cellmargin && cell_xy[1] < botton_cellmargin) {
try {
// Get Widget ID
int id = ((AppWidgetHostView)child).getAppWidgetId();
// Ask to WidgetSpace if the Widget identified itself when created as 'Scrollable'
return isWidgetScrollable(id);
} catch (Exception e)
{}
}
}
}
return false;
}
void enableChildrenCache() {
if(mDesktopCache){
final int count = getChildCount();
for (int i = 0; i < count; i++) {
//ADW: create cache only for current screen/previous/next.
if(i>=mCurrentScreen-1 || i<=mCurrentScreen+1){
final CellLayout layout = (CellLayout) getChildAt(i);
layout.setChildrenDrawnWithCacheEnabled(true);
layout.setChildrenDrawingCacheEnabled(true);
}
}
}
}
void clearChildrenCache() {
if(mDesktopCache){
final int count = getChildCount();
for (int i = 0; i < count; i++) {
final CellLayout layout = (CellLayout) getChildAt(i);
layout.setChildrenDrawnWithCacheEnabled(false);
}
}
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
//Wysie: If multitouch event is detected
/*if (multiTouchController.onTouchEvent(ev)) {
return false;
}*/
if (mLocked || mLauncher.isAllAppsVisible() || mSensemode) {
return true;
}
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain();
}
mVelocityTracker.addMovement(ev);
final int action = ev.getAction();
final float x = ev.getX();
switch (action) {
case MotionEvent.ACTION_DOWN:
/*
* If being flinged and user touches, stop the fling. isFinished
* will be false if being flinged.
*/
if (!mScroller.isFinished()) {
mScroller.abortAnimation();
}
// Remember where the motion event started
mLastMotionX = x;
break;
case MotionEvent.ACTION_MOVE:
if (mTouchState == TOUCH_STATE_SCROLLING) {
// Scroll to follow the motion event
final int deltaX = (int) (mLastMotionX - x);
mLastMotionX = x;
if (deltaX < 0) {
if (mScrollX > -mScrollingBounce) {
scrollBy(Math.min(deltaX,mScrollingBounce), 0);
if(lwpSupport)updateWallpaperOffset();
if(mLauncher.getDesktopIndicator()!=null)mLauncher.getDesktopIndicator().indicate((float)getScrollX()/(float)(getChildCount()*getWidth()));
}
} else if (deltaX > 0) {
final int availableToScroll = getChildAt(getChildCount() - 1).getRight() -
mScrollX - getWidth()+mScrollingBounce;
if (availableToScroll > 0) {
scrollBy(deltaX, 0);
if(lwpSupport)updateWallpaperOffset();
if(mLauncher.getDesktopIndicator()!=null)mLauncher.getDesktopIndicator().indicate((float)getScrollX()/(float)(getChildCount()*getWidth()));
}
}
}
break;
case MotionEvent.ACTION_UP:
if (mTouchState == TOUCH_STATE_SCROLLING) {
final VelocityTracker velocityTracker = mVelocityTracker;
velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
int velocityX = (int) velocityTracker.getXVelocity();
if (velocityX > SNAP_VELOCITY && mCurrentScreen > 0) {
// Fling hard enough to move left
snapToScreen(mCurrentScreen - 1);
} else if (velocityX < -SNAP_VELOCITY && mCurrentScreen < getChildCount() - 1) {
// Fling hard enough to move right
snapToScreen(mCurrentScreen + 1);
} else {
snapToDestination();
}
if (mVelocityTracker != null) {
mVelocityTracker.recycle();
mVelocityTracker = null;
}
} else if (mTouchState == TOUCH_SWIPE_DOWN_GESTURE )
{
mLauncher.fireSwipeDownAction();
} else if (mTouchState == TOUCH_SWIPE_UP_GESTURE )
{
mLauncher.fireSwipeUpAction();
}
mTouchState = TOUCH_STATE_REST;
break;
case MotionEvent.ACTION_CANCEL:
mTouchState = TOUCH_STATE_REST;
}
return true;
}
private void snapToDestination() {
final int screenWidth = getWidth();
final int whichScreen = (mScrollX + (screenWidth / 2)) / screenWidth;
snapToScreen(whichScreen);
}
void snapToScreen(int whichScreen) {
//if (!mScroller.isFinished()) return;
clearVacantCache();
enableChildrenCache();
whichScreen = Math.max(0, Math.min(whichScreen, getChildCount() - 1));
boolean changingScreens = whichScreen != mCurrentScreen;
mNextScreen = whichScreen;
//ADW: dots
indicatorLevels(mNextScreen);
View focusedChild = getFocusedChild();
if (focusedChild != null && changingScreens && focusedChild == getChildAt(mCurrentScreen)) {
focusedChild.clearFocus();
}
final int screenDelta = Math.abs(whichScreen - mCurrentScreen);
int durationOffset = 1;
// Faruq: Added to allow easing even when Screen doesn't changed (when revert happens)
//Log.d("Workspace", "whichScreen: "+whichScreen+"; mCurrentScreen: "+mCurrentScreen+"; getChildCount: "+(getChildCount()-1));
if (screenDelta == 0) {
durationOffset = 400;
//Log.d("Workspace", "Increasing duration by "+durationOffset+" times");
}
final int duration = mScrollingSpeed + durationOffset;
final int newX = whichScreen * getWidth();
final int delta = newX - mScrollX;
//mScroller.startScroll(mScrollX, 0, delta, 0, Math.abs(delta) * 2);
if(!mSensemode)
mScroller.startScroll(getScrollX(), 0, delta, 0, duration);
else
mScroller.startScroll(getScrollX(), 0, delta, 0, mAnimationDuration);
invalidate();
}
void startDrag(CellLayout.CellInfo cellInfo) {
View child = cellInfo.cell;
// Make sure the drag was started by a long press as opposed to a long click.
// Note that Search takes focus when clicked rather than entering touch mode
if (!child.isInTouchMode() && !(child instanceof Search)) {
return;
}
mDragInfo = cellInfo;
mDragInfo.screen = mCurrentScreen;
CellLayout current = ((CellLayout) getChildAt(mCurrentScreen));
current.onDragChild(child);
mDragger.startDrag(child, this, child.getTag(), DragController.DRAG_ACTION_MOVE);
invalidate();
}
@Override
protected Parcelable onSaveInstanceState() {
final SavedState state = new SavedState(super.onSaveInstanceState());
state.currentScreen = mCurrentScreen;
return state;
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
try{
SavedState savedState = (SavedState) state;
super.onRestoreInstanceState(savedState.getSuperState());
if (savedState.currentScreen != -1) {
mCurrentScreen = savedState.currentScreen;
Launcher.setScreen(mCurrentScreen);
}
}catch (Exception e) {
// TODO ADW: Weird bug http://code.google.com/p/android/issues/detail?id=3981
//Should be completely fixed on eclair
super.onRestoreInstanceState(null);
Log.d("WORKSPACE","Google bug http://code.google.com/p/android/issues/detail?id=3981 found, bypassing...");
}
}
void addApplicationShortcut(ApplicationInfo info, CellLayout.CellInfo cellInfo,
boolean insertAtFirst) {
final CellLayout layout = (CellLayout) getChildAt(cellInfo.screen);
final int[] result = new int[2];
layout.cellToPoint(cellInfo.cellX, cellInfo.cellY, result);
onDropExternal(result[0], result[1], info, layout, insertAtFirst);
}
public void onDrop(DragSource source, int x, int y, int xOffset, int yOffset, Object dragInfo) {
final CellLayout cellLayout = getCurrentDropLayout();
if (source != this) {
onDropExternal(x - xOffset, y - yOffset, dragInfo, cellLayout);
} else {
// Move internally
if (mDragInfo != null) {
final View cell = mDragInfo.cell;
int index = mScroller.isFinished() ? mCurrentScreen : mNextScreen;
if (index != mDragInfo.screen) {
final CellLayout originalCellLayout = (CellLayout) getChildAt(mDragInfo.screen);
originalCellLayout.removeView(cell);
cellLayout.addView(cell);
}
mTargetCell = estimateDropCell(x - xOffset, y - yOffset,
mDragInfo.spanX, mDragInfo.spanY, cell, cellLayout, mTargetCell);
cellLayout.onDropChild(cell, mTargetCell);
final ItemInfo info = (ItemInfo)cell.getTag();
CellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams();
LauncherModel.moveItemInDatabase(mLauncher, info,
LauncherSettings.Favorites.CONTAINER_DESKTOP, index, lp.cellX, lp.cellY);
}
}
}
public void onDragEnter(DragSource source, int x, int y, int xOffset, int yOffset,
Object dragInfo) {
clearVacantCache();
}
public void onDragOver(DragSource source, int x, int y, int xOffset, int yOffset,
Object dragInfo) {
}
public void onDragExit(DragSource source, int x, int y, int xOffset, int yOffset,
Object dragInfo) {
clearVacantCache();
}
private void onDropExternal(int x, int y, Object dragInfo, CellLayout cellLayout) {
onDropExternal(x, y, dragInfo, cellLayout, false);
}
private void onDropExternal(int x, int y, Object dragInfo, CellLayout cellLayout,
boolean insertAtFirst) {
// Drag from somewhere else
ItemInfo info = (ItemInfo) dragInfo;
View view;
switch (info.itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
if (info.container == NO_ID) {
// Came from all apps -- make a copy
info = new ApplicationInfo((ApplicationInfo) info);
}
view = mLauncher.createShortcut(R.layout.application, cellLayout,
(ApplicationInfo) info);
break;
case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
view = FolderIcon.fromXml(R.layout.folder_icon, mLauncher,
(ViewGroup) getChildAt(mCurrentScreen), ((UserFolderInfo) info));
break;
default:
throw new IllegalStateException("Unknown item type: " + info.itemType);
}
cellLayout.addView(view, insertAtFirst ? 0 : -1);
view.setOnLongClickListener(mLongClickListener);
mTargetCell = estimateDropCell(x, y, 1, 1, view, cellLayout, mTargetCell);
cellLayout.onDropChild(view, mTargetCell);
CellLayout.LayoutParams lp = (CellLayout.LayoutParams) view.getLayoutParams();
final LauncherModel model = Launcher.getModel();
model.addDesktopItem(info);
LauncherModel.addOrMoveItemInDatabase(mLauncher, info,
LauncherSettings.Favorites.CONTAINER_DESKTOP, mCurrentScreen, lp.cellX, lp.cellY);
}
/**
* Return the current {@link CellLayout}, correctly picking the destination
* screen while a scroll is in progress.
*/
private CellLayout getCurrentDropLayout() {
int index = mScroller.isFinished() ? mCurrentScreen : mNextScreen;
return (CellLayout) getChildAt(index);
}
/**
* {@inheritDoc}
*/
public boolean acceptDrop(DragSource source, int x, int y,
int xOffset, int yOffset, Object dragInfo) {
final CellLayout layout = getCurrentDropLayout();
final CellLayout.CellInfo cellInfo = mDragInfo;
final int spanX = cellInfo == null ? 1 : cellInfo.spanX;
final int spanY = cellInfo == null ? 1 : cellInfo.spanY;
if (mVacantCache == null) {
final View ignoreView = cellInfo == null ? null : cellInfo.cell;
mVacantCache = layout.findAllVacantCells(null, ignoreView);
}
return mVacantCache.findCellForSpan(mTempEstimate, spanX, spanY, false);
}
/**
* {@inheritDoc}
*/
public Rect estimateDropLocation(int x, int y, int xOffset, int yOffset, Rect recycle) {
final CellLayout layout = getCurrentDropLayout();
final CellLayout.CellInfo cellInfo = mDragInfo;
final int spanX = cellInfo == null ? 1 : cellInfo.spanX;
final int spanY = cellInfo == null ? 1 : cellInfo.spanY;
final View ignoreView = cellInfo == null ? null : cellInfo.cell;
final Rect location = recycle != null ? recycle : new Rect();
// Find drop cell and convert into rectangle
int[] dropCell = estimateDropCell(x - xOffset, y - yOffset,
spanX, spanY, ignoreView, layout, mTempCell);
if (dropCell == null) {
return null;
}
layout.cellToPoint(dropCell[0], dropCell[1], mTempEstimate);
location.left = mTempEstimate[0];
location.top = mTempEstimate[1];
layout.cellToPoint(dropCell[0] + spanX, dropCell[1] + spanY, mTempEstimate);
location.right = mTempEstimate[0];
location.bottom = mTempEstimate[1];
return location;
}
/**
* Calculate the nearest cell where the given object would be dropped.
*/
private int[] estimateDropCell(int pixelX, int pixelY,
int spanX, int spanY, View ignoreView, CellLayout layout, int[] recycle) {
// Create vacant cell cache if none exists
if (mVacantCache == null) {
mVacantCache = layout.findAllVacantCells(null, ignoreView);
}
// Find the best target drop location
return layout.findNearestVacantArea(pixelX, pixelY, spanX, spanY, mVacantCache, recycle);
}
void setLauncher(Launcher launcher) {
mLauncher = launcher;
if(mLauncher.isScrollableAllowed())registerProvider();
if(mLauncher.getDesktopIndicator()!=null)mLauncher.getDesktopIndicator().setItems(mHomeScreens);
}
public void setDragger(DragController dragger) {
mDragger = dragger;
}
public void onDropCompleted(View target, boolean success) {
// This is a bit expensive but safe
clearVacantCache();
if (success){
if (target != this && mDragInfo != null) {
final CellLayout cellLayout = (CellLayout) getChildAt(mDragInfo.screen);
cellLayout.removeView(mDragInfo.cell);
final Object tag = mDragInfo.cell.getTag();
Launcher.getModel().removeDesktopItem((ItemInfo) tag);
}
} else {
if (mDragInfo != null) {
final CellLayout cellLayout = (CellLayout) getChildAt(mDragInfo.screen);
cellLayout.onDropAborted(mDragInfo.cell);
}
}
mDragInfo = null;
}
public void scrollLeft() {
clearVacantCache();
if(mNextScreen!=INVALID_SCREEN){
mCurrentScreen=mNextScreen;
mNextScreen=INVALID_SCREEN;
}
if (mNextScreen == INVALID_SCREEN && mCurrentScreen > 0) {
snapToScreen(mCurrentScreen - 1);
}
}
public void scrollRight() {
clearVacantCache();
if(mNextScreen!=INVALID_SCREEN){
mCurrentScreen=mNextScreen;
mNextScreen=INVALID_SCREEN;
}
if (mNextScreen == INVALID_SCREEN && mCurrentScreen < getChildCount() -1) {
snapToScreen(mCurrentScreen + 1);
}
}
public int getScreenForView(View v) {
int result = -1;
if (v != null) {
ViewParent vp = v.getParent();
int count = getChildCount();
for (int i = 0; i < count; i++) {
if (vp == getChildAt(i)) {
return i;
}
}
}
return result;
}
/**
* Find a search widget on the given screen
*/
private Search findSearchWidget(CellLayout screen) {
final int count = screen.getChildCount();
for (int i = 0; i < count; i++) {
View v = screen.getChildAt(i);
if (v instanceof Search) {
return (Search) v;
}
}
return null;
}
/**
* Gets the first search widget on the current screen, if there is one.
* Returns <code>null</code> otherwise.
*/
public Search findSearchWidgetOnCurrentScreen() {
CellLayout currentScreen = (CellLayout)getChildAt(mCurrentScreen);
return findSearchWidget(currentScreen);
}
public Folder getFolderForTag(Object tag) {
int screenCount = getChildCount();
for (int screen = 0; screen < screenCount; screen++) {
CellLayout currentScreen = ((CellLayout) getChildAt(screen));
int count = currentScreen.getChildCount();
for (int i = 0; i < count; i++) {
View child = currentScreen.getChildAt(i);
CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams();
if (lp.cellHSpan == mDesktopColumns && lp.cellVSpan == mDesktopRows && child instanceof Folder) {
Folder f = (Folder) child;
if (f.getInfo() == tag) {
return f;
}
}
}
}
return null;
}
public View getViewForTag(Object tag) {
int screenCount = getChildCount();
for (int screen = 0; screen < screenCount; screen++) {
CellLayout currentScreen = ((CellLayout) getChildAt(screen));
int count = currentScreen.getChildCount();
for (int i = 0; i < count; i++) {
View child = currentScreen.getChildAt(i);
if (child.getTag() == tag) {
return child;
}
}
}
return null;
}
/**
* Unlocks the SlidingDrawer so that touch events are processed.
*
* @see #lock()
*/
public void unlock() {
mLocked = false;
}
/**
* Locks the SlidingDrawer so that touch events are ignores.
*
* @see #unlock()
*/
public void lock() {
mLocked = true;
}
/**
* @return True is long presses are still allowed for the current touch
*/
public boolean allowLongPress() {
return mAllowLongPress;
}
/**
* Set true to allow long-press events to be triggered, usually checked by
* {@link Launcher} to accept or block dpad-initiated long-presses.
*/
public void setAllowLongPress(boolean allowLongPress) {
mAllowLongPress = allowLongPress;
}
void removeShortcutsForPackage(String packageName) {
final ArrayList<View> childrenToRemove = new ArrayList<View>();
final LauncherModel model = Launcher.getModel();
final int count = getChildCount();
for (int i = 0; i < count; i++) {
final CellLayout layout = (CellLayout) getChildAt(i);
int childCount = layout.getChildCount();
childrenToRemove.clear();
for (int j = 0; j < childCount; j++) {
final View view = layout.getChildAt(j);
Object tag = view.getTag();
if (tag instanceof ApplicationInfo) {
final ApplicationInfo info = (ApplicationInfo) tag;
// We need to check for ACTION_MAIN otherwise getComponent() might
// return null for some shortcuts (for instance, for shortcuts to
// web pages.)
final Intent intent = info.intent;
final ComponentName name = intent.getComponent();
if (Intent.ACTION_MAIN.equals(intent.getAction()) &&
name != null && packageName.equals(name.getPackageName())) {
model.removeDesktopItem(info);
LauncherModel.deleteItemFromDatabase(mLauncher, info);
childrenToRemove.add(view);
}
} else if (tag instanceof UserFolderInfo) {
final UserFolderInfo info = (UserFolderInfo) tag;
final ArrayList<ApplicationInfo> contents = info.contents;
final ArrayList<ApplicationInfo> toRemove = new ArrayList<ApplicationInfo>(1);
final int contentsCount = contents.size();
boolean removedFromFolder = false;
for (int k = 0; k < contentsCount; k++) {
final ApplicationInfo appInfo = contents.get(k);
final Intent intent = appInfo.intent;
final ComponentName name = intent.getComponent();
if (Intent.ACTION_MAIN.equals(intent.getAction()) &&
name != null && packageName.equals(name.getPackageName())) {
toRemove.add(appInfo);
LauncherModel.deleteItemFromDatabase(mLauncher, appInfo);
removedFromFolder = true;
}
}
contents.removeAll(toRemove);
if (removedFromFolder) {
final Folder folder = getOpenFolder();
if (folder != null) folder.notifyDataSetChanged();
}
}
}
childCount = childrenToRemove.size();
for (int j = 0; j < childCount; j++) {
layout.removeViewInLayout(childrenToRemove.get(j));
}
if (childCount > 0) {
layout.requestLayout();
layout.invalidate();
}
}
}
void updateShortcutsForPackage(String packageName) {
final int count = getChildCount();
for (int i = 0; i < count; i++) {
final CellLayout layout = (CellLayout) getChildAt(i);
int childCount = layout.getChildCount();
for (int j = 0; j < childCount; j++) {
final View view = layout.getChildAt(j);
Object tag = view.getTag();
if (tag instanceof ApplicationInfo) {
ApplicationInfo info = (ApplicationInfo) tag;
// We need to check for ACTION_MAIN otherwise getComponent() might
// return null for some shortcuts (for instance, for shortcuts to
// web pages.)
final Intent intent = info.intent;
final ComponentName name = intent.getComponent();
if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION &&
Intent.ACTION_MAIN.equals(intent.getAction()) && name != null &&
packageName.equals(name.getPackageName())) {
final Drawable icon = Launcher.getModel().getApplicationInfoIcon(
mLauncher.getPackageManager(), info);
if (icon != null && icon != info.icon) {
info.icon.setCallback(null);
info.icon = Utilities.createIconThumbnail(icon, mContext);
info.filtered = true;
((TextView) view).setCompoundDrawablesWithIntrinsicBounds(null,
info.icon, null, null);
}
}
}
}
}
}
void moveToDefaultScreen() {
snapToScreen(mDefaultScreen);
getChildAt(mDefaultScreen).requestFocus();
}
public static class SavedState extends BaseSavedState {
int currentScreen = -1;
SavedState(Parcelable superState) {
super(superState);
}
private SavedState(Parcel in) {
super(in);
currentScreen = in.readInt();
}
@Override
public void writeToParcel(Parcel out, int flags) {
super.writeToParcel(out, flags);
out.writeInt(currentScreen);
}
public static final Parcelable.Creator<SavedState> CREATOR =
new Parcelable.Creator<SavedState>() {
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
/**************************************************
* ADW: Custom modifications
*/
/**
* Pagination indicators (dots)
*/
void setIndicators(Drawable previous, Drawable next) {
mPreviousIndicator = previous;
mNextIndicator = next;
indicatorLevels(mCurrentScreen);
}
void indicatorLevels(int mCurrent){
int numScreens=getChildCount();
mPreviousIndicator.setLevel(mCurrent);
mNextIndicator.setLevel(numScreens-mCurrent-1);
}
/**
* ADW: Make a local copy of wallpaper bitmap to use instead wallpapermanager
* only when detected not being a Live Wallpaper
*/
public void setWallpaper(boolean fromIntentReceiver){
if(mWallpaperManager.getWallpaperInfo()!=null || !wallpaperHack){
mWallpaperDrawable=null;
mWallpaperLoaded=false;
lwpSupport=true;
}else{
if(fromIntentReceiver || mWallpaperDrawable==null){
final Drawable drawable = mWallpaperManager.getDrawable();
mWallpaperDrawable=(BitmapDrawable) drawable;
mWallpaperLoaded=true;
}
lwpSupport=false;
}
mLauncher.setWindowBackground(lwpSupport);
invalidate();
requestLayout();
}
public void setWallpaperHack(boolean hack){
wallpaperHack=hack;
if(wallpaperHack && mWallpaperManager.getWallpaperInfo()==null){
lwpSupport=false;
}else{
lwpSupport=true;
}
mLauncher.setWindowBackground(lwpSupport);
}
/**
* ADW: Set the desktop scrolling speed (default scrolling duration)
* @param speed
*/
public void setSpeed(int speed){
mScrollingSpeed=speed;
}
/**
* ADW: Set the desktop scrolling bounce amount (0 to disable)
* @param amount
*/
public void setBounceAmount(int amount){
mScrollingBounce=amount;
mScroller.setInterpolator(new ElasticInterpolator(mScrollingBounce/10));
}
public void openSense(boolean open){
mScroller.abortAnimation();
enableChildrenCache();
if(open){
mSensemode=true;
isAnimating=true;
mStatus=SENSE_OPENING;
startTime=0;
}else{
mSensemode=true;
isAnimating=true;
mStatus=SENSE_CLOSING;
startTime=0;
}
}
@Override
protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
int saveCount = canvas.save();
if(mSensemode){
if(isAnimating||mStatus==SENSE_OPEN){
long currentTime=SystemClock.uptimeMillis()-startTime;
Rect r1=new Rect(0, 0, child.getWidth(), child.getHeight());
RectF r2=getScaledChild(child);
float x=0; float y=0; float width=0;float height=0; float alpha=255;
if(mStatus==SENSE_OPENING){
alpha=easeOut(currentTime,0,100,mAnimationDuration);
x=easeOut(currentTime, child.getLeft(), r2.left, mAnimationDuration);
y=easeOut(currentTime, child.getTop(), r2.top, mAnimationDuration);
width=easeOut(currentTime, child.getRight(), r2.right, mAnimationDuration);
height=easeOut(currentTime, child.getBottom(), r2.bottom, mAnimationDuration);
}else if (mStatus==SENSE_CLOSING){
alpha=easeOut(currentTime,100,0,mAnimationDuration);
x=easeOut(currentTime, r2.left,child.getLeft(), mAnimationDuration);
y=easeOut(currentTime, r2.top, child.getTop(), mAnimationDuration);
width=easeOut(currentTime, r2.right, child.getRight(), mAnimationDuration);
height=easeOut(currentTime, r2.bottom, child.getBottom(), mAnimationDuration);
}else if(mStatus==SENSE_OPEN){
x=r2.left;
y=r2.top;
width=r2.right;
height=r2.bottom;
alpha=100;
}
float scale=((width-x)/r1.width());
canvas.save();
canvas.translate(x, y);
canvas.scale(scale,scale);
mPaint.setAlpha((int) alpha);
canvas.drawRoundRect(new RectF(r1.left+5,r1.top+5,r1.right-5, r1.bottom-5), 15f, 15f, mPaint);
mPaint.setAlpha(255);
child.draw(canvas);
canvas.restore();
}else{
child.draw(canvas);
}
}else{
super.drawChild(canvas, child, drawingTime);
}
canvas.restoreToCount(saveCount);
return true;
}
/**
* ADW: easing functions for animation
*/
static float easeOut (float time, float begin, float end, float duration) {
float change=end- begin;
float value= change*((time=time/duration-1)*time*time + 1) + begin;
if(change>0 && value>end) value=end;
if(change<0 && value<end) value=end;
return value;
}
static float easeIn (float time, float begin, float end, float duration) {
float change=end- begin;
float value=change*(time/=duration)*time*time + begin;
if(change>0 && value>end) value=end;
if(change<0 && value<end) value=end;
return value;
}
static float easeInOut (float time, float begin, float end, float duration) {
float change=end- begin;
if ((time/=duration/2.0f) < 1) return change/2.0f*time*time*time + begin;
return change/2.0f*((time-=2.0f)*time*time + 2.0f) + begin;
}
private RectF getScaledChild(View child){
final int count = getChildCount();
final int width = getWidth();//r - l;
final int height = getHeight();//b-t;
int xpos = getScrollX();
int ypos = 0;
int distro_set=count-1;
int childPos=0;
//TODO:ADW We nedd to find the "longer row" and get the best children width
int maxItemsPerRow=0;
for(int rows=0;rows<distro[distro_set].length;rows++){
if(distro[distro_set][rows]>maxItemsPerRow){
maxItemsPerRow=distro[distro_set][rows];
}
}
int childWidth=(width/maxItemsPerRow);//-getPaddingLeft()-getPaddingRight();//-(horizontal_spacing*(maxItemsPerRow-1));
if(childWidth>maxPreviewWidth)childWidth=maxPreviewWidth;
final float scale = ((float)childWidth/(float)maxPreviewWidth);
int childHeight = Math.round(maxPreviewHeight*scale);
final int topMargin=(height/2)-((childHeight*distro[distro_set].length)/2);
for(int rows=0;rows<distro[distro_set].length;rows++){
final int leftMargin=(width/2)-((childWidth*distro[distro_set][rows])/2);
for(int columns=0;columns<distro[distro_set][rows];columns++){
if(childPos>getChildCount()-1) break;
final View c = getChildAt(childPos);
if (child== c) {
return new RectF(leftMargin+xpos, topMargin+ypos, leftMargin+xpos + childWidth, topMargin+ypos + childHeight);
}else{
xpos += childWidth;
}
childPos++;
}
xpos = getScrollX();
ypos += childHeight;
}
return new RectF();
}
private void findClickedPreview(float x, float y){
for(int i=0;i<getChildCount();i++){
RectF tmp=getScaledChild(getChildAt(i));
if (tmp.contains(x+getScrollX(), y+getScrollY())){
if(mCurrentScreen!=i){
mLauncher.dismissPreviews();
mScroller.setInterpolator(new ElasticInterpolator(0));
mRevertInterpolatorOnScrollFinish=true;
snapToScreen(i);
postInvalidate();
}else{
mLauncher.dismissPreviews();
}
}
}
}
/**
* Wysie: Multitouch methods/events
*/
@Override
public Object getDraggableObjectAtPoint(PointInfo pt) {
return this;
}
@Override
public void getPositionAndScale(Object obj,
PositionAndScale objPosAndScaleOut) {
objPosAndScaleOut.set(0.0f, 0.0f, true, 1.0f, false, 0.0f, 0.0f, false, 0.0f);
}
@Override
public void selectObject(Object obj, PointInfo pt) {
if(mStatus!=SENSE_OPEN){
mAllowLongPress=false;
}else{
mAllowLongPress=true;
}
}
@Override
public boolean setPositionAndScale(Object obj,
PositionAndScale update, PointInfo touchPoint) {
float newRelativeScale = update.getScale();
int targetZoom = (int) Math.round(Math.log(newRelativeScale) * ZOOM_LOG_BASE_INV);
// Only works for pinch in
if (targetZoom < 0 && mStatus==SENSE_CLOSED) { // Change to > 0 for pinch out, != 0 for both pinch in and out.
mLauncher.showPreviews(mLauncher.getDrawerHandle(), 0, getChildCount());
invalidate();
return true;
}
return false;
}
@Override
public Activity getLauncherActivity() {
// TODO Auto-generated method stub
return mLauncher;
}
public int currentDesktopRows(){
return mDesktopRows;
}
public int currentDesktopColumns(){
return mDesktopColumns;
}
}
| true | true | public boolean onInterceptTouchEvent(MotionEvent ev) {
if(mStatus==SENSE_OPEN){
if(ev.getAction()==MotionEvent.ACTION_DOWN){
findClickedPreview(ev.getX(),ev.getY());
}
return true;
}
//Wysie: If multitouch event is detected
if (multiTouchController.onTouchEvent(ev)) {
return false;
}
if (mLocked || mLauncher.isAllAppsVisible()) {
return true;
}
/*
* This method JUST determines whether we want to intercept the motion.
* If we return true, onTouchEvent will be called and we do the actual
* scrolling there.
*/
/*
* Shortcut the most recurring case: the user is in the dragging
* state and he is moving his finger. We want to intercept this
* motion.
*/
final int action = ev.getAction();
if ((action == MotionEvent.ACTION_MOVE) && (mTouchState != TOUCH_STATE_REST)) {
return true;
}
final float x = ev.getX();
final float y = ev.getY();
switch (action) {
case MotionEvent.ACTION_MOVE:
/*
* mIsBeingDragged == false, otherwise the shortcut would have caught it. Check
* whether the user has moved far enough from his original down touch.
*/
/*
* Locally do absolute value. mLastMotionX is set to the y value
* of the down event.
*/
final int xDiff = (int) Math.abs(x - mLastMotionX);
final int yDiff = (int) Math.abs(y - mLastMotionY);
final int touchSlop = mTouchSlop;
boolean xMoved = xDiff > touchSlop;
boolean yMoved = yDiff > touchSlop;
if (xMoved || yMoved) {
if (xMoved) {
// Scroll if the user moved far enough along the X axis
mTouchState = TOUCH_STATE_SCROLLING;
enableChildrenCache();
} else if (yMoved)
{
// As x scrolling is left untouched, every gesture should start by dragging in Y axis. In fact I only consider useful, swipe up and down.
// Guess if the first Pointer where the user click belongs to where a scrollable widget is.
mTouchedScrollableWidget = isWidgetAtLocationScrollable((int)mLastMotionX,(int)mLastMotionY);
if (!mTouchedScrollableWidget)
{
// Only y axis movement. So may be a Swipe down or up gesture
if ((y - mLastMotionY) > 0)
mTouchState = TOUCH_SWIPE_DOWN_GESTURE;
else
{
mTouchState = TOUCH_SWIPE_UP_GESTURE;
}
}
}
// Either way, cancel any pending longpress
if (mAllowLongPress) {
mAllowLongPress = false;
// Try canceling the long press. It could also have been scheduled
// by a distant descendant, so use the mAllowLongPress flag to block
// everything
final View currentScreen = getChildAt(mCurrentScreen);
currentScreen.cancelLongPress();
}
}
break;
case MotionEvent.ACTION_DOWN:
// Remember location of down touch
mLastMotionX = x;
mLastMotionY = y;
mAllowLongPress = true;
/*
* If being flinged and user touches the screen, initiate drag;
* otherwise don't. mScroller.isFinished should be false when
* being flinged.
*/
mTouchState = mScroller.isFinished() ? TOUCH_STATE_REST : TOUCH_STATE_SCROLLING;
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
if (mTouchState != TOUCH_STATE_SCROLLING && mTouchState != TOUCH_SWIPE_DOWN_GESTURE && mTouchState != TOUCH_SWIPE_UP_GESTURE) {
final CellLayout currentScreen = (CellLayout) getChildAt(mCurrentScreen);
if (!currentScreen.lastDownOnOccupiedCell()) {
getLocationOnScreen(mTempCell);
// Send a tap to the wallpaper if the last down was on empty space
if(lwpSupport)
mWallpaperManager.sendWallpaperCommand(getWindowToken(),
"android.wallpaper.tap",
mTempCell[0] + (int) ev.getX(),
mTempCell[1] + (int) ev.getY(), 0, null);
}
}
// Release the drag
clearChildrenCache();
mTouchState = TOUCH_STATE_REST;
mAllowLongPress = false;
break;
}
/*
* The only time we want to intercept motion events is if we are in the
* drag mode.
*/
return mTouchState != TOUCH_STATE_REST;
}
| public boolean onInterceptTouchEvent(MotionEvent ev) {
if(mStatus==SENSE_OPEN){
if(ev.getAction()==MotionEvent.ACTION_DOWN){
findClickedPreview(ev.getX(),ev.getY());
}
return true;
}
//Wysie: If multitouch event is detected
if (multiTouchController.onTouchEvent(ev)) {
return false;
}
if (mLocked || mLauncher.isAllAppsVisible()) {
return true;
}
/*
* This method JUST determines whether we want to intercept the motion.
* If we return true, onTouchEvent will be called and we do the actual
* scrolling there.
*/
/*
* Shortcut the most recurring case: the user is in the dragging
* state and he is moving his finger. We want to intercept this
* motion.
*/
final int action = ev.getAction();
if ((action == MotionEvent.ACTION_MOVE) && (mTouchState != TOUCH_STATE_REST)) {
return true;
}
final float x = ev.getX();
final float y = ev.getY();
switch (action) {
case MotionEvent.ACTION_MOVE:
/*
* mIsBeingDragged == false, otherwise the shortcut would have caught it. Check
* whether the user has moved far enough from his original down touch.
*/
/*
* Locally do absolute value. mLastMotionX is set to the y value
* of the down event.
*/
final int xDiff = (int) Math.abs(x - mLastMotionX);
final int yDiff = (int) Math.abs(y - mLastMotionY);
final int touchSlop = mTouchSlop;
boolean xMoved = xDiff > touchSlop;
boolean yMoved = yDiff > touchSlop;
if (xMoved || yMoved) {
if (xMoved) {
// Scroll if the user moved far enough along the X axis
mTouchState = TOUCH_STATE_SCROLLING;
enableChildrenCache();
} else if (yMoved && getOpenFolder()==null)
{
// As x scrolling is left untouched, every gesture should start by dragging in Y axis. In fact I only consider useful, swipe up and down.
// Guess if the first Pointer where the user click belongs to where a scrollable widget is.
mTouchedScrollableWidget = isWidgetAtLocationScrollable((int)mLastMotionX,(int)mLastMotionY);
if (!mTouchedScrollableWidget)
{
// Only y axis movement. So may be a Swipe down or up gesture
if ((y - mLastMotionY) > 0)
mTouchState = TOUCH_SWIPE_DOWN_GESTURE;
else
{
mTouchState = TOUCH_SWIPE_UP_GESTURE;
}
}
}
// Either way, cancel any pending longpress
if (mAllowLongPress) {
mAllowLongPress = false;
// Try canceling the long press. It could also have been scheduled
// by a distant descendant, so use the mAllowLongPress flag to block
// everything
final View currentScreen = getChildAt(mCurrentScreen);
currentScreen.cancelLongPress();
}
}
break;
case MotionEvent.ACTION_DOWN:
// Remember location of down touch
mLastMotionX = x;
mLastMotionY = y;
mAllowLongPress = true;
/*
* If being flinged and user touches the screen, initiate drag;
* otherwise don't. mScroller.isFinished should be false when
* being flinged.
*/
mTouchState = mScroller.isFinished() ? TOUCH_STATE_REST : TOUCH_STATE_SCROLLING;
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
if (mTouchState != TOUCH_STATE_SCROLLING && mTouchState != TOUCH_SWIPE_DOWN_GESTURE && mTouchState != TOUCH_SWIPE_UP_GESTURE) {
final CellLayout currentScreen = (CellLayout) getChildAt(mCurrentScreen);
if (!currentScreen.lastDownOnOccupiedCell()) {
getLocationOnScreen(mTempCell);
// Send a tap to the wallpaper if the last down was on empty space
if(lwpSupport)
mWallpaperManager.sendWallpaperCommand(getWindowToken(),
"android.wallpaper.tap",
mTempCell[0] + (int) ev.getX(),
mTempCell[1] + (int) ev.getY(), 0, null);
}
}
// Release the drag
clearChildrenCache();
mTouchState = TOUCH_STATE_REST;
mAllowLongPress = false;
break;
}
/*
* The only time we want to intercept motion events is if we are in the
* drag mode.
*/
return mTouchState != TOUCH_STATE_REST;
}
|
diff --git a/src/org/broad/igv/feature/genome/GenomeImporter.java b/src/org/broad/igv/feature/genome/GenomeImporter.java
index 07c38afad..78c56776f 100644
--- a/src/org/broad/igv/feature/genome/GenomeImporter.java
+++ b/src/org/broad/igv/feature/genome/GenomeImporter.java
@@ -1,312 +1,312 @@
/*
* Copyright (c) 2007-2012 The Broad Institute, Inc.
* SOFTWARE COPYRIGHT NOTICE
* This software and its documentation are the copyright of the Broad Institute, Inc. All rights are reserved.
*
* This software is supplied without any warranty or guaranteed support whatsoever. The Broad Institute is not responsible for its use, misuse, or functionality.
*
* This software is licensed under the terms of the GNU Lesser General Public License (LGPL),
* Version 2.1 which is available at http://www.opensource.org/licenses/lgpl-2.1.php.
*/
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.broad.igv.feature.genome;
import org.apache.log4j.Logger;
import org.broad.igv.Globals;
import org.broad.igv.util.FileUtils;
import org.broad.igv.util.HttpUtils;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* /**
*
* @author jrobinso
*/
public class GenomeImporter {
public static final int MAX_CONTIGS = 1500000;
static Logger log = Logger.getLogger(GenomeImporter.class);
public static final Pattern SEQUENCE_NAME_SPLITTER = Pattern.compile("\\s+");
/**
* Create a zip containing all the information and data required to load a
* genome. All file/directory validation is assume to have been done by validation
* outside of this method.
*
* @param genomeFile
* @param genomeId Id of the genome.
* @param genomeDisplayName The genome name that is user-friendly.
* @param fastaFile The location of a fasta file, or directory of fasta files
* @param refFlatFile RefFlat file.
* @param cytobandFile Cytoband file.
* @return The newly created genome archive file.
*/
public File createGenomeArchive(File genomeFile,
String genomeId,
String genomeDisplayName,
String fastaFile,
File refFlatFile,
File cytobandFile,
File chrAliasFile) throws IOException {
if ((genomeFile == null) || (genomeId == null) || (genomeDisplayName == null)) {
log.error("Invalid input for genome creation: ");
log.error("\tGenome file=" + genomeFile.getAbsolutePath());
log.error("\tGenome Id=" + genomeId);
log.error("\tGenome Name" + genomeDisplayName);
return null;
}
File propertyFile = null;
File archive = null;
FileWriter propertyFileWriter = null;
try {
boolean fastaDirectory = false;
List<String> fastaFileNames = new ArrayList<String>();
if (!FileUtils.resourceExists(fastaFile)) {
String msg = "File not found: " + fastaFile;
throw new GenomeException(msg);
}
if (fastaFile.toLowerCase().endsWith(Globals.ZIP_EXTENSION)) {
String msg = "Error. Zip archives are not supported. Please select a fasta file.";
throw new GenomeException(msg);
}
if (fastaFile.toLowerCase().endsWith(Globals.GZIP_FILE_EXTENSION)) {
String msg = "Error. GZipped files are not supported. Please select a non-gzipped fasta file.";
throw new GenomeException(msg);
}
List<String> fastaIndexPathList = new ArrayList<String>();
String fastaIndexPath = fastaFile + ".fai";
File sequenceInputFile = new File(fastaFile);
if (sequenceInputFile.exists()) {
// Local file
if (sequenceInputFile.isDirectory()) {
fastaDirectory = true;
List<File> files = getSequenceFiles(sequenceInputFile);
for (File file : files) {
if (file.getName().toLowerCase().endsWith(Globals.GZIP_FILE_EXTENSION)) {
String msg = "<html>Error. One or more fasta files are gzipped: " + file.getName() +
"<br>All fasta files must be gunzipped prior to importing.";
throw new GenomeException(msg);
}
- File indexFile = new File(fastaIndexPath);
+ File indexFile = new File(sequenceInputFile, file.getName() + ".fai");
if (!indexFile.exists()) {
- FastaUtils.createIndexFile(fastaFile, fastaIndexPath);
+ FastaUtils.createIndexFile(file.getAbsolutePath(), indexFile.getAbsolutePath());
}
fastaIndexPathList.add(fastaIndexPath);
fastaFileNames.add(file.getName());
}
} else {
// Index if neccessary
File indexFile = new File(fastaIndexPath);
if (!indexFile.exists()) {
FastaUtils.createIndexFile(fastaFile, fastaIndexPath);
}
fastaIndexPathList.add(fastaIndexPath);
}
} else {
if (!FileUtils.resourceExists(fastaIndexPath)) {
String msg = "<html>Index file " + fastaIndexPath + " Not found. " +
"<br>Remote fasta files must be indexed prior to importing.";
throw new GenomeException(msg);
}
}
fastaFile = FileUtils.getRelativePath(genomeFile.getParent(), fastaFile);
// Create "in memory" property file
byte[] propertyBytes = createGenomePropertyFile(genomeId, genomeDisplayName, fastaFile, refFlatFile,
cytobandFile, chrAliasFile, fastaDirectory, fastaFileNames);
File[] inputFiles = {refFlatFile, cytobandFile, chrAliasFile};
// Create archive
createGenomeArchive(genomeFile, inputFiles, propertyBytes);
} finally {
if (propertyFileWriter != null) {
try {
propertyFileWriter.close();
} catch (IOException ex) {
log.error("Failed to close genome archive: +" + archive.getAbsolutePath(), ex);
}
}
if (propertyFile != null) propertyFile.delete();
}
return archive;
}
private List<File> getSequenceFiles(File sequenceDir) {
ArrayList<File> files = new ArrayList();
for (File f : sequenceDir.listFiles()) {
if (f.getName().startsWith(".") || f.isDirectory() || f.getName().endsWith(".fai")) {
continue;
} else {
files.add(f);
}
}
return files;
}
/**
* This method creates the property.txt file that is stored in each
* .genome file. This is not the user-defined genome property file
* created by storeUserDefinedGenomeListToFile(...)
*
* @param genomeId
* @param genomeDisplayName
* @param relativeSequenceLocation
* @param refFlatFile
* @param cytobandFile
* @param fastaFileNames
* @return
*/
public byte[] createGenomePropertyFile(String genomeId,
String genomeDisplayName,
String relativeSequenceLocation,
File refFlatFile,
File cytobandFile,
File chrAliasFile,
boolean fastaDirectory,
List<String> fastaFileNames) throws IOException {
PrintWriter propertyFileWriter = null;
try {
ByteArrayOutputStream propertyBytes = new ByteArrayOutputStream();
// Add the new property file to the archive
propertyFileWriter = new PrintWriter(new OutputStreamWriter(propertyBytes));
propertyFileWriter.println("fasta=true"); // Fasta is the only format supported now
propertyFileWriter.println("fastaDirectory=" + fastaDirectory);
if (fastaDirectory) {
propertyFileWriter.print("fastaFiles=");
for (String fif : fastaFileNames) {
propertyFileWriter.print(fif + ",");
}
propertyFileWriter.println();
}
propertyFileWriter.println("ordered=" + !fastaDirectory);
if (genomeId != null) {
propertyFileWriter.println(Globals.GENOME_ARCHIVE_ID_KEY + "=" + genomeId);
}
if (genomeDisplayName != null) {
propertyFileWriter.println(Globals.GENOME_ARCHIVE_NAME_KEY + "=" + genomeDisplayName);
}
if (cytobandFile != null) {
propertyFileWriter.println(Globals.GENOME_ARCHIVE_CYTOBAND_FILE_KEY + "=" + cytobandFile.getName());
}
if (refFlatFile != null) {
propertyFileWriter.println(Globals.GENOME_ARCHIVE_GENE_FILE_KEY + "=" + refFlatFile.getName());
}
if (chrAliasFile != null) {
propertyFileWriter.println(Globals.GENOME_CHR_ALIAS_FILE_KEY + "=" + chrAliasFile.getName());
}
if (relativeSequenceLocation != null) {
if (!HttpUtils.isRemoteURL(relativeSequenceLocation)) {
relativeSequenceLocation = relativeSequenceLocation.replace('\\', '/');
}
propertyFileWriter.println(Globals.GENOME_ARCHIVE_SEQUENCE_FILE_LOCATION_KEY + "=" + relativeSequenceLocation);
}
propertyFileWriter.flush();
return propertyBytes.toByteArray();
} finally {
if (propertyFileWriter != null) {
propertyFileWriter.close();
}
}
}
final static int ZIP_ENTRY_CHUNK_SIZE = 64000;
static public void createGenomeArchive(File zipOutputFile, File[] inputFiles, byte[] propertyBytes)
throws FileNotFoundException, IOException {
if (zipOutputFile == null) {
return;
}
if ((inputFiles == null) || (inputFiles.length == 0)) {
return;
}
ZipOutputStream zipOutputStream = null;
try {
zipOutputStream = new ZipOutputStream(new FileOutputStream(zipOutputFile));
ZipEntry propertiesEntry = new ZipEntry("property.txt");
propertiesEntry.setSize(propertyBytes.length);
zipOutputStream.putNextEntry(propertiesEntry);
zipOutputStream.write(propertyBytes);
for (File file : inputFiles) {
if (file == null) {
continue;
}
long fileLength = file.length();
ZipEntry zipEntry = new ZipEntry(file.getName());
zipEntry.setSize(fileLength);
zipOutputStream.putNextEntry(zipEntry);
BufferedInputStream bufferedInputstream = null;
try {
InputStream inputStream = new FileInputStream(file);
bufferedInputstream = new BufferedInputStream(inputStream);
int bytesRead = 0;
byte[] data = new byte[ZIP_ENTRY_CHUNK_SIZE];
while ((bytesRead = bufferedInputstream.read(data)) != -1) {
zipOutputStream.write(data, 0, bytesRead);
}
} finally {
if (bufferedInputstream != null) {
bufferedInputstream.close();
}
}
}
} finally {
if (zipOutputStream != null) {
zipOutputStream.flush();
zipOutputStream.close();
}
}
}
}
| false | true | public File createGenomeArchive(File genomeFile,
String genomeId,
String genomeDisplayName,
String fastaFile,
File refFlatFile,
File cytobandFile,
File chrAliasFile) throws IOException {
if ((genomeFile == null) || (genomeId == null) || (genomeDisplayName == null)) {
log.error("Invalid input for genome creation: ");
log.error("\tGenome file=" + genomeFile.getAbsolutePath());
log.error("\tGenome Id=" + genomeId);
log.error("\tGenome Name" + genomeDisplayName);
return null;
}
File propertyFile = null;
File archive = null;
FileWriter propertyFileWriter = null;
try {
boolean fastaDirectory = false;
List<String> fastaFileNames = new ArrayList<String>();
if (!FileUtils.resourceExists(fastaFile)) {
String msg = "File not found: " + fastaFile;
throw new GenomeException(msg);
}
if (fastaFile.toLowerCase().endsWith(Globals.ZIP_EXTENSION)) {
String msg = "Error. Zip archives are not supported. Please select a fasta file.";
throw new GenomeException(msg);
}
if (fastaFile.toLowerCase().endsWith(Globals.GZIP_FILE_EXTENSION)) {
String msg = "Error. GZipped files are not supported. Please select a non-gzipped fasta file.";
throw new GenomeException(msg);
}
List<String> fastaIndexPathList = new ArrayList<String>();
String fastaIndexPath = fastaFile + ".fai";
File sequenceInputFile = new File(fastaFile);
if (sequenceInputFile.exists()) {
// Local file
if (sequenceInputFile.isDirectory()) {
fastaDirectory = true;
List<File> files = getSequenceFiles(sequenceInputFile);
for (File file : files) {
if (file.getName().toLowerCase().endsWith(Globals.GZIP_FILE_EXTENSION)) {
String msg = "<html>Error. One or more fasta files are gzipped: " + file.getName() +
"<br>All fasta files must be gunzipped prior to importing.";
throw new GenomeException(msg);
}
File indexFile = new File(fastaIndexPath);
if (!indexFile.exists()) {
FastaUtils.createIndexFile(fastaFile, fastaIndexPath);
}
fastaIndexPathList.add(fastaIndexPath);
fastaFileNames.add(file.getName());
}
} else {
// Index if neccessary
File indexFile = new File(fastaIndexPath);
if (!indexFile.exists()) {
FastaUtils.createIndexFile(fastaFile, fastaIndexPath);
}
fastaIndexPathList.add(fastaIndexPath);
}
} else {
if (!FileUtils.resourceExists(fastaIndexPath)) {
String msg = "<html>Index file " + fastaIndexPath + " Not found. " +
"<br>Remote fasta files must be indexed prior to importing.";
throw new GenomeException(msg);
}
}
fastaFile = FileUtils.getRelativePath(genomeFile.getParent(), fastaFile);
// Create "in memory" property file
byte[] propertyBytes = createGenomePropertyFile(genomeId, genomeDisplayName, fastaFile, refFlatFile,
cytobandFile, chrAliasFile, fastaDirectory, fastaFileNames);
File[] inputFiles = {refFlatFile, cytobandFile, chrAliasFile};
// Create archive
createGenomeArchive(genomeFile, inputFiles, propertyBytes);
} finally {
if (propertyFileWriter != null) {
try {
propertyFileWriter.close();
} catch (IOException ex) {
log.error("Failed to close genome archive: +" + archive.getAbsolutePath(), ex);
}
}
if (propertyFile != null) propertyFile.delete();
}
return archive;
}
| public File createGenomeArchive(File genomeFile,
String genomeId,
String genomeDisplayName,
String fastaFile,
File refFlatFile,
File cytobandFile,
File chrAliasFile) throws IOException {
if ((genomeFile == null) || (genomeId == null) || (genomeDisplayName == null)) {
log.error("Invalid input for genome creation: ");
log.error("\tGenome file=" + genomeFile.getAbsolutePath());
log.error("\tGenome Id=" + genomeId);
log.error("\tGenome Name" + genomeDisplayName);
return null;
}
File propertyFile = null;
File archive = null;
FileWriter propertyFileWriter = null;
try {
boolean fastaDirectory = false;
List<String> fastaFileNames = new ArrayList<String>();
if (!FileUtils.resourceExists(fastaFile)) {
String msg = "File not found: " + fastaFile;
throw new GenomeException(msg);
}
if (fastaFile.toLowerCase().endsWith(Globals.ZIP_EXTENSION)) {
String msg = "Error. Zip archives are not supported. Please select a fasta file.";
throw new GenomeException(msg);
}
if (fastaFile.toLowerCase().endsWith(Globals.GZIP_FILE_EXTENSION)) {
String msg = "Error. GZipped files are not supported. Please select a non-gzipped fasta file.";
throw new GenomeException(msg);
}
List<String> fastaIndexPathList = new ArrayList<String>();
String fastaIndexPath = fastaFile + ".fai";
File sequenceInputFile = new File(fastaFile);
if (sequenceInputFile.exists()) {
// Local file
if (sequenceInputFile.isDirectory()) {
fastaDirectory = true;
List<File> files = getSequenceFiles(sequenceInputFile);
for (File file : files) {
if (file.getName().toLowerCase().endsWith(Globals.GZIP_FILE_EXTENSION)) {
String msg = "<html>Error. One or more fasta files are gzipped: " + file.getName() +
"<br>All fasta files must be gunzipped prior to importing.";
throw new GenomeException(msg);
}
File indexFile = new File(sequenceInputFile, file.getName() + ".fai");
if (!indexFile.exists()) {
FastaUtils.createIndexFile(file.getAbsolutePath(), indexFile.getAbsolutePath());
}
fastaIndexPathList.add(fastaIndexPath);
fastaFileNames.add(file.getName());
}
} else {
// Index if neccessary
File indexFile = new File(fastaIndexPath);
if (!indexFile.exists()) {
FastaUtils.createIndexFile(fastaFile, fastaIndexPath);
}
fastaIndexPathList.add(fastaIndexPath);
}
} else {
if (!FileUtils.resourceExists(fastaIndexPath)) {
String msg = "<html>Index file " + fastaIndexPath + " Not found. " +
"<br>Remote fasta files must be indexed prior to importing.";
throw new GenomeException(msg);
}
}
fastaFile = FileUtils.getRelativePath(genomeFile.getParent(), fastaFile);
// Create "in memory" property file
byte[] propertyBytes = createGenomePropertyFile(genomeId, genomeDisplayName, fastaFile, refFlatFile,
cytobandFile, chrAliasFile, fastaDirectory, fastaFileNames);
File[] inputFiles = {refFlatFile, cytobandFile, chrAliasFile};
// Create archive
createGenomeArchive(genomeFile, inputFiles, propertyBytes);
} finally {
if (propertyFileWriter != null) {
try {
propertyFileWriter.close();
} catch (IOException ex) {
log.error("Failed to close genome archive: +" + archive.getAbsolutePath(), ex);
}
}
if (propertyFile != null) propertyFile.delete();
}
return archive;
}
|
diff --git a/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/nLayout/area/impl/RowArea.java b/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/nLayout/area/impl/RowArea.java
index 6536e4b44..9c3f857f5 100644
--- a/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/nLayout/area/impl/RowArea.java
+++ b/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/nLayout/area/impl/RowArea.java
@@ -1,358 +1,359 @@
/***********************************************************************
* Copyright (c) 2009 Actuate Corporation.
* 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:
* Actuate Corporation - initial API and implementation
***********************************************************************/
package org.eclipse.birt.report.engine.nLayout.area.impl;
import java.util.Iterator;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.report.engine.content.IContent;
import org.eclipse.birt.report.engine.nLayout.LayoutContext;
import org.eclipse.birt.report.engine.nLayout.area.IArea;
public class RowArea extends ContainerArea
{
protected transient CellArea[] cells;
protected transient TableArea table;
protected int rowID;
public RowArea( ContainerArea parent, LayoutContext context,
IContent content )
{
super( parent, context, content );
cells = new CellArea[getTable().getColumnCount( )];
}
RowArea( int colCount )
{
super( );
cells = new CellArea[colCount];
}
RowArea( RowArea row )
{
super( row );
this.rowID = row.getRowID( );
this.cells = new CellArea[row.getColumnCount()];
}
public int getColumnCount( )
{
TableArea table = getTableArea();
if ( table != null )
{
return table.getColumnCount( );
}
if ( cells != null )
{
return cells.length;
}
return 0;
}
public void setCell( CellArea cell )
{
int col = cell.getColumnID( );
int colSpan = cell.getColSpan( );
for ( int i = col; i < col + colSpan; i++ )
{
cells[i] = cell;
}
}
public CellArea getCell( int columnID )
{
if ( columnID >= 0 && columnID < cells.length )
{
return cells[columnID];
}
return null;
}
public void replace( CellArea origin, CellArea dest )
{
children.remove( origin );
children.add( dest );
dest.setParent( this );
}
public void setRowID( int rowID )
{
this.rowID = rowID;
}
public int getRowID( )
{
return rowID;
}
public RowArea cloneArea( )
{
return new RowArea( this );
}
public RowArea deepClone( )
{
RowArea result = (RowArea) cloneArea( );
Iterator iter = children.iterator( );
while ( iter.hasNext( ) )
{
CellArea child = (CellArea) iter.next( );
CellArea cloneChild =(CellArea) child.deepClone( );
result.children.add( cloneChild );
cloneChild.setParent( result );
result.setCell( cloneChild );
}
return result;
}
protected TableArea getTableArea()
{
if(table==null)
{
table = getTable();
}
return table;
}
public void close( ) throws BirtException
{
getTableArea().addRow( this );
if ( !isInInlineStacking && context.isAutoPageBreak( ) )
{
int aHeight = getAllocatedHeight( );
while ( aHeight + parent.getAbsoluteBP( ) >= context.getMaxBP( ) )
{
parent.autoPageBreak( );
aHeight = getAllocatedHeight( );
}
}
parent.update( this );
finished = true;
}
public void initialize( ) throws BirtException
{
calculateSpecifiedHeight( content );
width = parent.getMaxAvaWidth( );
buildLogicContainerProperties( content, context );
parent.add( this );
}
protected boolean isRowEmpty( )
{
Iterator iter = getChildren( );
while ( iter.hasNext( ) )
{
ContainerArea area = (ContainerArea) iter.next( );
if ( area.getChildrenCount( ) > 0 )
{
return false;
}
}
return true;
}
public void update( AbstractArea area ) throws BirtException
{
CellArea cArea = (CellArea) area;
int columnID = cArea.getColumnID( );
int colSpan = cArea.getColSpan( );
// Retrieve direction from the top-level content.
if ( colSpan > 1 && content.isRTL( ) )
{
columnID += colSpan - 1;
}
cArea.setPosition( getTableArea().getXPos( columnID ), 0 );
}
public void add(AbstractArea area)
{
addChild(area);
CellArea cArea = (CellArea) area;
int columnID = cArea.getColumnID( );
int colSpan = cArea.getColSpan( );
// Retrieve direction from the top-level content.
if ( colSpan > 1 && content.isRTL( ) )
{
columnID += colSpan - 1;
}
cArea.setPosition( getTableArea().getXPos( columnID ), 0 );
}
public void addChild( IArea area )
{
children.add( area );
this.setCell( ( CellArea)area);
}
public SplitResult split( int height, boolean force ) throws BirtException
{
if ( force )
{
return _split( height, force );
}
else if ( isPageBreakInsideAvoid( ) )
{
if ( isPageBreakBeforeAvoid( ) )
{
return SplitResult.BEFORE_AVOID_WITH_NULL;
}
else
{
_splitSpanCell( height , force);
return SplitResult.SUCCEED_WITH_NULL;
}
}
else
{
return _split( height, force );
}
}
protected void _splitSpanCell(int height, boolean force) throws BirtException
{
if ( cells.length != children.size( ) )
{
// split dummy cell
for ( int i = 0; i < cells.length; i++ )
{
if ( cells[i] instanceof DummyCell )
{
SplitResult splitCell = cells[i].split( 0, force );
CellArea cell = (CellArea)splitCell.getResult( );
if ( cell != null )
{
cell
.setHeight( ( (DummyCell) cells[i] )
.getDelta( ) );
CellArea org = ( (DummyCell) cells[i] ).getCell( );
RowArea row = (RowArea) org.getParent( );
row.replace( org, cell );
cell.setParent( row );
}
i = i + cells[i].getColSpan( ) - 1;
}
}
}
}
protected SplitResult _split( int height, boolean force )
throws BirtException
{
RowArea result = null;
for ( int i = 0; i < cells.length; i++ )
{
if(cells[i]!=null)
{
SplitResult splitCell = cells[i].split( height, force );
CellArea cell = (CellArea) splitCell.getResult( );
if ( cell != null )
{
if ( result == null )
{
result = cloneArea( );
}
result.addChild( cell );
result.setCell( cell );
}
i = cells[i].getColSpan( ) + i - 1;
}
}
if ( result != null )
{
result.updateRow( this );
updateRow();
return new SplitResult( result, SplitResult.SPLIT_SUCCEED_WITH_PART );
}
else
{
+ updateRow();
return SplitResult.SUCCEED_WITH_NULL;
}
}
protected void updateRow()
{
int height = 0;
for(int i=0; i<children.size( ); i++)
{
CellArea cell = (CellArea) children.get( i );
height = Math.max( height, cell.getHeight( ) );
}
this.height = height;
for(int i=0; i<children.size( ); i++)
{
CellArea cell = (CellArea) children.get( i );
cell.setHeight( height );
setCell(cell);
}
}
public void updateRow( RowArea original )
{
int height = 0;
Iterator iter = children.iterator( );
while ( iter.hasNext( ) )
{
CellArea cell = (CellArea) iter.next( );
height = Math.max( height, cell.getHeight( ) );
}
this.height = height;
for ( int i = 0; i < cells.length; i++ )
{
if ( cells[i] == null )
{
CellArea oCell = original.getCell( i );
if ( oCell!=null &&!( oCell instanceof DummyCell ) )
{
CellArea nCell = oCell.cloneArea( );
nCell.setHeight( height );
nCell.setParent( this );
children.add( nCell );
i = i + oCell.getColSpan( ) - 1;
}
}
else
{
cells[i].setHeight( height );
}
}
}
public boolean isPageBreakInsideAvoid()
{
if( getTableArea().isGridDesign( ))
{
return super.isPageBreakInsideAvoid( );
}
else
{
return true;
}
}
public SplitResult splitLines( int lineCount ) throws BirtException
{
if ( isPageBreakBeforeAvoid( ) )
{
return SplitResult.BEFORE_AVOID_WITH_NULL;
}
return SplitResult.SUCCEED_WITH_NULL;
}
}
| true | true | protected SplitResult _split( int height, boolean force )
throws BirtException
{
RowArea result = null;
for ( int i = 0; i < cells.length; i++ )
{
if(cells[i]!=null)
{
SplitResult splitCell = cells[i].split( height, force );
CellArea cell = (CellArea) splitCell.getResult( );
if ( cell != null )
{
if ( result == null )
{
result = cloneArea( );
}
result.addChild( cell );
result.setCell( cell );
}
i = cells[i].getColSpan( ) + i - 1;
}
}
if ( result != null )
{
result.updateRow( this );
updateRow();
return new SplitResult( result, SplitResult.SPLIT_SUCCEED_WITH_PART );
}
else
{
return SplitResult.SUCCEED_WITH_NULL;
}
}
| protected SplitResult _split( int height, boolean force )
throws BirtException
{
RowArea result = null;
for ( int i = 0; i < cells.length; i++ )
{
if(cells[i]!=null)
{
SplitResult splitCell = cells[i].split( height, force );
CellArea cell = (CellArea) splitCell.getResult( );
if ( cell != null )
{
if ( result == null )
{
result = cloneArea( );
}
result.addChild( cell );
result.setCell( cell );
}
i = cells[i].getColSpan( ) + i - 1;
}
}
if ( result != null )
{
result.updateRow( this );
updateRow();
return new SplitResult( result, SplitResult.SPLIT_SUCCEED_WITH_PART );
}
else
{
updateRow();
return SplitResult.SUCCEED_WITH_NULL;
}
}
|
diff --git a/java/modules/core/src/main/java/org/apache/synapse/mediators/transaction/TransactionMediator.java b/java/modules/core/src/main/java/org/apache/synapse/mediators/transaction/TransactionMediator.java
index 03c5bef96..f617bd7de 100644
--- a/java/modules/core/src/main/java/org/apache/synapse/mediators/transaction/TransactionMediator.java
+++ b/java/modules/core/src/main/java/org/apache/synapse/mediators/transaction/TransactionMediator.java
@@ -1,159 +1,159 @@
/*
* 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.mediators.transaction;
import org.apache.synapse.MessageContext;
import org.apache.synapse.SynapseException;
import org.apache.synapse.SynapseLog;
import org.apache.synapse.mediators.AbstractMediator;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.transaction.Status;
import javax.transaction.UserTransaction;
/**
* The Mediator for commit, rollback, suspend, resume jta transactions
*/
public class TransactionMediator extends AbstractMediator {
public static final String ACTION_COMMIT = "commit";
public static final String ACTION_ROLLBACK = "rollback";
public static final String ACTION_NEW = "new";
public static final String ACTION_USE_EXISTING_OR_NEW = "use-existing-or-new";
public static final String ACTION_FAULT_IF_NO_TX = "fault-if-no-tx";
private static final String USER_TX_LOOKUP_STR = "java:comp/UserTransaction";
private Context txContext;
private String action = "";
public boolean mediate(MessageContext synCtx) {
UserTransaction tx = null;
final SynapseLog synLog = getLog(synCtx);
if (synLog.isTraceOrDebugEnabled()) {
synLog.traceOrDebug("Start : Transaction mediator (" + action + ")");
if (synLog.isTraceTraceEnabled()) {
synLog.traceTrace("Message : " + synCtx.getEnvelope());
}
}
initContext(synCtx);
try {
tx = (UserTransaction) txContext.lookup(USER_TX_LOOKUP_STR);
} catch (NamingException e) {
handleException("Cloud not get the context name " + USER_TX_LOOKUP_STR, e, synCtx);
}
if (action.equals(ACTION_COMMIT)) {
try {
tx.commit();
} catch (Exception e) {
handleException("Unable to commit transaction", e, synCtx);
}
} else if (action.equals(ACTION_ROLLBACK)) {
try {
tx.rollback();
} catch (Exception e) {
handleException("Unable to rollback transaction", e, synCtx);
}
} else if (action.equals(ACTION_NEW)) {
int status = Status.STATUS_UNKNOWN;
try {
status = tx.getStatus();
} catch (Exception e) {
handleException("Unable to query transaction status", e, synCtx);
}
if (status != Status.STATUS_NO_TRANSACTION) {
throw new SynapseException("Require to begin a new transaction, " +
- "but a tansaction already exist");
+ "but a transaction already exist");
}
try {
tx.begin();
} catch (Exception e) {
handleException("Unable to begin a new transaction", e, synCtx);
}
} else if (action.equals(ACTION_USE_EXISTING_OR_NEW)) {
int status = Status.STATUS_UNKNOWN;
try {
status = tx.getStatus();
} catch (Exception e) {
handleException("Unable to query transaction status", e, synCtx);
}
try {
if (status == Status.STATUS_NO_TRANSACTION) {
tx.begin();
}
} catch (Exception e) {
handleException("Unable to begin a new transaction", e, synCtx);
}
} else if (action.equals(ACTION_FAULT_IF_NO_TX)) {
int status = Status.STATUS_UNKNOWN;
try {
status = tx.getStatus();
} catch (Exception e) {
handleException("Unable to query transaction status", e, synCtx);
}
if (status != Status.STATUS_ACTIVE)
throw new SynapseException("No active transaction. Require an active transaction");
} else {
handleException("Invalid transaction mediator action : " + action, synCtx);
}
if (synLog.isTraceOrDebugEnabled()) {
synLog.traceOrDebug("End : Transaction mediator");
}
return true;
}
public void setAction(String action) {
this.action = action;
}
public String getAction() {
return action;
}
private void initContext(MessageContext synCtx) {
try {
txContext = new InitialContext();
} catch (NamingException e) {
handleException("Cloud not create initial context", e, synCtx);
}
}
}
| true | true | public boolean mediate(MessageContext synCtx) {
UserTransaction tx = null;
final SynapseLog synLog = getLog(synCtx);
if (synLog.isTraceOrDebugEnabled()) {
synLog.traceOrDebug("Start : Transaction mediator (" + action + ")");
if (synLog.isTraceTraceEnabled()) {
synLog.traceTrace("Message : " + synCtx.getEnvelope());
}
}
initContext(synCtx);
try {
tx = (UserTransaction) txContext.lookup(USER_TX_LOOKUP_STR);
} catch (NamingException e) {
handleException("Cloud not get the context name " + USER_TX_LOOKUP_STR, e, synCtx);
}
if (action.equals(ACTION_COMMIT)) {
try {
tx.commit();
} catch (Exception e) {
handleException("Unable to commit transaction", e, synCtx);
}
} else if (action.equals(ACTION_ROLLBACK)) {
try {
tx.rollback();
} catch (Exception e) {
handleException("Unable to rollback transaction", e, synCtx);
}
} else if (action.equals(ACTION_NEW)) {
int status = Status.STATUS_UNKNOWN;
try {
status = tx.getStatus();
} catch (Exception e) {
handleException("Unable to query transaction status", e, synCtx);
}
if (status != Status.STATUS_NO_TRANSACTION) {
throw new SynapseException("Require to begin a new transaction, " +
"but a tansaction already exist");
}
try {
tx.begin();
} catch (Exception e) {
handleException("Unable to begin a new transaction", e, synCtx);
}
} else if (action.equals(ACTION_USE_EXISTING_OR_NEW)) {
int status = Status.STATUS_UNKNOWN;
try {
status = tx.getStatus();
} catch (Exception e) {
handleException("Unable to query transaction status", e, synCtx);
}
try {
if (status == Status.STATUS_NO_TRANSACTION) {
tx.begin();
}
} catch (Exception e) {
handleException("Unable to begin a new transaction", e, synCtx);
}
} else if (action.equals(ACTION_FAULT_IF_NO_TX)) {
int status = Status.STATUS_UNKNOWN;
try {
status = tx.getStatus();
} catch (Exception e) {
handleException("Unable to query transaction status", e, synCtx);
}
if (status != Status.STATUS_ACTIVE)
throw new SynapseException("No active transaction. Require an active transaction");
} else {
handleException("Invalid transaction mediator action : " + action, synCtx);
}
if (synLog.isTraceOrDebugEnabled()) {
synLog.traceOrDebug("End : Transaction mediator");
}
return true;
}
| public boolean mediate(MessageContext synCtx) {
UserTransaction tx = null;
final SynapseLog synLog = getLog(synCtx);
if (synLog.isTraceOrDebugEnabled()) {
synLog.traceOrDebug("Start : Transaction mediator (" + action + ")");
if (synLog.isTraceTraceEnabled()) {
synLog.traceTrace("Message : " + synCtx.getEnvelope());
}
}
initContext(synCtx);
try {
tx = (UserTransaction) txContext.lookup(USER_TX_LOOKUP_STR);
} catch (NamingException e) {
handleException("Cloud not get the context name " + USER_TX_LOOKUP_STR, e, synCtx);
}
if (action.equals(ACTION_COMMIT)) {
try {
tx.commit();
} catch (Exception e) {
handleException("Unable to commit transaction", e, synCtx);
}
} else if (action.equals(ACTION_ROLLBACK)) {
try {
tx.rollback();
} catch (Exception e) {
handleException("Unable to rollback transaction", e, synCtx);
}
} else if (action.equals(ACTION_NEW)) {
int status = Status.STATUS_UNKNOWN;
try {
status = tx.getStatus();
} catch (Exception e) {
handleException("Unable to query transaction status", e, synCtx);
}
if (status != Status.STATUS_NO_TRANSACTION) {
throw new SynapseException("Require to begin a new transaction, " +
"but a transaction already exist");
}
try {
tx.begin();
} catch (Exception e) {
handleException("Unable to begin a new transaction", e, synCtx);
}
} else if (action.equals(ACTION_USE_EXISTING_OR_NEW)) {
int status = Status.STATUS_UNKNOWN;
try {
status = tx.getStatus();
} catch (Exception e) {
handleException("Unable to query transaction status", e, synCtx);
}
try {
if (status == Status.STATUS_NO_TRANSACTION) {
tx.begin();
}
} catch (Exception e) {
handleException("Unable to begin a new transaction", e, synCtx);
}
} else if (action.equals(ACTION_FAULT_IF_NO_TX)) {
int status = Status.STATUS_UNKNOWN;
try {
status = tx.getStatus();
} catch (Exception e) {
handleException("Unable to query transaction status", e, synCtx);
}
if (status != Status.STATUS_ACTIVE)
throw new SynapseException("No active transaction. Require an active transaction");
} else {
handleException("Invalid transaction mediator action : " + action, synCtx);
}
if (synLog.isTraceOrDebugEnabled()) {
synLog.traceOrDebug("End : Transaction mediator");
}
return true;
}
|
diff --git a/src/main/java/walledin/game/entity/behaviors/logic/PlayerWeaponInventoryBehavior.java b/src/main/java/walledin/game/entity/behaviors/logic/PlayerWeaponInventoryBehavior.java
index 7f8ad67..cfc8375 100644
--- a/src/main/java/walledin/game/entity/behaviors/logic/PlayerWeaponInventoryBehavior.java
+++ b/src/main/java/walledin/game/entity/behaviors/logic/PlayerWeaponInventoryBehavior.java
@@ -1,120 +1,121 @@
/* Copyright 2010 Ben Ruijl, Wouter Smeenk
This file is part of Walled In.
Walled In 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, or (at your option)
any later version.
Walled In 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 Walled In; see the file LICENSE. If not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA.
*/
package walledin.game.entity.behaviors.logic;
import java.util.HashMap;
import java.util.Map;
import org.apache.log4j.Logger;
import walledin.game.CollisionManager.CollisionData;
import walledin.game.entity.Attribute;
import walledin.game.entity.Behavior;
import walledin.game.entity.Entity;
import walledin.game.entity.Family;
import walledin.game.entity.MessageType;
public class PlayerWeaponInventoryBehavior extends Behavior {
private final static Logger LOG = Logger
.getLogger(PlayerWeaponInventoryBehavior.class);
private final Map<Family, Entity> weapons;
private final Map<Integer, Family> weaponKeyMap;
public PlayerWeaponInventoryBehavior(final Entity owner) {
super(owner);
weapons = new HashMap<Family, Entity>();
weaponKeyMap = new HashMap<Integer, Family>();
/* Add default guns to list */
weaponKeyMap.put(1, Family.HANDGUN);
weaponKeyMap.put(2, Family.FOAMGUN);
}
@Override
public void onMessage(final MessageType messageType, final Object data) {
if (messageType == MessageType.COLLIDED) {
final CollisionData colData = (CollisionData) data;
final Entity weapon = colData.getCollisionEntity();
if (weapon.getFamily().getParent() == Family.WEAPON) {
if (!getOwner().hasAttribute(Attribute.ACTIVE_WEAPON)
|| getOwner().getAttribute(Attribute.ACTIVE_WEAPON) != weapon) {
// is weapon already owned?
- if ((Boolean) weapon.getAttribute(Attribute.PICKED_UP) == true) {
+ Boolean hasWeapon = (Boolean) weapon.getAttribute(Attribute.PICKED_UP);
+ if (hasWeapon != null && hasWeapon == true) {
return;
}
if (weapons.containsKey(weapon.getFamily())) {
return;
}
weapon.setAttribute(Attribute.PICKED_UP, Boolean.TRUE);
weapons.put(weapon.getFamily(), weapon);
LOG.info("Adding weapon of family "
+ weapon.getFamily().toString());
if (!getOwner().hasAttribute(Attribute.ACTIVE_WEAPON)) {
setAttribute(Attribute.ACTIVE_WEAPON, weapon);
// set some attributes for the weapon
weapon.setAttribute(Attribute.ORIENTATION_ANGLE,
getAttribute(Attribute.ORIENTATION_ANGLE));
} else {
// remove weapon if picked up
weapon.remove();
}
}
}
}
if (messageType == MessageType.SELECT_WEAPON) {
final Entity weapon = weapons.get(weaponKeyMap.get(data));
if (weapon != null
&& !getAttribute(Attribute.ACTIVE_WEAPON).equals(weapon)) {
getEntityManager().add(weapon);
final Entity oldWeapon = (Entity) getAttribute(Attribute.ACTIVE_WEAPON);
if (oldWeapon != null) {
oldWeapon.remove();
}
setAttribute(Attribute.ACTIVE_WEAPON, weapon);
// set some attributes for the weapon
weapon.setAttribute(Attribute.ORIENTATION_ANGLE,
getAttribute(Attribute.ORIENTATION_ANGLE));
}
}
}
@Override
public void onUpdate(final double delta) {
// TODO Auto-generated method stub
}
}
| true | true | public void onMessage(final MessageType messageType, final Object data) {
if (messageType == MessageType.COLLIDED) {
final CollisionData colData = (CollisionData) data;
final Entity weapon = colData.getCollisionEntity();
if (weapon.getFamily().getParent() == Family.WEAPON) {
if (!getOwner().hasAttribute(Attribute.ACTIVE_WEAPON)
|| getOwner().getAttribute(Attribute.ACTIVE_WEAPON) != weapon) {
// is weapon already owned?
if ((Boolean) weapon.getAttribute(Attribute.PICKED_UP) == true) {
return;
}
if (weapons.containsKey(weapon.getFamily())) {
return;
}
weapon.setAttribute(Attribute.PICKED_UP, Boolean.TRUE);
weapons.put(weapon.getFamily(), weapon);
LOG.info("Adding weapon of family "
+ weapon.getFamily().toString());
if (!getOwner().hasAttribute(Attribute.ACTIVE_WEAPON)) {
setAttribute(Attribute.ACTIVE_WEAPON, weapon);
// set some attributes for the weapon
weapon.setAttribute(Attribute.ORIENTATION_ANGLE,
getAttribute(Attribute.ORIENTATION_ANGLE));
} else {
// remove weapon if picked up
weapon.remove();
}
}
}
}
if (messageType == MessageType.SELECT_WEAPON) {
final Entity weapon = weapons.get(weaponKeyMap.get(data));
if (weapon != null
&& !getAttribute(Attribute.ACTIVE_WEAPON).equals(weapon)) {
getEntityManager().add(weapon);
final Entity oldWeapon = (Entity) getAttribute(Attribute.ACTIVE_WEAPON);
if (oldWeapon != null) {
oldWeapon.remove();
}
setAttribute(Attribute.ACTIVE_WEAPON, weapon);
// set some attributes for the weapon
weapon.setAttribute(Attribute.ORIENTATION_ANGLE,
getAttribute(Attribute.ORIENTATION_ANGLE));
}
}
}
| public void onMessage(final MessageType messageType, final Object data) {
if (messageType == MessageType.COLLIDED) {
final CollisionData colData = (CollisionData) data;
final Entity weapon = colData.getCollisionEntity();
if (weapon.getFamily().getParent() == Family.WEAPON) {
if (!getOwner().hasAttribute(Attribute.ACTIVE_WEAPON)
|| getOwner().getAttribute(Attribute.ACTIVE_WEAPON) != weapon) {
// is weapon already owned?
Boolean hasWeapon = (Boolean) weapon.getAttribute(Attribute.PICKED_UP);
if (hasWeapon != null && hasWeapon == true) {
return;
}
if (weapons.containsKey(weapon.getFamily())) {
return;
}
weapon.setAttribute(Attribute.PICKED_UP, Boolean.TRUE);
weapons.put(weapon.getFamily(), weapon);
LOG.info("Adding weapon of family "
+ weapon.getFamily().toString());
if (!getOwner().hasAttribute(Attribute.ACTIVE_WEAPON)) {
setAttribute(Attribute.ACTIVE_WEAPON, weapon);
// set some attributes for the weapon
weapon.setAttribute(Attribute.ORIENTATION_ANGLE,
getAttribute(Attribute.ORIENTATION_ANGLE));
} else {
// remove weapon if picked up
weapon.remove();
}
}
}
}
if (messageType == MessageType.SELECT_WEAPON) {
final Entity weapon = weapons.get(weaponKeyMap.get(data));
if (weapon != null
&& !getAttribute(Attribute.ACTIVE_WEAPON).equals(weapon)) {
getEntityManager().add(weapon);
final Entity oldWeapon = (Entity) getAttribute(Attribute.ACTIVE_WEAPON);
if (oldWeapon != null) {
oldWeapon.remove();
}
setAttribute(Attribute.ACTIVE_WEAPON, weapon);
// set some attributes for the weapon
weapon.setAttribute(Attribute.ORIENTATION_ANGLE,
getAttribute(Attribute.ORIENTATION_ANGLE));
}
}
}
|
diff --git a/src/Hello.java b/src/Hello.java
index 7102314..08a265c 100644
--- a/src/Hello.java
+++ b/src/Hello.java
@@ -1,14 +1,15 @@
public class Hello {
public static void main(String ... arg) {
System.out.println("Hello world");
System.out.println("Hello new commit");
+ System.out.println("Legacy code fix");
}
public void immediateFix() {
}
public void newFunction() {
}
}
| true | true | public static void main(String ... arg) {
System.out.println("Hello world");
System.out.println("Hello new commit");
}
| public static void main(String ... arg) {
System.out.println("Hello world");
System.out.println("Hello new commit");
System.out.println("Legacy code fix");
}
|
diff --git a/pentaho-gwt-widgets/src/org/pentaho/gwt/widgets/client/listbox/CustomListBox.java b/pentaho-gwt-widgets/src/org/pentaho/gwt/widgets/client/listbox/CustomListBox.java
index 86115f2..8723c12 100644
--- a/pentaho-gwt-widgets/src/org/pentaho/gwt/widgets/client/listbox/CustomListBox.java
+++ b/pentaho-gwt-widgets/src/org/pentaho/gwt/widgets/client/listbox/CustomListBox.java
@@ -1,619 +1,619 @@
package org.pentaho.gwt.widgets.client.listbox;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.ui.*;
import com.google.gwt.core.client.GWT;
import org.pentaho.gwt.widgets.client.utils.ElementUtils;
import org.pentaho.gwt.widgets.client.utils.Rectangle;
import java.util.ArrayList;
import java.util.List;
/**
*
* ComplexListBox is a List-style widget can contain custom list-items made (images + text, text + checkboxes)
* This list is displayed as a drop-down style component by default. If the visibleRowCount property is set higher
* than 1 (default), the list is rendered as a multi-line list box.
*
* <P>Usage:
*
* <p>
*
* <pre>
* ComplexListBox list = new ComplexListBox();
*
* list.addItem("Alberta");
* list.addItem("Atlanta");
* list.addItem("San Francisco");
* list.addItem(new DefaultListItem("Testing", new Image("16x16sample.png")));
* list.addItem(new DefaultListItem("Testing 2", new CheckBox()));
*
* list.setVisibleRowCount(6); // turns representation from drop-down to list
*
* list.addChangeListener(new ChangeListener(){
* public void onChange(Widget widget) {
* System.out.println(""+list.getSelectedIdex());
* }
* });
*</pre>
*
* User: NBaker
* Date: Mar 9, 2009
* Time: 11:01:57 AM
*
*/
public class CustomListBox extends HorizontalPanel implements PopupListener, MouseListener, FocusListener, KeyboardListener{
private List<ListItem> items = new ArrayList<ListItem>();
private int selectedIndex = -1;
private DropDownArrow arrow = new DropDownArrow();
private int visible = 1;
private int maxDropVisible = 15;
private VerticalPanel listPanel = new VerticalPanel();
private ScrollPanel listScrollPanel = new ScrollPanel();
// Members for drop-down style
private Grid dropGrid = new Grid(1,2);
private boolean popupShowing = false;
private DropPopupPanel popup = new DropPopupPanel();
private PopupList popupVbox = new PopupList();
private FocusPanel fPanel = new FocusPanel();
private ScrollPanel popupScrollPanel = new ScrollPanel();
private List<ChangeListener> listeners = new ArrayList<ChangeListener>();
private final int spacing = 2;
private int maxHeight, maxWidth, averageHeight; //height and width of largest ListItem
private String primaryStyleName;
private String height, width;
private String popupHeight, popupWidth;
public CustomListBox(){
dropGrid.getColumnFormatter().setWidth(0, "100%");
dropGrid.setWidget(0,1, arrow);
dropGrid.setCellPadding(0);
dropGrid.setCellSpacing(spacing);
updateUI();
// Add List Panel to it's scrollPanel
listScrollPanel.add(listPanel);
listScrollPanel.setHeight("100%");
listScrollPanel.setWidth("100%");
listScrollPanel.getElement().getStyle().setProperty("overflowX","hidden");
//listScrollPanel.getElement().getStyle().setProperty("padding",spacing+"px");
listPanel.setSpacing(spacing);
listPanel.setWidth("100%");
//default to drop-down
fPanel.add(dropGrid);
fPanel.setHeight("100%");
super.add(fPanel);
popup.addPopupListener(this);
popupScrollPanel.add(popupVbox);
popupScrollPanel.getElement().getStyle().setProperty("overflowX","hidden");
popupVbox.setWidth("100%");
popupVbox.setSpacing(spacing);
popup.add(popupScrollPanel);
fPanel.addMouseListener(this);
fPanel.addFocusListener(this);
fPanel.addKeyboardListener(this);
setStyleName("custom-list");
}
/**
* Only {@link: DefaultListItem} and Strings (as labels) may be passed into this Widget
*/
@Override
public void add(Widget child) {
throw new UnsupportedOperationException(
"This panel does not support no-arg add()");
}
/**
* Convenience method to support the more conventional method of child attachment
* @param listItem
*/
public void add(ListItem listItem){
this.addItem(listItem);
}
/**
* Convenience method to support the more conventional method of child attachment
* @param label
*/
public void add(String label){
this.addItem(label);
}
/**
* Adds the given ListItem to the list control.
*
* @param item ListItem
*/
public void addItem(ListItem item){
items.add(item);
item.setListBox(this);
// If first one added, set selectedIndex to 0
if(items.size() == 1){
setSelectedIndex(0);
}
updateUI();
}
/**
* Convenience method creates a {@link: DefaultListItem} with the given text and adds it to the list control
*
* @param label
*/
public void addItem(String label){
DefaultListItem item = new DefaultListItem(label);
items.add(item);
item.setListBox(this);
// If first one added, set selectedIndex to 0
if(items.size() == 1){
setSelectedIndex(0);
}
updateUI();
}
/**
* Returns a list of current ListItems.
*
* @return List of ListItems
*/
public List<ListItem> getItems(){
return items;
}
/**
* Sets the number of items to be displayed at once in the lsit control. If set to 1 (default) the list is rendered
* as a drop-down
*
* @param visibleCount number of rows to be visible.
*/
public void setVisibleRowCount(int visibleCount){
int prevCount = visible;
this.visible = visibleCount;
if(visible > 1 && prevCount == 1){
// switched from drop-down to list
fPanel.remove(dropGrid);
fPanel.add(listScrollPanel);
} else if(visible == 1 && prevCount > 1){
// switched from list to drop-down
fPanel.remove(listScrollPanel);
fPanel.add(dropGrid);
}
updateUI();
}
/**
* Returns the number of rows visible in the list
* @return number of visible rows.
*/
public int getVisibleRowCount(){
return visible;
}
private void updateUI(){
if(visible > 1){
updateList();
} else {
updateDropDown();
}
}
/**
* Returns the number of rows to be displayed in the drop-down popup.
*
* @return number of visible popup items.
*/
public int getMaxDropVisible() {
return maxDropVisible;
}
/**
* Sets the number of items to be visible in the drop-down popup. If set lower than the number of items
* a scroll-bar with provide access to hidden items.
*
* @param maxDropVisible number of items visible in popup.
*/
public void setMaxDropVisible(int maxDropVisible) {
this.maxDropVisible = maxDropVisible;
// Update the popup to respect this value
if(maxHeight > 0){ //Items already added
System.out.println("Max heihgt : "+this.maxDropVisible * maxHeight);
this.popupHeight = this.maxDropVisible * maxHeight + "px";
}
}
private void updateSelectedDropWidget(){
Widget selectedWidget = new Label(""); //Default to show in case of empty sets?
if(selectedIndex >= 0){
selectedWidget = items.get(selectedIndex).getWidgetForDropdown();
} else if(items.size() > 0){
selectedWidget = items.get(0).getWidgetForDropdown();
}
dropGrid.setWidget(0,0, selectedWidget);
}
/**
* Called by updateUI when the list is not a drop-down (visible row count > 1)
*/
private void updateList(){
popupVbox.clear();
maxHeight = 0;
maxWidth = 0;
//actually going to average up the heights
for(ListItem li : this.items){
Widget w = li.getWidget();
Rectangle rect = ElementUtils.getSize(w.getElement());
// we only care about this if the user hasn't specified a height.
if(height == null){
maxHeight += rect.height;
}
maxWidth = Math.max(maxWidth,rect.width);
// Add it to the dropdown
listPanel.add(w);
listPanel.setCellWidth(w, "100%");
}
if(height == null){
maxHeight = Math.round(maxHeight / this.items.size());
}
// we only care about this if the user has specified a visible row count and no heihgt
if(height == null){
this.fPanel.setHeight((this.visible * (maxHeight + spacing)) + "px");
}
if(width == null){
this.fPanel.setWidth(maxWidth + 20 + "px"); //20 is scrollbar space
}
}
/**
* Called by updateUI when the list is a drop-down (visible row count = 1)
*/
private void updateDropDown(){
// Update Shown selection in grid
updateSelectedDropWidget();
// Update popup panel,
// Calculate the size of the largest list item.
popupVbox.clear();
maxWidth = 0;
averageHeight = 0; // Actually used to set the width of the arrow
popupHeight = null;
for(ListItem li : this.items){
Widget w = li.getWidget();
Rectangle rect = ElementUtils.getSize(w.getElement());
maxWidth = Math.max(maxWidth,rect.width);
maxHeight = Math.max(maxHeight,rect.height);
averageHeight += rect.height;
// Add it to the dropdown
popupVbox.add(w);
popupVbox.setCellWidth(w, "100%");
}
// Average the height of the items
if(items.size() > 0){
averageHeight = Math.round(averageHeight / items.size());
}
// Set the size of the drop-down based on the largest list item
if(width == null){
dropGrid.setWidth(maxWidth + (spacing*6) + maxHeight + "px");
this.popupWidth = maxWidth + (spacing*6) + maxHeight + "px";
} else {
dropGrid.setWidth("100%");
}
// Store the the size of the popup to respect MaxDropVisible now that we know the item height
// This cannot be set here as the popup is not visible :(
if(maxDropVisible > 0){
// (Lesser of maxDropVisible or items size) * (Average item height + spacing value)
- this.popupHeight = (Math.min(this.maxDropVisible, this.items.size()) * (averageHeight + this.spacing * this.items.size())) + "px";
+ this.popupHeight = (Math.min(this.maxDropVisible, this.items.size()) * (averageHeight + this.spacing )) + "px";
}
}
/**
* Used internally to hide/show drop-down popup.
*/
private void togglePopup(){
if(popupShowing == false){
popupScrollPanel.setWidth(this.getElement().getOffsetWidth() - 8 +"px");
popup.setPopupPosition(this.getElement().getAbsoluteLeft(), this.getElement().getAbsoluteTop() + this.getElement().getOffsetHeight()+2);
popup.show();
// Set the size of the popup calculated in updateDropDown().
if(this.popupHeight != null){
this.popupScrollPanel.getElement().getStyle().setProperty("height", this.popupHeight);
}
if(this.popupWidth != null){
this.popupScrollPanel.getElement().getStyle().setProperty("width", this.popupWidth);
}
scrollSelectedItemIntoView();
popupShowing = true;
} else {
popup.hide();
fPanel.setFocus(true);
}
}
private void scrollSelectedItemIntoView(){
// Scroll to view currently selected widget
//DOM.scrollIntoView(this.getSelectedItem().getWidget().getElement());
// Side effect of the previous call scrolls the scrollpanel to the right. Compensate here
//popupScrollPanel.setHorizontalScrollPosition(0);
// if the position of the selected item is greater than the height of the scroll area plus it's scroll offset
if( ((this.selectedIndex + 1) * this.averageHeight) > popupScrollPanel.getOffsetHeight() + popupScrollPanel.getScrollPosition()){
popupScrollPanel.setScrollPosition( (((this.selectedIndex ) * this.averageHeight) - popupScrollPanel.getOffsetHeight()) + averageHeight );
return;
}
// if the position of the selected item is Less than the scroll offset
if( ((this.selectedIndex) * this.averageHeight) < popupScrollPanel.getScrollPosition()){
popupScrollPanel.setScrollPosition( ((this.selectedIndex ) * this.averageHeight));
}
}
/**
* Selects the given ListItem in the list.
*
* @param item ListItem to be selected.
*/
public void setSelectedItem(ListItem item){
if(items.contains(item) == false){
throw new RuntimeException("Item not in collection");
}
// Clear previously selected item
if(selectedIndex > -1){
items.get(selectedIndex).onDeselect();
}
if(visible == 1){ // Drop-down mode
if(popupShowing) {
togglePopup();
}
}
setSelectedIndex(items.indexOf(item));
}
/**
* Selects the ListItem at the given index (zero-based)
*
* @param idx index of ListItem to select
*/
public void setSelectedIndex(int idx){
if(idx < 0 || idx > items.size()){
throw new RuntimeException("Index out of bounds: "+ idx);
}
// De-Select the current
if(selectedIndex > -1){
items.get(selectedIndex).onDeselect();
}
selectedIndex = idx;
items.get(idx).onSelect();
for(ChangeListener l : listeners){
l.onChange(this);
}
if(visible == 1){
updateSelectedDropWidget();
scrollSelectedItemIntoView();
}
}
/**
* Registers a ChangeListener with the list.
*
* @param listener ChangeListner
*/
public void addChangeListener(ChangeListener listener){
listeners.add(listener);
}
/**
* Removes to given ChangeListener from list.
*
* @param listener ChangeListener
*/
public void removeChangeListener(ChangeListener listener){
this.listeners.remove(listener);
}
/**
* Returns the selected index of the list (zero-based)
*
* @return Integer index
*/
public int getSelectedIdex(){
return selectedIndex;
}
/**
* Returns the currently selected item
*
* @return currently selected Item
*/
public ListItem getSelectedItem(){
if(selectedIndex < 0){
return null;
}
return items.get(selectedIndex);
}
@Override
public void setStylePrimaryName(String s) {
super.setStylePrimaryName(s);
this.primaryStyleName = s;
// This may have came in late. Update ListItems
for(ListItem item : items){
item.setStylePrimaryName(s);
}
}
@Override
protected void onAttach() {
super.onAttach();
updateUI();
}
@Override
/**
* Calling setHeight will implecitly change the list from a drop-down style to a list style.
*/
public void setHeight(String s) {
this.height = s;
// user has specified height, focusPanel needs to be 100%;
this.fPanel.setHeight(s);
if(visible == 1){
this.setVisibleRowCount(15);
}
super.setHeight(s);
}
@Override
public void setWidth(String s) {
fPanel.setWidth(s);
this.listScrollPanel.setWidth("100%");
this.width = s;
super.setWidth(s);
}
// ======================================= Listener methods ===================================== //
public void onPopupClosed(PopupPanel popupPanel, boolean b) {
this.popupShowing = false;
}
public void onMouseDown(Widget widget, int i, int i1) {}
public void onMouseEnter(Widget widget) {}
public void onMouseLeave(Widget widget) {}
public void onMouseMove(Widget widget, int i, int i1) {}
public void onMouseUp(Widget widget, int i, int i1) {
if(visible == 1){ //drop-down mode
this.togglePopup();
}
}
public void onFocus(Widget widget) {
fPanel.setFocus(true);
}
public void onLostFocus(Widget widget) {}
public void onKeyDown(Widget widget, char c, int i) {}
public void onKeyPress(Widget widget, char c, int i) {}
public void onKeyUp(Widget widget, char c, int i) {
switch(c){
case 38: // UP
if(selectedIndex > 0){
setSelectedIndex(selectedIndex - 1);
}
break;
case 40: // Down
if(selectedIndex < items.size() -1){
setSelectedIndex(selectedIndex + 1);
}
break;
case 27: // ESC
case 13: // Enter
if(popupShowing){
togglePopup();
}
break;
}
}
// ======================================= Inner Classes ===================================== //
/**
* Panel used as a drop-down popup.
*/
private class DropPopupPanel extends PopupPanel {
public DropPopupPanel(){
super(true);
setStyleName("drop-popup");
}
@Override
public boolean onEventPreview(Event event) {
if(DOM.isOrHasChild(CustomListBox.this.getElement(), DOM.eventGetTarget(event))){
return true;
}
return super.onEventPreview(event);
}
}
/**
* Panel contained in the popup
*/
private class PopupList extends VerticalPanel{
public PopupList(){
this.sinkEvents(Event.MOUSEEVENTS);
}
@Override
public void onBrowserEvent(Event event) {
super.onBrowserEvent(event);
}
}
/**
* This is the arrow rendered in the drop-down.
*/
private class DropDownArrow extends SimplePanel{
public DropDownArrow(){
Image img = new Image(GWT.getModuleBaseURL() + "arrow.png");
this.setStylePrimaryName("combo-arrow");
super.add(img);
ElementUtils.preventTextSelection(this.getElement());
}
}
}
| true | true | private void updateDropDown(){
// Update Shown selection in grid
updateSelectedDropWidget();
// Update popup panel,
// Calculate the size of the largest list item.
popupVbox.clear();
maxWidth = 0;
averageHeight = 0; // Actually used to set the width of the arrow
popupHeight = null;
for(ListItem li : this.items){
Widget w = li.getWidget();
Rectangle rect = ElementUtils.getSize(w.getElement());
maxWidth = Math.max(maxWidth,rect.width);
maxHeight = Math.max(maxHeight,rect.height);
averageHeight += rect.height;
// Add it to the dropdown
popupVbox.add(w);
popupVbox.setCellWidth(w, "100%");
}
// Average the height of the items
if(items.size() > 0){
averageHeight = Math.round(averageHeight / items.size());
}
// Set the size of the drop-down based on the largest list item
if(width == null){
dropGrid.setWidth(maxWidth + (spacing*6) + maxHeight + "px");
this.popupWidth = maxWidth + (spacing*6) + maxHeight + "px";
} else {
dropGrid.setWidth("100%");
}
// Store the the size of the popup to respect MaxDropVisible now that we know the item height
// This cannot be set here as the popup is not visible :(
if(maxDropVisible > 0){
// (Lesser of maxDropVisible or items size) * (Average item height + spacing value)
this.popupHeight = (Math.min(this.maxDropVisible, this.items.size()) * (averageHeight + this.spacing * this.items.size())) + "px";
}
}
| private void updateDropDown(){
// Update Shown selection in grid
updateSelectedDropWidget();
// Update popup panel,
// Calculate the size of the largest list item.
popupVbox.clear();
maxWidth = 0;
averageHeight = 0; // Actually used to set the width of the arrow
popupHeight = null;
for(ListItem li : this.items){
Widget w = li.getWidget();
Rectangle rect = ElementUtils.getSize(w.getElement());
maxWidth = Math.max(maxWidth,rect.width);
maxHeight = Math.max(maxHeight,rect.height);
averageHeight += rect.height;
// Add it to the dropdown
popupVbox.add(w);
popupVbox.setCellWidth(w, "100%");
}
// Average the height of the items
if(items.size() > 0){
averageHeight = Math.round(averageHeight / items.size());
}
// Set the size of the drop-down based on the largest list item
if(width == null){
dropGrid.setWidth(maxWidth + (spacing*6) + maxHeight + "px");
this.popupWidth = maxWidth + (spacing*6) + maxHeight + "px";
} else {
dropGrid.setWidth("100%");
}
// Store the the size of the popup to respect MaxDropVisible now that we know the item height
// This cannot be set here as the popup is not visible :(
if(maxDropVisible > 0){
// (Lesser of maxDropVisible or items size) * (Average item height + spacing value)
this.popupHeight = (Math.min(this.maxDropVisible, this.items.size()) * (averageHeight + this.spacing )) + "px";
}
}
|
diff --git a/src/test/task4/CopyUtilsTest.java b/src/test/task4/CopyUtilsTest.java
index 048899c..ab41659 100644
--- a/src/test/task4/CopyUtilsTest.java
+++ b/src/test/task4/CopyUtilsTest.java
@@ -1,20 +1,20 @@
package task4;
import static org.junit.Assert.*;
import org.junit.Test;
public class CopyUtilsTest {
@Test
public void testCopy() throws Exception {
String src = "data/some_text.txt";
- String dst = "data/some_text_copy.txt";
+ String dst = "data/test";
int n = 10;
for (int i = 0; i < n; ++i) {
Thread.sleep(1000);
CopyUtils.copy(src, dst);
}
}
}
| true | true | public void testCopy() throws Exception {
String src = "data/some_text.txt";
String dst = "data/some_text_copy.txt";
int n = 10;
for (int i = 0; i < n; ++i) {
Thread.sleep(1000);
CopyUtils.copy(src, dst);
}
}
| public void testCopy() throws Exception {
String src = "data/some_text.txt";
String dst = "data/test";
int n = 10;
for (int i = 0; i < n; ++i) {
Thread.sleep(1000);
CopyUtils.copy(src, dst);
}
}
|
diff --git a/src/com/wolvencraft/prison/mines/cmd/EditCommand.java b/src/com/wolvencraft/prison/mines/cmd/EditCommand.java
index 6751262..a1b9158 100644
--- a/src/com/wolvencraft/prison/mines/cmd/EditCommand.java
+++ b/src/com/wolvencraft/prison/mines/cmd/EditCommand.java
@@ -1,244 +1,244 @@
/*
* EditCommand.java
*
* PrisonMine
* Copyright (C) 2013 bitWolfy <http://www.wolvencraft.com> and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* 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 com.wolvencraft.prison.mines.cmd;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.List;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.material.MaterialData;
import com.wolvencraft.prison.PrisonSuite;
import com.wolvencraft.prison.hooks.TimedTask;
import com.wolvencraft.prison.mines.CommandManager;
import com.wolvencraft.prison.mines.PrisonMine;
import com.wolvencraft.prison.mines.mine.Mine;
import com.wolvencraft.prison.mines.settings.Language;
import com.wolvencraft.prison.mines.settings.MineData;
import com.wolvencraft.prison.mines.util.Message;
import com.wolvencraft.prison.mines.util.Util;
import com.wolvencraft.prison.mines.util.data.MineBlock;
public class EditCommand implements BaseCommand {
@Override
public boolean run(String[] args) {
Language language = PrisonMine.getLanguage();
Mine curMine = PrisonMine.getCurMine();
if(curMine == null
&& !args[0].equalsIgnoreCase("edit")
&& !args[0].equalsIgnoreCase("delete")) {
Message.sendFormattedError(language.ERROR_MINENOTSELECTED);
return false;
}
if(args[0].equalsIgnoreCase("edit")) {
if(args.length == 1) {
if(PrisonMine.getCurMine() != null) {
Message.sendFormattedSuccess(language.MINE_DESELECTED);
PrisonMine.setCurMine(null);
return true;
} else { getHelp(); return true; }
} else if(args.length == 2) {
if(args[1].equalsIgnoreCase("help")) { getHelp(); return true; }
curMine = Mine.get(args[1]);
if(curMine == null) { Message.sendFormattedError(language.ERROR_MINENAME.replace("<ID>", args[1])); return false; }
PrisonMine.setCurMine(curMine);
Message.sendFormattedSuccess(language.MINE_SELECTED);
return true;
} else { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
} else if(args[0].equalsIgnoreCase("add") || args[0].equalsIgnoreCase("+")) {
if(args.length == 1) { getHelp(); return true; }
if(args.length > 3) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
List<MineBlock> localBlocks = curMine.getLocalBlocks();
if(localBlocks.size() == 0) curMine.addBlock(new MaterialData(Material.AIR), 1);
MaterialData block = Util.getBlock(args[1]);
MineBlock air = curMine.getBlock(new MaterialData(Material.AIR));
if(block == null) { Message.sendFormattedError(language.ERROR_NOSUCHBLOCK.replaceAll("<BLOCK>", args[1])); return false; }
if(block.equals(air.getBlock())) { Message.sendFormattedError(language.ERROR_FUCKIGNNOOB); return false; }
double percent, percentAvailable = air.getChance();
if(args.length == 3) {
String percentString = args[2].replace("%", "").replace(",", ".");
try { percent = Double.parseDouble(percentString); }
catch (NumberFormatException nfe) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
percent = percent / 100;
}
else percent = percentAvailable;
if(percent <= 0) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
if((percentAvailable - percent) < 0) { Message.sendFormattedError("Invalid percentage. Use /mine info " + curMine.getId() + " to review the percentages"); return false; }
else percentAvailable -= percent;
- air.setChance(Double.valueOf(percentAvailable));
+ air.setChance(percentAvailable);
MineBlock index = curMine.getBlock(block);
if(index == null) curMine.addBlock(block, percent);
else index.setChance(index.getChance() + percent);
Message.sendFormattedMine(Util.formatPercent(percent)+ " of " + block.getItemType().toString().toLowerCase().replace("_", " ") + " added to the mine");
Message.sendFormattedMine("Reset the mine for the changes to take effect");
return curMine.saveFile();
} else if(args[0].equalsIgnoreCase("remove") || args[0].equalsIgnoreCase("-")) {
if(args.length == 1) { getHelp(); return true; }
if(args.length > 3) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
MineBlock blockData = curMine.getBlock(Util.getBlock(args[1]));
if(blockData == null) { Message.sendFormattedError("There is no " + ChatColor.RED + args[1] + ChatColor.WHITE + " in mine '" + curMine.getId() + "'"); return false; }
MineBlock air = curMine.getBlock(new MaterialData(Material.AIR));
if(blockData.getBlock().equals(air.getBlock())) { Message.sendFormattedError(language.ERROR_FUCKIGNNOOB); return false; }
double percent = 0;
if(args.length == 3) {
try { percent = NumberFormat.getInstance().parse(args[2].replace("%", "")).doubleValue(); }
catch (ParseException e) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
catch (NumberFormatException nfe) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
percent = percent / 100;
if(percent > blockData.getChance()) percent = blockData.getChance();
air.setChance(air.getChance() + percent);
blockData.setChance(blockData.getChance() - percent);
Message.sendFormattedMine(Util.formatPercent(percent) + " of " + args[1] + " was successfully removed from the mine");
} else {
air.setChance(air.getChance() + blockData.getChance());
curMine.removeBlock(blockData);
Message.sendFormattedMine(args[1] + " was successfully removed from the mine");
}
return curMine.saveFile();
} else if(args[0].equalsIgnoreCase("name")) {
if(args.length == 1) {
curMine.setName("");
Message.sendFormattedMine("Mine display name has been cleared");
return true;
}
if(args.length < 2) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
String name = args[1];
for(int i = 2; i < args.length; i++) name = name + " " + args[i];
curMine.setName(name);
Message.sendFormattedMine("Mine now has a display name '" + ChatColor.GOLD + name + ChatColor.WHITE + "'");
return curMine.saveFile();
} else if(args[0].equalsIgnoreCase("cooldown")) {
if(args.length > 2) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
if(args.length == 1) {
if(curMine.getCooldown()) {
curMine.setCooldownEnabled(false);
Message.sendFormattedMine("Reset cooldown " + ChatColor.RED + "disabled");
}
else {
curMine.setCooldownEnabled(true);
Message.sendFormattedMine("Reset cooldown " + ChatColor.GREEN + "enabled");
}
} else if(args.length == 2) {
int seconds = Util.timeToSeconds(args[1]);
if(seconds == -1) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
curMine.setCooldownPeriod(seconds);
Message.sendFormattedMine("Reset cooldown set to " + ChatColor.GREEN + Util.secondsToTime(seconds));
} else { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
return curMine.saveFile();
} else if(args[0].equalsIgnoreCase("setparent") || args[0].equalsIgnoreCase("link")) {
if(args.length > 2) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
if(args.length == 1) {
if(curMine.getParent() != null) {
Message.sendFormattedMine("Mine is no longer linked to " + ChatColor.RED + curMine.getParent());
curMine.setParent(null);
} else { getHelp(); return true; }
} else {
Mine parentMine = Mine.get(args[1]);
if(parentMine == null) { Message.sendFormattedError(language.ERROR_MINENAME); return false; }
if(parentMine.getId().equalsIgnoreCase(curMine.getId())) { Message.sendFormattedError("The mine cannot be a parent of itself"); return false; }
if(parentMine.hasParent() && parentMine.getSuperParent().getId().equalsIgnoreCase(curMine.getId())) { Message.sendFormattedError("Looping structure detected!"); return false; }
curMine.setParent(args[1]);
Message.sendFormattedMine("Mine is now linked to " + ChatColor.GREEN + args[1]);
}
return curMine.saveFile();
} else if(args[0].equalsIgnoreCase("setwarp")) {
if(args.length != 1) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
curMine.setTpPoint(((Player) CommandManager.getSender()).getLocation());
Message.sendFormattedMine("Mine tp point is set to your current location");
return curMine.saveFile();
} else if(args[0].equalsIgnoreCase("delete") || args[0].equalsIgnoreCase("del")) {
if(args.length == 1 && curMine == null) { getHelp(); return true; }
if(args.length > 2) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
if(args.length != 1) {
curMine = Mine.get(args[1]);
if(curMine == null) { Message.sendFormattedError(language.ERROR_MINENAME); return false; }
}
for(Mine child : curMine.getChildren()) { child.setParent(null); }
for(TimedTask task : PrisonSuite.getLocalTasks()) {
if(task.getName().endsWith(curMine.getId())) task.cancel();
}
PrisonMine.removeMine(curMine);
PrisonMine.setCurMine(curMine);
Message.sendFormattedMine("Mine successfully deleted");
PrisonMine.setCurMine(null);
curMine.deleteFile();
MineData.saveAll();
return true;
} else {
Message.sendFormattedError(language.ERROR_COMMAND);
return false;
}
}
@Override
public void getHelp() {
Message.formatHeader(20, "Editing");
Message.formatHelp("edit", "<id>", "Selects a mine to edit its properties");
Message.formatHelp("edit", "", "Deselects the current mine");
Message.formatHelp("+", "<block> [percentage]", "Adds a block type to the mine");
Message.formatHelp("-", "<block> [percentage]", "Removes the block from the mine");
Message.formatHelp("name", "<name>", "Sets a display name for a mine. Spaces allowed");
Message.formatHelp("cooldown", "", "Toggles the reset cooldown");
Message.formatHelp("cooldown <time>", "", "Sets the cooldown time");
Message.formatHelp("setparent", "<id>", "Links the timers of two mines");
Message.formatHelp("setwarp", "", "Sets the teleportation point for the mine");
Message.formatHelp("delete", "[id]", "Deletes all the mine data");
return;
}
@Override
public void getHelpLine() { Message.formatHelp("edit help", "", "Shows a help page on mine attribute editing", "prison.mine.edit"); }
}
| true | true | public boolean run(String[] args) {
Language language = PrisonMine.getLanguage();
Mine curMine = PrisonMine.getCurMine();
if(curMine == null
&& !args[0].equalsIgnoreCase("edit")
&& !args[0].equalsIgnoreCase("delete")) {
Message.sendFormattedError(language.ERROR_MINENOTSELECTED);
return false;
}
if(args[0].equalsIgnoreCase("edit")) {
if(args.length == 1) {
if(PrisonMine.getCurMine() != null) {
Message.sendFormattedSuccess(language.MINE_DESELECTED);
PrisonMine.setCurMine(null);
return true;
} else { getHelp(); return true; }
} else if(args.length == 2) {
if(args[1].equalsIgnoreCase("help")) { getHelp(); return true; }
curMine = Mine.get(args[1]);
if(curMine == null) { Message.sendFormattedError(language.ERROR_MINENAME.replace("<ID>", args[1])); return false; }
PrisonMine.setCurMine(curMine);
Message.sendFormattedSuccess(language.MINE_SELECTED);
return true;
} else { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
} else if(args[0].equalsIgnoreCase("add") || args[0].equalsIgnoreCase("+")) {
if(args.length == 1) { getHelp(); return true; }
if(args.length > 3) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
List<MineBlock> localBlocks = curMine.getLocalBlocks();
if(localBlocks.size() == 0) curMine.addBlock(new MaterialData(Material.AIR), 1);
MaterialData block = Util.getBlock(args[1]);
MineBlock air = curMine.getBlock(new MaterialData(Material.AIR));
if(block == null) { Message.sendFormattedError(language.ERROR_NOSUCHBLOCK.replaceAll("<BLOCK>", args[1])); return false; }
if(block.equals(air.getBlock())) { Message.sendFormattedError(language.ERROR_FUCKIGNNOOB); return false; }
double percent, percentAvailable = air.getChance();
if(args.length == 3) {
String percentString = args[2].replace("%", "").replace(",", ".");
try { percent = Double.parseDouble(percentString); }
catch (NumberFormatException nfe) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
percent = percent / 100;
}
else percent = percentAvailable;
if(percent <= 0) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
if((percentAvailable - percent) < 0) { Message.sendFormattedError("Invalid percentage. Use /mine info " + curMine.getId() + " to review the percentages"); return false; }
else percentAvailable -= percent;
air.setChance(Double.valueOf(percentAvailable));
MineBlock index = curMine.getBlock(block);
if(index == null) curMine.addBlock(block, percent);
else index.setChance(index.getChance() + percent);
Message.sendFormattedMine(Util.formatPercent(percent)+ " of " + block.getItemType().toString().toLowerCase().replace("_", " ") + " added to the mine");
Message.sendFormattedMine("Reset the mine for the changes to take effect");
return curMine.saveFile();
} else if(args[0].equalsIgnoreCase("remove") || args[0].equalsIgnoreCase("-")) {
if(args.length == 1) { getHelp(); return true; }
if(args.length > 3) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
MineBlock blockData = curMine.getBlock(Util.getBlock(args[1]));
if(blockData == null) { Message.sendFormattedError("There is no " + ChatColor.RED + args[1] + ChatColor.WHITE + " in mine '" + curMine.getId() + "'"); return false; }
MineBlock air = curMine.getBlock(new MaterialData(Material.AIR));
if(blockData.getBlock().equals(air.getBlock())) { Message.sendFormattedError(language.ERROR_FUCKIGNNOOB); return false; }
double percent = 0;
if(args.length == 3) {
try { percent = NumberFormat.getInstance().parse(args[2].replace("%", "")).doubleValue(); }
catch (ParseException e) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
catch (NumberFormatException nfe) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
percent = percent / 100;
if(percent > blockData.getChance()) percent = blockData.getChance();
air.setChance(air.getChance() + percent);
blockData.setChance(blockData.getChance() - percent);
Message.sendFormattedMine(Util.formatPercent(percent) + " of " + args[1] + " was successfully removed from the mine");
} else {
air.setChance(air.getChance() + blockData.getChance());
curMine.removeBlock(blockData);
Message.sendFormattedMine(args[1] + " was successfully removed from the mine");
}
return curMine.saveFile();
} else if(args[0].equalsIgnoreCase("name")) {
if(args.length == 1) {
curMine.setName("");
Message.sendFormattedMine("Mine display name has been cleared");
return true;
}
if(args.length < 2) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
String name = args[1];
for(int i = 2; i < args.length; i++) name = name + " " + args[i];
curMine.setName(name);
Message.sendFormattedMine("Mine now has a display name '" + ChatColor.GOLD + name + ChatColor.WHITE + "'");
return curMine.saveFile();
} else if(args[0].equalsIgnoreCase("cooldown")) {
if(args.length > 2) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
if(args.length == 1) {
if(curMine.getCooldown()) {
curMine.setCooldownEnabled(false);
Message.sendFormattedMine("Reset cooldown " + ChatColor.RED + "disabled");
}
else {
curMine.setCooldownEnabled(true);
Message.sendFormattedMine("Reset cooldown " + ChatColor.GREEN + "enabled");
}
} else if(args.length == 2) {
int seconds = Util.timeToSeconds(args[1]);
if(seconds == -1) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
curMine.setCooldownPeriod(seconds);
Message.sendFormattedMine("Reset cooldown set to " + ChatColor.GREEN + Util.secondsToTime(seconds));
} else { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
return curMine.saveFile();
} else if(args[0].equalsIgnoreCase("setparent") || args[0].equalsIgnoreCase("link")) {
if(args.length > 2) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
if(args.length == 1) {
if(curMine.getParent() != null) {
Message.sendFormattedMine("Mine is no longer linked to " + ChatColor.RED + curMine.getParent());
curMine.setParent(null);
} else { getHelp(); return true; }
} else {
Mine parentMine = Mine.get(args[1]);
if(parentMine == null) { Message.sendFormattedError(language.ERROR_MINENAME); return false; }
if(parentMine.getId().equalsIgnoreCase(curMine.getId())) { Message.sendFormattedError("The mine cannot be a parent of itself"); return false; }
if(parentMine.hasParent() && parentMine.getSuperParent().getId().equalsIgnoreCase(curMine.getId())) { Message.sendFormattedError("Looping structure detected!"); return false; }
curMine.setParent(args[1]);
Message.sendFormattedMine("Mine is now linked to " + ChatColor.GREEN + args[1]);
}
return curMine.saveFile();
} else if(args[0].equalsIgnoreCase("setwarp")) {
if(args.length != 1) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
curMine.setTpPoint(((Player) CommandManager.getSender()).getLocation());
Message.sendFormattedMine("Mine tp point is set to your current location");
return curMine.saveFile();
} else if(args[0].equalsIgnoreCase("delete") || args[0].equalsIgnoreCase("del")) {
if(args.length == 1 && curMine == null) { getHelp(); return true; }
if(args.length > 2) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
if(args.length != 1) {
curMine = Mine.get(args[1]);
if(curMine == null) { Message.sendFormattedError(language.ERROR_MINENAME); return false; }
}
for(Mine child : curMine.getChildren()) { child.setParent(null); }
for(TimedTask task : PrisonSuite.getLocalTasks()) {
if(task.getName().endsWith(curMine.getId())) task.cancel();
}
PrisonMine.removeMine(curMine);
PrisonMine.setCurMine(curMine);
Message.sendFormattedMine("Mine successfully deleted");
PrisonMine.setCurMine(null);
curMine.deleteFile();
MineData.saveAll();
return true;
} else {
Message.sendFormattedError(language.ERROR_COMMAND);
return false;
}
}
| public boolean run(String[] args) {
Language language = PrisonMine.getLanguage();
Mine curMine = PrisonMine.getCurMine();
if(curMine == null
&& !args[0].equalsIgnoreCase("edit")
&& !args[0].equalsIgnoreCase("delete")) {
Message.sendFormattedError(language.ERROR_MINENOTSELECTED);
return false;
}
if(args[0].equalsIgnoreCase("edit")) {
if(args.length == 1) {
if(PrisonMine.getCurMine() != null) {
Message.sendFormattedSuccess(language.MINE_DESELECTED);
PrisonMine.setCurMine(null);
return true;
} else { getHelp(); return true; }
} else if(args.length == 2) {
if(args[1].equalsIgnoreCase("help")) { getHelp(); return true; }
curMine = Mine.get(args[1]);
if(curMine == null) { Message.sendFormattedError(language.ERROR_MINENAME.replace("<ID>", args[1])); return false; }
PrisonMine.setCurMine(curMine);
Message.sendFormattedSuccess(language.MINE_SELECTED);
return true;
} else { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
} else if(args[0].equalsIgnoreCase("add") || args[0].equalsIgnoreCase("+")) {
if(args.length == 1) { getHelp(); return true; }
if(args.length > 3) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
List<MineBlock> localBlocks = curMine.getLocalBlocks();
if(localBlocks.size() == 0) curMine.addBlock(new MaterialData(Material.AIR), 1);
MaterialData block = Util.getBlock(args[1]);
MineBlock air = curMine.getBlock(new MaterialData(Material.AIR));
if(block == null) { Message.sendFormattedError(language.ERROR_NOSUCHBLOCK.replaceAll("<BLOCK>", args[1])); return false; }
if(block.equals(air.getBlock())) { Message.sendFormattedError(language.ERROR_FUCKIGNNOOB); return false; }
double percent, percentAvailable = air.getChance();
if(args.length == 3) {
String percentString = args[2].replace("%", "").replace(",", ".");
try { percent = Double.parseDouble(percentString); }
catch (NumberFormatException nfe) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
percent = percent / 100;
}
else percent = percentAvailable;
if(percent <= 0) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
if((percentAvailable - percent) < 0) { Message.sendFormattedError("Invalid percentage. Use /mine info " + curMine.getId() + " to review the percentages"); return false; }
else percentAvailable -= percent;
air.setChance(percentAvailable);
MineBlock index = curMine.getBlock(block);
if(index == null) curMine.addBlock(block, percent);
else index.setChance(index.getChance() + percent);
Message.sendFormattedMine(Util.formatPercent(percent)+ " of " + block.getItemType().toString().toLowerCase().replace("_", " ") + " added to the mine");
Message.sendFormattedMine("Reset the mine for the changes to take effect");
return curMine.saveFile();
} else if(args[0].equalsIgnoreCase("remove") || args[0].equalsIgnoreCase("-")) {
if(args.length == 1) { getHelp(); return true; }
if(args.length > 3) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
MineBlock blockData = curMine.getBlock(Util.getBlock(args[1]));
if(blockData == null) { Message.sendFormattedError("There is no " + ChatColor.RED + args[1] + ChatColor.WHITE + " in mine '" + curMine.getId() + "'"); return false; }
MineBlock air = curMine.getBlock(new MaterialData(Material.AIR));
if(blockData.getBlock().equals(air.getBlock())) { Message.sendFormattedError(language.ERROR_FUCKIGNNOOB); return false; }
double percent = 0;
if(args.length == 3) {
try { percent = NumberFormat.getInstance().parse(args[2].replace("%", "")).doubleValue(); }
catch (ParseException e) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
catch (NumberFormatException nfe) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
percent = percent / 100;
if(percent > blockData.getChance()) percent = blockData.getChance();
air.setChance(air.getChance() + percent);
blockData.setChance(blockData.getChance() - percent);
Message.sendFormattedMine(Util.formatPercent(percent) + " of " + args[1] + " was successfully removed from the mine");
} else {
air.setChance(air.getChance() + blockData.getChance());
curMine.removeBlock(blockData);
Message.sendFormattedMine(args[1] + " was successfully removed from the mine");
}
return curMine.saveFile();
} else if(args[0].equalsIgnoreCase("name")) {
if(args.length == 1) {
curMine.setName("");
Message.sendFormattedMine("Mine display name has been cleared");
return true;
}
if(args.length < 2) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
String name = args[1];
for(int i = 2; i < args.length; i++) name = name + " " + args[i];
curMine.setName(name);
Message.sendFormattedMine("Mine now has a display name '" + ChatColor.GOLD + name + ChatColor.WHITE + "'");
return curMine.saveFile();
} else if(args[0].equalsIgnoreCase("cooldown")) {
if(args.length > 2) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
if(args.length == 1) {
if(curMine.getCooldown()) {
curMine.setCooldownEnabled(false);
Message.sendFormattedMine("Reset cooldown " + ChatColor.RED + "disabled");
}
else {
curMine.setCooldownEnabled(true);
Message.sendFormattedMine("Reset cooldown " + ChatColor.GREEN + "enabled");
}
} else if(args.length == 2) {
int seconds = Util.timeToSeconds(args[1]);
if(seconds == -1) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
curMine.setCooldownPeriod(seconds);
Message.sendFormattedMine("Reset cooldown set to " + ChatColor.GREEN + Util.secondsToTime(seconds));
} else { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
return curMine.saveFile();
} else if(args[0].equalsIgnoreCase("setparent") || args[0].equalsIgnoreCase("link")) {
if(args.length > 2) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
if(args.length == 1) {
if(curMine.getParent() != null) {
Message.sendFormattedMine("Mine is no longer linked to " + ChatColor.RED + curMine.getParent());
curMine.setParent(null);
} else { getHelp(); return true; }
} else {
Mine parentMine = Mine.get(args[1]);
if(parentMine == null) { Message.sendFormattedError(language.ERROR_MINENAME); return false; }
if(parentMine.getId().equalsIgnoreCase(curMine.getId())) { Message.sendFormattedError("The mine cannot be a parent of itself"); return false; }
if(parentMine.hasParent() && parentMine.getSuperParent().getId().equalsIgnoreCase(curMine.getId())) { Message.sendFormattedError("Looping structure detected!"); return false; }
curMine.setParent(args[1]);
Message.sendFormattedMine("Mine is now linked to " + ChatColor.GREEN + args[1]);
}
return curMine.saveFile();
} else if(args[0].equalsIgnoreCase("setwarp")) {
if(args.length != 1) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
curMine.setTpPoint(((Player) CommandManager.getSender()).getLocation());
Message.sendFormattedMine("Mine tp point is set to your current location");
return curMine.saveFile();
} else if(args[0].equalsIgnoreCase("delete") || args[0].equalsIgnoreCase("del")) {
if(args.length == 1 && curMine == null) { getHelp(); return true; }
if(args.length > 2) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
if(args.length != 1) {
curMine = Mine.get(args[1]);
if(curMine == null) { Message.sendFormattedError(language.ERROR_MINENAME); return false; }
}
for(Mine child : curMine.getChildren()) { child.setParent(null); }
for(TimedTask task : PrisonSuite.getLocalTasks()) {
if(task.getName().endsWith(curMine.getId())) task.cancel();
}
PrisonMine.removeMine(curMine);
PrisonMine.setCurMine(curMine);
Message.sendFormattedMine("Mine successfully deleted");
PrisonMine.setCurMine(null);
curMine.deleteFile();
MineData.saveAll();
return true;
} else {
Message.sendFormattedError(language.ERROR_COMMAND);
return false;
}
}
|
diff --git a/ContentConnectorAPI/src/com/gentics/cr/CRResolvableBean.java b/ContentConnectorAPI/src/com/gentics/cr/CRResolvableBean.java
index 607b65bc..67c272f7 100644
--- a/ContentConnectorAPI/src/com/gentics/cr/CRResolvableBean.java
+++ b/ContentConnectorAPI/src/com/gentics/cr/CRResolvableBean.java
@@ -1,502 +1,506 @@
package com.gentics.cr;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Vector;
import com.gentics.api.lib.exception.UnknownPropertyException;
import com.gentics.api.lib.resolving.PropertyResolver;
import com.gentics.api.lib.resolving.Resolvable;
/**
* Rosolveable Proxy Class. As Resolvsables are not serializable this class gets
* a resolvable and a list of attributes and stores these for further usage as
* serializable bean.
*
* This class also provides various methods to access attributes
*
* Last changed: $Date$
* @version $Revision$
* @author $Author$
*
*/
public class CRResolvableBean implements Serializable, Resolvable{
private static final long serialVersionUID = -8743515908056719834L;
private Collection<CRResolvableBean> childRepository;
private Hashtable<String,Object> attrMap;
private String contentid;
private String obj_id;
private String obj_type;
private String mother_id;
private String mother_type;
private Resolvable resolvable;
/**
* Populate the child elements with the given collection of CRResolvableBeans
* @param childRep
*/
public void fillChildRepository(Collection<CRResolvableBean> childRep)
{
this.childRepository.addAll(childRep);
}
/**
* Get the Child elements.
* @return collection of child elements.
*/
public Collection<CRResolvableBean> getChildRepository()
{
return(this.childRepository);
}
/**
* Set the child elements to the given collection of CRResolvableBeans
* @param children
*/
public void setChildRepository(Collection<CRResolvableBean> children)
{
this.childRepository=children;
}
/**
* Create new instance of CRResolvableBean
*/
public CRResolvableBean()
{
this.contentid="10001";
}
/**
* Create new instance of CRResolvableBean.
* This will generate an empty CRResolvableBean with only the contentid set.
* @param contentid
*/
public CRResolvableBean(String contentid)
{
this.contentid=contentid;
}
/**
* Create new instance of CRResolvableBean
* @param resolvable
* Sets the given resolvable as basis for the CRResolvableBean
* If obj_type of resolvable is 10008 it sets the attribute array to { "binarycontent", "mimetype" }, otherwise to { "binarycontent", "mimetype" }
* If you want to be more specific about the attribute array, use public CRResolvableBean(Resolvable resolvable, String[] attributeNames) instead
*/
public CRResolvableBean(Resolvable resolvable) {
//TODO This is ugly => make more beautiful
if ("10008".equals(resolvable.get("obj_type").toString())) {
init(resolvable, new String[] { "binarycontent", "mimetype" });
} else {
init(resolvable, new String[] { "binarycontent", "mimetype" });
}
}
/**
* make a CRResolvableBean out of a Resolvable
* @param resolvable The Resolvable to be converted to a CRResolveableBean
* @param attributeNames The attributenames as an array of strings that should be fetched from the Resolveable
*/
public CRResolvableBean(Resolvable resolvable, String[] attributeNames) {
init(resolvable, attributeNames);
}
/**
* Initialize the CRResolvableBean with the Resolvable and populate elements / sets the Resolvable as member
* @param resolvable
* @param attributeNames
*/
private void init(Resolvable resolvable, String[] attributeNames) {
if (resolvable != null) {
this.resolvable = resolvable;
this.childRepository = new Vector<CRResolvableBean>();
this.contentid = (String) resolvable.get("contentid");
if(resolvable.get("obj_id")!=null)
this.obj_id = ((Integer) resolvable.get("obj_id")).toString();
if(resolvable.get("obj_type")!=null)
this.obj_type = ((Integer) resolvable.get("obj_type")).toString();
if(resolvable.get("mother_obj_id")!=null)
this.mother_id = ((Integer) resolvable.get("mother_obj_id")).toString();
if(resolvable.get("mother_obj_type")!=null)
this.mother_type = ((Integer) resolvable.get("mother_obj_type")).toString();
this.attrMap = new Hashtable<String,Object>();
if (attributeNames != null) {
ArrayList<String> attributeList = new ArrayList<String>(Arrays.asList(attributeNames));
if(attributeList.contains("binarycontenturl"))
{
this.attrMap.put("binarycontenturl","ccr_bin?contentid="+this.contentid);
attributeList.remove("binarycontenturl");
attributeNames=attributeList.toArray(attributeNames);
}
for (int i = 0; i < attributeNames.length; i++) {
//we have to inspect returned attribute for containing not serializable objects (Resolvables) and convert them into CRResolvableBeans
try {
- this.attrMap.put(attributeNames[i], inspectResolvableAttribute(PropertyResolver.resolve(resolvable, attributeNames[i])));
+ Object o = inspectResolvableAttribute(PropertyResolver.resolve(resolvable, attributeNames[i]));
+ if(o!=null)
+ this.attrMap.put(attributeNames[i], o);
} catch (UnknownPropertyException e) {
- this.attrMap.put(attributeNames[i], inspectResolvableAttribute(resolvable.get(attributeNames[i])));
+ Object o = inspectResolvableAttribute(resolvable.get(attributeNames[i]));
+ if(o!=null)
+ this.attrMap.put(attributeNames[i], o);
}
}
}
}
}
/**
* Helper Method to inspect Attributes given from PropertyResolver or Resolvables theirself for containing not serializable Resolvables
* @param resolvableAttribute The attribute should be inspected
* @return the cleaned up attribute. All Resolvables are converted to CRResolvableBeans. The attribute should be serializable afterwards.
*/
@SuppressWarnings("unchecked")
private Object inspectResolvableAttribute(Object resolvableAttribute){
if(resolvableAttribute instanceof Collection){
//in Collections we must inspect all elements. We assume it is a parameterized Collection
//and therefore we quit if the first Object in the Collection is not a Resolvable
ArrayList<CRResolvableBean> newAttributeObject = new ArrayList<CRResolvableBean>();
for(Iterator<Object> it = ((Collection<Object>) resolvableAttribute).iterator(); it.hasNext(); ){
Object object = it.next();
if(object instanceof Resolvable){
newAttributeObject.add(new CRResolvableBean((Resolvable) object, new String[] {}));
}
else{
return resolvableAttribute;
}
}
return newAttributeObject;
}
else if(resolvableAttribute instanceof Resolvable){
return new CRResolvableBean((Resolvable) resolvableAttribute, new String[] {});
}
else
return resolvableAttribute;
}
/**
* Gets the fetched attributes as Map.
* @return attribute map
*/
public Map<String,Object> getAttrMap() {
return attrMap;
}
/**
* Sets the attributes of the CRResolvableBean to the given map of attributes.
* @param attr
* Checks if attr is instance of Hashtable. If true, it sets attr as the new attribute map. If false, a new Hashtable with the given map as basis is being generated.
*/
public void setAttrMap(Map<String,Object> attr)
{
if(attr instanceof Hashtable)
{
this.attrMap = (Hashtable<String,Object>)attr;
}
else
{
this.attrMap=new Hashtable<String,Object>(attr);
}
}
/**
* Gets the contentid of the CRResolvableBean
* @return contentid
*/
public String getContentid() {
return contentid;
}
/**
* Sets the contentid of the CRResolvableBean
* @param id - contentid
*/
public void setContentid(String id)
{
this.contentid=id;
}
/**
* Gets the mother contentid of the CRResolvableBean
* @return motherid
*/
public String getMother_id() {
return mother_id;
}
/**
* Seths the mother contentid of the CRResolvableBean
* @param id
*/
public void setMother_id(String id)
{
this.mother_id=id;
}
/**
* Gets the type of the mother object
* @return mothertype
*/
public String getMother_type() {
return mother_type;
}
/**
* Sets the type of the mother object
* @param type
*/
public void setMother_type(String type)
{
this.mother_type=type;
}
/**
* Gets the id of the object
* @return objectid
*/
public String getObj_id() {
return obj_id;
}
/**
* Sets the id of the object
* @param id
*/
public void setObj_id(String id)
{
this.obj_id=id;
}
/**
* Gets the type of the Object
* @return objecttype
*/
public String getObj_type() {
return obj_type;
}
/**
* Sets the type of the object
* @param type
*/
public void setObj_type(String type)
{
this.obj_type=type;
}
/**
* Returns true if this CRResolvableBean holds binary content
* @return boolean
*/
public boolean isBinary() {
//TODO this is ugly => make more beautiful
if(this.attrMap.containsKey("binarycontent") && this.attrMap.get("binarycontent")!=null)
{
return(true);
}
else if ("10008".equals(this.getObj_type())) {
return true;
} else {
return false;
}
}
/**
* Gets the mimetype of the CRResolvableBean
* @return
*/
public String getMimetype() {
return (String) this.attrMap.get("mimetype");
}
/**
* Returns the content attribute as string
* @return content
*/
public String getContent() {
Object o = this.get("content");
try
{
return (String) o;
}
catch(ClassCastException ex)
{
//If type is not String then assume that byte[] would do the trick
//Not very clean
return new String((byte[]) o);
}
}
/**
* Gets the Content as String using the given encoding
* @param encoding
* Has to be a supported charset
* US-ASCII Seven-bit ASCII, a.k.a. ISO646-US, a.k.a. the Basic Latin block of the Unicode character set
* ISO-8859-1 ISO Latin Alphabet No. 1, a.k.a. ISO-LATIN-1
* UTF-8 Eight-bit UCS Transformation Format
* UTF-16BE Sixteen-bit UCS Transformation Format, big-endian byte order
* UTF-16LE Sixteen-bit UCS Transformation Format, little-endian byte order
* UTF-16 Sixteen-bit UCS Transformation Format, byte order identified by an optional byte-order mark
* @return content
*/
public String getContent(String encoding) {
Object bValue = this.get("content");
String value="";
if(bValue!=null && bValue.getClass()==String.class)
{
value=(String)bValue;
}
else
{
try {
value = new String(getBytes(bValue),encoding);
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
}
return(value);
}
/**
* Gets the binary content if it is set otherwise returns null
* @return binary content as array of bytes
*/
public byte[] getBinaryContent() {
Object o = this.get("binarycontent");
if(o instanceof String)
{
return ((String)o).getBytes();
}
else
{
return (byte[]) o;
}
}
/**
* Gets the binary content as InputStream if it is set otherwise returns null
* @return
*/
public InputStream getBinaryContentAsStream()
{
byte[] buf = getBinaryContent();
InputStream os=null;
if(buf!=null)
{
os = new ByteArrayInputStream(getBinaryContent());
}
return(os);
}
/**
* Gets the value of the requested attribute
* Will first try to fetch the attribute from the Beans attribute array.
* If attribute can not be fetched and a base resolvable is set, then it tries to fetch the attribute over the resolvable
* @param attribute requested attribute name
* @return value of attribute or null if value is not set
*/
public Object get(String attribute) {
if("contentid".equalsIgnoreCase(attribute)){
return this.getContentid();
}
else if(this.attrMap!=null && this.attrMap.containsKey(attribute)){
return this.attrMap.get(attribute);
}
else if(this.resolvable!=null){
//if we are returning an attribute from an resolvable we must inspect it for containing not serializable Objects
return inspectResolvableAttribute(this.resolvable.get(attribute));
}
else
return(null);
}
/**
* Sets the value of the requested attribute
* @param attribute - requested attribute name
* @param obj - value of attribute
*/
public void set(String attribute, Object obj) {
if("contentid".equals(attribute)){
this.setContentid((String) obj);
}
else
{
if(this.attrMap==null)this.attrMap=new Hashtable<String,Object>();
this.attrMap.put(attribute, obj);
}
}
/**
* Converts an Object to an array of bytes
* @param Object to convert
* @return byte[] - converted object
*/
private byte[] getBytes(Object obj) throws java.io.IOException{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
oos.flush();
oos.close();
bos.close();
byte [] data = bos.toByteArray();
return data;
}
/**
* CRResolvableBean is always able to resolve properties
* @return true
*/
public boolean canResolve() {
return true;
}
/**
* Gets the value of the requested attribute.
* Alias for get(String key)
* @param key requested attribute name
* @return value of attribute
*/
public Object getProperty(String key) {
return get(key);
}
/**
* A String representation of this CRResolvableBean instance
* @return String contentid
*/
public String toString()
{
return this.getContentid();
}
}
| false | true | private void init(Resolvable resolvable, String[] attributeNames) {
if (resolvable != null) {
this.resolvable = resolvable;
this.childRepository = new Vector<CRResolvableBean>();
this.contentid = (String) resolvable.get("contentid");
if(resolvable.get("obj_id")!=null)
this.obj_id = ((Integer) resolvable.get("obj_id")).toString();
if(resolvable.get("obj_type")!=null)
this.obj_type = ((Integer) resolvable.get("obj_type")).toString();
if(resolvable.get("mother_obj_id")!=null)
this.mother_id = ((Integer) resolvable.get("mother_obj_id")).toString();
if(resolvable.get("mother_obj_type")!=null)
this.mother_type = ((Integer) resolvable.get("mother_obj_type")).toString();
this.attrMap = new Hashtable<String,Object>();
if (attributeNames != null) {
ArrayList<String> attributeList = new ArrayList<String>(Arrays.asList(attributeNames));
if(attributeList.contains("binarycontenturl"))
{
this.attrMap.put("binarycontenturl","ccr_bin?contentid="+this.contentid);
attributeList.remove("binarycontenturl");
attributeNames=attributeList.toArray(attributeNames);
}
for (int i = 0; i < attributeNames.length; i++) {
//we have to inspect returned attribute for containing not serializable objects (Resolvables) and convert them into CRResolvableBeans
try {
this.attrMap.put(attributeNames[i], inspectResolvableAttribute(PropertyResolver.resolve(resolvable, attributeNames[i])));
} catch (UnknownPropertyException e) {
this.attrMap.put(attributeNames[i], inspectResolvableAttribute(resolvable.get(attributeNames[i])));
}
}
}
}
}
| private void init(Resolvable resolvable, String[] attributeNames) {
if (resolvable != null) {
this.resolvable = resolvable;
this.childRepository = new Vector<CRResolvableBean>();
this.contentid = (String) resolvable.get("contentid");
if(resolvable.get("obj_id")!=null)
this.obj_id = ((Integer) resolvable.get("obj_id")).toString();
if(resolvable.get("obj_type")!=null)
this.obj_type = ((Integer) resolvable.get("obj_type")).toString();
if(resolvable.get("mother_obj_id")!=null)
this.mother_id = ((Integer) resolvable.get("mother_obj_id")).toString();
if(resolvable.get("mother_obj_type")!=null)
this.mother_type = ((Integer) resolvable.get("mother_obj_type")).toString();
this.attrMap = new Hashtable<String,Object>();
if (attributeNames != null) {
ArrayList<String> attributeList = new ArrayList<String>(Arrays.asList(attributeNames));
if(attributeList.contains("binarycontenturl"))
{
this.attrMap.put("binarycontenturl","ccr_bin?contentid="+this.contentid);
attributeList.remove("binarycontenturl");
attributeNames=attributeList.toArray(attributeNames);
}
for (int i = 0; i < attributeNames.length; i++) {
//we have to inspect returned attribute for containing not serializable objects (Resolvables) and convert them into CRResolvableBeans
try {
Object o = inspectResolvableAttribute(PropertyResolver.resolve(resolvable, attributeNames[i]));
if(o!=null)
this.attrMap.put(attributeNames[i], o);
} catch (UnknownPropertyException e) {
Object o = inspectResolvableAttribute(resolvable.get(attributeNames[i]));
if(o!=null)
this.attrMap.put(attributeNames[i], o);
}
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.