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/org/jruby/javasupport/JavaClass.java b/src/org/jruby/javasupport/JavaClass.java index 3faf5a2d8..246c33349 100644 --- a/src/org/jruby/javasupport/JavaClass.java +++ b/src/org/jruby/javasupport/JavaClass.java @@ -1,399 +1,399 @@ /***** 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) 2002-2004 Anders Bengtsson <[email protected]> * Copyright (C) 2002-2004 Jan Arne Petersen <[email protected]> * Copyright (C) 2004 Thomas E Enebo <[email protected]> * Copyright (C) 2004 Stefan Matthias Aust <[email protected]> * Copyright (C) 2004 David Corbin <[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.javasupport; import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import org.jruby.Ruby; import org.jruby.RubyArray; import org.jruby.RubyBoolean; import org.jruby.RubyClass; import org.jruby.RubyFixnum; import org.jruby.RubyInteger; import org.jruby.RubyModule; import org.jruby.RubyString; import org.jruby.exceptions.NameError; import org.jruby.exceptions.TypeError; import org.jruby.runtime.CallbackFactory; import org.jruby.runtime.builtin.IRubyObject; public class JavaClass extends JavaObject { private JavaClass(Ruby runtime, Class javaClass) { super(runtime, (RubyClass) runtime.getClasses().getClassFromPath("Java::JavaClass"), javaClass); } public static JavaClass get(Ruby runtime, Class klass) { JavaClass javaClass = runtime.getJavaSupport().getJavaClassFromCache(klass); if (javaClass == null) { javaClass = new JavaClass(runtime, klass); runtime.getJavaSupport().putJavaClassIntoCache(javaClass); } return javaClass; } public static RubyClass createJavaClassClass(Ruby runtime, RubyModule javaModule) { - RubyClass result = javaModule.defineClassUnder("JavaClass", runtime.getClasses().getObjectClass()); + RubyClass result = javaModule.defineClassUnder("JavaClass", runtime.getClasses().getJavaObjectClass()); CallbackFactory callbackFactory = runtime.callbackFactory(JavaClass.class); result.includeModule(runtime.getClasses().getComparableModule()); JavaObject.registerRubyMethods(runtime, result); result.defineSingletonMethod("for_name", callbackFactory.getSingletonMethod("for_name", IRubyObject.class)); result.defineMethod("public?", callbackFactory.getMethod("public_p")); result.defineMethod("final?", callbackFactory.getMethod("final_p")); result.defineMethod("interface?", callbackFactory.getMethod("interface_p")); result.defineMethod("array?", callbackFactory.getMethod("array_p")); result.defineMethod("name", callbackFactory.getMethod("name")); result.defineMethod("to_s", callbackFactory.getMethod("name")); result.defineMethod("superclass", callbackFactory.getMethod("superclass")); result.defineMethod("<=>", callbackFactory.getMethod("op_cmp", IRubyObject.class)); result.defineMethod("java_instance_methods", callbackFactory.getMethod("java_instance_methods")); result.defineMethod("java_class_methods", callbackFactory.getMethod("java_class_methods")); result.defineMethod("java_method", callbackFactory.getOptMethod("java_method")); result.defineMethod("constructors", callbackFactory.getMethod("constructors")); result.defineMethod("constructor", callbackFactory.getOptMethod("constructor")); result.defineMethod("array_class", callbackFactory.getMethod("array_class")); result.defineMethod("new_array", callbackFactory.getMethod("new_array", IRubyObject.class)); result.defineMethod("fields", callbackFactory.getMethod("fields")); result.defineMethod("field", callbackFactory.getMethod("field", IRubyObject.class)); result.defineMethod("interfaces", callbackFactory.getMethod("interfaces")); result.defineMethod("primitive?", callbackFactory.getMethod("primitive_p")); result.defineMethod("assignable_from?", callbackFactory.getMethod("assignable_from_p", IRubyObject.class)); result.defineMethod("component_type", callbackFactory.getMethod("component_type")); result.defineMethod("declared_instance_methods", callbackFactory.getMethod("declared_instance_methods")); result.defineMethod("declared_class_methods", callbackFactory.getMethod("declared_class_methods")); result.defineMethod("declared_fields", callbackFactory.getMethod("declared_fields")); result.defineMethod("declared_field", callbackFactory.getMethod("declared_field", IRubyObject.class)); result.defineMethod("declared_constructors", callbackFactory.getMethod("declared_constructors")); result.defineMethod("declared_constructor", callbackFactory.getOptMethod("declared_constructor")); result.defineMethod("declared_method", callbackFactory.getOptMethod("declared_method")); result.getMetaClass().undefineMethod("new"); return result; } public static JavaClass for_name(IRubyObject recv, IRubyObject name) { String className = name.asSymbol(); Class klass = recv.getRuntime().getJavaSupport().loadJavaClass(className); return JavaClass.get(recv.getRuntime(), klass); } public RubyBoolean public_p() { return getRuntime().newBoolean(Modifier.isPublic(javaClass().getModifiers())); } Class javaClass() { return (Class) getValue(); } public RubyBoolean final_p() { return getRuntime().newBoolean(Modifier.isFinal(javaClass().getModifiers())); } public RubyBoolean interface_p() { return getRuntime().newBoolean(javaClass().isInterface()); } public RubyBoolean array_p() { return getRuntime().newBoolean(javaClass().isArray()); } public RubyString name() { return getRuntime().newString(javaClass().getName()); } public IRubyObject superclass() { Class superclass = javaClass().getSuperclass(); if (superclass == null) { return getRuntime().getNil(); } return JavaClass.get(getRuntime(), superclass); } public RubyFixnum op_cmp(IRubyObject other) { if (! (other instanceof JavaClass)) { throw getRuntime().newTypeError("<=> requires JavaClass (" + other.getType() + " given)"); } JavaClass otherClass = (JavaClass) other; if (this.javaClass() == otherClass.javaClass()) { return getRuntime().newFixnum(0); } if (otherClass.javaClass().isAssignableFrom(this.javaClass())) { return getRuntime().newFixnum(-1); } return getRuntime().newFixnum(1); } public RubyArray java_instance_methods() { return java_methods(javaClass().getMethods(), false); } public RubyArray declared_instance_methods() { return java_methods(javaClass().getDeclaredMethods(), false); } private RubyArray java_methods(Method[] methods, boolean isStatic) { RubyArray result = getRuntime().newArray(methods.length); for (int i = 0; i < methods.length; i++) { Method method = methods[i]; if (isStatic == Modifier.isStatic(method.getModifiers())) { result.append(JavaMethod.create(getRuntime(), method)); } } return result; } public RubyArray java_class_methods() { return java_methods(javaClass().getMethods(), true); } public RubyArray declared_class_methods() { return java_methods(javaClass().getDeclaredMethods(), true); } public JavaMethod java_method(IRubyObject[] args) throws ClassNotFoundException { String methodName = args[0].asSymbol(); Class[] argumentTypes = buildArgumentTypes(args); return JavaMethod.create(getRuntime(), javaClass(), methodName, argumentTypes); } public JavaMethod declared_method(IRubyObject[] args) throws ClassNotFoundException { String methodName = args[0].asSymbol(); Class[] argumentTypes = buildArgumentTypes(args); return JavaMethod.createDeclared(getRuntime(), javaClass(), methodName, argumentTypes); } private Class[] buildArgumentTypes(IRubyObject[] args) throws ClassNotFoundException { if (args.length < 1) { throw getRuntime().newArgumentError(args.length, 1); } Class[] argumentTypes = new Class[args.length - 1]; for (int i = 1; i < args.length; i++) { JavaClass type = for_name(this, args[i]); argumentTypes[i - 1] = type.javaClass(); } return argumentTypes; } public RubyArray constructors() { return buildConstructors(javaClass().getConstructors()); } public RubyArray declared_constructors() { return buildConstructors(javaClass().getDeclaredConstructors()); } private RubyArray buildConstructors(Constructor[] constructors) { RubyArray result = getRuntime().newArray(constructors.length); for (int i = 0; i < constructors.length; i++) { result.append(new JavaConstructor(getRuntime(), constructors[i])); } return result; } public JavaConstructor constructor(IRubyObject[] args) { try { Class[] parameterTypes = buildClassArgs(args); Constructor constructor; constructor = javaClass().getConstructor(parameterTypes); return new JavaConstructor(getRuntime(), constructor); } catch (NoSuchMethodException nsme) { throw new NameError(getRuntime(), "no matching java constructor"); } } public JavaConstructor declared_constructor(IRubyObject[] args) { try { Class[] parameterTypes = buildClassArgs(args); Constructor constructor; constructor = javaClass().getDeclaredConstructor (parameterTypes); return new JavaConstructor(getRuntime(), constructor); } catch (NoSuchMethodException nsme) { throw new NameError(getRuntime(), "no matching java constructor"); } } private Class[] buildClassArgs(IRubyObject[] args) { Class[] parameterTypes = new Class[args.length]; for (int i = 0; i < args.length; i++) { String name = args[i].asSymbol(); parameterTypes[i] = getRuntime().getJavaSupport().loadJavaClass(name); } return parameterTypes; } public JavaClass array_class() { return JavaClass.get(getRuntime(), Array.newInstance(javaClass(), 0).getClass()); } public JavaObject new_array(IRubyObject lengthArgument) { if (! (lengthArgument instanceof RubyInteger)) { throw getRuntime().newTypeError(lengthArgument, getRuntime().getClasses().getIntegerClass()); } int length = (int) ((RubyInteger) lengthArgument).getLongValue(); return new JavaArray(getRuntime(), Array.newInstance(javaClass(), length)); } public RubyArray fields() { return buildFieldResults(javaClass().getFields()); } public RubyArray declared_fields() { return buildFieldResults(javaClass().getDeclaredFields()); } private RubyArray buildFieldResults(Field[] fields) { RubyArray result = getRuntime().newArray(fields.length); for (int i = 0; i < fields.length; i++) { Field field = fields[i]; result.append(getRuntime().newString(field.getName())); } return result; } public JavaField field(IRubyObject name) { String stringName = name.asSymbol(); try { Field field = javaClass().getField(stringName); return new JavaField(getRuntime(),field); } catch (NoSuchFieldException nsfe) { throw new NameError(getRuntime(), undefinedFieldMessage(stringName)); } } public JavaField declared_field(IRubyObject name) { String stringName = name.asSymbol(); try { Field field = javaClass().getDeclaredField(stringName); return new JavaField(getRuntime(),field); } catch (NoSuchFieldException nsfe) { throw new NameError(getRuntime(), undefinedFieldMessage(stringName)); } } private String undefinedFieldMessage(String stringName) { return "undefined field '" + stringName + "' for class '" + javaClass().getName() + "'"; } public RubyArray interfaces() { Class[] interfaces = javaClass().getInterfaces(); RubyArray result = getRuntime().newArray(interfaces.length); for (int i = 0; i < interfaces.length; i++) { result.append(JavaClass.get(getRuntime(), interfaces[i])); } return result; } public RubyBoolean primitive_p() { return getRuntime().newBoolean(isPrimitive()); } public RubyBoolean assignable_from_p(IRubyObject other) { if (! (other instanceof JavaClass)) { throw getRuntime().newTypeError("assignable_from requires JavaClass (" + other.getType() + " given)"); } Class otherClass = ((JavaClass) other).javaClass(); if (!javaClass().isPrimitive() && otherClass == Void.TYPE || javaClass().isAssignableFrom(otherClass)) { return getRuntime().getTrue(); } otherClass = JavaUtil.primitiveToWrapper(otherClass); Class thisJavaClass = JavaUtil.primitiveToWrapper(javaClass()); if (thisJavaClass.isAssignableFrom(otherClass)) { return getRuntime().getTrue(); } if (Number.class.isAssignableFrom(thisJavaClass)) { if (Number.class.isAssignableFrom(otherClass)) { return getRuntime().getTrue(); } if (otherClass.equals(Character.class)) { return getRuntime().getTrue(); } } if (thisJavaClass.equals(Character.class)) { if (Number.class.isAssignableFrom(otherClass)) { return getRuntime().getTrue(); } } return getRuntime().getFalse(); } private boolean isPrimitive() { return javaClass().isPrimitive(); } public JavaClass component_type() { if (! javaClass().isArray()) { throw new TypeError(getRuntime(), "not a java array-class"); } return JavaClass.get(getRuntime(), javaClass().getComponentType()); } }
true
true
public static RubyClass createJavaClassClass(Ruby runtime, RubyModule javaModule) { RubyClass result = javaModule.defineClassUnder("JavaClass", runtime.getClasses().getObjectClass()); CallbackFactory callbackFactory = runtime.callbackFactory(JavaClass.class); result.includeModule(runtime.getClasses().getComparableModule()); JavaObject.registerRubyMethods(runtime, result); result.defineSingletonMethod("for_name", callbackFactory.getSingletonMethod("for_name", IRubyObject.class)); result.defineMethod("public?", callbackFactory.getMethod("public_p")); result.defineMethod("final?", callbackFactory.getMethod("final_p")); result.defineMethod("interface?", callbackFactory.getMethod("interface_p")); result.defineMethod("array?", callbackFactory.getMethod("array_p")); result.defineMethod("name", callbackFactory.getMethod("name")); result.defineMethod("to_s", callbackFactory.getMethod("name")); result.defineMethod("superclass", callbackFactory.getMethod("superclass")); result.defineMethod("<=>", callbackFactory.getMethod("op_cmp", IRubyObject.class)); result.defineMethod("java_instance_methods", callbackFactory.getMethod("java_instance_methods")); result.defineMethod("java_class_methods", callbackFactory.getMethod("java_class_methods")); result.defineMethod("java_method", callbackFactory.getOptMethod("java_method")); result.defineMethod("constructors", callbackFactory.getMethod("constructors")); result.defineMethod("constructor", callbackFactory.getOptMethod("constructor")); result.defineMethod("array_class", callbackFactory.getMethod("array_class")); result.defineMethod("new_array", callbackFactory.getMethod("new_array", IRubyObject.class)); result.defineMethod("fields", callbackFactory.getMethod("fields")); result.defineMethod("field", callbackFactory.getMethod("field", IRubyObject.class)); result.defineMethod("interfaces", callbackFactory.getMethod("interfaces")); result.defineMethod("primitive?", callbackFactory.getMethod("primitive_p")); result.defineMethod("assignable_from?", callbackFactory.getMethod("assignable_from_p", IRubyObject.class)); result.defineMethod("component_type", callbackFactory.getMethod("component_type")); result.defineMethod("declared_instance_methods", callbackFactory.getMethod("declared_instance_methods")); result.defineMethod("declared_class_methods", callbackFactory.getMethod("declared_class_methods")); result.defineMethod("declared_fields", callbackFactory.getMethod("declared_fields")); result.defineMethod("declared_field", callbackFactory.getMethod("declared_field", IRubyObject.class)); result.defineMethod("declared_constructors", callbackFactory.getMethod("declared_constructors")); result.defineMethod("declared_constructor", callbackFactory.getOptMethod("declared_constructor")); result.defineMethod("declared_method", callbackFactory.getOptMethod("declared_method")); result.getMetaClass().undefineMethod("new"); return result; }
public static RubyClass createJavaClassClass(Ruby runtime, RubyModule javaModule) { RubyClass result = javaModule.defineClassUnder("JavaClass", runtime.getClasses().getJavaObjectClass()); CallbackFactory callbackFactory = runtime.callbackFactory(JavaClass.class); result.includeModule(runtime.getClasses().getComparableModule()); JavaObject.registerRubyMethods(runtime, result); result.defineSingletonMethod("for_name", callbackFactory.getSingletonMethod("for_name", IRubyObject.class)); result.defineMethod("public?", callbackFactory.getMethod("public_p")); result.defineMethod("final?", callbackFactory.getMethod("final_p")); result.defineMethod("interface?", callbackFactory.getMethod("interface_p")); result.defineMethod("array?", callbackFactory.getMethod("array_p")); result.defineMethod("name", callbackFactory.getMethod("name")); result.defineMethod("to_s", callbackFactory.getMethod("name")); result.defineMethod("superclass", callbackFactory.getMethod("superclass")); result.defineMethod("<=>", callbackFactory.getMethod("op_cmp", IRubyObject.class)); result.defineMethod("java_instance_methods", callbackFactory.getMethod("java_instance_methods")); result.defineMethod("java_class_methods", callbackFactory.getMethod("java_class_methods")); result.defineMethod("java_method", callbackFactory.getOptMethod("java_method")); result.defineMethod("constructors", callbackFactory.getMethod("constructors")); result.defineMethod("constructor", callbackFactory.getOptMethod("constructor")); result.defineMethod("array_class", callbackFactory.getMethod("array_class")); result.defineMethod("new_array", callbackFactory.getMethod("new_array", IRubyObject.class)); result.defineMethod("fields", callbackFactory.getMethod("fields")); result.defineMethod("field", callbackFactory.getMethod("field", IRubyObject.class)); result.defineMethod("interfaces", callbackFactory.getMethod("interfaces")); result.defineMethod("primitive?", callbackFactory.getMethod("primitive_p")); result.defineMethod("assignable_from?", callbackFactory.getMethod("assignable_from_p", IRubyObject.class)); result.defineMethod("component_type", callbackFactory.getMethod("component_type")); result.defineMethod("declared_instance_methods", callbackFactory.getMethod("declared_instance_methods")); result.defineMethod("declared_class_methods", callbackFactory.getMethod("declared_class_methods")); result.defineMethod("declared_fields", callbackFactory.getMethod("declared_fields")); result.defineMethod("declared_field", callbackFactory.getMethod("declared_field", IRubyObject.class)); result.defineMethod("declared_constructors", callbackFactory.getMethod("declared_constructors")); result.defineMethod("declared_constructor", callbackFactory.getOptMethod("declared_constructor")); result.defineMethod("declared_method", callbackFactory.getOptMethod("declared_method")); result.getMetaClass().undefineMethod("new"); return result; }
diff --git a/src/org/startsmall/openalarm/Alarms.java b/src/org/startsmall/openalarm/Alarms.java index bc79784..bb73315 100644 --- a/src/org/startsmall/openalarm/Alarms.java +++ b/src/org/startsmall/openalarm/Alarms.java @@ -1,860 +1,868 @@ /** * @file Alarms.java * @author <[email protected]> * @date Wed Sep 30 16:47:42 2009 * * @brief Utility class. * * */ package org.startsmall.openalarm; import android.app.AlarmManager; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.database.Cursor; import android.provider.BaseColumns; import android.provider.Settings; import android.net.Uri; import android.util.Log; import android.text.format.DateUtils; import android.text.TextUtils; import android.widget.Toast; import java.util.Calendar; import java.util.Date; import java.text.DateFormat; import java.util.Iterator; import java.util.List; import java.util.LinkedList; import java.text.SimpleDateFormat; /** * * */ public class Alarms { private static final String TAG = "Alarms"; /** * Authority of this application. * <p>Value: org.startsmall.openalarm</p> */ public static final String CONTENT_URI_AUTH = "org.startsmall.openalarm"; /** * Alarm alert action string. * <p>Value: org.startsmall.openalarm.HANDLE_ALARM</p> */ public static final String HANDLE_ALARM = CONTENT_URI_AUTH + ".HANDLE_ALARM"; /** * Action used to launch ActionDispatcher receiver. * <p>Value: org.startsmall.openalarm.DISPATCH_ACTION</p> */ // public static final String DISPATCH_ACTION = CONTENT_URI_AUTH + ".DISPATCH_ACTION"; /** * Content URI of this application. * * <p>Value: content://org.startsmall.openalarm</p> */ public static final String CONTENT_URI = "content://" + CONTENT_URI_AUTH; /** * Content URI for all alarms * * <p>Value: content://org.startsmall.openalarm/alarms</p> */ public static final String CONTENT_URI_PATH = "alarms"; public static final String CONTENT_URI_ALL_ALARMS = CONTENT_URI + "/" + CONTENT_URI_PATH; /** * Content URI for a single alarm * * <p>Value: content://org.startsmall.openalarm/alarms/#</p> */ public static final String CONTENT_URI_SINGLE_ALARM = CONTENT_URI_ALL_ALARMS + "/#"; /** * Convenient java.util.Calendar instance. * */ private static final Calendar CALENDAR = Calendar.getInstance(); public static Calendar getCalendarInstance() { CALENDAR.setTimeInMillis(System.currentTimeMillis()); return CALENDAR; } public static final String PREFERENCE_FILE_FOR_SNOOZED_ALARM = "snoozed_alarm"; private static final String USER_APK_DIR = "/data/app"; /***************************************************************** * Constants used in content provider and SQLiteDatabase. * *****************************************************************/ public static class AlarmColumns implements BaseColumns { /// Default sort order public static final String DEFAULT_SORT_ORDER = "_id ASC"; //// Inherited fields : _ID /// Label of this alarm public static final String LABEL = "label"; /// Hour in 24-hour (0 - 23) public static final String HOUR = "hour"; /// Minutes (0 - 59) public static final String MINUTES = "minutes"; /// Go off time in milliseconds public static final String AT_TIME_IN_MILLIS = "time"; /// Days this alarm works in this week. public static final String REPEAT_DAYS = "repeat_days"; /// Whether or not this alarm is active currently public static final String ENABLED = "enabled"; /// Audio to play when alarm triggers. public static final String HANDLER = "handler"; /// Audio to play when alarm triggers. public static final String EXTRA = "extra"; /** * Columns that will be pulled from a row. These should * be in sync with PROJECTION indexes. * */ public static final String[] QUERY_COLUMNS = { _ID, LABEL, HOUR, MINUTES, AT_TIME_IN_MILLIS, REPEAT_DAYS, ENABLED, HANDLER, EXTRA}; /** * */ public static final int PROJECTION_ID_INDEX = 0; public static final int PROJECTION_LABEL_INDEX = 1; public static final int PROJECTION_HOUR_INDEX = 2; public static final int PROJECTION_MINUTES_INDEX = 3; public static final int PROJECTION_AT_TIME_IN_MILLIS_INDEX = 4; public static final int PROJECTION_REPEAT_DAYS_INDEX = 5; public static final int PROJECTION_ENABLED_INDEX = 6; public static final int PROJECTION_HANDLER_INDEX = 7; public static final int PROJECTION_EXTRA_INDEX = 8; } /** * Suppress default constructor for noninstantiability. */ private Alarms() {} /****************************************************************** * Encoder/Decode repeat days. ******************************************************************/ public static class RepeatWeekdays { /** * 0x01 Calendar.SUNDAY * 0x02 Calendar.MONDAY * 0x04 Calendar.TUESDAY * 0x08 Calendar.WEDNESDAY * 0x10 Calendar.THURSDAY * 0x20 Calendar.FRIDAY * 0x40 Calendar.SATURDAY * * 0x7F On everyday */ /** * Suppress default constructor for noninstantiability. */ private RepeatWeekdays() {} public static boolean isSet(int code, int day) { return (code & encode(day)) > 0; } public static int set(int code, int day, boolean enabled) { if(enabled) { code = code | encode(day); } else { code = code & ~encode(day); } return code; } private static int encode(int day) { if(day < Calendar.SUNDAY || day > Calendar.SATURDAY) { throw new IllegalArgumentException( "Weekday must be among SUNDAY to SATURDAY"); } return (1 << (day - 1)); } public static String toString(int code) { String result = ""; if(code > 0) { if(code == 0x7F) { // b1111111 result = "Everyday"; } else { for(int i = 1; i < 8; i++) { // From SUNDAY to SATURDAY if(isSet(code, i)) { result = result + DateUtils.getDayOfWeekString( i, DateUtils.LENGTH_MEDIUM) + " "; } } } } else { result = "No days"; } return result; } public static List<String> toStringList(int code) { List<String> result = new LinkedList<String>(); if(code > 0) { if(code == 0x7F) { // b1111111 result.add("Everyday"); } else { for(int i = 1; i < 8; i++) { // From SUNDAY to SATURDAY if(isSet(code, i)) { result.add( DateUtils.getDayOfWeekString( i, DateUtils.LENGTH_MEDIUM)); } } } } else { result.add("No days"); } return result; } } /** * Return Uri of an alarm with id given. * * @param alarmId ID of the alarm. If -1 is given, it returns Uri representing all alarms. * * @return Uri of the alarm. */ public static Uri getAlarmUri(final long alarmId) { if(alarmId == -1) { return Uri.parse(CONTENT_URI_ALL_ALARMS); } else { return Uri.parse(CONTENT_URI_ALL_ALARMS + "/" + alarmId); } } /** * * * @param context * @param alarmUri * * @return */ public synchronized static Cursor getAlarmCursor(Context context, Uri alarmUri) { return context.getContentResolver().query( alarmUri, AlarmColumns.QUERY_COLUMNS, null, null, AlarmColumns.DEFAULT_SORT_ORDER); } /** * Listener interface that is used to report settings for every alarm * existed on the database. * */ public static interface OnVisitListener { void onVisit(final Context context, final int id, final String label, final int hour, final int minutes, final int atTimeInMillis, final int repeatOnDaysCode, final boolean enabled, final String handler, final String extra); } public static class GetAlarmSettings implements OnVisitListener { public int id; public String label; public int hour; public int minutes; public int atTimeInMillis; public int repeatOnDaysCode; public boolean enabled; public String handler; public String extra; @Override public void onVisit(final Context context, final int id, final String label, final int hour, final int minutes, final int atTimeInMillis, final int repeatOnDaysCode, final boolean enabled, final String handler, final String extra) { this.id = id; this.label = label; this.hour = hour; this.minutes = minutes; this.atTimeInMillis = atTimeInMillis; this.repeatOnDaysCode = repeatOnDaysCode; this.enabled = enabled; this.handler = handler; this.extra = extra; } } /** * Iterate alarms. * * @param context * @param alarmUri * @param listener */ public static void forEachAlarm(final Context context, final Uri alarmUri, final OnVisitListener listener) { Cursor cursor = getAlarmCursor(context, alarmUri); if(cursor.moveToFirst()) { do { final int id = cursor.getInt(AlarmColumns.PROJECTION_ID_INDEX); final String label = cursor.getString(AlarmColumns.PROJECTION_LABEL_INDEX); final int hour = cursor.getInt(AlarmColumns.PROJECTION_HOUR_INDEX); final int minutes = cursor.getInt(AlarmColumns.PROJECTION_MINUTES_INDEX); final int atTimeInMillis = cursor.getInt(AlarmColumns.PROJECTION_AT_TIME_IN_MILLIS_INDEX); final int repeatOnDaysCode = cursor.getInt(AlarmColumns.PROJECTION_REPEAT_DAYS_INDEX); final boolean enabled = cursor.getInt(AlarmColumns.PROJECTION_ENABLED_INDEX) == 1; final String handler = cursor.getString(AlarmColumns.PROJECTION_HANDLER_INDEX); final String extra = cursor.getString(AlarmColumns.PROJECTION_EXTRA_INDEX); if(listener != null) { listener.onVisit(context, id, label, hour, minutes, atTimeInMillis, repeatOnDaysCode, enabled, handler, extra); } } while(cursor.moveToNext()); } cursor.close(); } /** * Insert a new alarm record into database. * * @param context Context this is calling from. * * @return Uri of the newly inserted alarm. */ public synchronized static Uri newAlarm(Context context) { return context.getContentResolver().insert( Uri.parse(CONTENT_URI_ALL_ALARMS), null); } /** * * * @param context * @param alarmId * * @return */ public synchronized static int deleteAlarm(Context context, int alarmId) { Uri alarmUri = Alarms.getAlarmUri(alarmId); return context.getContentResolver().delete(alarmUri, null, null); } /** * * * @param context * @param alarmId * @param newValues * * @return */ public synchronized static int updateAlarm(final Context context, final Uri alarmUri, final ContentValues newValues) { if(newValues == null) { return -1; } return context.getContentResolver().update( alarmUri, newValues, null, null); } private static class EnableAlarm implements OnVisitListener { private final boolean mEnabled; public long mAtTimeInMillis; public String mHandler; public EnableAlarm(boolean enabled) { mEnabled = enabled; } @Override public void onVisit(final Context context, final int id, final String label, final int hour, final int minutes, final int oldAtTimeInMillis, final int repeatOnDaysCode, final boolean enabled, final String handler, final String extra) { if (TextUtils.isEmpty(handler)) { Log.d(TAG, "***** null alarm handler is not allowed"); return; } Log.d(TAG, "Inside EnableAlarm, alarm " + label + " handler=" + handler); mHandler = handler; if (mEnabled) { mAtTimeInMillis = calculateAlarmAtTimeInMillis(hour, minutes, repeatOnDaysCode); enableAlarm(context, id, label, mAtTimeInMillis, repeatOnDaysCode, handler, extra); showToast(context, mAtTimeInMillis); } else { disableAlarm(context, id, handler); } } } /** * Enable/disable the alarm pointed by @c alarmUri. * * @param context Context this method is called. * @param alarmUri Alarm uri. * @param enabled Enable or disable this alarm. */ public static synchronized boolean setAlarmEnabled(final Context context, final Uri alarmUri, final boolean enabled) { Log.d(TAG, "setAlarmEnabled(" + alarmUri + ", " + enabled + ")"); ContentValues newValues = new ContentValues(); newValues.put(AlarmColumns.ENABLED, enabled ? 1 : 0); // Activate or deactivate this alarm. EnableAlarm enabler = new EnableAlarm(enabled); forEachAlarm(context, alarmUri, enabler); if (enabled) { newValues.put(AlarmColumns.AT_TIME_IN_MILLIS, enabler.mAtTimeInMillis); if (TextUtils.isEmpty(enabler.mHandler)) { return false; } } updateAlarm(context, alarmUri, newValues); if (enabled) { // setNotification(context, id, handler, mEnabled); setNotification(context, true); } else { // If there are more than 2 alarms enabled, don't // remove notification final int numberOfEnabledAlarms = getNumberOfEnabledAlarms(context); Log.d(TAG, "===> there are still " + numberOfEnabledAlarms + " alarms enabled"); if (numberOfEnabledAlarms == 0) { setNotification(context, false); } } return true; } /** * * * @param context * @param alarmId * @param handlerClassName * @param intent * @param extraData * @param minutesLater */ public static void snoozeAlarm(final Context context, final int alarmId, final String label, final int repeatOnDays, final String handlerClassName, final String extraData, final int minutesLater) { // Cancel the old alert. disableAlarm(context, alarmId, handlerClassName); // Arrange new time for snoozed alarm from current date // and time. Calendar calendar = getCalendarInstance(); calendar.add(Calendar.MINUTE, minutesLater); int hourOfDay = calendar.get(Calendar.HOUR_OF_DAY); int minutes = calendar.get(Calendar.MINUTE); long newAtTimeInMillis = calendar.getTimeInMillis(); enableAlarm(context, alarmId, label, newAtTimeInMillis, repeatOnDays, handlerClassName, extraData); // Put info into SharedPreferences for the snoozed alarm. SharedPreferences preferences = context.getSharedPreferences(PREFERENCE_FILE_FOR_SNOOZED_ALARM, 0); SharedPreferences.Editor preferenceEditor = preferences.edit(); preferenceEditor.putLong(AlarmColumns.AT_TIME_IN_MILLIS, newAtTimeInMillis); preferenceEditor.putInt(AlarmColumns._ID, alarmId); preferenceEditor.putString(AlarmColumns.LABEL, label); // The handler is required to be persisted because it is // needed when we want to cancel the snoozed alarm. preferenceEditor.putString(AlarmColumns.HANDLER, handlerClassName); preferenceEditor.commit(); } public static void cancelSnoozedAlarm(final Context context, final int alarmId) { Log.d(TAG, "===> Canceling snoozed alarm " + alarmId); SharedPreferences preferences = context.getSharedPreferences( PREFERENCE_FILE_FOR_SNOOZED_ALARM, 0); final int persistedAlarmId = preferences.getInt(AlarmColumns._ID, -1); if (alarmId != -1 && // no checking on alarmId persistedAlarmId != alarmId) { return; } final String handler = preferences.getString(AlarmColumns.HANDLER, null); if (!TextUtils.isEmpty(handler)) { disableAlarm(context, alarmId, handler); // Remove _ID to indicate that the snoozed alert is cancelled. preferences.edit().remove(AlarmColumns._ID).commit(); } } public static void enableAlarm(final Context context, final int alarmId, final String label, final long atTimeInMillis, final int repeatOnDays, final String handlerClassName, final String extraData) { Intent i = new Intent(HANDLE_ALARM, getAlarmUri(alarmId)); - i.setClassName(context, handlerClassName); + try { + Class<?> handlerClass = getHandlerClass(handlerClassName); + String handlerPackageName = handlerClass.getPackage().getName(); + i.setClassName(handlerPackageName, handlerClassName); + } catch (ClassNotFoundException e) { + Log.d(TAG, "Handler class not found"); + return; + } + i.addCategory(Intent.CATEGORY_ALTERNATIVE); // Alarm ID is always necessary for its operations. i.putExtra(AlarmColumns._ID, alarmId); i.putExtra(AlarmColumns.LABEL, label); // Extract hourOfDay and minutes Calendar c = getCalendarInstance(); c.setTimeInMillis(atTimeInMillis); final int hourOfDay = c.get(Calendar.HOUR_OF_DAY); final int minutes = c.get(Calendar.MINUTE); i.putExtra(AlarmColumns.HOUR, hourOfDay); i.putExtra(AlarmColumns.MINUTES, minutes); i.putExtra(AlarmColumns.REPEAT_DAYS, repeatOnDays); // Intent might be provided different class to associate, // like FireAlarm. We need to cache the handlerClass in // the Intent for latter use. i.putExtra(AlarmColumns.HANDLER, handlerClassName); if (!TextUtils.isEmpty(extraData)) { i.putExtra(AlarmColumns.EXTRA, extraData); } AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE); alarmManager.set(AlarmManager.RTC_WAKEUP, atTimeInMillis, PendingIntent.getBroadcast( context, 0, i, PendingIntent.FLAG_CANCEL_CURRENT)); Calendar calendar = getCalendarInstance(); calendar.setTimeInMillis(atTimeInMillis); setAlarmInSystemSettings(context, calendar); } /** * @return true if clock is set to 24-hour mode */ public static boolean is24HourMode(final Context context) { return android.text.format.DateFormat.is24HourFormat(context); } public static void disableAlarm(final Context context, final int alarmId, final String handlerClassName) { Uri alarmUri = getAlarmUri(alarmId); Intent i = new Intent(HANDLE_ALARM, alarmUri); i.setClassName(context, handlerClassName); AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE); alarmManager.cancel(PendingIntent.getBroadcast( context, 0, i, PendingIntent.FLAG_CANCEL_CURRENT)); setAlarmInSystemSettings(context, null); } private static void setAlarmInSystemSettings(final Context context, final Calendar calendar) { String timeString = ""; if (calendar != null) { timeString = formatTime(is24HourMode(context) ? "E HH:mm" : "E hh:mm aa", calendar); } Settings.System.putString(context.getContentResolver(), Settings.System.NEXT_ALARM_FORMATTED, timeString); } public static String formatTime(String pattern, Calendar calendar) { SimpleDateFormat dateFormatter = new SimpleDateFormat(pattern); return dateFormatter.format(calendar.getTime()); } public static String formatTime(final boolean is24HourMode, final int hourOfDay, final int minutes, boolean isAmPmEnabled) { Calendar calendar = Alarms.getCalendarInstance(); calendar.set(Calendar.HOUR_OF_DAY, hourOfDay); calendar.set(Calendar.MINUTE, minutes); if (is24HourMode) { return formatTime("HH:mm", calendar); } return formatTime( isAmPmEnabled ? "hh:mm aa" : "hh:mm", calendar); } public static long calculateAlarmAtTimeInMillis(final int hourOfDay, final int minutes, final int repeatOnCode) { // Start with current date and time. Calendar calendar = getCalendarInstance(); int nowHourOfDay = calendar.get(Calendar.HOUR_OF_DAY); int nowMinutes = calendar.get(Calendar.MINUTE); // If alarm is set at the past, move calendar to the same // time tomorrow and then calculate the next time of // alarm's going off. if((hourOfDay < nowHourOfDay) || ((hourOfDay == nowHourOfDay) && (minutes < nowMinutes))) { calendar.add(Calendar.DAY_OF_YEAR, 1); } // Align calendar's time with this alarm. calendar.set(Calendar.HOUR_OF_DAY, hourOfDay); calendar.set(Calendar.MINUTE, minutes); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); // Try to shift calendar by days in order to find the // nearest alarm. while(true) { if(RepeatWeekdays.isSet(repeatOnCode, calendar.get(Calendar.DAY_OF_WEEK))) { break; } calendar.add(Calendar.DAY_OF_YEAR, 1); } return calendar.getTimeInMillis(); } public static void showToast(final Context context, final long atTimeInMillis) { DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM); String text = String.format( context.getString(R.string.alarm_notification_toast_text), dateFormat.format(new Date(atTimeInMillis))); Toast.makeText(context, text, Toast.LENGTH_LONG).show(); } public static void setNotification(final Context context, final boolean enabled) { if (enabled) { broadcastAlarmChanged(context, true); } else { // If there are more than 2 alarms enabled, don't // remove notification final int numberOfEnabledAlarms = getNumberOfEnabledAlarms(context); Log.d(TAG, "===> there are still " + numberOfEnabledAlarms + " alarms enabled"); if (numberOfEnabledAlarms == 0) { broadcastAlarmChanged(context, false); } } } private static void broadcastAlarmChanged(Context context, boolean enabled) { final String ACTION_ALARM_CHANGED = "android.intent.action.ALARM_CHANGED"; Intent i = new Intent(ACTION_ALARM_CHANGED); i.putExtra("alarmSet", enabled); context.sendBroadcast(i); } public static void setNotification(final Context context, final int alarmId, final String handlerClassName, boolean enabled) { Context appContext = context.getApplicationContext(); NotificationManager nm = (NotificationManager)appContext.getSystemService(Context.NOTIFICATION_SERVICE); if (enabled) { String tickerText = appContext.getString(R.string.alarm_notification_ticker_text); Notification notification = new Notification( R.drawable.stat_notify_alarm, tickerText, System.currentTimeMillis()); notification.flags = Notification.FLAG_NO_CLEAR; Intent notificationIntent = new Intent(appContext, OpenAlarm.class); PendingIntent contentIntent = PendingIntent.getActivity(appContext, 0, notificationIntent, 0); PackageManager pm = appContext.getPackageManager(); String handlerLabel; try { ActivityInfo handlerInfo = getHandlerInfo(pm, handlerClassName); handlerLabel = handlerInfo.loadLabel(pm).toString(); } catch(PackageManager.NameNotFoundException e) { Log.d(TAG, e.getMessage()); return; } String contentText = String.format(appContext.getString(R.string.alarm_notification_content_text), handlerLabel + "(" + handlerClassName + ")"); notification.setLatestEventInfo(appContext, tickerText, contentText, contentIntent); nm.notify(alarmId, notification); } else { nm.cancel(alarmId); } } public static Class<?> getHandlerClass(final String handlerClassName) throws ClassNotFoundException { final int lastDotPos = handlerClassName.lastIndexOf('.'); final String apkPaths = USER_APK_DIR + "/" + "org.startsmall.openalarm.apk:" + // myself // handlers defined by other developers USER_APK_DIR + "/" + handlerClassName.substring(0, lastDotPos) + ".apk"; dalvik.system.PathClassLoader classLoader = new dalvik.system.PathClassLoader( apkPaths, ClassLoader.getSystemClassLoader()); return Class.forName(handlerClassName, true, classLoader); } public static ActivityInfo getHandlerInfo(final PackageManager pm, final String handlerClassName) throws PackageManager.NameNotFoundException { // Make sure the handlerClass really exists // Class<?> handlerClass = getHandlerClass(handlerClassName); Intent i = new Intent(HANDLE_ALARM); i.addCategory(Intent.CATEGORY_ALTERNATIVE); // Search all receivers that can handle my alarms. Iterator<ResolveInfo> infoObjs = pm.queryBroadcastReceivers(i, 0).iterator(); while (infoObjs.hasNext()) { ActivityInfo activityInfo = infoObjs.next().activityInfo; if (activityInfo.name.equals(handlerClassName)) { return activityInfo; } } throw new PackageManager.NameNotFoundException( "BroadcastReceiver " + handlerClassName + " not found"); } private synchronized static int getNumberOfEnabledAlarms(Context context) { Cursor c = context.getContentResolver().query( getAlarmUri(-1), new String[]{AlarmColumns._ID, AlarmColumns.ENABLED}, AlarmColumns.ENABLED + "=1", null, AlarmColumns.DEFAULT_SORT_ORDER); final int count = c.getCount(); c.close(); return count; } }
true
true
public static void enableAlarm(final Context context, final int alarmId, final String label, final long atTimeInMillis, final int repeatOnDays, final String handlerClassName, final String extraData) { Intent i = new Intent(HANDLE_ALARM, getAlarmUri(alarmId)); i.setClassName(context, handlerClassName); // Alarm ID is always necessary for its operations. i.putExtra(AlarmColumns._ID, alarmId); i.putExtra(AlarmColumns.LABEL, label); // Extract hourOfDay and minutes Calendar c = getCalendarInstance(); c.setTimeInMillis(atTimeInMillis); final int hourOfDay = c.get(Calendar.HOUR_OF_DAY); final int minutes = c.get(Calendar.MINUTE); i.putExtra(AlarmColumns.HOUR, hourOfDay); i.putExtra(AlarmColumns.MINUTES, minutes); i.putExtra(AlarmColumns.REPEAT_DAYS, repeatOnDays); // Intent might be provided different class to associate, // like FireAlarm. We need to cache the handlerClass in // the Intent for latter use. i.putExtra(AlarmColumns.HANDLER, handlerClassName); if (!TextUtils.isEmpty(extraData)) { i.putExtra(AlarmColumns.EXTRA, extraData); } AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE); alarmManager.set(AlarmManager.RTC_WAKEUP, atTimeInMillis, PendingIntent.getBroadcast( context, 0, i, PendingIntent.FLAG_CANCEL_CURRENT)); Calendar calendar = getCalendarInstance(); calendar.setTimeInMillis(atTimeInMillis); setAlarmInSystemSettings(context, calendar); }
public static void enableAlarm(final Context context, final int alarmId, final String label, final long atTimeInMillis, final int repeatOnDays, final String handlerClassName, final String extraData) { Intent i = new Intent(HANDLE_ALARM, getAlarmUri(alarmId)); try { Class<?> handlerClass = getHandlerClass(handlerClassName); String handlerPackageName = handlerClass.getPackage().getName(); i.setClassName(handlerPackageName, handlerClassName); } catch (ClassNotFoundException e) { Log.d(TAG, "Handler class not found"); return; } i.addCategory(Intent.CATEGORY_ALTERNATIVE); // Alarm ID is always necessary for its operations. i.putExtra(AlarmColumns._ID, alarmId); i.putExtra(AlarmColumns.LABEL, label); // Extract hourOfDay and minutes Calendar c = getCalendarInstance(); c.setTimeInMillis(atTimeInMillis); final int hourOfDay = c.get(Calendar.HOUR_OF_DAY); final int minutes = c.get(Calendar.MINUTE); i.putExtra(AlarmColumns.HOUR, hourOfDay); i.putExtra(AlarmColumns.MINUTES, minutes); i.putExtra(AlarmColumns.REPEAT_DAYS, repeatOnDays); // Intent might be provided different class to associate, // like FireAlarm. We need to cache the handlerClass in // the Intent for latter use. i.putExtra(AlarmColumns.HANDLER, handlerClassName); if (!TextUtils.isEmpty(extraData)) { i.putExtra(AlarmColumns.EXTRA, extraData); } AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE); alarmManager.set(AlarmManager.RTC_WAKEUP, atTimeInMillis, PendingIntent.getBroadcast( context, 0, i, PendingIntent.FLAG_CANCEL_CURRENT)); Calendar calendar = getCalendarInstance(); calendar.setTimeInMillis(atTimeInMillis); setAlarmInSystemSettings(context, calendar); }
diff --git a/src/main/java/org/swordapp/server/SwordCollection.java b/src/main/java/org/swordapp/server/SwordCollection.java index 97ca8c8..bcd796b 100644 --- a/src/main/java/org/swordapp/server/SwordCollection.java +++ b/src/main/java/org/swordapp/server/SwordCollection.java @@ -1,338 +1,338 @@ package org.swordapp.server; import org.apache.abdera.Abdera; import org.apache.abdera.i18n.iri.IRI; import org.apache.abdera.model.Collection; import org.apache.abdera.model.Element; import javax.xml.namespace.QName; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class SwordCollection { private Collection collection; private List<String> multipartAccept = new ArrayList<String>(); private Abdera abdera; private String collectionPolicy = null; private boolean mediation = false; private String treatment = null; private List<String> acceptPackaging = new ArrayList<String>(); private List<IRI> subServices = new ArrayList<IRI>(); private String dcAbstract = null; public SwordCollection() { this.abdera = new Abdera(); this.collection = this.abdera.getFactory().newCollection(); } public Collection getWrappedCollection() { return this.collection; } public Collection getAbderaCollection() { Collection abderaCollection = (Collection) this.collection.clone(); // FIXME: this is wrong; clients must be free to leave the accepts blank // // ensure that there is an accept field set // List<String> singlePartAccepts = this.getSinglepartAccept(); // if (singlePartAccepts.size() == 0) // { // abderaCollection.addAccepts("*/*"); // } // // // ensure that there is multipart accepts set // List<String> multipartAccepts = this.getMultipartAccept(); // if (multipartAccepts.size() == 0 || this.multipartAccept.size() == 0) // { // this.multipartAccept.add("*/*"); // } // add the multipart accepts as elements for (String mpa : this.multipartAccept) { Element element = this.abdera.getFactory().newElement(UriRegistry.APP_ACCEPT); - element.setAttributeValue("alternate", "multipart/related"); + element.setAttributeValue("alternate", "multipart-related"); element.setText(mpa); abderaCollection.addExtension(element); } // add the collection Policy if (this.collectionPolicy != null) { abderaCollection.addSimpleExtension(UriRegistry.SWORD_COLLECTION_POLICY, this.collectionPolicy); } // add the mediation abderaCollection.addSimpleExtension(UriRegistry.SWORD_MEDIATION, (this.mediation ? "true" : "false")); // add the treatment if (this.treatment != null) { abderaCollection.addSimpleExtension(UriRegistry.SWORD_TREATMENT, this.treatment); } // add the acceptPackaging for (String ap : this.acceptPackaging) { abderaCollection.addSimpleExtension(UriRegistry.SWORD_ACCEPT_PACKAGING, ap); } // add the sub service document IRI for (IRI ss : this.subServices) { abderaCollection.addSimpleExtension(UriRegistry.SWORD_SERVICE, ss.toString()); } // add the abstract if (this.dcAbstract != null) { abderaCollection.addSimpleExtension(UriRegistry.DC_ABSTRACT, this.dcAbstract); } return abderaCollection; } public void setLocation(String href) { this.collection.setHref(href); } public void setAbstract(String dcAbstract) { this.dcAbstract = dcAbstract; } public List<IRI> getSubServices() { return subServices; } public void setSubServices(List<IRI> subServices) { this.subServices = subServices; } public void addSubService(IRI subService) { this.subServices.add(subService); } public void setCollectionPolicy(String collectionPolicy) { this.collectionPolicy = collectionPolicy; } public void setMediation(boolean mediation) { this.mediation = mediation; } public void setTreatment(String treatment) { this.treatment = treatment; } public void setAcceptPackaging(List<String> acceptPackaging) { this.acceptPackaging = acceptPackaging; } public void addAcceptPackaging(String acceptPackaging) { this.acceptPackaging.add(acceptPackaging); } public String getCollectionPolicy() { return collectionPolicy; } public boolean isMediation() { return mediation; } public String getTreatment() { return treatment; } public List<String> getAcceptPackaging() { return acceptPackaging; } public void setTitle(String title) { this.collection.setTitle(title); } public void setHref(String href) { this.collection.setHref(href); } public void setAccept(String... mediaRanges) { this.collection.setAccept(mediaRanges); } public void setAcceptsEntry() { this.collection.setAcceptsEntry(); } public void setAcceptsNothing() { this.collection.setAcceptsNothing(); } public void addAccepts(String mediaRange) { this.collection.addAccepts(mediaRange); } public void addAccepts(String... mediaRanges) { this.collection.addAccepts(mediaRanges); } public void addAcceptsEntry() { this.collection.addAcceptsEntry(); } public void setMultipartAccept(String... mediaRanges) { List<String> mrs = Arrays.asList(mediaRanges); this.multipartAccept.clear(); this.multipartAccept.addAll(mrs); } public void addMultipartAccepts(String mediaRange) { this.multipartAccept.add(mediaRange); } public void addMultipartAccepts(String... mediaRanges) { List<String> mrs = Arrays.asList(mediaRanges); this.multipartAccept.addAll(mrs); } public List<String> getMultipartAccept() { List<String> accepts = new ArrayList<String>(); List<Element> elements = this.collection.getElements(); boolean noAccept = false; for (Element e : elements) { String multipartRelated = e.getAttributeValue("alternate"); QName qn = e.getQName(); if (qn.getLocalPart().equals("accept") && qn.getNamespaceURI().equals(UriRegistry.APP_NAMESPACE) && "multipart-related".equals(multipartRelated)) { String content = e.getText(); if (content == null || "".equals(content)) { noAccept = true; } if (content != null && !"".equals(content) && !accepts.contains(content)) { accepts.add(content); } } } // if there are no accept values, and noAccept has not been triggered, then we add the // default accept type if (accepts.size() == 0 && !noAccept) { accepts.add("application/atom+xml;type=entry"); } // rationalise and return return this.rationaliseAccepts(accepts); } public List<String> getSinglepartAccept() { List<String> accepts = new ArrayList<String>(); List<Element> elements = this.collection.getElements(); boolean noAccept = false; for (Element e : elements) { String multipartRelated = e.getAttributeValue("alternate"); QName qn = e.getQName(); if (qn.getLocalPart().equals("accept") && qn.getNamespaceURI().equals(UriRegistry.APP_NAMESPACE) && !"multipart-related".equals(multipartRelated)) { String content = e.getText(); if (content == null || "".equals(content)) { noAccept = true; } if (content != null && !"".equals(content) && !accepts.contains(content)) { accepts.add(content); } } } // if there are no accept values, and noAccept has not been triggered, then we add the // default accept type if (accepts.size() == 0 && !noAccept) { accepts.add("application/atom+xml;type=entry"); } // rationalise and return return this.rationaliseAccepts(accepts); } private List<String> rationaliseAccepts(List<String> accepts) { List<String> rational = new ArrayList<String>(); // first, if "*/*" is there, then we accept anything if (accepts.contains("*/*")) { rational.add("*/*"); return rational; } // now look to see if we have <x>/* and if so eliminate the unnecessary accepts List<String> wildcards = new ArrayList<String>(); for (String a : accepts) { if (a.contains("/*")) { String wild = a.substring(0, a.indexOf("/")); wildcards.add(wild); if (!rational.contains(a)) { rational.add(a); } } } for (String a : accepts) { String type = a.substring(0, a.indexOf("/")); if (!wildcards.contains(type)) { rational.add(a); } } // by the time we get here we will have only unique and correctly wildcarded accept fields return rational; } }
true
true
public Collection getAbderaCollection() { Collection abderaCollection = (Collection) this.collection.clone(); // FIXME: this is wrong; clients must be free to leave the accepts blank // // ensure that there is an accept field set // List<String> singlePartAccepts = this.getSinglepartAccept(); // if (singlePartAccepts.size() == 0) // { // abderaCollection.addAccepts("*/*"); // } // // // ensure that there is multipart accepts set // List<String> multipartAccepts = this.getMultipartAccept(); // if (multipartAccepts.size() == 0 || this.multipartAccept.size() == 0) // { // this.multipartAccept.add("*/*"); // } // add the multipart accepts as elements for (String mpa : this.multipartAccept) { Element element = this.abdera.getFactory().newElement(UriRegistry.APP_ACCEPT); element.setAttributeValue("alternate", "multipart/related"); element.setText(mpa); abderaCollection.addExtension(element); } // add the collection Policy if (this.collectionPolicy != null) { abderaCollection.addSimpleExtension(UriRegistry.SWORD_COLLECTION_POLICY, this.collectionPolicy); } // add the mediation abderaCollection.addSimpleExtension(UriRegistry.SWORD_MEDIATION, (this.mediation ? "true" : "false")); // add the treatment if (this.treatment != null) { abderaCollection.addSimpleExtension(UriRegistry.SWORD_TREATMENT, this.treatment); } // add the acceptPackaging for (String ap : this.acceptPackaging) { abderaCollection.addSimpleExtension(UriRegistry.SWORD_ACCEPT_PACKAGING, ap); } // add the sub service document IRI for (IRI ss : this.subServices) { abderaCollection.addSimpleExtension(UriRegistry.SWORD_SERVICE, ss.toString()); } // add the abstract if (this.dcAbstract != null) { abderaCollection.addSimpleExtension(UriRegistry.DC_ABSTRACT, this.dcAbstract); } return abderaCollection; }
public Collection getAbderaCollection() { Collection abderaCollection = (Collection) this.collection.clone(); // FIXME: this is wrong; clients must be free to leave the accepts blank // // ensure that there is an accept field set // List<String> singlePartAccepts = this.getSinglepartAccept(); // if (singlePartAccepts.size() == 0) // { // abderaCollection.addAccepts("*/*"); // } // // // ensure that there is multipart accepts set // List<String> multipartAccepts = this.getMultipartAccept(); // if (multipartAccepts.size() == 0 || this.multipartAccept.size() == 0) // { // this.multipartAccept.add("*/*"); // } // add the multipart accepts as elements for (String mpa : this.multipartAccept) { Element element = this.abdera.getFactory().newElement(UriRegistry.APP_ACCEPT); element.setAttributeValue("alternate", "multipart-related"); element.setText(mpa); abderaCollection.addExtension(element); } // add the collection Policy if (this.collectionPolicy != null) { abderaCollection.addSimpleExtension(UriRegistry.SWORD_COLLECTION_POLICY, this.collectionPolicy); } // add the mediation abderaCollection.addSimpleExtension(UriRegistry.SWORD_MEDIATION, (this.mediation ? "true" : "false")); // add the treatment if (this.treatment != null) { abderaCollection.addSimpleExtension(UriRegistry.SWORD_TREATMENT, this.treatment); } // add the acceptPackaging for (String ap : this.acceptPackaging) { abderaCollection.addSimpleExtension(UriRegistry.SWORD_ACCEPT_PACKAGING, ap); } // add the sub service document IRI for (IRI ss : this.subServices) { abderaCollection.addSimpleExtension(UriRegistry.SWORD_SERVICE, ss.toString()); } // add the abstract if (this.dcAbstract != null) { abderaCollection.addSimpleExtension(UriRegistry.DC_ABSTRACT, this.dcAbstract); } return abderaCollection; }
diff --git a/src/main/java/be/Balor/Listeners/ACPlayerListener.java b/src/main/java/be/Balor/Listeners/ACPlayerListener.java index f13fcdbe..04ad251d 100644 --- a/src/main/java/be/Balor/Listeners/ACPlayerListener.java +++ b/src/main/java/be/Balor/Listeners/ACPlayerListener.java @@ -1,367 +1,367 @@ /************************************************************************ * This file is part of AdminCmd. * * AdminCmd 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. * * AdminCmd 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 AdminCmd. If not, see <http://www.gnu.org/licenses/>. ************************************************************************/ package be.Balor.Listeners; import java.util.HashMap; import java.util.List; import org.bukkit.Location; import org.bukkit.craftbukkit.entity.CraftPlayer; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerChatEvent; import org.bukkit.event.player.PlayerCommandPreprocessEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerKickEvent; import org.bukkit.event.player.PlayerLoginEvent; import org.bukkit.event.player.PlayerLoginEvent.Result; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.event.player.PlayerPickupItemEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.player.PlayerRespawnEvent; import org.bukkit.event.player.PlayerTeleportEvent; import be.Balor.Manager.CommandManager; import be.Balor.Manager.Exceptions.NoPermissionsPlugin; import be.Balor.Manager.Permissions.PermissionManager; import be.Balor.Manager.Permissions.Plugins.SuperPermissions; import be.Balor.Player.ACPlayer; import be.Balor.Player.PlayerManager; import be.Balor.Tools.Type; import be.Balor.Tools.UpdateInvisible; import be.Balor.Tools.Utils; import be.Balor.Tools.Debug.DebugLog; import be.Balor.World.ACWorld; import be.Balor.bukkit.AdminCmd.ACHelper; import be.Balor.bukkit.AdminCmd.ACPluginManager; import be.Balor.bukkit.AdminCmd.ConfigEnum; import belgium.Balor.Workers.AFKWorker; import belgium.Balor.Workers.InvisibleWorker; /** * @author Balor (aka Antoine Aflalo) * */ public class ACPlayerListener implements Listener { protected class UpdateInvisibleOnJoin implements Runnable { Player newPlayer; /** * */ public UpdateInvisibleOnJoin(final Player p) { newPlayer = p; } @Override public void run() { DebugLog.INSTANCE.info("Begin UpdateInvisibleOnJoin (Invisible) for " + newPlayer.getName()); for (final Player toVanish : InvisibleWorker.getInstance().getAllInvisiblePlayers()) { InvisibleWorker.getInstance().invisible(toVanish, newPlayer); if (ConfigEnum.FQINVISIBLE.getBoolean()) Utils.removePlayerFromOnlineList(toVanish, newPlayer); } DebugLog.INSTANCE.info("Begin UpdateInvisibleOnJoin (FakeQuit) for " + newPlayer.getName()); for (final Player toFq : ACHelper.getInstance().getFakeQuitPlayers()) Utils.removePlayerFromOnlineList(toFq, newPlayer); } } @EventHandler public void onPlayerChat(final PlayerChatEvent event) { final Player p = event.getPlayer(); final ACPlayer player = ACPlayer.getPlayer(p); if (ConfigEnum.AUTO_AFK.getBoolean()) { AFKWorker.getInstance().updateTimeStamp(p); if (AFKWorker.getInstance().isAfk(p)) AFKWorker.getInstance().setOnline(p); } if (player.hasPower(Type.MUTED)) { event.setCancelled(true); Utils.sI18n(p, "muteEnabled"); } } @EventHandler(priority = EventPriority.LOWEST) public void onPlayerCommandPreprocess(final PlayerCommandPreprocessEvent event) { final Player p = event.getPlayer(); final ACPlayer player = ACPlayer.getPlayer(p); if (player.hasPower(Type.MUTED_COMMAND)) { final String[] split = event.getMessage().split("\\s+"); if (split.length != 0) { if (split[0].contains("/")) { event.setCancelled(true); Utils.sI18n(p, "commandMuteEnabled"); } } } if (CommandManager.getInstance() .processCommandString(event.getPlayer(), event.getMessage())) { event.setCancelled(true); event.setMessage("/AdminCmd took the control of that command."); } } @EventHandler public void onPlayerInteract(final PlayerInteractEvent event) { if (event.isCancelled()) return; final Player p = event.getPlayer(); if (ConfigEnum.AUTO_AFK.getBoolean()) { AFKWorker.getInstance().updateTimeStamp(p); if (AFKWorker.getInstance().isAfk(p)) AFKWorker.getInstance().setOnline(p); } final ACPlayer player = ACPlayer.getPlayer(p); if (player.hasPower(Type.FROZEN)) { event.setCancelled(true); return; } } @EventHandler(priority = EventPriority.HIGH) public void onPlayerJoin(final PlayerJoinEvent event) { final Player p = event.getPlayer(); final ACPlayer player = PlayerManager.getInstance().setOnline(p); player.setInformation("last-ip", p.getAddress().getAddress().toString()); if (ConfigEnum.JQMSG.getBoolean() && !SuperPermissions.isApiSet()) { final HashMap<String, String> replace = new HashMap<String, String>(); replace.put("name", Utils.getPlayerName(p, null, true)); event.setJoinMessage(Utils.I18n("joinMessage", replace)); } if (player.hasPower(Type.INVISIBLE)) { event.setJoinMessage(null); Utils.sI18n(event.getPlayer(), "stillInv"); InvisibleWorker.getInstance().onJoinEvent(p); } ACPluginManager.getScheduler().scheduleAsyncDelayedTask(ACPluginManager.getCorePlugin(), new Runnable() { @Override public void run() { if (ConfigEnum.AUTO_AFK.getBoolean()) AFKWorker.getInstance().updateTimeStamp(p); final int imLvl = ACHelper.getInstance().getLimit(p, "immunityLvl", "defaultImmunityLvl"); player.setInformation("immunityLvl", imLvl == Integer.MAX_VALUE ? ConfigEnum.DIMMUNITY.getInt() : imLvl); if (player.hasPower(Type.SPYMSG)) ACHelper.getInstance().addSpy(p); player.setInformation("lastConnection", System.currentTimeMillis()); if (ConfigEnum.NEWS.getBoolean()) Utils.sParsedLocale(p, "NEWS"); if (ConfigEnum.RULES.getBoolean() && !ConfigEnum.FJ_RULES.getBoolean()) Utils.sParsedLocale(p, "Rules"); if (ConfigEnum.TPREQUEST.getBoolean() && !player.hasPower(Type.TP_REQUEST) - && PermissionManager.hasPerm(p, "admincmd.tp.toggle", false)) + && PermissionManager.hasPerm(p, "admincmd.tp.toggle.allow", false)) player.setPower(Type.TP_REQUEST); } }); if (player.hasPower(Type.FAKEQUIT)) { event.setJoinMessage(null); ACHelper.getInstance().addFakeQuit(p); } if (player.getInformation("firstTime").getBoolean(true)) { player.setInformation("firstTime", false); if (ConfigEnum.JQMSG.getBoolean() && !SuperPermissions.isApiSet()) { final HashMap<String, String> replace = new HashMap<String, String>(); replace.put("name", Utils.getPlayerName(p, null, true)); event.setJoinMessage(Utils.I18n("joinMessageFirstTime", replace)); } if (ConfigEnum.FCSPAWN.getBoolean()) ACHelper.getInstance().spawn(p); if (!ConfigEnum.FCSPAWN.getBoolean() && ConfigEnum.GSPAWN.getString().equalsIgnoreCase("group")) ACHelper.getInstance().groupSpawn(p); if (ConfigEnum.FJ_RULES.getBoolean()) Utils.sParsedLocale(p, "Rules"); if (ConfigEnum.MOTD.getBoolean()) Utils.sParsedLocale(p, "MOTDNewUser"); } else if (ConfigEnum.MOTD.getBoolean()) Utils.sParsedLocale(p, "MOTD"); } @EventHandler(priority = EventPriority.HIGH) public void onPlayerLogin(final PlayerLoginEvent event) { if (event.getResult().equals(Result.ALLOWED)) return; if (PermissionManager.hasPerm(event.getPlayer(), "admincmd.player.bypass", false) && event.getResult() == Result.KICK_FULL) event.allow(); } @EventHandler public void onPlayerMove(final PlayerMoveEvent event) { final Player p = event.getPlayer(); if (ConfigEnum.AUTO_AFK.getBoolean()) { AFKWorker.getInstance().updateTimeStamp(p); if (AFKWorker.getInstance().isAfk(p)) AFKWorker.getInstance().setOnline(p); } final ACPlayer player = ACPlayer.getPlayer(p.getName()); if (player.hasPower(Type.FROZEN)) { // event.setCancelled(true); /** * https://github.com/Bukkit/CraftBukkit/pull/434 * * @author Evenprime */ ((CraftPlayer) p).getHandle().netServerHandler.teleport(event.getFrom()); return; } } @EventHandler public void onPlayerPickupItem(final PlayerPickupItemEvent event) { if (event.isCancelled()) return; final ACPlayer player = ACPlayer.getPlayer(event.getPlayer()); if (player.hasPower(Type.NO_PICKUP)) event.setCancelled(true); } @EventHandler public void onPlayerKick(final PlayerKickEvent event) { if (event.isCancelled()) return; final Player p = event.getPlayer(); final ACPlayer player = ACPlayer.getPlayer(p); if (player != null && player.hasPower(Type.KICKED)) { event.setLeaveMessage(null); player.removePower(Type.KICKED); } } @EventHandler(priority = EventPriority.HIGH) public void onPlayerQuit(final PlayerQuitEvent event) { final Player p = event.getPlayer(); final ACPlayer player = ACPlayer.getPlayer(p); player.setInformation("lastDisconnect", System.currentTimeMillis()); ACPluginManager.getScheduler().scheduleAsyncDelayedTask(ACPluginManager.getCorePlugin(), new Runnable() { @Override public void run() { final int imLvl = ACHelper.getInstance().getLimit(p, "immunityLvl", "defaultImmunityLvl"); player.setInformation("immunityLvl", imLvl == Integer.MAX_VALUE ? ConfigEnum.DIMMUNITY.getInt() : imLvl); } }); if (ConfigEnum.JQMSG.getBoolean() && !SuperPermissions.isApiSet()) { final HashMap<String, String> replace = new HashMap<String, String>(); replace.put("name", Utils.getPlayerName(p, null, true)); event.setQuitMessage(Utils.I18n("quitMessage", replace)); } if (player.hasPower(Type.FAKEQUIT)) event.setQuitMessage(null); else if (InvisibleWorker.getInstance().hasInvisiblePowers(p.getName())) event.setQuitMessage(null); PlayerManager.getInstance().setOffline(player); ACHelper.getInstance().removeDisconnectedPlayer(p); } @EventHandler public void onPlayerRespawn(final PlayerRespawnEvent event) { final Player player = event.getPlayer(); playerRespawnOrJoin(player); final String spawn = ConfigEnum.GSPAWN.getString(); Location loc = null; final String worldName = player.getWorld().getName(); if (spawn.isEmpty() || spawn.equalsIgnoreCase("globalspawn")) { loc = ACWorld.getWorld(worldName).getSpawn(); event.setRespawnLocation(loc); } else if (spawn.equalsIgnoreCase("home")) { loc = ACPlayer.getPlayer(player).getHome(worldName); if (loc == null) loc = ACWorld.getWorld(worldName).getSpawn(); event.setRespawnLocation(loc); } else if (spawn.equalsIgnoreCase("bed")) { try { loc = player.getBedSpawnLocation(); if (loc == null) loc = ACWorld.getWorld(worldName).getSpawn(); } catch (final NullPointerException e) { loc = ACWorld.getWorld(worldName).getSpawn(); } event.setRespawnLocation(loc); } else if (spawn.equalsIgnoreCase("group")) { final List<String> groups = ACHelper.getInstance().getGroupList(); if (!groups.isEmpty()) { for (final String groupName : groups) { try { if (PermissionManager.isInGroup(groupName, player)) loc = ACWorld.getWorld(worldName).getWarp( "spawn" + groupName.toLowerCase()).loc; break; } catch (final NoPermissionsPlugin e) { loc = ACWorld.getWorld(worldName).getSpawn(); break; } } } if (loc == null) loc = ACWorld.getWorld(worldName).getSpawn(); event.setRespawnLocation(loc); } /* * else { loc = ACWorld.getWorld(worldName).getSpawn(); * event.setRespawnLocation(loc); } */ } @EventHandler public void onPlayerTeleport(final PlayerTeleportEvent event) { if (event.isCancelled()) return; final ACPlayer player = ACPlayer.getPlayer(event.getPlayer()); if (player.hasPower(Type.FROZEN)) { event.setCancelled(true); return; } playerRespawnOrJoin(event.getPlayer()); } private boolean playerRespawnOrJoin(final Player newPlayer) { ACPluginManager .getServer() .getScheduler() .scheduleSyncDelayedTask(ACHelper.getInstance().getCoreInstance(), new UpdateInvisibleOnJoin(newPlayer), 15); if (InvisibleWorker.getInstance().hasInvisiblePowers(newPlayer.getName())) { ACPluginManager .getServer() .getScheduler() .scheduleSyncDelayedTask(ACHelper.getInstance().getCoreInstance(), new UpdateInvisible(newPlayer), 15); Utils.removePlayerFromOnlineList(newPlayer); return true; } return false; } }
true
true
public void onPlayerJoin(final PlayerJoinEvent event) { final Player p = event.getPlayer(); final ACPlayer player = PlayerManager.getInstance().setOnline(p); player.setInformation("last-ip", p.getAddress().getAddress().toString()); if (ConfigEnum.JQMSG.getBoolean() && !SuperPermissions.isApiSet()) { final HashMap<String, String> replace = new HashMap<String, String>(); replace.put("name", Utils.getPlayerName(p, null, true)); event.setJoinMessage(Utils.I18n("joinMessage", replace)); } if (player.hasPower(Type.INVISIBLE)) { event.setJoinMessage(null); Utils.sI18n(event.getPlayer(), "stillInv"); InvisibleWorker.getInstance().onJoinEvent(p); } ACPluginManager.getScheduler().scheduleAsyncDelayedTask(ACPluginManager.getCorePlugin(), new Runnable() { @Override public void run() { if (ConfigEnum.AUTO_AFK.getBoolean()) AFKWorker.getInstance().updateTimeStamp(p); final int imLvl = ACHelper.getInstance().getLimit(p, "immunityLvl", "defaultImmunityLvl"); player.setInformation("immunityLvl", imLvl == Integer.MAX_VALUE ? ConfigEnum.DIMMUNITY.getInt() : imLvl); if (player.hasPower(Type.SPYMSG)) ACHelper.getInstance().addSpy(p); player.setInformation("lastConnection", System.currentTimeMillis()); if (ConfigEnum.NEWS.getBoolean()) Utils.sParsedLocale(p, "NEWS"); if (ConfigEnum.RULES.getBoolean() && !ConfigEnum.FJ_RULES.getBoolean()) Utils.sParsedLocale(p, "Rules"); if (ConfigEnum.TPREQUEST.getBoolean() && !player.hasPower(Type.TP_REQUEST) && PermissionManager.hasPerm(p, "admincmd.tp.toggle", false)) player.setPower(Type.TP_REQUEST); } }); if (player.hasPower(Type.FAKEQUIT)) { event.setJoinMessage(null); ACHelper.getInstance().addFakeQuit(p); } if (player.getInformation("firstTime").getBoolean(true)) { player.setInformation("firstTime", false); if (ConfigEnum.JQMSG.getBoolean() && !SuperPermissions.isApiSet()) { final HashMap<String, String> replace = new HashMap<String, String>(); replace.put("name", Utils.getPlayerName(p, null, true)); event.setJoinMessage(Utils.I18n("joinMessageFirstTime", replace)); } if (ConfigEnum.FCSPAWN.getBoolean()) ACHelper.getInstance().spawn(p); if (!ConfigEnum.FCSPAWN.getBoolean() && ConfigEnum.GSPAWN.getString().equalsIgnoreCase("group")) ACHelper.getInstance().groupSpawn(p); if (ConfigEnum.FJ_RULES.getBoolean()) Utils.sParsedLocale(p, "Rules"); if (ConfigEnum.MOTD.getBoolean()) Utils.sParsedLocale(p, "MOTDNewUser"); } else if (ConfigEnum.MOTD.getBoolean()) Utils.sParsedLocale(p, "MOTD"); }
public void onPlayerJoin(final PlayerJoinEvent event) { final Player p = event.getPlayer(); final ACPlayer player = PlayerManager.getInstance().setOnline(p); player.setInformation("last-ip", p.getAddress().getAddress().toString()); if (ConfigEnum.JQMSG.getBoolean() && !SuperPermissions.isApiSet()) { final HashMap<String, String> replace = new HashMap<String, String>(); replace.put("name", Utils.getPlayerName(p, null, true)); event.setJoinMessage(Utils.I18n("joinMessage", replace)); } if (player.hasPower(Type.INVISIBLE)) { event.setJoinMessage(null); Utils.sI18n(event.getPlayer(), "stillInv"); InvisibleWorker.getInstance().onJoinEvent(p); } ACPluginManager.getScheduler().scheduleAsyncDelayedTask(ACPluginManager.getCorePlugin(), new Runnable() { @Override public void run() { if (ConfigEnum.AUTO_AFK.getBoolean()) AFKWorker.getInstance().updateTimeStamp(p); final int imLvl = ACHelper.getInstance().getLimit(p, "immunityLvl", "defaultImmunityLvl"); player.setInformation("immunityLvl", imLvl == Integer.MAX_VALUE ? ConfigEnum.DIMMUNITY.getInt() : imLvl); if (player.hasPower(Type.SPYMSG)) ACHelper.getInstance().addSpy(p); player.setInformation("lastConnection", System.currentTimeMillis()); if (ConfigEnum.NEWS.getBoolean()) Utils.sParsedLocale(p, "NEWS"); if (ConfigEnum.RULES.getBoolean() && !ConfigEnum.FJ_RULES.getBoolean()) Utils.sParsedLocale(p, "Rules"); if (ConfigEnum.TPREQUEST.getBoolean() && !player.hasPower(Type.TP_REQUEST) && PermissionManager.hasPerm(p, "admincmd.tp.toggle.allow", false)) player.setPower(Type.TP_REQUEST); } }); if (player.hasPower(Type.FAKEQUIT)) { event.setJoinMessage(null); ACHelper.getInstance().addFakeQuit(p); } if (player.getInformation("firstTime").getBoolean(true)) { player.setInformation("firstTime", false); if (ConfigEnum.JQMSG.getBoolean() && !SuperPermissions.isApiSet()) { final HashMap<String, String> replace = new HashMap<String, String>(); replace.put("name", Utils.getPlayerName(p, null, true)); event.setJoinMessage(Utils.I18n("joinMessageFirstTime", replace)); } if (ConfigEnum.FCSPAWN.getBoolean()) ACHelper.getInstance().spawn(p); if (!ConfigEnum.FCSPAWN.getBoolean() && ConfigEnum.GSPAWN.getString().equalsIgnoreCase("group")) ACHelper.getInstance().groupSpawn(p); if (ConfigEnum.FJ_RULES.getBoolean()) Utils.sParsedLocale(p, "Rules"); if (ConfigEnum.MOTD.getBoolean()) Utils.sParsedLocale(p, "MOTDNewUser"); } else if (ConfigEnum.MOTD.getBoolean()) Utils.sParsedLocale(p, "MOTD"); }
diff --git a/jbi/src/main/java/org/apache/ode/jbi/OdeService.java b/jbi/src/main/java/org/apache/ode/jbi/OdeService.java index 09f7bbbfc..321463bae 100755 --- a/jbi/src/main/java/org/apache/ode/jbi/OdeService.java +++ b/jbi/src/main/java/org/apache/ode/jbi/OdeService.java @@ -1,388 +1,388 @@ /* * 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.jbi; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.ode.bpel.iapi.Endpoint; import org.apache.ode.bpel.iapi.Message; import org.apache.ode.bpel.iapi.MessageExchange.Status; import org.apache.ode.bpel.iapi.MyRoleMessageExchange; import org.apache.ode.jbi.msgmap.Mapper; import org.apache.ode.jbi.msgmap.MessageTranslationException; import org.w3c.dom.Element; import javax.jbi.JBIException; import javax.jbi.messaging.ExchangeStatus; import javax.jbi.messaging.Fault; import javax.jbi.messaging.InOnly; import javax.jbi.messaging.InOut; import javax.jbi.messaging.MessagingException; import javax.jbi.messaging.NormalizedMessage; import javax.jbi.servicedesc.ServiceEndpoint; import javax.xml.namespace.QName; import java.util.HashMap; import java.util.Map; /** * Bridge JBI (consumer) to ODE (provider). */ public class OdeService extends ServiceBridge implements JbiMessageExchangeProcessor { private static final Log __log = LogFactory.getLog(OdeService.class); /** utility for tracking outstanding JBI message exchanges. */ private final JbiMexTracker _jbiMexTracker = new JbiMexTracker(); /** JBI-Generated Endpoint */ private ServiceEndpoint _internal; /** External endpoint. */ private ServiceEndpoint _external; private OdeContext _ode; private Element _serviceref; private Endpoint _endpoint; public OdeService(OdeContext odeContext, Endpoint endpoint) throws Exception { _ode = odeContext; _endpoint = endpoint; } /** * Do the JBI endpoint activation. * * @throws JBIException */ public void activate() throws JBIException { if (_serviceref == null) { ServiceEndpoint[] candidates = _ode.getContext().getExternalEndpointsForService(_endpoint.serviceName); if (candidates.length != 0) { _external = candidates[0]; } } _internal = _ode.getContext().activateEndpoint(_endpoint.serviceName, _endpoint.portName); if (__log.isDebugEnabled()) { __log.debug("Activated endpoint " + _endpoint); } // TODO: Is there a race situation here? } /** * Deactivate endpoints in JBI. */ public void deactivate() throws JBIException { _ode.getContext().deactivateEndpoint(_internal); __log.debug("Dectivated endpoint " + _endpoint); } public ServiceEndpoint getInternalServiceEndpoint() { return _internal; } public ServiceEndpoint getExternalServiceEndpoint() { return _external; } public void onJbiMessageExchange(javax.jbi.messaging.MessageExchange jbiMex) throws MessagingException { if (jbiMex.getRole() != javax.jbi.messaging.MessageExchange.Role.PROVIDER) { String errmsg = "Message exchange is not in PROVIDER role as expected: " + jbiMex.getExchangeId(); __log.fatal(errmsg); throw new IllegalArgumentException(errmsg); } if (jbiMex.getStatus() != ExchangeStatus.ACTIVE) { // We can forget about the exchange. __log.debug("Consuming MEX tracker " + jbiMex.getExchangeId()); _jbiMexTracker.consume(jbiMex.getExchangeId()); return; } if (jbiMex.getOperation() == null) { throw new IllegalArgumentException("Null operation in JBI message exchange id=" + jbiMex.getExchangeId() + " endpoint=" + _endpoint); } if (jbiMex.getPattern().equals(org.apache.ode.jbi.MessageExchangePattern.IN_ONLY)) { boolean success = false; Exception err = null; try { invokeOde(jbiMex, ((InOnly) jbiMex).getInMessage()); success = true; } catch (Exception ex) { __log.error("Error invoking ODE.", ex); err = ex; } finally { if (!success) { jbiMex.setStatus(ExchangeStatus.ERROR); if (err != null && jbiMex.getError() == null) jbiMex.setError(err); } else { if (jbiMex.getStatus() == ExchangeStatus.ACTIVE) jbiMex.setStatus(ExchangeStatus.DONE); } _ode.getChannel().send(jbiMex); } } else if (jbiMex.getPattern().equals(org.apache.ode.jbi.MessageExchangePattern.IN_OUT)) { boolean success = false; Exception err = null; try { invokeOde(jbiMex, ((InOut) jbiMex).getInMessage()); success = true; } catch (Exception ex) { __log.error("Error invoking ODE.", ex); err = ex; } catch (Throwable t) { __log.error("Unexpected error invoking ODE.", t); err = new RuntimeException(t); } finally { // If we got an error that wasn't sent. if (jbiMex.getStatus() == ExchangeStatus.ACTIVE && !success) { - if (err != null && jbiMex.getError() != null) { + if (err != null && jbiMex.getError() == null) { jbiMex.setError(err); } jbiMex.setStatus(ExchangeStatus.ERROR); _ode.getChannel().send(jbiMex); } } } else { __log.error("JBI MessageExchange " + jbiMex.getExchangeId() + " is of an unsupported pattern " + jbiMex.getPattern()); jbiMex.setStatus(ExchangeStatus.ERROR); jbiMex.setError(new Exception("Unknown message exchange pattern: " + jbiMex.getPattern())); } } /** * Called from * {@link MessageExchangeContextImpl#onAsyncReply(MyRoleMessageExchange)} * * @param mex * message exchenge */ public void onResponse(MyRoleMessageExchange mex) { __log.debug("Consuming MEX tracker " + mex.getClientId()); javax.jbi.messaging.MessageExchange jbiMex = _jbiMexTracker.consume(mex.getClientId()); if (jbiMex == null) { __log.warn("Ignoring unknown async reply: " + mex); return; } switch (mex.getStatus()) { case FAULT: outResponseFault(mex, jbiMex); break; case RESPONSE: outResponse(mex, jbiMex); break; case FAILURE: outFailure(mex, jbiMex); break; default: __log.warn("Received ODE message exchange in unexpected state: " + mex.getStatus()); } mex.release(); } /** * Forward a JBI input message to ODE. * * @param jbiMex */ private void invokeOde(javax.jbi.messaging.MessageExchange jbiMex, NormalizedMessage request) throws Exception { // If this has already been tracked, we will not invoke! if (_jbiMexTracker.track(jbiMex)) { __log.debug("Skipping JBI MEX " + jbiMex.getExchangeId() + ", already received!"); return; } _ode.getTransactionManager().begin(); boolean success = false; MyRoleMessageExchange odeMex = null; try { if (__log.isDebugEnabled()) { __log.debug("invokeOde() JBI exchangeId=" + jbiMex.getExchangeId() + " endpoint=" + _endpoint + " operation=" + jbiMex.getOperation()); } odeMex = _ode._server.getEngine().createMessageExchange(jbiMex.getExchangeId(), _endpoint.serviceName, jbiMex.getOperation().getLocalPart()); if (odeMex.getOperation() != null) { copyMexProperties(odeMex, jbiMex); javax.wsdl.Message msgdef = odeMex.getOperation().getInput().getMessage(); Message odeRequest = odeMex.createMessage(odeMex.getOperation().getInput().getMessage().getQName()); Mapper mapper = _ode.findMapper(request, odeMex.getOperation()); if (mapper == null) { String errmsg = "Could not find a mapper for request message for JBI MEX " + jbiMex.getExchangeId() + "; ODE MEX " + odeMex.getMessageExchangeId() + " is failed. "; __log.error(errmsg); throw new MessageTranslationException(errmsg); } odeMex.setProperty(Mapper.class.getName(), mapper.getClass().getName()); mapper.toODE(odeRequest, request, msgdef); odeMex.invoke(odeRequest); // Handle the response if it is immediately available. if (odeMex.getStatus() != Status.ASYNC) { __log.debug("ODE MEX " + odeMex + " completed SYNCHRONOUSLY."); onResponse(odeMex); _jbiMexTracker.consume(jbiMex.getExchangeId()); } else { __log.debug("ODE MEX " + odeMex + " completed ASYNCHRONOUSLY."); } } else { __log.error("ODE MEX " + odeMex + " was unroutable."); sendError(jbiMex, new IllegalArgumentException("Unroutable invocation.")); } success = true; // For one-way invocation we do not need to maintain the association if (jbiMex.getPattern().equals(org.apache.ode.jbi.MessageExchangePattern.IN_ONLY)) { __log.debug("Consuming non Req/Res MEX tracker " + jbiMex.getExchangeId() + " with pattern " + jbiMex.getPattern()); _jbiMexTracker.consume(jbiMex.getExchangeId()); } } finally { if (success) { __log.debug("Commiting ODE MEX " + odeMex); _ode.getTransactionManager().commit(); } else { __log.debug("Rolling back ODE MEX " + odeMex); _jbiMexTracker.consume(jbiMex.getExchangeId()); _ode.getTransactionManager().rollback(); } } } private void outFailure(MyRoleMessageExchange odeMex, javax.jbi.messaging.MessageExchange jbiMex) { try { jbiMex.setError(new Exception("MEXFailure")); jbiMex.setStatus(ExchangeStatus.ERROR); // TODO: get failure codes out of the message. _ode.getChannel().send(jbiMex); } catch (MessagingException ex) { __log.fatal("Error bridging ODE out response: ", ex); } } private void outResponse(MyRoleMessageExchange mex, javax.jbi.messaging.MessageExchange jbiMex) { InOut inout = (InOut) jbiMex; try { NormalizedMessage nmsg = inout.createMessage(); String mapperName = mex.getProperty(Mapper.class.getName()); Mapper mapper = _ode.getMapper(mapperName); if (mapper == null) { String errmsg = "Message-mapper " + mapperName + " used in ODE MEX " + mex.getMessageExchangeId() + " is no longer available."; __log.error(errmsg); throw new MessageTranslationException(errmsg); } mapper.toNMS(nmsg, mex.getResponse(), mex.getOperation().getOutput().getMessage(), null); inout.setOutMessage(nmsg); _ode.getChannel().send(inout); } catch (MessagingException ex) { __log.error("Error bridging ODE out response: ", ex); sendError(jbiMex, ex); } catch (MessageTranslationException e) { __log.error("Error translating ODE message " + mex.getResponse() + " to NMS format!", e); sendError(jbiMex, e); } } private void outResponseFault(MyRoleMessageExchange mex, javax.jbi.messaging.MessageExchange jbiMex) { InOut inout = (InOut) jbiMex; try { Fault flt = inout.createFault(); String mapperName = mex.getProperty(Mapper.class.getName()); Mapper mapper = _ode.getMapper(mapperName); if (mapper == null) { String errmsg = "Message-mapper " + mapperName + " used in ODE MEX " + mex.getMessageExchangeId() + " is no longer available."; __log.error(errmsg); throw new MessageTranslationException(errmsg); } QName fault = mex.getFault(); javax.wsdl.Fault wsdlFault = mex.getOperation().getFault(fault.getLocalPart()); if (wsdlFault == null) { sendError(jbiMex, new MessageTranslationException("Unmapped Fault : " + fault + ": " + mex.getFaultExplanation())); } else { mapper.toNMS(flt, mex.getFaultResponse(), wsdlFault.getMessage(), fault); inout.setFault(flt); _ode.getChannel().send(inout); } } catch (MessagingException e) { __log.error("Error bridging ODE fault response: ", e); sendError(jbiMex, e); } catch (MessageTranslationException mte) { __log.error("Error translating ODE fault message " + mex.getFaultResponse() + " to NMS format!", mte); sendError(jbiMex, mte); } } private void sendError(javax.jbi.messaging.MessageExchange jbiMex, Exception error) { try { jbiMex.setError(error); jbiMex.setStatus(ExchangeStatus.ERROR); _ode.getChannel().send(jbiMex); } catch (Exception e) { __log.error("Error sending ERROR status: ", e); } } public Endpoint getEndpoint() { return _endpoint; } /** * Class for tracking outstanding message exchanges from JBI. */ private static class JbiMexTracker { /** * Outstanding JBI-initiated exchanges: mapping for JBI MEX ID to JBI * MEX */ private Map<String, javax.jbi.messaging.MessageExchange> _outstandingJbiExchanges = new HashMap<String, javax.jbi.messaging.MessageExchange>(); synchronized boolean track(javax.jbi.messaging.MessageExchange jbiMex) { boolean found = _outstandingJbiExchanges.containsKey(jbiMex.getExchangeId()); _outstandingJbiExchanges.put(jbiMex.getExchangeId(), jbiMex); return found; } synchronized javax.jbi.messaging.MessageExchange consume(String clientId) { return _outstandingJbiExchanges.remove(clientId); } } }
true
true
public void onJbiMessageExchange(javax.jbi.messaging.MessageExchange jbiMex) throws MessagingException { if (jbiMex.getRole() != javax.jbi.messaging.MessageExchange.Role.PROVIDER) { String errmsg = "Message exchange is not in PROVIDER role as expected: " + jbiMex.getExchangeId(); __log.fatal(errmsg); throw new IllegalArgumentException(errmsg); } if (jbiMex.getStatus() != ExchangeStatus.ACTIVE) { // We can forget about the exchange. __log.debug("Consuming MEX tracker " + jbiMex.getExchangeId()); _jbiMexTracker.consume(jbiMex.getExchangeId()); return; } if (jbiMex.getOperation() == null) { throw new IllegalArgumentException("Null operation in JBI message exchange id=" + jbiMex.getExchangeId() + " endpoint=" + _endpoint); } if (jbiMex.getPattern().equals(org.apache.ode.jbi.MessageExchangePattern.IN_ONLY)) { boolean success = false; Exception err = null; try { invokeOde(jbiMex, ((InOnly) jbiMex).getInMessage()); success = true; } catch (Exception ex) { __log.error("Error invoking ODE.", ex); err = ex; } finally { if (!success) { jbiMex.setStatus(ExchangeStatus.ERROR); if (err != null && jbiMex.getError() == null) jbiMex.setError(err); } else { if (jbiMex.getStatus() == ExchangeStatus.ACTIVE) jbiMex.setStatus(ExchangeStatus.DONE); } _ode.getChannel().send(jbiMex); } } else if (jbiMex.getPattern().equals(org.apache.ode.jbi.MessageExchangePattern.IN_OUT)) { boolean success = false; Exception err = null; try { invokeOde(jbiMex, ((InOut) jbiMex).getInMessage()); success = true; } catch (Exception ex) { __log.error("Error invoking ODE.", ex); err = ex; } catch (Throwable t) { __log.error("Unexpected error invoking ODE.", t); err = new RuntimeException(t); } finally { // If we got an error that wasn't sent. if (jbiMex.getStatus() == ExchangeStatus.ACTIVE && !success) { if (err != null && jbiMex.getError() != null) { jbiMex.setError(err); } jbiMex.setStatus(ExchangeStatus.ERROR); _ode.getChannel().send(jbiMex); } } } else { __log.error("JBI MessageExchange " + jbiMex.getExchangeId() + " is of an unsupported pattern " + jbiMex.getPattern()); jbiMex.setStatus(ExchangeStatus.ERROR); jbiMex.setError(new Exception("Unknown message exchange pattern: " + jbiMex.getPattern())); } }
public void onJbiMessageExchange(javax.jbi.messaging.MessageExchange jbiMex) throws MessagingException { if (jbiMex.getRole() != javax.jbi.messaging.MessageExchange.Role.PROVIDER) { String errmsg = "Message exchange is not in PROVIDER role as expected: " + jbiMex.getExchangeId(); __log.fatal(errmsg); throw new IllegalArgumentException(errmsg); } if (jbiMex.getStatus() != ExchangeStatus.ACTIVE) { // We can forget about the exchange. __log.debug("Consuming MEX tracker " + jbiMex.getExchangeId()); _jbiMexTracker.consume(jbiMex.getExchangeId()); return; } if (jbiMex.getOperation() == null) { throw new IllegalArgumentException("Null operation in JBI message exchange id=" + jbiMex.getExchangeId() + " endpoint=" + _endpoint); } if (jbiMex.getPattern().equals(org.apache.ode.jbi.MessageExchangePattern.IN_ONLY)) { boolean success = false; Exception err = null; try { invokeOde(jbiMex, ((InOnly) jbiMex).getInMessage()); success = true; } catch (Exception ex) { __log.error("Error invoking ODE.", ex); err = ex; } finally { if (!success) { jbiMex.setStatus(ExchangeStatus.ERROR); if (err != null && jbiMex.getError() == null) jbiMex.setError(err); } else { if (jbiMex.getStatus() == ExchangeStatus.ACTIVE) jbiMex.setStatus(ExchangeStatus.DONE); } _ode.getChannel().send(jbiMex); } } else if (jbiMex.getPattern().equals(org.apache.ode.jbi.MessageExchangePattern.IN_OUT)) { boolean success = false; Exception err = null; try { invokeOde(jbiMex, ((InOut) jbiMex).getInMessage()); success = true; } catch (Exception ex) { __log.error("Error invoking ODE.", ex); err = ex; } catch (Throwable t) { __log.error("Unexpected error invoking ODE.", t); err = new RuntimeException(t); } finally { // If we got an error that wasn't sent. if (jbiMex.getStatus() == ExchangeStatus.ACTIVE && !success) { if (err != null && jbiMex.getError() == null) { jbiMex.setError(err); } jbiMex.setStatus(ExchangeStatus.ERROR); _ode.getChannel().send(jbiMex); } } } else { __log.error("JBI MessageExchange " + jbiMex.getExchangeId() + " is of an unsupported pattern " + jbiMex.getPattern()); jbiMex.setStatus(ExchangeStatus.ERROR); jbiMex.setError(new Exception("Unknown message exchange pattern: " + jbiMex.getPattern())); } }
diff --git a/src/to/joe/j2mc/core/visibility/Visibility.java b/src/to/joe/j2mc/core/visibility/Visibility.java index 9850f9b..0c21f17 100644 --- a/src/to/joe/j2mc/core/visibility/Visibility.java +++ b/src/to/joe/j2mc/core/visibility/Visibility.java @@ -1,87 +1,90 @@ package to.joe.j2mc.core.visibility; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.bukkit.entity.Player; import org.kitteh.vanish.VanishPerms; import org.kitteh.vanish.staticaccess.VanishNoPacket; import org.kitteh.vanish.staticaccess.VanishNotLoadedException; import to.joe.j2mc.core.J2MC_Manager; import to.joe.j2mc.core.exceptions.BadPlayerMatchException; import to.joe.j2mc.core.exceptions.NoPlayersException; import to.joe.j2mc.core.exceptions.TooManyPlayersException; public class Visibility { /** * @param searcher * set as null for accessing all players on server * @return */ public List<Player> getOnlinePlayers(Player searcher) { final List<Player> players = Arrays.asList(J2MC_Manager.getCore().getServer().getOnlinePlayers()); if ((searcher != null) && !VanishPerms.canSeeAll(searcher)) { for (final Player player : J2MC_Manager.getCore().getServer().getOnlinePlayers()) { try { if ((player != null) && VanishNoPacket.isVanished(player.getName())) { players.remove(player); } } catch (final VanishNotLoadedException e) { J2MC_Manager.getCore().buggerAll("VanishNoPacket DIED"); } } } return players; } /** * @param target * @param searcher * set as null for accessing all players on server * @return player * @throws TooManyPlayersException * @throws NoPlayersException */ public Player getPlayer(String target, Player searcher) throws BadPlayerMatchException { final List<Player> players = new ArrayList<Player>(); final boolean hidingVanished = (searcher != null) && VanishPerms.canSeeAll(searcher); - for (final Player p : J2MC_Manager.getCore().getServer().getOnlinePlayers()) { + for (final Player player : J2MC_Manager.getCore().getServer().getOnlinePlayers()) { try { - if (!hidingVanished || !VanishNoPacket.isVanished(p.getName())) { - if (p.getName().toLowerCase().contains(target.toLowerCase())) { - players.add(p); + if (!hidingVanished || !VanishNoPacket.isVanished(player.getName())) { + if (player.getName().toLowerCase().contains(target.toLowerCase())) { + players.add(player); + } + if(player.getName().equalsIgnoreCase(target)){ + return player; } } } catch (final VanishNotLoadedException e) { J2MC_Manager.getCore().buggerAll("VanishNoPacket DIED"); } } if (players.size() > 1) { throw new TooManyPlayersException(players.size()); } if (players.size() == 0) { throw new NoPlayersException(); } return players.get(0); } /** * Is the player vanished? * * @param player * @return */ public boolean isVanished(Player player) { try { return VanishNoPacket.isVanished(player.getName()); } catch (final VanishNotLoadedException e) { J2MC_Manager.getCore().buggerAll("VanishNoPacket DIED"); } return false; } }
false
true
public Player getPlayer(String target, Player searcher) throws BadPlayerMatchException { final List<Player> players = new ArrayList<Player>(); final boolean hidingVanished = (searcher != null) && VanishPerms.canSeeAll(searcher); for (final Player p : J2MC_Manager.getCore().getServer().getOnlinePlayers()) { try { if (!hidingVanished || !VanishNoPacket.isVanished(p.getName())) { if (p.getName().toLowerCase().contains(target.toLowerCase())) { players.add(p); } } } catch (final VanishNotLoadedException e) { J2MC_Manager.getCore().buggerAll("VanishNoPacket DIED"); } } if (players.size() > 1) { throw new TooManyPlayersException(players.size()); } if (players.size() == 0) { throw new NoPlayersException(); } return players.get(0); }
public Player getPlayer(String target, Player searcher) throws BadPlayerMatchException { final List<Player> players = new ArrayList<Player>(); final boolean hidingVanished = (searcher != null) && VanishPerms.canSeeAll(searcher); for (final Player player : J2MC_Manager.getCore().getServer().getOnlinePlayers()) { try { if (!hidingVanished || !VanishNoPacket.isVanished(player.getName())) { if (player.getName().toLowerCase().contains(target.toLowerCase())) { players.add(player); } if(player.getName().equalsIgnoreCase(target)){ return player; } } } catch (final VanishNotLoadedException e) { J2MC_Manager.getCore().buggerAll("VanishNoPacket DIED"); } } if (players.size() > 1) { throw new TooManyPlayersException(players.size()); } if (players.size() == 0) { throw new NoPlayersException(); } return players.get(0); }
diff --git a/Android/PopConn/src/com/saranomy/popconn/FeedActivity.java b/Android/PopConn/src/com/saranomy/popconn/FeedActivity.java index 810f1b6..495c609 100644 --- a/Android/PopConn/src/com/saranomy/popconn/FeedActivity.java +++ b/Android/PopConn/src/com/saranomy/popconn/FeedActivity.java @@ -1,189 +1,190 @@ package com.saranomy.popconn; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.jinstagram.entity.comments.CommentData; import org.jinstagram.entity.users.feed.MediaFeed; import org.jinstagram.entity.users.feed.MediaFeedData; import org.jinstagram.exceptions.InstagramException; import twitter4j.Paging; import twitter4j.TwitterException; import android.app.Activity; import android.content.Context; import android.os.AsyncTask; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ListView; import android.widget.ProgressBar; import com.saranomy.popconn.core.InstagramCore; import com.saranomy.popconn.core.TwitterCore; import com.saranomy.popconn.item.Item; import com.saranomy.popconn.item.ItemAdapter; public class FeedActivity extends Activity { private ListView activity_feed_listview; private ProgressBar activity_feed_refresh; private TwitterCore twitterCore; private InstagramCore instagramCore; private List<Item> items; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_feed); syncViewById(); init(); } private void syncViewById() { activity_feed_listview = (ListView) findViewById(R.id.activity_feed_listview); // activity_feed_listview.setOnRefreshListener(new OnRefreshListener() { // @Override // public void onRefresh() { // init(); // } // }); activity_feed_refresh = (ProgressBar) findViewById(R.id.activity_feed_refresh); } private void init() { items = new ArrayList<Item>(); twitterCore = TwitterCore.getInstance(); instagramCore = InstagramCore.getInstance(); if (twitterCore.active) { new LoadTwitterItem().execute(); } else { new LoadInstagramItem().execute(); } } public class LoadTwitterItem extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... arg0) { try { getHomeTimeline(new Paging(1)); } catch (TwitterException e) { e.printStackTrace(); } return null; } private void getHomeTimeline(Paging paging) throws TwitterException { List<twitter4j.Status> statuses = twitterCore.twitter .getHomeTimeline(paging); for (twitter4j.Status status : statuses) { Item item = new Item(); item.socialId = 1; item.name = status.getUser().getScreenName(); item.action = "@" + status.getUser().getName(); item.thumbnail_url = status.getUser().getProfileImageURL(); item.date = status.getCreatedAt().getTime() / 1000L; item.time = countDown(item.date); item.content = status.getText(); String comment = ""; if (status.isRetweet()) { comment = status.getRetweetCount() + " Retweets "; } item.comment = comment; items.add(item); } } @Override protected void onPostExecute(Void result) { new LoadInstagramItem().execute(); super.onPostExecute(result); } } public class LoadInstagramItem extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... arg0) { if (instagramCore.active) { try { MediaFeed mediaFeed = instagramCore.instagram .getUserFeeds(); List<MediaFeedData> mediaFeedData = mediaFeed.getData(); - for (int i = 0; i < 20; i++) { + int maxSize = Math.max(mediaFeedData.size(), 20); + for (int i = 0; i < maxSize; i++) { MediaFeedData media = mediaFeedData.get(i); Item item = new Item(); item.socialId = 2; item.name = media.getUser().getUserName(); item.action = ""; if (media.getLocation() != null) item.action = media.getLocation().getName(); item.thumbnail_url = media.getUser() .getProfilePictureUrl(); item.date = Long.parseLong(media.getCreatedTime()); item.time = countDown(item.date); item.image_url = media.getImages() .getStandardResolution().getImageUrl(); StringBuffer sb = new StringBuffer(); sb.append(media.getLikes().getCount()).append(" likes\n"); List<CommentData> comments = media.getComments() .getComments(); for (CommentData comment : comments) { sb.append(comment.getCommentFrom().getUsername()) .append(": ").append(comment.getText()) .append("\n"); } item.comment = sb.toString(); items.add(item); } } catch (InstagramException e) { e.printStackTrace(); } } return null; } @Override protected void onPostExecute(Void result) { LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); ItemAdapter adapter = new ItemAdapter(inflater, items); Collections.sort(items, Item.comparator); activity_feed_listview.setAdapter(adapter); activity_feed_refresh.setVisibility(View.GONE); activity_feed_listview.setVisibility(View.VISIBLE); // activity_feed_listview.onRefreshComplete(); super.onPostExecute(result); } } public static String countDown(long time) { long delta = (System.currentTimeMillis() / 60000) - (time / 60); if (delta < 60) return delta + "m"; else if (delta < 1440) return Math.round(delta / 60) + "h"; else return Math.round(delta / 1440) + "d"; } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_feed, menu); return true; } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { // TODO Auto-generated method stub return super.onMenuItemSelected(featureId, item); } }
true
true
protected Void doInBackground(Void... arg0) { if (instagramCore.active) { try { MediaFeed mediaFeed = instagramCore.instagram .getUserFeeds(); List<MediaFeedData> mediaFeedData = mediaFeed.getData(); for (int i = 0; i < 20; i++) { MediaFeedData media = mediaFeedData.get(i); Item item = new Item(); item.socialId = 2; item.name = media.getUser().getUserName(); item.action = ""; if (media.getLocation() != null) item.action = media.getLocation().getName(); item.thumbnail_url = media.getUser() .getProfilePictureUrl(); item.date = Long.parseLong(media.getCreatedTime()); item.time = countDown(item.date); item.image_url = media.getImages() .getStandardResolution().getImageUrl(); StringBuffer sb = new StringBuffer(); sb.append(media.getLikes().getCount()).append(" likes\n"); List<CommentData> comments = media.getComments() .getComments(); for (CommentData comment : comments) { sb.append(comment.getCommentFrom().getUsername()) .append(": ").append(comment.getText()) .append("\n"); } item.comment = sb.toString(); items.add(item); } } catch (InstagramException e) { e.printStackTrace(); } } return null; }
protected Void doInBackground(Void... arg0) { if (instagramCore.active) { try { MediaFeed mediaFeed = instagramCore.instagram .getUserFeeds(); List<MediaFeedData> mediaFeedData = mediaFeed.getData(); int maxSize = Math.max(mediaFeedData.size(), 20); for (int i = 0; i < maxSize; i++) { MediaFeedData media = mediaFeedData.get(i); Item item = new Item(); item.socialId = 2; item.name = media.getUser().getUserName(); item.action = ""; if (media.getLocation() != null) item.action = media.getLocation().getName(); item.thumbnail_url = media.getUser() .getProfilePictureUrl(); item.date = Long.parseLong(media.getCreatedTime()); item.time = countDown(item.date); item.image_url = media.getImages() .getStandardResolution().getImageUrl(); StringBuffer sb = new StringBuffer(); sb.append(media.getLikes().getCount()).append(" likes\n"); List<CommentData> comments = media.getComments() .getComments(); for (CommentData comment : comments) { sb.append(comment.getCommentFrom().getUsername()) .append(": ").append(comment.getText()) .append("\n"); } item.comment = sb.toString(); items.add(item); } } catch (InstagramException e) { e.printStackTrace(); } } return null; }
diff --git a/src/com/atlauncher/gui/InstanceInstallerDialog.java b/src/com/atlauncher/gui/InstanceInstallerDialog.java index e305c35f..d58d4347 100644 --- a/src/com/atlauncher/gui/InstanceInstallerDialog.java +++ b/src/com/atlauncher/gui/InstanceInstallerDialog.java @@ -1,497 +1,507 @@ /** * Copyright 2013 by ATLauncher and Contributors * * This work is licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported License. * To view a copy of this license, visit http://creativecommons.org/licenses/by-sa/3.0/. */ package com.atlauncher.gui; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.concurrent.ExecutionException; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.JTextField; import com.atlauncher.App; import com.atlauncher.data.Instance; import com.atlauncher.data.Pack; import com.atlauncher.data.Version; import com.atlauncher.workers.InstanceInstaller; public class InstanceInstallerDialog extends JDialog { private boolean isReinstall = false; private boolean isServer = false; private Pack pack = null; private Instance instance = null; private JPanel top; private JPanel middle; private JPanel bottom; private JButton install; private JButton cancel; private JProgressBar progressBar; private JProgressBar subProgressBar; private JLabel instanceNameLabel; private JTextField instanceNameField; private JLabel versionLabel; private JComboBox<Version> versionsDropDown; private ArrayList<Version> versions = new ArrayList<Version>(); private JLabel installForLabel; private JCheckBox installForMe; private JLabel useLatestLWJGLLabel; private JCheckBox useLatestLWJGL; public InstanceInstallerDialog(Object object) { this(object, false, false); } public InstanceInstallerDialog(Pack pack, boolean isServer) { this((Object) pack, false, true); } public InstanceInstallerDialog(Object object, boolean isUpdate, final boolean isServer) { super(App.settings.getParent(), ModalityType.APPLICATION_MODAL); if (object instanceof Pack) { pack = (Pack) object; setTitle(App.settings.getLocalizedString("common.installing") + " " + pack.getName()); if (isServer) { setTitle(App.settings.getLocalizedString("common.installing") + " " + pack.getName() + " " + App.settings.getLocalizedString("common.server")); this.isServer = true; } } else { instance = (Instance) object; pack = instance.getRealPack(); isReinstall = true; // We're reinstalling setTitle(App.settings.getLocalizedString("common.reinstalling") + " " + instance.getName()); } setSize(400, 225); setLocationRelativeTo(App.settings.getParent()); setLayout(new BorderLayout()); setResizable(false); // Top Panel Stuff top = new JPanel(); top.add(new JLabel(((isReinstall) ? App.settings.getLocalizedString("common.reinstalling") : App.settings.getLocalizedString("common.installing")) + " " + pack.getName())); // Middle Panel Stuff middle = new JPanel(); middle.setLayout(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 0; if (!this.isServer) { gbc.anchor = GridBagConstraints.BASELINE_TRAILING; instanceNameLabel = new JLabel(App.settings.getLocalizedString("instance.name") + ": "); middle.add(instanceNameLabel, gbc); gbc.gridx++; gbc.anchor = GridBagConstraints.BASELINE_LEADING; instanceNameField = new JTextField(17); instanceNameField.setText(((isReinstall) ? instance.getName() : pack.getName())); if (isReinstall) { instanceNameField.setEnabled(false); } middle.add(instanceNameField, gbc); gbc.gridx = 0; gbc.gridy++; } gbc.anchor = GridBagConstraints.BASELINE_TRAILING; versionLabel = new JLabel(App.settings.getLocalizedString("instance.versiontoinstall") + ": "); middle.add(versionLabel, gbc); gbc.gridx++; gbc.anchor = GridBagConstraints.BASELINE_LEADING; versionsDropDown = new JComboBox<Version>(); if (pack.isTester()) { for (int i = 0; i < pack.getDevVersionCount(); i++) { versions.add(new Version(true, pack.getDevVersion(i), pack .getDevMinecraftVersion(i))); } } for (int i = 0; i < pack.getVersionCount(); i++) { versions.add(new Version(false, pack.getVersion(i), pack.getMinecraftVersion(i))); } for (Version version : versions) { versionsDropDown.addItem(version); } if (isUpdate) { if (pack.isTester()) { versionsDropDown.setSelectedIndex(1); } else { versionsDropDown.setSelectedIndex(0); } } else if (isReinstall) { for (Version version : versions) { if (version.getVersion().equalsIgnoreCase(instance.getVersion())) { versionsDropDown.setSelectedItem(version); } } } versionsDropDown.setPreferredSize(new Dimension(200, 25)); versionsDropDown.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Version selected = (Version) versionsDropDown.getSelectedItem(); if (App.settings.getMinecraftInstallMethod(selected.getMinecraftVersion()) .equalsIgnoreCase("new")) { useLatestLWJGLLabel.setVisible(false); useLatestLWJGL.setVisible(false); useLatestLWJGL.setSelected(false); } else if (pack.isLatestLWJGLEnabled()) { useLatestLWJGLLabel.setVisible(false); useLatestLWJGL.setVisible(false); useLatestLWJGL.setSelected(true); } else { useLatestLWJGLLabel.setVisible(true); useLatestLWJGL.setVisible(true); } } }); middle.add(versionsDropDown, gbc); if (!this.isServer) { if (!isReinstall) { gbc.gridx = 0; gbc.gridy++; gbc.anchor = GridBagConstraints.BASELINE_TRAILING; installForLabel = new JLabel( App.settings.getLocalizedString("instance.installjustforme") + "? "); middle.add(installForLabel, gbc); gbc.gridx++; gbc.anchor = GridBagConstraints.BASELINE_LEADING; installForMe = new JCheckBox(); middle.add(installForMe, gbc); } gbc.gridx = 0; gbc.gridy++; gbc.anchor = GridBagConstraints.BASELINE_TRAILING; useLatestLWJGLLabel = new JLabel( App.settings.getLocalizedString("instance.uselatestlwjgl") + "? "); middle.add(useLatestLWJGLLabel, gbc); gbc.gridx++; gbc.anchor = GridBagConstraints.BASELINE_LEADING; useLatestLWJGL = new JCheckBox(); middle.add(useLatestLWJGL, gbc); } Version selected = (Version) versionsDropDown.getSelectedItem(); if (!isServer) { if (App.settings.getMinecraftInstallMethod(selected.getMinecraftVersion()) .equalsIgnoreCase("new")) { useLatestLWJGLLabel.setVisible(false); useLatestLWJGL.setVisible(false); } else if (pack.isLatestLWJGLEnabled()) { useLatestLWJGLLabel.setVisible(false); useLatestLWJGL.setVisible(false); useLatestLWJGL.setSelected(true); } else { useLatestLWJGLLabel.setVisible(true); useLatestLWJGL.setVisible(true); } } // Bottom Panel Stuff bottom = new JPanel(); bottom.setLayout(new FlowLayout()); install = new JButton( ((isReinstall) ? (isUpdate ? App.settings.getLocalizedString("common.update") : App.settings.getLocalizedString("common.reinstall")) : App.settings.getLocalizedString("common.install"))); install.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (!isReinstall && !isServer && App.settings.isInstance(instanceNameField.getText())) { JOptionPane.showMessageDialog( App.settings.getParent(), "<html><center>" + App.settings.getLocalizedString("common.error") + "<br/><br/>" + App.settings.getLocalizedString("instance.alreadyinstance", instanceNameField.getText() + "<br/><br/>") + "</center></html>", App.settings .getLocalizedString("common.error"), JOptionPane.ERROR_MESSAGE); return; } final Version version = (Version) versionsDropDown.getSelectedItem(); final JDialog dialog = new JDialog(App.settings.getParent(), ((isReinstall) ? App.settings.getLocalizedString("common.reinstalling") : App.settings.getLocalizedString("common.installing")) + " " - + pack.getName() + " " + version.getVersion(), - ModalityType.DOCUMENT_MODAL); + + pack.getName() + + " " + + version.getVersion() + + ((isServer) ? " " + App.settings.getLocalizedString("common.server") + : ""), ModalityType.DOCUMENT_MODAL); dialog.setLocationRelativeTo(App.settings.getParent()); dialog.setSize(300, 100); dialog.setResizable(false); JPanel topPanel = new JPanel(); topPanel.setLayout(new BorderLayout()); final JLabel doing = new JLabel(App.settings.getLocalizedString( "instance.startingprocess", ((isReinstall) ? App.settings.getLocalizedString("common.reinstall") : App.settings.getLocalizedString("common.install")))); doing.setHorizontalAlignment(JLabel.CENTER); doing.setVerticalAlignment(JLabel.TOP); topPanel.add(doing); JPanel bottomPanel = new JPanel(); bottomPanel.setLayout(new BorderLayout()); progressBar = new JProgressBar(0, 100); bottomPanel.add(progressBar, BorderLayout.NORTH); progressBar.setIndeterminate(true); subProgressBar = new JProgressBar(0, 100); bottomPanel.add(subProgressBar, BorderLayout.SOUTH); subProgressBar.setValue(0); subProgressBar.setVisible(false); dialog.add(topPanel, BorderLayout.CENTER); dialog.add(bottomPanel, BorderLayout.SOUTH); final InstanceInstaller instanceInstaller = new InstanceInstaller((isServer ? "" : instanceNameField.getText()), pack, version.getVersion(), version .getMinecraftVersion(), (useLatestLWJGL == null ? false : useLatestLWJGL .isSelected()), isReinstall, isServer) { protected void done() { Boolean success = false; int type; String text; String title; if (isCancelled()) { type = JOptionPane.ERROR_MESSAGE; text = pack.getName() + " " + version.getVersion() + " " + App.settings.getLocalizedString("common.wasnt") + " " + ((isReinstall) ? App.settings .getLocalizedString("common.reinstalled") : App.settings.getLocalizedString("common.installed")) + "<br/><br/>" + App.settings.getLocalizedString("instance.actioncancelled"); title = pack.getName() + " " + version.getVersion() + " " + App.settings.getLocalizedString("common.not") + " " + ((isReinstall) ? App.settings .getLocalizedString("common.reinstalled") : App.settings.getLocalizedString("common.installed")); if (isReinstall) { App.settings.setInstanceUnplayable(instance); } } else { try { success = get(); } catch (InterruptedException e) { App.settings.getConsole().logStackTrace(e); } catch (ExecutionException e) { App.settings.getConsole().logStackTrace(e); } if (success) { type = JOptionPane.INFORMATION_MESSAGE; text = pack.getName() + " " + version.getVersion() + " " + App.settings.getLocalizedString("common.hasbeen") + " " + ((isReinstall) ? App.settings .getLocalizedString("common.reinstalled") : App.settings .getLocalizedString("common.installed")) + "<br/><br/>" - + App.settings.getLocalizedString("instance.findit"); + + ((isServer) ? App.settings + .getLocalizedString("instance.finditserver", + "<br/><br/>" + + this.getRootDirectory() + .getAbsolutePath()) + : App.settings + .getLocalizedString("instance.findit")); title = pack.getName() + " " + version.getVersion() + " " + App.settings.getLocalizedString("common.installed"); + System.out.println(isServer); if (isReinstall) { instance.setVersion(version.getVersion()); instance.setMinecraftVersion(this.getMinecraftVersion()); instance.setModsInstalled(this.getModsInstalled()); instance.setJarOrder(this.getJarOrder()); instance.setIsNewLaunchMethod(this.isNewLaunchMethod()); if (this.isNewLaunchMethod()) { instance.setLibrariesNeeded(this.getLibrariesNeeded()); instance.setMinecraftArguments(this.getMinecraftArguments()); instance.setMainClass(this.getMainClass()); } if (version.isDevVersion()) { instance.setDevVersion(); } else { instance.setNotDevVersion(); } if (!instance.isPlayable()) { instance.setPlayable(); } } else if (isServer) { } else { App.settings.getInstances().add( new Instance(instanceNameField.getText(), pack .getName(), pack, installForMe.isSelected(), version.getVersion(), this .getMinecraftVersion(), this .getMemory(), this.getPermGen(), this .getModsInstalled(), this.getJarOrder(), this.getLibrariesNeeded(), this.getMinecraftArguments(), this .getMainClass(), version.isDevVersion(), this .isNewLaunchMethod())); // Add It } App.settings.saveInstances(); App.settings.reloadInstancesPanel(); if (pack.isLoggingEnabled() && App.settings.enableLogs()) { App.settings.apiCall(App.settings.getAccount() .getMinecraftUsername(), "packinstalled", pack.getID() + "", version.getVersion()); } } else { if (isReinstall) { type = JOptionPane.ERROR_MESSAGE; text = pack.getName() + " " + version.getVersion() + " " + App.settings.getLocalizedString("common.wasnt") + " " + App.settings.getLocalizedString("common.reinstalled") + "<br/><br/>" + App.settings .getLocalizedString("instance.nolongerplayable") + "<br/><br/>" + App.settings .getLocalizedString("instance.checkerrorlogs") + "!"; title = pack.getName() + " " + version.getVersion() + " " + App.settings.getLocalizedString("common.not") + " " + App.settings.getLocalizedString("common.reinstalled"); App.settings.setInstanceUnplayable(instance); } else { // Install failed so delete the folder and clear Temp Dir Utils.delete(this.getRootDirectory()); type = JOptionPane.ERROR_MESSAGE; text = pack.getName() + " " + version.getVersion() + " " + App.settings.getLocalizedString("common.wasnt") + " " + App.settings.getLocalizedString("common.installed") + "<br/><br/>" + App.settings .getLocalizedString("instance.checkerrorlogs") + "!"; title = pack.getName() + " " + version.getVersion() + " " + App.settings.getLocalizedString("common.not") + " " + App.settings.getLocalizedString("common.installed"); } } } dialog.dispose(); Utils.cleanTempDirectory(); JOptionPane.showMessageDialog(App.settings.getParent(), "<html><center>" + text + "</center></html>", title, type); } }; instanceInstaller.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { if ("progress" == evt.getPropertyName()) { if (progressBar.isIndeterminate()) { progressBar.setIndeterminate(false); } int progress = (Integer) evt.getNewValue(); if (progress > 100) { progress = 100; } progressBar.setValue(progress); } else if ("subprogress" == evt.getPropertyName()) { if (!subProgressBar.isVisible()) { subProgressBar.setVisible(true); } if (subProgressBar.isIndeterminate()) { subProgressBar.setIndeterminate(false); } int progress = (Integer) evt.getNewValue(); if (progress > 100) { progress = 100; } if (progress == 0) { subProgressBar.setVisible(false); } subProgressBar.setValue(progress); } else if ("subprogressint" == evt.getPropertyName()) { if (!subProgressBar.isVisible()) { subProgressBar.setVisible(true); } if (!subProgressBar.isIndeterminate()) { subProgressBar.setIndeterminate(true); } } else if ("doing" == evt.getPropertyName()) { String doingText = (String) evt.getNewValue(); doing.setText(doingText); } } }); dialog.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { instanceInstaller.cancel(true); } }); if (isReinstall) { instanceInstaller.setInstance(instance); } instanceInstaller.execute(); dispose(); dialog.setVisible(true); } }); cancel = new JButton(App.settings.getLocalizedString("common.cancel")); cancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); } }); bottom.add(install); bottom.add(cancel); add(top, BorderLayout.NORTH); add(middle, BorderLayout.CENTER); add(bottom, BorderLayout.SOUTH); setVisible(true); } }
false
true
public InstanceInstallerDialog(Object object, boolean isUpdate, final boolean isServer) { super(App.settings.getParent(), ModalityType.APPLICATION_MODAL); if (object instanceof Pack) { pack = (Pack) object; setTitle(App.settings.getLocalizedString("common.installing") + " " + pack.getName()); if (isServer) { setTitle(App.settings.getLocalizedString("common.installing") + " " + pack.getName() + " " + App.settings.getLocalizedString("common.server")); this.isServer = true; } } else { instance = (Instance) object; pack = instance.getRealPack(); isReinstall = true; // We're reinstalling setTitle(App.settings.getLocalizedString("common.reinstalling") + " " + instance.getName()); } setSize(400, 225); setLocationRelativeTo(App.settings.getParent()); setLayout(new BorderLayout()); setResizable(false); // Top Panel Stuff top = new JPanel(); top.add(new JLabel(((isReinstall) ? App.settings.getLocalizedString("common.reinstalling") : App.settings.getLocalizedString("common.installing")) + " " + pack.getName())); // Middle Panel Stuff middle = new JPanel(); middle.setLayout(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 0; if (!this.isServer) { gbc.anchor = GridBagConstraints.BASELINE_TRAILING; instanceNameLabel = new JLabel(App.settings.getLocalizedString("instance.name") + ": "); middle.add(instanceNameLabel, gbc); gbc.gridx++; gbc.anchor = GridBagConstraints.BASELINE_LEADING; instanceNameField = new JTextField(17); instanceNameField.setText(((isReinstall) ? instance.getName() : pack.getName())); if (isReinstall) { instanceNameField.setEnabled(false); } middle.add(instanceNameField, gbc); gbc.gridx = 0; gbc.gridy++; } gbc.anchor = GridBagConstraints.BASELINE_TRAILING; versionLabel = new JLabel(App.settings.getLocalizedString("instance.versiontoinstall") + ": "); middle.add(versionLabel, gbc); gbc.gridx++; gbc.anchor = GridBagConstraints.BASELINE_LEADING; versionsDropDown = new JComboBox<Version>(); if (pack.isTester()) { for (int i = 0; i < pack.getDevVersionCount(); i++) { versions.add(new Version(true, pack.getDevVersion(i), pack .getDevMinecraftVersion(i))); } } for (int i = 0; i < pack.getVersionCount(); i++) { versions.add(new Version(false, pack.getVersion(i), pack.getMinecraftVersion(i))); } for (Version version : versions) { versionsDropDown.addItem(version); } if (isUpdate) { if (pack.isTester()) { versionsDropDown.setSelectedIndex(1); } else { versionsDropDown.setSelectedIndex(0); } } else if (isReinstall) { for (Version version : versions) { if (version.getVersion().equalsIgnoreCase(instance.getVersion())) { versionsDropDown.setSelectedItem(version); } } } versionsDropDown.setPreferredSize(new Dimension(200, 25)); versionsDropDown.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Version selected = (Version) versionsDropDown.getSelectedItem(); if (App.settings.getMinecraftInstallMethod(selected.getMinecraftVersion()) .equalsIgnoreCase("new")) { useLatestLWJGLLabel.setVisible(false); useLatestLWJGL.setVisible(false); useLatestLWJGL.setSelected(false); } else if (pack.isLatestLWJGLEnabled()) { useLatestLWJGLLabel.setVisible(false); useLatestLWJGL.setVisible(false); useLatestLWJGL.setSelected(true); } else { useLatestLWJGLLabel.setVisible(true); useLatestLWJGL.setVisible(true); } } }); middle.add(versionsDropDown, gbc); if (!this.isServer) { if (!isReinstall) { gbc.gridx = 0; gbc.gridy++; gbc.anchor = GridBagConstraints.BASELINE_TRAILING; installForLabel = new JLabel( App.settings.getLocalizedString("instance.installjustforme") + "? "); middle.add(installForLabel, gbc); gbc.gridx++; gbc.anchor = GridBagConstraints.BASELINE_LEADING; installForMe = new JCheckBox(); middle.add(installForMe, gbc); } gbc.gridx = 0; gbc.gridy++; gbc.anchor = GridBagConstraints.BASELINE_TRAILING; useLatestLWJGLLabel = new JLabel( App.settings.getLocalizedString("instance.uselatestlwjgl") + "? "); middle.add(useLatestLWJGLLabel, gbc); gbc.gridx++; gbc.anchor = GridBagConstraints.BASELINE_LEADING; useLatestLWJGL = new JCheckBox(); middle.add(useLatestLWJGL, gbc); } Version selected = (Version) versionsDropDown.getSelectedItem(); if (!isServer) { if (App.settings.getMinecraftInstallMethod(selected.getMinecraftVersion()) .equalsIgnoreCase("new")) { useLatestLWJGLLabel.setVisible(false); useLatestLWJGL.setVisible(false); } else if (pack.isLatestLWJGLEnabled()) { useLatestLWJGLLabel.setVisible(false); useLatestLWJGL.setVisible(false); useLatestLWJGL.setSelected(true); } else { useLatestLWJGLLabel.setVisible(true); useLatestLWJGL.setVisible(true); } } // Bottom Panel Stuff bottom = new JPanel(); bottom.setLayout(new FlowLayout()); install = new JButton( ((isReinstall) ? (isUpdate ? App.settings.getLocalizedString("common.update") : App.settings.getLocalizedString("common.reinstall")) : App.settings.getLocalizedString("common.install"))); install.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (!isReinstall && !isServer && App.settings.isInstance(instanceNameField.getText())) { JOptionPane.showMessageDialog( App.settings.getParent(), "<html><center>" + App.settings.getLocalizedString("common.error") + "<br/><br/>" + App.settings.getLocalizedString("instance.alreadyinstance", instanceNameField.getText() + "<br/><br/>") + "</center></html>", App.settings .getLocalizedString("common.error"), JOptionPane.ERROR_MESSAGE); return; } final Version version = (Version) versionsDropDown.getSelectedItem(); final JDialog dialog = new JDialog(App.settings.getParent(), ((isReinstall) ? App.settings.getLocalizedString("common.reinstalling") : App.settings.getLocalizedString("common.installing")) + " " + pack.getName() + " " + version.getVersion(), ModalityType.DOCUMENT_MODAL); dialog.setLocationRelativeTo(App.settings.getParent()); dialog.setSize(300, 100); dialog.setResizable(false); JPanel topPanel = new JPanel(); topPanel.setLayout(new BorderLayout()); final JLabel doing = new JLabel(App.settings.getLocalizedString( "instance.startingprocess", ((isReinstall) ? App.settings.getLocalizedString("common.reinstall") : App.settings.getLocalizedString("common.install")))); doing.setHorizontalAlignment(JLabel.CENTER); doing.setVerticalAlignment(JLabel.TOP); topPanel.add(doing); JPanel bottomPanel = new JPanel(); bottomPanel.setLayout(new BorderLayout()); progressBar = new JProgressBar(0, 100); bottomPanel.add(progressBar, BorderLayout.NORTH); progressBar.setIndeterminate(true); subProgressBar = new JProgressBar(0, 100); bottomPanel.add(subProgressBar, BorderLayout.SOUTH); subProgressBar.setValue(0); subProgressBar.setVisible(false); dialog.add(topPanel, BorderLayout.CENTER); dialog.add(bottomPanel, BorderLayout.SOUTH); final InstanceInstaller instanceInstaller = new InstanceInstaller((isServer ? "" : instanceNameField.getText()), pack, version.getVersion(), version .getMinecraftVersion(), (useLatestLWJGL == null ? false : useLatestLWJGL .isSelected()), isReinstall, isServer) { protected void done() { Boolean success = false; int type; String text; String title; if (isCancelled()) { type = JOptionPane.ERROR_MESSAGE; text = pack.getName() + " " + version.getVersion() + " " + App.settings.getLocalizedString("common.wasnt") + " " + ((isReinstall) ? App.settings .getLocalizedString("common.reinstalled") : App.settings.getLocalizedString("common.installed")) + "<br/><br/>" + App.settings.getLocalizedString("instance.actioncancelled"); title = pack.getName() + " " + version.getVersion() + " " + App.settings.getLocalizedString("common.not") + " " + ((isReinstall) ? App.settings .getLocalizedString("common.reinstalled") : App.settings.getLocalizedString("common.installed")); if (isReinstall) { App.settings.setInstanceUnplayable(instance); } } else { try { success = get(); } catch (InterruptedException e) { App.settings.getConsole().logStackTrace(e); } catch (ExecutionException e) { App.settings.getConsole().logStackTrace(e); } if (success) { type = JOptionPane.INFORMATION_MESSAGE; text = pack.getName() + " " + version.getVersion() + " " + App.settings.getLocalizedString("common.hasbeen") + " " + ((isReinstall) ? App.settings .getLocalizedString("common.reinstalled") : App.settings .getLocalizedString("common.installed")) + "<br/><br/>" + App.settings.getLocalizedString("instance.findit"); title = pack.getName() + " " + version.getVersion() + " " + App.settings.getLocalizedString("common.installed"); if (isReinstall) { instance.setVersion(version.getVersion()); instance.setMinecraftVersion(this.getMinecraftVersion()); instance.setModsInstalled(this.getModsInstalled()); instance.setJarOrder(this.getJarOrder()); instance.setIsNewLaunchMethod(this.isNewLaunchMethod()); if (this.isNewLaunchMethod()) { instance.setLibrariesNeeded(this.getLibrariesNeeded()); instance.setMinecraftArguments(this.getMinecraftArguments()); instance.setMainClass(this.getMainClass()); } if (version.isDevVersion()) { instance.setDevVersion(); } else { instance.setNotDevVersion(); } if (!instance.isPlayable()) { instance.setPlayable(); } } else if (isServer) { } else { App.settings.getInstances().add( new Instance(instanceNameField.getText(), pack .getName(), pack, installForMe.isSelected(), version.getVersion(), this .getMinecraftVersion(), this .getMemory(), this.getPermGen(), this .getModsInstalled(), this.getJarOrder(), this.getLibrariesNeeded(), this.getMinecraftArguments(), this .getMainClass(), version.isDevVersion(), this .isNewLaunchMethod())); // Add It } App.settings.saveInstances(); App.settings.reloadInstancesPanel(); if (pack.isLoggingEnabled() && App.settings.enableLogs()) { App.settings.apiCall(App.settings.getAccount() .getMinecraftUsername(), "packinstalled", pack.getID() + "", version.getVersion()); } } else { if (isReinstall) { type = JOptionPane.ERROR_MESSAGE; text = pack.getName() + " " + version.getVersion() + " " + App.settings.getLocalizedString("common.wasnt") + " " + App.settings.getLocalizedString("common.reinstalled") + "<br/><br/>" + App.settings .getLocalizedString("instance.nolongerplayable") + "<br/><br/>" + App.settings .getLocalizedString("instance.checkerrorlogs") + "!"; title = pack.getName() + " " + version.getVersion() + " " + App.settings.getLocalizedString("common.not") + " " + App.settings.getLocalizedString("common.reinstalled"); App.settings.setInstanceUnplayable(instance); } else { // Install failed so delete the folder and clear Temp Dir Utils.delete(this.getRootDirectory()); type = JOptionPane.ERROR_MESSAGE; text = pack.getName() + " " + version.getVersion() + " " + App.settings.getLocalizedString("common.wasnt") + " " + App.settings.getLocalizedString("common.installed") + "<br/><br/>" + App.settings .getLocalizedString("instance.checkerrorlogs") + "!"; title = pack.getName() + " " + version.getVersion() + " " + App.settings.getLocalizedString("common.not") + " " + App.settings.getLocalizedString("common.installed"); } } } dialog.dispose(); Utils.cleanTempDirectory(); JOptionPane.showMessageDialog(App.settings.getParent(), "<html><center>" + text + "</center></html>", title, type); } }; instanceInstaller.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { if ("progress" == evt.getPropertyName()) { if (progressBar.isIndeterminate()) { progressBar.setIndeterminate(false); } int progress = (Integer) evt.getNewValue(); if (progress > 100) { progress = 100; } progressBar.setValue(progress); } else if ("subprogress" == evt.getPropertyName()) { if (!subProgressBar.isVisible()) { subProgressBar.setVisible(true); } if (subProgressBar.isIndeterminate()) { subProgressBar.setIndeterminate(false); } int progress = (Integer) evt.getNewValue(); if (progress > 100) { progress = 100; } if (progress == 0) { subProgressBar.setVisible(false); } subProgressBar.setValue(progress); } else if ("subprogressint" == evt.getPropertyName()) { if (!subProgressBar.isVisible()) { subProgressBar.setVisible(true); } if (!subProgressBar.isIndeterminate()) { subProgressBar.setIndeterminate(true); } } else if ("doing" == evt.getPropertyName()) { String doingText = (String) evt.getNewValue(); doing.setText(doingText); } } }); dialog.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { instanceInstaller.cancel(true); } }); if (isReinstall) { instanceInstaller.setInstance(instance); } instanceInstaller.execute(); dispose(); dialog.setVisible(true); } }); cancel = new JButton(App.settings.getLocalizedString("common.cancel")); cancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); } }); bottom.add(install); bottom.add(cancel); add(top, BorderLayout.NORTH); add(middle, BorderLayout.CENTER); add(bottom, BorderLayout.SOUTH); setVisible(true); }
public InstanceInstallerDialog(Object object, boolean isUpdate, final boolean isServer) { super(App.settings.getParent(), ModalityType.APPLICATION_MODAL); if (object instanceof Pack) { pack = (Pack) object; setTitle(App.settings.getLocalizedString("common.installing") + " " + pack.getName()); if (isServer) { setTitle(App.settings.getLocalizedString("common.installing") + " " + pack.getName() + " " + App.settings.getLocalizedString("common.server")); this.isServer = true; } } else { instance = (Instance) object; pack = instance.getRealPack(); isReinstall = true; // We're reinstalling setTitle(App.settings.getLocalizedString("common.reinstalling") + " " + instance.getName()); } setSize(400, 225); setLocationRelativeTo(App.settings.getParent()); setLayout(new BorderLayout()); setResizable(false); // Top Panel Stuff top = new JPanel(); top.add(new JLabel(((isReinstall) ? App.settings.getLocalizedString("common.reinstalling") : App.settings.getLocalizedString("common.installing")) + " " + pack.getName())); // Middle Panel Stuff middle = new JPanel(); middle.setLayout(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 0; if (!this.isServer) { gbc.anchor = GridBagConstraints.BASELINE_TRAILING; instanceNameLabel = new JLabel(App.settings.getLocalizedString("instance.name") + ": "); middle.add(instanceNameLabel, gbc); gbc.gridx++; gbc.anchor = GridBagConstraints.BASELINE_LEADING; instanceNameField = new JTextField(17); instanceNameField.setText(((isReinstall) ? instance.getName() : pack.getName())); if (isReinstall) { instanceNameField.setEnabled(false); } middle.add(instanceNameField, gbc); gbc.gridx = 0; gbc.gridy++; } gbc.anchor = GridBagConstraints.BASELINE_TRAILING; versionLabel = new JLabel(App.settings.getLocalizedString("instance.versiontoinstall") + ": "); middle.add(versionLabel, gbc); gbc.gridx++; gbc.anchor = GridBagConstraints.BASELINE_LEADING; versionsDropDown = new JComboBox<Version>(); if (pack.isTester()) { for (int i = 0; i < pack.getDevVersionCount(); i++) { versions.add(new Version(true, pack.getDevVersion(i), pack .getDevMinecraftVersion(i))); } } for (int i = 0; i < pack.getVersionCount(); i++) { versions.add(new Version(false, pack.getVersion(i), pack.getMinecraftVersion(i))); } for (Version version : versions) { versionsDropDown.addItem(version); } if (isUpdate) { if (pack.isTester()) { versionsDropDown.setSelectedIndex(1); } else { versionsDropDown.setSelectedIndex(0); } } else if (isReinstall) { for (Version version : versions) { if (version.getVersion().equalsIgnoreCase(instance.getVersion())) { versionsDropDown.setSelectedItem(version); } } } versionsDropDown.setPreferredSize(new Dimension(200, 25)); versionsDropDown.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Version selected = (Version) versionsDropDown.getSelectedItem(); if (App.settings.getMinecraftInstallMethod(selected.getMinecraftVersion()) .equalsIgnoreCase("new")) { useLatestLWJGLLabel.setVisible(false); useLatestLWJGL.setVisible(false); useLatestLWJGL.setSelected(false); } else if (pack.isLatestLWJGLEnabled()) { useLatestLWJGLLabel.setVisible(false); useLatestLWJGL.setVisible(false); useLatestLWJGL.setSelected(true); } else { useLatestLWJGLLabel.setVisible(true); useLatestLWJGL.setVisible(true); } } }); middle.add(versionsDropDown, gbc); if (!this.isServer) { if (!isReinstall) { gbc.gridx = 0; gbc.gridy++; gbc.anchor = GridBagConstraints.BASELINE_TRAILING; installForLabel = new JLabel( App.settings.getLocalizedString("instance.installjustforme") + "? "); middle.add(installForLabel, gbc); gbc.gridx++; gbc.anchor = GridBagConstraints.BASELINE_LEADING; installForMe = new JCheckBox(); middle.add(installForMe, gbc); } gbc.gridx = 0; gbc.gridy++; gbc.anchor = GridBagConstraints.BASELINE_TRAILING; useLatestLWJGLLabel = new JLabel( App.settings.getLocalizedString("instance.uselatestlwjgl") + "? "); middle.add(useLatestLWJGLLabel, gbc); gbc.gridx++; gbc.anchor = GridBagConstraints.BASELINE_LEADING; useLatestLWJGL = new JCheckBox(); middle.add(useLatestLWJGL, gbc); } Version selected = (Version) versionsDropDown.getSelectedItem(); if (!isServer) { if (App.settings.getMinecraftInstallMethod(selected.getMinecraftVersion()) .equalsIgnoreCase("new")) { useLatestLWJGLLabel.setVisible(false); useLatestLWJGL.setVisible(false); } else if (pack.isLatestLWJGLEnabled()) { useLatestLWJGLLabel.setVisible(false); useLatestLWJGL.setVisible(false); useLatestLWJGL.setSelected(true); } else { useLatestLWJGLLabel.setVisible(true); useLatestLWJGL.setVisible(true); } } // Bottom Panel Stuff bottom = new JPanel(); bottom.setLayout(new FlowLayout()); install = new JButton( ((isReinstall) ? (isUpdate ? App.settings.getLocalizedString("common.update") : App.settings.getLocalizedString("common.reinstall")) : App.settings.getLocalizedString("common.install"))); install.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (!isReinstall && !isServer && App.settings.isInstance(instanceNameField.getText())) { JOptionPane.showMessageDialog( App.settings.getParent(), "<html><center>" + App.settings.getLocalizedString("common.error") + "<br/><br/>" + App.settings.getLocalizedString("instance.alreadyinstance", instanceNameField.getText() + "<br/><br/>") + "</center></html>", App.settings .getLocalizedString("common.error"), JOptionPane.ERROR_MESSAGE); return; } final Version version = (Version) versionsDropDown.getSelectedItem(); final JDialog dialog = new JDialog(App.settings.getParent(), ((isReinstall) ? App.settings.getLocalizedString("common.reinstalling") : App.settings.getLocalizedString("common.installing")) + " " + pack.getName() + " " + version.getVersion() + ((isServer) ? " " + App.settings.getLocalizedString("common.server") : ""), ModalityType.DOCUMENT_MODAL); dialog.setLocationRelativeTo(App.settings.getParent()); dialog.setSize(300, 100); dialog.setResizable(false); JPanel topPanel = new JPanel(); topPanel.setLayout(new BorderLayout()); final JLabel doing = new JLabel(App.settings.getLocalizedString( "instance.startingprocess", ((isReinstall) ? App.settings.getLocalizedString("common.reinstall") : App.settings.getLocalizedString("common.install")))); doing.setHorizontalAlignment(JLabel.CENTER); doing.setVerticalAlignment(JLabel.TOP); topPanel.add(doing); JPanel bottomPanel = new JPanel(); bottomPanel.setLayout(new BorderLayout()); progressBar = new JProgressBar(0, 100); bottomPanel.add(progressBar, BorderLayout.NORTH); progressBar.setIndeterminate(true); subProgressBar = new JProgressBar(0, 100); bottomPanel.add(subProgressBar, BorderLayout.SOUTH); subProgressBar.setValue(0); subProgressBar.setVisible(false); dialog.add(topPanel, BorderLayout.CENTER); dialog.add(bottomPanel, BorderLayout.SOUTH); final InstanceInstaller instanceInstaller = new InstanceInstaller((isServer ? "" : instanceNameField.getText()), pack, version.getVersion(), version .getMinecraftVersion(), (useLatestLWJGL == null ? false : useLatestLWJGL .isSelected()), isReinstall, isServer) { protected void done() { Boolean success = false; int type; String text; String title; if (isCancelled()) { type = JOptionPane.ERROR_MESSAGE; text = pack.getName() + " " + version.getVersion() + " " + App.settings.getLocalizedString("common.wasnt") + " " + ((isReinstall) ? App.settings .getLocalizedString("common.reinstalled") : App.settings.getLocalizedString("common.installed")) + "<br/><br/>" + App.settings.getLocalizedString("instance.actioncancelled"); title = pack.getName() + " " + version.getVersion() + " " + App.settings.getLocalizedString("common.not") + " " + ((isReinstall) ? App.settings .getLocalizedString("common.reinstalled") : App.settings.getLocalizedString("common.installed")); if (isReinstall) { App.settings.setInstanceUnplayable(instance); } } else { try { success = get(); } catch (InterruptedException e) { App.settings.getConsole().logStackTrace(e); } catch (ExecutionException e) { App.settings.getConsole().logStackTrace(e); } if (success) { type = JOptionPane.INFORMATION_MESSAGE; text = pack.getName() + " " + version.getVersion() + " " + App.settings.getLocalizedString("common.hasbeen") + " " + ((isReinstall) ? App.settings .getLocalizedString("common.reinstalled") : App.settings .getLocalizedString("common.installed")) + "<br/><br/>" + ((isServer) ? App.settings .getLocalizedString("instance.finditserver", "<br/><br/>" + this.getRootDirectory() .getAbsolutePath()) : App.settings .getLocalizedString("instance.findit")); title = pack.getName() + " " + version.getVersion() + " " + App.settings.getLocalizedString("common.installed"); System.out.println(isServer); if (isReinstall) { instance.setVersion(version.getVersion()); instance.setMinecraftVersion(this.getMinecraftVersion()); instance.setModsInstalled(this.getModsInstalled()); instance.setJarOrder(this.getJarOrder()); instance.setIsNewLaunchMethod(this.isNewLaunchMethod()); if (this.isNewLaunchMethod()) { instance.setLibrariesNeeded(this.getLibrariesNeeded()); instance.setMinecraftArguments(this.getMinecraftArguments()); instance.setMainClass(this.getMainClass()); } if (version.isDevVersion()) { instance.setDevVersion(); } else { instance.setNotDevVersion(); } if (!instance.isPlayable()) { instance.setPlayable(); } } else if (isServer) { } else { App.settings.getInstances().add( new Instance(instanceNameField.getText(), pack .getName(), pack, installForMe.isSelected(), version.getVersion(), this .getMinecraftVersion(), this .getMemory(), this.getPermGen(), this .getModsInstalled(), this.getJarOrder(), this.getLibrariesNeeded(), this.getMinecraftArguments(), this .getMainClass(), version.isDevVersion(), this .isNewLaunchMethod())); // Add It } App.settings.saveInstances(); App.settings.reloadInstancesPanel(); if (pack.isLoggingEnabled() && App.settings.enableLogs()) { App.settings.apiCall(App.settings.getAccount() .getMinecraftUsername(), "packinstalled", pack.getID() + "", version.getVersion()); } } else { if (isReinstall) { type = JOptionPane.ERROR_MESSAGE; text = pack.getName() + " " + version.getVersion() + " " + App.settings.getLocalizedString("common.wasnt") + " " + App.settings.getLocalizedString("common.reinstalled") + "<br/><br/>" + App.settings .getLocalizedString("instance.nolongerplayable") + "<br/><br/>" + App.settings .getLocalizedString("instance.checkerrorlogs") + "!"; title = pack.getName() + " " + version.getVersion() + " " + App.settings.getLocalizedString("common.not") + " " + App.settings.getLocalizedString("common.reinstalled"); App.settings.setInstanceUnplayable(instance); } else { // Install failed so delete the folder and clear Temp Dir Utils.delete(this.getRootDirectory()); type = JOptionPane.ERROR_MESSAGE; text = pack.getName() + " " + version.getVersion() + " " + App.settings.getLocalizedString("common.wasnt") + " " + App.settings.getLocalizedString("common.installed") + "<br/><br/>" + App.settings .getLocalizedString("instance.checkerrorlogs") + "!"; title = pack.getName() + " " + version.getVersion() + " " + App.settings.getLocalizedString("common.not") + " " + App.settings.getLocalizedString("common.installed"); } } } dialog.dispose(); Utils.cleanTempDirectory(); JOptionPane.showMessageDialog(App.settings.getParent(), "<html><center>" + text + "</center></html>", title, type); } }; instanceInstaller.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { if ("progress" == evt.getPropertyName()) { if (progressBar.isIndeterminate()) { progressBar.setIndeterminate(false); } int progress = (Integer) evt.getNewValue(); if (progress > 100) { progress = 100; } progressBar.setValue(progress); } else if ("subprogress" == evt.getPropertyName()) { if (!subProgressBar.isVisible()) { subProgressBar.setVisible(true); } if (subProgressBar.isIndeterminate()) { subProgressBar.setIndeterminate(false); } int progress = (Integer) evt.getNewValue(); if (progress > 100) { progress = 100; } if (progress == 0) { subProgressBar.setVisible(false); } subProgressBar.setValue(progress); } else if ("subprogressint" == evt.getPropertyName()) { if (!subProgressBar.isVisible()) { subProgressBar.setVisible(true); } if (!subProgressBar.isIndeterminate()) { subProgressBar.setIndeterminate(true); } } else if ("doing" == evt.getPropertyName()) { String doingText = (String) evt.getNewValue(); doing.setText(doingText); } } }); dialog.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { instanceInstaller.cancel(true); } }); if (isReinstall) { instanceInstaller.setInstance(instance); } instanceInstaller.execute(); dispose(); dialog.setVisible(true); } }); cancel = new JButton(App.settings.getLocalizedString("common.cancel")); cancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); } }); bottom.add(install); bottom.add(cancel); add(top, BorderLayout.NORTH); add(middle, BorderLayout.CENTER); add(bottom, BorderLayout.SOUTH); setVisible(true); }
diff --git a/modules/com.noelios.restlet/src/com/noelios/restlet/application/RangeFilter.java b/modules/com.noelios.restlet/src/com/noelios/restlet/application/RangeFilter.java index 8a094e77a..6a7070e42 100644 --- a/modules/com.noelios.restlet/src/com/noelios/restlet/application/RangeFilter.java +++ b/modules/com.noelios.restlet/src/com/noelios/restlet/application/RangeFilter.java @@ -1,101 +1,101 @@ /** * Copyright 2005-2008 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 royaltee 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 com.noelios.restlet.application; import org.restlet.Context; import org.restlet.Filter; import org.restlet.data.Method; import org.restlet.data.Range; import org.restlet.data.Request; import org.restlet.data.Response; import org.restlet.data.Status; import org.restlet.service.RangeService; /** * Filter that is in charge to check the responses to requests for partial * content. * */ public class RangeFilter extends Filter { /** * Constructor. * * @param context * The parent context. */ public RangeFilter(Context context) { super(context); } @Override protected void afterHandle(Request request, Response response) { if (getRangeService().isEnabled()) { response.getServerInfo().setAcceptRanges(true); if (response.isEntityAvailable()) { if (request.getRanges().size() == 1) { // At this time, list of ranges are not supported. Range requestedRange = request.getRanges().get(0); if (!requestedRange.equals(response.getEntity().getRange())) { getLogger() .info( - "The range of the response entity is not equals to the requested one."); + "The range of the response entity is not equal to the requested one."); response.setEntity(new RangeRepresentation(response .getEntity(), requestedRange)); } if (Method.GET.equals(request.getMethod()) && response.getStatus().isSuccess() && !Status.SUCCESS_PARTIAL_CONTENT.equals(response .getStatus())) { response.setStatus(Status.SUCCESS_PARTIAL_CONTENT); getLogger() .info( "The status of a response to a partial GET must be \"206 Partial content\"."); } } else if (request.getRanges().size() > 1) { // Return a server error as this isn't supported yet response .setStatus(Status.CLIENT_ERROR_REQUESTED_RANGE_NOT_SATISFIABLE); response.setEntity(null); } } } } /** * Returns the Range service of the parent application. * * @return The Range service of the parent application. */ public RangeService getRangeService() { return getApplication().getRangeService(); } }
true
true
protected void afterHandle(Request request, Response response) { if (getRangeService().isEnabled()) { response.getServerInfo().setAcceptRanges(true); if (response.isEntityAvailable()) { if (request.getRanges().size() == 1) { // At this time, list of ranges are not supported. Range requestedRange = request.getRanges().get(0); if (!requestedRange.equals(response.getEntity().getRange())) { getLogger() .info( "The range of the response entity is not equals to the requested one."); response.setEntity(new RangeRepresentation(response .getEntity(), requestedRange)); } if (Method.GET.equals(request.getMethod()) && response.getStatus().isSuccess() && !Status.SUCCESS_PARTIAL_CONTENT.equals(response .getStatus())) { response.setStatus(Status.SUCCESS_PARTIAL_CONTENT); getLogger() .info( "The status of a response to a partial GET must be \"206 Partial content\"."); } } else if (request.getRanges().size() > 1) { // Return a server error as this isn't supported yet response .setStatus(Status.CLIENT_ERROR_REQUESTED_RANGE_NOT_SATISFIABLE); response.setEntity(null); } } } }
protected void afterHandle(Request request, Response response) { if (getRangeService().isEnabled()) { response.getServerInfo().setAcceptRanges(true); if (response.isEntityAvailable()) { if (request.getRanges().size() == 1) { // At this time, list of ranges are not supported. Range requestedRange = request.getRanges().get(0); if (!requestedRange.equals(response.getEntity().getRange())) { getLogger() .info( "The range of the response entity is not equal to the requested one."); response.setEntity(new RangeRepresentation(response .getEntity(), requestedRange)); } if (Method.GET.equals(request.getMethod()) && response.getStatus().isSuccess() && !Status.SUCCESS_PARTIAL_CONTENT.equals(response .getStatus())) { response.setStatus(Status.SUCCESS_PARTIAL_CONTENT); getLogger() .info( "The status of a response to a partial GET must be \"206 Partial content\"."); } } else if (request.getRanges().size() > 1) { // Return a server error as this isn't supported yet response .setStatus(Status.CLIENT_ERROR_REQUESTED_RANGE_NOT_SATISFIABLE); response.setEntity(null); } } } }
diff --git a/gdx/src/com/badlogic/gdx/files/FileHandle.java b/gdx/src/com/badlogic/gdx/files/FileHandle.java index ab42c9023..71c9652c6 100644 --- a/gdx/src/com/badlogic/gdx/files/FileHandle.java +++ b/gdx/src/com/badlogic/gdx/files/FileHandle.java @@ -1,644 +1,644 @@ /******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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.badlogic.gdx.files; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.io.Writer; import com.badlogic.gdx.Files; import com.badlogic.gdx.Files.FileType; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.utils.GdxRuntimeException; /** Represents a file or directory on the filesystem, classpath, Android SD card, or Android assets directory. FileHandles are * created via a {@link Files} instance. * @author mzechner * @author Nathan Sweet */ public class FileHandle { protected File file; protected FileType type; protected FileHandle () { } /** Creates a new absolute FileHandle for the file name. Use this for tools on the desktop that don't need any of the backends. * Do not use this constructor in case you write something cross-platform. Use the {@link Files} interface instead. * @param fileName the filename. */ public FileHandle (String fileName) { this.file = new File(fileName); this.type = FileType.Absolute; } /** Creates a new absolute FileHandle for the {@link File}. Use this for tools on the desktop that don't need any of the * backends. Do not use this constructor in case you write something cross-platform. Use the {@link Files} interface instead. * @param file the file. */ public FileHandle (File file) { this.file = file; this.type = FileType.Absolute; } protected FileHandle (String fileName, FileType type) { this.type = type; file = new File(fileName); } protected FileHandle (File file, FileType type) { this.file = file; this.type = type; } /** @return the path of the file as specified on construction, e.g. Gdx.files.internal("dir/file.png") -> dir/file.png. backward * slashes will be replaced by forward slashes. */ public String path () { return file.getPath().replace('\\', '/'); } /** @return the name of the file, without any parent paths. */ public String name () { return file.getName(); } public String extension () { String name = file.getName(); int dotIndex = name.lastIndexOf('.'); if (dotIndex == -1) return ""; return name.substring(dotIndex + 1); } /** @return the name of the file, without parent paths or the extension. */ public String nameWithoutExtension () { String name = file.getName(); int dotIndex = name.lastIndexOf('.'); if (dotIndex == -1) return name; return name.substring(0, dotIndex); } /** @return the path and filename without the extension, e.g. dir/dir2/file.png -> dir/dir2/file. backward slashes will be * returned as forward slashes. */ public String pathWithoutExtension () { String path = file.getPath().replace('\\', '/'); int dotIndex = path.lastIndexOf('.'); if (dotIndex == -1) return path; return path.substring(0, dotIndex); } public FileType type () { return type; } /** Returns a java.io.File that represents this file handle. Note the returned file will only be usable for * {@link FileType#Absolute} and {@link FileType#External} file handles. */ public File file () { if (type == FileType.External) return new File(Gdx.files.getExternalStoragePath(), file.getPath()); return file; } /** Returns a stream for reading this file as bytes. * @throw GdxRuntimeException if the file handle represents a directory, doesn't exist, or could not be read. */ public InputStream read () { if (type == FileType.Classpath || (type == FileType.Internal && !file.exists()) || (type == FileType.Local && !file.exists())) { InputStream input = FileHandle.class.getResourceAsStream("/" + file.getPath().replace('\\', '/')); if (input == null) throw new GdxRuntimeException("File not found: " + file + " (" + type + ")"); return input; } try { return new FileInputStream(file()); } catch (Exception ex) { if (file().isDirectory()) throw new GdxRuntimeException("Cannot open a stream to a directory: " + file + " (" + type + ")", ex); throw new GdxRuntimeException("Error reading file: " + file + " (" + type + ")", ex); } } /** Returns a buffered stream for reading this file as bytes. * @throw GdxRuntimeException if the file handle represents a directory, doesn't exist, or could not be read. */ public BufferedInputStream read (int bufferSize) { return new BufferedInputStream(read(), bufferSize); } /** Returns a reader for reading this file as characters. * @throw GdxRuntimeException if the file handle represents a directory, doesn't exist, or could not be read. */ public Reader reader () { return new InputStreamReader(read()); } /** Returns a reader for reading this file as characters. * @throw GdxRuntimeException if the file handle represents a directory, doesn't exist, or could not be read. */ public Reader reader (String charset) { try { return new InputStreamReader(read(), charset); } catch (UnsupportedEncodingException ex) { throw new GdxRuntimeException("Error reading file: " + this, ex); } } /** Returns a buffered reader for reading this file as characters. * @throw GdxRuntimeException if the file handle represents a directory, doesn't exist, or could not be read. */ public BufferedReader reader (int bufferSize) { return new BufferedReader(new InputStreamReader(read()), bufferSize); } /** Returns a buffered reader for reading this file as characters. * @throw GdxRuntimeException if the file handle represents a directory, doesn't exist, or could not be read. */ public BufferedReader reader (int bufferSize, String charset) { try { return new BufferedReader(new InputStreamReader(read(), charset), bufferSize); } catch (UnsupportedEncodingException ex) { throw new GdxRuntimeException("Error reading file: " + this, ex); } } /** Reads the entire file into a string using the platform's default charset. * @throw GdxRuntimeException if the file handle represents a directory, doesn't exist, or could not be read. */ public String readString () { return readString(null); } /** Reads the entire file into a string using the specified charset. * @throw GdxRuntimeException if the file handle represents a directory, doesn't exist, or could not be read. */ public String readString (String charset) { int fileLength = (int)length(); if (fileLength == 0) fileLength = 512; StringBuilder output = new StringBuilder(fileLength); InputStreamReader reader = null; try { if (charset == null) reader = new InputStreamReader(read()); else reader = new InputStreamReader(read(), charset); char[] buffer = new char[256]; while (true) { int length = reader.read(buffer); if (length == -1) break; output.append(buffer, 0, length); } } catch (IOException ex) { throw new GdxRuntimeException("Error reading layout file: " + this, ex); } finally { try { if (reader != null) reader.close(); } catch (IOException ignored) { } } return output.toString(); } /** Reads the entire file into a byte array. * @throw GdxRuntimeException if the file handle represents a directory, doesn't exist, or could not be read. */ public byte[] readBytes () { int length = (int)length(); if (length == 0) length = 512; byte[] buffer = new byte[length]; int position = 0; InputStream input = read(); try { while (true) { int count = input.read(buffer, position, buffer.length - position); if (count == -1) break; position += count; - if (position == buffer.length) { + if (count == 0 && position == buffer.length) { // Grow buffer. byte[] newBuffer = new byte[buffer.length * 2]; System.arraycopy(buffer, 0, newBuffer, 0, position); buffer = newBuffer; } } } catch (IOException ex) { throw new GdxRuntimeException("Error reading file: " + this, ex); } finally { try { if (input != null) input.close(); } catch (IOException ignored) { } } if (position < buffer.length) { // Shrink buffer. byte[] newBuffer = new byte[position]; System.arraycopy(buffer, 0, newBuffer, 0, position); buffer = newBuffer; } return buffer; } /** Reads the entire file into the byte array. The byte array must be big enough to hold the file's data. * @param bytes the array to load the file into * @param offset the offset to start writing bytes * @param size the number of bytes to read, see {@link #length()} * @return the number of read bytes */ public int readBytes (byte[] bytes, int offset, int size) { InputStream input = read(); int position = 0; try { while (true) { int count = input.read(bytes, offset + position, size - position); if (count <= 0) break; position += count; } } catch (IOException ex) { throw new GdxRuntimeException("Error reading file: " + this, ex); } finally { try { if (input != null) input.close(); } catch (IOException ignored) { } } return position - offset; } /** Returns a stream for writing to this file. Parent directories will be created if necessary. * @param append If false, this file will be overwritten if it exists, otherwise it will be appended. * @throw GdxRuntimeException if this file handle represents a directory, if it is a {@link FileType#Classpath} or * {@link FileType#Internal} file, or if it could not be written. */ public OutputStream write (boolean append) { if (type == FileType.Classpath) throw new GdxRuntimeException("Cannot write to a classpath file: " + file); if (type == FileType.Internal) throw new GdxRuntimeException("Cannot write to an internal file: " + file); parent().mkdirs(); try { return new FileOutputStream(file(), append); } catch (Exception ex) { if (file().isDirectory()) throw new GdxRuntimeException("Cannot open a stream to a directory: " + file + " (" + type + ")", ex); throw new GdxRuntimeException("Error writing file: " + file + " (" + type + ")", ex); } } /** Reads the remaining bytes from the specified stream and writes them to this file. The stream is closed. Parent directories * will be created if necessary. * @param append If false, this file will be overwritten if it exists, otherwise it will be appended. * @throw GdxRuntimeException if this file handle represents a directory, if it is a {@link FileType#Classpath} or * {@link FileType#Internal} file, or if it could not be written. */ public void write (InputStream input, boolean append) { OutputStream output = null; try { output = write(append); byte[] buffer = new byte[4096]; while (true) { int length = input.read(buffer); if (length == -1) break; output.write(buffer, 0, length); } } catch (Exception ex) { throw new GdxRuntimeException("Error stream writing to file: " + file + " (" + type + ")", ex); } finally { try { if (input != null) input.close(); } catch (Exception ignored) { } try { if (output != null) output.close(); } catch (Exception ignored) { } } } /** Returns a writer for writing to this file using the default charset. Parent directories will be created if necessary. * @param append If false, this file will be overwritten if it exists, otherwise it will be appended. * @throw GdxRuntimeException if this file handle represents a directory, if it is a {@link FileType#Classpath} or * {@link FileType#Internal} file, or if it could not be written. */ public Writer writer (boolean append) { return writer(append, null); } /** Returns a writer for writing to this file. Parent directories will be created if necessary. * @param append If false, this file will be overwritten if it exists, otherwise it will be appended. * @param charset May be null to use the default charset. * @throw GdxRuntimeException if this file handle represents a directory, if it is a {@link FileType#Classpath} or * {@link FileType#Internal} file, or if it could not be written. */ public Writer writer (boolean append, String charset) { if (type == FileType.Classpath) throw new GdxRuntimeException("Cannot write to a classpath file: " + file); if (type == FileType.Internal) throw new GdxRuntimeException("Cannot write to an internal file: " + file); parent().mkdirs(); try { FileOutputStream output = new FileOutputStream(file(), append); if (charset == null) return new OutputStreamWriter(output); else return new OutputStreamWriter(output, charset); } catch (IOException ex) { if (file().isDirectory()) throw new GdxRuntimeException("Cannot open a stream to a directory: " + file + " (" + type + ")", ex); throw new GdxRuntimeException("Error writing file: " + file + " (" + type + ")", ex); } } /** Writes the specified string to the file using the default charset. Parent directories will be created if necessary. * @param append If false, this file will be overwritten if it exists, otherwise it will be appended. * @throw GdxRuntimeException if this file handle represents a directory, if it is a {@link FileType#Classpath} or * {@link FileType#Internal} file, or if it could not be written. */ public void writeString (String string, boolean append) { writeString(string, append, null); } /** Writes the specified string to the file as UTF-8. Parent directories will be created if necessary. * @param append If false, this file will be overwritten if it exists, otherwise it will be appended. * @param charset May be null to use the default charset. * @throw GdxRuntimeException if this file handle represents a directory, if it is a {@link FileType#Classpath} or * {@link FileType#Internal} file, or if it could not be written. */ public void writeString (String string, boolean append, String charset) { Writer writer = null; try { writer = writer(append, charset); writer.write(string); } catch (Exception ex) { throw new GdxRuntimeException("Error writing file: " + file + " (" + type + ")", ex); } finally { try { if (writer != null) writer.close(); } catch (Exception ignored) { } } } /** Writes the specified bytes to the file. Parent directories will be created if necessary. * @param append If false, this file will be overwritten if it exists, otherwise it will be appended. * @throw GdxRuntimeException if this file handle represents a directory, if it is a {@link FileType#Classpath} or * {@link FileType#Internal} file, or if it could not be written. */ public void writeBytes (byte[] bytes, boolean append) { OutputStream output = write(append); try { output.write(bytes); } catch (IOException ex) { throw new GdxRuntimeException("Error writing file: " + file + " (" + type + ")", ex); } finally { try { output.close(); } catch (IOException ignored) { } } } /** Writes the specified bytes to the file. Parent directories will be created if necessary. * @param append If false, this file will be overwritten if it exists, otherwise it will be appended. * @throw GdxRuntimeException if this file handle represents a directory, if it is a {@link FileType#Classpath} or * {@link FileType#Internal} file, or if it could not be written. */ public void writeBytes (byte[] bytes, int offset, int length, boolean append) { OutputStream output = write(append); try { output.write(bytes, offset, length); } catch (IOException ex) { throw new GdxRuntimeException("Error writing file: " + file + " (" + type + ")", ex); } finally { try { output.close(); } catch (IOException ignored) { } } } /** Returns the paths to the children of this directory. Returns an empty list if this file handle represents a file and not a * directory. On the desktop, an {@link FileType#Internal} handle to a directory on the classpath will return a zero length * array. * @throw GdxRuntimeException if this file is an {@link FileType#Classpath} file. */ public FileHandle[] list () { if (type == FileType.Classpath) throw new GdxRuntimeException("Cannot list a classpath directory: " + file); String[] relativePaths = file().list(); if (relativePaths == null) return new FileHandle[0]; FileHandle[] handles = new FileHandle[relativePaths.length]; for (int i = 0, n = relativePaths.length; i < n; i++) handles[i] = child(relativePaths[i]); return handles; } /** Returns the paths to the children of this directory with the specified suffix. Returns an empty list if this file handle * represents a file and not a directory. On the desktop, an {@link FileType#Internal} handle to a directory on the classpath * will return a zero length array. * @throw GdxRuntimeException if this file is an {@link FileType#Classpath} file. */ public FileHandle[] list (String suffix) { if (type == FileType.Classpath) throw new GdxRuntimeException("Cannot list a classpath directory: " + file); String[] relativePaths = file().list(); if (relativePaths == null) return new FileHandle[0]; FileHandle[] handles = new FileHandle[relativePaths.length]; int count = 0; for (int i = 0, n = relativePaths.length; i < n; i++) { String path = relativePaths[i]; if (!path.endsWith(suffix)) continue; handles[count] = child(path); count++; } if (count < relativePaths.length) { FileHandle[] newHandles = new FileHandle[count]; System.arraycopy(handles, 0, newHandles, 0, count); handles = newHandles; } return handles; } /** Returns true if this file is a directory. Always returns false for classpath files. On Android, an {@link FileType#Internal} * handle to an empty directory will return false. On the desktop, an {@link FileType#Internal} handle to a directory on the * classpath will return false. */ public boolean isDirectory () { if (type == FileType.Classpath) return false; return file().isDirectory(); } /** Returns a handle to the child with the specified name. * @throw GdxRuntimeException if this file handle is a {@link FileType#Classpath} or {@link FileType#Internal} and the child * doesn't exist. */ public FileHandle child (String name) { if (file.getPath().length() == 0) return new FileHandle(new File(name), type); return new FileHandle(new File(file, name), type); } /** Returns a handle to the sibling with the specified name. * @throw GdxRuntimeException if this file handle is a {@link FileType#Classpath} or {@link FileType#Internal} and the sibling * doesn't exist, or this file is the root. */ public FileHandle sibling (String name) { if (file.getPath().length() == 0) throw new GdxRuntimeException("Cannot get the sibling of the root."); return new FileHandle(new File(file.getParent(), name), type); } public FileHandle parent () { File parent = file.getParentFile(); if (parent == null) { if (type == FileType.Absolute) parent = new File("/"); else parent = new File(""); } return new FileHandle(parent, type); } /** @throw GdxRuntimeException if this file handle is a {@link FileType#Classpath} or {@link FileType#Internal} file. */ public void mkdirs () { if (type == FileType.Classpath) throw new GdxRuntimeException("Cannot mkdirs with a classpath file: " + file); if (type == FileType.Internal) throw new GdxRuntimeException("Cannot mkdirs with an internal file: " + file); file().mkdirs(); } /** Returns true if the file exists. On Android, a {@link FileType#Classpath} or {@link FileType#Internal} handle to a directory * will always return false. */ public boolean exists () { switch (type) { case Internal: if (file.exists()) return true; // Fall through. case Classpath: return FileHandle.class.getResource("/" + file.getPath().replace('\\', '/')) != null; } return file().exists(); } /** Deletes this file or empty directory and returns success. Will not delete a directory that has children. * @throw GdxRuntimeException if this file handle is a {@link FileType#Classpath} or {@link FileType#Internal} file. */ public boolean delete () { if (type == FileType.Classpath) throw new GdxRuntimeException("Cannot delete a classpath file: " + file); if (type == FileType.Internal) throw new GdxRuntimeException("Cannot delete an internal file: " + file); return file().delete(); } /** Deletes this file or directory and all children, recursively. * @throw GdxRuntimeException if this file handle is a {@link FileType#Classpath} or {@link FileType#Internal} file. */ public boolean deleteDirectory () { if (type == FileType.Classpath) throw new GdxRuntimeException("Cannot delete a classpath file: " + file); if (type == FileType.Internal) throw new GdxRuntimeException("Cannot delete an internal file: " + file); return deleteDirectory(file()); } /** Copies this file or directory to the specified file or directory. If this handle is a file, then 1) if the destination is a * file, it is overwritten, or 2) if the destination is a directory, this file is copied into it, or 3) if the destination * doesn't exist, {@link #mkdirs()} is called on the destination's parent and this file is copied into it with a new name. If * this handle is a directory, then 1) if the destination is a file, GdxRuntimeException is thrown, or 2) if the destination is * a directory, this directory is copied into it recursively, overwriting existing files, or 3) if the destination doesn't * exist, {@link #mkdirs()} is called on the destination and this directory is copied into it recursively. * @throw GdxRuntimeException if the destination file handle is a {@link FileType#Classpath} or {@link FileType#Internal} file, * or copying failed. */ public void copyTo (FileHandle dest) { boolean sourceDir = isDirectory(); if (!sourceDir) { if (dest.isDirectory()) dest = dest.child(name()); copyFile(this, dest); return; } if (dest.exists()) { if (!dest.isDirectory()) throw new GdxRuntimeException("Destination exists but is not a directory: " + dest); } else { dest.mkdirs(); if (!dest.isDirectory()) throw new GdxRuntimeException("Destination directory cannot be created: " + dest); } if (!sourceDir) dest = dest.child(name()); copyDirectory(this, dest); } /** Moves this file to the specified file, overwriting the file if it already exists. * @throw GdxRuntimeException if the source or destination file handle is a {@link FileType#Classpath} or * {@link FileType#Internal} file. */ public void moveTo (FileHandle dest) { if (type == FileType.Classpath) throw new GdxRuntimeException("Cannot move a classpath file: " + file); if (type == FileType.Internal) throw new GdxRuntimeException("Cannot move an internal file: " + file); copyTo(dest); delete(); } /** Returns the length in bytes of this file, or 0 if this file is a directory, does not exist, or the size cannot otherwise be * determined. */ public long length () { if (type == FileType.Classpath || (type == FileType.Internal && !file.exists())) { InputStream input = read(); try { return input.available(); } catch (Exception ignored) { } finally { try { input.close(); } catch (IOException ignored) { } } return 0; } return file().length(); } /** Returns the last modified time in milliseconds for this file. Zero is returned if the file doesn't exist. Zero is returned * for {@link FileType#Classpath} files. On Android, zero is returned for {@link FileType#Internal} files. On the desktop, zero * is returned for {@link FileType#Internal} files on the classpath. */ public long lastModified () { return file().lastModified(); } public String toString () { return file.getPath().replace('\\', '/'); } static public FileHandle tempFile (String prefix) { try { return new FileHandle(File.createTempFile(prefix, null)); } catch (IOException ex) { throw new GdxRuntimeException("Unable to create temp file.", ex); } } static public FileHandle tempDirectory (String prefix) { try { File file = File.createTempFile(prefix, null); if (!file.delete()) throw new IOException("Unable to delete temp file: " + file); if (!file.mkdir()) throw new IOException("Unable to create temp directory: " + file); return new FileHandle(file); } catch (IOException ex) { throw new GdxRuntimeException("Unable to create temp file.", ex); } } static private boolean deleteDirectory (File file) { if (file.exists()) { File[] files = file.listFiles(); if (files != null) { for (int i = 0, n = files.length; i < n; i++) { if (files[i].isDirectory()) deleteDirectory(files[i]); else files[i].delete(); } } } return file.delete(); } static private void copyFile (FileHandle source, FileHandle dest) { try { dest.write(source.read(), false); } catch (Exception ex) { throw new GdxRuntimeException("Error copying source file: " + source.file + " (" + source.type + ")\n" // + "To destination: " + dest.file + " (" + dest.type + ")", ex); } } static private void copyDirectory (FileHandle sourceDir, FileHandle destDir) { destDir.mkdirs(); FileHandle[] files = sourceDir.list(); for (int i = 0, n = files.length; i < n; i++) { FileHandle srcFile = files[i]; FileHandle destFile = destDir.child(srcFile.name()); if (srcFile.isDirectory()) copyDirectory(srcFile, destFile); else copyFile(srcFile, destFile); } } }
true
true
public byte[] readBytes () { int length = (int)length(); if (length == 0) length = 512; byte[] buffer = new byte[length]; int position = 0; InputStream input = read(); try { while (true) { int count = input.read(buffer, position, buffer.length - position); if (count == -1) break; position += count; if (position == buffer.length) { // Grow buffer. byte[] newBuffer = new byte[buffer.length * 2]; System.arraycopy(buffer, 0, newBuffer, 0, position); buffer = newBuffer; } } } catch (IOException ex) { throw new GdxRuntimeException("Error reading file: " + this, ex); } finally { try { if (input != null) input.close(); } catch (IOException ignored) { } } if (position < buffer.length) { // Shrink buffer. byte[] newBuffer = new byte[position]; System.arraycopy(buffer, 0, newBuffer, 0, position); buffer = newBuffer; } return buffer; }
public byte[] readBytes () { int length = (int)length(); if (length == 0) length = 512; byte[] buffer = new byte[length]; int position = 0; InputStream input = read(); try { while (true) { int count = input.read(buffer, position, buffer.length - position); if (count == -1) break; position += count; if (count == 0 && position == buffer.length) { // Grow buffer. byte[] newBuffer = new byte[buffer.length * 2]; System.arraycopy(buffer, 0, newBuffer, 0, position); buffer = newBuffer; } } } catch (IOException ex) { throw new GdxRuntimeException("Error reading file: " + this, ex); } finally { try { if (input != null) input.close(); } catch (IOException ignored) { } } if (position < buffer.length) { // Shrink buffer. byte[] newBuffer = new byte[position]; System.arraycopy(buffer, 0, newBuffer, 0, position); buffer = newBuffer; } return buffer; }
diff --git a/android/src/com/google/android/apps/iosched/ui/widget/Workspace.java b/android/src/com/google/android/apps/iosched/ui/widget/Workspace.java index c801172..591480a 100644 --- a/android/src/com/google/android/apps/iosched/ui/widget/Workspace.java +++ b/android/src/com/google/android/apps/iosched/ui/widget/Workspace.java @@ -1,1065 +1,1067 @@ /* * Copyright 2011 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.android.apps.iosched.ui.widget; import com.google.android.apps.iosched.util.MotionEventUtils; import com.google.android.apps.iosched.util.ReflectionUtils; import android.content.Context; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.os.Parcel; import android.os.Parcelable; 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.widget.Scroller; import java.util.ArrayList; /** * A {@link android.view.ViewGroup} that shows one child at a time, allowing the user to swipe * horizontally to page between other child views. Based on <code>Workspace.java</code> in the * <code>Launcher.git</code> AOSP project. */ public class Workspace extends ViewGroup { private static final String TAG = "Workspace"; 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; /** * The user needs to drag at least this much for it to be considered a fling gesture. This * reduces the chance of a random twitch sending the user to the next screen. */ // TODO: refactor private static final int MIN_LENGTH_FOR_FLING = 100; private int mDefaultScreen; private boolean mFirstLayout = true; private boolean mHasLaidOut = false; private int mCurrentScreen; private int mNextScreen = INVALID_SCREEN; private Scroller mScroller; private VelocityTracker mVelocityTracker; /** * X position of the active pointer when it was first pressed down. */ private float mDownMotionX; /** * Y position of the active pointer when it was first pressed down. */ private float mDownMotionY; /** * This view's X scroll offset when the active pointer was first pressed down. */ private int mDownScrollX; private final static int TOUCH_STATE_REST = 0; private final static int TOUCH_STATE_SCROLLING = 1; private int mTouchState = TOUCH_STATE_REST; private OnLongClickListener mLongClickListener; private boolean mAllowLongPress = true; private int mTouchSlop; private int mPagingTouchSlop; private int mMaximumVelocity; private static final int INVALID_POINTER = -1; private int mActivePointerId = INVALID_POINTER; private Drawable mSeparatorDrawable; private OnScreenChangeListener mOnScreenChangeListener; private OnScrollListener mOnScrollListener; private boolean mLocked; private int mDeferredScreenChange = -1; private boolean mDeferredScreenChangeFast = false; private boolean mDeferredNotify = false; private boolean mIgnoreChildFocusRequests; private boolean mIsVerbose = false; public interface OnScreenChangeListener { void onScreenChanged(View newScreen, int newScreenIndex); void onScreenChanging(View newScreen, int newScreenIndex); } public interface OnScrollListener { void onScroll(float screenFraction); } /** * Used to inflate the com.google.android.ext.workspace.Workspace from XML. * * @param context The application's context. * @param attrs The attributes set containing the com.google.android.ext.workspace.Workspace's * customization values. */ public Workspace(Context context, AttributeSet attrs) { super(context, attrs); mDefaultScreen = 0; mLocked = false; setHapticFeedbackEnabled(false); initWorkspace(); mIsVerbose = Log.isLoggable(TAG, Log.VERBOSE); } /** * Initializes various states for this workspace. */ private void initWorkspace() { mScroller = new Scroller(getContext()); mCurrentScreen = mDefaultScreen; final ViewConfiguration configuration = ViewConfiguration.get(getContext()); mTouchSlop = configuration.getScaledTouchSlop(); mMaximumVelocity = configuration.getScaledMaximumFlingVelocity(); mPagingTouchSlop = ReflectionUtils.callWithDefault(configuration, "getScaledPagingTouchSlop", mTouchSlop * 2); } /** * Returns the index of the currently displayed screen. */ int getCurrentScreen() { return mCurrentScreen; } /** * Returns the number of screens currently contained in this Workspace. */ int getScreenCount() { int childCount = getChildCount(); if (mSeparatorDrawable != null) { return (childCount + 1) / 2; } return childCount; } View getScreenAt(int index) { if (mSeparatorDrawable == null) { return getChildAt(index); } return getChildAt(index * 2); } int getScrollWidth() { int w = getWidth(); if (mSeparatorDrawable != null) { w += mSeparatorDrawable.getIntrinsicWidth(); } return w; } void handleScreenChangeCompletion(int currentScreen) { mCurrentScreen = currentScreen; View screen = getScreenAt(mCurrentScreen); //screen.requestFocus(); try { ReflectionUtils.tryInvoke(screen, "dispatchDisplayHint", new Class[]{int.class}, View.VISIBLE); invalidate(); } catch (NullPointerException e) { Log.e(TAG, "Caught NullPointerException", e); } notifyScreenChangeListener(mCurrentScreen, true); } void notifyScreenChangeListener(int whichScreen, boolean changeComplete) { if (mOnScreenChangeListener != null) { if (changeComplete) mOnScreenChangeListener.onScreenChanged(getScreenAt(whichScreen), whichScreen); else mOnScreenChangeListener.onScreenChanging(getScreenAt(whichScreen), whichScreen); } if (mOnScrollListener != null) { mOnScrollListener.onScroll(getCurrentScreenFraction()); } } /** * Registers the specified listener on each screen contained in this workspace. * * @param listener The listener used to respond to long clicks. */ @Override public void setOnLongClickListener(OnLongClickListener listener) { mLongClickListener = listener; final int count = getScreenCount(); for (int i = 0; i < count; i++) { getScreenAt(i).setOnLongClickListener(listener); } } @Override public void computeScroll() { if (mScroller.computeScrollOffset()) { scrollTo(mScroller.getCurrX(), mScroller.getCurrY()); if (mOnScrollListener != null) { mOnScrollListener.onScroll(getCurrentScreenFraction()); } postInvalidate(); } else if (mNextScreen != INVALID_SCREEN) { // The scroller has finished. handleScreenChangeCompletion(Math.max(0, Math.min(mNextScreen, getScreenCount() - 1))); mNextScreen = INVALID_SCREEN; } } @Override protected void dispatchDraw(Canvas canvas) { boolean restore = false; int restoreCount = 0; // 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) { if (getScreenAt(mCurrentScreen) != null) { drawChild(canvas, getScreenAt(mCurrentScreen), getDrawingTime()); } } else { final long drawingTime = getDrawingTime(); // If we are flinging, draw only the current screen and the target screen if (mNextScreen >= 0 && mNextScreen < getScreenCount() && Math.abs(mCurrentScreen - mNextScreen) == 1) { drawChild(canvas, getScreenAt(mCurrentScreen), drawingTime); drawChild(canvas, getScreenAt(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); } } } if (restore) { canvas.restoreToCount(restoreCount); } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); // The children are given the same width and height as the workspace final int count = getChildCount(); for (int i = 0; i < count; i++) { if (mSeparatorDrawable != null && (i & 1) == 1) { // separator getChildAt(i).measure(mSeparatorDrawable.getIntrinsicWidth(), heightMeasureSpec); } else { getChildAt(i).measure(widthMeasureSpec, heightMeasureSpec); } } if (mFirstLayout) { setHorizontalScrollBarEnabled(false); int width = MeasureSpec.getSize(widthMeasureSpec); if (mSeparatorDrawable != null) { width += mSeparatorDrawable.getIntrinsicWidth(); } scrollTo(mCurrentScreen * width, 0); setHorizontalScrollBarEnabled(true); mFirstLayout = false; } } @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; } } mHasLaidOut = true; if (mDeferredScreenChange >= 0) { snapToScreen(mDeferredScreenChange, mDeferredScreenChangeFast, mDeferredNotify); mDeferredScreenChange = -1; mDeferredScreenChangeFast = false; } } @Override public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) { int screen = indexOfChild(child); if (mIgnoreChildFocusRequests && !mScroller.isFinished()) { Log.w(TAG, "Ignoring child focus request: request " + mCurrentScreen + " -> " + screen); return false; } if (screen != mCurrentScreen || !mScroller.isFinished()) { snapToScreen(screen); return true; } return false; } @Override protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) { int focusableScreen; if (mNextScreen != INVALID_SCREEN) { focusableScreen = mNextScreen; } else { focusableScreen = mCurrentScreen; } View v = getScreenAt(focusableScreen); if (v != null) { return v.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() < getScreenCount() - 1) { snapToScreen(getCurrentScreen() + 1); return true; } } return super.dispatchUnhandledMove(focused, direction); } @Override public void addFocusables(ArrayList<View> views, int direction, int focusableMode) { View focusableSourceScreen = null; if (mCurrentScreen >= 0 && mCurrentScreen < getScreenCount()) { focusableSourceScreen = getScreenAt(mCurrentScreen); } if (direction == View.FOCUS_LEFT) { if (mCurrentScreen > 0) { focusableSourceScreen = getScreenAt(mCurrentScreen - 1); } } else if (direction == View.FOCUS_RIGHT) { if (mCurrentScreen < getScreenCount() - 1) { focusableSourceScreen = getScreenAt(mCurrentScreen + 1); } } if (focusableSourceScreen != null) { focusableSourceScreen.addFocusables(views, direction, focusableMode); } } /** * If one of our descendant views decides that it could be focused now, only pass that along if * it's on the current screen. * * This happens when live folders requery, and if they're off screen, they end up calling * requestFocus, which pulls it on screen. */ @Override public void focusableViewAvailable(View focused) { View current = getScreenAt(mCurrentScreen); View v = focused; ViewParent parent; while (true) { if (v == current) { super.focusableViewAvailable(focused); return; } if (v == this) { return; } parent = v.getParent(); if (parent instanceof View) { v = (View) v.getParent(); } else { return; } } } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { /* * 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. */ // Begin tracking velocity even before we have intercepted touch events. if (mVelocityTracker == null) { mVelocityTracker = VelocityTracker.obtain(); } mVelocityTracker.addMovement(ev); /* * 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 (mIsVerbose) { Log.v(TAG, "onInterceptTouchEvent: " + (ev.getAction() & MotionEventUtils.ACTION_MASK)); } if (((action & MotionEventUtils.ACTION_MASK) == MotionEvent.ACTION_MOVE) && (mTouchState == TOUCH_STATE_SCROLLING)) { if (mIsVerbose) { Log.v(TAG, "Intercepting touch events"); } return true; } switch (action & MotionEventUtils.ACTION_MASK) { case MotionEvent.ACTION_MOVE: { if (mLocked) { // we're locked on the current screen, don't allow moving break; } /* * Locally do absolute value. mDownMotionX is set to the y value * of the down event. */ final int pointerIndex = MotionEventUtils.findPointerIndex(ev, mActivePointerId); final float x = MotionEventUtils.getX(ev, pointerIndex); final float y = MotionEventUtils.getY(ev, pointerIndex); final int xDiff = (int) Math.abs(x - mDownMotionX); final int yDiff = (int) Math.abs(y - mDownMotionY); boolean xPaged = xDiff > mPagingTouchSlop; boolean xMoved = xDiff > mTouchSlop; boolean yMoved = yDiff > mTouchSlop; if (xMoved || yMoved) { if (xPaged) { // Scroll if the user moved far enough along the X axis mTouchState = TOUCH_STATE_SCROLLING; } // 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 = getScreenAt(mCurrentScreen); if (currentScreen != null) { currentScreen.cancelLongPress(); } } } break; } case MotionEvent.ACTION_DOWN: { final float x = ev.getX(); final float y = ev.getY(); // Remember location of down touch mDownMotionX = x; mDownMotionY = y; mDownScrollX = getScrollX(); mActivePointerId = MotionEventUtils.getPointerId(ev, 0); 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: // Release the drag mTouchState = TOUCH_STATE_REST; mAllowLongPress = false; mActivePointerId = INVALID_POINTER; if (mVelocityTracker == null) { mVelocityTracker.recycle(); mVelocityTracker = null; } break; case MotionEventUtils.ACTION_POINTER_UP: onSecondaryPointerUp(ev); break; } /* * The only time we want to intercept motion events is if we are in the * drag mode. */ boolean intercept = mTouchState != TOUCH_STATE_REST; if (mIsVerbose) { Log.v(TAG, "Intercepting touch events: " + Boolean.toString(intercept)); } return intercept; } void onSecondaryPointerUp(MotionEvent ev) { final int pointerIndex = (ev.getAction() & MotionEventUtils.ACTION_POINTER_INDEX_MASK) >> MotionEventUtils.ACTION_POINTER_INDEX_SHIFT; final int pointerId = MotionEventUtils.getPointerId(ev, pointerIndex); if (pointerId == mActivePointerId) { // This was our active pointer going up. Choose a new // active pointer and adjust accordingly. // TODO: Make this decision more intelligent. final int newPointerIndex = pointerIndex == 0 ? 1 : 0; mDownMotionX = MotionEventUtils.getX(ev, newPointerIndex); mDownMotionX = MotionEventUtils.getY(ev, newPointerIndex); mDownScrollX = getScrollX(); mActivePointerId = MotionEventUtils.getPointerId(ev, newPointerIndex); if (mVelocityTracker != null) { mVelocityTracker.clear(); } } } @Override public void requestChildFocus(View child, View focused) { super.requestChildFocus(child, focused); int screen = indexOfChild(child); if (mSeparatorDrawable != null) { screen /= 2; } if (screen >= 0 && !isInTouchMode()) { snapToScreen(screen); } } @Override public boolean onTouchEvent(MotionEvent ev) { if (mIsVerbose) { Log.v(TAG, "onTouchEvent: " + (ev.getAction() & MotionEventUtils.ACTION_MASK)); } if (mVelocityTracker == null) { mVelocityTracker = VelocityTracker.obtain(); } mVelocityTracker.addMovement(ev); final int action = ev.getAction(); switch (action & MotionEventUtils.ACTION_MASK) { 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 mDownMotionX = ev.getX(); mDownMotionY = ev.getY(); mDownScrollX = getScrollX(); mActivePointerId = MotionEventUtils.getPointerId(ev, 0); break; case MotionEvent.ACTION_MOVE: if (mIsVerbose) { Log.v(TAG, "mTouchState=" + mTouchState); } if (mTouchState == TOUCH_STATE_SCROLLING) { // Scroll to follow the motion event final int pointerIndex = MotionEventUtils .findPointerIndex(ev, mActivePointerId); final float x = MotionEventUtils.getX(ev, pointerIndex); final View lastChild = getChildAt(getChildCount() - 1); final int maxScrollX = lastChild.getRight() - getWidth(); scrollTo(Math.max(0, Math.min(maxScrollX, (int)(mDownScrollX + mDownMotionX - x ))), 0); if (mOnScrollListener != null) { mOnScrollListener.onScroll(getCurrentScreenFraction()); } } else if (mTouchState == TOUCH_STATE_REST) { if (mLocked) { // we're locked on the current screen, don't allow moving break; } /* * Locally do absolute value. mLastMotionX is set to the y value * of the down event. */ final int pointerIndex = MotionEventUtils.findPointerIndex(ev, mActivePointerId); final float x = MotionEventUtils.getX(ev, pointerIndex); final float y = MotionEventUtils.getY(ev, pointerIndex); final int xDiff = (int) Math.abs(x - mDownMotionX); final int yDiff = (int) Math.abs(y - mDownMotionY); boolean xPaged = xDiff > mPagingTouchSlop; boolean xMoved = xDiff > mTouchSlop; boolean yMoved = yDiff > mTouchSlop; if (xMoved || yMoved) { if (xPaged) { // Scroll if the user moved far enough along the X axis mTouchState = TOUCH_STATE_SCROLLING; } // 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 = getScreenAt(mCurrentScreen); if (currentScreen != null) { currentScreen.cancelLongPress(); } } } } break; case MotionEvent.ACTION_UP: if (mTouchState == TOUCH_STATE_SCROLLING) { final int activePointerId = mActivePointerId; final int pointerIndex = MotionEventUtils.findPointerIndex(ev, activePointerId); final float x = MotionEventUtils.getX(ev, pointerIndex); final VelocityTracker velocityTracker = mVelocityTracker; velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity); //TODO(minsdk8): int velocityX = (int) MotionEventUtils.getXVelocity(velocityTracker, activePointerId); int velocityX = (int) velocityTracker.getXVelocity(); boolean isFling = Math.abs(mDownMotionX - x) > MIN_LENGTH_FOR_FLING; final float scrolledPos = getCurrentScreenFraction(); final int whichScreen = Math.round(scrolledPos); if (isFling && mIsVerbose) { Log.v(TAG, "isFling, whichScreen=" + whichScreen + " scrolledPos=" + scrolledPos + " mCurrentScreen=" + mCurrentScreen + " velocityX=" + velocityX); } if (isFling && velocityX > SNAP_VELOCITY && mCurrentScreen > 0) { // Fling hard enough to move left // Don't fling across more than one screen at a time. final int bound = scrolledPos <= whichScreen ? mCurrentScreen - 1 : mCurrentScreen; snapToScreen(Math.min(whichScreen, bound)); } else if (isFling && velocityX < -SNAP_VELOCITY && mCurrentScreen < getChildCount() - 1) { // Fling hard enough to move right // Don't fling across more than one screen at a time. final int bound = scrolledPos >= whichScreen ? mCurrentScreen + 1 : mCurrentScreen; snapToScreen(Math.max(whichScreen, bound)); } else { snapToDestination(); } + } else { + performClick(); } mTouchState = TOUCH_STATE_REST; mActivePointerId = INVALID_POINTER; // Intentially fall through to cancel case MotionEvent.ACTION_CANCEL: mTouchState = TOUCH_STATE_REST; mActivePointerId = INVALID_POINTER; if (mVelocityTracker != null) { mVelocityTracker.recycle(); mVelocityTracker = null; } break; case MotionEventUtils.ACTION_POINTER_UP: onSecondaryPointerUp(ev); break; } return true; } /** * Returns the current scroll position as a float value from 0 to the number of screens. * Fractional values indicate that the user is mid-scroll or mid-fling, and whole values * indicate that the Workspace is currently snapped to a screen. */ float getCurrentScreenFraction() { if (!mHasLaidOut) { return mCurrentScreen; } final int scrollX = getScrollX(); final int screenWidth = getWidth(); return (float) scrollX / screenWidth; } void snapToDestination() { final int screenWidth = getScrollWidth(); final int whichScreen = (getScrollX() + (screenWidth / 2)) / screenWidth; snapToScreen(whichScreen); } void snapToScreen(int whichScreen) { snapToScreen(whichScreen, false, true); } void snapToScreen(int whichScreen, boolean fast, boolean notify) { if (!mHasLaidOut) { // Can't handle scrolling until we are laid out. mDeferredScreenChange = whichScreen; mDeferredScreenChangeFast = fast; mDeferredNotify = notify; return; } if (mIsVerbose) { Log.v(TAG, "Snapping to screen: " + whichScreen); } whichScreen = Math.max(0, Math.min(whichScreen, getScreenCount() - 1)); final int screenDelta = Math.abs(whichScreen - mCurrentScreen); final boolean screenChanging = (mNextScreen != INVALID_SCREEN && mNextScreen != whichScreen) || (mCurrentScreen != whichScreen); mNextScreen = whichScreen; View focusedChild = getFocusedChild(); boolean setTabFocus = false; if (focusedChild != null && screenDelta != 0 && focusedChild == getScreenAt( mCurrentScreen)) { // clearing the focus of the child will cause focus to jump to the tabs, // which will in turn cause snapToScreen to be called again with a different // value. To prevent this, we temporarily disable the OnTabClickListener //if (mTabRow != null) { // mTabRow.setOnTabClickListener(null); //} //focusedChild.clearFocus(); //setTabRow(mTabRow); // restore the listener //setTabFocus = true; } final int newX = whichScreen * getScrollWidth(); final int sX = getScrollX(); final int delta = newX - sX; int duration = screenDelta * 300; awakenScrollBars(duration); if (duration == 0) { duration = Math.abs(delta); } if (fast) { duration = 0; } if (mNextScreen != mCurrentScreen) { // make the current listview hide its filter popup final View screenAt = getScreenAt(mCurrentScreen); if (screenAt != null) { ReflectionUtils.tryInvoke(screenAt, "dispatchDisplayHint", new Class[]{int.class}, View.INVISIBLE); } else { Log.e(TAG, "Screen at index was null. mCurrentScreen = " + mCurrentScreen); return; } // showing the filter popup for the next listview needs to be delayed // until we've fully moved to that listview, since otherwise the // popup will appear at the wrong place on the screen //removeCallbacks(mFilterWindowEnabler); //postDelayed(mFilterWindowEnabler, duration + 10); // NOTE: moved to computeScroll and handleScreenChangeCompletion() } if (!mScroller.isFinished()) { mScroller.abortAnimation(); } mScroller.startScroll(sX, 0, delta, 0, duration); if (screenChanging && notify) { notifyScreenChangeListener(mNextScreen, false); } invalidate(); } @Override protected Parcelable onSaveInstanceState() { final SavedState state = new SavedState(super.onSaveInstanceState()); state.currentScreen = mCurrentScreen; return state; } @Override protected void onRestoreInstanceState(Parcelable state) { SavedState savedState = (SavedState) state; super.onRestoreInstanceState(savedState.getSuperState()); if (savedState.currentScreen != -1) { snapToScreen(savedState.currentScreen, true, true); } } /** * @return True is long presses are still allowed for the current touch */ boolean allowLongPress() { return mAllowLongPress; } /** * Register a callback to be invoked when the screen is changed, either programmatically or via * user interaction. Will automatically trigger a callback. * * @param screenChangeListener The callback. */ public void setOnScreenChangeListener(OnScreenChangeListener screenChangeListener) { setOnScreenChangeListener(screenChangeListener, true); } /** * Register a callback to be invoked when the screen is changed, either programmatically or via * user interaction. * * @param screenChangeListener The callback. * @param notifyImmediately Whether to trigger a notification immediately */ public void setOnScreenChangeListener(OnScreenChangeListener screenChangeListener, boolean notifyImmediately) { mOnScreenChangeListener = screenChangeListener; if (mOnScreenChangeListener != null && notifyImmediately) { mOnScreenChangeListener.onScreenChanged(getScreenAt(mCurrentScreen), mCurrentScreen); } } /** * Register a callback to be invoked when this Workspace is mid-scroll or mid-fling, either * due to user interaction or programmatic changes in the current screen index. * * @param scrollListener The callback. * @param notifyImmediately Whether to trigger a notification immediately */ public void setOnScrollListener(OnScrollListener scrollListener, boolean notifyImmediately) { mOnScrollListener = scrollListener; if (mOnScrollListener != null && notifyImmediately) { mOnScrollListener.onScroll(getCurrentScreenFraction()); } } /** * Scrolls to the given screen. */ public void setCurrentScreen(int screenIndex) { snapToScreen(Math.max(0, Math.min(getScreenCount() - 1, screenIndex))); } /** * Scrolls to the given screen fast (no matter how large the scroll distance is) * * @param screenIndex */ public void setCurrentScreenNow(int screenIndex) { setCurrentScreenNow(screenIndex, true); } public void setCurrentScreenNow(int screenIndex, boolean notify) { snapToScreen(Math.max(0, Math.min(getScreenCount() - 1, screenIndex)), true, notify); } /** * Scrolls to the screen adjacent to the current screen on the left, if it exists. This method * is a no-op if the Workspace is currently locked. */ public void scrollLeft() { if (mLocked) { return; } if (mScroller.isFinished()) { if (mCurrentScreen > 0) { snapToScreen(mCurrentScreen - 1); } } else { if (mNextScreen > 0) { snapToScreen(mNextScreen - 1); } } } /** * Scrolls to the screen adjacent to the current screen on the right, if it exists. This method * is a no-op if the Workspace is currently locked. */ public void scrollRight() { if (mLocked) { return; } if (mScroller.isFinished()) { if (mCurrentScreen < getChildCount() - 1) { snapToScreen(mCurrentScreen + 1); } } else { if (mNextScreen < getChildCount() - 1) { snapToScreen(mNextScreen + 1); } } } /** * If set, invocations of requestChildRectangleOnScreen() will be ignored. */ public void setIgnoreChildFocusRequests(boolean mIgnoreChildFocusRequests) { this.mIgnoreChildFocusRequests = mIgnoreChildFocusRequests; } public void markViewSelected(View v) { mCurrentScreen = indexOfChild(v); } /** * Locks the current screen, preventing users from changing screens by swiping. */ public void lockCurrentScreen() { mLocked = true; } /** * Unlocks the current screen, if it was previously locked. See also {@link * Workspace#lockCurrentScreen()}. */ public void unlockCurrentScreen() { mLocked = false; } /** * Sets the resource ID of the separator drawable to use between adjacent screens. */ public void setSeparator(int resId) { if (mSeparatorDrawable != null && resId == 0) { // remove existing separators mSeparatorDrawable = null; int num = getChildCount(); for (int i = num - 2; i > 0; i -= 2) { removeViewAt(i); } requestLayout(); } else if (resId != 0) { // add or update separators if (mSeparatorDrawable == null) { // add int numsep = getChildCount(); int insertIndex = 1; mSeparatorDrawable = getResources().getDrawable(resId); for (int i = 1; i < numsep; i++) { View v = new View(getContext()); v.setBackgroundDrawable(mSeparatorDrawable); LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT); v.setLayoutParams(lp); addView(v, insertIndex); insertIndex += 2; } requestLayout(); } else { // update mSeparatorDrawable = getResources().getDrawable(resId); int num = getChildCount(); for (int i = num - 2; i > 0; i -= 2) { getChildAt(i).setBackgroundDrawable(mSeparatorDrawable); } requestLayout(); } } } private 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]; } }; } public void addViewToFront(View v) { mCurrentScreen++; addView(v, 0); } public void removeViewFromFront() { mCurrentScreen--; removeViewAt(0); } public void addViewToBack(View v) { addView(v); } public void removeViewFromBack() { removeViewAt(getChildCount() - 1); } }
true
true
public boolean onTouchEvent(MotionEvent ev) { if (mIsVerbose) { Log.v(TAG, "onTouchEvent: " + (ev.getAction() & MotionEventUtils.ACTION_MASK)); } if (mVelocityTracker == null) { mVelocityTracker = VelocityTracker.obtain(); } mVelocityTracker.addMovement(ev); final int action = ev.getAction(); switch (action & MotionEventUtils.ACTION_MASK) { 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 mDownMotionX = ev.getX(); mDownMotionY = ev.getY(); mDownScrollX = getScrollX(); mActivePointerId = MotionEventUtils.getPointerId(ev, 0); break; case MotionEvent.ACTION_MOVE: if (mIsVerbose) { Log.v(TAG, "mTouchState=" + mTouchState); } if (mTouchState == TOUCH_STATE_SCROLLING) { // Scroll to follow the motion event final int pointerIndex = MotionEventUtils .findPointerIndex(ev, mActivePointerId); final float x = MotionEventUtils.getX(ev, pointerIndex); final View lastChild = getChildAt(getChildCount() - 1); final int maxScrollX = lastChild.getRight() - getWidth(); scrollTo(Math.max(0, Math.min(maxScrollX, (int)(mDownScrollX + mDownMotionX - x ))), 0); if (mOnScrollListener != null) { mOnScrollListener.onScroll(getCurrentScreenFraction()); } } else if (mTouchState == TOUCH_STATE_REST) { if (mLocked) { // we're locked on the current screen, don't allow moving break; } /* * Locally do absolute value. mLastMotionX is set to the y value * of the down event. */ final int pointerIndex = MotionEventUtils.findPointerIndex(ev, mActivePointerId); final float x = MotionEventUtils.getX(ev, pointerIndex); final float y = MotionEventUtils.getY(ev, pointerIndex); final int xDiff = (int) Math.abs(x - mDownMotionX); final int yDiff = (int) Math.abs(y - mDownMotionY); boolean xPaged = xDiff > mPagingTouchSlop; boolean xMoved = xDiff > mTouchSlop; boolean yMoved = yDiff > mTouchSlop; if (xMoved || yMoved) { if (xPaged) { // Scroll if the user moved far enough along the X axis mTouchState = TOUCH_STATE_SCROLLING; } // 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 = getScreenAt(mCurrentScreen); if (currentScreen != null) { currentScreen.cancelLongPress(); } } } } break; case MotionEvent.ACTION_UP: if (mTouchState == TOUCH_STATE_SCROLLING) { final int activePointerId = mActivePointerId; final int pointerIndex = MotionEventUtils.findPointerIndex(ev, activePointerId); final float x = MotionEventUtils.getX(ev, pointerIndex); final VelocityTracker velocityTracker = mVelocityTracker; velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity); //TODO(minsdk8): int velocityX = (int) MotionEventUtils.getXVelocity(velocityTracker, activePointerId); int velocityX = (int) velocityTracker.getXVelocity(); boolean isFling = Math.abs(mDownMotionX - x) > MIN_LENGTH_FOR_FLING; final float scrolledPos = getCurrentScreenFraction(); final int whichScreen = Math.round(scrolledPos); if (isFling && mIsVerbose) { Log.v(TAG, "isFling, whichScreen=" + whichScreen + " scrolledPos=" + scrolledPos + " mCurrentScreen=" + mCurrentScreen + " velocityX=" + velocityX); } if (isFling && velocityX > SNAP_VELOCITY && mCurrentScreen > 0) { // Fling hard enough to move left // Don't fling across more than one screen at a time. final int bound = scrolledPos <= whichScreen ? mCurrentScreen - 1 : mCurrentScreen; snapToScreen(Math.min(whichScreen, bound)); } else if (isFling && velocityX < -SNAP_VELOCITY && mCurrentScreen < getChildCount() - 1) { // Fling hard enough to move right // Don't fling across more than one screen at a time. final int bound = scrolledPos >= whichScreen ? mCurrentScreen + 1 : mCurrentScreen; snapToScreen(Math.max(whichScreen, bound)); } else { snapToDestination(); } } mTouchState = TOUCH_STATE_REST; mActivePointerId = INVALID_POINTER; // Intentially fall through to cancel case MotionEvent.ACTION_CANCEL: mTouchState = TOUCH_STATE_REST; mActivePointerId = INVALID_POINTER; if (mVelocityTracker != null) { mVelocityTracker.recycle(); mVelocityTracker = null; } break; case MotionEventUtils.ACTION_POINTER_UP: onSecondaryPointerUp(ev); break; } return true; }
public boolean onTouchEvent(MotionEvent ev) { if (mIsVerbose) { Log.v(TAG, "onTouchEvent: " + (ev.getAction() & MotionEventUtils.ACTION_MASK)); } if (mVelocityTracker == null) { mVelocityTracker = VelocityTracker.obtain(); } mVelocityTracker.addMovement(ev); final int action = ev.getAction(); switch (action & MotionEventUtils.ACTION_MASK) { 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 mDownMotionX = ev.getX(); mDownMotionY = ev.getY(); mDownScrollX = getScrollX(); mActivePointerId = MotionEventUtils.getPointerId(ev, 0); break; case MotionEvent.ACTION_MOVE: if (mIsVerbose) { Log.v(TAG, "mTouchState=" + mTouchState); } if (mTouchState == TOUCH_STATE_SCROLLING) { // Scroll to follow the motion event final int pointerIndex = MotionEventUtils .findPointerIndex(ev, mActivePointerId); final float x = MotionEventUtils.getX(ev, pointerIndex); final View lastChild = getChildAt(getChildCount() - 1); final int maxScrollX = lastChild.getRight() - getWidth(); scrollTo(Math.max(0, Math.min(maxScrollX, (int)(mDownScrollX + mDownMotionX - x ))), 0); if (mOnScrollListener != null) { mOnScrollListener.onScroll(getCurrentScreenFraction()); } } else if (mTouchState == TOUCH_STATE_REST) { if (mLocked) { // we're locked on the current screen, don't allow moving break; } /* * Locally do absolute value. mLastMotionX is set to the y value * of the down event. */ final int pointerIndex = MotionEventUtils.findPointerIndex(ev, mActivePointerId); final float x = MotionEventUtils.getX(ev, pointerIndex); final float y = MotionEventUtils.getY(ev, pointerIndex); final int xDiff = (int) Math.abs(x - mDownMotionX); final int yDiff = (int) Math.abs(y - mDownMotionY); boolean xPaged = xDiff > mPagingTouchSlop; boolean xMoved = xDiff > mTouchSlop; boolean yMoved = yDiff > mTouchSlop; if (xMoved || yMoved) { if (xPaged) { // Scroll if the user moved far enough along the X axis mTouchState = TOUCH_STATE_SCROLLING; } // 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 = getScreenAt(mCurrentScreen); if (currentScreen != null) { currentScreen.cancelLongPress(); } } } } break; case MotionEvent.ACTION_UP: if (mTouchState == TOUCH_STATE_SCROLLING) { final int activePointerId = mActivePointerId; final int pointerIndex = MotionEventUtils.findPointerIndex(ev, activePointerId); final float x = MotionEventUtils.getX(ev, pointerIndex); final VelocityTracker velocityTracker = mVelocityTracker; velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity); //TODO(minsdk8): int velocityX = (int) MotionEventUtils.getXVelocity(velocityTracker, activePointerId); int velocityX = (int) velocityTracker.getXVelocity(); boolean isFling = Math.abs(mDownMotionX - x) > MIN_LENGTH_FOR_FLING; final float scrolledPos = getCurrentScreenFraction(); final int whichScreen = Math.round(scrolledPos); if (isFling && mIsVerbose) { Log.v(TAG, "isFling, whichScreen=" + whichScreen + " scrolledPos=" + scrolledPos + " mCurrentScreen=" + mCurrentScreen + " velocityX=" + velocityX); } if (isFling && velocityX > SNAP_VELOCITY && mCurrentScreen > 0) { // Fling hard enough to move left // Don't fling across more than one screen at a time. final int bound = scrolledPos <= whichScreen ? mCurrentScreen - 1 : mCurrentScreen; snapToScreen(Math.min(whichScreen, bound)); } else if (isFling && velocityX < -SNAP_VELOCITY && mCurrentScreen < getChildCount() - 1) { // Fling hard enough to move right // Don't fling across more than one screen at a time. final int bound = scrolledPos >= whichScreen ? mCurrentScreen + 1 : mCurrentScreen; snapToScreen(Math.max(whichScreen, bound)); } else { snapToDestination(); } } else { performClick(); } mTouchState = TOUCH_STATE_REST; mActivePointerId = INVALID_POINTER; // Intentially fall through to cancel case MotionEvent.ACTION_CANCEL: mTouchState = TOUCH_STATE_REST; mActivePointerId = INVALID_POINTER; if (mVelocityTracker != null) { mVelocityTracker.recycle(); mVelocityTracker = null; } break; case MotionEventUtils.ACTION_POINTER_UP: onSecondaryPointerUp(ev); break; } return true; }
diff --git a/tests/frontend/org/voltdb/compiler/TestVoltCompilerAnnotationsAndWarnings.java b/tests/frontend/org/voltdb/compiler/TestVoltCompilerAnnotationsAndWarnings.java index be05062ef..68049eef1 100644 --- a/tests/frontend/org/voltdb/compiler/TestVoltCompilerAnnotationsAndWarnings.java +++ b/tests/frontend/org/voltdb/compiler/TestVoltCompilerAnnotationsAndWarnings.java @@ -1,231 +1,231 @@ /* This file is part of VoltDB. * Copyright (C) 2008-2013 VoltDB 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 BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package org.voltdb.compiler; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import junit.framework.TestCase; import org.voltdb.VoltDB.Configuration; import org.voltdb.compiler.procedures.FloatParamToGetNiceComplaint; import org.voltdb_testprocs.regressionsuites.failureprocs.DeterministicRONonSeqProc; import org.voltdb_testprocs.regressionsuites.failureprocs.DeterministicROSeqProc; import org.voltdb_testprocs.regressionsuites.failureprocs.DeterministicRWProc1; import org.voltdb_testprocs.regressionsuites.failureprocs.DeterministicRWProc2; import org.voltdb_testprocs.regressionsuites.failureprocs.NondeterministicROProc; import org.voltdb_testprocs.regressionsuites.failureprocs.NondeterministicRWProc; import org.voltdb_testprocs.regressionsuites.failureprocs.ProcSPNoncandidate1; import org.voltdb_testprocs.regressionsuites.failureprocs.ProcSPNoncandidate2; import org.voltdb_testprocs.regressionsuites.failureprocs.ProcSPNoncandidate3; import org.voltdb_testprocs.regressionsuites.failureprocs.ProcSPNoncandidate4; import org.voltdb_testprocs.regressionsuites.failureprocs.ProcSPNoncandidate5; import org.voltdb_testprocs.regressionsuites.failureprocs.ProcSPNoncandidate6; import org.voltdb_testprocs.regressionsuites.failureprocs.ProcSPcandidate1; import org.voltdb_testprocs.regressionsuites.failureprocs.ProcSPcandidate2; import org.voltdb_testprocs.regressionsuites.failureprocs.ProcSPcandidate3; import org.voltdb_testprocs.regressionsuites.failureprocs.ProcSPcandidate4; import org.voltdb_testprocs.regressionsuites.failureprocs.ProcSPcandidate5; import org.voltdb_testprocs.regressionsuites.failureprocs.ProcSPcandidate6; import org.voltdb_testprocs.regressionsuites.failureprocs.ProcSPcandidate7; public class TestVoltCompilerAnnotationsAndWarnings extends TestCase { public void testFloatParamComplaint() throws Exception { String simpleSchema = "create table floatie (" + "ival bigint default 0 not null, " + "fval float not null," + "PRIMARY KEY(ival)" + ");"; VoltProjectBuilder builder = new VoltProjectBuilder(); ByteArrayOutputStream capturer = new ByteArrayOutputStream(); PrintStream capturing = new PrintStream(capturer); builder.setCompilerDebugPrintStream(capturing); builder.addLiteralSchema(simpleSchema); builder.addPartitionInfo("floatie", "ival"); builder.addProcedures(FloatParamToGetNiceComplaint.class); boolean success = builder.compile(Configuration.getPathToCatalogForTest("annotations.jar")); assertFalse(success); String captured = capturer.toString("UTF-8"); String[] lines = captured.split("\n"); // Output should include a line suggesting replacement of float with double. assertTrue(foundLineMatching(lines, ".*FloatParamToGetNiceComplaint.* float.* double.*")); } public void testSimple() throws Exception { String simpleSchema = "create table blah (" + "ival bigint default 0 not null, " + "sval varchar(255) not null" + ");" + "create table indexed_replicated_blah (" + "ival bigint default 0 not null, " + "sval varchar(255) not null, " + "PRIMARY KEY(ival)" + ");" + "create table indexed_partitioned_blah (" + "ival bigint default 0 not null, " + "sval varchar(255) not null, " + "PRIMARY KEY(ival)" + ");" + ""; VoltProjectBuilder builder = new VoltProjectBuilder(); ByteArrayOutputStream capturer = new ByteArrayOutputStream(); PrintStream capturing = new PrintStream(capturer); builder.setCompilerDebugPrintStream(capturing); builder.addLiteralSchema(simpleSchema); builder.addPartitionInfo("blah", "ival"); builder.addPartitionInfo("indexed_partitioned_blah", "ival"); // Note: indexed_replicated_blah is left as a replicated table. builder.addStmtProcedure("Insert", // Include lots of filthy whitespace to test output cleanup. "insert into\t \tblah values\n\n(? \t ,\t\t\t?) ;", null); builder.addProcedures(NondeterministicROProc.class); builder.addProcedures(NondeterministicRWProc.class); builder.addProcedures(DeterministicRONonSeqProc.class); builder.addProcedures(DeterministicROSeqProc.class); builder.addProcedures(DeterministicRWProc1.class); builder.addProcedures(DeterministicRWProc2.class); builder.addProcedures(ProcSPcandidate1.class); builder.addProcedures(ProcSPcandidate2.class); builder.addProcedures(ProcSPcandidate3.class); builder.addProcedures(ProcSPcandidate4.class); builder.addProcedures(ProcSPcandidate5.class); builder.addProcedures(ProcSPcandidate6.class); builder.addProcedures(ProcSPcandidate7.class); builder.addProcedures(ProcSPNoncandidate1.class); builder.addProcedures(ProcSPNoncandidate2.class); builder.addProcedures(ProcSPNoncandidate3.class); builder.addProcedures(ProcSPNoncandidate4.class); builder.addProcedures(ProcSPNoncandidate5.class); builder.addProcedures(ProcSPNoncandidate6.class); builder.addStmtProcedure("StmtSPcandidate1", "select count(*) from blah where ival = ?", null); builder.addStmtProcedure("StmtSPcandidate2", "select count(*) from blah where ival = 12345678", null); builder.addStmtProcedure("StmtSPcandidate3", "select count(*) from blah, indexed_replicated_blah " + "where indexed_replicated_blah.sval = blah.sval and blah.ival = 12345678", null); builder.addStmtProcedure("StmtSPcandidate4", "select count(*) from blah, indexed_replicated_blah " + "where indexed_replicated_blah.sval = blah.sval and blah.ival = abs(1)+1", null); builder.addStmtProcedure("StmtSPcandidate5", "select count(*) from blah where sval = ? and ival = 12345678", null); builder.addStmtProcedure("StmtSPcandidate6", "select count(*) from blah where sval = ? and ival = ?", null); builder.addStmtProcedure("StmtSPNoncandidate1", "select count(*) from blah where sval = ?", null); builder.addStmtProcedure("StmtSPNoncandidate2", "select count(*) from blah where sval = '12345678'", null); builder.addStmtProcedure("StmtSPNoncandidate3", "select count(*) from indexed_replicated_blah where ival = ?", null); boolean success = builder.compile(Configuration.getPathToCatalogForTest("annotations.jar")); assert(success); String captured = capturer.toString("UTF-8"); String[] lines = captured.split("\n"); - assertTrue(foundLineMatching(lines, ".*\\[RO].*NondeterministicROProc.*")); - assertTrue(foundLineMatching(lines, ".*\\[RO].*NondeterministicROProc.*")); - assertTrue(foundLineMatching(lines, ".*\\[RO].*DeterministicRONonSeqProc.*")); - assertTrue(foundLineMatching(lines, ".*\\[RO].*\\[Seq].*DeterministicROSeqProc.*")); - assertTrue(foundLineMatching(lines, ".*\\[RW].*Insert.*")); - assertTrue(foundLineMatching(lines, ".*\\[RW].*BLAH.insert.*")); - assertTrue(foundLineMatching(lines, ".*\\[RW].*NondeterministicRWProc.*")); - assertTrue(foundLineMatching(lines, ".*\\[RW].*DeterministicRWProc.*")); + assertTrue(foundLineMatching(lines, ".*\\[READ].*NondeterministicROProc.*")); + assertTrue(foundLineMatching(lines, ".*\\[READ].*NondeterministicROProc.*")); + assertTrue(foundLineMatching(lines, ".*\\[READ].*DeterministicRONonSeqProc.*")); + assertTrue(foundLineMatching(lines, ".*\\[READ].*DeterministicROSeqProc.*")); + assertTrue(foundLineMatching(lines, ".*\\[WRITE].*Insert.*")); + assertTrue(foundLineMatching(lines, ".*\\[WRITE].*BLAH.insert.*")); + assertTrue(foundLineMatching(lines, ".*\\[WRITE].*NondeterministicRWProc.*")); + assertTrue(foundLineMatching(lines, ".*\\[WRITE].*DeterministicRWProc.*")); assertEquals(1, countLinesMatching(lines, ".*\\[NDC].*NDC=true.*")); assertFalse(foundLineMatching(lines, ".*\\[NDC].*NDC=false.*")); - assertFalse(foundLineMatching(lines, ".*\\[RW].*NondeterministicROProc.*")); - assertFalse(foundLineMatching(lines, ".*\\[RW].*DeterministicRONonSeqProc.*")); - assertFalse(foundLineMatching(lines, ".*\\[RW].*\\[Seq].*DeterministicROSeqProc.*")); - assertFalse(foundLineMatching(lines, ".*\\[Seq].*DeterministicRONonSeqProc.*")); - assertFalse(foundLineMatching(lines, ".*\\[RO].*Insert.*")); - assertFalse(foundLineMatching(lines, ".*\\[RO].*BLAH.insert.*")); - assertFalse(foundLineMatching(lines, ".*\\[Seq].*Insert.*")); - assertFalse(foundLineMatching(lines, ".*\\[Seq].*BLAH.insert.*")); - assertFalse(foundLineMatching(lines, ".*\\[RO].*NondeterministicRWProc.*")); - assertFalse(foundLineMatching(lines, ".*\\[RO].*DeterministicRWProc.*")); + assertFalse(foundLineMatching(lines, ".*\\[WRITE].*NondeterministicROProc.*")); + assertFalse(foundLineMatching(lines, ".*\\[WRITE].*DeterministicRONonSeqProc.*")); + assertFalse(foundLineMatching(lines, ".*\\[WRITE].*DeterministicROSeqProc.*")); + assertFalse(foundLineMatching(lines, ".*\\[TABLE SCAN].*DeterministicRONonSeqProc.*")); + assertFalse(foundLineMatching(lines, ".*\\[READ].*Insert.*")); + assertFalse(foundLineMatching(lines, ".*\\[READ].*BLAH.insert.*")); + assertFalse(foundLineMatching(lines, ".*\\[TABLE SCAN].*Insert.*")); + assertFalse(foundLineMatching(lines, ".*\\[TABLE SCAN].*BLAH.insert.*")); + assertFalse(foundLineMatching(lines, ".*\\[READ].*NondeterministicRWProc.*")); + assertFalse(foundLineMatching(lines, ".*\\[READ].*DeterministicRWProc.*")); assertFalse(foundLineMatching(lines, ".*DeterministicRWProc.*non-deterministic.*")); // test SP improvement warnings assertEquals(4, countLinesMatching(lines, ".*\\[StmtSPcandidate.].*partitioninfo=BLAH\\.IVAL:0.*")); // StmtSPcandidates 1,2,3,4 assertEquals(2, countLinesMatching(lines, ".*\\[StmtSPcandidate.].*12345678.*partitioninfo=BLAH\\.IVAL:0.*")); // 2, 3 assertEquals(1, countLinesMatching(lines, ".*\\[StmtSPcandidate.].*abs.*partitioninfo=BLAH\\.IVAL:0.*")); // just 4 assertEquals(1, countLinesMatching(lines, ".*\\[StmtSPcandidate.].*12345678.*partitioninfo=BLAH\\.IVAL:1.*")); // just 5 assertEquals(2, countLinesMatching(lines, ".*\\[StmtSPcandidate.].*partitioninfo=BLAH\\.IVAL:1.*")); // 5, 6 assertEquals(1, countLinesMatching(lines, ".*\\[ProcSPcandidate.\\.class].*designating parameter 0 .*")); // ProcSPcandidate 1 assertEquals(4, countLinesMatching(lines, ".*\\[ProcSPcandidate.\\.class].*added parameter .*87654321.*")); // 2, 3, 5, 6 assertEquals(1, countLinesMatching(lines, ".*\\[ProcSPcandidate.\\.class].*added parameter .*abs.*")); // just 4 assertEquals(1, countLinesMatching(lines, ".*\\[ProcSPcandidate.\\.class].*designating parameter 1 .*")); // 7 // Non-candidates disqualify themselves by various means. assertEquals(0, countLinesMatching(lines, ".*\\[SPNoncandidate.].*partitioninfo=BLAH\\.IVAL:0.*")); assertEquals(0, countLinesMatching(lines, ".*\\[SPNoncandidate.].*partitioninfo=BLAH\\.IVAL:1.*")); assertEquals(0, countLinesMatching(lines, ".*\\[ProcSPNoncandidate.\\.class].* parameter .*")); assertEquals(0, countLinesMatching(lines, ".*\\[ProcSPNoncandidate.\\.class].* parameter .*")); // test prettying-up of statements in feedback output. ("^[^ ].*") is used to confirm that the (symbol-prefixed) log statements contain the original ugliness. // While ("^ .*") is used to confirm that the (space-prefixed) feedback to the user is cleaned up. assertTrue(foundLineMatching(lines, "^[^ ].*values.* .*")); // includes 2 embedded or trailing spaces. assertFalse(foundLineMatching(lines, "^ .*values.* .*")); // includes 2 embedded or trailing spaces. assertTrue(foundLineMatching(lines, "^[^ ].*nsert.* .*values.*")); // includes 2 embedded spaces. assertFalse(foundLineMatching(lines, "^ .*nsert.* .*values.*")); // includes 2 embedded spaces. assertTrue(foundLineMatching(lines, "^[^ ].*values.*\u0009.*")); // that's an embedded or trailing unicode tab. assertFalse(foundLineMatching(lines, "^ .*values.*\u0009.*")); // that's an embedded or trailing unicode tab. assertTrue(foundLineMatching(lines, "^[^ ].*nsert.*\u0009.*values.*")); // that's an embedded unicode tab. assertFalse(foundLineMatching(lines, "^ .*nsert.*\u0009.*values.*")); // that's an embedded unicode tab. assertTrue(foundLineMatching(lines, "^[^ ].*values.*\\s\\s.*")); // includes 2 successive embedded or trailing whitespace of any kind assertFalse(foundLineMatching(lines, "^ .*values.*\\s\\s.*")); // includes 2 successive embedded or trailing whitespace of any kind assertTrue(foundLineMatching(lines, "^[^ ].*nsert.*\\s\\s.*values.*")); // includes 2 successive embedded whitespace of any kind assertFalse(foundLineMatching(lines, "^ .*nsert.*\\s\\s.*values.*")); // includes 2 successive embedded whitespace of any kind } private boolean foundLineMatching(String[] lines, String pattern) { for (String string : lines) { if (string.matches(pattern)) { return true; } } return false; } private int countLinesMatching(String[] lines, String pattern) { int count = 0; for (String string : lines) { if (string.matches(pattern)) { ++count; } } return count; } }
false
true
public void testSimple() throws Exception { String simpleSchema = "create table blah (" + "ival bigint default 0 not null, " + "sval varchar(255) not null" + ");" + "create table indexed_replicated_blah (" + "ival bigint default 0 not null, " + "sval varchar(255) not null, " + "PRIMARY KEY(ival)" + ");" + "create table indexed_partitioned_blah (" + "ival bigint default 0 not null, " + "sval varchar(255) not null, " + "PRIMARY KEY(ival)" + ");" + ""; VoltProjectBuilder builder = new VoltProjectBuilder(); ByteArrayOutputStream capturer = new ByteArrayOutputStream(); PrintStream capturing = new PrintStream(capturer); builder.setCompilerDebugPrintStream(capturing); builder.addLiteralSchema(simpleSchema); builder.addPartitionInfo("blah", "ival"); builder.addPartitionInfo("indexed_partitioned_blah", "ival"); // Note: indexed_replicated_blah is left as a replicated table. builder.addStmtProcedure("Insert", // Include lots of filthy whitespace to test output cleanup. "insert into\t \tblah values\n\n(? \t ,\t\t\t?) ;", null); builder.addProcedures(NondeterministicROProc.class); builder.addProcedures(NondeterministicRWProc.class); builder.addProcedures(DeterministicRONonSeqProc.class); builder.addProcedures(DeterministicROSeqProc.class); builder.addProcedures(DeterministicRWProc1.class); builder.addProcedures(DeterministicRWProc2.class); builder.addProcedures(ProcSPcandidate1.class); builder.addProcedures(ProcSPcandidate2.class); builder.addProcedures(ProcSPcandidate3.class); builder.addProcedures(ProcSPcandidate4.class); builder.addProcedures(ProcSPcandidate5.class); builder.addProcedures(ProcSPcandidate6.class); builder.addProcedures(ProcSPcandidate7.class); builder.addProcedures(ProcSPNoncandidate1.class); builder.addProcedures(ProcSPNoncandidate2.class); builder.addProcedures(ProcSPNoncandidate3.class); builder.addProcedures(ProcSPNoncandidate4.class); builder.addProcedures(ProcSPNoncandidate5.class); builder.addProcedures(ProcSPNoncandidate6.class); builder.addStmtProcedure("StmtSPcandidate1", "select count(*) from blah where ival = ?", null); builder.addStmtProcedure("StmtSPcandidate2", "select count(*) from blah where ival = 12345678", null); builder.addStmtProcedure("StmtSPcandidate3", "select count(*) from blah, indexed_replicated_blah " + "where indexed_replicated_blah.sval = blah.sval and blah.ival = 12345678", null); builder.addStmtProcedure("StmtSPcandidate4", "select count(*) from blah, indexed_replicated_blah " + "where indexed_replicated_blah.sval = blah.sval and blah.ival = abs(1)+1", null); builder.addStmtProcedure("StmtSPcandidate5", "select count(*) from blah where sval = ? and ival = 12345678", null); builder.addStmtProcedure("StmtSPcandidate6", "select count(*) from blah where sval = ? and ival = ?", null); builder.addStmtProcedure("StmtSPNoncandidate1", "select count(*) from blah where sval = ?", null); builder.addStmtProcedure("StmtSPNoncandidate2", "select count(*) from blah where sval = '12345678'", null); builder.addStmtProcedure("StmtSPNoncandidate3", "select count(*) from indexed_replicated_blah where ival = ?", null); boolean success = builder.compile(Configuration.getPathToCatalogForTest("annotations.jar")); assert(success); String captured = capturer.toString("UTF-8"); String[] lines = captured.split("\n"); assertTrue(foundLineMatching(lines, ".*\\[RO].*NondeterministicROProc.*")); assertTrue(foundLineMatching(lines, ".*\\[RO].*NondeterministicROProc.*")); assertTrue(foundLineMatching(lines, ".*\\[RO].*DeterministicRONonSeqProc.*")); assertTrue(foundLineMatching(lines, ".*\\[RO].*\\[Seq].*DeterministicROSeqProc.*")); assertTrue(foundLineMatching(lines, ".*\\[RW].*Insert.*")); assertTrue(foundLineMatching(lines, ".*\\[RW].*BLAH.insert.*")); assertTrue(foundLineMatching(lines, ".*\\[RW].*NondeterministicRWProc.*")); assertTrue(foundLineMatching(lines, ".*\\[RW].*DeterministicRWProc.*")); assertEquals(1, countLinesMatching(lines, ".*\\[NDC].*NDC=true.*")); assertFalse(foundLineMatching(lines, ".*\\[NDC].*NDC=false.*")); assertFalse(foundLineMatching(lines, ".*\\[RW].*NondeterministicROProc.*")); assertFalse(foundLineMatching(lines, ".*\\[RW].*DeterministicRONonSeqProc.*")); assertFalse(foundLineMatching(lines, ".*\\[RW].*\\[Seq].*DeterministicROSeqProc.*")); assertFalse(foundLineMatching(lines, ".*\\[Seq].*DeterministicRONonSeqProc.*")); assertFalse(foundLineMatching(lines, ".*\\[RO].*Insert.*")); assertFalse(foundLineMatching(lines, ".*\\[RO].*BLAH.insert.*")); assertFalse(foundLineMatching(lines, ".*\\[Seq].*Insert.*")); assertFalse(foundLineMatching(lines, ".*\\[Seq].*BLAH.insert.*")); assertFalse(foundLineMatching(lines, ".*\\[RO].*NondeterministicRWProc.*")); assertFalse(foundLineMatching(lines, ".*\\[RO].*DeterministicRWProc.*")); assertFalse(foundLineMatching(lines, ".*DeterministicRWProc.*non-deterministic.*")); // test SP improvement warnings assertEquals(4, countLinesMatching(lines, ".*\\[StmtSPcandidate.].*partitioninfo=BLAH\\.IVAL:0.*")); // StmtSPcandidates 1,2,3,4 assertEquals(2, countLinesMatching(lines, ".*\\[StmtSPcandidate.].*12345678.*partitioninfo=BLAH\\.IVAL:0.*")); // 2, 3 assertEquals(1, countLinesMatching(lines, ".*\\[StmtSPcandidate.].*abs.*partitioninfo=BLAH\\.IVAL:0.*")); // just 4 assertEquals(1, countLinesMatching(lines, ".*\\[StmtSPcandidate.].*12345678.*partitioninfo=BLAH\\.IVAL:1.*")); // just 5 assertEquals(2, countLinesMatching(lines, ".*\\[StmtSPcandidate.].*partitioninfo=BLAH\\.IVAL:1.*")); // 5, 6 assertEquals(1, countLinesMatching(lines, ".*\\[ProcSPcandidate.\\.class].*designating parameter 0 .*")); // ProcSPcandidate 1 assertEquals(4, countLinesMatching(lines, ".*\\[ProcSPcandidate.\\.class].*added parameter .*87654321.*")); // 2, 3, 5, 6 assertEquals(1, countLinesMatching(lines, ".*\\[ProcSPcandidate.\\.class].*added parameter .*abs.*")); // just 4 assertEquals(1, countLinesMatching(lines, ".*\\[ProcSPcandidate.\\.class].*designating parameter 1 .*")); // 7 // Non-candidates disqualify themselves by various means. assertEquals(0, countLinesMatching(lines, ".*\\[SPNoncandidate.].*partitioninfo=BLAH\\.IVAL:0.*")); assertEquals(0, countLinesMatching(lines, ".*\\[SPNoncandidate.].*partitioninfo=BLAH\\.IVAL:1.*")); assertEquals(0, countLinesMatching(lines, ".*\\[ProcSPNoncandidate.\\.class].* parameter .*")); assertEquals(0, countLinesMatching(lines, ".*\\[ProcSPNoncandidate.\\.class].* parameter .*")); // test prettying-up of statements in feedback output. ("^[^ ].*") is used to confirm that the (symbol-prefixed) log statements contain the original ugliness. // While ("^ .*") is used to confirm that the (space-prefixed) feedback to the user is cleaned up. assertTrue(foundLineMatching(lines, "^[^ ].*values.* .*")); // includes 2 embedded or trailing spaces. assertFalse(foundLineMatching(lines, "^ .*values.* .*")); // includes 2 embedded or trailing spaces. assertTrue(foundLineMatching(lines, "^[^ ].*nsert.* .*values.*")); // includes 2 embedded spaces. assertFalse(foundLineMatching(lines, "^ .*nsert.* .*values.*")); // includes 2 embedded spaces. assertTrue(foundLineMatching(lines, "^[^ ].*values.*\u0009.*")); // that's an embedded or trailing unicode tab. assertFalse(foundLineMatching(lines, "^ .*values.*\u0009.*")); // that's an embedded or trailing unicode tab. assertTrue(foundLineMatching(lines, "^[^ ].*nsert.*\u0009.*values.*")); // that's an embedded unicode tab. assertFalse(foundLineMatching(lines, "^ .*nsert.*\u0009.*values.*")); // that's an embedded unicode tab. assertTrue(foundLineMatching(lines, "^[^ ].*values.*\\s\\s.*")); // includes 2 successive embedded or trailing whitespace of any kind assertFalse(foundLineMatching(lines, "^ .*values.*\\s\\s.*")); // includes 2 successive embedded or trailing whitespace of any kind assertTrue(foundLineMatching(lines, "^[^ ].*nsert.*\\s\\s.*values.*")); // includes 2 successive embedded whitespace of any kind assertFalse(foundLineMatching(lines, "^ .*nsert.*\\s\\s.*values.*")); // includes 2 successive embedded whitespace of any kind }
public void testSimple() throws Exception { String simpleSchema = "create table blah (" + "ival bigint default 0 not null, " + "sval varchar(255) not null" + ");" + "create table indexed_replicated_blah (" + "ival bigint default 0 not null, " + "sval varchar(255) not null, " + "PRIMARY KEY(ival)" + ");" + "create table indexed_partitioned_blah (" + "ival bigint default 0 not null, " + "sval varchar(255) not null, " + "PRIMARY KEY(ival)" + ");" + ""; VoltProjectBuilder builder = new VoltProjectBuilder(); ByteArrayOutputStream capturer = new ByteArrayOutputStream(); PrintStream capturing = new PrintStream(capturer); builder.setCompilerDebugPrintStream(capturing); builder.addLiteralSchema(simpleSchema); builder.addPartitionInfo("blah", "ival"); builder.addPartitionInfo("indexed_partitioned_blah", "ival"); // Note: indexed_replicated_blah is left as a replicated table. builder.addStmtProcedure("Insert", // Include lots of filthy whitespace to test output cleanup. "insert into\t \tblah values\n\n(? \t ,\t\t\t?) ;", null); builder.addProcedures(NondeterministicROProc.class); builder.addProcedures(NondeterministicRWProc.class); builder.addProcedures(DeterministicRONonSeqProc.class); builder.addProcedures(DeterministicROSeqProc.class); builder.addProcedures(DeterministicRWProc1.class); builder.addProcedures(DeterministicRWProc2.class); builder.addProcedures(ProcSPcandidate1.class); builder.addProcedures(ProcSPcandidate2.class); builder.addProcedures(ProcSPcandidate3.class); builder.addProcedures(ProcSPcandidate4.class); builder.addProcedures(ProcSPcandidate5.class); builder.addProcedures(ProcSPcandidate6.class); builder.addProcedures(ProcSPcandidate7.class); builder.addProcedures(ProcSPNoncandidate1.class); builder.addProcedures(ProcSPNoncandidate2.class); builder.addProcedures(ProcSPNoncandidate3.class); builder.addProcedures(ProcSPNoncandidate4.class); builder.addProcedures(ProcSPNoncandidate5.class); builder.addProcedures(ProcSPNoncandidate6.class); builder.addStmtProcedure("StmtSPcandidate1", "select count(*) from blah where ival = ?", null); builder.addStmtProcedure("StmtSPcandidate2", "select count(*) from blah where ival = 12345678", null); builder.addStmtProcedure("StmtSPcandidate3", "select count(*) from blah, indexed_replicated_blah " + "where indexed_replicated_blah.sval = blah.sval and blah.ival = 12345678", null); builder.addStmtProcedure("StmtSPcandidate4", "select count(*) from blah, indexed_replicated_blah " + "where indexed_replicated_blah.sval = blah.sval and blah.ival = abs(1)+1", null); builder.addStmtProcedure("StmtSPcandidate5", "select count(*) from blah where sval = ? and ival = 12345678", null); builder.addStmtProcedure("StmtSPcandidate6", "select count(*) from blah where sval = ? and ival = ?", null); builder.addStmtProcedure("StmtSPNoncandidate1", "select count(*) from blah where sval = ?", null); builder.addStmtProcedure("StmtSPNoncandidate2", "select count(*) from blah where sval = '12345678'", null); builder.addStmtProcedure("StmtSPNoncandidate3", "select count(*) from indexed_replicated_blah where ival = ?", null); boolean success = builder.compile(Configuration.getPathToCatalogForTest("annotations.jar")); assert(success); String captured = capturer.toString("UTF-8"); String[] lines = captured.split("\n"); assertTrue(foundLineMatching(lines, ".*\\[READ].*NondeterministicROProc.*")); assertTrue(foundLineMatching(lines, ".*\\[READ].*NondeterministicROProc.*")); assertTrue(foundLineMatching(lines, ".*\\[READ].*DeterministicRONonSeqProc.*")); assertTrue(foundLineMatching(lines, ".*\\[READ].*DeterministicROSeqProc.*")); assertTrue(foundLineMatching(lines, ".*\\[WRITE].*Insert.*")); assertTrue(foundLineMatching(lines, ".*\\[WRITE].*BLAH.insert.*")); assertTrue(foundLineMatching(lines, ".*\\[WRITE].*NondeterministicRWProc.*")); assertTrue(foundLineMatching(lines, ".*\\[WRITE].*DeterministicRWProc.*")); assertEquals(1, countLinesMatching(lines, ".*\\[NDC].*NDC=true.*")); assertFalse(foundLineMatching(lines, ".*\\[NDC].*NDC=false.*")); assertFalse(foundLineMatching(lines, ".*\\[WRITE].*NondeterministicROProc.*")); assertFalse(foundLineMatching(lines, ".*\\[WRITE].*DeterministicRONonSeqProc.*")); assertFalse(foundLineMatching(lines, ".*\\[WRITE].*DeterministicROSeqProc.*")); assertFalse(foundLineMatching(lines, ".*\\[TABLE SCAN].*DeterministicRONonSeqProc.*")); assertFalse(foundLineMatching(lines, ".*\\[READ].*Insert.*")); assertFalse(foundLineMatching(lines, ".*\\[READ].*BLAH.insert.*")); assertFalse(foundLineMatching(lines, ".*\\[TABLE SCAN].*Insert.*")); assertFalse(foundLineMatching(lines, ".*\\[TABLE SCAN].*BLAH.insert.*")); assertFalse(foundLineMatching(lines, ".*\\[READ].*NondeterministicRWProc.*")); assertFalse(foundLineMatching(lines, ".*\\[READ].*DeterministicRWProc.*")); assertFalse(foundLineMatching(lines, ".*DeterministicRWProc.*non-deterministic.*")); // test SP improvement warnings assertEquals(4, countLinesMatching(lines, ".*\\[StmtSPcandidate.].*partitioninfo=BLAH\\.IVAL:0.*")); // StmtSPcandidates 1,2,3,4 assertEquals(2, countLinesMatching(lines, ".*\\[StmtSPcandidate.].*12345678.*partitioninfo=BLAH\\.IVAL:0.*")); // 2, 3 assertEquals(1, countLinesMatching(lines, ".*\\[StmtSPcandidate.].*abs.*partitioninfo=BLAH\\.IVAL:0.*")); // just 4 assertEquals(1, countLinesMatching(lines, ".*\\[StmtSPcandidate.].*12345678.*partitioninfo=BLAH\\.IVAL:1.*")); // just 5 assertEquals(2, countLinesMatching(lines, ".*\\[StmtSPcandidate.].*partitioninfo=BLAH\\.IVAL:1.*")); // 5, 6 assertEquals(1, countLinesMatching(lines, ".*\\[ProcSPcandidate.\\.class].*designating parameter 0 .*")); // ProcSPcandidate 1 assertEquals(4, countLinesMatching(lines, ".*\\[ProcSPcandidate.\\.class].*added parameter .*87654321.*")); // 2, 3, 5, 6 assertEquals(1, countLinesMatching(lines, ".*\\[ProcSPcandidate.\\.class].*added parameter .*abs.*")); // just 4 assertEquals(1, countLinesMatching(lines, ".*\\[ProcSPcandidate.\\.class].*designating parameter 1 .*")); // 7 // Non-candidates disqualify themselves by various means. assertEquals(0, countLinesMatching(lines, ".*\\[SPNoncandidate.].*partitioninfo=BLAH\\.IVAL:0.*")); assertEquals(0, countLinesMatching(lines, ".*\\[SPNoncandidate.].*partitioninfo=BLAH\\.IVAL:1.*")); assertEquals(0, countLinesMatching(lines, ".*\\[ProcSPNoncandidate.\\.class].* parameter .*")); assertEquals(0, countLinesMatching(lines, ".*\\[ProcSPNoncandidate.\\.class].* parameter .*")); // test prettying-up of statements in feedback output. ("^[^ ].*") is used to confirm that the (symbol-prefixed) log statements contain the original ugliness. // While ("^ .*") is used to confirm that the (space-prefixed) feedback to the user is cleaned up. assertTrue(foundLineMatching(lines, "^[^ ].*values.* .*")); // includes 2 embedded or trailing spaces. assertFalse(foundLineMatching(lines, "^ .*values.* .*")); // includes 2 embedded or trailing spaces. assertTrue(foundLineMatching(lines, "^[^ ].*nsert.* .*values.*")); // includes 2 embedded spaces. assertFalse(foundLineMatching(lines, "^ .*nsert.* .*values.*")); // includes 2 embedded spaces. assertTrue(foundLineMatching(lines, "^[^ ].*values.*\u0009.*")); // that's an embedded or trailing unicode tab. assertFalse(foundLineMatching(lines, "^ .*values.*\u0009.*")); // that's an embedded or trailing unicode tab. assertTrue(foundLineMatching(lines, "^[^ ].*nsert.*\u0009.*values.*")); // that's an embedded unicode tab. assertFalse(foundLineMatching(lines, "^ .*nsert.*\u0009.*values.*")); // that's an embedded unicode tab. assertTrue(foundLineMatching(lines, "^[^ ].*values.*\\s\\s.*")); // includes 2 successive embedded or trailing whitespace of any kind assertFalse(foundLineMatching(lines, "^ .*values.*\\s\\s.*")); // includes 2 successive embedded or trailing whitespace of any kind assertTrue(foundLineMatching(lines, "^[^ ].*nsert.*\\s\\s.*values.*")); // includes 2 successive embedded whitespace of any kind assertFalse(foundLineMatching(lines, "^ .*nsert.*\\s\\s.*values.*")); // includes 2 successive embedded whitespace of any kind }
diff --git a/core/src/test/java/eu/europeana/bootstrap/LoadContent.java b/core/src/test/java/eu/europeana/bootstrap/LoadContent.java index bec2d86..230abf3 100644 --- a/core/src/test/java/eu/europeana/bootstrap/LoadContent.java +++ b/core/src/test/java/eu/europeana/bootstrap/LoadContent.java @@ -1,105 +1,105 @@ /* * Copyright 2007 EDL FOUNDATION * * Licensed under the EUPL, Version 1.1 or - as soon they * will be approved by the European Commission - subsequent * versions of the EUPL (the "Licence"); * you may not use this work except in compliance with the * Licence. * You may obtain a copy of the Licence at: * * http://ec.europa.eu/idabc/eupl * * Unless required by applicable law or agreed to in * writing, software distributed under the Licence is * distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. * See the Licence for the specific language governing * permissions and limitations under the Licence. */ package eu.europeana.bootstrap; import eu.europeana.database.DashboardDao; import eu.europeana.database.LanguageDao; import eu.europeana.database.StaticInfoDao; import eu.europeana.database.domain.EuropeanaCollection; import eu.europeana.database.domain.ImportFileState; import eu.europeana.database.migration.DataMigration; import eu.europeana.incoming.ESEImporter; import eu.europeana.incoming.ImportFile; import eu.europeana.incoming.ImportRepository; import org.apache.log4j.Logger; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import java.io.File; /** * @author Sjoerd Siebinga <[email protected]> * @since Jun 29, 2009: 4:15:22 PM */ public class LoadContent { private static final Logger log = Logger.getLogger(LoadContent.class); public static void main(String[] args) throws Exception { ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{ "/core-application-context.xml" }); ESEImporter eseImporter = (ESEImporter) context.getBean("normalizedEseImporter"); DashboardDao dashboardDao = (DashboardDao) context.getBean("dashboardDao"); ImportRepository repository = (ImportRepository) context.getBean("normalizedImportRepository"); LanguageDao languageDao = (LanguageDao) context.getBean("languageDao"); StaticInfoDao staticInfoDao = (StaticInfoDao) context.getBean("staticInfoDao"); // load static content etc. - if ((args.length > 0) && !args[0].equalsIgnoreCase("skip=true")) { + if ((args.length == 0) || !args[0].equalsIgnoreCase("skip=true")) { log.info("Start loading static content."); DataMigration migration = new DataMigration(); migration.setLanguageDao(languageDao); migration.setPartnerDao(staticInfoDao); migration.readTableFromResource(DataMigration.Table.CONTRIBUTORS); migration.readTableFromResource(DataMigration.Table.PARTNERS); migration.readTableFromResource(DataMigration.Table.TRANSLATION_KEYS); migration.readTableFromResource(DataMigration.Table.STATIC_PAGE); log.info("Finished loading static content."); } // import and index sample records SolrStarter solr = new SolrStarter(); log.info("Starting Solr Server"); solr.start(); final File file = new File("./core/src/test/resources/test-files/92001_Ag_EU_TELtreasures.xml"); EuropeanaCollection europeanaCollection = dashboardDao.fetchCollectionByFileName(file.getName()); ImportFile importFile = repository.copyToUploaded(file); if (europeanaCollection == null) { europeanaCollection = dashboardDao.fetchCollectionByName(importFile.getFileName(), true); } importFile = eseImporter.commenceImport(importFile, europeanaCollection.getId()); log.info("Importing commenced for " + importFile); while (europeanaCollection.getFileState() == ImportFileState.UPLOADED) { log.info("waiting to leave UPLOADED state"); Thread.sleep(500); europeanaCollection = dashboardDao.fetchCollection(europeanaCollection.getId()); } while (europeanaCollection.getFileState() == ImportFileState.IMPORTING) { log.info("waiting to leave IMPORTING state"); Thread.sleep(500); europeanaCollection = dashboardDao.fetchCollection(europeanaCollection.getId()); } Thread.sleep(10000); solr.stop(); log.info("Stopping Solr server"); // check if default user exist otherwise create } }
true
true
public static void main(String[] args) throws Exception { ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{ "/core-application-context.xml" }); ESEImporter eseImporter = (ESEImporter) context.getBean("normalizedEseImporter"); DashboardDao dashboardDao = (DashboardDao) context.getBean("dashboardDao"); ImportRepository repository = (ImportRepository) context.getBean("normalizedImportRepository"); LanguageDao languageDao = (LanguageDao) context.getBean("languageDao"); StaticInfoDao staticInfoDao = (StaticInfoDao) context.getBean("staticInfoDao"); // load static content etc. if ((args.length > 0) && !args[0].equalsIgnoreCase("skip=true")) { log.info("Start loading static content."); DataMigration migration = new DataMigration(); migration.setLanguageDao(languageDao); migration.setPartnerDao(staticInfoDao); migration.readTableFromResource(DataMigration.Table.CONTRIBUTORS); migration.readTableFromResource(DataMigration.Table.PARTNERS); migration.readTableFromResource(DataMigration.Table.TRANSLATION_KEYS); migration.readTableFromResource(DataMigration.Table.STATIC_PAGE); log.info("Finished loading static content."); } // import and index sample records SolrStarter solr = new SolrStarter(); log.info("Starting Solr Server"); solr.start(); final File file = new File("./core/src/test/resources/test-files/92001_Ag_EU_TELtreasures.xml"); EuropeanaCollection europeanaCollection = dashboardDao.fetchCollectionByFileName(file.getName()); ImportFile importFile = repository.copyToUploaded(file); if (europeanaCollection == null) { europeanaCollection = dashboardDao.fetchCollectionByName(importFile.getFileName(), true); } importFile = eseImporter.commenceImport(importFile, europeanaCollection.getId()); log.info("Importing commenced for " + importFile); while (europeanaCollection.getFileState() == ImportFileState.UPLOADED) { log.info("waiting to leave UPLOADED state"); Thread.sleep(500); europeanaCollection = dashboardDao.fetchCollection(europeanaCollection.getId()); } while (europeanaCollection.getFileState() == ImportFileState.IMPORTING) { log.info("waiting to leave IMPORTING state"); Thread.sleep(500); europeanaCollection = dashboardDao.fetchCollection(europeanaCollection.getId()); } Thread.sleep(10000); solr.stop(); log.info("Stopping Solr server"); // check if default user exist otherwise create }
public static void main(String[] args) throws Exception { ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{ "/core-application-context.xml" }); ESEImporter eseImporter = (ESEImporter) context.getBean("normalizedEseImporter"); DashboardDao dashboardDao = (DashboardDao) context.getBean("dashboardDao"); ImportRepository repository = (ImportRepository) context.getBean("normalizedImportRepository"); LanguageDao languageDao = (LanguageDao) context.getBean("languageDao"); StaticInfoDao staticInfoDao = (StaticInfoDao) context.getBean("staticInfoDao"); // load static content etc. if ((args.length == 0) || !args[0].equalsIgnoreCase("skip=true")) { log.info("Start loading static content."); DataMigration migration = new DataMigration(); migration.setLanguageDao(languageDao); migration.setPartnerDao(staticInfoDao); migration.readTableFromResource(DataMigration.Table.CONTRIBUTORS); migration.readTableFromResource(DataMigration.Table.PARTNERS); migration.readTableFromResource(DataMigration.Table.TRANSLATION_KEYS); migration.readTableFromResource(DataMigration.Table.STATIC_PAGE); log.info("Finished loading static content."); } // import and index sample records SolrStarter solr = new SolrStarter(); log.info("Starting Solr Server"); solr.start(); final File file = new File("./core/src/test/resources/test-files/92001_Ag_EU_TELtreasures.xml"); EuropeanaCollection europeanaCollection = dashboardDao.fetchCollectionByFileName(file.getName()); ImportFile importFile = repository.copyToUploaded(file); if (europeanaCollection == null) { europeanaCollection = dashboardDao.fetchCollectionByName(importFile.getFileName(), true); } importFile = eseImporter.commenceImport(importFile, europeanaCollection.getId()); log.info("Importing commenced for " + importFile); while (europeanaCollection.getFileState() == ImportFileState.UPLOADED) { log.info("waiting to leave UPLOADED state"); Thread.sleep(500); europeanaCollection = dashboardDao.fetchCollection(europeanaCollection.getId()); } while (europeanaCollection.getFileState() == ImportFileState.IMPORTING) { log.info("waiting to leave IMPORTING state"); Thread.sleep(500); europeanaCollection = dashboardDao.fetchCollection(europeanaCollection.getId()); } Thread.sleep(10000); solr.stop(); log.info("Stopping Solr server"); // check if default user exist otherwise create }
diff --git a/com.ibm.wala.j2ee/src/com/ibm/wala/model/javax/servlet/ServletConfig.java b/com.ibm.wala.j2ee/src/com/ibm/wala/model/javax/servlet/ServletConfig.java index 344587c63..c391d4db0 100644 --- a/com.ibm.wala.j2ee/src/com/ibm/wala/model/javax/servlet/ServletConfig.java +++ b/com.ibm.wala.j2ee/src/com/ibm/wala/model/javax/servlet/ServletConfig.java @@ -1,41 +1,41 @@ /******************************************************************************* * Copyright (c) 2002 - 2006 IBM 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: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.wala.model.javax.servlet; import java.util.Enumeration; import java.util.Vector; /** * @author sfink * */ public class ServletConfig implements javax.servlet.ServletConfig { public String getServletName() { return "some name"; } public javax.servlet.ServletContext getServletContext() { return com.ibm.wala.model.javax.servlet.ServletContext.getModelInstance(); } public String getInitParameter(String arg0) { return ServletRequest.getInputString(); } public Enumeration<String> getInitParameterNames() { Vector<String> v = new Vector<String>(); - v.add("a String"); + v.add(ServletRequest.getInputString()); return v.elements(); } }
true
true
public Enumeration<String> getInitParameterNames() { Vector<String> v = new Vector<String>(); v.add("a String"); return v.elements(); }
public Enumeration<String> getInitParameterNames() { Vector<String> v = new Vector<String>(); v.add(ServletRequest.getInputString()); return v.elements(); }
diff --git a/src/au/edu/labshare/rigclient/action/access/DeviceOwnershipAccessAction.java b/src/au/edu/labshare/rigclient/action/access/DeviceOwnershipAccessAction.java index 48dda05..dea5dcf 100644 --- a/src/au/edu/labshare/rigclient/action/access/DeviceOwnershipAccessAction.java +++ b/src/au/edu/labshare/rigclient/action/access/DeviceOwnershipAccessAction.java @@ -1,208 +1,209 @@ /** * SAHARA Rig Client * * Software abstraction of physical rig to provide rig session control * and rig device control. Automatically tests rig hardware and reports * the rig status to ensure rig goodness. * * @license See LICENSE in the top level directory for complete license terms. * * Copyright (c) 2010, University of Technology, Sydney * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Technology, Sydney 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. * * @author David Knight (davknigh) * @date 27th August 2010 * * Changelog: * - 27/08/2010 - davknigh - Initial file creation. */ package au.edu.labshare.rigclient.action.access; import java.util.ArrayList; import java.util.List; import au.edu.uts.eng.remotelabs.rigclient.rig.IAccessAction; import au.edu.uts.eng.remotelabs.rigclient.util.ConfigFactory; import au.edu.uts.eng.remotelabs.rigclient.util.IConfig; import au.edu.uts.eng.remotelabs.rigclient.util.ILogger; import au.edu.uts.eng.remotelabs.rigclient.util.LoggerFactory; /** * Access action that changes the ownership of specified devices to the * allocated user on allocate, and then back to root on * revoke. This action can be used to change ownership of local devices, or * devices on a remote host, using ssh. For remote hosts, Host key * authentication must be enabled - if the ssh transaction requires * a password, the rigclient will deadlock. * <br /> * The required configuration for this action is: * <ul> * <li>Device_Ownership_Host_Address - The address to the host where the * device is connected to. This is only needed if the device is not local and * requires a SSH connection to change the device ownership.</li> * <li>Device_Ownership_Path_&lt;n&gt; - The paths of the devices to change the * ownership of. Multiple paths can be configured from 1 to n paths * where n is the property name suffix.</li> * </ul> */ public class DeviceOwnershipAccessAction implements IAccessAction { /** Logger */ private ILogger logger; /** The devices to change ownership of */ private List<String> devices; /** The last reason for failure */ private String failureReason; /** Builder for operating system process */ private ProcessBuilder pb; public DeviceOwnershipAccessAction() { IConfig config = ConfigFactory.getInstance(); this.logger = LoggerFactory.getLoggerInstance(); if (!"Linux".equals(System.getProperty("os.name"))) { this.logger.error("The '" + this.getActionType() + "' class can only be used on Linux ('" + System.getProperty("os.name") + "' detected)."); throw new IllegalStateException(this.getActionType() + " only works on Linux."); } this.devices = new ArrayList<String>(); + this.pb = new ProcessBuilder(); String hostAddress; - if ((hostAddress = config.getProperty("Device_Ownership_Host_Address")) != null) + if ((hostAddress = config.getProperty("Device_Ownership_Host_Address")) != null && !"".equals(hostAddress)) { this.pb.command().add("ssh"); this.pb.command().add(hostAddress); this.logger.debug(this.getActionType() + ": Changing ownership of devices on " + hostAddress + '.'); } else { this.logger.debug(this.getActionType() + ": Changing ownership of local devices."); } this.pb.command().add("chown"); /* Load configuration for each node. */ int i = 1; String path; - while ((path = config.getProperty("Device_Ownership_Path_" + i)) != null) + while ((path = config.getProperty("Device_Ownership_Path_" + i)) != null && !"".equals(path)) { this.logger.info(this.getActionType() + ": Going to change ownership of device node with path " + path + "."); this.devices.add(path); i++; } } @Override public boolean assign(String name) { for (String device : this.devices) { this.logger.info(this.getActionType() + ": Changing ownership of device " + device + " to " + name + "."); if (!(setOwner(device, name))) { return false; } } return true; } @Override public boolean revoke(String name) { for (String device : this.devices) { this.logger.info(this.getActionType() + ": Changing ownership of device " + device + " to root."); if (!(setOwner(device, "root"))) { return false; } } return true; } @Override public String getActionType() { return "Unix Device Ownership Access"; } @Override public String getFailureReason() { return this.failureReason; } /** * Sets owner of specified device to specified user, using chown, and * optionally, ssh, commands. * @param device device to change owner of * @param owner the new owner for the device * @return true on success, false otherwise */ private boolean setOwner(String device, String owner) { boolean ret = true; try { this.pb.command().add(owner); this.pb.command().add(device); Process proc = this.pb.start(); int returnValue; if ((returnValue = proc.waitFor()) != 0) { this.logger.warn("Attempt to change owner of " + device + " to " + owner + " failed with return value " + returnValue + '.'); this.failureReason = "Device ownership could not be set."; ret = false; } } catch (Exception ex) { this.logger.warn("Attempt to change permissions of " + device + " to " + owner + " failed with exception " + ex.getClass().getName() + " and message " + ex.getMessage() + '.'); this.failureReason = "Device ownership could not be set."; ret = false; } finally { this.pb.command().remove(owner); this.pb.command().remove(device); } return ret; } }
false
true
public DeviceOwnershipAccessAction() { IConfig config = ConfigFactory.getInstance(); this.logger = LoggerFactory.getLoggerInstance(); if (!"Linux".equals(System.getProperty("os.name"))) { this.logger.error("The '" + this.getActionType() + "' class can only be used on Linux ('" + System.getProperty("os.name") + "' detected)."); throw new IllegalStateException(this.getActionType() + " only works on Linux."); } this.devices = new ArrayList<String>(); String hostAddress; if ((hostAddress = config.getProperty("Device_Ownership_Host_Address")) != null) { this.pb.command().add("ssh"); this.pb.command().add(hostAddress); this.logger.debug(this.getActionType() + ": Changing ownership of devices on " + hostAddress + '.'); } else { this.logger.debug(this.getActionType() + ": Changing ownership of local devices."); } this.pb.command().add("chown"); /* Load configuration for each node. */ int i = 1; String path; while ((path = config.getProperty("Device_Ownership_Path_" + i)) != null) { this.logger.info(this.getActionType() + ": Going to change ownership of device node with path " + path + "."); this.devices.add(path); i++; } }
public DeviceOwnershipAccessAction() { IConfig config = ConfigFactory.getInstance(); this.logger = LoggerFactory.getLoggerInstance(); if (!"Linux".equals(System.getProperty("os.name"))) { this.logger.error("The '" + this.getActionType() + "' class can only be used on Linux ('" + System.getProperty("os.name") + "' detected)."); throw new IllegalStateException(this.getActionType() + " only works on Linux."); } this.devices = new ArrayList<String>(); this.pb = new ProcessBuilder(); String hostAddress; if ((hostAddress = config.getProperty("Device_Ownership_Host_Address")) != null && !"".equals(hostAddress)) { this.pb.command().add("ssh"); this.pb.command().add(hostAddress); this.logger.debug(this.getActionType() + ": Changing ownership of devices on " + hostAddress + '.'); } else { this.logger.debug(this.getActionType() + ": Changing ownership of local devices."); } this.pb.command().add("chown"); /* Load configuration for each node. */ int i = 1; String path; while ((path = config.getProperty("Device_Ownership_Path_" + i)) != null && !"".equals(path)) { this.logger.info(this.getActionType() + ": Going to change ownership of device node with path " + path + "."); this.devices.add(path); i++; } }
diff --git a/src/Lihad/Conflict/Command/CommandHandler.java b/src/Lihad/Conflict/Command/CommandHandler.java index f62ad87..4a31f3f 100644 --- a/src/Lihad/Conflict/Command/CommandHandler.java +++ b/src/Lihad/Conflict/Command/CommandHandler.java @@ -1,337 +1,338 @@ package Lihad.Conflict.Command; import java.util.Arrays; import java.util.List; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.command.ConsoleCommandSender; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import Lihad.Conflict.Conflict; import Lihad.Conflict.City; import Lihad.Conflict.Util.BeyondUtil; import Lihad.Conflict.Information.BeyondInfo; public class CommandHandler implements CommandExecutor { public static Conflict plugin; public ItemStack post; public CommandHandler(Conflict instance) { plugin = instance; } @Override public boolean onCommand(CommandSender sender, Command cmd, String string, String[] arg) { // if (!(sender instanceof Player) { // // Console can't send Conflict commands. Sorry. // return false; // } - Player player = (Player)sender; + Player player = null; + if(sender instanceof Player)player = (Player)sender; if(cmd.getName().equalsIgnoreCase("point") && arg.length == 2 && arg[0].equalsIgnoreCase("set") && sender instanceof Player && (player).isOp()){ if(!Conflict.PLAYER_SET_SELECT.isEmpty() && Conflict.PLAYER_SET_SELECT.containsKey((player).getName())){ (player).sendMessage(ChatColor.LIGHT_PURPLE.toString()+"Selection turned off"); Conflict.PLAYER_SET_SELECT.remove((player).getName()); }else if(Conflict.getCity(arg[1]) != null || arg[1].equalsIgnoreCase("blacksmith") || arg[1].equalsIgnoreCase("potions") || arg[1].equalsIgnoreCase("enchantments") || arg[1].equalsIgnoreCase("richportal") || arg[1].equalsIgnoreCase("mystportal") || (arg[1].length() > 7 && arg[1].substring(0, 7).equalsIgnoreCase("drifter") && Conflict.getCity(arg[1].substring(7)) != null)){ (player).sendMessage(ChatColor.LIGHT_PURPLE.toString()+"Please select a position"); Conflict.PLAYER_SET_SELECT.put((player).getName(), arg[1]); } return true; }else if(cmd.getName().equalsIgnoreCase("cwho")){ if(arg.length == 1){ City city = Conflict.getCity(arg[1]); if (city != null) { List<Player> players = Arrays.asList(plugin.getServer().getOnlinePlayers()); String message = ""; for(int i = 0;i<players.size();i++){ if(city.hasPlayer(players.get(i).getName())) message = message.concat(players.get(i).getName() + " "); } (player).sendMessage(message); }else if(plugin.getServer().getPlayer(arg[0]) != null){ city = Conflict.getPlayerCity(arg[0]); if (city != null) player.sendMessage( arg[0] + " - " + city.getName()); else player.sendMessage( arg[0] + " - <None>"); }else (player).sendMessage("Player is not online"); }else (player).sendMessage("try '/cwho <playername>|<capname>"); return true; }else if(cmd.getName().equalsIgnoreCase("rarity") && arg.length == 0){ if(BeyondUtil.rarity((player).getItemInHand()) >= 60)(player).sendMessage("The Rarity Index of your "+ChatColor.BLUE.toString()+(player).getItemInHand().getType().name()+" is "+BeyondUtil.getColorOfRarity(BeyondUtil.rarity((player).getItemInHand()))+BeyondUtil.rarity((player).getItemInHand())); else (player).sendMessage("This item has no Rarity Index"); return true; }else if(cmd.getName().equalsIgnoreCase("myst") && arg.length == 3){ if((player).getWorld().getName().equals("mystworld")){ if(Integer.parseInt(arg[0]) < 100000 && Integer.parseInt(arg[0]) > -100000 && Integer.parseInt(arg[1]) < 255 && Integer.parseInt(arg[1]) > 0 && Integer.parseInt(arg[2]) < 100000 && Integer.parseInt(arg[2]) > -100000){ (player).teleport(new Location(plugin.getServer().getWorld("survival"),Integer.parseInt(arg[0]),Integer.parseInt(arg[1]),Integer.parseInt(arg[2]))); } }else (player).sendMessage("You are not in the correct world to use this command"); return true; }else if(cmd.getName().equalsIgnoreCase("protectcity") && arg.length == 1){ if(Integer.parseInt(arg[0]) <= 500 && Integer.parseInt(arg[0]) > -1){ City city = Conflict.getPlayerCity(player.getName()); if (city.getGenerals().contains(player.getName())) city.setProtectionRadius(Integer.parseInt(arg[0])); }else{ (player).sendMessage("Invalid number. 0-500"); } return true; }else if(cmd.getName().equalsIgnoreCase("cca") && ((sender instanceof Player && (player).isOp()) || sender instanceof ConsoleCommandSender)){ if(arg.length == 1 && arg[0].equalsIgnoreCase("count")){ sender.sendMessage("Count:"); for (int i=0; i<Conflict.cities.length; i++) { sender.sendMessage(Conflict.cities[i].getName() + " - " + Conflict.cities[i].getPopulation()); } }else if(arg.length == 1 && arg[0].equalsIgnoreCase("trade")){ for (int i=0; i<Conflict.cities.length; i++) { sender.sendMessage(Conflict.cities[i].getName() + " - " + Conflict.cities[i].getTrades()); } }else if(arg.length == 3 && arg[0].equalsIgnoreCase("cmove")){ String playerName = plugin.getFormattedPlayerName(arg[2]); if(playerName != null) { City city = Conflict.getCity(arg[1]); City oldCity = Conflict.getPlayerCity(playerName); if (city != null && oldCity != null && !city.equals(oldCity)) { oldCity.removePlayer(playerName); city.addPlayer(playerName); sender.sendMessage("Player " + playerName + " is now a member of " + city.getName()); }else{ sender.sendMessage("Invalid city. Try one of: " + Conflict.cities.toString()); } }else{ sender.sendMessage("Player has not logged in before. Please wait until they have at least played here."); } }else if(arg.length == 3 && arg[0].equalsIgnoreCase("gassign")){ String playerName = plugin.getFormattedPlayerName(arg[2]); if(playerName != null) { City city = Conflict.getCity(arg[1]); City oldCity = Conflict.getPlayerCity(playerName); if (city != null && oldCity != null && city.equals(oldCity)) { //player is a member of the town you are assigning them as general to city.getGenerals().add(playerName); Conflict.ex.getUser(playerName).setPrefix(ChatColor.WHITE.toString() + "[" + ChatColor.LIGHT_PURPLE.toString() + city.getName().substring(0, 2).toUpperCase() + "-General" + ChatColor.WHITE.toString() + "]", null); sender.sendMessage("Player " + playerName + " is now one of " + city.getName() + "'s Generals"); }else{ sender.sendMessage("Player " + playerName + " is not a member of " + arg[1]); } }else{ sender.sendMessage("Player has not logged in before. Please wait until they have at least played here."); } }else if(arg.length == 3 && arg[0].equalsIgnoreCase("gremove")){ String playerName = plugin.getFormattedPlayerName(arg[2]); if(playerName != null) { City city = Conflict.getCity(arg[1]); City oldCity = Conflict.getPlayerCity(playerName); if (city != null && oldCity != null && city.equals(oldCity)) { //player is a member of the town you are assigning them as general to if (city.getGenerals().contains(playerName)) { Conflict.ex.getUser(playerName).setPrefix("", null); sender.sendMessage("Player " + playerName + " is no longer one of " + city.getName() + "'s Generals"); } else { sender.sendMessage("Player " + playerName + " was already not a general for " + city.getName()); } }else{ sender.sendMessage("Player " + playerName + " is not a member of " + arg[1]); } }else{ sender.sendMessage("Player has not logged in before. Please wait until they have at least played here."); } }else if(arg.length == 1 && arg[0].equalsIgnoreCase("worth")){ sender.sendMessage("Worth:"); for (int i=0; i<Conflict.cities.length; i++) { sender.sendMessage(Conflict.cities[i].getName() + " - " + Conflict.cities[i].getMoney()); } }else if(arg.length == 4 && arg[0].equalsIgnoreCase("worth") && arg[1].equalsIgnoreCase("modify")){ City city = Conflict.getCity(arg[2]); if (city != null) { city.addMoney(Integer.parseInt(arg[3])); sender.sendMessage(city.getName() + " worth = " + city.getMoney()); }else{ sender.sendMessage("Invalid city. Try one of: " + Conflict.cities.toString()); } }else if(arg.length == 4 && arg[0].equalsIgnoreCase("worth") && arg[1].equalsIgnoreCase("set")){ City city = Conflict.getCity(arg[2]); if (city != null) { city.setMoney(Integer.parseInt(arg[3])); sender.sendMessage(city.getName() + " worth = " + city.getMoney()); }else{ sender.sendMessage("Invalid city. Try one of: " + Conflict.cities.toString()); } }else if(arg.length == 1 && arg[0].equalsIgnoreCase("generals")){ for (int i=0; i<Conflict.cities.length; i++) { sender.sendMessage(Conflict.cities[i].getName() + " - " + Conflict.cities[i].getGenerals()); } }else if(arg.length == 1 && arg[0].equalsIgnoreCase("save")){ Conflict.saveInfoFile(); }else if(arg.length == 1 && arg[0].equalsIgnoreCase("reload")){ Conflict.loadInfoFile(Conflict.information, Conflict.infoFile); BeyondInfo.loader(); } return true; }else if(cmd.getName().equalsIgnoreCase("cc") && arg.length == 0){ City city = Conflict.getPlayerCity(player.getName()); if (city != null) player.performCommand("ch " + city.getName()); return true; }else if(cmd.getName().equalsIgnoreCase("post") && arg.length == 0){ if(BeyondUtil.rarity((player).getItemInHand()) >= 60){ (player).chat(BeyondUtil.getColorOfRarity(BeyondUtil.rarity((player).getItemInHand()))+"["+(player).getItemInHand().getType().name()+"] Rarity Index : "+BeyondUtil.rarity((player).getItemInHand())); post = (player).getItemInHand(); } else (player).sendMessage("This item has no Rarity Index so it can't be posted to chat"); return true; } else if(cmd.getName().equalsIgnoreCase("look") && arg.length == 0){ if(post != null){ player.sendMessage(ChatColor.YELLOW.toString()+" -------------------------------- "); player.sendMessage(BeyondUtil.getColorOfRarity(BeyondUtil.rarity(post))+"["+post.getType().name()+"] Rarity Index : "+BeyondUtil.rarity(post)); for(int i = 0; i<post.getEnchantments().keySet().size(); i++){ player.sendMessage(" -- "+ChatColor.BLUE.toString()+((Enchantment)(post.getEnchantments().keySet().toArray()[i])).getName()+ChatColor.WHITE.toString()+" LVL"+BeyondUtil.getColorOfLevel(post.getEnchantmentLevel(((Enchantment)(post.getEnchantments().keySet().toArray()[i]))))+post.getEnchantmentLevel(((Enchantment)(post.getEnchantments().keySet().toArray()[i])))); } if(post.getEnchantments().keySet().size() <= 0)player.sendMessage(ChatColor.WHITE.toString()+" -- This Item Has No Enchants"); player.sendMessage(ChatColor.YELLOW.toString()+" -------------------------------- "); }else (player).sendMessage("There is no item to look at"); return true; } else if(cmd.getName().equalsIgnoreCase("gear") && arg.length == 0){ double total = (BeyondUtil.rarity((player).getInventory().getHelmet())+BeyondUtil.rarity((player).getInventory().getLeggings())+BeyondUtil.rarity((player).getInventory().getBoots())+BeyondUtil.rarity((player).getInventory().getChestplate())+BeyondUtil.rarity((player).getInventory().getItemInHand()))/5.00; (player).sendMessage(BeyondUtil.getColorOfRarity(total)+"Your Gear Rating is : "+total); return true; } else if(cmd.getName().equalsIgnoreCase("gear") && arg.length == 1){ if(plugin.getServer().getPlayer(arg[1]) != null){ Player target = plugin.getServer().getPlayer(arg[1]); org.bukkit.inventory.PlayerInventory inv = target.getInventory(); double total = (BeyondUtil.rarity(inv.getHelmet())+BeyondUtil.rarity(inv.getLeggings())+BeyondUtil.rarity(inv.getBoots())+BeyondUtil.rarity(inv.getChestplate())+BeyondUtil.rarity(inv.getItemInHand()))/5.00; player.sendMessage(target.getName()+" has a Gear Rating of "+BeyondUtil.getColorOfRarity(total)+total); }else player.sendMessage("This player either doesn't exist, or isn't online"); return true; }else if(Conflict.getCity(cmd.getName()) != null && arg.length == 0 && Conflict.UNASSIGNED_PLAYERS.contains((player).getName())){ City city = Conflict.getCity(cmd.getName()); int least = Integer.MAX_VALUE; for (int i=0; i<Conflict.cities.length; i++) { if (Conflict.cities[i].getPopulation() < least) least = Conflict.cities[i].getPopulation(); } if (least < (city.getPopulation() - 10)) (player).sendMessage(ChatColor.BLUE.toString() + city.getName() + " is over capacity! Try joining one of the others, or wait and try later."); else{ city.addPlayer(player.getName()); Conflict.UNASSIGNED_PLAYERS.remove(player.getName()); } return true; }else if(cmd.getName().equalsIgnoreCase("spawn") && arg.length == 0){ City city = Conflict.getPlayerCity(player.getName()); if (city != null && city.getSpawn() != null) player.teleport(city.getSpawn()); else player.teleport(player.getWorld().getSpawnLocation()); return true; }else if(cmd.getName().equalsIgnoreCase("nulls") && arg.length == 0 && (player).isOp()){ (player).teleport((player).getWorld().getSpawnLocation()); }else if(cmd.getName().equalsIgnoreCase("setcityspawn") && arg.length == 0){ City city = Conflict.getPlayerCity(player.getName()); if (city != null && city.getGenerals().contains(player.getName())) city.setSpawn(player.getLocation()); else player.sendMessage(ChatColor.LIGHT_PURPLE.toString()+"Unable to use this command"); return true; }else if(cmd.getName().equalsIgnoreCase("purchase") && arg.length == 0){ sender.sendMessage("Possible Perks: weapondrops, armordrops, potiondrops, tooldrops, bowdrops, shield, strike, endergrenade, enchantup, golddrops"); return true; }else if(cmd.getName().equalsIgnoreCase("purchase") && arg.length == 1){ City city = Conflict.getPlayerCity(player.getName()); if(city != null && city.getGenerals().contains(player.getName())){ if(city.getMoney() >= 500){ if(!city.getPerks().contains(arg[0].toLowerCase())){ if(arg[0].equalsIgnoreCase("weapondrops")){ city.addPerk("weapondrops"); city.subtractMoney(500); }else if(arg[0].equalsIgnoreCase("armordrops")){ city.addPerk("armordrops"); city.subtractMoney(500); }else if(arg[0].equalsIgnoreCase("potiondrops")){ city.addPerk("potiondrops"); city.subtractMoney(500); }else if(arg[0].equalsIgnoreCase("tooldrops")){ city.addPerk("tooldrops"); city.subtractMoney(500); }else if(arg[0].equalsIgnoreCase("bowdrops")){ city.addPerk("bowdrops"); city.subtractMoney(500); }else if(arg[0].equalsIgnoreCase("shield")){ city.addPerk("shield"); city.subtractMoney(500); }else if(arg[0].equalsIgnoreCase("strike")){ city.addPerk("strike"); city.subtractMoney(500); }else if(arg[0].equalsIgnoreCase("endergrenade")){ city.addPerk("endergrenade"); city.subtractMoney(500); }else if(arg[0].equalsIgnoreCase("enchantup")){ city.addPerk("enchantup"); city.subtractMoney(500); }else if(arg[0].equalsIgnoreCase("golddrops")){ city.addPerk("golddrops"); city.subtractMoney(500); }else (player).sendMessage("Invalid perk"); }else (player).sendMessage(city.getName() + " currently owns perk: " + arg[0]); }else (player).sendMessage(city.getName() + " does not have enough gold to purchase the ability"); }else player.sendMessage(ChatColor.LIGHT_PURPLE.toString()+"Unable to use this command"); return true; } else if(cmd.getName().equalsIgnoreCase("warstats") && arg.length == 0){ if (Conflict.war != null) { Conflict.war.postWarAutoList(sender); } return true; } else if(cmd.getName().equalsIgnoreCase("perks")) { City city = null; if (arg.length == 0 && sender instanceof Player) { city = Conflict.getPlayerCity((player).getName()); } if (arg.length == 1 && (player).isOp()) { for (City c : Conflict.cities) { if (c.getName().equals(arg[0])) { city = c; break; } } } if (city == null) { return false; } sender.sendMessage("" + city + " mini-perks: " + city.getPerks().toString()); // TODO: Give nodes in this message as well. sender.sendMessage("" + city + " nodes: " + city.getTrades().toString()); return true; } else if(cmd.getName().equalsIgnoreCase("bnn") && Conflict.war != null && arg.length == 2 && arg[0].equalsIgnoreCase("reporter") && arg[1].equalsIgnoreCase("enable") && (sender instanceof Player)) { Conflict.war.reporters.add(player); } return false; } }
true
true
public boolean onCommand(CommandSender sender, Command cmd, String string, String[] arg) { // if (!(sender instanceof Player) { // // Console can't send Conflict commands. Sorry. // return false; // } Player player = (Player)sender; if(cmd.getName().equalsIgnoreCase("point") && arg.length == 2 && arg[0].equalsIgnoreCase("set") && sender instanceof Player && (player).isOp()){ if(!Conflict.PLAYER_SET_SELECT.isEmpty() && Conflict.PLAYER_SET_SELECT.containsKey((player).getName())){ (player).sendMessage(ChatColor.LIGHT_PURPLE.toString()+"Selection turned off"); Conflict.PLAYER_SET_SELECT.remove((player).getName()); }else if(Conflict.getCity(arg[1]) != null || arg[1].equalsIgnoreCase("blacksmith") || arg[1].equalsIgnoreCase("potions") || arg[1].equalsIgnoreCase("enchantments") || arg[1].equalsIgnoreCase("richportal") || arg[1].equalsIgnoreCase("mystportal") || (arg[1].length() > 7 && arg[1].substring(0, 7).equalsIgnoreCase("drifter") && Conflict.getCity(arg[1].substring(7)) != null)){ (player).sendMessage(ChatColor.LIGHT_PURPLE.toString()+"Please select a position"); Conflict.PLAYER_SET_SELECT.put((player).getName(), arg[1]); } return true; }else if(cmd.getName().equalsIgnoreCase("cwho")){ if(arg.length == 1){ City city = Conflict.getCity(arg[1]); if (city != null) { List<Player> players = Arrays.asList(plugin.getServer().getOnlinePlayers()); String message = ""; for(int i = 0;i<players.size();i++){ if(city.hasPlayer(players.get(i).getName())) message = message.concat(players.get(i).getName() + " "); } (player).sendMessage(message); }else if(plugin.getServer().getPlayer(arg[0]) != null){ city = Conflict.getPlayerCity(arg[0]); if (city != null) player.sendMessage( arg[0] + " - " + city.getName()); else player.sendMessage( arg[0] + " - <None>"); }else (player).sendMessage("Player is not online"); }else (player).sendMessage("try '/cwho <playername>|<capname>"); return true; }else if(cmd.getName().equalsIgnoreCase("rarity") && arg.length == 0){ if(BeyondUtil.rarity((player).getItemInHand()) >= 60)(player).sendMessage("The Rarity Index of your "+ChatColor.BLUE.toString()+(player).getItemInHand().getType().name()+" is "+BeyondUtil.getColorOfRarity(BeyondUtil.rarity((player).getItemInHand()))+BeyondUtil.rarity((player).getItemInHand())); else (player).sendMessage("This item has no Rarity Index"); return true; }else if(cmd.getName().equalsIgnoreCase("myst") && arg.length == 3){ if((player).getWorld().getName().equals("mystworld")){ if(Integer.parseInt(arg[0]) < 100000 && Integer.parseInt(arg[0]) > -100000 && Integer.parseInt(arg[1]) < 255 && Integer.parseInt(arg[1]) > 0 && Integer.parseInt(arg[2]) < 100000 && Integer.parseInt(arg[2]) > -100000){ (player).teleport(new Location(plugin.getServer().getWorld("survival"),Integer.parseInt(arg[0]),Integer.parseInt(arg[1]),Integer.parseInt(arg[2]))); } }else (player).sendMessage("You are not in the correct world to use this command"); return true; }else if(cmd.getName().equalsIgnoreCase("protectcity") && arg.length == 1){ if(Integer.parseInt(arg[0]) <= 500 && Integer.parseInt(arg[0]) > -1){ City city = Conflict.getPlayerCity(player.getName()); if (city.getGenerals().contains(player.getName())) city.setProtectionRadius(Integer.parseInt(arg[0])); }else{ (player).sendMessage("Invalid number. 0-500"); } return true; }else if(cmd.getName().equalsIgnoreCase("cca") && ((sender instanceof Player && (player).isOp()) || sender instanceof ConsoleCommandSender)){ if(arg.length == 1 && arg[0].equalsIgnoreCase("count")){ sender.sendMessage("Count:"); for (int i=0; i<Conflict.cities.length; i++) { sender.sendMessage(Conflict.cities[i].getName() + " - " + Conflict.cities[i].getPopulation()); } }else if(arg.length == 1 && arg[0].equalsIgnoreCase("trade")){ for (int i=0; i<Conflict.cities.length; i++) { sender.sendMessage(Conflict.cities[i].getName() + " - " + Conflict.cities[i].getTrades()); } }else if(arg.length == 3 && arg[0].equalsIgnoreCase("cmove")){ String playerName = plugin.getFormattedPlayerName(arg[2]); if(playerName != null) { City city = Conflict.getCity(arg[1]); City oldCity = Conflict.getPlayerCity(playerName); if (city != null && oldCity != null && !city.equals(oldCity)) { oldCity.removePlayer(playerName); city.addPlayer(playerName); sender.sendMessage("Player " + playerName + " is now a member of " + city.getName()); }else{ sender.sendMessage("Invalid city. Try one of: " + Conflict.cities.toString()); } }else{ sender.sendMessage("Player has not logged in before. Please wait until they have at least played here."); } }else if(arg.length == 3 && arg[0].equalsIgnoreCase("gassign")){ String playerName = plugin.getFormattedPlayerName(arg[2]); if(playerName != null) { City city = Conflict.getCity(arg[1]); City oldCity = Conflict.getPlayerCity(playerName); if (city != null && oldCity != null && city.equals(oldCity)) { //player is a member of the town you are assigning them as general to city.getGenerals().add(playerName); Conflict.ex.getUser(playerName).setPrefix(ChatColor.WHITE.toString() + "[" + ChatColor.LIGHT_PURPLE.toString() + city.getName().substring(0, 2).toUpperCase() + "-General" + ChatColor.WHITE.toString() + "]", null); sender.sendMessage("Player " + playerName + " is now one of " + city.getName() + "'s Generals"); }else{ sender.sendMessage("Player " + playerName + " is not a member of " + arg[1]); } }else{ sender.sendMessage("Player has not logged in before. Please wait until they have at least played here."); } }else if(arg.length == 3 && arg[0].equalsIgnoreCase("gremove")){ String playerName = plugin.getFormattedPlayerName(arg[2]); if(playerName != null) { City city = Conflict.getCity(arg[1]); City oldCity = Conflict.getPlayerCity(playerName); if (city != null && oldCity != null && city.equals(oldCity)) { //player is a member of the town you are assigning them as general to if (city.getGenerals().contains(playerName)) { Conflict.ex.getUser(playerName).setPrefix("", null); sender.sendMessage("Player " + playerName + " is no longer one of " + city.getName() + "'s Generals"); } else { sender.sendMessage("Player " + playerName + " was already not a general for " + city.getName()); } }else{ sender.sendMessage("Player " + playerName + " is not a member of " + arg[1]); } }else{ sender.sendMessage("Player has not logged in before. Please wait until they have at least played here."); } }else if(arg.length == 1 && arg[0].equalsIgnoreCase("worth")){ sender.sendMessage("Worth:"); for (int i=0; i<Conflict.cities.length; i++) { sender.sendMessage(Conflict.cities[i].getName() + " - " + Conflict.cities[i].getMoney()); } }else if(arg.length == 4 && arg[0].equalsIgnoreCase("worth") && arg[1].equalsIgnoreCase("modify")){ City city = Conflict.getCity(arg[2]); if (city != null) { city.addMoney(Integer.parseInt(arg[3])); sender.sendMessage(city.getName() + " worth = " + city.getMoney()); }else{ sender.sendMessage("Invalid city. Try one of: " + Conflict.cities.toString()); } }else if(arg.length == 4 && arg[0].equalsIgnoreCase("worth") && arg[1].equalsIgnoreCase("set")){ City city = Conflict.getCity(arg[2]); if (city != null) { city.setMoney(Integer.parseInt(arg[3])); sender.sendMessage(city.getName() + " worth = " + city.getMoney()); }else{ sender.sendMessage("Invalid city. Try one of: " + Conflict.cities.toString()); } }else if(arg.length == 1 && arg[0].equalsIgnoreCase("generals")){ for (int i=0; i<Conflict.cities.length; i++) { sender.sendMessage(Conflict.cities[i].getName() + " - " + Conflict.cities[i].getGenerals()); } }else if(arg.length == 1 && arg[0].equalsIgnoreCase("save")){ Conflict.saveInfoFile(); }else if(arg.length == 1 && arg[0].equalsIgnoreCase("reload")){ Conflict.loadInfoFile(Conflict.information, Conflict.infoFile); BeyondInfo.loader(); } return true; }else if(cmd.getName().equalsIgnoreCase("cc") && arg.length == 0){ City city = Conflict.getPlayerCity(player.getName()); if (city != null) player.performCommand("ch " + city.getName()); return true; }else if(cmd.getName().equalsIgnoreCase("post") && arg.length == 0){ if(BeyondUtil.rarity((player).getItemInHand()) >= 60){ (player).chat(BeyondUtil.getColorOfRarity(BeyondUtil.rarity((player).getItemInHand()))+"["+(player).getItemInHand().getType().name()+"] Rarity Index : "+BeyondUtil.rarity((player).getItemInHand())); post = (player).getItemInHand(); } else (player).sendMessage("This item has no Rarity Index so it can't be posted to chat"); return true; } else if(cmd.getName().equalsIgnoreCase("look") && arg.length == 0){ if(post != null){ player.sendMessage(ChatColor.YELLOW.toString()+" -------------------------------- "); player.sendMessage(BeyondUtil.getColorOfRarity(BeyondUtil.rarity(post))+"["+post.getType().name()+"] Rarity Index : "+BeyondUtil.rarity(post)); for(int i = 0; i<post.getEnchantments().keySet().size(); i++){ player.sendMessage(" -- "+ChatColor.BLUE.toString()+((Enchantment)(post.getEnchantments().keySet().toArray()[i])).getName()+ChatColor.WHITE.toString()+" LVL"+BeyondUtil.getColorOfLevel(post.getEnchantmentLevel(((Enchantment)(post.getEnchantments().keySet().toArray()[i]))))+post.getEnchantmentLevel(((Enchantment)(post.getEnchantments().keySet().toArray()[i])))); } if(post.getEnchantments().keySet().size() <= 0)player.sendMessage(ChatColor.WHITE.toString()+" -- This Item Has No Enchants"); player.sendMessage(ChatColor.YELLOW.toString()+" -------------------------------- "); }else (player).sendMessage("There is no item to look at"); return true; } else if(cmd.getName().equalsIgnoreCase("gear") && arg.length == 0){ double total = (BeyondUtil.rarity((player).getInventory().getHelmet())+BeyondUtil.rarity((player).getInventory().getLeggings())+BeyondUtil.rarity((player).getInventory().getBoots())+BeyondUtil.rarity((player).getInventory().getChestplate())+BeyondUtil.rarity((player).getInventory().getItemInHand()))/5.00; (player).sendMessage(BeyondUtil.getColorOfRarity(total)+"Your Gear Rating is : "+total); return true; } else if(cmd.getName().equalsIgnoreCase("gear") && arg.length == 1){ if(plugin.getServer().getPlayer(arg[1]) != null){ Player target = plugin.getServer().getPlayer(arg[1]); org.bukkit.inventory.PlayerInventory inv = target.getInventory(); double total = (BeyondUtil.rarity(inv.getHelmet())+BeyondUtil.rarity(inv.getLeggings())+BeyondUtil.rarity(inv.getBoots())+BeyondUtil.rarity(inv.getChestplate())+BeyondUtil.rarity(inv.getItemInHand()))/5.00; player.sendMessage(target.getName()+" has a Gear Rating of "+BeyondUtil.getColorOfRarity(total)+total); }else player.sendMessage("This player either doesn't exist, or isn't online"); return true; }else if(Conflict.getCity(cmd.getName()) != null && arg.length == 0 && Conflict.UNASSIGNED_PLAYERS.contains((player).getName())){ City city = Conflict.getCity(cmd.getName()); int least = Integer.MAX_VALUE; for (int i=0; i<Conflict.cities.length; i++) { if (Conflict.cities[i].getPopulation() < least) least = Conflict.cities[i].getPopulation(); } if (least < (city.getPopulation() - 10)) (player).sendMessage(ChatColor.BLUE.toString() + city.getName() + " is over capacity! Try joining one of the others, or wait and try later."); else{ city.addPlayer(player.getName()); Conflict.UNASSIGNED_PLAYERS.remove(player.getName()); } return true; }else if(cmd.getName().equalsIgnoreCase("spawn") && arg.length == 0){ City city = Conflict.getPlayerCity(player.getName()); if (city != null && city.getSpawn() != null) player.teleport(city.getSpawn()); else player.teleport(player.getWorld().getSpawnLocation()); return true; }else if(cmd.getName().equalsIgnoreCase("nulls") && arg.length == 0 && (player).isOp()){ (player).teleport((player).getWorld().getSpawnLocation()); }else if(cmd.getName().equalsIgnoreCase("setcityspawn") && arg.length == 0){ City city = Conflict.getPlayerCity(player.getName()); if (city != null && city.getGenerals().contains(player.getName())) city.setSpawn(player.getLocation()); else player.sendMessage(ChatColor.LIGHT_PURPLE.toString()+"Unable to use this command"); return true; }else if(cmd.getName().equalsIgnoreCase("purchase") && arg.length == 0){ sender.sendMessage("Possible Perks: weapondrops, armordrops, potiondrops, tooldrops, bowdrops, shield, strike, endergrenade, enchantup, golddrops"); return true; }else if(cmd.getName().equalsIgnoreCase("purchase") && arg.length == 1){ City city = Conflict.getPlayerCity(player.getName()); if(city != null && city.getGenerals().contains(player.getName())){ if(city.getMoney() >= 500){ if(!city.getPerks().contains(arg[0].toLowerCase())){ if(arg[0].equalsIgnoreCase("weapondrops")){ city.addPerk("weapondrops"); city.subtractMoney(500); }else if(arg[0].equalsIgnoreCase("armordrops")){ city.addPerk("armordrops"); city.subtractMoney(500); }else if(arg[0].equalsIgnoreCase("potiondrops")){ city.addPerk("potiondrops"); city.subtractMoney(500); }else if(arg[0].equalsIgnoreCase("tooldrops")){ city.addPerk("tooldrops"); city.subtractMoney(500); }else if(arg[0].equalsIgnoreCase("bowdrops")){ city.addPerk("bowdrops"); city.subtractMoney(500); }else if(arg[0].equalsIgnoreCase("shield")){ city.addPerk("shield"); city.subtractMoney(500); }else if(arg[0].equalsIgnoreCase("strike")){ city.addPerk("strike"); city.subtractMoney(500); }else if(arg[0].equalsIgnoreCase("endergrenade")){ city.addPerk("endergrenade"); city.subtractMoney(500); }else if(arg[0].equalsIgnoreCase("enchantup")){ city.addPerk("enchantup"); city.subtractMoney(500); }else if(arg[0].equalsIgnoreCase("golddrops")){ city.addPerk("golddrops"); city.subtractMoney(500); }else (player).sendMessage("Invalid perk"); }else (player).sendMessage(city.getName() + " currently owns perk: " + arg[0]); }else (player).sendMessage(city.getName() + " does not have enough gold to purchase the ability"); }else player.sendMessage(ChatColor.LIGHT_PURPLE.toString()+"Unable to use this command"); return true; } else if(cmd.getName().equalsIgnoreCase("warstats") && arg.length == 0){ if (Conflict.war != null) { Conflict.war.postWarAutoList(sender); } return true; } else if(cmd.getName().equalsIgnoreCase("perks")) { City city = null; if (arg.length == 0 && sender instanceof Player) { city = Conflict.getPlayerCity((player).getName()); } if (arg.length == 1 && (player).isOp()) { for (City c : Conflict.cities) { if (c.getName().equals(arg[0])) { city = c; break; } } } if (city == null) { return false; } sender.sendMessage("" + city + " mini-perks: " + city.getPerks().toString()); // TODO: Give nodes in this message as well. sender.sendMessage("" + city + " nodes: " + city.getTrades().toString()); return true; } else if(cmd.getName().equalsIgnoreCase("bnn") && Conflict.war != null && arg.length == 2 && arg[0].equalsIgnoreCase("reporter") && arg[1].equalsIgnoreCase("enable") && (sender instanceof Player)) { Conflict.war.reporters.add(player); } return false; }
public boolean onCommand(CommandSender sender, Command cmd, String string, String[] arg) { // if (!(sender instanceof Player) { // // Console can't send Conflict commands. Sorry. // return false; // } Player player = null; if(sender instanceof Player)player = (Player)sender; if(cmd.getName().equalsIgnoreCase("point") && arg.length == 2 && arg[0].equalsIgnoreCase("set") && sender instanceof Player && (player).isOp()){ if(!Conflict.PLAYER_SET_SELECT.isEmpty() && Conflict.PLAYER_SET_SELECT.containsKey((player).getName())){ (player).sendMessage(ChatColor.LIGHT_PURPLE.toString()+"Selection turned off"); Conflict.PLAYER_SET_SELECT.remove((player).getName()); }else if(Conflict.getCity(arg[1]) != null || arg[1].equalsIgnoreCase("blacksmith") || arg[1].equalsIgnoreCase("potions") || arg[1].equalsIgnoreCase("enchantments") || arg[1].equalsIgnoreCase("richportal") || arg[1].equalsIgnoreCase("mystportal") || (arg[1].length() > 7 && arg[1].substring(0, 7).equalsIgnoreCase("drifter") && Conflict.getCity(arg[1].substring(7)) != null)){ (player).sendMessage(ChatColor.LIGHT_PURPLE.toString()+"Please select a position"); Conflict.PLAYER_SET_SELECT.put((player).getName(), arg[1]); } return true; }else if(cmd.getName().equalsIgnoreCase("cwho")){ if(arg.length == 1){ City city = Conflict.getCity(arg[1]); if (city != null) { List<Player> players = Arrays.asList(plugin.getServer().getOnlinePlayers()); String message = ""; for(int i = 0;i<players.size();i++){ if(city.hasPlayer(players.get(i).getName())) message = message.concat(players.get(i).getName() + " "); } (player).sendMessage(message); }else if(plugin.getServer().getPlayer(arg[0]) != null){ city = Conflict.getPlayerCity(arg[0]); if (city != null) player.sendMessage( arg[0] + " - " + city.getName()); else player.sendMessage( arg[0] + " - <None>"); }else (player).sendMessage("Player is not online"); }else (player).sendMessage("try '/cwho <playername>|<capname>"); return true; }else if(cmd.getName().equalsIgnoreCase("rarity") && arg.length == 0){ if(BeyondUtil.rarity((player).getItemInHand()) >= 60)(player).sendMessage("The Rarity Index of your "+ChatColor.BLUE.toString()+(player).getItemInHand().getType().name()+" is "+BeyondUtil.getColorOfRarity(BeyondUtil.rarity((player).getItemInHand()))+BeyondUtil.rarity((player).getItemInHand())); else (player).sendMessage("This item has no Rarity Index"); return true; }else if(cmd.getName().equalsIgnoreCase("myst") && arg.length == 3){ if((player).getWorld().getName().equals("mystworld")){ if(Integer.parseInt(arg[0]) < 100000 && Integer.parseInt(arg[0]) > -100000 && Integer.parseInt(arg[1]) < 255 && Integer.parseInt(arg[1]) > 0 && Integer.parseInt(arg[2]) < 100000 && Integer.parseInt(arg[2]) > -100000){ (player).teleport(new Location(plugin.getServer().getWorld("survival"),Integer.parseInt(arg[0]),Integer.parseInt(arg[1]),Integer.parseInt(arg[2]))); } }else (player).sendMessage("You are not in the correct world to use this command"); return true; }else if(cmd.getName().equalsIgnoreCase("protectcity") && arg.length == 1){ if(Integer.parseInt(arg[0]) <= 500 && Integer.parseInt(arg[0]) > -1){ City city = Conflict.getPlayerCity(player.getName()); if (city.getGenerals().contains(player.getName())) city.setProtectionRadius(Integer.parseInt(arg[0])); }else{ (player).sendMessage("Invalid number. 0-500"); } return true; }else if(cmd.getName().equalsIgnoreCase("cca") && ((sender instanceof Player && (player).isOp()) || sender instanceof ConsoleCommandSender)){ if(arg.length == 1 && arg[0].equalsIgnoreCase("count")){ sender.sendMessage("Count:"); for (int i=0; i<Conflict.cities.length; i++) { sender.sendMessage(Conflict.cities[i].getName() + " - " + Conflict.cities[i].getPopulation()); } }else if(arg.length == 1 && arg[0].equalsIgnoreCase("trade")){ for (int i=0; i<Conflict.cities.length; i++) { sender.sendMessage(Conflict.cities[i].getName() + " - " + Conflict.cities[i].getTrades()); } }else if(arg.length == 3 && arg[0].equalsIgnoreCase("cmove")){ String playerName = plugin.getFormattedPlayerName(arg[2]); if(playerName != null) { City city = Conflict.getCity(arg[1]); City oldCity = Conflict.getPlayerCity(playerName); if (city != null && oldCity != null && !city.equals(oldCity)) { oldCity.removePlayer(playerName); city.addPlayer(playerName); sender.sendMessage("Player " + playerName + " is now a member of " + city.getName()); }else{ sender.sendMessage("Invalid city. Try one of: " + Conflict.cities.toString()); } }else{ sender.sendMessage("Player has not logged in before. Please wait until they have at least played here."); } }else if(arg.length == 3 && arg[0].equalsIgnoreCase("gassign")){ String playerName = plugin.getFormattedPlayerName(arg[2]); if(playerName != null) { City city = Conflict.getCity(arg[1]); City oldCity = Conflict.getPlayerCity(playerName); if (city != null && oldCity != null && city.equals(oldCity)) { //player is a member of the town you are assigning them as general to city.getGenerals().add(playerName); Conflict.ex.getUser(playerName).setPrefix(ChatColor.WHITE.toString() + "[" + ChatColor.LIGHT_PURPLE.toString() + city.getName().substring(0, 2).toUpperCase() + "-General" + ChatColor.WHITE.toString() + "]", null); sender.sendMessage("Player " + playerName + " is now one of " + city.getName() + "'s Generals"); }else{ sender.sendMessage("Player " + playerName + " is not a member of " + arg[1]); } }else{ sender.sendMessage("Player has not logged in before. Please wait until they have at least played here."); } }else if(arg.length == 3 && arg[0].equalsIgnoreCase("gremove")){ String playerName = plugin.getFormattedPlayerName(arg[2]); if(playerName != null) { City city = Conflict.getCity(arg[1]); City oldCity = Conflict.getPlayerCity(playerName); if (city != null && oldCity != null && city.equals(oldCity)) { //player is a member of the town you are assigning them as general to if (city.getGenerals().contains(playerName)) { Conflict.ex.getUser(playerName).setPrefix("", null); sender.sendMessage("Player " + playerName + " is no longer one of " + city.getName() + "'s Generals"); } else { sender.sendMessage("Player " + playerName + " was already not a general for " + city.getName()); } }else{ sender.sendMessage("Player " + playerName + " is not a member of " + arg[1]); } }else{ sender.sendMessage("Player has not logged in before. Please wait until they have at least played here."); } }else if(arg.length == 1 && arg[0].equalsIgnoreCase("worth")){ sender.sendMessage("Worth:"); for (int i=0; i<Conflict.cities.length; i++) { sender.sendMessage(Conflict.cities[i].getName() + " - " + Conflict.cities[i].getMoney()); } }else if(arg.length == 4 && arg[0].equalsIgnoreCase("worth") && arg[1].equalsIgnoreCase("modify")){ City city = Conflict.getCity(arg[2]); if (city != null) { city.addMoney(Integer.parseInt(arg[3])); sender.sendMessage(city.getName() + " worth = " + city.getMoney()); }else{ sender.sendMessage("Invalid city. Try one of: " + Conflict.cities.toString()); } }else if(arg.length == 4 && arg[0].equalsIgnoreCase("worth") && arg[1].equalsIgnoreCase("set")){ City city = Conflict.getCity(arg[2]); if (city != null) { city.setMoney(Integer.parseInt(arg[3])); sender.sendMessage(city.getName() + " worth = " + city.getMoney()); }else{ sender.sendMessage("Invalid city. Try one of: " + Conflict.cities.toString()); } }else if(arg.length == 1 && arg[0].equalsIgnoreCase("generals")){ for (int i=0; i<Conflict.cities.length; i++) { sender.sendMessage(Conflict.cities[i].getName() + " - " + Conflict.cities[i].getGenerals()); } }else if(arg.length == 1 && arg[0].equalsIgnoreCase("save")){ Conflict.saveInfoFile(); }else if(arg.length == 1 && arg[0].equalsIgnoreCase("reload")){ Conflict.loadInfoFile(Conflict.information, Conflict.infoFile); BeyondInfo.loader(); } return true; }else if(cmd.getName().equalsIgnoreCase("cc") && arg.length == 0){ City city = Conflict.getPlayerCity(player.getName()); if (city != null) player.performCommand("ch " + city.getName()); return true; }else if(cmd.getName().equalsIgnoreCase("post") && arg.length == 0){ if(BeyondUtil.rarity((player).getItemInHand()) >= 60){ (player).chat(BeyondUtil.getColorOfRarity(BeyondUtil.rarity((player).getItemInHand()))+"["+(player).getItemInHand().getType().name()+"] Rarity Index : "+BeyondUtil.rarity((player).getItemInHand())); post = (player).getItemInHand(); } else (player).sendMessage("This item has no Rarity Index so it can't be posted to chat"); return true; } else if(cmd.getName().equalsIgnoreCase("look") && arg.length == 0){ if(post != null){ player.sendMessage(ChatColor.YELLOW.toString()+" -------------------------------- "); player.sendMessage(BeyondUtil.getColorOfRarity(BeyondUtil.rarity(post))+"["+post.getType().name()+"] Rarity Index : "+BeyondUtil.rarity(post)); for(int i = 0; i<post.getEnchantments().keySet().size(); i++){ player.sendMessage(" -- "+ChatColor.BLUE.toString()+((Enchantment)(post.getEnchantments().keySet().toArray()[i])).getName()+ChatColor.WHITE.toString()+" LVL"+BeyondUtil.getColorOfLevel(post.getEnchantmentLevel(((Enchantment)(post.getEnchantments().keySet().toArray()[i]))))+post.getEnchantmentLevel(((Enchantment)(post.getEnchantments().keySet().toArray()[i])))); } if(post.getEnchantments().keySet().size() <= 0)player.sendMessage(ChatColor.WHITE.toString()+" -- This Item Has No Enchants"); player.sendMessage(ChatColor.YELLOW.toString()+" -------------------------------- "); }else (player).sendMessage("There is no item to look at"); return true; } else if(cmd.getName().equalsIgnoreCase("gear") && arg.length == 0){ double total = (BeyondUtil.rarity((player).getInventory().getHelmet())+BeyondUtil.rarity((player).getInventory().getLeggings())+BeyondUtil.rarity((player).getInventory().getBoots())+BeyondUtil.rarity((player).getInventory().getChestplate())+BeyondUtil.rarity((player).getInventory().getItemInHand()))/5.00; (player).sendMessage(BeyondUtil.getColorOfRarity(total)+"Your Gear Rating is : "+total); return true; } else if(cmd.getName().equalsIgnoreCase("gear") && arg.length == 1){ if(plugin.getServer().getPlayer(arg[1]) != null){ Player target = plugin.getServer().getPlayer(arg[1]); org.bukkit.inventory.PlayerInventory inv = target.getInventory(); double total = (BeyondUtil.rarity(inv.getHelmet())+BeyondUtil.rarity(inv.getLeggings())+BeyondUtil.rarity(inv.getBoots())+BeyondUtil.rarity(inv.getChestplate())+BeyondUtil.rarity(inv.getItemInHand()))/5.00; player.sendMessage(target.getName()+" has a Gear Rating of "+BeyondUtil.getColorOfRarity(total)+total); }else player.sendMessage("This player either doesn't exist, or isn't online"); return true; }else if(Conflict.getCity(cmd.getName()) != null && arg.length == 0 && Conflict.UNASSIGNED_PLAYERS.contains((player).getName())){ City city = Conflict.getCity(cmd.getName()); int least = Integer.MAX_VALUE; for (int i=0; i<Conflict.cities.length; i++) { if (Conflict.cities[i].getPopulation() < least) least = Conflict.cities[i].getPopulation(); } if (least < (city.getPopulation() - 10)) (player).sendMessage(ChatColor.BLUE.toString() + city.getName() + " is over capacity! Try joining one of the others, or wait and try later."); else{ city.addPlayer(player.getName()); Conflict.UNASSIGNED_PLAYERS.remove(player.getName()); } return true; }else if(cmd.getName().equalsIgnoreCase("spawn") && arg.length == 0){ City city = Conflict.getPlayerCity(player.getName()); if (city != null && city.getSpawn() != null) player.teleport(city.getSpawn()); else player.teleport(player.getWorld().getSpawnLocation()); return true; }else if(cmd.getName().equalsIgnoreCase("nulls") && arg.length == 0 && (player).isOp()){ (player).teleport((player).getWorld().getSpawnLocation()); }else if(cmd.getName().equalsIgnoreCase("setcityspawn") && arg.length == 0){ City city = Conflict.getPlayerCity(player.getName()); if (city != null && city.getGenerals().contains(player.getName())) city.setSpawn(player.getLocation()); else player.sendMessage(ChatColor.LIGHT_PURPLE.toString()+"Unable to use this command"); return true; }else if(cmd.getName().equalsIgnoreCase("purchase") && arg.length == 0){ sender.sendMessage("Possible Perks: weapondrops, armordrops, potiondrops, tooldrops, bowdrops, shield, strike, endergrenade, enchantup, golddrops"); return true; }else if(cmd.getName().equalsIgnoreCase("purchase") && arg.length == 1){ City city = Conflict.getPlayerCity(player.getName()); if(city != null && city.getGenerals().contains(player.getName())){ if(city.getMoney() >= 500){ if(!city.getPerks().contains(arg[0].toLowerCase())){ if(arg[0].equalsIgnoreCase("weapondrops")){ city.addPerk("weapondrops"); city.subtractMoney(500); }else if(arg[0].equalsIgnoreCase("armordrops")){ city.addPerk("armordrops"); city.subtractMoney(500); }else if(arg[0].equalsIgnoreCase("potiondrops")){ city.addPerk("potiondrops"); city.subtractMoney(500); }else if(arg[0].equalsIgnoreCase("tooldrops")){ city.addPerk("tooldrops"); city.subtractMoney(500); }else if(arg[0].equalsIgnoreCase("bowdrops")){ city.addPerk("bowdrops"); city.subtractMoney(500); }else if(arg[0].equalsIgnoreCase("shield")){ city.addPerk("shield"); city.subtractMoney(500); }else if(arg[0].equalsIgnoreCase("strike")){ city.addPerk("strike"); city.subtractMoney(500); }else if(arg[0].equalsIgnoreCase("endergrenade")){ city.addPerk("endergrenade"); city.subtractMoney(500); }else if(arg[0].equalsIgnoreCase("enchantup")){ city.addPerk("enchantup"); city.subtractMoney(500); }else if(arg[0].equalsIgnoreCase("golddrops")){ city.addPerk("golddrops"); city.subtractMoney(500); }else (player).sendMessage("Invalid perk"); }else (player).sendMessage(city.getName() + " currently owns perk: " + arg[0]); }else (player).sendMessage(city.getName() + " does not have enough gold to purchase the ability"); }else player.sendMessage(ChatColor.LIGHT_PURPLE.toString()+"Unable to use this command"); return true; } else if(cmd.getName().equalsIgnoreCase("warstats") && arg.length == 0){ if (Conflict.war != null) { Conflict.war.postWarAutoList(sender); } return true; } else if(cmd.getName().equalsIgnoreCase("perks")) { City city = null; if (arg.length == 0 && sender instanceof Player) { city = Conflict.getPlayerCity((player).getName()); } if (arg.length == 1 && (player).isOp()) { for (City c : Conflict.cities) { if (c.getName().equals(arg[0])) { city = c; break; } } } if (city == null) { return false; } sender.sendMessage("" + city + " mini-perks: " + city.getPerks().toString()); // TODO: Give nodes in this message as well. sender.sendMessage("" + city + " nodes: " + city.getTrades().toString()); return true; } else if(cmd.getName().equalsIgnoreCase("bnn") && Conflict.war != null && arg.length == 2 && arg[0].equalsIgnoreCase("reporter") && arg[1].equalsIgnoreCase("enable") && (sender instanceof Player)) { Conflict.war.reporters.add(player); } return false; }
diff --git a/shell/impl/src/main/java/org/jboss/forge/addon/shell/commands/AbstractExitCommand.java b/shell/impl/src/main/java/org/jboss/forge/addon/shell/commands/AbstractExitCommand.java index f43629871..56b309a19 100644 --- a/shell/impl/src/main/java/org/jboss/forge/addon/shell/commands/AbstractExitCommand.java +++ b/shell/impl/src/main/java/org/jboss/forge/addon/shell/commands/AbstractExitCommand.java @@ -1,46 +1,47 @@ /* * Copyright 2012 Red Hat, Inc. and/or its affiliates. * * Licensed under the Eclipse Public License version 1.0, available at * http://www.eclipse.org/legal/epl-v10.html */ package org.jboss.forge.addon.shell.commands; import javax.inject.Inject; import org.jboss.forge.addon.shell.ui.AbstractShellCommand; import org.jboss.forge.addon.shell.ui.ShellContext; import org.jboss.forge.addon.ui.UICommand; import org.jboss.forge.addon.ui.context.UIBuilder; import org.jboss.forge.addon.ui.result.Result; import org.jboss.forge.addon.ui.result.Results; import org.jboss.forge.addon.ui.util.Metadata; import org.jboss.forge.furnace.Furnace; /** * @author <a href="mailto:[email protected]">Ståle W. Pedersen</a> */ public abstract class AbstractExitCommand extends AbstractShellCommand implements UICommand { @Inject private Furnace forge; @Override public Metadata getMetadata() { return super.getMetadata().name("exit").description("Exit the shell"); } @Override public void initializeUI(UIBuilder context) throws Exception { } @Override public Result execute(ShellContext context) throws Exception { + context.getProvider().getConsole().stop(); forge.stop(); return Results.success(""); } }
true
true
public Result execute(ShellContext context) throws Exception { forge.stop(); return Results.success(""); }
public Result execute(ShellContext context) throws Exception { context.getProvider().getConsole().stop(); forge.stop(); return Results.success(""); }
diff --git a/iotope-node/src/main/java/org/iotope/node/reader/PollThread.java b/iotope-node/src/main/java/org/iotope/node/reader/PollThread.java index bf6d775..4bfddee 100644 --- a/iotope-node/src/main/java/org/iotope/node/reader/PollThread.java +++ b/iotope-node/src/main/java/org/iotope/node/reader/PollThread.java @@ -1,160 +1,162 @@ package org.iotope.node.reader; import org.cometd.bayeux.client.ClientSessionChannel; import org.iotope.nfc.reader.ReaderChannel; import org.iotope.nfc.reader.pn532.PN532InAutoPoll; import org.iotope.nfc.reader.pn532.PN532InAutoPollResponse; import org.iotope.nfc.reader.pn532.PN532RFConfiguration; import org.iotope.nfc.tag.NfcTarget; import org.iotope.nfc.target.TargetContent; import org.iotope.nfc.tech.NfcType2; import org.iotope.node.Node; import org.iotope.node.apps.Correlation; import org.iotope.node.conf.Cfg; import org.iotope.node.conf.CfgTech; import org.iotope.node.conf.CfgTech.Protocol; import org.iotope.node.conf.Configuration; import org.iotope.node.conf.Mode; import org.iotope.pipeline.ExecutionContextImpl; import org.iotope.pipeline.ExecutionPipeline; import org.iotope.pipeline.model.Field; import org.iotope.pipeline.model.Reader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.eventbus.EventBus; public class PollThread implements Runnable { private static Logger Log = LoggerFactory.getLogger(PollThread.class); private ReaderChannel channel; private Reader reader; private EventBus bus; Correlation correlation = Node.instance(Correlation.class); Configuration configuration = Node.instance(Configuration.class); Mode mode = Node.instance(Mode.class); ExecutionPipeline executionPipeline = Node.instance(ExecutionPipeline.class); ClientSessionChannel cometdChannel; NfcTarget[] previousTargets = new NfcTarget[2]; public PollThread(EventBus bus, ReaderChannel channel, Reader reader) { this.bus = bus; this.reader = reader; this.channel = channel; } @Override public void run() { try { Cfg prevCfg = null; channel.transmit(new PN532RFConfiguration()); while (true) { Cfg cfg = configuration.getConfig(); if (prevCfg != cfg) { // config change prevCfg = cfg; } PN532InAutoPollResponse response = channel.transmit(new PN532InAutoPoll()); NfcTarget[] currentTargets = response.getTags(); // After detection, remove all the old targets from our list // and broadcast the removal on the bus removeTargetsFromSlots(currentTargets); // Handle new targets that are detected as well as broadcast the new // targets handleNewTargets(cfg, currentTargets); // Wait for next auto poll request Thread.sleep(250); } } catch (Exception e) { throw new RuntimeException(e); } } private void handleNewTargets(Cfg cfg, NfcTarget[] currentTargets) { // for (int ix = 0; ix < currentTargets.length; ix++) { if (previousTargets[ix] == null) { NfcTarget nfcTarget = currentTargets[ix]; if (nfcTarget != null) { startPipeline(cfg, ix, nfcTarget); previousTargets[ix] = nfcTarget; } else { Log.error("Trying to handle nfcTarget but it has NULL"); } } } } private void removeTargetsFromSlots(NfcTarget[] currentTargets) { // remove previously different tags slots for (int ix = 0; ix < previousTargets.length; ix++) { NfcTarget nfcTarget = null; if (ix < currentTargets.length) { nfcTarget = currentTargets[ix]; } if ((previousTargets[ix] != null) && !(previousTargets[ix].equals(nfcTarget))) { bus.post(new TagChange(TagChange.Event.REMOVED, reader, ix, null)); previousTargets[ix] = null; } } } private void startPipeline(Cfg cfg, int ix, NfcTarget nfcTarget) { TagChange tagChange = new TagChange(TagChange.Event.ADDED, reader, ix, nfcTarget); ExecutionPipeline pipeline = Node.instance(ExecutionPipeline.class); ExecutionContextImpl executionContext = new ExecutionContextImpl(); executionContext.setNfcTarget(nfcTarget); if (nfcTarget.isDEP()) { // DEP Log.trace("Handling new DEP target: " + nfcTarget.toString()); } else { // TAG Log.debug("Handling new TAG target: " + nfcTarget.toString()); try { CfgTech cfgTech; switch (nfcTarget.getType()) { case MIFARE_1K: cfgTech = cfg.getTechnology(Protocol.MIFARE_CLASSIC); if (cfgTech != null) { //readClassicAll(nfcTag); } break; case MIFARE_ULTRALIGHT: cfgTech = cfg.getTechnology(Protocol.MIFARE_ULTRALIGHT); if (cfgTech != null) { if (cfgTech.isNdef()) { NfcType2 ultraLight = new NfcType2(channel); - executionContext.setTargetContent(ultraLight.readNDEF(nfcTarget)); + TargetContent targetContent = ultraLight.readNDEF(nfcTarget); + executionContext.setTargetContent(targetContent); + tagChange.addTagContent(targetContent); } if (cfgTech.isMeta()) { correlation.getAssociateDataForTag(tagChange.getNfcId(), executionContext); } //writeTest(nfcTag); } break; default: Log.error("Can't handle unsupported target type: " + nfcTarget.getType()); } } catch (Exception e) { e.printStackTrace(); } } pipeline.initPipeline(cfg, executionContext); tagChange.setApplication(executionContext.getApplication()); if (executionContext.getFields() != null) { for (Field field : executionContext.getFields()) { tagChange.addField(field); } } if (!mode.isLearnMode()) { pipeline.startPipeline(); } bus.post(tagChange); } }
true
true
private void startPipeline(Cfg cfg, int ix, NfcTarget nfcTarget) { TagChange tagChange = new TagChange(TagChange.Event.ADDED, reader, ix, nfcTarget); ExecutionPipeline pipeline = Node.instance(ExecutionPipeline.class); ExecutionContextImpl executionContext = new ExecutionContextImpl(); executionContext.setNfcTarget(nfcTarget); if (nfcTarget.isDEP()) { // DEP Log.trace("Handling new DEP target: " + nfcTarget.toString()); } else { // TAG Log.debug("Handling new TAG target: " + nfcTarget.toString()); try { CfgTech cfgTech; switch (nfcTarget.getType()) { case MIFARE_1K: cfgTech = cfg.getTechnology(Protocol.MIFARE_CLASSIC); if (cfgTech != null) { //readClassicAll(nfcTag); } break; case MIFARE_ULTRALIGHT: cfgTech = cfg.getTechnology(Protocol.MIFARE_ULTRALIGHT); if (cfgTech != null) { if (cfgTech.isNdef()) { NfcType2 ultraLight = new NfcType2(channel); executionContext.setTargetContent(ultraLight.readNDEF(nfcTarget)); } if (cfgTech.isMeta()) { correlation.getAssociateDataForTag(tagChange.getNfcId(), executionContext); } //writeTest(nfcTag); } break; default: Log.error("Can't handle unsupported target type: " + nfcTarget.getType()); } } catch (Exception e) { e.printStackTrace(); } } pipeline.initPipeline(cfg, executionContext); tagChange.setApplication(executionContext.getApplication()); if (executionContext.getFields() != null) { for (Field field : executionContext.getFields()) { tagChange.addField(field); } } if (!mode.isLearnMode()) { pipeline.startPipeline(); } bus.post(tagChange); }
private void startPipeline(Cfg cfg, int ix, NfcTarget nfcTarget) { TagChange tagChange = new TagChange(TagChange.Event.ADDED, reader, ix, nfcTarget); ExecutionPipeline pipeline = Node.instance(ExecutionPipeline.class); ExecutionContextImpl executionContext = new ExecutionContextImpl(); executionContext.setNfcTarget(nfcTarget); if (nfcTarget.isDEP()) { // DEP Log.trace("Handling new DEP target: " + nfcTarget.toString()); } else { // TAG Log.debug("Handling new TAG target: " + nfcTarget.toString()); try { CfgTech cfgTech; switch (nfcTarget.getType()) { case MIFARE_1K: cfgTech = cfg.getTechnology(Protocol.MIFARE_CLASSIC); if (cfgTech != null) { //readClassicAll(nfcTag); } break; case MIFARE_ULTRALIGHT: cfgTech = cfg.getTechnology(Protocol.MIFARE_ULTRALIGHT); if (cfgTech != null) { if (cfgTech.isNdef()) { NfcType2 ultraLight = new NfcType2(channel); TargetContent targetContent = ultraLight.readNDEF(nfcTarget); executionContext.setTargetContent(targetContent); tagChange.addTagContent(targetContent); } if (cfgTech.isMeta()) { correlation.getAssociateDataForTag(tagChange.getNfcId(), executionContext); } //writeTest(nfcTag); } break; default: Log.error("Can't handle unsupported target type: " + nfcTarget.getType()); } } catch (Exception e) { e.printStackTrace(); } } pipeline.initPipeline(cfg, executionContext); tagChange.setApplication(executionContext.getApplication()); if (executionContext.getFields() != null) { for (Field field : executionContext.getFields()) { tagChange.addField(field); } } if (!mode.isLearnMode()) { pipeline.startPipeline(); } bus.post(tagChange); }
diff --git a/src/main/java/org/everit/jira/timetracker/plugin/AdminSettingsWebAction.java b/src/main/java/org/everit/jira/timetracker/plugin/AdminSettingsWebAction.java index 10392a5a..d10ae6d8 100644 --- a/src/main/java/org/everit/jira/timetracker/plugin/AdminSettingsWebAction.java +++ b/src/main/java/org/everit/jira/timetracker/plugin/AdminSettingsWebAction.java @@ -1,335 +1,337 @@ package org.everit.jira.timetracker.plugin; /* * Copyright (c) 2011, Everit Kft. * * All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 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., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ import java.text.ParseException; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; import org.apache.log4j.Logger; import org.everit.jira.timetracker.plugin.dto.PluginSettingsValues; import com.atlassian.jira.web.action.JiraWebActionSupport; public class AdminSettingsWebAction extends JiraWebActionSupport { /** * Serial version UID. */ private static final long serialVersionUID = 1L; /** * The {@link JiraTimetrackerPlugin}. */ private JiraTimetrackerPlugin jiraTimetrackerPlugin; /** * Logger. */ private static final Logger LOGGER = Logger.getLogger(AdminSettingsWebAction.class); /** * The IDs of the projects. */ private List<String> projectsId; /** * The exclude dates in String format. */ private String excludeDates = ""; /** * The include dates in String format. */ private String includeDates = ""; /** * The calendar is popup, inLine or both. */ private int isPopup; /** * The calenar show the actualDate or the last unfilled date. */ private boolean isActualDate; /** * The issue key. */ private String issueKey = ""; /** * The collector issue key. */ private String collectorIssueKey = ""; /** * The filtered Issues id. */ private List<Pattern> issuesPatterns; /** * The settings page message parameter. */ private String messageExclude = ""; /** * The paramater of the message. */ private String messageParameterExclude = ""; /** * The settings page message parameter. */ private String messageInclude = ""; /** * The paramater of the message. */ private String messageParameterInclude = ""; /** * The collector issue ids. */ private List<Pattern> collectorIssuePatterns; public AdminSettingsWebAction(final JiraTimetrackerPlugin jiraTimetrackerPlugin) { this.jiraTimetrackerPlugin = jiraTimetrackerPlugin; } @Override public String doDefault() throws ParseException { boolean isUserLogged = JiraTimetrackerUtil.isUserLogged(); if (!isUserLogged) { setReturnUrl("/secure/Dashboard.jspa"); return getRedirect(NONE); } loadPluginSettingAndParseResult(); try { projectsId = jiraTimetrackerPlugin.getProjectsId(); } catch (Exception e) { LOGGER.error("Error when try set the plugin variables.", e); return ERROR; } return INPUT; } @Override public String doExecute() throws ParseException { boolean isUserLogged = JiraTimetrackerUtil.isUserLogged(); if (!isUserLogged) { setReturnUrl("/secure/Dashboard.jspa"); return getRedirect(NONE); } loadPluginSettingAndParseResult(); try { projectsId = jiraTimetrackerPlugin.getProjectsId(); } catch (Exception e) { LOGGER.error("Error when try set the plugin variables.", e); return ERROR; } if (request.getParameter("savesettings") != null) { String parseReuslt = parseSaveSettings(request); if (parseReuslt != null) { return parseReuslt; } savePluginSettings(); setReturnUrl("/secure/AdminSummary.jspa"); return getRedirect(INPUT); } return SUCCESS; } public String getCollectorIssueKey() { return collectorIssueKey; } public String getExcludeDates() { return excludeDates; } public String getIncludeDates() { return includeDates; } public String getIssueKey() { return issueKey; } public String getMessageExclude() { return messageExclude; } public String getMessageInclude() { return messageInclude; } public String getMessageParameterExclude() { return messageParameterExclude; } public String getMessageParameterInclude() { return messageParameterInclude; } public List<String> getProjectsId() { return projectsId; } /** * Load the plugin settings and set the variables. */ public void loadPluginSettingAndParseResult() { PluginSettingsValues pluginSettingsValues = jiraTimetrackerPlugin.loadPluginSettings(); isPopup = pluginSettingsValues.isCalendarPopup(); isActualDate = pluginSettingsValues.isActualDate(); issuesPatterns = pluginSettingsValues.getFilteredSummaryIssues(); for (Pattern issueId : issuesPatterns) { issueKey += issueId.toString() + " "; } collectorIssuePatterns = pluginSettingsValues.getCollectorIssues(); for (Pattern issuePattern : collectorIssuePatterns) { collectorIssueKey += issuePattern.toString() + " "; } excludeDates = pluginSettingsValues.getExcludeDates(); includeDates = pluginSettingsValues.getIncludeDates(); } /** * Parse the reqest after the save button was clicked. Set the variables. * * @param request * The HttpServletRequest. */ public String parseSaveSettings(final HttpServletRequest request) { String[] issueSelectValue = request.getParameterValues("issueSelect"); String[] collectorIssueSelectValue = request.getParameterValues("issueSelect_collector"); String[] excludeDatesValue = request.getParameterValues("excludedates"); String[] includeDatesValue = request.getParameterValues("includedates"); if (issueSelectValue == null) { issuesPatterns = new ArrayList<Pattern>(); } else { issuesPatterns = new ArrayList<Pattern>(); for (String filteredIssueKey : issueSelectValue) { issuesPatterns.add(Pattern.compile(filteredIssueKey)); } } if (collectorIssueSelectValue == null) { collectorIssuePatterns = new ArrayList<Pattern>(); } else { collectorIssuePatterns = new ArrayList<Pattern>(); for (String filteredIssueKey : collectorIssueSelectValue) { collectorIssuePatterns.add(Pattern.compile(filteredIssueKey)); } } boolean parseExcludeException = false; boolean parseIncludeException = false; // Handle exclude and include date in the parse method end. if (excludeDatesValue == null) { excludeDates = ""; } else { String excludeDatesValueString = excludeDatesValue[0]; if (!excludeDatesValueString.isEmpty()) { + excludeDatesValueString = excludeDatesValueString.replace(" ", "").replace("\r", "").replace("\n", ""); for (String dateString : excludeDatesValueString.split(",")) { try { DateTimeConverterUtil.stringToDate(dateString); } catch (ParseException e) { parseExcludeException = true; messageExclude = "plugin.parse.exception.exclude"; if (messageParameterExclude.isEmpty()) { messageParameterExclude += dateString; } else { messageParameterExclude += ", " + dateString; } } } } excludeDates = excludeDatesValueString; } if (includeDatesValue == null) { includeDates = ""; } else { String includeDatesValueString = includeDatesValue[0]; if (!includeDatesValueString.isEmpty()) { + includeDatesValueString = includeDatesValueString.replace(" ", "").replace("\r", "").replace("\n", ""); for (String dateString : includeDatesValueString.split(",")) { try { DateTimeConverterUtil.stringToDate(dateString); } catch (ParseException e) { parseIncludeException = true; messageInclude = "plugin.parse.exception.include"; if (messageParameterInclude.isEmpty()) { messageParameterInclude += dateString; } else { messageParameterInclude += ", " + dateString; } } } } includeDates = includeDatesValueString; } if (parseExcludeException || parseIncludeException) { return SUCCESS; } return null; } /** * Save the plugin settings. */ public void savePluginSettings() { PluginSettingsValues pluginSettingValues = new PluginSettingsValues(isPopup, isActualDate, issuesPatterns, collectorIssuePatterns, excludeDates, includeDates); jiraTimetrackerPlugin.savePluginSettings(pluginSettingValues); } public void setCollectorIssueKey(final String collectorIssueKey) { this.collectorIssueKey = collectorIssueKey; } public void setExcludeDates(final String excludeDates) { this.excludeDates = excludeDates; } public void setIncludeDates(final String includeDates) { this.includeDates = includeDates; } public void setIssueKey(final String issueKey) { this.issueKey = issueKey; } public void setMessageExclude(final String messageExclude) { this.messageExclude = messageExclude; } public void setMessageInclude(final String messageInclude) { this.messageInclude = messageInclude; } public void setMessageParameterExclude(final String messageParameterExclude) { this.messageParameterExclude = messageParameterExclude; } public void setMessageParameterInclude(final String messageParameterInclude) { this.messageParameterInclude = messageParameterInclude; } public void setProjectsId(final List<String> projectsId) { this.projectsId = projectsId; } }
false
true
public String parseSaveSettings(final HttpServletRequest request) { String[] issueSelectValue = request.getParameterValues("issueSelect"); String[] collectorIssueSelectValue = request.getParameterValues("issueSelect_collector"); String[] excludeDatesValue = request.getParameterValues("excludedates"); String[] includeDatesValue = request.getParameterValues("includedates"); if (issueSelectValue == null) { issuesPatterns = new ArrayList<Pattern>(); } else { issuesPatterns = new ArrayList<Pattern>(); for (String filteredIssueKey : issueSelectValue) { issuesPatterns.add(Pattern.compile(filteredIssueKey)); } } if (collectorIssueSelectValue == null) { collectorIssuePatterns = new ArrayList<Pattern>(); } else { collectorIssuePatterns = new ArrayList<Pattern>(); for (String filteredIssueKey : collectorIssueSelectValue) { collectorIssuePatterns.add(Pattern.compile(filteredIssueKey)); } } boolean parseExcludeException = false; boolean parseIncludeException = false; // Handle exclude and include date in the parse method end. if (excludeDatesValue == null) { excludeDates = ""; } else { String excludeDatesValueString = excludeDatesValue[0]; if (!excludeDatesValueString.isEmpty()) { for (String dateString : excludeDatesValueString.split(",")) { try { DateTimeConverterUtil.stringToDate(dateString); } catch (ParseException e) { parseExcludeException = true; messageExclude = "plugin.parse.exception.exclude"; if (messageParameterExclude.isEmpty()) { messageParameterExclude += dateString; } else { messageParameterExclude += ", " + dateString; } } } } excludeDates = excludeDatesValueString; } if (includeDatesValue == null) { includeDates = ""; } else { String includeDatesValueString = includeDatesValue[0]; if (!includeDatesValueString.isEmpty()) { for (String dateString : includeDatesValueString.split(",")) { try { DateTimeConverterUtil.stringToDate(dateString); } catch (ParseException e) { parseIncludeException = true; messageInclude = "plugin.parse.exception.include"; if (messageParameterInclude.isEmpty()) { messageParameterInclude += dateString; } else { messageParameterInclude += ", " + dateString; } } } } includeDates = includeDatesValueString; } if (parseExcludeException || parseIncludeException) { return SUCCESS; } return null; }
public String parseSaveSettings(final HttpServletRequest request) { String[] issueSelectValue = request.getParameterValues("issueSelect"); String[] collectorIssueSelectValue = request.getParameterValues("issueSelect_collector"); String[] excludeDatesValue = request.getParameterValues("excludedates"); String[] includeDatesValue = request.getParameterValues("includedates"); if (issueSelectValue == null) { issuesPatterns = new ArrayList<Pattern>(); } else { issuesPatterns = new ArrayList<Pattern>(); for (String filteredIssueKey : issueSelectValue) { issuesPatterns.add(Pattern.compile(filteredIssueKey)); } } if (collectorIssueSelectValue == null) { collectorIssuePatterns = new ArrayList<Pattern>(); } else { collectorIssuePatterns = new ArrayList<Pattern>(); for (String filteredIssueKey : collectorIssueSelectValue) { collectorIssuePatterns.add(Pattern.compile(filteredIssueKey)); } } boolean parseExcludeException = false; boolean parseIncludeException = false; // Handle exclude and include date in the parse method end. if (excludeDatesValue == null) { excludeDates = ""; } else { String excludeDatesValueString = excludeDatesValue[0]; if (!excludeDatesValueString.isEmpty()) { excludeDatesValueString = excludeDatesValueString.replace(" ", "").replace("\r", "").replace("\n", ""); for (String dateString : excludeDatesValueString.split(",")) { try { DateTimeConverterUtil.stringToDate(dateString); } catch (ParseException e) { parseExcludeException = true; messageExclude = "plugin.parse.exception.exclude"; if (messageParameterExclude.isEmpty()) { messageParameterExclude += dateString; } else { messageParameterExclude += ", " + dateString; } } } } excludeDates = excludeDatesValueString; } if (includeDatesValue == null) { includeDates = ""; } else { String includeDatesValueString = includeDatesValue[0]; if (!includeDatesValueString.isEmpty()) { includeDatesValueString = includeDatesValueString.replace(" ", "").replace("\r", "").replace("\n", ""); for (String dateString : includeDatesValueString.split(",")) { try { DateTimeConverterUtil.stringToDate(dateString); } catch (ParseException e) { parseIncludeException = true; messageInclude = "plugin.parse.exception.include"; if (messageParameterInclude.isEmpty()) { messageParameterInclude += dateString; } else { messageParameterInclude += ", " + dateString; } } } } includeDates = includeDatesValueString; } if (parseExcludeException || parseIncludeException) { return SUCCESS; } return null; }
diff --git a/roborumble/roborumble/RoboRumbleAtHome.java b/roborumble/roborumble/RoboRumbleAtHome.java index 82489e551..4c8a3a69e 100644 --- a/roborumble/roborumble/RoboRumbleAtHome.java +++ b/roborumble/roborumble/RoboRumbleAtHome.java @@ -1,151 +1,152 @@ /******************************************************************************* * Copyright (c) 2003, 2007 Albert P�rez and RoboRumble contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://robocode.sourceforge.net/license/cpl-v10.html * * Contributors: * Albert P�rez * - Initial API and implementation * Flemming N. Larsen * - Properties are now read using PropertiesUtil.getProperties() * - Renamed UpdateRatings() into updateRatings() *******************************************************************************/ package roborumble; import roborumble.battlesengine.*; import roborumble.netengine.*; import java.util.*; import static roborumble.util.PropertiesUtil.getProperties; /** * Implements the client side of RoboRumble@Home. * Controlled by properties files. * * @author Albert P�rez (original) * @author Flemming N. Larsen (contributor) */ public class RoboRumbleAtHome { public static void main(String args[]) { // get the associated parameters file String parameters = "./roborumble/roborumble.txt"; try { parameters = args[0]; } catch (Exception e) { System.out.println("No argument found specifying properties file. \"roborumble.txt\" assumed."); } // Read parameters for running the app Properties param = getProperties(parameters); String downloads = param.getProperty("DOWNLOAD", "NOT"); String executes = param.getProperty("EXECUTE", "NOT"); String uploads = param.getProperty("UPLOAD", "NOT"); String iterates = param.getProperty("ITERATE", "NOT"); String runonly = param.getProperty("RUNONLY", "GENERAL"); String melee = param.getProperty("MELEE", "NOT"); int iterations = 0; long lastdownload = 0; boolean ratingsdownloaded = false; boolean participantsdownloaded = false; do { System.out.println("Iteration number " + iterations); // Download data from internet if downloads is YES and it has not beeen download for two hours if (downloads.equals("YES") && (System.currentTimeMillis() - lastdownload) > 2 * 3600 * 1000) { BotsDownload download = new BotsDownload(parameters); System.out.println("Downloading participants list ..."); participantsdownloaded = download.downloadParticipantsList(); System.out.println("Downloading missing bots ..."); download.downloadMissingBots(); download.updateCodeSize(); if (runonly.equals("SERVER")) { // download rating files and update ratings downloaded System.out.println("Downloading rating files ..."); ratingsdownloaded = download.downloadRatings(); } // send the order to the server to remove old participants from the ratings file if (ratingsdownloaded && participantsdownloaded) { System.out.println("Removing old participants from server ..."); // send unwanted participants to the server download.notifyServerForOldParticipants(); } download = null; lastdownload = System.currentTimeMillis(); } // create battles file (and delete old ones), and execute battles if (executes.equals("YES")) { boolean ready = false; PrepareBattles battles = new PrepareBattles(parameters); if (melee.equals("YES")) { System.out.println("Preparing melee battles list ..."); ready = battles.createMeleeBattlesList(); } else { System.out.println( "Preparing battles list ... Using smart battles is " + (ratingsdownloaded && runonly.equals("SERVER"))); if (ratingsdownloaded && runonly.equals("SERVER")) { ready = battles.createSmartBattlesList(); } // create the smart lists else { ready = battles.createBattlesList(); } // create the normal lists } battles = null; // execute battles if (ready) { if (melee.equals("YES")) { System.out.println("Executing melee battles ..."); BattlesRunner engine = new BattlesRunner(parameters); engine.runMeleeBattles(); engine = null; } else { System.out.println("Executing battles ..."); BattlesRunner engine = new BattlesRunner(parameters); engine.runBattles(); engine = null; } } } // upload results if (uploads.equals("YES")) { System.out.println("Uloading results ..."); ResultsUpload upload = new ResultsUpload(parameters); // uploads the results to the server upload.uploadResults(); upload = null; // updates the number of battles from the info received from the server System.out.println("Updating number of battles fought ..."); UpdateRatingFiles updater = new UpdateRatingFiles(parameters); ratingsdownloaded = updater.updateRatings(); // if (!ok) ratingsdownloaded = false; updater = null; } iterations++; } while (iterates.equals("YES")); - System.exit(0); + // With Java 5 this causes a IllegalThreadStateException, but not in Java 6 + // System.exit(0); } }
true
true
public static void main(String args[]) { // get the associated parameters file String parameters = "./roborumble/roborumble.txt"; try { parameters = args[0]; } catch (Exception e) { System.out.println("No argument found specifying properties file. \"roborumble.txt\" assumed."); } // Read parameters for running the app Properties param = getProperties(parameters); String downloads = param.getProperty("DOWNLOAD", "NOT"); String executes = param.getProperty("EXECUTE", "NOT"); String uploads = param.getProperty("UPLOAD", "NOT"); String iterates = param.getProperty("ITERATE", "NOT"); String runonly = param.getProperty("RUNONLY", "GENERAL"); String melee = param.getProperty("MELEE", "NOT"); int iterations = 0; long lastdownload = 0; boolean ratingsdownloaded = false; boolean participantsdownloaded = false; do { System.out.println("Iteration number " + iterations); // Download data from internet if downloads is YES and it has not beeen download for two hours if (downloads.equals("YES") && (System.currentTimeMillis() - lastdownload) > 2 * 3600 * 1000) { BotsDownload download = new BotsDownload(parameters); System.out.println("Downloading participants list ..."); participantsdownloaded = download.downloadParticipantsList(); System.out.println("Downloading missing bots ..."); download.downloadMissingBots(); download.updateCodeSize(); if (runonly.equals("SERVER")) { // download rating files and update ratings downloaded System.out.println("Downloading rating files ..."); ratingsdownloaded = download.downloadRatings(); } // send the order to the server to remove old participants from the ratings file if (ratingsdownloaded && participantsdownloaded) { System.out.println("Removing old participants from server ..."); // send unwanted participants to the server download.notifyServerForOldParticipants(); } download = null; lastdownload = System.currentTimeMillis(); } // create battles file (and delete old ones), and execute battles if (executes.equals("YES")) { boolean ready = false; PrepareBattles battles = new PrepareBattles(parameters); if (melee.equals("YES")) { System.out.println("Preparing melee battles list ..."); ready = battles.createMeleeBattlesList(); } else { System.out.println( "Preparing battles list ... Using smart battles is " + (ratingsdownloaded && runonly.equals("SERVER"))); if (ratingsdownloaded && runonly.equals("SERVER")) { ready = battles.createSmartBattlesList(); } // create the smart lists else { ready = battles.createBattlesList(); } // create the normal lists } battles = null; // execute battles if (ready) { if (melee.equals("YES")) { System.out.println("Executing melee battles ..."); BattlesRunner engine = new BattlesRunner(parameters); engine.runMeleeBattles(); engine = null; } else { System.out.println("Executing battles ..."); BattlesRunner engine = new BattlesRunner(parameters); engine.runBattles(); engine = null; } } } // upload results if (uploads.equals("YES")) { System.out.println("Uloading results ..."); ResultsUpload upload = new ResultsUpload(parameters); // uploads the results to the server upload.uploadResults(); upload = null; // updates the number of battles from the info received from the server System.out.println("Updating number of battles fought ..."); UpdateRatingFiles updater = new UpdateRatingFiles(parameters); ratingsdownloaded = updater.updateRatings(); // if (!ok) ratingsdownloaded = false; updater = null; } iterations++; } while (iterates.equals("YES")); System.exit(0); }
public static void main(String args[]) { // get the associated parameters file String parameters = "./roborumble/roborumble.txt"; try { parameters = args[0]; } catch (Exception e) { System.out.println("No argument found specifying properties file. \"roborumble.txt\" assumed."); } // Read parameters for running the app Properties param = getProperties(parameters); String downloads = param.getProperty("DOWNLOAD", "NOT"); String executes = param.getProperty("EXECUTE", "NOT"); String uploads = param.getProperty("UPLOAD", "NOT"); String iterates = param.getProperty("ITERATE", "NOT"); String runonly = param.getProperty("RUNONLY", "GENERAL"); String melee = param.getProperty("MELEE", "NOT"); int iterations = 0; long lastdownload = 0; boolean ratingsdownloaded = false; boolean participantsdownloaded = false; do { System.out.println("Iteration number " + iterations); // Download data from internet if downloads is YES and it has not beeen download for two hours if (downloads.equals("YES") && (System.currentTimeMillis() - lastdownload) > 2 * 3600 * 1000) { BotsDownload download = new BotsDownload(parameters); System.out.println("Downloading participants list ..."); participantsdownloaded = download.downloadParticipantsList(); System.out.println("Downloading missing bots ..."); download.downloadMissingBots(); download.updateCodeSize(); if (runonly.equals("SERVER")) { // download rating files and update ratings downloaded System.out.println("Downloading rating files ..."); ratingsdownloaded = download.downloadRatings(); } // send the order to the server to remove old participants from the ratings file if (ratingsdownloaded && participantsdownloaded) { System.out.println("Removing old participants from server ..."); // send unwanted participants to the server download.notifyServerForOldParticipants(); } download = null; lastdownload = System.currentTimeMillis(); } // create battles file (and delete old ones), and execute battles if (executes.equals("YES")) { boolean ready = false; PrepareBattles battles = new PrepareBattles(parameters); if (melee.equals("YES")) { System.out.println("Preparing melee battles list ..."); ready = battles.createMeleeBattlesList(); } else { System.out.println( "Preparing battles list ... Using smart battles is " + (ratingsdownloaded && runonly.equals("SERVER"))); if (ratingsdownloaded && runonly.equals("SERVER")) { ready = battles.createSmartBattlesList(); } // create the smart lists else { ready = battles.createBattlesList(); } // create the normal lists } battles = null; // execute battles if (ready) { if (melee.equals("YES")) { System.out.println("Executing melee battles ..."); BattlesRunner engine = new BattlesRunner(parameters); engine.runMeleeBattles(); engine = null; } else { System.out.println("Executing battles ..."); BattlesRunner engine = new BattlesRunner(parameters); engine.runBattles(); engine = null; } } } // upload results if (uploads.equals("YES")) { System.out.println("Uloading results ..."); ResultsUpload upload = new ResultsUpload(parameters); // uploads the results to the server upload.uploadResults(); upload = null; // updates the number of battles from the info received from the server System.out.println("Updating number of battles fought ..."); UpdateRatingFiles updater = new UpdateRatingFiles(parameters); ratingsdownloaded = updater.updateRatings(); // if (!ok) ratingsdownloaded = false; updater = null; } iterations++; } while (iterates.equals("YES")); // With Java 5 this causes a IllegalThreadStateException, but not in Java 6 // System.exit(0); }
diff --git a/JsTestDriver/src/com/google/jstestdriver/ui/CapturedBrowsersPanel.java b/JsTestDriver/src/com/google/jstestdriver/ui/CapturedBrowsersPanel.java index cab6f24f..d8e1b030 100644 --- a/JsTestDriver/src/com/google/jstestdriver/ui/CapturedBrowsersPanel.java +++ b/JsTestDriver/src/com/google/jstestdriver/ui/CapturedBrowsersPanel.java @@ -1,116 +1,116 @@ /* * Copyright 2009 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.jstestdriver.ui; import com.google.jstestdriver.SlaveBrowser; import java.awt.Dimension; import java.awt.color.ColorSpace; import java.awt.image.BufferedImage; import java.awt.image.ColorConvertOp; import java.io.IOException; import java.util.Observable; import java.util.Observer; import javax.imageio.ImageIO; import javax.swing.BoxLayout; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JPanel; /** * @author [email protected] (Alex Eagle) */ @SuppressWarnings("serial") public class CapturedBrowsersPanel extends JPanel implements Observer { private BrowserIcon chrome; private BrowserIcon ie; private BrowserIcon firefox; // private BrowserIcon opera; private BrowserIcon safari; private JLabel chromeLabel; private JLabel ieLabel; private JLabel firefoxLabel; // private JLabel operaLabel; private JLabel safariLabel; public CapturedBrowsersPanel() { try { chrome = BrowserIcon.buildFromResource("Chrome.png"); ie = BrowserIcon.buildFromResource("IE.png"); firefox = BrowserIcon.buildFromResource("Firefox.png"); // opera = BrowserIcon.buildFromResource("Opera.png"); safari = BrowserIcon.buildFromResource("Safari.png"); } catch (IOException e) { throw new RuntimeException(); } setLayout(new BoxLayout(this, BoxLayout.X_AXIS)); chromeLabel = new JLabel(chrome.getGreyscaleIcon()); ieLabel = new JLabel(ie.getGreyscaleIcon()); firefoxLabel = new JLabel(firefox.getGreyscaleIcon()); // operaLabel = new JLabel(opera.getGreyscaleIcon()); safariLabel = new JLabel(safari.getGreyscaleIcon()); add(chromeLabel); add(ieLabel); add(firefoxLabel); // TODO(jeremie): Support opera? //add(operaLabel); add(safariLabel); - Dimension minimumSize = new Dimension(256 * 4, 256); + Dimension minimumSize = new Dimension(chrome.getColorIcon().getIconWidth() * 4, chrome.getColorIcon().getIconHeight()); setMinimumSize(minimumSize); setPreferredSize(minimumSize); } public void update(Observable observable, Object o) { SlaveBrowser slave = (SlaveBrowser) o; if (slave.getBrowserInfo().getName().contains("Firefox")) { firefoxLabel.setIcon(firefox.getColorIcon()); } else if (slave.getBrowserInfo().getName().contains("Chrome")) { chromeLabel.setIcon(chrome.getColorIcon()); } else if (slave.getBrowserInfo().getName().contains("Safari")) { safariLabel.setIcon(safari.getColorIcon()); } else if (slave.getBrowserInfo().getName().contains("MSIE")) { ieLabel.setIcon(ie.getColorIcon()); } } private static class BrowserIcon { private final BufferedImage color; private final BufferedImage greyscale; private ColorConvertOp op = new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_GRAY), null); public BrowserIcon(BufferedImage color) { this.color = color; greyscale = op.filter(color, null); } public static BrowserIcon buildFromResource(String resourceName) throws IOException { return new BrowserIcon(ImageIO.read(BrowserIcon.class.getResourceAsStream(resourceName))); } public Icon getColorIcon() { return new ImageIcon(color); } public Icon getGreyscaleIcon() { return new ImageIcon(greyscale); } } }
true
true
public CapturedBrowsersPanel() { try { chrome = BrowserIcon.buildFromResource("Chrome.png"); ie = BrowserIcon.buildFromResource("IE.png"); firefox = BrowserIcon.buildFromResource("Firefox.png"); // opera = BrowserIcon.buildFromResource("Opera.png"); safari = BrowserIcon.buildFromResource("Safari.png"); } catch (IOException e) { throw new RuntimeException(); } setLayout(new BoxLayout(this, BoxLayout.X_AXIS)); chromeLabel = new JLabel(chrome.getGreyscaleIcon()); ieLabel = new JLabel(ie.getGreyscaleIcon()); firefoxLabel = new JLabel(firefox.getGreyscaleIcon()); // operaLabel = new JLabel(opera.getGreyscaleIcon()); safariLabel = new JLabel(safari.getGreyscaleIcon()); add(chromeLabel); add(ieLabel); add(firefoxLabel); // TODO(jeremie): Support opera? //add(operaLabel); add(safariLabel); Dimension minimumSize = new Dimension(256 * 4, 256); setMinimumSize(minimumSize); setPreferredSize(minimumSize); }
public CapturedBrowsersPanel() { try { chrome = BrowserIcon.buildFromResource("Chrome.png"); ie = BrowserIcon.buildFromResource("IE.png"); firefox = BrowserIcon.buildFromResource("Firefox.png"); // opera = BrowserIcon.buildFromResource("Opera.png"); safari = BrowserIcon.buildFromResource("Safari.png"); } catch (IOException e) { throw new RuntimeException(); } setLayout(new BoxLayout(this, BoxLayout.X_AXIS)); chromeLabel = new JLabel(chrome.getGreyscaleIcon()); ieLabel = new JLabel(ie.getGreyscaleIcon()); firefoxLabel = new JLabel(firefox.getGreyscaleIcon()); // operaLabel = new JLabel(opera.getGreyscaleIcon()); safariLabel = new JLabel(safari.getGreyscaleIcon()); add(chromeLabel); add(ieLabel); add(firefoxLabel); // TODO(jeremie): Support opera? //add(operaLabel); add(safariLabel); Dimension minimumSize = new Dimension(chrome.getColorIcon().getIconWidth() * 4, chrome.getColorIcon().getIconHeight()); setMinimumSize(minimumSize); setPreferredSize(minimumSize); }
diff --git a/src/org/bouncycastle/asn1/x509/KeyUsage.java b/src/org/bouncycastle/asn1/x509/KeyUsage.java index 76c8d8e2..918173b7 100644 --- a/src/org/bouncycastle/asn1/x509/KeyUsage.java +++ b/src/org/bouncycastle/asn1/x509/KeyUsage.java @@ -1,77 +1,77 @@ package org.bouncycastle.asn1.x509; import org.bouncycastle.asn1.DERBitString; /** * The KeyUsage object. * <pre> * id-ce-keyUsage OBJECT IDENTIFIER ::= { id-ce 15 } * * KeyUsage ::= BIT STRING { * digitalSignature (0), * nonRepudiation (1), * keyEncipherment (2), * dataEncipherment (3), * keyAgreement (4), * keyCertSign (5), * cRLSign (6), * encipherOnly (7), * decipherOnly (8) } * </pre> */ public class KeyUsage extends DERBitString { public static final int digitalSignature = (1 << 7); public static final int nonRepudiation = (1 << 6); public static final int keyEncipherment = (1 << 5); public static final int dataEncipherment = (1 << 4); public static final int keyAgreement = (1 << 3); public static final int keyCertSign = (1 << 2); public static final int cRLSign = (1 << 1); public static final int encipherOnly = (1 << 0); public static final int decipherOnly = (1 << 15); - public static DERBitString getInstance(Object obj) + public static KeyUsage getInstance(Object obj) { if (obj instanceof KeyUsage) { return (KeyUsage)obj; } if (obj instanceof X509Extension) { return new KeyUsage(DERBitString.getInstance(X509Extension.convertValueToObject((X509Extension)obj))); } return new KeyUsage(DERBitString.getInstance(obj)); } /** * Basic constructor. * * @param usage - the bitwise OR of the Key Usage flags giving the * allowed uses for the key. * e.g. (KeyUsage.keyEncipherment | KeyUsage.dataEncipherment) */ public KeyUsage( int usage) { super(getBytes(usage), getPadBits(usage)); } public KeyUsage( DERBitString usage) { super(usage.getBytes(), usage.getPadBits()); } public String toString() { if (data.length == 1) { return "KeyUsage: 0x" + Integer.toHexString(data[0] & 0xff); } return "KeyUsage: 0x" + Integer.toHexString((data[1] & 0xff) << 8 | (data[0] & 0xff)); } }
true
true
public static DERBitString getInstance(Object obj) { if (obj instanceof KeyUsage) { return (KeyUsage)obj; } if (obj instanceof X509Extension) { return new KeyUsage(DERBitString.getInstance(X509Extension.convertValueToObject((X509Extension)obj))); } return new KeyUsage(DERBitString.getInstance(obj)); }
public static KeyUsage getInstance(Object obj) { if (obj instanceof KeyUsage) { return (KeyUsage)obj; } if (obj instanceof X509Extension) { return new KeyUsage(DERBitString.getInstance(X509Extension.convertValueToObject((X509Extension)obj))); } return new KeyUsage(DERBitString.getInstance(obj)); }
diff --git a/source/de/anomic/http/httpdProxyHandler.java b/source/de/anomic/http/httpdProxyHandler.java index dcd7d0c21..980b7945e 100644 --- a/source/de/anomic/http/httpdProxyHandler.java +++ b/source/de/anomic/http/httpdProxyHandler.java @@ -1,1000 +1,1011 @@ // httpdProxyHandler.java // ----------------------- // part of YACY // (C) by Michael Peter Christen; [email protected] // first published on http://www.anomic.de // Frankfurt, Germany, 2004 // last major change: 10.05.2004 // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Using this software in any meaning (reading, learning, copying, compiling, // running) means that you agree that the Author(s) is (are) not responsible // for cost, loss of data or any harm that may be caused directly or indirectly // by usage of this softare or this documentation. The usage of this software // is on your own risk. The installation and usage (starting/running) of this // software may allow other people or application to access your computer and // any attached devices and is highly dependent on the configuration of the // software which must be done by the user of the software; the author(s) is // (are) also not responsible for proper configuration and usage of the // software, even if provoked by documentation provided together with // the software. // // Any changes to this file according to the GPL as documented in the file // gpl.txt aside this file in the shipment you received can be done to the // lines that follows this copyright notice here, but changes must not be // done inside the copyright notive above. A re-distribution must contain // the intact and unchanged copyright notice. // Contributions and changes to the program code must be marked as such. // Contributions: // [AS] Alexander Schier: Blacklist (404 response for AGIS hosts) // [TL] Timo Leise: url-wildcards for blacklists /* Class documentation: This class is a servlet to the httpd daemon. It is accessed each time an URL in a GET, HEAD or POST command contains the whole host information or a host is given in the header host field of an HTTP/1.0 / HTTP/1.1 command. Transparency is maintained, whenever appropriate. We change header atributes if necessary for the indexing mechanism; i.e. we do not support gzip-ed encoding. We also do not support unrealistic 'expires' values that would force a cache to be flushed immediately pragma non-cache attributes are supported */ package de.anomic.http; import java.io.*; import java.net.*; import java.util.*; import de.anomic.htmlFilter.*; import de.anomic.server.*; import de.anomic.yacy.*; import de.anomic.plasma.*; public final class httpdProxyHandler extends httpdAbstractHandler implements httpdHandler { // static variables // can only be instantiated upon first instantiation of this class object private static plasmaSwitchboard switchboard = null; private static plasmaHTCache cacheManager = null; public static serverLog log; public static HashSet yellowList = null; public static TreeMap blackListURLs = null; private static int timeout = 30000; private static boolean yacyTrigger = true; public static boolean remoteProxyUse = false; public static String remoteProxyHost = ""; public static int remoteProxyPort = -1; public static String remoteProxyNoProxy = ""; public static String[] remoteProxyNoProxyPatterns = null; private static final HashSet remoteProxyAllowProxySet = new HashSet(); private static final HashSet remoteProxyDisallowProxySet = new HashSet(); private static htmlFilterTransformer transformer = null; public static final String userAgent = "yacy (" + httpc.systemOST +") yacy.net"; private File htRootPath = null; // class methods public httpdProxyHandler(serverSwitch sb) { if (switchboard == null) { switchboard = (plasmaSwitchboard) sb; cacheManager = switchboard.getCacheManager(); // load remote proxy data remoteProxyHost = switchboard.getConfig("remoteProxyHost",""); try { remoteProxyPort = Integer.parseInt(switchboard.getConfig("remoteProxyPort","3128")); } catch (NumberFormatException e) { remoteProxyPort = 3128; } remoteProxyUse = switchboard.getConfig("remoteProxyUse","false").equals("true"); remoteProxyNoProxy = switchboard.getConfig("remoteProxyNoProxy",""); remoteProxyNoProxyPatterns = remoteProxyNoProxy.split(","); // set loglevel int loglevel = Integer.parseInt(switchboard.getConfig("proxyLoglevel", "2")); log = new serverLog("HTTPDProxy", loglevel); // set timeout timeout = Integer.parseInt(switchboard.getConfig("clientTimeout", "10000")); // create a htRootPath: system pages if (htRootPath == null) { htRootPath = new File(switchboard.getRootPath(), switchboard.getConfig("htRootPath","htroot")); if (!(htRootPath.exists())) htRootPath.mkdir(); } // load a transformer transformer = new htmlFilterContentTransformer(); transformer.init(new File(switchboard.getRootPath(), switchboard.getConfig("plasmaBlueList", "")).toString()); String f; // load the yellow-list f = switchboard.getConfig("proxyYellowList", null); if (f != null) yellowList = loadSet("yellow", f); else yellowList = new HashSet(); // load the black-list / inspired by [AS] f = switchboard.getConfig("proxyBlackListsActive", null); if (f != null) blackListURLs = loadBlacklist("black", f, "/"); else blackListURLs = new TreeMap(); log.logSystem("Proxy Handler Initialized"); } } private static HashSet loadSet(String setname, String filename) { HashSet set = new HashSet(); try { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filename))); String line; while ((line = br.readLine()) != null) { line = line.trim(); if ((line.length() > 0) && (!(line.startsWith("#")))) set.add(line.trim().toLowerCase()); } br.close(); serverLog.logInfo("PROXY", "read " + setname + " set from file " + filename); } catch (IOException e) {} return set; } private static TreeMap loadMap(String mapname, String filename, String sep) { TreeMap map = new TreeMap(); try { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filename))); String line; int pos; while ((line = br.readLine()) != null) { line = line.trim(); if ((line.length() > 0) && (!(line.startsWith("#"))) && ((pos = line.indexOf(sep)) > 0)) map.put(line.substring(0, pos).trim().toLowerCase(), line.substring(pos + sep.length()).trim()); } br.close(); serverLog.logInfo("PROXY", "read " + mapname + " map from file " + filename); } catch (IOException e) {} return map; } public static TreeMap loadBlacklist(String mapname, String filenames, String sep) { TreeMap map = new TreeMap(); if (switchboard == null) return map; // not initialized yet File listsPath = new File(switchboard.getRootPath(), switchboard.getConfig("listsPath", "DATA/LISTS")); String filenamesarray[] = filenames.split(","); String filename = ""; if(filenamesarray.length >0) for(int i = 0; i < filenamesarray.length; i++) map.putAll(loadMap(mapname, (new File(listsPath, filenamesarray[i])).toString(), sep)); return map; } private static String domain(String host) { String domain = host; int pos = domain.lastIndexOf("."); if (pos >= 0) { // truncate from last part domain = domain.substring(0, pos); pos = domain.lastIndexOf("."); if (pos >= 0) { // truncate from first part domain = domain.substring(pos + 1); } } return domain; } private boolean blacklistedURL(String hostlow, String path) { if (blackListURLs == null) return false; int index = 0; // [TL] While "." are found within the string while ((index = hostlow.indexOf(".", index + 1)) != -1) { if (blackListURLs.get(hostlow.substring(0, index + 1) + "*") != null) { //System.out.println("Host blocked: " + hostlow.substring(0, index+1) + "*"); return true; } } index = hostlow.length(); while ((index = hostlow.lastIndexOf(".", index - 1)) != -1) { if (blackListURLs.get("*" + hostlow.substring(index, hostlow.length())) != null) { //System.out.println("Host blocked: " + "*" + hostlow.substring(index, host.length())); return true; } } String pp = ""; // path-pattern return (((pp = (String) blackListURLs.get(hostlow)) != null) && ((pp.equals("*")) || (path.substring(1).matches(pp)))); } public void handleOutgoingCookies(httpHeader requestHeader, String targethost, String clienthost) { // request header may have double-entries: they are accumulated in one entry // by the httpd and separated by a "#" in the value field /* The syntax for the header is: cookie = "Cookie:" cookie-version 1*((";" | ",") cookie-value) cookie-value = NAME "=" VALUE [";" path] [";" domain] cookie-version = "$Version" "=" value NAME = attr VALUE = value path = "$Path" "=" value domain = "$Domain" "=" value */ if (requestHeader.containsKey("Cookie")) { Object[] entry = new Object[]{new Date(), clienthost, requestHeader.get("Cookie")}; switchboard.outgoingCookies.put(targethost, entry); } } public void handleIncomingCookies(httpHeader respondHeader, String serverhost, String targetclient) { // respond header may have double-entries: they are accumulated in one entry // by the httpc and separated by a "#" in the value field /* The syntax for the Set-Cookie response header is set-cookie = "Set-Cookie:" cookies cookies = 1#cookie cookie = NAME "=" VALUE *(";" cookie-av) NAME = attr VALUE = value cookie-av = "Comment" "=" value | "Domain" "=" value | "Max-Age" "=" value | "Path" "=" value | "Secure" | "Version" "=" 1*DIGIT */ if (respondHeader.containsKey("Set-Cookie")) { Object[] entry = new Object[]{new Date(), targetclient, respondHeader.get("Set-Cookie")}; switchboard.incomingCookies.put(serverhost, entry); } } public void doGet(Properties conProp, httpHeader requestHeader, OutputStream respond) throws IOException { // prepare response // conProp : a collection of properties about the connection, like URL // requestHeader : The header lines of the connection from the request // args : the argument values of a connection, like &-values in GET and values within boundaries in POST // files : files within POST boundaries, same key as in args if (yacyTrigger) de.anomic.yacy.yacyCore.triggerOnlineAction(); Date requestDate = new Date(); // remember the time... String method = conProp.getProperty("METHOD"); String host = conProp.getProperty("HOST"); String path = conProp.getProperty("PATH"); // always starts with leading '/' String args = conProp.getProperty("ARGS"); // may be null if no args were given String ip = conProp.getProperty("CLIENTIP"); // the ip from the connecting peer int port; int pos; if ((pos = host.indexOf(":")) < 0) { port = 80; } else { port = Integer.parseInt(host.substring(pos + 1)); host = host.substring(0, pos); } String ext; if ((pos = path.lastIndexOf('.')) < 0) { ext = ""; } else { ext = path.substring(pos + 1).toLowerCase(); } URL url = null; try { if (args == null) url = new URL("http", host, port, path); else url = new URL("http", host, port, path + "?" + args); } catch (MalformedURLException e) { serverLog.logError("PROXY", "ERROR: internal error with url generation: host=" + host + ", port=" + port + ", path=" + path + ", args=" + args); url = null; } //System.out.println("GENERATED URL:" + url.toString()); // debug // check the blacklist // blacklist idea inspired by [AS]: // respond a 404 for all AGIS ("all you get is shit") servers String hostlow = host.toLowerCase(); if (blacklistedURL(hostlow, path)) { try { respondHeader(respond,"404 Not Found (AGIS)", new httpHeader(null)); respond.write(("404 (generated): URL '" + hostlow + "' blocked by yacy proxy (blacklisted)\r\n").getBytes()); respond.flush(); serverLog.logInfo("PROXY", "AGIS blocking of host '" + hostlow + "'"); // debug return; } catch (Exception ee) {} } // handle outgoing cookies handleOutgoingCookies(requestHeader, host, ip); // set another userAgent, if not yellowlisted if ((yellowList != null) && (!(yellowList.contains(domain(hostlow))))) { // change the User-Agent requestHeader.put("User-Agent", userAgent); } // set a scraper and a htmlFilter OutputStream hfos = null; htmlFilterContentScraper scraper = null; // resolve yacy and yacyh domains String yAddress = yacyCore.seedDB.resolveYacyAddress(host); // re-calc the url path String remotePath = (args == null) ? path : (path + "?" + args); // with leading '/' // attach possible yacy-sublevel-domain if ((yAddress != null) && ((pos = yAddress.indexOf("/")) >= 0) && (!(remotePath.startsWith("/env"))) // this is the special path, staying always at root-level ) remotePath = yAddress.substring(pos) + remotePath; // decide wether to use a cache entry or connect to the network File cacheFile = cacheManager.getCachePath(url); String urlHash = plasmaCrawlLURL.urlHash(url); httpHeader cachedResponseHeader = null; boolean cacheExists = ((cacheFile.exists()) && (cacheFile.isFile()) && ((cachedResponseHeader = cacheManager.getCachedResponse(urlHash)) != null)); // why are files unzipped upon arrival? why not zip all files in cache? // This follows from the following premises // (a) no file shall be unzip-ed more than once to prevent unnessesary computing time // (b) old cache entries shall be comparable with refill-entries to detect/distiguish case 3+4 // (c) the indexing mechanism needs files unzip-ed, a schedule could do that later // case b and c contradicts, if we use a scheduler, because files in a stale cache would be unzipped // and the newly arrival would be zipped and would have to be unzipped upon load. But then the // scheduler is superfluous. Therefore the only reminding case is // (d) cached files shall be either all zipped or unzipped // case d contradicts with a, because files need to be unzipped for indexing. Therefore // the only remaining case is to unzip files right upon load. Thats what we do here. // finally use existing cache if appropriate // here we must decide weather or not to save the data // to a cache // we distinguish four CACHE STATE cases: // 1. cache fill // 2. cache fresh - no refill // 3. cache stale - refill - necessary // 4. cache stale - refill - superfluous // in two of these cases we trigger a scheduler to handle newly arrived files: // case 1 and case 3 plasmaHTCache.Entry cacheEntry; if ((cacheExists) && ((cacheEntry = cacheManager.newEntry(requestDate, 0, url, requestHeader, "200 OK", cachedResponseHeader, null, switchboard.defaultProxyProfile)).shallUseCache())) { // we respond on the request by using the cache, the cache is fresh try { // replace date field in old header by actual date, this is according to RFC cachedResponseHeader.put("Date", httpc.dateString(httpc.nowDate())); // maybe the content length is missing if (!(cachedResponseHeader.containsKey("CONTENT-LENGTH"))) cachedResponseHeader.put("CONTENT-LENGTH", Long.toString(cacheFile.length())); // check if we can send a 304 instead the complete content if (requestHeader.containsKey("IF-MODIFIED-SINCE")) { // conditional request: freshness of cache for that condition was already // checked within shallUseCache(). Now send only a 304 response log.logInfo("CACHE HIT/304 " + cacheFile.toString()); // send cached header with replaced date and added length respondHeader(respond, "304 OK", cachedResponseHeader); // respond with 'not modified' } else { // unconditional request: send content of cache log.logInfo("CACHE HIT/203 " + cacheFile.toString()); // send cached header with replaced date and added length respondHeader(respond, "203 OK", cachedResponseHeader); // respond with 'non-authoritative' // make a transformer if ((!(transformer.isIdentityTransformer())) && ((ext == null) || (!(switchboard.extensionBlack.contains(ext)))) && ((cachedResponseHeader == null) || (httpd.isTextMime(cachedResponseHeader.mime(), switchboard.mimeWhite)))) { hfos = new htmlFilterOutputStream(respond, null, transformer, (ext.length() == 0)); } else { hfos = respond; } // send also the complete body now from the cache // simply read the file and transfer to out socket InputStream is = new FileInputStream(cacheFile); byte[] buffer = new byte[2048]; int l; while ((l = is.read(buffer)) > 0) {hfos.write(buffer, 0, l);} is.close(); if (hfos instanceof htmlFilterOutputStream) ((htmlFilterOutputStream) hfos).finalize(); } // that's it! } catch (SocketException e) { // this happens if the client stops loading the file // we do nothing here respondError(respond, "111 socket error: " + e.getMessage(), 1, url.toString()); } respond.flush(); return; } // the cache does either not exist or is (supposed to be) stale long sizeBeforeDelete = -1; if (cacheExists) { // delete the cache sizeBeforeDelete = cacheFile.length(); cacheFile.delete(); } // take a new file from the server httpc remote = null; httpc.response res = null; try { // open the connection if (yAddress == null) { remote = newhttpc(host, port, timeout); } else { remote = newhttpc(yAddress, timeout); } //System.out.println("HEADER: CLIENT TO PROXY = " + requestHeader.toString()); // DEBUG // send request res = remote.GET(remotePath, requestHeader); long contentLength = res.responseHeader.contentLength(); // reserver cache entry cacheEntry = cacheManager.newEntry(requestDate, 0, url, requestHeader, res.status, res.responseHeader, null, switchboard.defaultProxyProfile); // handle file types if (((ext == null) || (!(switchboard.extensionBlack.contains(ext)))) && (httpd.isTextMime(res.responseHeader.mime(), switchboard.mimeWhite))) { // this is a file that is a possible candidate for parsing by the indexer if (transformer.isIdentityTransformer()) { log.logDebug("create passthrough (parse candidate) for url " + url); // no transformation, only passthrough // this is especially the case if the bluelist is empty // in that case, the content is not scraped here but later hfos = respond; } else { // make a scraper and transformer log.logDebug("create scraper for url " + url); scraper = new htmlFilterContentScraper(url); hfos = new htmlFilterOutputStream(respond, scraper, transformer, (ext.length() == 0)); if (((htmlFilterOutputStream) hfos).binarySuspect()) { scraper = null; // forget it, may be rubbish log.logDebug("Content of " + url + " is probably binary. deleted scraper."); } cacheEntry.scraper = scraper; } } else { log.logDebug("Resource " + url + " has wrong extension (" + ext + ") or wrong mime-type (" + res.responseHeader.mime() + "). not scraped"); scraper = null; hfos = respond; cacheEntry.scraper = scraper; } // handle incoming cookies handleIncomingCookies(res.responseHeader, host, ip); // request has been placed and result has been returned. work off response try { respondHeader(respond, res.status, res.responseHeader); String storeError; if ((storeError = cacheEntry.shallStoreCache()) == null) { // we write a new cache entry if ((contentLength > 0) && // known (contentLength < 1048576)) {// 1 MB // ok, we don't write actually into a file, only to RAM, and schedule writing the file. byte[] cacheArray = res.writeContent(hfos); log.logDebug("writeContent of " + url + " produced cacheArray = " + ((cacheArray == null) ? "null" : ("size=" + cacheArray.length))); if (hfos instanceof htmlFilterOutputStream) ((htmlFilterOutputStream) hfos).finalize(); if (sizeBeforeDelete == -1) { // totally fresh file cacheEntry.status = plasmaHTCache.CACHE_FILL; // it's an insert cacheManager.stackProcess(cacheEntry, cacheArray); } else if (sizeBeforeDelete == cacheArray.length) { // before we came here we deleted a cache entry cacheArray = null; cacheEntry.status = plasmaHTCache.CACHE_STALE_RELOAD_BAD; cacheManager.stackProcess(cacheEntry); // unnecessary update } else { // before we came here we deleted a cache entry cacheEntry.status = plasmaHTCache.CACHE_STALE_RELOAD_GOOD; cacheManager.stackProcess(cacheEntry, cacheArray); // necessary update, write response header to cache } } else { // the file is too big to cache it in the ram, or the size is unknown // write to file right here. cacheFile.getParentFile().mkdirs(); res.writeContent(hfos, cacheFile); if (hfos instanceof htmlFilterOutputStream) ((htmlFilterOutputStream) hfos).finalize(); log.logDebug("for write-file of " + url + ": contentLength = " + contentLength + ", sizeBeforeDelete = " + sizeBeforeDelete); if (sizeBeforeDelete == -1) { // totally fresh file cacheEntry.status = plasmaHTCache.CACHE_FILL; // it's an insert cacheManager.stackProcess(cacheEntry); } else if (sizeBeforeDelete == cacheFile.length()) { // before we came here we deleted a cache entry cacheEntry.status = plasmaHTCache.CACHE_STALE_RELOAD_BAD; cacheManager.stackProcess(cacheEntry); // unnecessary update } else { // before we came here we deleted a cache entry cacheEntry.status = plasmaHTCache.CACHE_STALE_RELOAD_GOOD; cacheManager.stackProcess(cacheEntry); // necessary update, write response header to cache } // beware! all these writings will not fill the cacheEntry.cacheArray // that means they are not available for the indexer (except they are scraped before) } } else { // no caching log.logDebug(cacheFile.toString() + " not cached: " + storeError); res.writeContent(hfos, null); if (hfos instanceof htmlFilterOutputStream) ((htmlFilterOutputStream) hfos).finalize(); if (sizeBeforeDelete == -1) { // no old file and no load. just data passing cacheEntry.status = plasmaHTCache.CACHE_PASSING; cacheManager.stackProcess(cacheEntry); } else { // before we came here we deleted a cache entry cacheEntry.status = plasmaHTCache.CACHE_STALE_NO_RELOAD; cacheManager.stackProcess(cacheEntry); } } } catch (SocketException e) { // this may happen if the client suddenly closes its connection // maybe the user has stopped loading // in that case, we are not responsible and just forget it // but we clean the cache also, since it may be only partial // and most possible corrupted if (cacheFile.exists()) cacheFile.delete(); respondHeader(respond,"404 client unexpectedly closed connection", new httpHeader(null)); + } catch (IOException e) { + // can have various reasons + if (cacheFile.exists()) cacheFile.delete(); + if (e.getMessage().indexOf("Corrupt GZIP trailer") >= 0) { + // just do nothing, we leave it this way + log.logDebug("ignoring bad gzip trail for URL " + url + " (" + e.getMessage() + ")"); + } else { + respondHeader(respond,"404 client unexpectedly closed connection", new httpHeader(null)); + log.logDebug("IOError for URL " + url + " (" + e.getMessage() + ") - responded 404"); + e.printStackTrace(); + } } remote.close(); } catch (Exception e) { // this may happen if the targeted host does not exist or anything with the // remote server was wrong. // in any case, sending a 404 is appropriate try { if ((e.toString().indexOf("unknown host")) > 0) { respondHeader(respond,"404 unknown host", new httpHeader(null)); } else { respondHeader(respond,"404 Not Found", new httpHeader(null)); respond.write(("Exception occurred:\r\n").getBytes()); respond.write((e.toString() + "\r\n").getBytes()); respond.write(("[TRACE: ").getBytes()); e.printStackTrace(new PrintStream(respond)); respond.write(("]\r\n").getBytes()); } } catch (Exception ee) {} } finally { if (remote != null) httpc.returnInstance(remote); } respond.flush(); } private void respondError(OutputStream respond, String origerror, int errorcase, String url) { try { // set rewrite values serverObjects tp = new serverObjects(); tp.put("errormessage", errorcase); tp.put("httperror", origerror); tp.put("url", url); // rewrite the file File file = new File(htRootPath, "/proxymsg/error.html"); byte[] result; ByteArrayOutputStream o = new ByteArrayOutputStream(); FileInputStream fis = new FileInputStream(file); httpTemplate.writeTemplate(fis, o, tp, "-UNRESOLVED_PATTERN-".getBytes()); o.close(); result = o.toByteArray(); // return header httpHeader header = new httpHeader(); header.put("Date", httpc.dateString(httpc.nowDate())); header.put("Content-type", "text/html"); header.put("Content-length", "" + o.size()); header.put("Pragma", "no-cache"); // write the array to the client respondHeader(respond, origerror, header); serverFileUtils.write(result, respond); respond.flush(); } catch (IOException e) { } } public void doHead(Properties conProp, httpHeader requestHeader, OutputStream respond) throws IOException { String method = conProp.getProperty("METHOD"); String host = conProp.getProperty("HOST"); String path = conProp.getProperty("PATH"); String args = conProp.getProperty("ARGS"); // may be null if no args were given int port; int pos; if ((pos = host.indexOf(":")) < 0) { port = 80; } else { port = Integer.parseInt(host.substring(pos + 1)); host = host.substring(0, pos); } // check the blacklist, inspired by [AS]: respond a 404 for all AGIS (all you get is shit) servers String hostlow = host.toLowerCase(); if (blacklistedURL(hostlow, path)) { try { respondHeader(respond,"404 Not Found (AGIS)", new httpHeader(null)); respond.write(("404 (generated): URL '" + hostlow + "' blocked by yacy proxy (blacklisted)\r\n").getBytes()); respond.flush(); serverLog.logInfo("PROXY", "AGIS blocking of host '" + hostlow + "'"); // debug return; } catch (Exception ee) {} } // set another userAgent, if not yellowlisted if (!(yellowList.contains(domain(hostlow)))) { // change the User-Agent requestHeader.put("User-Agent", userAgent); } // resolve yacy and yacyh domains String yAddress = yacyCore.seedDB.resolveYacyAddress(host); // re-calc the url path String remotePath = (args == null) ? path : (path + "?" + args); // attach possible yacy-sublevel-domain if ((yAddress != null) && ((pos = yAddress.indexOf("/")) >= 0)) remotePath = yAddress.substring(pos) + remotePath; httpc remote = null; httpc.response res = null; try { // open the connection if (yAddress == null) { remote = newhttpc(host, port, timeout); } else { remote = newhttpc(yAddress, timeout); // with [AS] patch } res = remote.HEAD(remotePath, requestHeader); respondHeader(respond, res.status, res.responseHeader); } catch (Exception e) { try { respondHeader(respond,"404 Not Found", new httpHeader(null)); respond.write(("Exception occurred:\r\n").getBytes()); respond.write((e.toString() + "\r\n").getBytes()); respond.write(("[TRACE: ").getBytes()); e.printStackTrace(new PrintStream(respond)); respond.write(("]\r\n").getBytes()); } catch (Exception ee) {} } finally { if (remote != null) httpc.returnInstance(remote); } respond.flush(); } public void doPost(Properties conProp, httpHeader requestHeader, OutputStream respond, PushbackInputStream body) throws IOException { String host = conProp.getProperty("HOST"); String path = conProp.getProperty("PATH"); String args = conProp.getProperty("ARGS"); // may be null if no args were given int port; int pos; if ((pos = host.indexOf(":")) < 0) { port = 80; } else { port = Integer.parseInt(host.substring(pos + 1)); host = host.substring(0, pos); } // set another userAgent, if not yellowlisted if (!(yellowList.contains(domain(host).toLowerCase()))) { // change the User-Agent requestHeader.put("User-Agent", userAgent); } // resolve yacy and yacyh domains String yAddress = yacyCore.seedDB.resolveYacyAddress(host); // re-calc the url path String remotePath = (args == null) ? path : (path + "?" + args); // attach possible yacy-sublevel-domain if ((yAddress != null) && ((pos = yAddress.indexOf("/")) >= 0)) remotePath = yAddress.substring(pos) + remotePath; httpc remote = null; httpc.response res = null; try { if (yAddress == null) { remote = newhttpc(host, port, timeout); } else { remote = newhttpc(yAddress, timeout); } res = remote.POST(remotePath, requestHeader, body); respondHeader(respond, res.status, res.responseHeader); res.writeContent(respond, null); remote.close(); } catch (Exception e) { try { respondHeader(respond,"404 Not Found", new httpHeader(null)); respond.write(("Exception occurred:\r\n").getBytes()); respond.write((e.toString() + "\r\n").getBytes()); respond.write(("[TRACE: ").getBytes()); e.printStackTrace(new PrintStream(respond)); respond.write(("]\r\n").getBytes()); } catch (Exception ee) {} } finally { if (remote != null) httpc.returnInstance(remote); } respond.flush(); } public void doConnect(Properties conProp, de.anomic.http.httpHeader requestHeader, InputStream clientIn, OutputStream clientOut) throws IOException { String host = conProp.getProperty("HOST"); int port = Integer.parseInt(conProp.getProperty("PORT")); String httpVersion = conProp.getProperty("HTTP"); int timeout = Integer.parseInt(switchboard.getConfig("clientTimeout", "10000")); // possibly branch into PROXY-PROXY connection if (remoteProxyUse) { httpc remoteProxy = null; try { remoteProxy = httpc.getInstance(host, port, timeout, false, remoteProxyHost, remoteProxyPort); httpc.response response = remoteProxy.CONNECT(host, port, requestHeader); response.print(); if (response.success()) { // replace connection details host = remoteProxyHost; port = remoteProxyPort; // go on (see below) } else { // pass error response back to client respondHeader(clientOut, response.status, response.responseHeader); return; } } catch (Exception e) { throw new IOException(e.getMessage()); } finally { if (remoteProxy != null) httpc.returnInstance(remoteProxy); } } // try to establish connection to remote host Socket sslSocket = new Socket(host, port); sslSocket.setSoTimeout(timeout); // waiting time for write sslSocket.setSoLinger(true, timeout); // waiting time for read InputStream promiscuousIn = sslSocket.getInputStream(); OutputStream promiscuousOut = sslSocket.getOutputStream(); // now then we can return a success message clientOut.write((httpVersion + " 200 Connection established" + serverCore.crlfString + "Proxy-agent: YACY" + serverCore.crlfString + serverCore.crlfString).getBytes()); log.logInfo("SSL CONNECTION TO " + host + ":" + port + " ESTABLISHED"); // start stream passing with mediate processes try { Mediate cs = new Mediate(sslSocket, clientIn, promiscuousOut); Mediate sc = new Mediate(sslSocket, promiscuousIn, clientOut); cs.start(); sc.start(); while ((sslSocket != null) && (sslSocket.isBound()) && (!(sslSocket.isClosed())) && (sslSocket.isConnected()) && ((cs.isAlive()) || (sc.isAlive()))) { // idle try {Thread.currentThread().sleep(1000);} catch (InterruptedException e) {} // wait a while } // set stop mode cs.pleaseTerminate(); sc.pleaseTerminate(); // wake up thread cs.interrupt(); sc.interrupt(); // ...hope they have terminated... } catch (IOException e) { //System.out.println("promiscuous termination: " + e.getMessage()); } } public class Mediate extends Thread { boolean terminate; Socket socket; InputStream in; OutputStream out; public Mediate(Socket socket, InputStream in, OutputStream out) throws IOException { this.terminate = false; this.in = in; this.out = out; this.socket = socket; } public void run() { byte[] buffer = new byte[512]; int len; try { while ((socket != null) && (socket.isBound()) && (!(socket.isClosed())) && (socket.isConnected()) && (!(terminate)) && (in != null) && (out != null) && ((len = in.read(buffer)) >= 0) ) { out.write(buffer, 0, len); } } catch (IOException e) {} } public void pleaseTerminate() { terminate = true; } } private httpc newhttpc(String server, int port, int timeout) throws IOException { // a new httpc connection, combined with possible remote proxy boolean useProxy = remoteProxyUse; // check no-proxy rule if ((useProxy) && (!(remoteProxyAllowProxySet.contains(server)))) { if (remoteProxyDisallowProxySet.contains(server)) { useProxy = false; } else { // analyse remoteProxyNoProxy; // set either remoteProxyAllowProxySet or remoteProxyDisallowProxySet accordingly int i = 0; while (i < remoteProxyNoProxyPatterns.length) { if (server.matches(remoteProxyNoProxyPatterns[i])) { // disallow proxy for this server remoteProxyDisallowProxySet.add(server); useProxy = false; break; } i++; } if (i == remoteProxyNoProxyPatterns.length) { // no pattern matches: allow server remoteProxyAllowProxySet.add(server); } } } // branch to server/proxy if (useProxy) { return httpc.getInstance(server, port, timeout, false, remoteProxyHost, remoteProxyPort); } else { return httpc.getInstance(server, port, timeout, false); } } private httpc newhttpc(String address, int timeout) throws IOException { // a new httpc connection for <host>:<port>/<path> syntax // this is called when a '.yacy'-domain is used int p = address.indexOf(":"); if (p < 0) return null; String server = address.substring(0, p); address = address.substring(p + 1); // remove possible path elements (may occur for 'virtual' subdomains p = address.indexOf("/"); if (p >= 0) address = address.substring(0, p); // cut it off int port = Integer.parseInt(address); // normal creation of httpc object return newhttpc(server, port, timeout); } private void respondHeader(OutputStream respond, String status, httpHeader header) throws IOException, SocketException { // prepare header //header.put("Server", "AnomicHTTPD (www.anomic.de)"); if (!(header.containsKey("date"))) header.put("Date", httpc.dateString(httpc.nowDate())); if (!(header.containsKey("content-type"))) header.put("Content-type", "text/html"); // fix this StringBuffer headerStringBuffer = new StringBuffer(200); // write status line headerStringBuffer.append("HTTP/1.1 ") .append(status) .append("\r\n"); //System.out.println("HEADER: PROXY TO CLIENT = " + header.toString()); // DEBUG // write header Iterator i = header.keySet().iterator(); String key; String value; int pos; //System.out.println("vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv"); while (i.hasNext()) { key = (String) i.next(); if (!(key.startsWith("#"))) { // '#' in key is reserved for proxy attributes as artificial header values value = (String) header.get(key); if (!(key.equals("Location"))) while ((pos = value.lastIndexOf("#")) >= 0) { // special handling is needed if a key appeared several times, which is valid. // all lines with same key are combined in one value, separated by a "#" headerStringBuffer .append(key) .append(": ") .append(value.substring(pos + 1).trim()) .append("\r\n"); //System.out.println("#" + key + ": " + value.substring(pos + 1).trim()); value = value.substring(0, pos).trim(); } headerStringBuffer .append(key) .append(": ") .append(value) .append("\r\n"); //System.out.println("#" + key + ": " + value); } } headerStringBuffer.append("\r\n"); // end header respond.write(headerStringBuffer.toString().getBytes()); respond.flush(); } private void textMessage(OutputStream out, String body) throws IOException { out.write(("HTTP/1.1 200 OK\r\n").getBytes()); out.write(("Server: AnomicHTTPD (www.anomic.de)\r\n").getBytes()); out.write(("Date: " + httpc.dateString(httpc.nowDate()) + "\r\n").getBytes()); out.write(("Content-type: text/plain\r\n").getBytes()); out.write(("Content-length: " + body.length() +"\r\n").getBytes()); out.write(("\r\n").getBytes()); out.flush(); out.write(body.getBytes()); out.flush(); } private void transferFile(OutputStream out, File f) throws IOException { InputStream source = new FileInputStream(f); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = source.read(buffer)) > 0) out.write(buffer, 0, bytes_read); out.flush(); source.close(); } } /* proxy test: http://www.chipchapin.com/WebTools/cookietest.php? http://xlists.aza.org/moderator/cookietest/cookietest1.php http://vancouver-webpages.com/proxy/cache-test.html */
true
true
public void doGet(Properties conProp, httpHeader requestHeader, OutputStream respond) throws IOException { // prepare response // conProp : a collection of properties about the connection, like URL // requestHeader : The header lines of the connection from the request // args : the argument values of a connection, like &-values in GET and values within boundaries in POST // files : files within POST boundaries, same key as in args if (yacyTrigger) de.anomic.yacy.yacyCore.triggerOnlineAction(); Date requestDate = new Date(); // remember the time... String method = conProp.getProperty("METHOD"); String host = conProp.getProperty("HOST"); String path = conProp.getProperty("PATH"); // always starts with leading '/' String args = conProp.getProperty("ARGS"); // may be null if no args were given String ip = conProp.getProperty("CLIENTIP"); // the ip from the connecting peer int port; int pos; if ((pos = host.indexOf(":")) < 0) { port = 80; } else { port = Integer.parseInt(host.substring(pos + 1)); host = host.substring(0, pos); } String ext; if ((pos = path.lastIndexOf('.')) < 0) { ext = ""; } else { ext = path.substring(pos + 1).toLowerCase(); } URL url = null; try { if (args == null) url = new URL("http", host, port, path); else url = new URL("http", host, port, path + "?" + args); } catch (MalformedURLException e) { serverLog.logError("PROXY", "ERROR: internal error with url generation: host=" + host + ", port=" + port + ", path=" + path + ", args=" + args); url = null; } //System.out.println("GENERATED URL:" + url.toString()); // debug // check the blacklist // blacklist idea inspired by [AS]: // respond a 404 for all AGIS ("all you get is shit") servers String hostlow = host.toLowerCase(); if (blacklistedURL(hostlow, path)) { try { respondHeader(respond,"404 Not Found (AGIS)", new httpHeader(null)); respond.write(("404 (generated): URL '" + hostlow + "' blocked by yacy proxy (blacklisted)\r\n").getBytes()); respond.flush(); serverLog.logInfo("PROXY", "AGIS blocking of host '" + hostlow + "'"); // debug return; } catch (Exception ee) {} } // handle outgoing cookies handleOutgoingCookies(requestHeader, host, ip); // set another userAgent, if not yellowlisted if ((yellowList != null) && (!(yellowList.contains(domain(hostlow))))) { // change the User-Agent requestHeader.put("User-Agent", userAgent); } // set a scraper and a htmlFilter OutputStream hfos = null; htmlFilterContentScraper scraper = null; // resolve yacy and yacyh domains String yAddress = yacyCore.seedDB.resolveYacyAddress(host); // re-calc the url path String remotePath = (args == null) ? path : (path + "?" + args); // with leading '/' // attach possible yacy-sublevel-domain if ((yAddress != null) && ((pos = yAddress.indexOf("/")) >= 0) && (!(remotePath.startsWith("/env"))) // this is the special path, staying always at root-level ) remotePath = yAddress.substring(pos) + remotePath; // decide wether to use a cache entry or connect to the network File cacheFile = cacheManager.getCachePath(url); String urlHash = plasmaCrawlLURL.urlHash(url); httpHeader cachedResponseHeader = null; boolean cacheExists = ((cacheFile.exists()) && (cacheFile.isFile()) && ((cachedResponseHeader = cacheManager.getCachedResponse(urlHash)) != null)); // why are files unzipped upon arrival? why not zip all files in cache? // This follows from the following premises // (a) no file shall be unzip-ed more than once to prevent unnessesary computing time // (b) old cache entries shall be comparable with refill-entries to detect/distiguish case 3+4 // (c) the indexing mechanism needs files unzip-ed, a schedule could do that later // case b and c contradicts, if we use a scheduler, because files in a stale cache would be unzipped // and the newly arrival would be zipped and would have to be unzipped upon load. But then the // scheduler is superfluous. Therefore the only reminding case is // (d) cached files shall be either all zipped or unzipped // case d contradicts with a, because files need to be unzipped for indexing. Therefore // the only remaining case is to unzip files right upon load. Thats what we do here. // finally use existing cache if appropriate // here we must decide weather or not to save the data // to a cache // we distinguish four CACHE STATE cases: // 1. cache fill // 2. cache fresh - no refill // 3. cache stale - refill - necessary // 4. cache stale - refill - superfluous // in two of these cases we trigger a scheduler to handle newly arrived files: // case 1 and case 3 plasmaHTCache.Entry cacheEntry; if ((cacheExists) && ((cacheEntry = cacheManager.newEntry(requestDate, 0, url, requestHeader, "200 OK", cachedResponseHeader, null, switchboard.defaultProxyProfile)).shallUseCache())) { // we respond on the request by using the cache, the cache is fresh try { // replace date field in old header by actual date, this is according to RFC cachedResponseHeader.put("Date", httpc.dateString(httpc.nowDate())); // maybe the content length is missing if (!(cachedResponseHeader.containsKey("CONTENT-LENGTH"))) cachedResponseHeader.put("CONTENT-LENGTH", Long.toString(cacheFile.length())); // check if we can send a 304 instead the complete content if (requestHeader.containsKey("IF-MODIFIED-SINCE")) { // conditional request: freshness of cache for that condition was already // checked within shallUseCache(). Now send only a 304 response log.logInfo("CACHE HIT/304 " + cacheFile.toString()); // send cached header with replaced date and added length respondHeader(respond, "304 OK", cachedResponseHeader); // respond with 'not modified' } else { // unconditional request: send content of cache log.logInfo("CACHE HIT/203 " + cacheFile.toString()); // send cached header with replaced date and added length respondHeader(respond, "203 OK", cachedResponseHeader); // respond with 'non-authoritative' // make a transformer if ((!(transformer.isIdentityTransformer())) && ((ext == null) || (!(switchboard.extensionBlack.contains(ext)))) && ((cachedResponseHeader == null) || (httpd.isTextMime(cachedResponseHeader.mime(), switchboard.mimeWhite)))) { hfos = new htmlFilterOutputStream(respond, null, transformer, (ext.length() == 0)); } else { hfos = respond; } // send also the complete body now from the cache // simply read the file and transfer to out socket InputStream is = new FileInputStream(cacheFile); byte[] buffer = new byte[2048]; int l; while ((l = is.read(buffer)) > 0) {hfos.write(buffer, 0, l);} is.close(); if (hfos instanceof htmlFilterOutputStream) ((htmlFilterOutputStream) hfos).finalize(); } // that's it! } catch (SocketException e) { // this happens if the client stops loading the file // we do nothing here respondError(respond, "111 socket error: " + e.getMessage(), 1, url.toString()); } respond.flush(); return; } // the cache does either not exist or is (supposed to be) stale long sizeBeforeDelete = -1; if (cacheExists) { // delete the cache sizeBeforeDelete = cacheFile.length(); cacheFile.delete(); } // take a new file from the server httpc remote = null; httpc.response res = null; try { // open the connection if (yAddress == null) { remote = newhttpc(host, port, timeout); } else { remote = newhttpc(yAddress, timeout); } //System.out.println("HEADER: CLIENT TO PROXY = " + requestHeader.toString()); // DEBUG // send request res = remote.GET(remotePath, requestHeader); long contentLength = res.responseHeader.contentLength(); // reserver cache entry cacheEntry = cacheManager.newEntry(requestDate, 0, url, requestHeader, res.status, res.responseHeader, null, switchboard.defaultProxyProfile); // handle file types if (((ext == null) || (!(switchboard.extensionBlack.contains(ext)))) && (httpd.isTextMime(res.responseHeader.mime(), switchboard.mimeWhite))) { // this is a file that is a possible candidate for parsing by the indexer if (transformer.isIdentityTransformer()) { log.logDebug("create passthrough (parse candidate) for url " + url); // no transformation, only passthrough // this is especially the case if the bluelist is empty // in that case, the content is not scraped here but later hfos = respond; } else { // make a scraper and transformer log.logDebug("create scraper for url " + url); scraper = new htmlFilterContentScraper(url); hfos = new htmlFilterOutputStream(respond, scraper, transformer, (ext.length() == 0)); if (((htmlFilterOutputStream) hfos).binarySuspect()) { scraper = null; // forget it, may be rubbish log.logDebug("Content of " + url + " is probably binary. deleted scraper."); } cacheEntry.scraper = scraper; } } else { log.logDebug("Resource " + url + " has wrong extension (" + ext + ") or wrong mime-type (" + res.responseHeader.mime() + "). not scraped"); scraper = null; hfos = respond; cacheEntry.scraper = scraper; } // handle incoming cookies handleIncomingCookies(res.responseHeader, host, ip); // request has been placed and result has been returned. work off response try { respondHeader(respond, res.status, res.responseHeader); String storeError; if ((storeError = cacheEntry.shallStoreCache()) == null) { // we write a new cache entry if ((contentLength > 0) && // known (contentLength < 1048576)) {// 1 MB // ok, we don't write actually into a file, only to RAM, and schedule writing the file. byte[] cacheArray = res.writeContent(hfos); log.logDebug("writeContent of " + url + " produced cacheArray = " + ((cacheArray == null) ? "null" : ("size=" + cacheArray.length))); if (hfos instanceof htmlFilterOutputStream) ((htmlFilterOutputStream) hfos).finalize(); if (sizeBeforeDelete == -1) { // totally fresh file cacheEntry.status = plasmaHTCache.CACHE_FILL; // it's an insert cacheManager.stackProcess(cacheEntry, cacheArray); } else if (sizeBeforeDelete == cacheArray.length) { // before we came here we deleted a cache entry cacheArray = null; cacheEntry.status = plasmaHTCache.CACHE_STALE_RELOAD_BAD; cacheManager.stackProcess(cacheEntry); // unnecessary update } else { // before we came here we deleted a cache entry cacheEntry.status = plasmaHTCache.CACHE_STALE_RELOAD_GOOD; cacheManager.stackProcess(cacheEntry, cacheArray); // necessary update, write response header to cache } } else { // the file is too big to cache it in the ram, or the size is unknown // write to file right here. cacheFile.getParentFile().mkdirs(); res.writeContent(hfos, cacheFile); if (hfos instanceof htmlFilterOutputStream) ((htmlFilterOutputStream) hfos).finalize(); log.logDebug("for write-file of " + url + ": contentLength = " + contentLength + ", sizeBeforeDelete = " + sizeBeforeDelete); if (sizeBeforeDelete == -1) { // totally fresh file cacheEntry.status = plasmaHTCache.CACHE_FILL; // it's an insert cacheManager.stackProcess(cacheEntry); } else if (sizeBeforeDelete == cacheFile.length()) { // before we came here we deleted a cache entry cacheEntry.status = plasmaHTCache.CACHE_STALE_RELOAD_BAD; cacheManager.stackProcess(cacheEntry); // unnecessary update } else { // before we came here we deleted a cache entry cacheEntry.status = plasmaHTCache.CACHE_STALE_RELOAD_GOOD; cacheManager.stackProcess(cacheEntry); // necessary update, write response header to cache } // beware! all these writings will not fill the cacheEntry.cacheArray // that means they are not available for the indexer (except they are scraped before) } } else { // no caching log.logDebug(cacheFile.toString() + " not cached: " + storeError); res.writeContent(hfos, null); if (hfos instanceof htmlFilterOutputStream) ((htmlFilterOutputStream) hfos).finalize(); if (sizeBeforeDelete == -1) { // no old file and no load. just data passing cacheEntry.status = plasmaHTCache.CACHE_PASSING; cacheManager.stackProcess(cacheEntry); } else { // before we came here we deleted a cache entry cacheEntry.status = plasmaHTCache.CACHE_STALE_NO_RELOAD; cacheManager.stackProcess(cacheEntry); } } } catch (SocketException e) { // this may happen if the client suddenly closes its connection // maybe the user has stopped loading // in that case, we are not responsible and just forget it // but we clean the cache also, since it may be only partial // and most possible corrupted if (cacheFile.exists()) cacheFile.delete(); respondHeader(respond,"404 client unexpectedly closed connection", new httpHeader(null)); } remote.close(); } catch (Exception e) { // this may happen if the targeted host does not exist or anything with the // remote server was wrong. // in any case, sending a 404 is appropriate try { if ((e.toString().indexOf("unknown host")) > 0) { respondHeader(respond,"404 unknown host", new httpHeader(null)); } else { respondHeader(respond,"404 Not Found", new httpHeader(null)); respond.write(("Exception occurred:\r\n").getBytes()); respond.write((e.toString() + "\r\n").getBytes()); respond.write(("[TRACE: ").getBytes()); e.printStackTrace(new PrintStream(respond)); respond.write(("]\r\n").getBytes()); } } catch (Exception ee) {} } finally { if (remote != null) httpc.returnInstance(remote); } respond.flush(); }
public void doGet(Properties conProp, httpHeader requestHeader, OutputStream respond) throws IOException { // prepare response // conProp : a collection of properties about the connection, like URL // requestHeader : The header lines of the connection from the request // args : the argument values of a connection, like &-values in GET and values within boundaries in POST // files : files within POST boundaries, same key as in args if (yacyTrigger) de.anomic.yacy.yacyCore.triggerOnlineAction(); Date requestDate = new Date(); // remember the time... String method = conProp.getProperty("METHOD"); String host = conProp.getProperty("HOST"); String path = conProp.getProperty("PATH"); // always starts with leading '/' String args = conProp.getProperty("ARGS"); // may be null if no args were given String ip = conProp.getProperty("CLIENTIP"); // the ip from the connecting peer int port; int pos; if ((pos = host.indexOf(":")) < 0) { port = 80; } else { port = Integer.parseInt(host.substring(pos + 1)); host = host.substring(0, pos); } String ext; if ((pos = path.lastIndexOf('.')) < 0) { ext = ""; } else { ext = path.substring(pos + 1).toLowerCase(); } URL url = null; try { if (args == null) url = new URL("http", host, port, path); else url = new URL("http", host, port, path + "?" + args); } catch (MalformedURLException e) { serverLog.logError("PROXY", "ERROR: internal error with url generation: host=" + host + ", port=" + port + ", path=" + path + ", args=" + args); url = null; } //System.out.println("GENERATED URL:" + url.toString()); // debug // check the blacklist // blacklist idea inspired by [AS]: // respond a 404 for all AGIS ("all you get is shit") servers String hostlow = host.toLowerCase(); if (blacklistedURL(hostlow, path)) { try { respondHeader(respond,"404 Not Found (AGIS)", new httpHeader(null)); respond.write(("404 (generated): URL '" + hostlow + "' blocked by yacy proxy (blacklisted)\r\n").getBytes()); respond.flush(); serverLog.logInfo("PROXY", "AGIS blocking of host '" + hostlow + "'"); // debug return; } catch (Exception ee) {} } // handle outgoing cookies handleOutgoingCookies(requestHeader, host, ip); // set another userAgent, if not yellowlisted if ((yellowList != null) && (!(yellowList.contains(domain(hostlow))))) { // change the User-Agent requestHeader.put("User-Agent", userAgent); } // set a scraper and a htmlFilter OutputStream hfos = null; htmlFilterContentScraper scraper = null; // resolve yacy and yacyh domains String yAddress = yacyCore.seedDB.resolveYacyAddress(host); // re-calc the url path String remotePath = (args == null) ? path : (path + "?" + args); // with leading '/' // attach possible yacy-sublevel-domain if ((yAddress != null) && ((pos = yAddress.indexOf("/")) >= 0) && (!(remotePath.startsWith("/env"))) // this is the special path, staying always at root-level ) remotePath = yAddress.substring(pos) + remotePath; // decide wether to use a cache entry or connect to the network File cacheFile = cacheManager.getCachePath(url); String urlHash = plasmaCrawlLURL.urlHash(url); httpHeader cachedResponseHeader = null; boolean cacheExists = ((cacheFile.exists()) && (cacheFile.isFile()) && ((cachedResponseHeader = cacheManager.getCachedResponse(urlHash)) != null)); // why are files unzipped upon arrival? why not zip all files in cache? // This follows from the following premises // (a) no file shall be unzip-ed more than once to prevent unnessesary computing time // (b) old cache entries shall be comparable with refill-entries to detect/distiguish case 3+4 // (c) the indexing mechanism needs files unzip-ed, a schedule could do that later // case b and c contradicts, if we use a scheduler, because files in a stale cache would be unzipped // and the newly arrival would be zipped and would have to be unzipped upon load. But then the // scheduler is superfluous. Therefore the only reminding case is // (d) cached files shall be either all zipped or unzipped // case d contradicts with a, because files need to be unzipped for indexing. Therefore // the only remaining case is to unzip files right upon load. Thats what we do here. // finally use existing cache if appropriate // here we must decide weather or not to save the data // to a cache // we distinguish four CACHE STATE cases: // 1. cache fill // 2. cache fresh - no refill // 3. cache stale - refill - necessary // 4. cache stale - refill - superfluous // in two of these cases we trigger a scheduler to handle newly arrived files: // case 1 and case 3 plasmaHTCache.Entry cacheEntry; if ((cacheExists) && ((cacheEntry = cacheManager.newEntry(requestDate, 0, url, requestHeader, "200 OK", cachedResponseHeader, null, switchboard.defaultProxyProfile)).shallUseCache())) { // we respond on the request by using the cache, the cache is fresh try { // replace date field in old header by actual date, this is according to RFC cachedResponseHeader.put("Date", httpc.dateString(httpc.nowDate())); // maybe the content length is missing if (!(cachedResponseHeader.containsKey("CONTENT-LENGTH"))) cachedResponseHeader.put("CONTENT-LENGTH", Long.toString(cacheFile.length())); // check if we can send a 304 instead the complete content if (requestHeader.containsKey("IF-MODIFIED-SINCE")) { // conditional request: freshness of cache for that condition was already // checked within shallUseCache(). Now send only a 304 response log.logInfo("CACHE HIT/304 " + cacheFile.toString()); // send cached header with replaced date and added length respondHeader(respond, "304 OK", cachedResponseHeader); // respond with 'not modified' } else { // unconditional request: send content of cache log.logInfo("CACHE HIT/203 " + cacheFile.toString()); // send cached header with replaced date and added length respondHeader(respond, "203 OK", cachedResponseHeader); // respond with 'non-authoritative' // make a transformer if ((!(transformer.isIdentityTransformer())) && ((ext == null) || (!(switchboard.extensionBlack.contains(ext)))) && ((cachedResponseHeader == null) || (httpd.isTextMime(cachedResponseHeader.mime(), switchboard.mimeWhite)))) { hfos = new htmlFilterOutputStream(respond, null, transformer, (ext.length() == 0)); } else { hfos = respond; } // send also the complete body now from the cache // simply read the file and transfer to out socket InputStream is = new FileInputStream(cacheFile); byte[] buffer = new byte[2048]; int l; while ((l = is.read(buffer)) > 0) {hfos.write(buffer, 0, l);} is.close(); if (hfos instanceof htmlFilterOutputStream) ((htmlFilterOutputStream) hfos).finalize(); } // that's it! } catch (SocketException e) { // this happens if the client stops loading the file // we do nothing here respondError(respond, "111 socket error: " + e.getMessage(), 1, url.toString()); } respond.flush(); return; } // the cache does either not exist or is (supposed to be) stale long sizeBeforeDelete = -1; if (cacheExists) { // delete the cache sizeBeforeDelete = cacheFile.length(); cacheFile.delete(); } // take a new file from the server httpc remote = null; httpc.response res = null; try { // open the connection if (yAddress == null) { remote = newhttpc(host, port, timeout); } else { remote = newhttpc(yAddress, timeout); } //System.out.println("HEADER: CLIENT TO PROXY = " + requestHeader.toString()); // DEBUG // send request res = remote.GET(remotePath, requestHeader); long contentLength = res.responseHeader.contentLength(); // reserver cache entry cacheEntry = cacheManager.newEntry(requestDate, 0, url, requestHeader, res.status, res.responseHeader, null, switchboard.defaultProxyProfile); // handle file types if (((ext == null) || (!(switchboard.extensionBlack.contains(ext)))) && (httpd.isTextMime(res.responseHeader.mime(), switchboard.mimeWhite))) { // this is a file that is a possible candidate for parsing by the indexer if (transformer.isIdentityTransformer()) { log.logDebug("create passthrough (parse candidate) for url " + url); // no transformation, only passthrough // this is especially the case if the bluelist is empty // in that case, the content is not scraped here but later hfos = respond; } else { // make a scraper and transformer log.logDebug("create scraper for url " + url); scraper = new htmlFilterContentScraper(url); hfos = new htmlFilterOutputStream(respond, scraper, transformer, (ext.length() == 0)); if (((htmlFilterOutputStream) hfos).binarySuspect()) { scraper = null; // forget it, may be rubbish log.logDebug("Content of " + url + " is probably binary. deleted scraper."); } cacheEntry.scraper = scraper; } } else { log.logDebug("Resource " + url + " has wrong extension (" + ext + ") or wrong mime-type (" + res.responseHeader.mime() + "). not scraped"); scraper = null; hfos = respond; cacheEntry.scraper = scraper; } // handle incoming cookies handleIncomingCookies(res.responseHeader, host, ip); // request has been placed and result has been returned. work off response try { respondHeader(respond, res.status, res.responseHeader); String storeError; if ((storeError = cacheEntry.shallStoreCache()) == null) { // we write a new cache entry if ((contentLength > 0) && // known (contentLength < 1048576)) {// 1 MB // ok, we don't write actually into a file, only to RAM, and schedule writing the file. byte[] cacheArray = res.writeContent(hfos); log.logDebug("writeContent of " + url + " produced cacheArray = " + ((cacheArray == null) ? "null" : ("size=" + cacheArray.length))); if (hfos instanceof htmlFilterOutputStream) ((htmlFilterOutputStream) hfos).finalize(); if (sizeBeforeDelete == -1) { // totally fresh file cacheEntry.status = plasmaHTCache.CACHE_FILL; // it's an insert cacheManager.stackProcess(cacheEntry, cacheArray); } else if (sizeBeforeDelete == cacheArray.length) { // before we came here we deleted a cache entry cacheArray = null; cacheEntry.status = plasmaHTCache.CACHE_STALE_RELOAD_BAD; cacheManager.stackProcess(cacheEntry); // unnecessary update } else { // before we came here we deleted a cache entry cacheEntry.status = plasmaHTCache.CACHE_STALE_RELOAD_GOOD; cacheManager.stackProcess(cacheEntry, cacheArray); // necessary update, write response header to cache } } else { // the file is too big to cache it in the ram, or the size is unknown // write to file right here. cacheFile.getParentFile().mkdirs(); res.writeContent(hfos, cacheFile); if (hfos instanceof htmlFilterOutputStream) ((htmlFilterOutputStream) hfos).finalize(); log.logDebug("for write-file of " + url + ": contentLength = " + contentLength + ", sizeBeforeDelete = " + sizeBeforeDelete); if (sizeBeforeDelete == -1) { // totally fresh file cacheEntry.status = plasmaHTCache.CACHE_FILL; // it's an insert cacheManager.stackProcess(cacheEntry); } else if (sizeBeforeDelete == cacheFile.length()) { // before we came here we deleted a cache entry cacheEntry.status = plasmaHTCache.CACHE_STALE_RELOAD_BAD; cacheManager.stackProcess(cacheEntry); // unnecessary update } else { // before we came here we deleted a cache entry cacheEntry.status = plasmaHTCache.CACHE_STALE_RELOAD_GOOD; cacheManager.stackProcess(cacheEntry); // necessary update, write response header to cache } // beware! all these writings will not fill the cacheEntry.cacheArray // that means they are not available for the indexer (except they are scraped before) } } else { // no caching log.logDebug(cacheFile.toString() + " not cached: " + storeError); res.writeContent(hfos, null); if (hfos instanceof htmlFilterOutputStream) ((htmlFilterOutputStream) hfos).finalize(); if (sizeBeforeDelete == -1) { // no old file and no load. just data passing cacheEntry.status = plasmaHTCache.CACHE_PASSING; cacheManager.stackProcess(cacheEntry); } else { // before we came here we deleted a cache entry cacheEntry.status = plasmaHTCache.CACHE_STALE_NO_RELOAD; cacheManager.stackProcess(cacheEntry); } } } catch (SocketException e) { // this may happen if the client suddenly closes its connection // maybe the user has stopped loading // in that case, we are not responsible and just forget it // but we clean the cache also, since it may be only partial // and most possible corrupted if (cacheFile.exists()) cacheFile.delete(); respondHeader(respond,"404 client unexpectedly closed connection", new httpHeader(null)); } catch (IOException e) { // can have various reasons if (cacheFile.exists()) cacheFile.delete(); if (e.getMessage().indexOf("Corrupt GZIP trailer") >= 0) { // just do nothing, we leave it this way log.logDebug("ignoring bad gzip trail for URL " + url + " (" + e.getMessage() + ")"); } else { respondHeader(respond,"404 client unexpectedly closed connection", new httpHeader(null)); log.logDebug("IOError for URL " + url + " (" + e.getMessage() + ") - responded 404"); e.printStackTrace(); } } remote.close(); } catch (Exception e) { // this may happen if the targeted host does not exist or anything with the // remote server was wrong. // in any case, sending a 404 is appropriate try { if ((e.toString().indexOf("unknown host")) > 0) { respondHeader(respond,"404 unknown host", new httpHeader(null)); } else { respondHeader(respond,"404 Not Found", new httpHeader(null)); respond.write(("Exception occurred:\r\n").getBytes()); respond.write((e.toString() + "\r\n").getBytes()); respond.write(("[TRACE: ").getBytes()); e.printStackTrace(new PrintStream(respond)); respond.write(("]\r\n").getBytes()); } } catch (Exception ee) {} } finally { if (remote != null) httpc.returnInstance(remote); } respond.flush(); }
diff --git a/src/fr/iutvalence/ubpe/main/UBPE2013SerialRadioRelayClientLocalAndRemotewithLocalStorage.java b/src/fr/iutvalence/ubpe/main/UBPE2013SerialRadioRelayClientLocalAndRemotewithLocalStorage.java index dd8f4c1..754e2dc 100644 --- a/src/fr/iutvalence/ubpe/main/UBPE2013SerialRadioRelayClientLocalAndRemotewithLocalStorage.java +++ b/src/fr/iutvalence/ubpe/main/UBPE2013SerialRadioRelayClientLocalAndRemotewithLocalStorage.java @@ -1,147 +1,147 @@ package fr.iutvalence.ubpe.main; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.net.InetSocketAddress; import java.util.HashMap; import java.util.Map; import fr.iutvalence.ubpe.commons.services.RawFileSystemStorageDataEventListenerService; import fr.iutvalence.ubpe.commons.services.SystemOutDebugDataEventListenerService; import fr.iutvalence.ubpe.commons.services.UBPEInputStreamDataEventReaderService; import fr.iutvalence.ubpe.commons.services.WebFrontEndExporterDataEventListenerService; import fr.iutvalence.ubpe.core.helpers.RawDataEventFileSystemStorage; import fr.iutvalence.ubpe.core.helpers.Serial600InputStream; import fr.iutvalence.ubpe.core.helpers.UBPEDataEventParserForwarder; import fr.iutvalence.ubpe.core.interfaces.DataEventParserForwarder; import gnu.io.NoSuchPortException; import gnu.io.PortInUseException; import gnu.io.UnsupportedCommOperationException; public class UBPE2013SerialRadioRelayClientLocalAndRemotewithLocalStorage { /** * @param args * @throws */ public static void main(String[] args) { // args[0] station name // args[1] serial port identifier // args[2] relay server IP // args[3] relay server port // args[4] object name if (args.length != 5) { System.err.println("Missing arguments, exiting..."); // System.err.println("(expected IP and port for local binding)"); System.exit(1); } // files are stored in current directory, under "station name" subfolder System.out.println("Trying to configure serial port " + args[1] + " ..."); Serial600InputStream in = null; try { in = new Serial600InputStream(args[1]); } catch (PortInUseException e) { System.err.println("Serial port is already in use, please close it before running this application again"); System.exit(1); } catch (NoSuchPortException e) { System.err.println("Specified port (" + args[1] + ") does not exist, please check serial port name before running this application again"); System.exit(1); } catch (UnsupportedCommOperationException e) { System.err.println("Specified port (" + args[1] + ") can not be configured properly, please check it before running this application again"); System.exit(1); } catch (IOException e) { System.err.println("Unable to read from specified port (" + args[1] + "), please check it before running this application again"); System.exit(1); } System.out.println("... done"); System.out.println("Creating and registering ubpe2013 event parser ..."); UBPEDataEventParserForwarder ubpe2013Parser = new UBPEDataEventParserForwarder(fr.iutvalence.ubpe.ubpe2013.UBPE2013DataEvent.class, "UBPE2013"); Map<String, DataEventParserForwarder> parsers = new HashMap<String, DataEventParserForwarder>(); parsers.put("UBPE2013", ubpe2013Parser); System.out.println("... done"); System.out.println("Creating console debug service ..."); SystemOutDebugDataEventListenerService debugService = new SystemOutDebugDataEventListenerService(); System.out.println("... done"); System.out.println("Creating raw filesystem storage service ..."); RawDataEventFileSystemStorage storage = null; RawFileSystemStorageDataEventListenerService storageService = null; try { storage = new RawDataEventFileSystemStorage(args[0] + "-storage", new File(args[0])); storageService = new RawFileSystemStorageDataEventListenerService(storage); } catch (FileNotFoundException e1) { System.err.println("Unable to create subdir in working directory, check permissions"); System.exit(1); } System.out.println("... done"); System.out.println("Creating remote Web frontend exporter service ..."); WebFrontEndExporterDataEventListenerService remoteExporterService = new WebFrontEndExporterDataEventListenerService(new InetSocketAddress(args[2], Integer.parseInt(args[3]))); System.out.println("... done"); System.out.println("Creating local Web frontend exporter service ..."); - WebFrontEndExporterDataEventListenerService localExporterService = new WebFrontEndExporterDataEventListenerService(new InetSocketAddress(Integer.parseInt(args[3]))); + WebFrontEndExporterDataEventListenerService localExporterService = new WebFrontEndExporterDataEventListenerService(new InetSocketAddress("127.0.0.1", Integer.parseInt(args[3]))); System.out.println("... done"); System.out.println("Registering console debug service as a parser listener ..."); ubpe2013Parser.registerDataEventListener(debugService); System.out.println("... done"); System.out.println("Registering raw filesystem storage service as a parser listener ..."); ubpe2013Parser.registerDataEventListener(storageService); System.out.println("... done"); System.out.println("Registering remote Web frontend exporter service as a parser listener ..."); ubpe2013Parser.registerDataEventListener(remoteExporterService); System.out.println("... done"); System.out.println("Registering local Web frontend exporter service as a parser listener ..."); ubpe2013Parser.registerDataEventListener(localExporterService); System.out.println("... done"); System.out.println("Starting console debug service ..."); new Thread(debugService).start(); System.out.println("... done"); System.out.println("Starting raw filesystem storage service ..."); new Thread(storageService).start(); System.out.println("... done"); System.out.println("Starting remote Web frontend exporter service ..."); new Thread(remoteExporterService).start(); System.out.println("... done"); System.out.println("Starting local Web frontend exporter service ..."); new Thread(localExporterService).start(); System.out.println("... done"); System.out.println("Starting serial event reader service ..."); UBPEInputStreamDataEventReaderService readerService = new UBPEInputStreamDataEventReaderService(in, parsers, "UBPE2013", args[0]); new Thread(readerService).start(); System.out.println("... done"); System.out.println("Initialization completed."); } }
true
true
public static void main(String[] args) { // args[0] station name // args[1] serial port identifier // args[2] relay server IP // args[3] relay server port // args[4] object name if (args.length != 5) { System.err.println("Missing arguments, exiting..."); // System.err.println("(expected IP and port for local binding)"); System.exit(1); } // files are stored in current directory, under "station name" subfolder System.out.println("Trying to configure serial port " + args[1] + " ..."); Serial600InputStream in = null; try { in = new Serial600InputStream(args[1]); } catch (PortInUseException e) { System.err.println("Serial port is already in use, please close it before running this application again"); System.exit(1); } catch (NoSuchPortException e) { System.err.println("Specified port (" + args[1] + ") does not exist, please check serial port name before running this application again"); System.exit(1); } catch (UnsupportedCommOperationException e) { System.err.println("Specified port (" + args[1] + ") can not be configured properly, please check it before running this application again"); System.exit(1); } catch (IOException e) { System.err.println("Unable to read from specified port (" + args[1] + "), please check it before running this application again"); System.exit(1); } System.out.println("... done"); System.out.println("Creating and registering ubpe2013 event parser ..."); UBPEDataEventParserForwarder ubpe2013Parser = new UBPEDataEventParserForwarder(fr.iutvalence.ubpe.ubpe2013.UBPE2013DataEvent.class, "UBPE2013"); Map<String, DataEventParserForwarder> parsers = new HashMap<String, DataEventParserForwarder>(); parsers.put("UBPE2013", ubpe2013Parser); System.out.println("... done"); System.out.println("Creating console debug service ..."); SystemOutDebugDataEventListenerService debugService = new SystemOutDebugDataEventListenerService(); System.out.println("... done"); System.out.println("Creating raw filesystem storage service ..."); RawDataEventFileSystemStorage storage = null; RawFileSystemStorageDataEventListenerService storageService = null; try { storage = new RawDataEventFileSystemStorage(args[0] + "-storage", new File(args[0])); storageService = new RawFileSystemStorageDataEventListenerService(storage); } catch (FileNotFoundException e1) { System.err.println("Unable to create subdir in working directory, check permissions"); System.exit(1); } System.out.println("... done"); System.out.println("Creating remote Web frontend exporter service ..."); WebFrontEndExporterDataEventListenerService remoteExporterService = new WebFrontEndExporterDataEventListenerService(new InetSocketAddress(args[2], Integer.parseInt(args[3]))); System.out.println("... done"); System.out.println("Creating local Web frontend exporter service ..."); WebFrontEndExporterDataEventListenerService localExporterService = new WebFrontEndExporterDataEventListenerService(new InetSocketAddress(Integer.parseInt(args[3]))); System.out.println("... done"); System.out.println("Registering console debug service as a parser listener ..."); ubpe2013Parser.registerDataEventListener(debugService); System.out.println("... done"); System.out.println("Registering raw filesystem storage service as a parser listener ..."); ubpe2013Parser.registerDataEventListener(storageService); System.out.println("... done"); System.out.println("Registering remote Web frontend exporter service as a parser listener ..."); ubpe2013Parser.registerDataEventListener(remoteExporterService); System.out.println("... done"); System.out.println("Registering local Web frontend exporter service as a parser listener ..."); ubpe2013Parser.registerDataEventListener(localExporterService); System.out.println("... done"); System.out.println("Starting console debug service ..."); new Thread(debugService).start(); System.out.println("... done"); System.out.println("Starting raw filesystem storage service ..."); new Thread(storageService).start(); System.out.println("... done"); System.out.println("Starting remote Web frontend exporter service ..."); new Thread(remoteExporterService).start(); System.out.println("... done"); System.out.println("Starting local Web frontend exporter service ..."); new Thread(localExporterService).start(); System.out.println("... done"); System.out.println("Starting serial event reader service ..."); UBPEInputStreamDataEventReaderService readerService = new UBPEInputStreamDataEventReaderService(in, parsers, "UBPE2013", args[0]); new Thread(readerService).start(); System.out.println("... done"); System.out.println("Initialization completed."); }
public static void main(String[] args) { // args[0] station name // args[1] serial port identifier // args[2] relay server IP // args[3] relay server port // args[4] object name if (args.length != 5) { System.err.println("Missing arguments, exiting..."); // System.err.println("(expected IP and port for local binding)"); System.exit(1); } // files are stored in current directory, under "station name" subfolder System.out.println("Trying to configure serial port " + args[1] + " ..."); Serial600InputStream in = null; try { in = new Serial600InputStream(args[1]); } catch (PortInUseException e) { System.err.println("Serial port is already in use, please close it before running this application again"); System.exit(1); } catch (NoSuchPortException e) { System.err.println("Specified port (" + args[1] + ") does not exist, please check serial port name before running this application again"); System.exit(1); } catch (UnsupportedCommOperationException e) { System.err.println("Specified port (" + args[1] + ") can not be configured properly, please check it before running this application again"); System.exit(1); } catch (IOException e) { System.err.println("Unable to read from specified port (" + args[1] + "), please check it before running this application again"); System.exit(1); } System.out.println("... done"); System.out.println("Creating and registering ubpe2013 event parser ..."); UBPEDataEventParserForwarder ubpe2013Parser = new UBPEDataEventParserForwarder(fr.iutvalence.ubpe.ubpe2013.UBPE2013DataEvent.class, "UBPE2013"); Map<String, DataEventParserForwarder> parsers = new HashMap<String, DataEventParserForwarder>(); parsers.put("UBPE2013", ubpe2013Parser); System.out.println("... done"); System.out.println("Creating console debug service ..."); SystemOutDebugDataEventListenerService debugService = new SystemOutDebugDataEventListenerService(); System.out.println("... done"); System.out.println("Creating raw filesystem storage service ..."); RawDataEventFileSystemStorage storage = null; RawFileSystemStorageDataEventListenerService storageService = null; try { storage = new RawDataEventFileSystemStorage(args[0] + "-storage", new File(args[0])); storageService = new RawFileSystemStorageDataEventListenerService(storage); } catch (FileNotFoundException e1) { System.err.println("Unable to create subdir in working directory, check permissions"); System.exit(1); } System.out.println("... done"); System.out.println("Creating remote Web frontend exporter service ..."); WebFrontEndExporterDataEventListenerService remoteExporterService = new WebFrontEndExporterDataEventListenerService(new InetSocketAddress(args[2], Integer.parseInt(args[3]))); System.out.println("... done"); System.out.println("Creating local Web frontend exporter service ..."); WebFrontEndExporterDataEventListenerService localExporterService = new WebFrontEndExporterDataEventListenerService(new InetSocketAddress("127.0.0.1", Integer.parseInt(args[3]))); System.out.println("... done"); System.out.println("Registering console debug service as a parser listener ..."); ubpe2013Parser.registerDataEventListener(debugService); System.out.println("... done"); System.out.println("Registering raw filesystem storage service as a parser listener ..."); ubpe2013Parser.registerDataEventListener(storageService); System.out.println("... done"); System.out.println("Registering remote Web frontend exporter service as a parser listener ..."); ubpe2013Parser.registerDataEventListener(remoteExporterService); System.out.println("... done"); System.out.println("Registering local Web frontend exporter service as a parser listener ..."); ubpe2013Parser.registerDataEventListener(localExporterService); System.out.println("... done"); System.out.println("Starting console debug service ..."); new Thread(debugService).start(); System.out.println("... done"); System.out.println("Starting raw filesystem storage service ..."); new Thread(storageService).start(); System.out.println("... done"); System.out.println("Starting remote Web frontend exporter service ..."); new Thread(remoteExporterService).start(); System.out.println("... done"); System.out.println("Starting local Web frontend exporter service ..."); new Thread(localExporterService).start(); System.out.println("... done"); System.out.println("Starting serial event reader service ..."); UBPEInputStreamDataEventReaderService readerService = new UBPEInputStreamDataEventReaderService(in, parsers, "UBPE2013", args[0]); new Thread(readerService).start(); System.out.println("... done"); System.out.println("Initialization completed."); }
diff --git a/org.eclipse.mylyn.tests/src/org/eclipse/mylyn/tests/misc/AllMiscTests.java b/org.eclipse.mylyn.tests/src/org/eclipse/mylyn/tests/misc/AllMiscTests.java index af2fa9a..3728f32 100644 --- a/org.eclipse.mylyn.tests/src/org/eclipse/mylyn/tests/misc/AllMiscTests.java +++ b/org.eclipse.mylyn.tests/src/org/eclipse/mylyn/tests/misc/AllMiscTests.java @@ -1,34 +1,34 @@ /******************************************************************************* * Copyright (c) 2004 - 2005 University Of British Columbia and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * University Of British Columbia - initial API and implementation *******************************************************************************/ package org.eclipse.mylar.tests.misc; import junit.framework.Test; import junit.framework.TestSuite; /** * @author Mik Kersten */ public class AllMiscTests { public static Test suite() { TestSuite suite = new TestSuite( "Test for org.eclipse.mylar.tests"); //$JUnit-BEGIN$ // suite.addTestSuite(SharedTaskFolderTest.class); +// suite.addTestSuite(BugzillaSearchPluginTest.class); suite.addTestSuite(HypertextStructureBridgeTest.class); - suite.addTestSuite(BugzillaSearchPluginTest.class); suite.addTestSuite(BugzillaStackTraceTest.class); //$JUnit-END$ return suite; } }
false
true
public static Test suite() { TestSuite suite = new TestSuite( "Test for org.eclipse.mylar.tests"); //$JUnit-BEGIN$ // suite.addTestSuite(SharedTaskFolderTest.class); suite.addTestSuite(HypertextStructureBridgeTest.class); suite.addTestSuite(BugzillaSearchPluginTest.class); suite.addTestSuite(BugzillaStackTraceTest.class); //$JUnit-END$ return suite; }
public static Test suite() { TestSuite suite = new TestSuite( "Test for org.eclipse.mylar.tests"); //$JUnit-BEGIN$ // suite.addTestSuite(SharedTaskFolderTest.class); // suite.addTestSuite(BugzillaSearchPluginTest.class); suite.addTestSuite(HypertextStructureBridgeTest.class); suite.addTestSuite(BugzillaStackTraceTest.class); //$JUnit-END$ return suite; }
diff --git a/web-core/src/main/java/com/silverpeas/servlets/upload/AjaxFileUploadServlet.java b/web-core/src/main/java/com/silverpeas/servlets/upload/AjaxFileUploadServlet.java index e23f04266a..233c386d76 100644 --- a/web-core/src/main/java/com/silverpeas/servlets/upload/AjaxFileUploadServlet.java +++ b/web-core/src/main/java/com/silverpeas/servlets/upload/AjaxFileUploadServlet.java @@ -1,247 +1,250 @@ /** * Copyright (C) 2000 - 2013 Silverpeas * * This program is free software: you can redistribute it and/or modify it under the terms of the * GNU Affero General Public License as published by the Free Software Foundation, either version 3 * of the License, or (at your option) any later version. * * As a special exception to the terms and conditions of version 3.0 of the GPL, you may * redistribute this Program in connection with Free/Libre Open Source Software ("FLOSS") * applications as described in Silverpeas's FLOSS exception. You should have received a copy of the * text describing the FLOSS exception, and it is also available here: * "http://www.silverpeas.org/docs/core/legal/floss_exception.html" * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. * If not, see <http://www.gnu.org/licenses/>. */ package com.silverpeas.servlets.upload; import com.silverpeas.util.StringUtil; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import org.codehaus.jackson.map.ObjectMapper; /** * Sample servlet to upload file in an ajax way. * * @author ehugonnet */ public class AjaxFileUploadServlet extends HttpServlet { private static final long serialVersionUID = -557782586447656336L; private static final String UPLOAD_DIRECTORY = "UPLOAD_DIRECTORY"; private static final String WHITE_LIST = "WHITE_LIST"; private static final String FILE_UPLOAD_STATS = "FILE_UPLOAD_STATS"; private static final String FILE_UPLOAD_PATHS = "FILE_UPLOAD_PATHS"; private static String uploadDir; private static String whiteList; @Override public void init(ServletConfig config) throws ServletException { super.init(config); uploadDir = config.getInitParameter(UPLOAD_DIRECTORY); whiteList = config.getInitParameter(WHITE_LIST); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); if ("status".equals(request.getParameter("q"))) { doStatus(session, response); } else { doFileUpload(session, request, response); } } /** * Do the effective upload of files. * * @param session the HttpSession * @param request the multpart request * @param response the response * @throws IOException */ @SuppressWarnings("unchecked") private void doFileUpload(HttpSession session, HttpServletRequest request, HttpServletResponse response) throws IOException { try { FileUploadListener listener = new FileUploadListener(request.getContentLength()); session.setAttribute(FILE_UPLOAD_STATS, listener.getFileUploadStats()); FileItemFactory factory = new MonitoringFileItemFactory(listener); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = (List<FileItem>) upload.parseRequest(request); boolean hasError = false; String errorMessage = ""; List<String> paths = new ArrayList<String>(items.size()); session.setAttribute(FILE_UPLOAD_PATHS, paths); for (FileItem fileItem : items) { if (!fileItem.isFormField() && fileItem.getSize() > 0L) { String filename = fileItem.getName(); if (filename.indexOf('/') >= 0) { filename = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.indexOf('\\') >= 0) { filename = filename.substring(filename.lastIndexOf('\\') + 1); } if (!isInWhiteList(filename)) { hasError = true; - errorMessage += "The file " + filename - + " isn't uploaded! Only HTML files can be uploaded<br/>"; + errorMessage += "The file " + filename + " is not uploaded!"; + errorMessage += (StringUtil.isDefined(whiteList) ? " Only " + whiteList.replaceAll( + " ", ", ") + + " file types can be uploaded<br/>" + : " No allowed file format has been defined for upload<br/>"); } else { filename = System.currentTimeMillis() + "-" + filename; File targetDirectory = new File(uploadDir, fileItem.getFieldName()); targetDirectory.mkdirs(); File uploadedFile = new File(targetDirectory, filename); OutputStream out = null; try { out = new FileOutputStream(uploadedFile); IOUtils.copy(fileItem.getInputStream(), out); paths.add(uploadedFile.getParentFile().getName() + '/' + uploadedFile.getName()); } finally { IOUtils.closeQuietly(out); } fileItem.delete(); } } } String uploadedFiles = getUploadedFilePaths(paths); if (!hasError) { sendCompleteResponse(response, uploadedFiles, null); } else { sendCompleteResponse(response, uploadedFiles, errorMessage); } } catch (Exception e) { Logger.getLogger(getClass().getSimpleName()).log(Level.WARNING, e.getMessage()); sendCompleteResponse(response, "[]", "Could not process uploaded file. Please see log for details."); } } /** * Return the current status of the upload. * * @param session the HttpSession. * @param response where the status is to be written. * @throws IOException */ private void doStatus(HttpSession session, HttpServletResponse response) throws IOException { // Make sure the status response is not cached by the browser response.addHeader("Expires", "0"); response.addHeader("Cache-Control", "no-store, no-cache, must-revalidate"); response.addHeader("Cache-Control", "post-check=0, pre-check=0"); response.addHeader("Pragma", "no-cache"); FileUploadListener.FileUploadStats fileUploadStats = (FileUploadListener.FileUploadStats) session.getAttribute(FILE_UPLOAD_STATS); if (fileUploadStats != null) { long bytesProcessed = fileUploadStats.getBytesRead(); long sizeTotal = fileUploadStats.getTotalSize(); long percentComplete = (long) Math.floor(((double) bytesProcessed / (double) sizeTotal) * 100.0); response.getWriter().println("<b>Upload Status:</b><br/>"); if (fileUploadStats.getBytesRead() != fileUploadStats.getTotalSize()) { response.getWriter().println( "<div class=\"prog-border\"><div class=\"prog-bar\" style=\"width: " + percentComplete + "%;\"></div></div>"); } else { response .getWriter() .println( "<div class=\"prog-border\"><div class=\"prog-bar\" style=\"width: 100%;\"></div></div>"); response.getWriter().println("Complete.<br/>"); } } if (fileUploadStats != null && fileUploadStats.getBytesRead() == fileUploadStats.getTotalSize()) { List<String> paths = (List<String>) session.getAttribute(FILE_UPLOAD_PATHS); String uploadedFilePaths = getUploadedFilePaths(paths); response.getWriter().println( "<b>Upload complete.</b>"); response.getWriter().println( "<script type='text/javascript'>window.parent.stop('', " + uploadedFilePaths + "); stop('', " + uploadedFilePaths + ");</script>"); } } /** * Send the response after the upload. * * @param response the HttpServletResponse. * @param paths the paths to the uploaded files. * @param message the error message. * @throws IOException */ private void sendCompleteResponse(HttpServletResponse response, String paths, String message) throws IOException { if (message == null) { response .getOutputStream() .print( "<html><head><script type='text/javascript'>function killUpdate() { window.parent.stop('', " + paths + " ); }</script></head><body onload='killUpdate()'></body></html>"); } else { response .getOutputStream() .print( "<html><head><script type='text/javascript'>function killUpdate() { window.parent.stop('" + message + "', ''); }</script></head><body onload='killUpdate()'></body></html>"); } } /** * Compute a javascript array from the uploaded file paths * * @param session the HttpSession. */ @SuppressWarnings("unchecked") private String getUploadedFilePaths(List<String> paths) throws IOException { if (paths == null) { paths = new ArrayList<String>(); } ObjectMapper mapper = new ObjectMapper(); return mapper.writeValueAsString(paths); } private List<String> getWhiteList() { if (StringUtil.isDefined(whiteList)) { return Arrays.asList(whiteList.split(" ")); } return Arrays.asList(); } private boolean isInWhiteList(String filename) { List<String> whileList = getWhiteList(); String extension = FilenameUtils.getExtension(filename).toLowerCase(); return whileList.contains(extension); } }
true
true
private void doFileUpload(HttpSession session, HttpServletRequest request, HttpServletResponse response) throws IOException { try { FileUploadListener listener = new FileUploadListener(request.getContentLength()); session.setAttribute(FILE_UPLOAD_STATS, listener.getFileUploadStats()); FileItemFactory factory = new MonitoringFileItemFactory(listener); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = (List<FileItem>) upload.parseRequest(request); boolean hasError = false; String errorMessage = ""; List<String> paths = new ArrayList<String>(items.size()); session.setAttribute(FILE_UPLOAD_PATHS, paths); for (FileItem fileItem : items) { if (!fileItem.isFormField() && fileItem.getSize() > 0L) { String filename = fileItem.getName(); if (filename.indexOf('/') >= 0) { filename = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.indexOf('\\') >= 0) { filename = filename.substring(filename.lastIndexOf('\\') + 1); } if (!isInWhiteList(filename)) { hasError = true; errorMessage += "The file " + filename + " isn't uploaded! Only HTML files can be uploaded<br/>"; } else { filename = System.currentTimeMillis() + "-" + filename; File targetDirectory = new File(uploadDir, fileItem.getFieldName()); targetDirectory.mkdirs(); File uploadedFile = new File(targetDirectory, filename); OutputStream out = null; try { out = new FileOutputStream(uploadedFile); IOUtils.copy(fileItem.getInputStream(), out); paths.add(uploadedFile.getParentFile().getName() + '/' + uploadedFile.getName()); } finally { IOUtils.closeQuietly(out); } fileItem.delete(); } } } String uploadedFiles = getUploadedFilePaths(paths); if (!hasError) { sendCompleteResponse(response, uploadedFiles, null); } else { sendCompleteResponse(response, uploadedFiles, errorMessage); } } catch (Exception e) { Logger.getLogger(getClass().getSimpleName()).log(Level.WARNING, e.getMessage()); sendCompleteResponse(response, "[]", "Could not process uploaded file. Please see log for details."); } }
private void doFileUpload(HttpSession session, HttpServletRequest request, HttpServletResponse response) throws IOException { try { FileUploadListener listener = new FileUploadListener(request.getContentLength()); session.setAttribute(FILE_UPLOAD_STATS, listener.getFileUploadStats()); FileItemFactory factory = new MonitoringFileItemFactory(listener); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = (List<FileItem>) upload.parseRequest(request); boolean hasError = false; String errorMessage = ""; List<String> paths = new ArrayList<String>(items.size()); session.setAttribute(FILE_UPLOAD_PATHS, paths); for (FileItem fileItem : items) { if (!fileItem.isFormField() && fileItem.getSize() > 0L) { String filename = fileItem.getName(); if (filename.indexOf('/') >= 0) { filename = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.indexOf('\\') >= 0) { filename = filename.substring(filename.lastIndexOf('\\') + 1); } if (!isInWhiteList(filename)) { hasError = true; errorMessage += "The file " + filename + " is not uploaded!"; errorMessage += (StringUtil.isDefined(whiteList) ? " Only " + whiteList.replaceAll( " ", ", ") + " file types can be uploaded<br/>" : " No allowed file format has been defined for upload<br/>"); } else { filename = System.currentTimeMillis() + "-" + filename; File targetDirectory = new File(uploadDir, fileItem.getFieldName()); targetDirectory.mkdirs(); File uploadedFile = new File(targetDirectory, filename); OutputStream out = null; try { out = new FileOutputStream(uploadedFile); IOUtils.copy(fileItem.getInputStream(), out); paths.add(uploadedFile.getParentFile().getName() + '/' + uploadedFile.getName()); } finally { IOUtils.closeQuietly(out); } fileItem.delete(); } } } String uploadedFiles = getUploadedFilePaths(paths); if (!hasError) { sendCompleteResponse(response, uploadedFiles, null); } else { sendCompleteResponse(response, uploadedFiles, errorMessage); } } catch (Exception e) { Logger.getLogger(getClass().getSimpleName()).log(Level.WARNING, e.getMessage()); sendCompleteResponse(response, "[]", "Could not process uploaded file. Please see log for details."); } }
diff --git a/javafx.editor/src/org/netbeans/modules/javafx/editor/completion/JavaFXCompletionEnvironment.java b/javafx.editor/src/org/netbeans/modules/javafx/editor/completion/JavaFXCompletionEnvironment.java index ef918b08..841d13de 100644 --- a/javafx.editor/src/org/netbeans/modules/javafx/editor/completion/JavaFXCompletionEnvironment.java +++ b/javafx.editor/src/org/netbeans/modules/javafx/editor/completion/JavaFXCompletionEnvironment.java @@ -1,1189 +1,1189 @@ /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 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 * 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. 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): * * The Original Software is NetBeans. The Initial Developer of the Original * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun * Microsystems, Inc. All Rights Reserved. * * 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. */ package org.netbeans.modules.javafx.editor.completion; import com.sun.javafx.api.tree.BlockExpressionTree; import com.sun.javafx.api.tree.ErroneousTree; import com.sun.javafx.api.tree.ExpressionTree; import com.sun.javafx.api.tree.ForExpressionInClauseTree; import com.sun.javafx.api.tree.ForExpressionTree; import com.sun.javafx.api.tree.FunctionDefinitionTree; import com.sun.javafx.api.tree.FunctionInvocationTree; import com.sun.javafx.api.tree.FunctionValueTree; import com.sun.javafx.api.tree.IdentifierTree; import com.sun.javafx.api.tree.InstanceOfTree; import com.sun.javafx.api.tree.JavaFXTreePath; import com.sun.javafx.api.tree.MemberSelectTree; import com.sun.javafx.api.tree.Tree; import com.sun.javafx.api.tree.Tree.JavaFXKind; import com.sun.javafx.api.tree.VariableTree; import com.sun.javafx.api.tree.OnReplaceTree; import com.sun.javafx.api.tree.SourcePositions; import com.sun.javafx.api.tree.UnitTree; import com.sun.tools.javac.code.Scope; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javafx.api.JavafxcScope; import com.sun.tools.javafx.api.JavafxcTrees; import com.sun.tools.javafx.code.JavafxTypes; import com.sun.tools.javafx.tree.JFXClassDeclaration; import com.sun.tools.javafx.tree.JFXFunctionDefinition; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.EnumSet; import java.util.Iterator; import java.util.List; import java.util.Random; import java.util.Set; import java.util.TreeSet; import java.util.logging.Level; import java.util.logging.Logger; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.element.PackageElement; import static javax.lang.model.element.Modifier.*; import javax.lang.model.element.TypeElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.ExecutableType; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.Elements; import javax.lang.model.util.Types; import javax.swing.text.BadLocationException; import javax.tools.Diagnostic; import org.netbeans.api.java.classpath.ClassPath; import org.netbeans.api.javafx.lexer.JFXTokenId; import org.netbeans.api.javafx.source.ClasspathInfo; import org.netbeans.api.javafx.source.ClasspathInfo.PathKind; import org.netbeans.api.javafx.source.CompilationController; import org.netbeans.api.javafx.source.JavaFXSource; import org.netbeans.api.javafx.source.JavaFXSource.Phase; import org.netbeans.api.javafx.source.Task; import org.netbeans.api.lexer.TokenHierarchy; import org.netbeans.api.lexer.TokenSequence; import org.netbeans.modules.editor.indent.api.IndentUtils; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileSystem; import org.openide.filesystems.FileUtil; import static org.netbeans.modules.javafx.editor.completion.JavaFXCompletionQuery.*; /** * * @author David Strupl, Anton Chechel */ public class JavaFXCompletionEnvironment<T extends Tree> { private static final Logger logger = Logger.getLogger(JavaFXCompletionEnvironment.class.getName()); private static final boolean LOGGABLE = logger.isLoggable(Level.FINE); private static int usingFakeSource = 0; protected int offset; protected String prefix; protected boolean isCamelCasePrefix; protected CompilationController controller; protected JavaFXTreePath path; protected SourcePositions sourcePositions; protected boolean insideForEachExpressiion = false; protected UnitTree root; protected JavaFXCompletionQuery query; protected JavaFXCompletionEnvironment() { } /* * Thies method must be called after constructor before a call to resolveCompletion */ void init(int offset, String prefix, CompilationController controller, JavaFXTreePath path, SourcePositions sourcePositions, JavaFXCompletionQuery query) { this.offset = offset; this.prefix = prefix; this.isCamelCasePrefix = prefix != null && prefix.length() > 1 && JavaFXCompletionQuery.camelCasePattern.matcher(prefix).matches(); this.controller = controller; this.path = path; this.sourcePositions = sourcePositions; this.query = query; this.root = path.getCompilationUnit(); } /** * This method should be overriden in subclasses */ protected void inside(T t) throws IOException { if (LOGGABLE) log("NOT IMPLEMENTED inside " + t); } public int getOffset() { return offset; } public String getPrefix() { return prefix; } public boolean isCamelCasePrefix() { return isCamelCasePrefix; } public CompilationController getController() { return controller; } public UnitTree getRoot() { return root; } public JavaFXTreePath getPath() { return path; } public SourcePositions getSourcePositions() { return sourcePositions; } public void insideForEachExpressiion() { this.insideForEachExpressiion = true; } public boolean isInsideForEachExpressiion() { return insideForEachExpressiion; } /** * If the tree is broken we are in fact not in the compilation unit. * @param env * @return */ protected boolean isTreeBroken() { int start = (int) sourcePositions.getStartPosition(root, root); int end = (int) sourcePositions.getEndPosition(root, root); if (LOGGABLE) log("isTreeBroken start: " + start + " end: " + end); return start == -1 || end == -1; } protected String fullName(Tree tree) { switch (tree.getJavaFXKind()) { case IDENTIFIER: return ((IdentifierTree) tree).getName().toString(); case MEMBER_SELECT: String sname = fullName(((MemberSelectTree) tree).getExpression()); return sname == null ? null : sname + '.' + ((MemberSelectTree) tree).getIdentifier(); default: return null; } } void insideTypeCheck() throws IOException { InstanceOfTree iot = (InstanceOfTree) getPath().getLeaf(); TokenSequence<JFXTokenId> ts = findLastNonWhitespaceToken(iot, getOffset()); } protected void insideExpression(JavaFXTreePath exPath) throws IOException { if (LOGGABLE) log("insideExpression " + exPath.getLeaf()); Tree et = exPath.getLeaf(); Tree parent = exPath.getParentPath().getLeaf(); int endPos = (int) getSourcePositions().getEndPosition(root, et); if (endPos != Diagnostic.NOPOS && endPos < offset) { TokenSequence<JFXTokenId> last = findLastNonWhitespaceToken(endPos, offset); if (LOGGABLE) log(" last: " + last); if (last != null) { return; } } if (LOGGABLE) log("NOT IMPLEMENTED: insideExpression " + exPath.getLeaf()); } protected void addResult(JavaFXCompletionItem i) { query.results.add(i); } protected void addMembers(final TypeMirror type, final boolean methods, final boolean fields) throws IOException { addMembers(type, methods, fields, null); } protected void addMembers(final TypeMirror type, final boolean methods, final boolean fields, final String textToAdd) throws IOException { if (LOGGABLE) log("addMembers: " + type); JavafxcTrees trees = controller.getTrees(); JavaFXTreePath p = new JavaFXTreePath(root); JavafxcScope scope = trees.getScope(p); if (type == null || type.getKind() != TypeKind.DECLARED) { if (LOGGABLE) log("RETURNING: type.getKind() == " + type.getKind()); return; } DeclaredType dt = (DeclaredType) type; if (LOGGABLE) log(" elementKind == " + dt.asElement().getKind()); if (dt.asElement().getKind() != ElementKind.CLASS) { return; } Elements elements = controller.getElements(); final TypeElement te = (TypeElement) dt.asElement(); for (Element member : te.getEnclosedElements()) { if (LOGGABLE) log(" member1 = " + member + " member1.getKind() " + member.getKind()); if ("<error>".equals(member.getSimpleName().toString())) { continue; } String s = member.getSimpleName().toString(); if (!trees.isAccessible(scope, member,dt)) { if (LOGGABLE) log(" not accessible " + s); continue; } if (fields && member.getKind() == ElementKind.FIELD) { if (JavaFXCompletionProvider.startsWith(s, getPrefix())) { addResult(JavaFXCompletionItem.createVariableItem(s, offset, textToAdd, true)); } } } for (Element member : elements.getAllMembers(te)) { if (LOGGABLE) log(" member2 == " + member + " member2.getKind() " + member.getKind()); String s = member.getSimpleName().toString(); if ("<error>".equals(member.getSimpleName().toString())) { continue; } if (!trees.isAccessible(scope, member,dt)) { if (LOGGABLE) log(" not accessible " + s); continue; } if (methods && member.getKind() == ElementKind.METHOD) { if (s.contains("$")) { continue; } if (JavaFXCompletionProvider.startsWith(s, getPrefix())) { addResult( JavaFXCompletionItem.createExecutableItem( (ExecutableElement) member, (ExecutableType) member.asType(), offset, false, false, false, false)); } } else if (fields && member.getKind() == ElementKind.FIELD) { if (JavaFXCompletionProvider.startsWith(s, getPrefix())) { addResult(JavaFXCompletionItem.createVariableItem(s, offset, textToAdd, false)); } } } } protected void localResult(TypeMirror smart) throws IOException { addLocalMembersAndVars(smart); addLocalAndImportedTypes(null, null, null, false, smart); } protected void addMemberConstantsAndTypes(final TypeMirror type, final Element elem) throws IOException { if (LOGGABLE) log("addMemberConstantsAndTypes: " + type + " elem: " + elem); } protected void addLocalMembersAndVars(TypeMirror smart) throws IOException { if (LOGGABLE) log("addLocalMembersAndVars: " + prefix); // controller.toPhase(Phase.ANALYZED); final JavafxcTrees trees = controller.getTrees(); if (smart != null && smart.getKind() == TypeKind.DECLARED) { if (LOGGABLE) log("adding declared type + subtypes: " + smart); DeclaredType dt = (DeclaredType) smart; TypeElement elem = (TypeElement) dt.asElement(); addResult(JavaFXCompletionItem.createTypeItem(elem, dt, offset, false, false, true)); for (DeclaredType subtype : getSubtypesOf((DeclaredType) smart)) { TypeElement subElem = (TypeElement) subtype.asElement(); addResult(JavaFXCompletionItem.createTypeItem(subElem, subtype, offset, false, false, true)); } } for (JavaFXTreePath tp = getPath(); tp != null; tp = tp.getParentPath()) { Tree t = tp.getLeaf(); if (LOGGABLE) log(" tree kind: " + t.getJavaFXKind()); if (t instanceof UnitTree) { UnitTree cut = (UnitTree) t; for (Tree tt : cut.getTypeDecls()) { if (LOGGABLE) log(" tt: " + tt); JavaFXKind kk = tt.getJavaFXKind(); if (kk == JavaFXKind.CLASS_DECLARATION) { JFXClassDeclaration cd = (JFXClassDeclaration) tt; for (Tree jct : cd.getClassMembers()) { if (LOGGABLE) log(" jct == " + jct); JavaFXKind k = jct.getJavaFXKind(); if (LOGGABLE) log(" kind of jct = " + k); if (k == JavaFXKind.FUNCTION_DEFINITION) { JFXFunctionDefinition fdt = (JFXFunctionDefinition) jct; if (LOGGABLE) log(" fdt == " + fdt.name.toString()); if ("javafx$run$".equals(fdt.name.toString())) { addBlockExpressionLocals(fdt.getBodyExpression(), tp, smart); } } } } } } JavaFXKind k = t.getJavaFXKind(); if (LOGGABLE) log(" fx kind: " + k); if (k == JavaFXKind.CLASS_DECLARATION) { TypeMirror tm = trees.getTypeMirror(tp); if (LOGGABLE) log(" tm == " + tm + " ---- tm.getKind() == " + (tm == null ? "null" : tm.getKind())); addMembers(tm, true, true); } if (k == JavaFXKind.BLOCK_EXPRESSION) { addBlockExpressionLocals((BlockExpressionTree) t, tp, smart); } if (k == JavaFXKind.FOR_EXPRESSION_FOR) { ForExpressionTree fet = (ForExpressionTree) t; if (LOGGABLE) log(" for expression: " + fet + "\n"); for (ForExpressionInClauseTree fetic : fet.getInClauses()) { if (LOGGABLE) log(" fetic: " + fetic + "\n"); String s = fetic.getVariable().getName().toString(); if (LOGGABLE) log(" adding(2) " + s + " with prefix " + prefix); TypeMirror tm = trees.getTypeMirror(new JavaFXTreePath(tp, fetic)); - if (smart != null && tm.getKind() == smart.getKind()) { + if (smart != null && tm != null && tm.getKind() == smart.getKind()) { addResult(JavaFXCompletionItem.createVariableItem(s, offset, true)); } if (JavaFXCompletionProvider.startsWith(s, prefix)) { addResult(JavaFXCompletionItem.createVariableItem(s, offset, false)); } } } if (k == JavaFXKind.FUNCTION_VALUE) { FunctionValueTree fvt = (FunctionValueTree) t; for (VariableTree var : fvt.getParameters()) { if (LOGGABLE) log(" var: " + var + "\n"); String s = var.getName().toString(); if (LOGGABLE) log(" adding(3) " + s + " with prefix " + prefix); TypeMirror tm = trees.getTypeMirror(new JavaFXTreePath(tp, var)); if (smart != null && tm.getKind() == smart.getKind()) { addResult(JavaFXCompletionItem.createVariableItem(s, offset, true)); } if (JavaFXCompletionProvider.startsWith(s, prefix)) { addResult(JavaFXCompletionItem.createVariableItem(s, offset, false)); } } } if (k == JavaFXKind.ON_REPLACE) { OnReplaceTree ort = (OnReplaceTree) t; // commented out log because of JFXC-1205 // if (LOGGABLE) log(" OnReplaceTree: " + ort + "\n"); VariableTree varTree = ort.getNewElements(); if (varTree != null) { String s1 = varTree.getName().toString(); if (LOGGABLE) log(" adding(4) " + s1 + " with prefix " + prefix); TypeMirror tm = trees.getTypeMirror(new JavaFXTreePath(tp, varTree)); if (smart != null && tm.getKind() == smart.getKind()) { addResult(JavaFXCompletionItem.createVariableItem(s1, offset, true)); } if (JavaFXCompletionProvider.startsWith(s1, prefix)) { addResult(JavaFXCompletionItem.createVariableItem(s1, offset, false)); } } VariableTree varTree2 = ort.getOldValue(); if (varTree2 != null) { String s2 = varTree2.getName().toString(); if (LOGGABLE) log(" adding(5) " + s2 + " with prefix " + prefix); TypeMirror tm = trees.getTypeMirror(new JavaFXTreePath(tp, varTree2)); if (smart != null && tm.getKind() == smart.getKind()) { addResult(JavaFXCompletionItem.createVariableItem(s2, offset, true)); } if (JavaFXCompletionProvider.startsWith(s2, prefix)) { addResult(JavaFXCompletionItem.createVariableItem(s2, offset, false)); } } } } } private void addBlockExpressionLocals(BlockExpressionTree bet, JavaFXTreePath tp, TypeMirror smart) { if (LOGGABLE) log(" block expression: " + bet + "\n"); for (ExpressionTree st : bet.getStatements()) { JavaFXTreePath expPath = new JavaFXTreePath(tp, st); if (LOGGABLE) log(" expPath == " + expPath.getLeaf()); JavafxcTrees trees = controller.getTrees(); Element type = trees.getElement(expPath); if (type == null) { continue; } if (LOGGABLE) log(" type.getKind() == " + type.getKind()); if (type.getKind() == ElementKind.LOCAL_VARIABLE) { String s = type.getSimpleName().toString(); if (LOGGABLE) log(" adding(1) " + s + " with prefix " + prefix); TypeMirror tm = trees.getTypeMirror(expPath); if (smart != null && tm.getKind() == smart.getKind()) { addResult(JavaFXCompletionItem.createVariableItem( s, offset, true)); } if (JavaFXCompletionProvider.startsWith(s, getPrefix())) { addResult(JavaFXCompletionItem.createVariableItem( s, offset, false)); } } } } protected void addPackages(String fqnPrefix) { if (LOGGABLE) log("addPackages " + fqnPrefix); if (fqnPrefix == null) { fqnPrefix = ""; } JavaFXSource js = controller.getJavaFXSource(); ClasspathInfo info = js.getCpInfo(); ArrayList<FileObject> fos = new ArrayList<FileObject>(); ClassPath cp = info.getClassPath(PathKind.SOURCE); fos.addAll(Arrays.asList(cp.getRoots())); cp = info.getClassPath(PathKind.COMPILE); fos.addAll(Arrays.asList(cp.getRoots())); cp = info.getClassPath(PathKind.BOOT); fos.addAll(Arrays.asList(cp.getRoots())); String pr = ""; if (fqnPrefix.lastIndexOf('.') >= 0) { pr = fqnPrefix.substring(0, fqnPrefix.lastIndexOf('.')); } if (LOGGABLE) log(" pr == " + pr); for (String name : pr.split("\\.")) { ArrayList<FileObject> newFos = new ArrayList<FileObject>(); if (LOGGABLE) log(" traversing to " + name); for (FileObject f : fos) { if (f.isFolder()) { FileObject child = f.getFileObject(name); if (child != null) { newFos.add(child); } } } if (LOGGABLE) log(" replacing " + fos + "\n with " + newFos); fos = newFos; } for (FileObject fo : fos) { if (fo.isFolder()) { for (FileObject child : fo.getChildren()) { if (child.isFolder()) { if (LOGGABLE) log(" found : " + child); if (("META-INF".equals(child.getName())) || ("doc-files".equals(child.getName()))) { continue; } String s = child.getPath().replace('/', '.'); addResult(JavaFXCompletionItem.createPackageItem(s, offset, false)); } } } } } protected List<DeclaredType> getSubtypesOf(DeclaredType baseType) throws IOException { if (LOGGABLE) log("NOT IMPLEMENTED: getSubtypesOf " + baseType); return Collections.emptyList(); } protected void addMethodArguments(FunctionInvocationTree mit) throws IOException { if (LOGGABLE) log("NOT IMPLEMENTED: addMethodArguments " + mit); } protected void addKeyword(String kw, String postfix, boolean smartType) { if (JavaFXCompletionProvider.startsWith(kw, getPrefix())) { addResult(JavaFXCompletionItem.createKeywordItem(kw, postfix, query.anchorOffset, smartType)); } } protected void addKeywordsForCU() { List<String> kws = new ArrayList<String>(); kws.add(ABSTRACT_KEYWORD); kws.add(CLASS_KEYWORD); kws.add(VAR_KEYWORD); kws.add(FUNCTION_KEYWORD); kws.add(PUBLIC_KEYWORD); kws.add(IMPORT_KEYWORD); boolean beforeAnyClass = true; for (Tree t : root.getTypeDecls()) { if (t.getJavaFXKind() == Tree.JavaFXKind.CLASS_DECLARATION) { int pos = (int) sourcePositions.getEndPosition(root, t); if (pos != Diagnostic.NOPOS && offset >= pos) { beforeAnyClass = false; } } } if (beforeAnyClass) { Tree firstImport = null; for (Tree t : root.getImports()) { firstImport = t; break; } Tree pd = root.getPackageName(); if ((pd != null && offset <= sourcePositions.getStartPosition(root, root)) || (pd == null && (firstImport == null || sourcePositions.getStartPosition(root, firstImport) >= offset))) { kws.add(PACKAGE_KEYWORD); } } for (String kw : kws) { if (JavaFXCompletionProvider.startsWith(kw, prefix)) { addResult(JavaFXCompletionItem.createKeywordItem(kw, SPACE, query.anchorOffset, false)); } } addKeywordsForStatement(); } protected void addKeywordsForClassBody() { for (String kw : CLASS_BODY_KEYWORDS) { if (JavaFXCompletionProvider.startsWith(kw, prefix)) { addResult(JavaFXCompletionItem.createKeywordItem(kw, SPACE, query.anchorOffset, false)); } } } @SuppressWarnings("fallthrough") protected void addKeywordsForStatement() { for (String kw : STATEMENT_KEYWORDS) { if (JavaFXCompletionProvider.startsWith(kw, prefix)) { addResult(JavaFXCompletionItem.createKeywordItem(kw, null, query.anchorOffset, false)); } } for (String kw : STATEMENT_SPACE_KEYWORDS) { if (JavaFXCompletionProvider.startsWith(kw, prefix)) { addResult(JavaFXCompletionItem.createKeywordItem(kw, SPACE, query.anchorOffset, false)); } } if (JavaFXCompletionProvider.startsWith(RETURN_KEYWORD, prefix)) { JavaFXTreePath mth = JavaFXCompletionProvider.getPathElementOfKind(Tree.JavaFXKind.FUNCTION_DEFINITION, getPath()); String postfix = SPACE; if (mth != null) { // XXX[pn]: is this right? Tree rt = ((FunctionDefinitionTree) mth.getLeaf()).getFunctionValue().getType(); if (rt == null) { postfix = SEMI; } } addResult(JavaFXCompletionItem.createKeywordItem(RETURN_KEYWORD, postfix, query.anchorOffset, false)); } JavaFXTreePath tp = getPath(); while (tp != null) { switch (tp.getLeaf().getJavaFXKind()) { case FOR_EXPRESSION_IN_CLAUSE: case FOR_EXPRESSION_FOR: case WHILE_LOOP: if (JavaFXCompletionProvider.startsWith(CONTINUE_KEYWORD, prefix)) { addResult(JavaFXCompletionItem.createKeywordItem(CONTINUE_KEYWORD, SEMI, query.anchorOffset, false)); } /* case SWITCH: if (JavaFXCompletionProvider.startsWith(BREAK_KEYWORD, prefix)) { addResult(JavaFXCompletionItem.createKeywordItem(BREAK_KEYWORD, SEMI, query.anchorOffset, false)); } break;*/ } tp = tp.getParentPath(); } } protected void addValueKeywords() throws IOException { if (JavaFXCompletionProvider.startsWith(FALSE_KEYWORD, prefix)) { addResult(JavaFXCompletionItem.createKeywordItem(FALSE_KEYWORD, null, query.anchorOffset, false)); } if (JavaFXCompletionProvider.startsWith(TRUE_KEYWORD, prefix)) { addResult(JavaFXCompletionItem.createKeywordItem(TRUE_KEYWORD, null, query.anchorOffset, false)); } if (JavaFXCompletionProvider.startsWith(NULL_KEYWORD, prefix)) { addResult(JavaFXCompletionItem.createKeywordItem(NULL_KEYWORD, null, query.anchorOffset, false)); } if (JavaFXCompletionProvider.startsWith(NEW_KEYWORD, prefix)) { addResult(JavaFXCompletionItem.createKeywordItem(NEW_KEYWORD, SPACE, query.anchorOffset, false)); } if (JavaFXCompletionProvider.startsWith(BIND_KEYWORD, prefix)) { addResult(JavaFXCompletionItem.createKeywordItem(BIND_KEYWORD, SPACE, query.anchorOffset, false)); } } protected void addClassModifiers(Set<Modifier> modifiers) { List<String> kws = new ArrayList<String>(); if (!modifiers.contains(PUBLIC) && !modifiers.contains(PRIVATE)) { kws.add(PUBLIC_KEYWORD); } if (!modifiers.contains(FINAL) && !modifiers.contains(ABSTRACT)) { kws.add(ABSTRACT_KEYWORD); } kws.add(CLASS_KEYWORD); for (String kw : kws) { if (JavaFXCompletionProvider.startsWith(kw, prefix)) { addResult(JavaFXCompletionItem.createKeywordItem(kw, SPACE, query.anchorOffset, false)); } } } protected void addMemberModifiers(Set<Modifier> modifiers, boolean isLocal) { if (LOGGABLE) log("addMemberModifiers"); List<String> kws = new ArrayList<String>(); if (isLocal) { } else { if (!modifiers.contains(PUBLIC) && !modifiers.contains(PROTECTED) && !modifiers.contains(PRIVATE)) { kws.add(PUBLIC_KEYWORD); kws.add(PROTECTED_KEYWORD); kws.add(PRIVATE_KEYWORD); } if (!modifiers.contains(FINAL) && !modifiers.contains(ABSTRACT)) { kws.add(ABSTRACT_KEYWORD); } if (!modifiers.contains(STATIC)) { kws.add(STATIC_KEYWORD); } kws.add(READONLY_KEYWORD); } for (String kw : kws) { if (JavaFXCompletionProvider.startsWith(kw, prefix)) { addResult(JavaFXCompletionItem.createKeywordItem(kw, SPACE, query.anchorOffset, false)); } } } /** * This methods hacks over issue #135926. To prevent NPE we first complete * all symbols that are classes and not inner classes in a package. * @param pe * @return pe.getEnclosedElements() but without the NPE */ private List<? extends Element> getEnclosedElements(PackageElement pe) { Symbol s = (Symbol)pe; for (Scope.Entry e = s.members().elems; e != null; e = e.sibling) { if ((e.sym != null) && (!e.sym.toString().contains("$"))){ try { e.sym.complete(); } catch (RuntimeException x) { if (LOGGABLE) { logger.log(Level.FINE,"Let's see whether we survive this: ",x); } } } } return pe.getEnclosedElements(); } protected void addPackageContent(PackageElement pe, EnumSet<ElementKind> kinds, DeclaredType baseType, boolean insideNew) { if (LOGGABLE) log("addPackageContent " + pe); Elements elements = controller.getElements(); JavafxTypes types = controller.getJavafxTypes(); JavafxcTrees trees = controller.getTrees(); JavaFXTreePath p = new JavaFXTreePath(root); JavafxcScope scope = trees.getScope(p); for (Element e : getEnclosedElements(pe)) { if (e.getKind().isClass() || e.getKind() == ElementKind.INTERFACE) { String name = e.getSimpleName().toString(); if (!trees.isAccessible(scope, (TypeElement) e)) { if (LOGGABLE) log(" not accessible " + name); continue; } if (JavaFXCompletionProvider.startsWith(name, prefix) && !name.contains("$")) { addResult(JavaFXCompletionItem.createTypeItem((TypeElement) e, (DeclaredType) e.asType(), offset, elements.isDeprecated(e), insideNew, false)); } for (Element ee : e.getEnclosedElements()) { if (ee.getKind().isClass() || ee.getKind() == ElementKind.INTERFACE) { String ename = ee.getSimpleName().toString(); if (!trees.isAccessible(scope, (TypeElement) ee)) { if (LOGGABLE) log(" not accessible " + ename); continue; } log(ename + " isJFXClass " + types.isJFXClass((Symbol) ee)); if (JavaFXCompletionProvider.startsWith(ename, prefix) && types.isJFXClass((Symbol) ee)) { addResult(JavaFXCompletionItem.createTypeItem((TypeElement) ee, (DeclaredType) ee.asType(), offset, elements.isDeprecated(ee), insideNew, false)); } } } } } String pkgName = pe.getQualifiedName() + "."; //NOI18N if (prefix != null && prefix.length() > 0) { pkgName += prefix; } addPackages(pkgName); } protected void addBasicTypes() { if (LOGGABLE) log("addBasicTypes "); addBasicType("Boolean", "boolean"); addBasicType("Integer", "int"); addBasicType("Number", "double"); addBasicType("String", "String"); } private void addBasicType(String name1, String name2) { if (LOGGABLE) log(" addBasicType " + name1 + " : " + name2); JavafxcTrees trees = controller.getTrees(); JavaFXTreePath p = new JavaFXTreePath(root); JavafxcScope scope = trees.getScope(p); if (LOGGABLE) log(" scope == " + scope); for (Element local : scope.getLocalElements()) { if (LOGGABLE) log(" local == " + local.getSimpleName() + " kind: " + local.getKind() + " class: " + local.getClass().getName() + " asType: " + local.asType()); if (local.getKind().isClass() || local.getKind() == ElementKind.INTERFACE) { if (! (local instanceof TypeElement)) { if (LOGGABLE) log(" " + local.getSimpleName() + " not TypeElement"); continue; } TypeElement te = (TypeElement) local; String name = local.getSimpleName().toString(); if (name.equals(name2)) { if (JavaFXCompletionProvider.startsWith(name1, prefix)) { if (LOGGABLE) log(" found " + name1); if (local.asType() == null || local.asType().getKind() != TypeKind.DECLARED) { addResult(JavaFXCompletionItem.createTypeItem(name1, offset, false, false, false)); } else { DeclaredType dt = (DeclaredType) local.asType(); addResult(JavaFXCompletionItem.createTypeItem(te, dt, offset, false, false, false)); } return; } } } } } protected void addLocalAndImportedTypes(final EnumSet<ElementKind> kinds, final DeclaredType baseType, final Set<? extends Element> toExclude, boolean insideNew, TypeMirror smart) throws IOException { if (LOGGABLE) log("addLocalAndImportedTypes"); JavafxcTrees trees = controller.getTrees(); JavaFXTreePath p = new JavaFXTreePath(root); JavafxcScope scope = trees.getScope(p); JavafxcScope originalScope = scope; while (scope != null) { if (LOGGABLE) log(" scope == " + scope); addLocalAndImportedTypes(scope.getLocalElements(), kinds, baseType, toExclude, insideNew, smart, originalScope, null,false); scope = scope.getEnclosingScope(); } Element e = trees.getElement(p); while (e != null && e.getKind() != ElementKind.PACKAGE) { e = e.getEnclosingElement(); } if (e != null) { if (LOGGABLE) log("will scan package " + e.getSimpleName()); PackageElement pkge = (PackageElement)e; addLocalAndImportedTypes(getEnclosedElements(pkge), kinds, baseType, toExclude, insideNew, smart, originalScope, pkge,false); } addPackages(""); } private void addLocalAndImportedTypes(Iterable<? extends Element> from, final EnumSet<ElementKind> kinds, final DeclaredType baseType, final Set<? extends Element> toExclude, boolean insideNew, TypeMirror smart, JavafxcScope originalScope, PackageElement myPackage,boolean simpleNameOnly) throws IOException { final Elements elements = controller.getElements(); JavafxcTrees trees = controller.getTrees(); for (Element local : from) { if (LOGGABLE) log(" local == " + local); if (local.getKind().isClass() || local.getKind() == ElementKind.INTERFACE) { if (local.asType() == null || local.asType().getKind() != TypeKind.DECLARED) { continue; } DeclaredType dt = (DeclaredType) local.asType(); TypeElement te = (TypeElement) local; String name = local.getSimpleName().toString(); if (!trees.isAccessible(originalScope, te)) { if (LOGGABLE) log(" not accessible " + name); continue; } Element parent = te.getEnclosingElement(); if (parent.getKind() == ElementKind.CLASS) { if (!trees.isAccessible(originalScope, (TypeElement) parent)) { if (LOGGABLE) log(" parent not accessible " + name); continue; } } if (smart != null && local.asType() == smart) { addResult(JavaFXCompletionItem.createTypeItem(te, dt, offset, elements.isDeprecated(local), insideNew, true)); } if (JavaFXCompletionProvider.startsWith(name, prefix) && !name.contains("$")) { if (simpleNameOnly) { addResult(JavaFXCompletionItem.createTypeItem(local.getSimpleName().toString(), offset, elements.isDeprecated(local), insideNew, false)); } else { addResult(JavaFXCompletionItem.createTypeItem(te, dt, offset, elements.isDeprecated(local), insideNew, false)); } } if (parent == myPackage) { if (LOGGABLE) log(" will check inner classes of: " + local); addLocalAndImportedTypes(local.getEnclosedElements(), kinds, baseType, toExclude, insideNew, smart, originalScope, null,true); } } } } /** * @param simpleName name of a class or fully qualified name of a class * @return TypeElement or null if the passed in String does not denote a class */ protected TypeElement findTypeElement(String simpleName) { if (LOGGABLE) log("findTypeElement: " + simpleName); JavafxcTrees trees = controller.getTrees(); JavaFXTreePath p = new JavaFXTreePath(root); JavafxcScope scope = trees.getScope(p); while (scope != null) { if (LOGGABLE) log(" scope == " + scope); TypeElement res = findTypeElement(scope.getLocalElements(), simpleName,null); if (res != null) { return res; } scope = scope.getEnclosingScope(); } Element e = trees.getElement(p); while (e != null && e.getKind() != ElementKind.PACKAGE) { e = e.getEnclosingElement(); } if (e != null) { PackageElement pkge = (PackageElement)e; return findTypeElement(getEnclosedElements(pkge), simpleName,pkge); } return null; } /** * @param simpleName name of a class or fully qualified name of a class * @param myPackage can be null - if not null the inner classes of classes from this package will be checked * @return TypeElement or null if the passed in String does not denote a class */ private TypeElement findTypeElement(Iterable<? extends Element> from, String simpleName,PackageElement myPackage) { if (LOGGABLE) log(" private findTypeElement " + simpleName + " in package " + myPackage); Elements elements = controller.getElements(); for (Element local : from) { if (LOGGABLE) log(" local == " + local.getSimpleName() + " kind: " + local.getKind() + " class: " + local.getClass().getName() + " asType: " + local.asType()); if (local.getKind().isClass() || local.getKind() == ElementKind.INTERFACE) { if (local.asType() == null || local.asType().getKind() != TypeKind.DECLARED) { if (LOGGABLE) log(" is not TypeKind.DECLARED -- ignoring"); continue; } if (local instanceof TypeElement) { String name = local.getSimpleName().toString(); if (name.equals(simpleName)) { return (TypeElement) local; } PackageElement pe = elements.getPackageOf(local); String fullName = pe.getQualifiedName().toString() + '.' + name; if (fullName.equals(simpleName)) { return (TypeElement) local; } if (pe == myPackage) { if (LOGGABLE) log(" will check inner classes of: " + local); TypeElement res = findTypeElement(local.getEnclosedElements(), simpleName,null); if (res != null) { return res; } } } } } return null; } private void addAllTypes(EnumSet<ElementKind> kinds, boolean insideNew) { if (LOGGABLE) log("NOT IMPLEMENTED addAllTypes "); // for(ElementHandle<TypeElement> name : controller.getJavaSource().getClasspathInfo().getClassIndex().getDeclaredTypes(prefix != null ? prefix : EMPTY, kind, EnumSet.allOf(ClassIndex.SearchScope.class))) { // LazyTypeCompletionItem item = LazyTypeCompletionItem.create(name, kinds, anchorOffset, controller.getJavaSource(), insideNew); // if (item.isAnnonInner()) // continue; // results.add(item); // } } protected TokenSequence<JFXTokenId> findLastNonWhitespaceToken(Tree tree, int position) { int startPos = (int) getSourcePositions().getStartPosition(root, tree); return findLastNonWhitespaceToken(startPos, position); } protected TokenSequence<JFXTokenId> findLastNonWhitespaceToken(int startPos, int endPos) { TokenSequence<JFXTokenId> ts = ((TokenHierarchy<?>) controller.getTokenHierarchy()).tokenSequence(JFXTokenId.language()); ts.move(endPos); ts = previousNonWhitespaceToken(ts); if (ts == null || ts.offset() < startPos) { return null; } return ts; } private TokenSequence<JFXTokenId> findFirstNonWhitespaceToken(Tree tree, int position) { int startPos = (int) getSourcePositions().getStartPosition(root, tree); return findFirstNonWhitespaceToken(startPos, position); } protected TokenSequence<JFXTokenId> findFirstNonWhitespaceToken(int startPos, int endPos) { TokenSequence<JFXTokenId> ts = ((TokenHierarchy<?>) controller.getTokenHierarchy()).tokenSequence(JFXTokenId.language()); ts.move(startPos); ts = nextNonWhitespaceToken(ts); if (ts == null || ts.offset() >= endPos) { return null; } return ts; } protected Tree getArgumentUpToPos(Iterable<? extends ExpressionTree> args, int startPos, int cursorPos) { for (ExpressionTree e : args) { int argStart = (int) sourcePositions.getStartPosition(root, e); int argEnd = (int) sourcePositions.getEndPosition(root, e); if (argStart == Diagnostic.NOPOS || argEnd == Diagnostic.NOPOS) { continue; } if (cursorPos >= argStart && cursorPos < argEnd) { return e; } else { TokenSequence<JFXTokenId> last = findLastNonWhitespaceToken(startPos, cursorPos); if (last == null) { continue; } if (last.token().id() == JFXTokenId.LPAREN) { return e; } if (last.token().id() == JFXTokenId.COMMA && cursorPos - 1 == argEnd) { return e; } } } return null; } /** * We don't have an AST - let's try some heuristics */ void useCrystalBall() { try { int lineStart = IndentUtils.lineStartOffset(controller.getJavaFXSource().getDocument(), offset); if (LOGGABLE) log("useCrystalBall lineStart " + lineStart + " offset " + offset); TokenSequence<JFXTokenId> ts = findFirstNonWhitespaceToken(lineStart, offset); if (ts == null) { // nothing interesting on this line? let's try to delete it: tryToDeleteCurrentLine(lineStart); if (query.results.isEmpty()) { tryToTypeSomeNonsense(lineStart); } return; } if (LOGGABLE) log(" first == " + ts.token().id() + " at " + ts.offset()); if (ts.token().id() == JFXTokenId.IMPORT) { int count = ts.offset(); char[] chars = new char[count]; while (count>0) chars[--count] = ' '; String helper = new String(chars); String next = ts.token().text().toString(); while (ts.offset() < offset && ts.moveNext()) { if (LOGGABLE) log("Watching : " + ts.token().id() + " " + ts.token().text().toString()); helper += next; next = ts.token().text().toString(); if (LOGGABLE) log("helper == " + helper); } helper += "*;"; if (LOGGABLE) log("Helper prepared: " + helper); if (!helper.endsWith("import *;")) { useFakeSource(helper, helper.length()-2); } else { addPackages(""); } } else { tryToTypeSomeNonsense(lineStart); } } catch (BadLocationException ex) { if (LOGGABLE) { logger.log(Level.FINE,"Crystal ball failed: ",ex); } } } private void tryToTypeSomeNonsense(int lineStart) { String text = controller.getText(); StringBuilder builder = new StringBuilder(text); builder.insert(offset, 'x'); useFakeSource(builder.toString(), offset); if (query.results.isEmpty()) { builder = new StringBuilder(text); builder.insert(offset, "x;"); useFakeSource(builder.toString(), offset); } if (query.results.isEmpty()) { builder = new StringBuilder(text); builder.insert(offset, "x]"); useFakeSource(builder.toString(), offset); } if (query.results.isEmpty()) { builder = new StringBuilder(text); builder.insert(offset, "x];"); useFakeSource(builder.toString(), offset); } if (query.results.isEmpty()) { // still nothing? let's be desperate: String currentLine = controller.getText().substring(lineStart, offset); if ((!currentLine.contains(":")) && (!currentLine.contains("(")) && (!currentLine.contains(".")) && (!currentLine.contains("{")) ) { tryToDeleteCurrentLine(lineStart); } } } /** * * @param lineStart */ private void tryToDeleteCurrentLine(int lineStart) { if (LOGGABLE) log("tryToDeleteCurrentLine lineStart == " + lineStart + " offset == " + offset); if (offset < lineStart) { if (LOGGABLE) log(" no line, sorry"); return; } int pLength = (prefix != null ? prefix.length():0); int count = offset - lineStart + pLength; char[] chars = new char[count]; while (count>0) chars[--count] = ' '; String text = controller.getText(); StringBuilder builder = new StringBuilder(text); builder.replace(lineStart, offset + pLength, new String(chars)); useFakeSource(builder.toString(), offset); } /** * * @param source */ protected void useFakeSource(String source, final int pos) { if (LOGGABLE) log("useFakeSource " + source + " pos == " + pos); if (usingFakeSource > 1) { // allow to recurse only twice ;-) return; } try { usingFakeSource++; FileSystem fs = FileUtil.createMemoryFileSystem(); final FileObject fo = fs.getRoot().createData("tmp" + (new Random().nextLong()) + ".fx"); Writer w = new OutputStreamWriter(fo.getOutputStream()); w.write(source); w.close(); if (LOGGABLE) log(" source written to " + fo); ClasspathInfo info = ClasspathInfo.create(controller.getFileObject()); JavaFXSource s = JavaFXSource.create(info,Collections.singleton(fo)); if (LOGGABLE) log(" jfxsource obtained " + s); s.runWhenScanFinished(new Task<CompilationController>() { public void run(CompilationController fakeController) throws Exception { if (LOGGABLE) log(" scan finished"); JavaFXCompletionEnvironment env = query.getCompletionEnvironment(fakeController, pos); if (LOGGABLE) log(" env == " + env); fakeController.toPhase(Phase.ANALYZED); if (LOGGABLE) log(" fake analyzed"); if (! env.isTreeBroken()) { if (LOGGABLE) log(" fake non-broken tree"); final Tree leaf = env.getPath().getLeaf(); env.inside(leaf); // try to remove faked entries: String fakeName = fo.getName(); Set<JavaFXCompletionItem> toRemove = new TreeSet<JavaFXCompletionItem>(); for (JavaFXCompletionItem r : query.results) { if (LOGGABLE) log(" checking " + r.getLeftHtmlText()); if (r.getLeftHtmlText().contains(fakeName)) { if (LOGGABLE) log(" will remove " + r); toRemove.add(r); } } query.results.removeAll(toRemove); } } },true); } catch (IOException ex) { if (LOGGABLE) { logger.log(Level.FINE,"useFakeSource failed: ",ex); } } finally { usingFakeSource--; } } protected static TokenSequence<JFXTokenId> nextNonWhitespaceToken(TokenSequence<JFXTokenId> ts) { while (ts.moveNext()) { switch (ts.token().id()) { case WS: case LINE_COMMENT: case COMMENT: case DOC_COMMENT: break; default: return ts; } } return null; } private static TokenSequence<JFXTokenId> previousNonWhitespaceToken(TokenSequence<JFXTokenId> ts) { while (ts.movePrevious()) { switch (ts.token().id()) { case WS: case LINE_COMMENT: case COMMENT: case DOC_COMMENT: break; default: return ts; } } return null; } protected static Tree unwrapErrTree(Tree tree) { if (tree != null && tree.getJavaFXKind() == Tree.JavaFXKind.ERRONEOUS) { Iterator<? extends Tree> it = ((ErroneousTree) tree).getErrorTrees().iterator(); tree = it.hasNext() ? it.next() : null; } return tree; } protected static TypeMirror asMemberOf(Element element, TypeMirror type, Types types) { TypeMirror ret = element.asType(); TypeMirror enclType = element.getEnclosingElement().asType(); if (enclType.getKind() == TypeKind.DECLARED) { enclType = types.erasure(enclType); } while (type != null && type.getKind() == TypeKind.DECLARED) { if (types.isSubtype(type, enclType)) { ret = types.asMemberOf((DeclaredType) type, element); break; } type = ((DeclaredType) type).getEnclosingType(); } return ret; } private static void log(String s) { if (LOGGABLE) { logger.fine(s); } } }
true
true
protected void addLocalMembersAndVars(TypeMirror smart) throws IOException { if (LOGGABLE) log("addLocalMembersAndVars: " + prefix); // controller.toPhase(Phase.ANALYZED); final JavafxcTrees trees = controller.getTrees(); if (smart != null && smart.getKind() == TypeKind.DECLARED) { if (LOGGABLE) log("adding declared type + subtypes: " + smart); DeclaredType dt = (DeclaredType) smart; TypeElement elem = (TypeElement) dt.asElement(); addResult(JavaFXCompletionItem.createTypeItem(elem, dt, offset, false, false, true)); for (DeclaredType subtype : getSubtypesOf((DeclaredType) smart)) { TypeElement subElem = (TypeElement) subtype.asElement(); addResult(JavaFXCompletionItem.createTypeItem(subElem, subtype, offset, false, false, true)); } } for (JavaFXTreePath tp = getPath(); tp != null; tp = tp.getParentPath()) { Tree t = tp.getLeaf(); if (LOGGABLE) log(" tree kind: " + t.getJavaFXKind()); if (t instanceof UnitTree) { UnitTree cut = (UnitTree) t; for (Tree tt : cut.getTypeDecls()) { if (LOGGABLE) log(" tt: " + tt); JavaFXKind kk = tt.getJavaFXKind(); if (kk == JavaFXKind.CLASS_DECLARATION) { JFXClassDeclaration cd = (JFXClassDeclaration) tt; for (Tree jct : cd.getClassMembers()) { if (LOGGABLE) log(" jct == " + jct); JavaFXKind k = jct.getJavaFXKind(); if (LOGGABLE) log(" kind of jct = " + k); if (k == JavaFXKind.FUNCTION_DEFINITION) { JFXFunctionDefinition fdt = (JFXFunctionDefinition) jct; if (LOGGABLE) log(" fdt == " + fdt.name.toString()); if ("javafx$run$".equals(fdt.name.toString())) { addBlockExpressionLocals(fdt.getBodyExpression(), tp, smart); } } } } } } JavaFXKind k = t.getJavaFXKind(); if (LOGGABLE) log(" fx kind: " + k); if (k == JavaFXKind.CLASS_DECLARATION) { TypeMirror tm = trees.getTypeMirror(tp); if (LOGGABLE) log(" tm == " + tm + " ---- tm.getKind() == " + (tm == null ? "null" : tm.getKind())); addMembers(tm, true, true); } if (k == JavaFXKind.BLOCK_EXPRESSION) { addBlockExpressionLocals((BlockExpressionTree) t, tp, smart); } if (k == JavaFXKind.FOR_EXPRESSION_FOR) { ForExpressionTree fet = (ForExpressionTree) t; if (LOGGABLE) log(" for expression: " + fet + "\n"); for (ForExpressionInClauseTree fetic : fet.getInClauses()) { if (LOGGABLE) log(" fetic: " + fetic + "\n"); String s = fetic.getVariable().getName().toString(); if (LOGGABLE) log(" adding(2) " + s + " with prefix " + prefix); TypeMirror tm = trees.getTypeMirror(new JavaFXTreePath(tp, fetic)); if (smart != null && tm.getKind() == smart.getKind()) { addResult(JavaFXCompletionItem.createVariableItem(s, offset, true)); } if (JavaFXCompletionProvider.startsWith(s, prefix)) { addResult(JavaFXCompletionItem.createVariableItem(s, offset, false)); } } } if (k == JavaFXKind.FUNCTION_VALUE) { FunctionValueTree fvt = (FunctionValueTree) t; for (VariableTree var : fvt.getParameters()) { if (LOGGABLE) log(" var: " + var + "\n"); String s = var.getName().toString(); if (LOGGABLE) log(" adding(3) " + s + " with prefix " + prefix); TypeMirror tm = trees.getTypeMirror(new JavaFXTreePath(tp, var)); if (smart != null && tm.getKind() == smart.getKind()) { addResult(JavaFXCompletionItem.createVariableItem(s, offset, true)); } if (JavaFXCompletionProvider.startsWith(s, prefix)) { addResult(JavaFXCompletionItem.createVariableItem(s, offset, false)); } } } if (k == JavaFXKind.ON_REPLACE) { OnReplaceTree ort = (OnReplaceTree) t; // commented out log because of JFXC-1205 // if (LOGGABLE) log(" OnReplaceTree: " + ort + "\n"); VariableTree varTree = ort.getNewElements(); if (varTree != null) { String s1 = varTree.getName().toString(); if (LOGGABLE) log(" adding(4) " + s1 + " with prefix " + prefix); TypeMirror tm = trees.getTypeMirror(new JavaFXTreePath(tp, varTree)); if (smart != null && tm.getKind() == smart.getKind()) { addResult(JavaFXCompletionItem.createVariableItem(s1, offset, true)); } if (JavaFXCompletionProvider.startsWith(s1, prefix)) { addResult(JavaFXCompletionItem.createVariableItem(s1, offset, false)); } } VariableTree varTree2 = ort.getOldValue(); if (varTree2 != null) { String s2 = varTree2.getName().toString(); if (LOGGABLE) log(" adding(5) " + s2 + " with prefix " + prefix); TypeMirror tm = trees.getTypeMirror(new JavaFXTreePath(tp, varTree2)); if (smart != null && tm.getKind() == smart.getKind()) { addResult(JavaFXCompletionItem.createVariableItem(s2, offset, true)); } if (JavaFXCompletionProvider.startsWith(s2, prefix)) { addResult(JavaFXCompletionItem.createVariableItem(s2, offset, false)); } } } } }
protected void addLocalMembersAndVars(TypeMirror smart) throws IOException { if (LOGGABLE) log("addLocalMembersAndVars: " + prefix); // controller.toPhase(Phase.ANALYZED); final JavafxcTrees trees = controller.getTrees(); if (smart != null && smart.getKind() == TypeKind.DECLARED) { if (LOGGABLE) log("adding declared type + subtypes: " + smart); DeclaredType dt = (DeclaredType) smart; TypeElement elem = (TypeElement) dt.asElement(); addResult(JavaFXCompletionItem.createTypeItem(elem, dt, offset, false, false, true)); for (DeclaredType subtype : getSubtypesOf((DeclaredType) smart)) { TypeElement subElem = (TypeElement) subtype.asElement(); addResult(JavaFXCompletionItem.createTypeItem(subElem, subtype, offset, false, false, true)); } } for (JavaFXTreePath tp = getPath(); tp != null; tp = tp.getParentPath()) { Tree t = tp.getLeaf(); if (LOGGABLE) log(" tree kind: " + t.getJavaFXKind()); if (t instanceof UnitTree) { UnitTree cut = (UnitTree) t; for (Tree tt : cut.getTypeDecls()) { if (LOGGABLE) log(" tt: " + tt); JavaFXKind kk = tt.getJavaFXKind(); if (kk == JavaFXKind.CLASS_DECLARATION) { JFXClassDeclaration cd = (JFXClassDeclaration) tt; for (Tree jct : cd.getClassMembers()) { if (LOGGABLE) log(" jct == " + jct); JavaFXKind k = jct.getJavaFXKind(); if (LOGGABLE) log(" kind of jct = " + k); if (k == JavaFXKind.FUNCTION_DEFINITION) { JFXFunctionDefinition fdt = (JFXFunctionDefinition) jct; if (LOGGABLE) log(" fdt == " + fdt.name.toString()); if ("javafx$run$".equals(fdt.name.toString())) { addBlockExpressionLocals(fdt.getBodyExpression(), tp, smart); } } } } } } JavaFXKind k = t.getJavaFXKind(); if (LOGGABLE) log(" fx kind: " + k); if (k == JavaFXKind.CLASS_DECLARATION) { TypeMirror tm = trees.getTypeMirror(tp); if (LOGGABLE) log(" tm == " + tm + " ---- tm.getKind() == " + (tm == null ? "null" : tm.getKind())); addMembers(tm, true, true); } if (k == JavaFXKind.BLOCK_EXPRESSION) { addBlockExpressionLocals((BlockExpressionTree) t, tp, smart); } if (k == JavaFXKind.FOR_EXPRESSION_FOR) { ForExpressionTree fet = (ForExpressionTree) t; if (LOGGABLE) log(" for expression: " + fet + "\n"); for (ForExpressionInClauseTree fetic : fet.getInClauses()) { if (LOGGABLE) log(" fetic: " + fetic + "\n"); String s = fetic.getVariable().getName().toString(); if (LOGGABLE) log(" adding(2) " + s + " with prefix " + prefix); TypeMirror tm = trees.getTypeMirror(new JavaFXTreePath(tp, fetic)); if (smart != null && tm != null && tm.getKind() == smart.getKind()) { addResult(JavaFXCompletionItem.createVariableItem(s, offset, true)); } if (JavaFXCompletionProvider.startsWith(s, prefix)) { addResult(JavaFXCompletionItem.createVariableItem(s, offset, false)); } } } if (k == JavaFXKind.FUNCTION_VALUE) { FunctionValueTree fvt = (FunctionValueTree) t; for (VariableTree var : fvt.getParameters()) { if (LOGGABLE) log(" var: " + var + "\n"); String s = var.getName().toString(); if (LOGGABLE) log(" adding(3) " + s + " with prefix " + prefix); TypeMirror tm = trees.getTypeMirror(new JavaFXTreePath(tp, var)); if (smart != null && tm.getKind() == smart.getKind()) { addResult(JavaFXCompletionItem.createVariableItem(s, offset, true)); } if (JavaFXCompletionProvider.startsWith(s, prefix)) { addResult(JavaFXCompletionItem.createVariableItem(s, offset, false)); } } } if (k == JavaFXKind.ON_REPLACE) { OnReplaceTree ort = (OnReplaceTree) t; // commented out log because of JFXC-1205 // if (LOGGABLE) log(" OnReplaceTree: " + ort + "\n"); VariableTree varTree = ort.getNewElements(); if (varTree != null) { String s1 = varTree.getName().toString(); if (LOGGABLE) log(" adding(4) " + s1 + " with prefix " + prefix); TypeMirror tm = trees.getTypeMirror(new JavaFXTreePath(tp, varTree)); if (smart != null && tm.getKind() == smart.getKind()) { addResult(JavaFXCompletionItem.createVariableItem(s1, offset, true)); } if (JavaFXCompletionProvider.startsWith(s1, prefix)) { addResult(JavaFXCompletionItem.createVariableItem(s1, offset, false)); } } VariableTree varTree2 = ort.getOldValue(); if (varTree2 != null) { String s2 = varTree2.getName().toString(); if (LOGGABLE) log(" adding(5) " + s2 + " with prefix " + prefix); TypeMirror tm = trees.getTypeMirror(new JavaFXTreePath(tp, varTree2)); if (smart != null && tm.getKind() == smart.getKind()) { addResult(JavaFXCompletionItem.createVariableItem(s2, offset, true)); } if (JavaFXCompletionProvider.startsWith(s2, prefix)) { addResult(JavaFXCompletionItem.createVariableItem(s2, offset, false)); } } } } }
diff --git a/src/view/SlotPanel.java b/src/view/SlotPanel.java index 111c30a..2dc067d 100644 --- a/src/view/SlotPanel.java +++ b/src/view/SlotPanel.java @@ -1,70 +1,70 @@ package view; import java.awt.Color; import java.awt.Graphics; import java.awt.image.BufferedImage; import javax.swing.JPanel; import resources.Translator; import model.items.weapons.Weapon; import model.sprites.Player; /** * A class that draws the picture that each weapon slot has in the HUD(PlayerPanel). * * @author Jonatan and Martin * */ public class SlotPanel extends JPanel{ private static final long serialVersionUID = 1L; private Player player; private static BufferedImage[] textures = Resources.splitImages("supplies.png", 5, 5); private static BufferedImage slot = Resources.getSingleImage("slot.png"); private int weaponIndex; /** * Creates an instance of a slot panel containing a picture and name of the weapon, * it also indicates if that weapon is selected by the player. * @param player the player holding the weapon. * @param weapon the weapon to display. */ public SlotPanel(Player player, Weapon weapon){ super(); this.setBackground(Color.BLACK); this.player = player; this.weaponIndex = player.getIndex(weapon); } //Using paint and not paintComponents as this panel does not have to be buffered nor transparent @Override public void paint(Graphics g){ g.setColor(new Color(0, 0, 0, 100)); g.fillRect(0, 0, this.getWidth(), this.getHeight()); g.drawImage(slot, this.getWidth()/2 - slot.getWidth()/2, 5, null); Weapon w = player.getWeapons()[weaponIndex]; if(w != null) { g.setColor(Color.WHITE); StringBuilder sb = new StringBuilder(); for(int i = 0; i < w.getKeys().length; i++) { - sb.append(Translator.getWeaponString(w.getKeys()[i]) + " "); + sb.append(Translator.getWeaponString(w.getKeys()[i])); } String text = sb.toString(); g.drawString(text, this.getWidth()/2 - (int)g.getFontMetrics().getStringBounds(text, g).getWidth()/2, this.getHeight() - 4); g.drawImage(textures[player.getWeapons()[weaponIndex].getIconNumber()], this.getWidth()/2 - slot.getWidth()/2, 5, null); } g.setColor(new Color(76, 76, 76)); g.drawRect(this.getWidth()/2 - slot.getWidth()/2, 5, slot.getWidth(), slot.getHeight()); //If this is the active weapon, draw some indications if(player.getActiveWeapon() == player.getWeapons()[weaponIndex]){ g.setColor(Color.RED); g.drawRect(0, 0, this.getWidth() - 1, this.getHeight() - 1); } } }
true
true
public void paint(Graphics g){ g.setColor(new Color(0, 0, 0, 100)); g.fillRect(0, 0, this.getWidth(), this.getHeight()); g.drawImage(slot, this.getWidth()/2 - slot.getWidth()/2, 5, null); Weapon w = player.getWeapons()[weaponIndex]; if(w != null) { g.setColor(Color.WHITE); StringBuilder sb = new StringBuilder(); for(int i = 0; i < w.getKeys().length; i++) { sb.append(Translator.getWeaponString(w.getKeys()[i]) + " "); } String text = sb.toString(); g.drawString(text, this.getWidth()/2 - (int)g.getFontMetrics().getStringBounds(text, g).getWidth()/2, this.getHeight() - 4); g.drawImage(textures[player.getWeapons()[weaponIndex].getIconNumber()], this.getWidth()/2 - slot.getWidth()/2, 5, null); } g.setColor(new Color(76, 76, 76)); g.drawRect(this.getWidth()/2 - slot.getWidth()/2, 5, slot.getWidth(), slot.getHeight()); //If this is the active weapon, draw some indications if(player.getActiveWeapon() == player.getWeapons()[weaponIndex]){ g.setColor(Color.RED); g.drawRect(0, 0, this.getWidth() - 1, this.getHeight() - 1); } }
public void paint(Graphics g){ g.setColor(new Color(0, 0, 0, 100)); g.fillRect(0, 0, this.getWidth(), this.getHeight()); g.drawImage(slot, this.getWidth()/2 - slot.getWidth()/2, 5, null); Weapon w = player.getWeapons()[weaponIndex]; if(w != null) { g.setColor(Color.WHITE); StringBuilder sb = new StringBuilder(); for(int i = 0; i < w.getKeys().length; i++) { sb.append(Translator.getWeaponString(w.getKeys()[i])); } String text = sb.toString(); g.drawString(text, this.getWidth()/2 - (int)g.getFontMetrics().getStringBounds(text, g).getWidth()/2, this.getHeight() - 4); g.drawImage(textures[player.getWeapons()[weaponIndex].getIconNumber()], this.getWidth()/2 - slot.getWidth()/2, 5, null); } g.setColor(new Color(76, 76, 76)); g.drawRect(this.getWidth()/2 - slot.getWidth()/2, 5, slot.getWidth(), slot.getHeight()); //If this is the active weapon, draw some indications if(player.getActiveWeapon() == player.getWeapons()[weaponIndex]){ g.setColor(Color.RED); g.drawRect(0, 0, this.getWidth() - 1, this.getHeight() - 1); } }
diff --git a/application/src/main/java/org/richfaces/tests/metamer/bean/RichCalendarBean.java b/application/src/main/java/org/richfaces/tests/metamer/bean/RichCalendarBean.java index 525bc74b..c63b4bc7 100644 --- a/application/src/main/java/org/richfaces/tests/metamer/bean/RichCalendarBean.java +++ b/application/src/main/java/org/richfaces/tests/metamer/bean/RichCalendarBean.java @@ -1,92 +1,94 @@ /******************************************************************************* * JBoss, Home of Professional Open Source * Copyright 2010, Red Hat, Inc. and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. *******************************************************************************/ package org.richfaces.tests.metamer.bean; import java.io.Serializable; import java.util.Date; import javax.annotation.PostConstruct; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import org.richfaces.component.UICalendar; import org.richfaces.tests.metamer.Attributes; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Managed bean for rich:calendar. * * @author <a href="mailto:[email protected]">Pavol Pitonak</a> * @version $Revision$ */ @ManagedBean(name = "richCalendarBean") @SessionScoped public class RichCalendarBean implements Serializable { private static final long serialVersionUID = -1L; private static Logger logger; private Attributes attributes; private Date date = new Date(); /** * Initializes the managed bean. */ @PostConstruct public void init() { logger = LoggerFactory.getLogger(getClass()); logger.debug("initializing bean " + getClass().getName()); attributes = Attributes.getUIComponentAttributes(UICalendar.class, getClass(), false); attributes.setAttribute("datePattern", "MMM d, yyyy HH:mm"); + attributes.setAttribute("direction", "bottom-right"); + attributes.setAttribute("jointPoint", "bottom-left"); attributes.setAttribute("popup", true); attributes.setAttribute("rendered", true); attributes.setAttribute("showApplyButton", true); attributes.setAttribute("showHeader", true); attributes.setAttribute("showFooter", true); attributes.setAttribute("showInput", true); attributes.setAttribute("showWeeksBar", true); attributes.setAttribute("showWeekDaysBar", true); // TODO has to be tested in another way attributes.remove("converter"); attributes.remove("validator"); attributes.remove("valueChangeListener"); } public Attributes getAttributes() { return attributes; } public void setAttributes(Attributes attributes) { this.attributes = attributes; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } }
true
true
public void init() { logger = LoggerFactory.getLogger(getClass()); logger.debug("initializing bean " + getClass().getName()); attributes = Attributes.getUIComponentAttributes(UICalendar.class, getClass(), false); attributes.setAttribute("datePattern", "MMM d, yyyy HH:mm"); attributes.setAttribute("popup", true); attributes.setAttribute("rendered", true); attributes.setAttribute("showApplyButton", true); attributes.setAttribute("showHeader", true); attributes.setAttribute("showFooter", true); attributes.setAttribute("showInput", true); attributes.setAttribute("showWeeksBar", true); attributes.setAttribute("showWeekDaysBar", true); // TODO has to be tested in another way attributes.remove("converter"); attributes.remove("validator"); attributes.remove("valueChangeListener"); }
public void init() { logger = LoggerFactory.getLogger(getClass()); logger.debug("initializing bean " + getClass().getName()); attributes = Attributes.getUIComponentAttributes(UICalendar.class, getClass(), false); attributes.setAttribute("datePattern", "MMM d, yyyy HH:mm"); attributes.setAttribute("direction", "bottom-right"); attributes.setAttribute("jointPoint", "bottom-left"); attributes.setAttribute("popup", true); attributes.setAttribute("rendered", true); attributes.setAttribute("showApplyButton", true); attributes.setAttribute("showHeader", true); attributes.setAttribute("showFooter", true); attributes.setAttribute("showInput", true); attributes.setAttribute("showWeeksBar", true); attributes.setAttribute("showWeekDaysBar", true); // TODO has to be tested in another way attributes.remove("converter"); attributes.remove("validator"); attributes.remove("valueChangeListener"); }
diff --git a/src/main/java/org/atlasapi/media/entity/simple/Location.java b/src/main/java/org/atlasapi/media/entity/simple/Location.java index 159bf824..b7b2858e 100644 --- a/src/main/java/org/atlasapi/media/entity/simple/Location.java +++ b/src/main/java/org/atlasapi/media/entity/simple/Location.java @@ -1,505 +1,507 @@ package org.atlasapi.media.entity.simple; /* Copyright 2010 Meta Broadcast Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import java.util.Date; import java.util.Set; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import org.atlasapi.media.TransportType; import org.atlasapi.media.vocabulary.PLAY_SIMPLE_XML; import org.joda.time.DateTime; import com.google.common.base.Function; import com.google.common.base.Objects; import com.google.common.base.Predicate; import com.google.common.base.Strings; import com.google.common.collect.Ordering; import com.google.common.collect.Sets; import com.metabroadcast.common.time.DateTimeZones; @XmlRootElement(namespace = PLAY_SIMPLE_XML.NS) @XmlType(name = "location", namespace = PLAY_SIMPLE_XML.NS) public class Location extends Version { private Integer advertisingDuration; private Integer audioBitRate; private Integer audioChannels; private String audioCoding; private Integer bitRate; private Boolean containsAdvertising; private String dataContainerFormat; private Long dataSize; private String distributor; private Boolean hasDOG; private String source; private String videoAspectRatio; private Integer videoBitRate; private String videoCoding; private Float videoFrameRate; private Integer videoHorizontalSize; private Boolean videoProgressiveScan; private Integer videoVerticalSize; private Date actualAvailabilityStart; private Date availabilityStart; private Date availabilityEnd; private Date drmPlayableFrom; private Set<String> availableCountries = Sets.newHashSet(); private String currency; private Integer price; private String revenueContract; private String restrictedBy; private Boolean transportIsLive; private String transportSubType; private String transportType; private String uri; private String embedCode; private String embedId; private String platform; private String network; private Boolean available; public String getUri() { return uri; } public void setUri(String uri) { this.uri = uri; } public String getDataContainerFormat() { return dataContainerFormat; } public void setDataContainerFormat(String dataContainerFormat) { this.dataContainerFormat = dataContainerFormat; } @XmlElementWrapper(namespace = PLAY_SIMPLE_XML.NS, name = "availableCountries") @XmlElement(name = "code") public Set<String> getAvailableCountries() { return availableCountries; } public void setAvailableCountries(Iterable<String> availableCountries) { this.availableCountries = Sets.newHashSet(availableCountries); } public String getCurrency() { return currency; } public void setCurrency(String currency) { this.currency = currency; } public Integer getPrice() { return price; } public void setPrice(Integer price) { this.price = price; } public String getRevenueContract() { return revenueContract; } public void setRevenueContract(String revenueContract) { this.revenueContract = revenueContract; } public Integer getAdvertisingDuration() { return advertisingDuration; } public void setAdvertisingDuration(Integer advertisingDuration) { this.advertisingDuration = advertisingDuration; } public Integer getAudioBitRate() { return audioBitRate; } public void setAudioBitRate(Integer audioBitRate) { this.audioBitRate = audioBitRate; } public Integer getAudioChannels() { return audioChannels; } public void setAudioChannels(Integer audioChannels) { this.audioChannels = audioChannels; } public String getAudioCoding() { return audioCoding; } public void setAudioCoding(String audioCoding) { this.audioCoding = audioCoding; } public Integer getBitRate() { return bitRate; } public void setBitRate(Integer bitRate) { this.bitRate = bitRate; } public Boolean getContainsAdvertising() { return containsAdvertising; } public void setContainsAdvertising(Boolean containsAdvertising) { this.containsAdvertising = containsAdvertising; } public Long getDataSize() { return dataSize; } public void setDataSize(Long dataSize) { this.dataSize = dataSize; } public String getDistributor() { return distributor; } public void setDistributor(String distributor) { this.distributor = distributor; } public Boolean getHasDOG() { return hasDOG; } public void setHasDOG(Boolean hasDOG) { this.hasDOG = hasDOG; } public String getSource() { return source; } public void setSource(String source) { this.source = source; } public String getVideoAspectRatio() { return videoAspectRatio; } public void setVideoAspectRatio(String videoAspectRatio) { this.videoAspectRatio = videoAspectRatio; } public Integer getVideoBitRate() { return videoBitRate; } public void setVideoBitRate(Integer videoBitRate) { this.videoBitRate = videoBitRate; } public String getVideoCoding() { return videoCoding; } public void setVideoCoding(String videoCoding) { this.videoCoding = videoCoding; } public Float getVideoFrameRate() { return videoFrameRate; } public void setVideoFrameRate(Float videoFrameRate) { this.videoFrameRate = videoFrameRate; } public Integer getVideoHorizontalSize() { return videoHorizontalSize; } public void setVideoHorizontalSize(Integer videoHorizontalSize) { this.videoHorizontalSize = videoHorizontalSize; } public Boolean getVideoProgressiveScan() { return videoProgressiveScan; } public void setVideoProgressiveScan(Boolean videoProgressiveScan) { this.videoProgressiveScan = videoProgressiveScan; } public Integer getVideoVerticalSize() { return videoVerticalSize; } public void setVideoVerticalSize(Integer videoVerticalSize) { this.videoVerticalSize = videoVerticalSize; } public Date getActualAvailabilityStart() { return actualAvailabilityStart; } public void setActualAvailabilityStart(Date actualAvailabilityStart) { this.actualAvailabilityStart = actualAvailabilityStart; } public Date getAvailabilityStart() { return availabilityStart; } public void setAvailabilityStart(Date availabilityStart) { this.availabilityStart = availabilityStart; } public Date getDrmPlayableFrom() { return drmPlayableFrom; } public void setDrmPlayableFrom(Date drmPlayableFrom) { this.drmPlayableFrom = drmPlayableFrom; } public String getRestrictedBy() { return restrictedBy; } public void setRestrictedBy(String restrictedBy) { this.restrictedBy = restrictedBy; } public Boolean getTransportIsLive() { return transportIsLive; } public void setTransportIsLive(Boolean transportIsLive) { this.transportIsLive = transportIsLive; } public String getTransportSubType() { return transportSubType; } public void setTransportSubType(String transportSubType) { this.transportSubType = transportSubType; } public String getTransportType() { return transportType; } public void setTransportType(String transportType) { this.transportType = transportType; } public String getEmbedCode() { return embedCode; } public void setEmbedCode(String embedCode) { this.embedCode = embedCode; } public String getEmbedId() { return embedId; } public void setEmbedId(String embedId) { this.embedId = embedId; } @XmlElement public boolean isAvailable() { return IS_AVAILABLE.apply(this); } public void setAvailable(boolean available) { this.available = available; } public void setAvailabilityEnd(Date availabilityEnd) { this.availabilityEnd = availabilityEnd; } public Date getAvailabilityEnd() { return availabilityEnd; } public void setPlatform(String platform) { this.platform = platform; } public String getPlatform() { return platform; } public void setNetwork(String network) { this.network = network; } public String getNetwork() { return network; } @Override public boolean equals(Object obj) { if (obj instanceof Location) { Location target = (Location) obj; if (isEmbed()) { return transportType.equals(target.transportType) && Objects.equal(embedCode, target.embedCode) && Objects.equal(embedId, target.embedId); } else if (!Strings.isNullOrEmpty(uri)) { return transportType.equals(target.transportType) && Objects.equal(uri, target.uri) && Objects.equal(actualAvailabilityStart, target.actualAvailabilityStart) && Objects.equal(availabilityStart, target.availabilityStart) && Objects.equal(platform, target.platform) && Objects.equal(network, target.network) && Objects.equal(availableCountries, target.availableCountries); } else { return super.equals(obj); } } return false; } @Override public int hashCode() { if (TransportType.EMBED.toString().equals(transportType) && !Strings.isNullOrEmpty(embedCode)) { return embedCode.hashCode(); } else if (TransportType.EMBED.toString().equals(transportType) && !Strings.isNullOrEmpty(embedId)) { return embedId.hashCode(); } else if (!Strings.isNullOrEmpty(uri)) { return Objects.hashCode(uri, transportType, actualAvailabilityStart, availabilityStart, platform, network, availableCountries); } else { return super.hashCode(); } } @Override public String toString() { if (isEmbed()) { return "embed location: " + embedCode + " and id: "+ embedId; } else { return transportType + " location: " + uri; } } private boolean isEmbed() { return TransportType.EMBED.toString().equals(transportType) && (!Strings.isNullOrEmpty(embedCode) || !Strings.isNullOrEmpty(embedId)); } public Location copy() { Location copy = new Location(); copyTo(copy); copy.setAdvertisingDuration(getAdvertisingDuration()); copy.setAudioBitRate(getAudioBitRate()); copy.setAudioChannels(getAudioChannels()); copy.setAudioCoding(getAudioCoding()); copy.setBitRate(getBitRate()); copy.setContainsAdvertising(getContainsAdvertising()); copy.setDataContainerFormat(getDataContainerFormat()); copy.setDataSize(getDataSize()); copy.setDistributor(getDistributor()); copy.setHasDOG(getHasDOG()); copy.setSource(getSource()); copy.setVideoAspectRatio(getVideoAspectRatio()); copy.setVideoBitRate(getVideoBitRate()); copy.setVideoCoding(getVideoCoding()); copy.setVideoFrameRate(getVideoFrameRate()); copy.setVideoHorizontalSize(getVideoHorizontalSize()); copy.setVideoProgressiveScan(getVideoProgressiveScan()); copy.setVideoVerticalSize(getVideoVerticalSize()); if (getActualAvailabilityStart() != null) { copy.setActualAvailabilityStart((Date) getActualAvailabilityStart().clone()); } if (getAvailabilityStart() != null) { copy.setAvailabilityStart((Date) getAvailabilityStart().clone()); } if (getAvailabilityEnd() != null) { copy.setAvailabilityEnd((Date) getAvailabilityEnd().clone()); } if (getDrmPlayableFrom() != null) { copy.setDrmPlayableFrom((Date) getDrmPlayableFrom().clone()); } copy.setAvailableCountries(getAvailableCountries()); copy.setCurrency(getCurrency()); copy.setPrice(getPrice()); copy.setRevenueContract(getRevenueContract()); copy.setRestrictedBy(getRestrictedBy()); copy.setTransportType(getTransportType()); copy.setTransportIsLive(getTransportIsLive()); copy.setTransportSubType(getTransportSubType()); copy.setUri(getUri()); copy.setEmbedCode(getEmbedCode()); copy.setEmbedId(getEmbedId()); copy.setPlatform(getPlatform()); copy.setNetwork(getNetwork()); - copy.setAvailable(available); + if (available != null) { + copy.setAvailable(available); + } return copy; } public static final Predicate<Location> IS_AVAILABLE = new Predicate<Location>() { @Override public boolean apply(Location input) { Date start = input.getActualAvailabilityStart(); start = start == null ? input.getAvailabilityStart() : start; return (input.available == null || input.available) && (start == null || ! (new DateTime(start).isAfterNow())) && (input.getAvailabilityEnd() == null || new DateTime(input.getAvailabilityEnd()).isAfterNow()); } }; public static final Predicate<Location> IS_UPCOMING = new Predicate<Location>() { @Override public boolean apply(Location input) { return input.getAvailabilityStart() != null && new DateTime(input.getAvailabilityStart(), DateTimeZones.UTC).isAfterNow(); } }; public static final Ordering<Location> BY_AVAILABILITY_START = new Ordering<Location>() { @Override public int compare(Location left, Location right) { return left.getAvailabilityStart().compareTo(right.getAvailabilityStart()); } }; public static final Function<Location, Location> TO_COPY = new Function<Location, Location>() { @Override public Location apply(Location input) { return input.copy(); } }; }
true
true
public Location copy() { Location copy = new Location(); copyTo(copy); copy.setAdvertisingDuration(getAdvertisingDuration()); copy.setAudioBitRate(getAudioBitRate()); copy.setAudioChannels(getAudioChannels()); copy.setAudioCoding(getAudioCoding()); copy.setBitRate(getBitRate()); copy.setContainsAdvertising(getContainsAdvertising()); copy.setDataContainerFormat(getDataContainerFormat()); copy.setDataSize(getDataSize()); copy.setDistributor(getDistributor()); copy.setHasDOG(getHasDOG()); copy.setSource(getSource()); copy.setVideoAspectRatio(getVideoAspectRatio()); copy.setVideoBitRate(getVideoBitRate()); copy.setVideoCoding(getVideoCoding()); copy.setVideoFrameRate(getVideoFrameRate()); copy.setVideoHorizontalSize(getVideoHorizontalSize()); copy.setVideoProgressiveScan(getVideoProgressiveScan()); copy.setVideoVerticalSize(getVideoVerticalSize()); if (getActualAvailabilityStart() != null) { copy.setActualAvailabilityStart((Date) getActualAvailabilityStart().clone()); } if (getAvailabilityStart() != null) { copy.setAvailabilityStart((Date) getAvailabilityStart().clone()); } if (getAvailabilityEnd() != null) { copy.setAvailabilityEnd((Date) getAvailabilityEnd().clone()); } if (getDrmPlayableFrom() != null) { copy.setDrmPlayableFrom((Date) getDrmPlayableFrom().clone()); } copy.setAvailableCountries(getAvailableCountries()); copy.setCurrency(getCurrency()); copy.setPrice(getPrice()); copy.setRevenueContract(getRevenueContract()); copy.setRestrictedBy(getRestrictedBy()); copy.setTransportType(getTransportType()); copy.setTransportIsLive(getTransportIsLive()); copy.setTransportSubType(getTransportSubType()); copy.setUri(getUri()); copy.setEmbedCode(getEmbedCode()); copy.setEmbedId(getEmbedId()); copy.setPlatform(getPlatform()); copy.setNetwork(getNetwork()); copy.setAvailable(available); return copy; }
public Location copy() { Location copy = new Location(); copyTo(copy); copy.setAdvertisingDuration(getAdvertisingDuration()); copy.setAudioBitRate(getAudioBitRate()); copy.setAudioChannels(getAudioChannels()); copy.setAudioCoding(getAudioCoding()); copy.setBitRate(getBitRate()); copy.setContainsAdvertising(getContainsAdvertising()); copy.setDataContainerFormat(getDataContainerFormat()); copy.setDataSize(getDataSize()); copy.setDistributor(getDistributor()); copy.setHasDOG(getHasDOG()); copy.setSource(getSource()); copy.setVideoAspectRatio(getVideoAspectRatio()); copy.setVideoBitRate(getVideoBitRate()); copy.setVideoCoding(getVideoCoding()); copy.setVideoFrameRate(getVideoFrameRate()); copy.setVideoHorizontalSize(getVideoHorizontalSize()); copy.setVideoProgressiveScan(getVideoProgressiveScan()); copy.setVideoVerticalSize(getVideoVerticalSize()); if (getActualAvailabilityStart() != null) { copy.setActualAvailabilityStart((Date) getActualAvailabilityStart().clone()); } if (getAvailabilityStart() != null) { copy.setAvailabilityStart((Date) getAvailabilityStart().clone()); } if (getAvailabilityEnd() != null) { copy.setAvailabilityEnd((Date) getAvailabilityEnd().clone()); } if (getDrmPlayableFrom() != null) { copy.setDrmPlayableFrom((Date) getDrmPlayableFrom().clone()); } copy.setAvailableCountries(getAvailableCountries()); copy.setCurrency(getCurrency()); copy.setPrice(getPrice()); copy.setRevenueContract(getRevenueContract()); copy.setRestrictedBy(getRestrictedBy()); copy.setTransportType(getTransportType()); copy.setTransportIsLive(getTransportIsLive()); copy.setTransportSubType(getTransportSubType()); copy.setUri(getUri()); copy.setEmbedCode(getEmbedCode()); copy.setEmbedId(getEmbedId()); copy.setPlatform(getPlatform()); copy.setNetwork(getNetwork()); if (available != null) { copy.setAvailable(available); } return copy; }
diff --git a/txtfnnl-bin/src/main/java/txtfnnl/pipelines/GeneNormalization.java b/txtfnnl-bin/src/main/java/txtfnnl/pipelines/GeneNormalization.java index d37b870..42fdc21 100644 --- a/txtfnnl-bin/src/main/java/txtfnnl/pipelines/GeneNormalization.java +++ b/txtfnnl-bin/src/main/java/txtfnnl/pipelines/GeneNormalization.java @@ -1,157 +1,157 @@ package txtfnnl.pipelines; import java.io.File; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.cli.PosixParser; import org.apache.uima.UIMAException; import org.apache.uima.resource.ExternalResourceDescription; import org.apache.uima.resource.ResourceInitializationException; import txtfnnl.uima.analysis_component.GeneAnnotator; import txtfnnl.uima.analysis_component.GeniaTaggerAnnotator; import txtfnnl.uima.analysis_component.NOOPAnnotator; import txtfnnl.uima.analysis_component.opennlp.SentenceAnnotator; import txtfnnl.uima.analysis_component.opennlp.TokenAnnotator; import txtfnnl.uima.collection.AnnotationLineWriter; import txtfnnl.uima.resource.GnamedGazetteerResource; /** * A pipeline to detect gene and protein names that match names recorded in databases. * <p> * Input files can be read from a directory or listed explicitly, while output lines are written to * some directory or to STDOUT. Output is written as tab-separated values, where each line contains * the matched text, the gene ID, the taxon ID, and a confidence value. * <p> * The default setup assumes gene and/or protein entities found in a <a * href="https://github.com/fnl/gnamed">gnamed</a> database. * * @author Florian Leitner */ public class GeneNormalization extends Pipeline { static final String DEFAULT_DATABASE = "gnamed"; static final String DEFAULT_JDBC_DRIVER = "org.postgresql.Driver"; static final String DEFAULT_DB_PROVIDER = "postgresql"; // default: all known gene and protein symbols static final String SQL_QUERY = "SELECT gr.accession, g.species_id, ps.value " + "FROM gene_refs AS gr, genes AS g, genes2proteins AS g2p, protein_strings AS ps " + "WHERE gr.namespace = 'gi' AND gr.id = g.id AND g.id = g2p.gene_id AND g2p.protein_id = ps.id AND ps.cat = 'symbol' " + "UNION SELECT gr.accession, g.species_id, gs.value " + "FROM gene_refs AS gr, genes AS g, gene_strings AS gs " + "WHERE gr.namespace = 'gi' AND gr.id = g.id AND gr.id = gs.id AND gs.cat = 'symbol'"; private GeneNormalization() { throw new AssertionError("n/a"); } public static void main(String[] arguments) { final CommandLineParser parser = new PosixParser(); final Options opts = new Options(); CommandLine cmd = null; Pipeline.addLogHelpAndInputOptions(opts); Pipeline.addTikaOptions(opts); Pipeline.addJdbcResourceOptions(opts, DEFAULT_JDBC_DRIVER, DEFAULT_DB_PROVIDER, DEFAULT_DATABASE); Pipeline.addOutputOptions(opts); // sentence splitter options opts.addOption("S", "successive-newlines", false, "split sentences on successive newlines"); opts.addOption("s", "single-newlines", false, "split sentences on single newlines"); // tokenizer options setup opts.addOption("G", "genia", true, "use GENIA (with the dir containing 'morphdic/') instead of OpenNLP"); // query options - opts.addOption("q", "query", true, "SQL query that produces gene ID, tax ID, name triplets"); + opts.addOption("Q", "query", true, "SQL query that produces gene ID, tax ID, name triplets"); try { cmd = parser.parse(opts, arguments); } catch (final ParseException e) { System.err.println(e.getLocalizedMessage()); System.exit(1); // == EXIT == } final Logger l = Pipeline.loggingSetup(cmd, opts, "txtfnnl gn [options] <directory|files...>\n"); // sentence splitter String splitSentences = null; // S, s if (cmd.hasOption('s')) { splitSentences = "single"; } else if (cmd.hasOption('S')) { splitSentences = "successive"; } // (GENIA) tokenizer final String geniaDir = cmd.getOptionValue('G'); // query - final String querySql = cmd.hasOption('q') ? cmd.getOptionValue('q') : SQL_QUERY; + final String querySql = cmd.hasOption('Q') ? cmd.getOptionValue('Q') : SQL_QUERY; // DB resource ExternalResourceDescription geneGazetteer = null; try { final String driverClass = cmd.getOptionValue('D', DEFAULT_JDBC_DRIVER); Class.forName(driverClass); // db url final String dbHost = cmd.getOptionValue('H', "localhost"); final String dbProvider = cmd.getOptionValue('P', DEFAULT_DB_PROVIDER); final String dbName = cmd.getOptionValue('d', DEFAULT_DATABASE); final String dbUrl = String.format("jdbc:%s://%s/%s", dbProvider, dbHost, dbName); l.log(Level.INFO, "JDBC URL: {0}", dbUrl); // create builder GnamedGazetteerResource.Builder b = GnamedGazetteerResource.configure(dbUrl, driverClass, querySql); // set username/password options if (cmd.hasOption('u')) b.setUsername(cmd.getOptionValue('u')); if (cmd.hasOption('p')) b.setPassword(cmd.getOptionValue('p')); geneGazetteer = b.create(); } catch (final ResourceInitializationException e) { System.err.println("JDBC resoruce setup failed:"); System.err.println(e.toString()); System.exit(1); // == EXIT == } catch (final ClassNotFoundException e) { System.err.println("JDBC driver class unknown:"); System.err.println(e.toString()); System.exit(1); // == EXIT == } // output final String geneAnnotationNamespace = "gene"; AnnotationLineWriter.Builder alw = AnnotationLineWriter.configureTodo() .setAnnotatorUri(GeneAnnotator.URI).setAnnotationNamespace(geneAnnotationNamespace); alw.setEncoding(Pipeline.outputEncoding(cmd)); alw.setOutputDirectory(Pipeline.outputDirectory(cmd)); if (Pipeline.outputOverwriteFiles(cmd)) alw.overwriteFiles(); try { // 0:tika, 1:splitter, 2:tokenizer, (3:NOOP), 4:gazetteer final Pipeline gn = new Pipeline(5); gn.setReader(cmd); gn.configureTika(cmd); gn.set(1, SentenceAnnotator.configure(splitSentences)); if (geniaDir == null) { gn.set(2, TokenAnnotator.configure()); // gn.set(4, BioLemmatizerAnnotator.configure()); gn.set(3, NOOPAnnotator.configure()); } else { gn.set(2, GeniaTaggerAnnotator.configure().setDirectory(new File(geniaDir)).create()); // the GENIA Tagger already lemmatizes; nothing to do gn.set(3, NOOPAnnotator.configure()); } gn.set( 4, GeneAnnotator.configure(geneAnnotationNamespace, geneGazetteer) .setTextNamespace(SentenceAnnotator.NAMESPACE) .setTextIdentifier(SentenceAnnotator.IDENTIFIER).create()); gn.setConsumer(alw.create()); gn.run(); } catch (final UIMAException e) { l.severe(e.toString()); System.err.println(e.getLocalizedMessage()); e.printStackTrace(); System.exit(1); // == EXIT == } catch (final IOException e) { l.severe(e.toString()); System.err.println(e.getLocalizedMessage()); System.exit(1); // == EXIT == } System.exit(0); } }
false
true
public static void main(String[] arguments) { final CommandLineParser parser = new PosixParser(); final Options opts = new Options(); CommandLine cmd = null; Pipeline.addLogHelpAndInputOptions(opts); Pipeline.addTikaOptions(opts); Pipeline.addJdbcResourceOptions(opts, DEFAULT_JDBC_DRIVER, DEFAULT_DB_PROVIDER, DEFAULT_DATABASE); Pipeline.addOutputOptions(opts); // sentence splitter options opts.addOption("S", "successive-newlines", false, "split sentences on successive newlines"); opts.addOption("s", "single-newlines", false, "split sentences on single newlines"); // tokenizer options setup opts.addOption("G", "genia", true, "use GENIA (with the dir containing 'morphdic/') instead of OpenNLP"); // query options opts.addOption("q", "query", true, "SQL query that produces gene ID, tax ID, name triplets"); try { cmd = parser.parse(opts, arguments); } catch (final ParseException e) { System.err.println(e.getLocalizedMessage()); System.exit(1); // == EXIT == } final Logger l = Pipeline.loggingSetup(cmd, opts, "txtfnnl gn [options] <directory|files...>\n"); // sentence splitter String splitSentences = null; // S, s if (cmd.hasOption('s')) { splitSentences = "single"; } else if (cmd.hasOption('S')) { splitSentences = "successive"; } // (GENIA) tokenizer final String geniaDir = cmd.getOptionValue('G'); // query final String querySql = cmd.hasOption('q') ? cmd.getOptionValue('q') : SQL_QUERY; // DB resource ExternalResourceDescription geneGazetteer = null; try { final String driverClass = cmd.getOptionValue('D', DEFAULT_JDBC_DRIVER); Class.forName(driverClass); // db url final String dbHost = cmd.getOptionValue('H', "localhost"); final String dbProvider = cmd.getOptionValue('P', DEFAULT_DB_PROVIDER); final String dbName = cmd.getOptionValue('d', DEFAULT_DATABASE); final String dbUrl = String.format("jdbc:%s://%s/%s", dbProvider, dbHost, dbName); l.log(Level.INFO, "JDBC URL: {0}", dbUrl); // create builder GnamedGazetteerResource.Builder b = GnamedGazetteerResource.configure(dbUrl, driverClass, querySql); // set username/password options if (cmd.hasOption('u')) b.setUsername(cmd.getOptionValue('u')); if (cmd.hasOption('p')) b.setPassword(cmd.getOptionValue('p')); geneGazetteer = b.create(); } catch (final ResourceInitializationException e) { System.err.println("JDBC resoruce setup failed:"); System.err.println(e.toString()); System.exit(1); // == EXIT == } catch (final ClassNotFoundException e) { System.err.println("JDBC driver class unknown:"); System.err.println(e.toString()); System.exit(1); // == EXIT == } // output final String geneAnnotationNamespace = "gene"; AnnotationLineWriter.Builder alw = AnnotationLineWriter.configureTodo() .setAnnotatorUri(GeneAnnotator.URI).setAnnotationNamespace(geneAnnotationNamespace); alw.setEncoding(Pipeline.outputEncoding(cmd)); alw.setOutputDirectory(Pipeline.outputDirectory(cmd)); if (Pipeline.outputOverwriteFiles(cmd)) alw.overwriteFiles(); try { // 0:tika, 1:splitter, 2:tokenizer, (3:NOOP), 4:gazetteer final Pipeline gn = new Pipeline(5); gn.setReader(cmd); gn.configureTika(cmd); gn.set(1, SentenceAnnotator.configure(splitSentences)); if (geniaDir == null) { gn.set(2, TokenAnnotator.configure()); // gn.set(4, BioLemmatizerAnnotator.configure()); gn.set(3, NOOPAnnotator.configure()); } else { gn.set(2, GeniaTaggerAnnotator.configure().setDirectory(new File(geniaDir)).create()); // the GENIA Tagger already lemmatizes; nothing to do gn.set(3, NOOPAnnotator.configure()); } gn.set( 4, GeneAnnotator.configure(geneAnnotationNamespace, geneGazetteer) .setTextNamespace(SentenceAnnotator.NAMESPACE) .setTextIdentifier(SentenceAnnotator.IDENTIFIER).create()); gn.setConsumer(alw.create()); gn.run(); } catch (final UIMAException e) { l.severe(e.toString()); System.err.println(e.getLocalizedMessage()); e.printStackTrace(); System.exit(1); // == EXIT == } catch (final IOException e) { l.severe(e.toString()); System.err.println(e.getLocalizedMessage()); System.exit(1); // == EXIT == } System.exit(0); }
public static void main(String[] arguments) { final CommandLineParser parser = new PosixParser(); final Options opts = new Options(); CommandLine cmd = null; Pipeline.addLogHelpAndInputOptions(opts); Pipeline.addTikaOptions(opts); Pipeline.addJdbcResourceOptions(opts, DEFAULT_JDBC_DRIVER, DEFAULT_DB_PROVIDER, DEFAULT_DATABASE); Pipeline.addOutputOptions(opts); // sentence splitter options opts.addOption("S", "successive-newlines", false, "split sentences on successive newlines"); opts.addOption("s", "single-newlines", false, "split sentences on single newlines"); // tokenizer options setup opts.addOption("G", "genia", true, "use GENIA (with the dir containing 'morphdic/') instead of OpenNLP"); // query options opts.addOption("Q", "query", true, "SQL query that produces gene ID, tax ID, name triplets"); try { cmd = parser.parse(opts, arguments); } catch (final ParseException e) { System.err.println(e.getLocalizedMessage()); System.exit(1); // == EXIT == } final Logger l = Pipeline.loggingSetup(cmd, opts, "txtfnnl gn [options] <directory|files...>\n"); // sentence splitter String splitSentences = null; // S, s if (cmd.hasOption('s')) { splitSentences = "single"; } else if (cmd.hasOption('S')) { splitSentences = "successive"; } // (GENIA) tokenizer final String geniaDir = cmd.getOptionValue('G'); // query final String querySql = cmd.hasOption('Q') ? cmd.getOptionValue('Q') : SQL_QUERY; // DB resource ExternalResourceDescription geneGazetteer = null; try { final String driverClass = cmd.getOptionValue('D', DEFAULT_JDBC_DRIVER); Class.forName(driverClass); // db url final String dbHost = cmd.getOptionValue('H', "localhost"); final String dbProvider = cmd.getOptionValue('P', DEFAULT_DB_PROVIDER); final String dbName = cmd.getOptionValue('d', DEFAULT_DATABASE); final String dbUrl = String.format("jdbc:%s://%s/%s", dbProvider, dbHost, dbName); l.log(Level.INFO, "JDBC URL: {0}", dbUrl); // create builder GnamedGazetteerResource.Builder b = GnamedGazetteerResource.configure(dbUrl, driverClass, querySql); // set username/password options if (cmd.hasOption('u')) b.setUsername(cmd.getOptionValue('u')); if (cmd.hasOption('p')) b.setPassword(cmd.getOptionValue('p')); geneGazetteer = b.create(); } catch (final ResourceInitializationException e) { System.err.println("JDBC resoruce setup failed:"); System.err.println(e.toString()); System.exit(1); // == EXIT == } catch (final ClassNotFoundException e) { System.err.println("JDBC driver class unknown:"); System.err.println(e.toString()); System.exit(1); // == EXIT == } // output final String geneAnnotationNamespace = "gene"; AnnotationLineWriter.Builder alw = AnnotationLineWriter.configureTodo() .setAnnotatorUri(GeneAnnotator.URI).setAnnotationNamespace(geneAnnotationNamespace); alw.setEncoding(Pipeline.outputEncoding(cmd)); alw.setOutputDirectory(Pipeline.outputDirectory(cmd)); if (Pipeline.outputOverwriteFiles(cmd)) alw.overwriteFiles(); try { // 0:tika, 1:splitter, 2:tokenizer, (3:NOOP), 4:gazetteer final Pipeline gn = new Pipeline(5); gn.setReader(cmd); gn.configureTika(cmd); gn.set(1, SentenceAnnotator.configure(splitSentences)); if (geniaDir == null) { gn.set(2, TokenAnnotator.configure()); // gn.set(4, BioLemmatizerAnnotator.configure()); gn.set(3, NOOPAnnotator.configure()); } else { gn.set(2, GeniaTaggerAnnotator.configure().setDirectory(new File(geniaDir)).create()); // the GENIA Tagger already lemmatizes; nothing to do gn.set(3, NOOPAnnotator.configure()); } gn.set( 4, GeneAnnotator.configure(geneAnnotationNamespace, geneGazetteer) .setTextNamespace(SentenceAnnotator.NAMESPACE) .setTextIdentifier(SentenceAnnotator.IDENTIFIER).create()); gn.setConsumer(alw.create()); gn.run(); } catch (final UIMAException e) { l.severe(e.toString()); System.err.println(e.getLocalizedMessage()); e.printStackTrace(); System.exit(1); // == EXIT == } catch (final IOException e) { l.severe(e.toString()); System.err.println(e.getLocalizedMessage()); System.exit(1); // == EXIT == } System.exit(0); }
diff --git a/src/com/neuro_immune_detector_core/services/FileExtractorImpl.java b/src/com/neuro_immune_detector_core/services/FileExtractorImpl.java index 84f739e..d58797e 100644 --- a/src/com/neuro_immune_detector_core/services/FileExtractorImpl.java +++ b/src/com/neuro_immune_detector_core/services/FileExtractorImpl.java @@ -1,36 +1,36 @@ package com.neuro_immune_detector_core.services; import java.io.File; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Set; import com.neuro_immune_detector_core.helpers.RandomHelper; import com.neuro_immune_detector_core.repositories.FileRepository; public class FileExtractorImpl implements FileExtractor { @Override public Collection<File> getRandomFiles(FileRepository repository, int numberOfFiles) { if (repository.size() < numberOfFiles) { throw new IllegalArgumentException("Repository's size is less than requested numberOfFiles"); } Set<File> res = new HashSet<File>(numberOfFiles); int repositorySize = repository.size(); for(int i = repositorySize - numberOfFiles; i < repositorySize; i++) { - int pos = RandomHelper.getRandomValue(i + 1); + int pos = RandomHelper.getRandomValue(i); File file = repository.get(pos); if (res.contains(file)) { res.add(repository.get(i)); } else { res.add(file); } } return Collections.unmodifiableCollection(res); } }
true
true
public Collection<File> getRandomFiles(FileRepository repository, int numberOfFiles) { if (repository.size() < numberOfFiles) { throw new IllegalArgumentException("Repository's size is less than requested numberOfFiles"); } Set<File> res = new HashSet<File>(numberOfFiles); int repositorySize = repository.size(); for(int i = repositorySize - numberOfFiles; i < repositorySize; i++) { int pos = RandomHelper.getRandomValue(i + 1); File file = repository.get(pos); if (res.contains(file)) { res.add(repository.get(i)); } else { res.add(file); } } return Collections.unmodifiableCollection(res); }
public Collection<File> getRandomFiles(FileRepository repository, int numberOfFiles) { if (repository.size() < numberOfFiles) { throw new IllegalArgumentException("Repository's size is less than requested numberOfFiles"); } Set<File> res = new HashSet<File>(numberOfFiles); int repositorySize = repository.size(); for(int i = repositorySize - numberOfFiles; i < repositorySize; i++) { int pos = RandomHelper.getRandomValue(i); File file = repository.get(pos); if (res.contains(file)) { res.add(repository.get(i)); } else { res.add(file); } } return Collections.unmodifiableCollection(res); }
diff --git a/cruisecontrol/main/src/net/sourceforge/cruisecontrol/Builder.java b/cruisecontrol/main/src/net/sourceforge/cruisecontrol/Builder.java index 36becee5..8baefe57 100644 --- a/cruisecontrol/main/src/net/sourceforge/cruisecontrol/Builder.java +++ b/cruisecontrol/main/src/net/sourceforge/cruisecontrol/Builder.java @@ -1,199 +1,203 @@ /******************************************************************************** * CruiseControl, a Continuous Integration Toolkit * Copyright (c) 2001, ThoughtWorks, Inc. * 200 E. Randolph, 25th Floor * Chicago, IL 60601 USA * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * + Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * + Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * + Neither the name of ThoughtWorks, Inc., CruiseControl, 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 REGENTS 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 net.sourceforge.cruisecontrol; import java.io.File; import java.io.IOException; import java.util.Calendar; import java.util.Date; import java.util.Map; import net.sourceforge.cruisecontrol.util.BuildOutputLogger; import net.sourceforge.cruisecontrol.util.PerDayScheduleItem; import net.sourceforge.cruisecontrol.util.ValidationHelper; import org.jdom.Element; public abstract class Builder extends PerDayScheduleItem implements Comparable { private int time = NOT_SET; private int multiple = 1; private boolean multipleSet = false; private boolean showProgress = true; private boolean isLiveOutput = true; private BuildOutputLogger buildOutputLogger; /** Build property name of property that is pass to all builders. */ public static final String BUILD_PROP_PROJECTNAME = "projectname"; /** * Execute a build. * @param properties build properties * @param progress callback to provide progress updates * @return the log resulting from executing the build * @throws CruiseControlException if something breaks */ public abstract Element build(Map<String, String> properties, Progress progress) throws CruiseControlException; /** * Execute a build with the given target. * @param properties build properties * @param target the build target to call, overrides target defined in config * @param progress callback to provide progress updates * @return the log resulting from executing the build * @throws CruiseControlException if something breaks */ public abstract Element buildWithTarget(Map<String, String> properties, String target, Progress progress) throws CruiseControlException; public void validate() throws CruiseControlException { boolean timeSet = time != NOT_SET; if (timeSet) { ValidationHelper.assertFalse(time < 0, "negative values for time are not allowed"); } ValidationHelper.assertFalse(timeSet && multipleSet, "Only one of 'time' or 'multiple' are allowed on builders."); } public int getTime() { return time; } /** * can use ScheduleItem.NOT_SET to reset. * @param timeString new time integer */ public void setTime(String timeString) { time = Integer.parseInt(timeString); } /** * can use Builder.NOT_SET to reset. * @param multiple new multiple */ public void setMultiple(int multiple) { multipleSet = multiple != NOT_SET; this.multiple = multiple; } public int getMultiple() { boolean timeSet = time != NOT_SET; if (timeSet && !multipleSet) { return NOT_SET; } return multiple; } public void setShowProgress(final boolean showProgress) { this.showProgress = showProgress; } public boolean getShowProgress() { return showProgress; } public void setLiveOutput(final boolean isLiveOutputEnabled) { isLiveOutput = isLiveOutputEnabled; } public boolean isLiveOutput() { return isLiveOutput; } protected BuildOutputLogger getBuildOutputConsumer(final String projectName, final File workingDir, final String logFilename) { if (isLiveOutput && buildOutputLogger == null) { final File outputFile; if (logFilename != null) { outputFile = new File(workingDir, logFilename); } else { + final String safeProjectName; + if (projectName != null) { + safeProjectName = projectName.replaceAll("/", "_"); // replace prevents error if name has slash + } else { + safeProjectName = null; + } try { outputFile = File.createTempFile( - "ccLiveOutput-" - + projectName.replaceAll("/", "_") // replace prevents error if name has slash - + "-" + getClass().getSimpleName() + "-", + "ccLiveOutput-" + safeProjectName + "-" + getClass().getSimpleName() + "-", ".tmp", workingDir); } catch (IOException e) { throw new RuntimeException(e); } } outputFile.deleteOnExit(); final BuildOutputLogger buildOutputConsumer = BuildOutputLoggerManager.INSTANCE.lookupOrCreate(projectName, outputFile); buildOutputConsumer.clear(); buildOutputLogger = buildOutputConsumer; } return buildOutputLogger; } /** * Is this the correct day to be running this builder? * @param now the current date * @return true if this this the correct day to be running this builder */ public boolean isValidDay(Date now) { if (getDay() < 0) { return true; } Calendar cal = Calendar.getInstance(); cal.setTime(now); return cal.get(Calendar.DAY_OF_WEEK) == getDay(); } /** * used to sort builders. we're only going to care about sorting builders based on build number, * so we'll sort based on the multiple attribute. */ public int compareTo(Object o) { Builder builder = (Builder) o; Integer integer = new Integer(multiple); Integer integer2 = new Integer(builder.getMultiple()); return integer2.compareTo(integer); //descending order } public boolean isTimeBuilder() { return time != NOT_SET; } }
false
true
protected BuildOutputLogger getBuildOutputConsumer(final String projectName, final File workingDir, final String logFilename) { if (isLiveOutput && buildOutputLogger == null) { final File outputFile; if (logFilename != null) { outputFile = new File(workingDir, logFilename); } else { try { outputFile = File.createTempFile( "ccLiveOutput-" + projectName.replaceAll("/", "_") // replace prevents error if name has slash + "-" + getClass().getSimpleName() + "-", ".tmp", workingDir); } catch (IOException e) { throw new RuntimeException(e); } } outputFile.deleteOnExit(); final BuildOutputLogger buildOutputConsumer = BuildOutputLoggerManager.INSTANCE.lookupOrCreate(projectName, outputFile); buildOutputConsumer.clear(); buildOutputLogger = buildOutputConsumer; } return buildOutputLogger; }
protected BuildOutputLogger getBuildOutputConsumer(final String projectName, final File workingDir, final String logFilename) { if (isLiveOutput && buildOutputLogger == null) { final File outputFile; if (logFilename != null) { outputFile = new File(workingDir, logFilename); } else { final String safeProjectName; if (projectName != null) { safeProjectName = projectName.replaceAll("/", "_"); // replace prevents error if name has slash } else { safeProjectName = null; } try { outputFile = File.createTempFile( "ccLiveOutput-" + safeProjectName + "-" + getClass().getSimpleName() + "-", ".tmp", workingDir); } catch (IOException e) { throw new RuntimeException(e); } } outputFile.deleteOnExit(); final BuildOutputLogger buildOutputConsumer = BuildOutputLoggerManager.INSTANCE.lookupOrCreate(projectName, outputFile); buildOutputConsumer.clear(); buildOutputLogger = buildOutputConsumer; } return buildOutputLogger; }
diff --git a/src/de/ub0r/android/smsdroid/SmsReceiver.java b/src/de/ub0r/android/smsdroid/SmsReceiver.java index 06d04a5..439b453 100644 --- a/src/de/ub0r/android/smsdroid/SmsReceiver.java +++ b/src/de/ub0r/android/smsdroid/SmsReceiver.java @@ -1,433 +1,433 @@ /* * Copyright (C) 2010 Felix Bechstein * * This file is part of SMSdroid. * * 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 de.ub0r.android.smsdroid; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.appwidget.AppWidgetManager; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.provider.CallLog.Calls; import android.telephony.gsm.SmsMessage; import de.ub0r.android.lib.Log; /** * Listen for new sms. * * @author flx */ @SuppressWarnings("deprecation") public class SmsReceiver extends BroadcastReceiver { /** Tag for logging. */ static final String TAG = "bcr"; /** {@link Uri} to get messages from. */ private static final Uri URI_SMS = Uri.parse("content://sms/"); /** {@link Uri} to get messages from. */ private static final Uri URI_MMS = Uri.parse("content://mms/"); /** Intent.action for receiving SMS. */ private static final String ACTION_SMS = // . "android.provider.Telephony.SMS_RECEIVED"; /** Intent.action for receiving MMS. */ private static final String ACTION_MMS = // . "android.provider.Telephony.WAP_PUSH_RECEIVED"; /** An unreadable MMS body. */ private static final String MMS_BODY = "<MMS>"; /** Index: thread id. */ private static final int ID_TID = 0; /** Index: count. */ private static final int ID_COUNT = 1; /** Sort the newest message first. */ private static final String SORT = Calls.DATE + " DESC"; /** Delay for spinlock, waiting for new messages. */ private static final long SLEEP = 500; /** Number of maximal spins. */ private static final int MAX_SPINS = 15; /** ID for new message notification. */ private static final int NOTIFICATION_ID_NEW = 1; /** Last unread message's date. */ private static long lastUnreadDate = 0L; /** Last unread message's body. */ private static String lastUnreadBody = null; /** * {@inheritDoc} */ @Override public final void onReceive(final Context context, final Intent intent) { final String action = intent.getAction(); Log.d(TAG, "got intent: " + action); String t = null; if (action.equals(ACTION_SMS)) { Bundle b = intent.getExtras(); Object[] messages = (Object[]) b.get("pdus"); SmsMessage[] smsMessage = new SmsMessage[messages.length]; int l = messages.length; for (int i = 0; i < l; i++) { smsMessage[i] = SmsMessage.createFromPdu((byte[]) messages[i]); } t = null; if (l > 0) { t = smsMessage[0].getDisplayMessageBody(); // ! Check in blacklist db - filter spam boolean q = false; final String s = smsMessage[0].getOriginatingAddress(); final SpamDB db = new SpamDB(context); db.open(); if (db.isInDB(smsMessage[0].getOriginatingAddress())) { Log.d(TAG, "Message from " + s + " filtered."); q = true; } else { Log.d(TAG, "Message from " + s + " NOT filtered."); } // db.getEntrieCount(); db.close(); if (q) { return; } } } else if (action.equals(ACTION_MMS)) { t = MMS_BODY; } Log.d(TAG, "t: " + t); int count = MAX_SPINS; do { Log.d(TAG, "spin: " + count); try { Thread.sleep(SLEEP); } catch (InterruptedException e) { Log.d(TAG, "interrupted in spinlock", e); e.printStackTrace(); } --count; } while (updateNewMessageNotification(context, t) <= 0 && count > 0); if (count == 0) { // use messages as they are available updateNewMessageNotification(context, null); } } /** * Get unread SMS. * * @param cr * {@link ContentResolver} to query * @param text * text of the last assumed unread message * @return [thread id (-1 if there are more), number of unread messages (-1 * if text does not match newest message)] */ private static int[] getUnreadSMS(final ContentResolver cr, final String text) { Log.d(TAG, "getUnreadSMS(cr, " + text + ")"); Cursor cursor = cr.query(URI_SMS, Message.PROJECTION, Message.SELECTION_UNREAD, null, SORT); if (cursor == null || cursor.getCount() == 0 || !cursor.moveToFirst()) { if (text != null) { // try again! if (cursor != null && !cursor.isClosed()) { cursor.close(); } return new int[] { -1, -1 }; } else { if (cursor != null && !cursor.isClosed()) { cursor.close(); } return new int[] { 0, 0 }; } } final String t = cursor.getString(Message.INDEX_BODY); if (text != null && (t == null || !t.startsWith(text))) { if (cursor != null && !cursor.isClosed()) { cursor.close(); } return new int[] { -1, -1 }; // try again! } final long d = cursor.getLong(Message.INDEX_DATE); if (d > lastUnreadDate) { lastUnreadBody = t; } int tid = cursor.getInt(Message.INDEX_THREADID); while (cursor.moveToNext() && tid > -1) { // check if following messages are from the same thread if (tid != cursor.getInt(Message.INDEX_THREADID)) { tid = -1; } } if (cursor != null && !cursor.isClosed()) { cursor.close(); } return new int[] { tid, cursor.getCount() }; } /** * Get unread MMS. * * @param cr * {@link ContentResolver} to query * @param text * text of the last assumed unread message * @return [thread id (-1 if there are more), number of unread messages] */ private static int[] getUnreadMMS(final ContentResolver cr, final String text) { Log.d(TAG, "getUnreadMMS(cr, " + text + ")"); Cursor cursor = cr.query(URI_MMS, Message.PROJECTION_READ, Message.SELECTION_UNREAD, null, null); if (cursor == null || cursor.getCount() == 0 || !cursor.moveToFirst()) { if (text == MMS_BODY) { if (cursor != null && !cursor.isClosed()) { cursor.close(); } return new int[] { -1, -1 }; // try again! } else { if (cursor != null && !cursor.isClosed()) { cursor.close(); } return new int[] { 0, 0 }; } } int tid = cursor.getInt(Message.INDEX_THREADID); long d = cursor.getLong(Message.INDEX_DATE); if (d < ConversationList.MIN_DATE) { d *= ConversationList.MILLIS; } if (d > lastUnreadDate) { lastUnreadBody = null; } while (cursor.moveToNext() && tid > -1) { // check if following messages are from the same thread if (tid != cursor.getInt(Message.INDEX_THREADID)) { tid = -1; } } if (cursor != null && !cursor.isClosed()) { cursor.close(); } return new int[] { tid, cursor.getCount() }; } /** * Get unread messages (MMS and SMS). * * @param cr * {@link ContentResolver} to query * @param text * text of the last assumed unread message * @return [thread id (-1 if there are more), number of unread messages (-1 * if text does not match newest message)] */ private static int[] getUnread(final ContentResolver cr, // . final String text) { Log.d(TAG, "getUnread(cr, " + text + ")"); lastUnreadBody = null; lastUnreadDate = 0L; String t = text; if (t == MMS_BODY) { t = null; } final int[] retSMS = getUnreadSMS(cr, t); if (retSMS[ID_COUNT] == -1) { // return to retry return new int[] { -1, -1 }; } final int[] retMMS = getUnreadMMS(cr, text); if (retMMS[ID_COUNT] == -1) { // return to retry return new int[] { -1, -1 }; } final int[] ret = new int[] { -1, retSMS[ID_COUNT] + retMMS[ID_COUNT] }; if (retMMS[ID_TID] <= 0 || retSMS[ID_TID] == retMMS[ID_TID]) { ret[ID_TID] = retSMS[ID_TID]; } else if (retSMS[ID_TID] <= 0) { ret[ID_TID] = retMMS[ID_TID]; } return ret; } /** * Update new message {@link Notification}. * * @param context * {@link Context} * @param text * text of the last assumed unread message * @return number of unread messages */ static final int updateNewMessageNotification(final Context context, final String text) { Log.d(TAG, "updNewMsgNoti(" + context + "," + text + ")"); final NotificationManager mNotificationMgr = // . (NotificationManager) context .getSystemService(Context.NOTIFICATION_SERVICE); final SharedPreferences prefs = PreferenceManager .getDefaultSharedPreferences(context); final boolean enableNotifications = prefs.getBoolean( Preferences.PREFS_NOTIFICATION_ENABLE, true); final boolean privateNotification = prefs.getBoolean( Preferences.PREFS_NOTIFICATION_PRIVACY, false); if (!enableNotifications) { mNotificationMgr.cancelAll(); Log.d(TAG, "no notification needed!"); } final int[] status = getUnread(context.getContentResolver(), text); final int l = status[ID_COUNT]; final int tid = status[ID_TID]; Log.d(TAG, "l: " + l); if (l < 0) { return l; } int ret = l; if (enableNotifications && (text != null || l == 0)) { mNotificationMgr.cancel(NOTIFICATION_ID_NEW); } Uri uri = null; PendingIntent pIntent; if (l == 0) { final Intent i = new Intent(context, ConversationList.class); // add pending intent - i.setFlags(i.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK); + i.setFlags(i.getFlags() | Intent.FLAG_ACTIVITY_CLEAR_TOP); pIntent = PendingIntent.getActivity(context, 0, i, PendingIntent.FLAG_CANCEL_CURRENT); } else { Notification n = null; Intent i; if (tid >= 0) { uri = Uri.parse(MessageList.URI + tid); i = new Intent(Intent.ACTION_VIEW, uri, context, MessageList.class); pIntent = PendingIntent.getActivity(context, 0, i, PendingIntent.FLAG_CANCEL_CURRENT); if (enableNotifications) { final Conversation conv = Conversation.getConversation( context, tid, true); if (conv != null) { String a; if (privateNotification) { if (l == 1) { a = context.getString(R.string.new_message_); } else { a = context.getString(R.string.new_messages_); } } else { a = conv.getDisplayName(); } n = new Notification(R.drawable.stat_notify_sms, a, System.currentTimeMillis()); if (l == 1) { String body; if (privateNotification) { body = context.getString(R.string.new_message); } else { body = lastUnreadBody; } if (body == null) { body = context .getString(R.string.mms_conversation); } n.setLatestEventInfo(context, a, body, pIntent); } else { n.setLatestEventInfo(context, a, String .format(context .getString(R.string.new_messages), l), pIntent); } } } } else { uri = Uri.parse(MessageList.URI); i = new Intent(Intent.ACTION_VIEW, uri, context, // . ConversationList.class); pIntent = PendingIntent.getActivity(context, 0, i, PendingIntent.FLAG_CANCEL_CURRENT); if (enableNotifications) { n = new Notification(R.drawable.stat_notify_sms, context .getString(R.string.new_messages_), System .currentTimeMillis()); n.setLatestEventInfo(context, context .getString(R.string.new_messages_), String.format( context.getString(R.string.new_messages), l), pIntent); n.number = l; } } // add pending intent i.setFlags(i.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK); if (enableNotifications && n != null) { n.flags |= Notification.FLAG_SHOW_LIGHTS; n.ledARGB = Preferences.getLEDcolor(context); int[] ledFlash = Preferences.getLEDflash(context); n.ledOnMS = ledFlash[0]; n.ledOffMS = ledFlash[1]; final SharedPreferences p = PreferenceManager .getDefaultSharedPreferences(context); if (text != null) { final boolean vibrate = p.getBoolean( Preferences.PREFS_VIBRATE, false); final String s = p.getString(Preferences.PREFS_SOUND, null); Uri sound; if (s == null || s.length() <= 0) { sound = null; } else { sound = Uri.parse(s); } if (vibrate) { final long[] pattern = Preferences .getVibratorPattern(context); if (pattern.length == 1 && pattern[0] == 0) { n.defaults |= Notification.DEFAULT_VIBRATE; } else { n.vibrate = pattern; } } n.sound = sound; } } Log.d(TAG, "uri: " + uri); mNotificationMgr.cancel(NOTIFICATION_ID_NEW); if (enableNotifications && n != null) { mNotificationMgr.notify(NOTIFICATION_ID_NEW, n); } } Log.d(TAG, "return " + ret + " (2)"); AppWidgetManager.getInstance(context).updateAppWidget( new ComponentName(context, WidgetProvider.class), WidgetProvider.getRemoteViews(context, l, pIntent)); return ret; } }
true
true
static final int updateNewMessageNotification(final Context context, final String text) { Log.d(TAG, "updNewMsgNoti(" + context + "," + text + ")"); final NotificationManager mNotificationMgr = // . (NotificationManager) context .getSystemService(Context.NOTIFICATION_SERVICE); final SharedPreferences prefs = PreferenceManager .getDefaultSharedPreferences(context); final boolean enableNotifications = prefs.getBoolean( Preferences.PREFS_NOTIFICATION_ENABLE, true); final boolean privateNotification = prefs.getBoolean( Preferences.PREFS_NOTIFICATION_PRIVACY, false); if (!enableNotifications) { mNotificationMgr.cancelAll(); Log.d(TAG, "no notification needed!"); } final int[] status = getUnread(context.getContentResolver(), text); final int l = status[ID_COUNT]; final int tid = status[ID_TID]; Log.d(TAG, "l: " + l); if (l < 0) { return l; } int ret = l; if (enableNotifications && (text != null || l == 0)) { mNotificationMgr.cancel(NOTIFICATION_ID_NEW); } Uri uri = null; PendingIntent pIntent; if (l == 0) { final Intent i = new Intent(context, ConversationList.class); // add pending intent i.setFlags(i.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK); pIntent = PendingIntent.getActivity(context, 0, i, PendingIntent.FLAG_CANCEL_CURRENT); } else { Notification n = null; Intent i; if (tid >= 0) { uri = Uri.parse(MessageList.URI + tid); i = new Intent(Intent.ACTION_VIEW, uri, context, MessageList.class); pIntent = PendingIntent.getActivity(context, 0, i, PendingIntent.FLAG_CANCEL_CURRENT); if (enableNotifications) { final Conversation conv = Conversation.getConversation( context, tid, true); if (conv != null) { String a; if (privateNotification) { if (l == 1) { a = context.getString(R.string.new_message_); } else { a = context.getString(R.string.new_messages_); } } else { a = conv.getDisplayName(); } n = new Notification(R.drawable.stat_notify_sms, a, System.currentTimeMillis()); if (l == 1) { String body; if (privateNotification) { body = context.getString(R.string.new_message); } else { body = lastUnreadBody; } if (body == null) { body = context .getString(R.string.mms_conversation); } n.setLatestEventInfo(context, a, body, pIntent); } else { n.setLatestEventInfo(context, a, String .format(context .getString(R.string.new_messages), l), pIntent); } } } } else { uri = Uri.parse(MessageList.URI); i = new Intent(Intent.ACTION_VIEW, uri, context, // . ConversationList.class); pIntent = PendingIntent.getActivity(context, 0, i, PendingIntent.FLAG_CANCEL_CURRENT); if (enableNotifications) { n = new Notification(R.drawable.stat_notify_sms, context .getString(R.string.new_messages_), System .currentTimeMillis()); n.setLatestEventInfo(context, context .getString(R.string.new_messages_), String.format( context.getString(R.string.new_messages), l), pIntent); n.number = l; } } // add pending intent i.setFlags(i.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK); if (enableNotifications && n != null) { n.flags |= Notification.FLAG_SHOW_LIGHTS; n.ledARGB = Preferences.getLEDcolor(context); int[] ledFlash = Preferences.getLEDflash(context); n.ledOnMS = ledFlash[0]; n.ledOffMS = ledFlash[1]; final SharedPreferences p = PreferenceManager .getDefaultSharedPreferences(context); if (text != null) { final boolean vibrate = p.getBoolean( Preferences.PREFS_VIBRATE, false); final String s = p.getString(Preferences.PREFS_SOUND, null); Uri sound; if (s == null || s.length() <= 0) { sound = null; } else { sound = Uri.parse(s); } if (vibrate) { final long[] pattern = Preferences .getVibratorPattern(context); if (pattern.length == 1 && pattern[0] == 0) { n.defaults |= Notification.DEFAULT_VIBRATE; } else { n.vibrate = pattern; } } n.sound = sound; } } Log.d(TAG, "uri: " + uri); mNotificationMgr.cancel(NOTIFICATION_ID_NEW); if (enableNotifications && n != null) { mNotificationMgr.notify(NOTIFICATION_ID_NEW, n); } } Log.d(TAG, "return " + ret + " (2)"); AppWidgetManager.getInstance(context).updateAppWidget( new ComponentName(context, WidgetProvider.class), WidgetProvider.getRemoteViews(context, l, pIntent)); return ret; }
static final int updateNewMessageNotification(final Context context, final String text) { Log.d(TAG, "updNewMsgNoti(" + context + "," + text + ")"); final NotificationManager mNotificationMgr = // . (NotificationManager) context .getSystemService(Context.NOTIFICATION_SERVICE); final SharedPreferences prefs = PreferenceManager .getDefaultSharedPreferences(context); final boolean enableNotifications = prefs.getBoolean( Preferences.PREFS_NOTIFICATION_ENABLE, true); final boolean privateNotification = prefs.getBoolean( Preferences.PREFS_NOTIFICATION_PRIVACY, false); if (!enableNotifications) { mNotificationMgr.cancelAll(); Log.d(TAG, "no notification needed!"); } final int[] status = getUnread(context.getContentResolver(), text); final int l = status[ID_COUNT]; final int tid = status[ID_TID]; Log.d(TAG, "l: " + l); if (l < 0) { return l; } int ret = l; if (enableNotifications && (text != null || l == 0)) { mNotificationMgr.cancel(NOTIFICATION_ID_NEW); } Uri uri = null; PendingIntent pIntent; if (l == 0) { final Intent i = new Intent(context, ConversationList.class); // add pending intent i.setFlags(i.getFlags() | Intent.FLAG_ACTIVITY_CLEAR_TOP); pIntent = PendingIntent.getActivity(context, 0, i, PendingIntent.FLAG_CANCEL_CURRENT); } else { Notification n = null; Intent i; if (tid >= 0) { uri = Uri.parse(MessageList.URI + tid); i = new Intent(Intent.ACTION_VIEW, uri, context, MessageList.class); pIntent = PendingIntent.getActivity(context, 0, i, PendingIntent.FLAG_CANCEL_CURRENT); if (enableNotifications) { final Conversation conv = Conversation.getConversation( context, tid, true); if (conv != null) { String a; if (privateNotification) { if (l == 1) { a = context.getString(R.string.new_message_); } else { a = context.getString(R.string.new_messages_); } } else { a = conv.getDisplayName(); } n = new Notification(R.drawable.stat_notify_sms, a, System.currentTimeMillis()); if (l == 1) { String body; if (privateNotification) { body = context.getString(R.string.new_message); } else { body = lastUnreadBody; } if (body == null) { body = context .getString(R.string.mms_conversation); } n.setLatestEventInfo(context, a, body, pIntent); } else { n.setLatestEventInfo(context, a, String .format(context .getString(R.string.new_messages), l), pIntent); } } } } else { uri = Uri.parse(MessageList.URI); i = new Intent(Intent.ACTION_VIEW, uri, context, // . ConversationList.class); pIntent = PendingIntent.getActivity(context, 0, i, PendingIntent.FLAG_CANCEL_CURRENT); if (enableNotifications) { n = new Notification(R.drawable.stat_notify_sms, context .getString(R.string.new_messages_), System .currentTimeMillis()); n.setLatestEventInfo(context, context .getString(R.string.new_messages_), String.format( context.getString(R.string.new_messages), l), pIntent); n.number = l; } } // add pending intent i.setFlags(i.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK); if (enableNotifications && n != null) { n.flags |= Notification.FLAG_SHOW_LIGHTS; n.ledARGB = Preferences.getLEDcolor(context); int[] ledFlash = Preferences.getLEDflash(context); n.ledOnMS = ledFlash[0]; n.ledOffMS = ledFlash[1]; final SharedPreferences p = PreferenceManager .getDefaultSharedPreferences(context); if (text != null) { final boolean vibrate = p.getBoolean( Preferences.PREFS_VIBRATE, false); final String s = p.getString(Preferences.PREFS_SOUND, null); Uri sound; if (s == null || s.length() <= 0) { sound = null; } else { sound = Uri.parse(s); } if (vibrate) { final long[] pattern = Preferences .getVibratorPattern(context); if (pattern.length == 1 && pattern[0] == 0) { n.defaults |= Notification.DEFAULT_VIBRATE; } else { n.vibrate = pattern; } } n.sound = sound; } } Log.d(TAG, "uri: " + uri); mNotificationMgr.cancel(NOTIFICATION_ID_NEW); if (enableNotifications && n != null) { mNotificationMgr.notify(NOTIFICATION_ID_NEW, n); } } Log.d(TAG, "return " + ret + " (2)"); AppWidgetManager.getInstance(context).updateAppWidget( new ComponentName(context, WidgetProvider.class), WidgetProvider.getRemoteViews(context, l, pIntent)); return ret; }
diff --git a/src/org/jruby/RubyGlobal.java b/src/org/jruby/RubyGlobal.java index 3723be941..dab92ccfc 100644 --- a/src/org/jruby/RubyGlobal.java +++ b/src/org/jruby/RubyGlobal.java @@ -1,624 +1,624 @@ /***** 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) 2002 Benoit Cerrina <[email protected]> * Copyright (C) 2002-2004 Anders Bengtsson <[email protected]> * Copyright (C) 2002-2004 Jan Arne Petersen <[email protected]> * Copyright (C) 2004 Charles O Nutter <[email protected]> * Copyright (C) 2004 Thomas E Enebo <[email protected]> * Copyright (C) 2004 Stefan Matthias Aust <[email protected]> * Copyright (C) 2006 Tim Azzopardi <[email protected]> * Copyright (C) 2006 Miguel Covarrubias <[email protected]> * Copyright (C) 2006 Michael Studman <[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 org.jruby.util.io.STDIO; import java.util.HashMap; import java.util.Map; import org.jruby.anno.JRubyMethod; import org.jruby.common.IRubyWarnings.ID; import org.jruby.environment.OSEnvironmentReaderExcepton; import org.jruby.environment.OSEnvironment; import org.jruby.internal.runtime.ValueAccessor; import org.jruby.javasupport.util.RuntimeHelpers; import org.jruby.runtime.Constants; import org.jruby.runtime.GlobalVariable; import org.jruby.runtime.IAccessor; import org.jruby.runtime.MethodIndex; import org.jruby.runtime.ReadonlyGlobalVariable; import org.jruby.runtime.ThreadContext; import org.jruby.runtime.builtin.IRubyObject; import org.jruby.util.KCode; /** This class initializes global variables and constants. * * @author jpetersen */ public class RubyGlobal { /** * Obligate string-keyed and string-valued hash, used for ENV and ENV_JAVA * */ public static class StringOnlyRubyHash extends RubyHash { public StringOnlyRubyHash(Ruby runtime, Map valueMap, IRubyObject defaultValue) { super(runtime, valueMap, defaultValue); } @Override public RubyHash to_hash() { Ruby runtime = getRuntime(); RubyHash hash = RubyHash.newHash(runtime); hash.replace(runtime.getCurrentContext(), this); return hash; } @Override public IRubyObject op_aref(ThreadContext context, IRubyObject key) { return super.op_aref(context, key.convertToString()); } @Override public IRubyObject op_aset(ThreadContext context, IRubyObject key, IRubyObject value) { if (!key.respondsTo("to_str")) { throw getRuntime().newTypeError("can't convert " + key.getMetaClass() + " into String"); } if (!value.respondsTo("to_str") && !value.isNil()) { throw getRuntime().newTypeError("can't convert " + value.getMetaClass() + " into String"); } if (value.isNil()) { return super.delete(context, key, org.jruby.runtime.Block.NULL_BLOCK); } //return super.aset(getRuntime().newString("sadfasdF"), getRuntime().newString("sadfasdF")); return super.op_aset(context, RuntimeHelpers.invoke(context, key, MethodIndex.TO_STR, "to_str", IRubyObject.NULL_ARRAY), value.isNil() ? getRuntime().getNil() : RuntimeHelpers.invoke(context, value, MethodIndex.TO_STR, "to_str", IRubyObject.NULL_ARRAY)); } @JRubyMethod @Override public IRubyObject to_s(){ return getRuntime().newString("ENV"); } } public static void createGlobals(ThreadContext context, Ruby runtime) { runtime.defineGlobalConstant("TOPLEVEL_BINDING", runtime.newBinding()); runtime.defineGlobalConstant("TRUE", runtime.getTrue()); runtime.defineGlobalConstant("FALSE", runtime.getFalse()); runtime.defineGlobalConstant("NIL", runtime.getNil()); // define ARGV and $* for this runtime RubyArray argvArray = runtime.newArray(); String[] argv = runtime.getInstanceConfig().getArgv(); for (int i = 0; i < argv.length; i++) { - argvArray.append(RubyString.newUnicodeString(runtime, argv[i])); + argvArray.append(RubyString.newString(runtime, argv[i].getBytes())); } runtime.defineGlobalConstant("ARGV", argvArray); runtime.getGlobalVariables().defineReadonly("$*", new ValueAccessor(argvArray)); IAccessor d = new ValueAccessor(runtime.newString( runtime.getInstanceConfig().displayedFileName())); runtime.getGlobalVariables().define("$PROGRAM_NAME", d); runtime.getGlobalVariables().define("$0", d); // Version information: IRubyObject version = runtime.newString(Constants.RUBY_VERSION).freeze(context); IRubyObject release = runtime.newString(Constants.COMPILE_DATE).freeze(context); IRubyObject platform = runtime.newString(Constants.PLATFORM).freeze(context); IRubyObject engine = runtime.newString(Constants.ENGINE).freeze(context); runtime.defineGlobalConstant("RUBY_VERSION", version); runtime.defineGlobalConstant("RUBY_PATCHLEVEL", runtime.newString(Constants.RUBY_PATCHLEVEL).freeze(context)); runtime.defineGlobalConstant("RUBY_RELEASE_DATE", release); runtime.defineGlobalConstant("RUBY_PLATFORM", platform); runtime.defineGlobalConstant("RUBY_ENGINE", engine); runtime.defineGlobalConstant("VERSION", version); runtime.defineGlobalConstant("RELEASE_DATE", release); runtime.defineGlobalConstant("PLATFORM", platform); IRubyObject jrubyVersion = runtime.newString(Constants.VERSION).freeze(context); runtime.defineGlobalConstant("JRUBY_VERSION", jrubyVersion); GlobalVariable kcodeGV = new KCodeGlobalVariable(runtime, "$KCODE", runtime.newString("NONE")); runtime.defineVariable(kcodeGV); runtime.defineVariable(new GlobalVariable.Copy(runtime, "$-K", kcodeGV)); IRubyObject defaultRS = runtime.newString(runtime.getInstanceConfig().getRecordSeparator()).freeze(context); GlobalVariable rs = new StringGlobalVariable(runtime, "$/", defaultRS); runtime.defineVariable(rs); runtime.setRecordSeparatorVar(rs); runtime.getGlobalVariables().setDefaultSeparator(defaultRS); runtime.defineVariable(new StringGlobalVariable(runtime, "$\\", runtime.getNil())); runtime.defineVariable(new StringGlobalVariable(runtime, "$,", runtime.getNil())); runtime.defineVariable(new LineNumberGlobalVariable(runtime, "$.", RubyFixnum.one(runtime))); runtime.defineVariable(new LastlineGlobalVariable(runtime, "$_")); runtime.defineVariable(new LastExitStatusVariable(runtime, "$?")); runtime.defineVariable(new ErrorInfoGlobalVariable(runtime, "$!", runtime.getNil())); runtime.defineVariable(new NonEffectiveGlobalVariable(runtime, "$=", runtime.getFalse())); if(runtime.getInstanceConfig().getInputFieldSeparator() == null) { runtime.defineVariable(new GlobalVariable(runtime, "$;", runtime.getNil())); } else { runtime.defineVariable(new GlobalVariable(runtime, "$;", RubyRegexp.newRegexp(runtime, runtime.getInstanceConfig().getInputFieldSeparator(), 0))); } Boolean verbose = runtime.getInstanceConfig().getVerbose(); IRubyObject verboseValue = null; if (verbose == null) { verboseValue = runtime.getNil(); } else if(verbose == Boolean.TRUE) { verboseValue = runtime.getTrue(); } else { verboseValue = runtime.getFalse(); } runtime.defineVariable(new VerboseGlobalVariable(runtime, "$VERBOSE", verboseValue)); IRubyObject debug = runtime.newBoolean(runtime.getInstanceConfig().isDebug()); runtime.defineVariable(new DebugGlobalVariable(runtime, "$DEBUG", debug)); runtime.defineVariable(new DebugGlobalVariable(runtime, "$-d", debug)); runtime.defineVariable(new SafeGlobalVariable(runtime, "$SAFE")); runtime.defineVariable(new BacktraceGlobalVariable(runtime, "$@")); IRubyObject stdin = new RubyIO(runtime, STDIO.IN); IRubyObject stdout = new RubyIO(runtime, STDIO.OUT); IRubyObject stderr = new RubyIO(runtime, STDIO.ERR); runtime.defineVariable(new InputGlobalVariable(runtime, "$stdin", stdin)); runtime.defineVariable(new OutputGlobalVariable(runtime, "$stdout", stdout)); runtime.getGlobalVariables().alias("$>", "$stdout"); runtime.getGlobalVariables().alias("$defout", "$stdout"); runtime.defineVariable(new OutputGlobalVariable(runtime, "$stderr", stderr)); runtime.getGlobalVariables().alias("$deferr", "$stderr"); runtime.defineGlobalConstant("STDIN", stdin); runtime.defineGlobalConstant("STDOUT", stdout); runtime.defineGlobalConstant("STDERR", stderr); runtime.defineVariable(new LoadedFeatures(runtime, "$\"")); runtime.defineVariable(new LoadedFeatures(runtime, "$LOADED_FEATURES")); runtime.defineVariable(new LoadPath(runtime, "$:")); runtime.defineVariable(new LoadPath(runtime, "$-I")); runtime.defineVariable(new LoadPath(runtime, "$LOAD_PATH")); runtime.defineVariable(new MatchMatchGlobalVariable(runtime, "$&")); runtime.defineVariable(new PreMatchGlobalVariable(runtime, "$`")); runtime.defineVariable(new PostMatchGlobalVariable(runtime, "$'")); runtime.defineVariable(new LastMatchGlobalVariable(runtime, "$+")); runtime.defineVariable(new BackRefGlobalVariable(runtime, "$~")); // On platforms without a c-library accessable through JNA, getpid will return hashCode // as $$ used to. Using $$ to kill processes could take down many runtimes, but by basing // $$ on getpid() where available, we have the same semantics as MRI. runtime.getGlobalVariables().defineReadonly("$$", new ValueAccessor(runtime.newFixnum(runtime.getPosix().getpid()))); // after defn of $stderr as the call may produce warnings defineGlobalEnvConstants(runtime); // Fixme: Do we need the check or does Main.java not call this...they should consolidate if (runtime.getGlobalVariables().get("$*").isNil()) { runtime.getGlobalVariables().defineReadonly("$*", new ValueAccessor(runtime.newArray())); } runtime.getGlobalVariables().defineReadonly("$-p", new ValueAccessor(runtime.getInstanceConfig().isAssumePrinting() ? runtime.getTrue() : runtime.getNil())); runtime.getGlobalVariables().defineReadonly("$-n", new ValueAccessor(runtime.getInstanceConfig().isAssumeLoop() ? runtime.getTrue() : runtime.getNil())); runtime.getGlobalVariables().defineReadonly("$-a", new ValueAccessor(runtime.getInstanceConfig().isSplit() ? runtime.getTrue() : runtime.getNil())); runtime.getGlobalVariables().defineReadonly("$-l", new ValueAccessor(runtime.getInstanceConfig().isProcessLineEnds() ? runtime.getTrue() : runtime.getNil())); // ARGF, $< object RubyArgsFile.initArgsFile(runtime); } private static void defineGlobalEnvConstants(Ruby runtime) { Map environmentVariableMap = null; OSEnvironment environment = new OSEnvironment(); try { environmentVariableMap = environment.getEnvironmentVariableMap(runtime); } catch (OSEnvironmentReaderExcepton e) { // If the environment variables are not accessible shouldn't terminate runtime.getWarnings().warn(ID.MISCELLANEOUS, e.getMessage()); } if (environmentVariableMap == null) { // if the environment variables can't be obtained, define an empty ENV environmentVariableMap = new HashMap(); } StringOnlyRubyHash h1 = new StringOnlyRubyHash(runtime, environmentVariableMap, runtime.getNil()); h1.getSingletonClass().defineAnnotatedMethods(StringOnlyRubyHash.class); runtime.defineGlobalConstant("ENV", h1); // Define System.getProperties() in ENV_JAVA Map systemProps = environment.getSystemPropertiesMap(runtime); runtime.defineGlobalConstant("ENV_JAVA", new StringOnlyRubyHash( runtime, systemProps, runtime.getNil())); } private static class NonEffectiveGlobalVariable extends GlobalVariable { public NonEffectiveGlobalVariable(Ruby runtime, String name, IRubyObject value) { super(runtime, name, value); } @Override public IRubyObject set(IRubyObject value) { runtime.getWarnings().warn(ID.INEFFECTIVE_GLOBAL, "warning: variable " + name + " is no longer effective; ignored", name); return value; } @Override public IRubyObject get() { runtime.getWarnings().warn(ID.INEFFECTIVE_GLOBAL, "warning: variable " + name + " is no longer effective", name); return runtime.getFalse(); } } private static class LastExitStatusVariable extends GlobalVariable { public LastExitStatusVariable(Ruby runtime, String name) { super(runtime, name, runtime.getNil()); } @Override public IRubyObject get() { IRubyObject lastExitStatus = runtime.getCurrentContext().getLastExitStatus(); return lastExitStatus == null ? runtime.getNil() : lastExitStatus; } @Override public IRubyObject set(IRubyObject lastExitStatus) { runtime.getCurrentContext().setLastExitStatus(lastExitStatus); return lastExitStatus; } } private static class MatchMatchGlobalVariable extends GlobalVariable { public MatchMatchGlobalVariable(Ruby runtime, String name) { super(runtime, name, runtime.getNil()); } @Override public IRubyObject get() { return RubyRegexp.last_match(runtime.getCurrentContext().getCurrentFrame().getBackRef()); } } private static class PreMatchGlobalVariable extends GlobalVariable { public PreMatchGlobalVariable(Ruby runtime, String name) { super(runtime, name, runtime.getNil()); } @Override public IRubyObject get() { return RubyRegexp.match_pre(runtime.getCurrentContext().getCurrentFrame().getBackRef()); } } private static class PostMatchGlobalVariable extends GlobalVariable { public PostMatchGlobalVariable(Ruby runtime, String name) { super(runtime, name, runtime.getNil()); } @Override public IRubyObject get() { return RubyRegexp.match_post(runtime.getCurrentContext().getCurrentFrame().getBackRef()); } } private static class LastMatchGlobalVariable extends GlobalVariable { public LastMatchGlobalVariable(Ruby runtime, String name) { super(runtime, name, runtime.getNil()); } @Override public IRubyObject get() { return RubyRegexp.match_last(runtime.getCurrentContext().getCurrentFrame().getBackRef()); } } private static class BackRefGlobalVariable extends GlobalVariable { public BackRefGlobalVariable(Ruby runtime, String name) { super(runtime, name, runtime.getNil()); } @Override public IRubyObject get() { return RuntimeHelpers.getBackref(runtime, runtime.getCurrentContext()); } @Override public IRubyObject set(IRubyObject value) { RuntimeHelpers.setBackref(runtime, runtime.getCurrentContext(), value); return value; } } // Accessor methods. private static class LineNumberGlobalVariable extends GlobalVariable { public LineNumberGlobalVariable(Ruby runtime, String name, RubyFixnum value) { super(runtime, name, value); } @Override public IRubyObject set(IRubyObject value) { RubyArgsFile.setCurrentLineNumber(runtime.getGlobalVariables().get("$<"),RubyNumeric.fix2int(value)); return super.set(value); } } private static class ErrorInfoGlobalVariable extends GlobalVariable { public ErrorInfoGlobalVariable(Ruby runtime, String name, IRubyObject value) { super(runtime, name, null); set(value); } @Override public IRubyObject set(IRubyObject value) { if (!value.isNil() && ! runtime.getException().isInstance(value)) { throw runtime.newTypeError("assigning non-exception to $!"); } return runtime.getCurrentContext().setErrorInfo(value); } @Override public IRubyObject get() { return runtime.getCurrentContext().getErrorInfo(); } } // FIXME: move out of this class! public static class StringGlobalVariable extends GlobalVariable { public StringGlobalVariable(Ruby runtime, String name, IRubyObject value) { super(runtime, name, value); } @Override public IRubyObject set(IRubyObject value) { if (!value.isNil() && ! (value instanceof RubyString)) { throw runtime.newTypeError("value of " + name() + " must be a String"); } return super.set(value); } } public static class KCodeGlobalVariable extends GlobalVariable { public KCodeGlobalVariable(Ruby runtime, String name, IRubyObject value) { super(runtime, name, value); } @Override public IRubyObject get() { return runtime.getKCode().kcode(runtime); } @Override public IRubyObject set(IRubyObject value) { runtime.setKCode(KCode.create(runtime, value.convertToString().toString())); return value; } } private static class SafeGlobalVariable extends GlobalVariable { public SafeGlobalVariable(Ruby runtime, String name) { super(runtime, name, null); } @Override public IRubyObject get() { return runtime.newFixnum(runtime.getSafeLevel()); } @Override public IRubyObject set(IRubyObject value) { // int level = RubyNumeric.fix2int(value); // if (level < runtime.getSafeLevel()) { // throw runtime.newSecurityError("tried to downgrade safe level from " + // runtime.getSafeLevel() + " to " + level); // } // runtime.setSafeLevel(level); // thread.setSafeLevel(level); runtime.getWarnings().warn(ID.SAFE_NOT_SUPPORTED, "SAFE levels are not supported in JRuby"); return RubyFixnum.newFixnum(runtime, runtime.getSafeLevel()); } } private static class VerboseGlobalVariable extends GlobalVariable { public VerboseGlobalVariable(Ruby runtime, String name, IRubyObject initialValue) { super(runtime, name, initialValue); set(initialValue); } @Override public IRubyObject get() { return runtime.getVerbose(); } @Override public IRubyObject set(IRubyObject newValue) { if (newValue.isNil()) { runtime.setVerbose(newValue); } else { runtime.setVerbose(runtime.newBoolean(newValue.isTrue())); } return newValue; } } private static class DebugGlobalVariable extends GlobalVariable { public DebugGlobalVariable(Ruby runtime, String name, IRubyObject initialValue) { super(runtime, name, initialValue); set(initialValue); } @Override public IRubyObject get() { return runtime.getDebug(); } @Override public IRubyObject set(IRubyObject newValue) { if (newValue.isNil()) { runtime.setDebug(newValue); } else { runtime.setDebug(runtime.newBoolean(newValue.isTrue())); } return newValue; } } private static class BacktraceGlobalVariable extends GlobalVariable { public BacktraceGlobalVariable(Ruby runtime, String name) { super(runtime, name, null); } @Override public IRubyObject get() { IRubyObject errorInfo = runtime.getGlobalVariables().get("$!"); IRubyObject backtrace = errorInfo.isNil() ? runtime.getNil() : errorInfo.callMethod(errorInfo.getRuntime().getCurrentContext(), "backtrace"); //$@ returns nil if $!.backtrace is not an array if (!(backtrace instanceof RubyArray)) { backtrace = runtime.getNil(); } return backtrace; } @Override public IRubyObject set(IRubyObject value) { if (runtime.getGlobalVariables().get("$!").isNil()) { throw runtime.newArgumentError("$! not set."); } runtime.getGlobalVariables().get("$!").callMethod(value.getRuntime().getCurrentContext(), "set_backtrace", value); return value; } } private static class LastlineGlobalVariable extends GlobalVariable { public LastlineGlobalVariable(Ruby runtime, String name) { super(runtime, name, null); } @Override public IRubyObject get() { return RuntimeHelpers.getLastLine(runtime, runtime.getCurrentContext()); } @Override public IRubyObject set(IRubyObject value) { RuntimeHelpers.setLastLine(runtime, runtime.getCurrentContext(), value); return value; } } private static class InputGlobalVariable extends GlobalVariable { public InputGlobalVariable(Ruby runtime, String name, IRubyObject value) { super(runtime, name, value); } @Override public IRubyObject set(IRubyObject value) { if (value == get()) { return value; } return super.set(value); } } private static class OutputGlobalVariable extends GlobalVariable { public OutputGlobalVariable(Ruby runtime, String name, IRubyObject value) { super(runtime, name, value); } @Override public IRubyObject set(IRubyObject value) { if (value == get()) { return value; } if (value instanceof RubyIO) { RubyIO io = (RubyIO)value; // HACK: in order to have stdout/err act like ttys and flush always, // we set anything assigned to stdout/stderr to sync io.getHandler().setSync(true); } if (!value.respondsTo("write")) { throw runtime.newTypeError(name() + " must have write method, " + value.getType().getName() + " given"); } return super.set(value); } } private static class LoadPath extends ReadonlyGlobalVariable { public LoadPath(Ruby runtime, String name) { super(runtime, name, null); } /** * @see org.jruby.runtime.GlobalVariable#get() */ @Override public IRubyObject get() { return runtime.getLoadService().getLoadPath(); } } private static class LoadedFeatures extends ReadonlyGlobalVariable { public LoadedFeatures(Ruby runtime, String name) { super(runtime, name, null); } /** * @see org.jruby.runtime.GlobalVariable#get() */ public IRubyObject get() { return runtime.getLoadService().getLoadedFeatures(); } } }
true
true
public static void createGlobals(ThreadContext context, Ruby runtime) { runtime.defineGlobalConstant("TOPLEVEL_BINDING", runtime.newBinding()); runtime.defineGlobalConstant("TRUE", runtime.getTrue()); runtime.defineGlobalConstant("FALSE", runtime.getFalse()); runtime.defineGlobalConstant("NIL", runtime.getNil()); // define ARGV and $* for this runtime RubyArray argvArray = runtime.newArray(); String[] argv = runtime.getInstanceConfig().getArgv(); for (int i = 0; i < argv.length; i++) { argvArray.append(RubyString.newUnicodeString(runtime, argv[i])); } runtime.defineGlobalConstant("ARGV", argvArray); runtime.getGlobalVariables().defineReadonly("$*", new ValueAccessor(argvArray)); IAccessor d = new ValueAccessor(runtime.newString( runtime.getInstanceConfig().displayedFileName())); runtime.getGlobalVariables().define("$PROGRAM_NAME", d); runtime.getGlobalVariables().define("$0", d); // Version information: IRubyObject version = runtime.newString(Constants.RUBY_VERSION).freeze(context); IRubyObject release = runtime.newString(Constants.COMPILE_DATE).freeze(context); IRubyObject platform = runtime.newString(Constants.PLATFORM).freeze(context); IRubyObject engine = runtime.newString(Constants.ENGINE).freeze(context); runtime.defineGlobalConstant("RUBY_VERSION", version); runtime.defineGlobalConstant("RUBY_PATCHLEVEL", runtime.newString(Constants.RUBY_PATCHLEVEL).freeze(context)); runtime.defineGlobalConstant("RUBY_RELEASE_DATE", release); runtime.defineGlobalConstant("RUBY_PLATFORM", platform); runtime.defineGlobalConstant("RUBY_ENGINE", engine); runtime.defineGlobalConstant("VERSION", version); runtime.defineGlobalConstant("RELEASE_DATE", release); runtime.defineGlobalConstant("PLATFORM", platform); IRubyObject jrubyVersion = runtime.newString(Constants.VERSION).freeze(context); runtime.defineGlobalConstant("JRUBY_VERSION", jrubyVersion); GlobalVariable kcodeGV = new KCodeGlobalVariable(runtime, "$KCODE", runtime.newString("NONE")); runtime.defineVariable(kcodeGV); runtime.defineVariable(new GlobalVariable.Copy(runtime, "$-K", kcodeGV)); IRubyObject defaultRS = runtime.newString(runtime.getInstanceConfig().getRecordSeparator()).freeze(context); GlobalVariable rs = new StringGlobalVariable(runtime, "$/", defaultRS); runtime.defineVariable(rs); runtime.setRecordSeparatorVar(rs); runtime.getGlobalVariables().setDefaultSeparator(defaultRS); runtime.defineVariable(new StringGlobalVariable(runtime, "$\\", runtime.getNil())); runtime.defineVariable(new StringGlobalVariable(runtime, "$,", runtime.getNil())); runtime.defineVariable(new LineNumberGlobalVariable(runtime, "$.", RubyFixnum.one(runtime))); runtime.defineVariable(new LastlineGlobalVariable(runtime, "$_")); runtime.defineVariable(new LastExitStatusVariable(runtime, "$?")); runtime.defineVariable(new ErrorInfoGlobalVariable(runtime, "$!", runtime.getNil())); runtime.defineVariable(new NonEffectiveGlobalVariable(runtime, "$=", runtime.getFalse())); if(runtime.getInstanceConfig().getInputFieldSeparator() == null) { runtime.defineVariable(new GlobalVariable(runtime, "$;", runtime.getNil())); } else { runtime.defineVariable(new GlobalVariable(runtime, "$;", RubyRegexp.newRegexp(runtime, runtime.getInstanceConfig().getInputFieldSeparator(), 0))); } Boolean verbose = runtime.getInstanceConfig().getVerbose(); IRubyObject verboseValue = null; if (verbose == null) { verboseValue = runtime.getNil(); } else if(verbose == Boolean.TRUE) { verboseValue = runtime.getTrue(); } else { verboseValue = runtime.getFalse(); } runtime.defineVariable(new VerboseGlobalVariable(runtime, "$VERBOSE", verboseValue)); IRubyObject debug = runtime.newBoolean(runtime.getInstanceConfig().isDebug()); runtime.defineVariable(new DebugGlobalVariable(runtime, "$DEBUG", debug)); runtime.defineVariable(new DebugGlobalVariable(runtime, "$-d", debug)); runtime.defineVariable(new SafeGlobalVariable(runtime, "$SAFE")); runtime.defineVariable(new BacktraceGlobalVariable(runtime, "$@")); IRubyObject stdin = new RubyIO(runtime, STDIO.IN); IRubyObject stdout = new RubyIO(runtime, STDIO.OUT); IRubyObject stderr = new RubyIO(runtime, STDIO.ERR); runtime.defineVariable(new InputGlobalVariable(runtime, "$stdin", stdin)); runtime.defineVariable(new OutputGlobalVariable(runtime, "$stdout", stdout)); runtime.getGlobalVariables().alias("$>", "$stdout"); runtime.getGlobalVariables().alias("$defout", "$stdout"); runtime.defineVariable(new OutputGlobalVariable(runtime, "$stderr", stderr)); runtime.getGlobalVariables().alias("$deferr", "$stderr"); runtime.defineGlobalConstant("STDIN", stdin); runtime.defineGlobalConstant("STDOUT", stdout); runtime.defineGlobalConstant("STDERR", stderr); runtime.defineVariable(new LoadedFeatures(runtime, "$\"")); runtime.defineVariable(new LoadedFeatures(runtime, "$LOADED_FEATURES")); runtime.defineVariable(new LoadPath(runtime, "$:")); runtime.defineVariable(new LoadPath(runtime, "$-I")); runtime.defineVariable(new LoadPath(runtime, "$LOAD_PATH")); runtime.defineVariable(new MatchMatchGlobalVariable(runtime, "$&")); runtime.defineVariable(new PreMatchGlobalVariable(runtime, "$`")); runtime.defineVariable(new PostMatchGlobalVariable(runtime, "$'")); runtime.defineVariable(new LastMatchGlobalVariable(runtime, "$+")); runtime.defineVariable(new BackRefGlobalVariable(runtime, "$~")); // On platforms without a c-library accessable through JNA, getpid will return hashCode // as $$ used to. Using $$ to kill processes could take down many runtimes, but by basing // $$ on getpid() where available, we have the same semantics as MRI. runtime.getGlobalVariables().defineReadonly("$$", new ValueAccessor(runtime.newFixnum(runtime.getPosix().getpid()))); // after defn of $stderr as the call may produce warnings defineGlobalEnvConstants(runtime); // Fixme: Do we need the check or does Main.java not call this...they should consolidate if (runtime.getGlobalVariables().get("$*").isNil()) { runtime.getGlobalVariables().defineReadonly("$*", new ValueAccessor(runtime.newArray())); } runtime.getGlobalVariables().defineReadonly("$-p", new ValueAccessor(runtime.getInstanceConfig().isAssumePrinting() ? runtime.getTrue() : runtime.getNil())); runtime.getGlobalVariables().defineReadonly("$-n", new ValueAccessor(runtime.getInstanceConfig().isAssumeLoop() ? runtime.getTrue() : runtime.getNil())); runtime.getGlobalVariables().defineReadonly("$-a", new ValueAccessor(runtime.getInstanceConfig().isSplit() ? runtime.getTrue() : runtime.getNil())); runtime.getGlobalVariables().defineReadonly("$-l", new ValueAccessor(runtime.getInstanceConfig().isProcessLineEnds() ? runtime.getTrue() : runtime.getNil())); // ARGF, $< object RubyArgsFile.initArgsFile(runtime); }
public static void createGlobals(ThreadContext context, Ruby runtime) { runtime.defineGlobalConstant("TOPLEVEL_BINDING", runtime.newBinding()); runtime.defineGlobalConstant("TRUE", runtime.getTrue()); runtime.defineGlobalConstant("FALSE", runtime.getFalse()); runtime.defineGlobalConstant("NIL", runtime.getNil()); // define ARGV and $* for this runtime RubyArray argvArray = runtime.newArray(); String[] argv = runtime.getInstanceConfig().getArgv(); for (int i = 0; i < argv.length; i++) { argvArray.append(RubyString.newString(runtime, argv[i].getBytes())); } runtime.defineGlobalConstant("ARGV", argvArray); runtime.getGlobalVariables().defineReadonly("$*", new ValueAccessor(argvArray)); IAccessor d = new ValueAccessor(runtime.newString( runtime.getInstanceConfig().displayedFileName())); runtime.getGlobalVariables().define("$PROGRAM_NAME", d); runtime.getGlobalVariables().define("$0", d); // Version information: IRubyObject version = runtime.newString(Constants.RUBY_VERSION).freeze(context); IRubyObject release = runtime.newString(Constants.COMPILE_DATE).freeze(context); IRubyObject platform = runtime.newString(Constants.PLATFORM).freeze(context); IRubyObject engine = runtime.newString(Constants.ENGINE).freeze(context); runtime.defineGlobalConstant("RUBY_VERSION", version); runtime.defineGlobalConstant("RUBY_PATCHLEVEL", runtime.newString(Constants.RUBY_PATCHLEVEL).freeze(context)); runtime.defineGlobalConstant("RUBY_RELEASE_DATE", release); runtime.defineGlobalConstant("RUBY_PLATFORM", platform); runtime.defineGlobalConstant("RUBY_ENGINE", engine); runtime.defineGlobalConstant("VERSION", version); runtime.defineGlobalConstant("RELEASE_DATE", release); runtime.defineGlobalConstant("PLATFORM", platform); IRubyObject jrubyVersion = runtime.newString(Constants.VERSION).freeze(context); runtime.defineGlobalConstant("JRUBY_VERSION", jrubyVersion); GlobalVariable kcodeGV = new KCodeGlobalVariable(runtime, "$KCODE", runtime.newString("NONE")); runtime.defineVariable(kcodeGV); runtime.defineVariable(new GlobalVariable.Copy(runtime, "$-K", kcodeGV)); IRubyObject defaultRS = runtime.newString(runtime.getInstanceConfig().getRecordSeparator()).freeze(context); GlobalVariable rs = new StringGlobalVariable(runtime, "$/", defaultRS); runtime.defineVariable(rs); runtime.setRecordSeparatorVar(rs); runtime.getGlobalVariables().setDefaultSeparator(defaultRS); runtime.defineVariable(new StringGlobalVariable(runtime, "$\\", runtime.getNil())); runtime.defineVariable(new StringGlobalVariable(runtime, "$,", runtime.getNil())); runtime.defineVariable(new LineNumberGlobalVariable(runtime, "$.", RubyFixnum.one(runtime))); runtime.defineVariable(new LastlineGlobalVariable(runtime, "$_")); runtime.defineVariable(new LastExitStatusVariable(runtime, "$?")); runtime.defineVariable(new ErrorInfoGlobalVariable(runtime, "$!", runtime.getNil())); runtime.defineVariable(new NonEffectiveGlobalVariable(runtime, "$=", runtime.getFalse())); if(runtime.getInstanceConfig().getInputFieldSeparator() == null) { runtime.defineVariable(new GlobalVariable(runtime, "$;", runtime.getNil())); } else { runtime.defineVariable(new GlobalVariable(runtime, "$;", RubyRegexp.newRegexp(runtime, runtime.getInstanceConfig().getInputFieldSeparator(), 0))); } Boolean verbose = runtime.getInstanceConfig().getVerbose(); IRubyObject verboseValue = null; if (verbose == null) { verboseValue = runtime.getNil(); } else if(verbose == Boolean.TRUE) { verboseValue = runtime.getTrue(); } else { verboseValue = runtime.getFalse(); } runtime.defineVariable(new VerboseGlobalVariable(runtime, "$VERBOSE", verboseValue)); IRubyObject debug = runtime.newBoolean(runtime.getInstanceConfig().isDebug()); runtime.defineVariable(new DebugGlobalVariable(runtime, "$DEBUG", debug)); runtime.defineVariable(new DebugGlobalVariable(runtime, "$-d", debug)); runtime.defineVariable(new SafeGlobalVariable(runtime, "$SAFE")); runtime.defineVariable(new BacktraceGlobalVariable(runtime, "$@")); IRubyObject stdin = new RubyIO(runtime, STDIO.IN); IRubyObject stdout = new RubyIO(runtime, STDIO.OUT); IRubyObject stderr = new RubyIO(runtime, STDIO.ERR); runtime.defineVariable(new InputGlobalVariable(runtime, "$stdin", stdin)); runtime.defineVariable(new OutputGlobalVariable(runtime, "$stdout", stdout)); runtime.getGlobalVariables().alias("$>", "$stdout"); runtime.getGlobalVariables().alias("$defout", "$stdout"); runtime.defineVariable(new OutputGlobalVariable(runtime, "$stderr", stderr)); runtime.getGlobalVariables().alias("$deferr", "$stderr"); runtime.defineGlobalConstant("STDIN", stdin); runtime.defineGlobalConstant("STDOUT", stdout); runtime.defineGlobalConstant("STDERR", stderr); runtime.defineVariable(new LoadedFeatures(runtime, "$\"")); runtime.defineVariable(new LoadedFeatures(runtime, "$LOADED_FEATURES")); runtime.defineVariable(new LoadPath(runtime, "$:")); runtime.defineVariable(new LoadPath(runtime, "$-I")); runtime.defineVariable(new LoadPath(runtime, "$LOAD_PATH")); runtime.defineVariable(new MatchMatchGlobalVariable(runtime, "$&")); runtime.defineVariable(new PreMatchGlobalVariable(runtime, "$`")); runtime.defineVariable(new PostMatchGlobalVariable(runtime, "$'")); runtime.defineVariable(new LastMatchGlobalVariable(runtime, "$+")); runtime.defineVariable(new BackRefGlobalVariable(runtime, "$~")); // On platforms without a c-library accessable through JNA, getpid will return hashCode // as $$ used to. Using $$ to kill processes could take down many runtimes, but by basing // $$ on getpid() where available, we have the same semantics as MRI. runtime.getGlobalVariables().defineReadonly("$$", new ValueAccessor(runtime.newFixnum(runtime.getPosix().getpid()))); // after defn of $stderr as the call may produce warnings defineGlobalEnvConstants(runtime); // Fixme: Do we need the check or does Main.java not call this...they should consolidate if (runtime.getGlobalVariables().get("$*").isNil()) { runtime.getGlobalVariables().defineReadonly("$*", new ValueAccessor(runtime.newArray())); } runtime.getGlobalVariables().defineReadonly("$-p", new ValueAccessor(runtime.getInstanceConfig().isAssumePrinting() ? runtime.getTrue() : runtime.getNil())); runtime.getGlobalVariables().defineReadonly("$-n", new ValueAccessor(runtime.getInstanceConfig().isAssumeLoop() ? runtime.getTrue() : runtime.getNil())); runtime.getGlobalVariables().defineReadonly("$-a", new ValueAccessor(runtime.getInstanceConfig().isSplit() ? runtime.getTrue() : runtime.getNil())); runtime.getGlobalVariables().defineReadonly("$-l", new ValueAccessor(runtime.getInstanceConfig().isProcessLineEnds() ? runtime.getTrue() : runtime.getNil())); // ARGF, $< object RubyArgsFile.initArgsFile(runtime); }
diff --git a/samples/dom/DOMCount.java b/samples/dom/DOMCount.java index 49b82be4..bc136521 100644 --- a/samples/dom/DOMCount.java +++ b/samples/dom/DOMCount.java @@ -1,335 +1,335 @@ /* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999, 2000 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 "Xerces" and "Apache Software Foundation" 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", * 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 and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.apache.org. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ package dom; import util.Arguments; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import org.apache.xerces.dom.TextImpl; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * A sample DOM counter. This sample program illustrates how to * traverse a DOM tree in order to information about the document. * * @version $id$ */ public class DOMCount { // // Constants // /** Default parser name. */ private static final String DEFAULT_PARSER_NAME = "dom.wrappers.DOMParser"; private static boolean setValidation = false; //defaults private static boolean setNameSpaces = true; private static boolean setSchemaSupport = true; private static boolean setDeferredDOM = true; // // Data // /** Elements. */ private long elements; /** Attributes. */ private long attributes; /** Characters. */ private long characters; /** Ignorable whitespace. */ private long ignorableWhitespace; // // Public static methods // /** Counts the resulting document tree. */ public static void count(String parserWrapperName, String uri) { try { DOMParserWrapper parser = (DOMParserWrapper)Class.forName(parserWrapperName).newInstance(); DOMCount counter = new DOMCount(); long before = System.currentTimeMillis(); parser.setFeature( "http://apache.org/xml/features/dom/defer-node-expansion", setDeferredDOM ); parser.setFeature( "http://xml.org/sax/features/validation", setValidation ); parser.setFeature( "http://xml.org/sax/features/namespaces", setNameSpaces ); parser.setFeature( "http://apache.org/xml/features/validation/schema", setSchemaSupport ); Document document = parser.parse(uri); counter.traverse(document); long after = System.currentTimeMillis(); counter.printResults(uri, after - before); } catch (org.xml.sax.SAXParseException spe) { } catch (org.xml.sax.SAXNotRecognizedException ex ){ } catch (org.xml.sax.SAXNotSupportedException ex ){ } catch (org.xml.sax.SAXException se) { if (se.getException() != null) se.getException().printStackTrace(System.err); else se.printStackTrace(System.err); } catch (Exception e) { e.printStackTrace(System.err); } } // print(String,String,boolean) // // Public methods // /** Traverses the specified node, recursively. */ public void traverse(Node node) { // is there anything to do? if (node == null) { return; } int type = node.getNodeType(); switch (type) { // print document case Node.DOCUMENT_NODE: { elements = 0; attributes = 0; characters = 0; ignorableWhitespace = 0; traverse(((Document)node).getDocumentElement()); break; } // print element with attributes case Node.ELEMENT_NODE: { elements++; NamedNodeMap attrs = node.getAttributes(); if (attrs != null) { attributes += attrs.getLength(); } NodeList children = node.getChildNodes(); if (children != null) { int len = children.getLength(); for (int i = 0; i < len; i++) { traverse(children.item(i)); } } break; } // handle entity reference nodes case Node.ENTITY_REFERENCE_NODE: { NodeList children = node.getChildNodes(); if (children != null) { int len = children.getLength(); for (int i = 0; i < len; i++) { traverse(children.item(i)); } } break; } // print text case Node.CDATA_SECTION_NODE: { characters += node.getNodeValue().length(); break; } case Node.TEXT_NODE: { if (node instanceof TextImpl) { if (((TextImpl)node).isIgnorableWhitespace()) ignorableWhitespace += node.getNodeValue().length(); else characters += node.getNodeValue().length(); } else characters += node.getNodeValue().length(); break; } } } // traverse(Node) /** Prints the results. */ public void printResults(String uri, long time) { // filename.xml: 631 ms (4 elems, 0 attrs, 78 spaces, 0 chars) System.out.print(uri); System.out.print(": "); System.out.print(time); System.out.print(" ms ("); System.out.print(elements); System.out.print(" elems, "); System.out.print(attributes); System.out.print(" attrs, "); System.out.print(ignorableWhitespace); System.out.print(" spaces, "); System.out.print(characters); System.out.print(" chars)"); System.out.println(); } // printResults(String,long) // // Main // /** Main program entry point. */ public static void main(String argv[]) { Arguments argopt = new Arguments(); argopt.setUsage( new String[] { "usage: java dom.DOMCount (options) uri ...", "", "options:", " -p name Specify DOM parser wrapper by name.", " -n | -N Turn on/off namespace [default=on]", - " -v | -V Turn on/off validation [default=on]", + " -v | -V Turn on/off validation [default=off]", " -s | -S Turn on/off Schema support [default=on]", " -d | -D Turn on/off deferred DOM [default=on]", " -h This help screen."} ); // is there anything to do? if (argv.length == 0) { argopt.printUsage(); System.exit(1); } // vars String parserName = DEFAULT_PARSER_NAME; argopt.parseArgumentTokens(argv , new char[] { 'p'} ); int c; String arg = null; while ( ( arg = argopt.getlistFiles() ) != null ) { outer: while ( (c = argopt.getArguments()) != -1 ){ switch (c) { case 'v': setValidation = true; //System.out.println( "v" ); break; case 'V': setValidation = false; //System.out.println( "V" ); break; case 'N': setNameSpaces = false; break; case 'n': setNameSpaces = true; break; case 'p': //System.out.println('p'); parserName = argopt.getStringParameter(); //System.out.println( "parserName = " + parserName ); break; case 'd': setDeferredDOM = true; break; case 'D': setDeferredDOM = false; break; case 's': //System.out.println("s" ); setSchemaSupport = true; break; case 'S': //System.out.println("S" ); setSchemaSupport = false; break; case '?': case 'h': case '-': argopt.printUsage(); System.exit(1); break; case -1: //System.out.println( "-1" ); break outer; default: break; } } count(parserName, arg ); //count uri } } // main(String[]) } // class DOMCount
true
true
public static void main(String argv[]) { Arguments argopt = new Arguments(); argopt.setUsage( new String[] { "usage: java dom.DOMCount (options) uri ...", "", "options:", " -p name Specify DOM parser wrapper by name.", " -n | -N Turn on/off namespace [default=on]", " -v | -V Turn on/off validation [default=on]", " -s | -S Turn on/off Schema support [default=on]", " -d | -D Turn on/off deferred DOM [default=on]", " -h This help screen."} ); // is there anything to do? if (argv.length == 0) { argopt.printUsage(); System.exit(1); } // vars String parserName = DEFAULT_PARSER_NAME; argopt.parseArgumentTokens(argv , new char[] { 'p'} ); int c; String arg = null; while ( ( arg = argopt.getlistFiles() ) != null ) { outer: while ( (c = argopt.getArguments()) != -1 ){ switch (c) { case 'v': setValidation = true; //System.out.println( "v" ); break; case 'V': setValidation = false; //System.out.println( "V" ); break; case 'N': setNameSpaces = false; break; case 'n': setNameSpaces = true; break; case 'p': //System.out.println('p'); parserName = argopt.getStringParameter(); //System.out.println( "parserName = " + parserName ); break; case 'd': setDeferredDOM = true; break; case 'D': setDeferredDOM = false; break; case 's': //System.out.println("s" ); setSchemaSupport = true; break; case 'S': //System.out.println("S" ); setSchemaSupport = false; break; case '?': case 'h': case '-': argopt.printUsage(); System.exit(1); break; case -1: //System.out.println( "-1" ); break outer; default: break; } } count(parserName, arg ); //count uri } } // main(String[])
public static void main(String argv[]) { Arguments argopt = new Arguments(); argopt.setUsage( new String[] { "usage: java dom.DOMCount (options) uri ...", "", "options:", " -p name Specify DOM parser wrapper by name.", " -n | -N Turn on/off namespace [default=on]", " -v | -V Turn on/off validation [default=off]", " -s | -S Turn on/off Schema support [default=on]", " -d | -D Turn on/off deferred DOM [default=on]", " -h This help screen."} ); // is there anything to do? if (argv.length == 0) { argopt.printUsage(); System.exit(1); } // vars String parserName = DEFAULT_PARSER_NAME; argopt.parseArgumentTokens(argv , new char[] { 'p'} ); int c; String arg = null; while ( ( arg = argopt.getlistFiles() ) != null ) { outer: while ( (c = argopt.getArguments()) != -1 ){ switch (c) { case 'v': setValidation = true; //System.out.println( "v" ); break; case 'V': setValidation = false; //System.out.println( "V" ); break; case 'N': setNameSpaces = false; break; case 'n': setNameSpaces = true; break; case 'p': //System.out.println('p'); parserName = argopt.getStringParameter(); //System.out.println( "parserName = " + parserName ); break; case 'd': setDeferredDOM = true; break; case 'D': setDeferredDOM = false; break; case 's': //System.out.println("s" ); setSchemaSupport = true; break; case 'S': //System.out.println("S" ); setSchemaSupport = false; break; case '?': case 'h': case '-': argopt.printUsage(); System.exit(1); break; case -1: //System.out.println( "-1" ); break outer; default: break; } } count(parserName, arg ); //count uri } } // main(String[])
diff --git a/mcp/src/minecraft/mods/elysium/Elysium.java b/mcp/src/minecraft/mods/elysium/Elysium.java index d0f663d..a5bc1f3 100644 --- a/mcp/src/minecraft/mods/elysium/Elysium.java +++ b/mcp/src/minecraft/mods/elysium/Elysium.java @@ -1,315 +1,315 @@ package mods.elysium; import java.io.File; import java.util.ArrayList; import java.util.List; import mods.elysium.api.Plants; import mods.elysium.block.*; import mods.elysium.dimension.*; import mods.elysium.dimension.portal.ElysiumBlockPortalCore; import mods.elysium.dimension.portal.ElysiumTileEntityPortal; import mods.elysium.dimension.portal.ElysiumTileEntityPortalRenderer; import mods.elysium.gen.ElysiumWorldGen; import mods.elysium.handlers.BonemealHandler; import mods.elysium.items.*; import mods.elysium.proxy.ClientProxy; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.world.biome.BiomeGenBase; import net.minecraftforge.common.DimensionManager; import net.minecraftforge.common.ForgeHooks; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.Property; import net.minecraftforge.event.EventBus; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.Mod.Init; import cpw.mods.fml.common.Mod.Instance; import cpw.mods.fml.common.Mod.PreInit; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.registry.GameRegistry; import cpw.mods.fml.common.registry.LanguageRegistry; @Mod(name="The Elysium", version="1.0", useMetadata = false, modid = "TheElysium", dependencies="required-after:Forge@[7.8.0,)") //@NetworkMod(channels = {DefaultProps.NET_CHANNEL_NAME}, packetHandler = PacketHandler.class, clientSideRequired = true, serverSideRequired = true) public class Elysium { @Instance public static Elysium instance; public static ElysiumConfiguration mainConfiguration; public static final CreativeTabs tabElysium = new ElysiumTab(12, "The Elysium"); /** Dimension ID **/ public static int DimensionID; //Blocks public static Block paleStone; public static Block soilBlock; public static Block grassBlock; public static Block LeucosandBlock; public static Block RiltBlock; public static Block FostimberLogBlock; public static Block FostimberLeavesBlock; public static Block GastroShellBlock; public static Block FostimberSaplingBlock; public static Block WoodBlock; public static Block FlowerBlock; public static Block CurlgrassBlock; public static Block SulphurOreBlock; public static Block CobaltOreBlock; public static Block IridiumOreBlock; public static Block SiliconOreBlock; public static Block JadeOreBlock; public static Block TourmalineOreBlock; public static Block BerylOreBlock; public static Block waterStill; public static ElysiumBlockFluid waterMoving; public static Block shellFloatingBlock; // public static Block LeucosandBlock; // public static Block LeucosandBlock; // public static Block LeucosandBlock; // public static Block LeucosandBlock; public static Block portalCore; //Items public static Item GracePrismItem; public static Item WhistleItem; public static Item PepperSeedItem; public static Item AsphodelPetalsItem; public static Item OverKillItem; public static Item DebugItem; /** Biome's **/ public static BiomeGenBase ElysiumPlainBiome = null; @PreInit public void loadConfiguration(FMLPreInitializationEvent evt) { // NetworkRegistry.instance().registerGuiHandler(this, guiHandler); // GameRegistry.registerTileEntity(TileMixer.class, "Mixer"); // GameRegistry.registerTileEntity(TileCandyMaker.class, "Candy Maker"); // GameRegistry.addBiome(Halloween); // Version.versionCheck(); mainConfiguration = new ElysiumConfiguration(new File(evt.getModConfigurationDirectory(), "Elysium.cfg")); try { mainConfiguration.load(); Property idDim = Elysium.mainConfiguration.get("dimensionID", "dim", DefaultProps.DimensionID, "This is the id of the dimension change if needed!"); DimensionID = idDim.getInt(); // Block Registry Property idPalestoneBlock = Elysium.mainConfiguration.getTerrainBlock("terrainGen", "palestone.id", DefaultProps.idPalestoneBlock, null); paleStone = (new PalestoneBlock(idPalestoneBlock.getInt(), Material.rock)).setHardness(1.5F).setResistance(10.0F).setStepSound(Block.soundStoneFootstep).setUnlocalizedName("Palestone"); ClientProxy.proxy.registerBlock(paleStone); LanguageRegistry.addName(paleStone, "Palestone"); Property idSoilBlock = Elysium.mainConfiguration.getTerrainBlock("terrainGen", "ElysiumDirt.id", DefaultProps.idSoilBlock, null); soilBlock = (new SoilBlock(idSoilBlock.getInt(), Material.ground)).setHardness(0.5F).setStepSound(Block.soundGravelFootstep).setUnlocalizedName("Gammasoil"); ClientProxy.proxy.registerBlock(soilBlock); LanguageRegistry.addName(soilBlock, "Elysian Soil"); Property idGrassBlock = Elysium.mainConfiguration.getTerrainBlock("terrainGen", "ElysiumGrass.id", DefaultProps.idGrassBlock, null); grassBlock = (new GrassBlock(idGrassBlock.getInt(), Material.ground)).setHardness(0.6F).setStepSound(Block.soundGrassFootstep).setUnlocalizedName("Gammagrass"); ClientProxy.proxy.registerBlock(grassBlock); LanguageRegistry.addName(grassBlock, "Elysian Grass"); Property idLeucosandBlock = Elysium.mainConfiguration.getTerrainBlock("terrainGen", "Leucogrit.id", DefaultProps.idLeucosandBlock, null); LeucosandBlock = (new LeucosandBlock(idLeucosandBlock.getInt(), Material.sand)).setHardness(0.5F).setStepSound(Block.soundSandFootstep).setUnlocalizedName("Leucogrit"); ClientProxy.proxy.registerBlock(LeucosandBlock); LanguageRegistry.addName(LeucosandBlock, "Leucosand"); Property idRiltBlock = Elysium.mainConfiguration.getTerrainBlock("terrainGen", "Rilt.id", DefaultProps.idRiltBlock, null); RiltBlock = (new RiltBlock(idRiltBlock.getInt(), Material.sand)).setHardness(0.6F).setStepSound(Block.soundGravelFootstep).setUnlocalizedName("Rilt"); ClientProxy.proxy.registerBlock(RiltBlock); LanguageRegistry.addName(RiltBlock, "Rilt Block"); Property idFostimberSaplingBlock = Elysium.mainConfiguration.getBlock("FostimberSaplingBlock.id", DefaultProps.idFostimberSaplingBlock); FostimberSaplingBlock = (new FostimberSaplingBlock(idFostimberSaplingBlock.getInt())).setHardness(0F).setUnlocalizedName("fostimber_sapling"); ClientProxy.proxy.registerBlock(FostimberSaplingBlock); LanguageRegistry.addName(FostimberSaplingBlock, "Fostimber Sapling"); Property idFostimberLogBlock = Elysium.mainConfiguration.getBlock("FostimberLog.id", DefaultProps.idFostimberLogBlock); FostimberLogBlock = (new FostimberLogBlock(idFostimberLogBlock.getInt(), Material.wood)).setHardness(2.0F).setStepSound(Block.soundWoodFootstep).setUnlocalizedName("Fostimber Log Top"); ClientProxy.proxy.registerBlock(FostimberLogBlock); LanguageRegistry.addName(FostimberLogBlock, "Fostimber Log"); Property idFostimberLeavesBlock = Elysium.mainConfiguration.getBlock("FostimberLeavesBlock.id", DefaultProps.idFostimberLeavesBlock); FostimberLeavesBlock = (new FostimberLeavesBlock(idFostimberLeavesBlock.getInt(), Material.leaves)).setLightOpacity(1).setHardness(0.2F).setStepSound(Block.soundGrassFootstep).setUnlocalizedName("fostimber_leaves"); ClientProxy.proxy.registerBlock(FostimberLeavesBlock); LanguageRegistry.addName(FostimberLeavesBlock, "Fostimber Leaves"); Property idWoodBlock = Elysium.mainConfiguration.getBlock("idWoodBlock.id", DefaultProps.idWoodBlock); WoodBlock = (new ElysiumBlock(idWoodBlock.getInt(), Material.wood)).setHardness(0.2F).setStepSound(Block.soundGrassFootstep).setUnlocalizedName("fostimber_planks"); ClientProxy.proxy.registerBlock(WoodBlock); LanguageRegistry.addName(WoodBlock, "Wooden Planks"); Property idGastroShellBlock = Elysium.mainConfiguration.getBlock("idGastroShellBlock.id", DefaultProps.idGastroShellBlock); GastroShellBlock = (new GastroShellBlock(idGastroShellBlock.getInt(), Material.leaves)).setHardness(0.2F).setStepSound(Block.soundGrassFootstep).setUnlocalizedName("gastroshellTop"); ClientProxy.proxy.registerBlock(GastroShellBlock); LanguageRegistry.addName(GastroShellBlock, "Gastro Shell"); Property idAsphodelFlowerBlock = Elysium.mainConfiguration.getBlock("idAsphodelFlowerBlock.id", DefaultProps.idAsphodelFlowerBlock); - FlowerBlock = (new ElysiumFlowerBlock(idAsphodelFlowerBlock.getInt())).setHardness(0.2F).setStepSound(Block.soundGrassFootstep).setUnlocalizedName("asphodel_flower"); + FlowerBlock = (new ElysiumFlowerBlock(idAsphodelFlowerBlock.getInt())).setHardness(0.0F).setStepSound(Block.soundGrassFootstep).setUnlocalizedName("asphodel_flower"); ClientProxy.proxy.registerBlock(FlowerBlock); LanguageRegistry.addName(FlowerBlock, "Asphodel Flower"); Property idCurlgrassBlock = Elysium.mainConfiguration.getBlock("idCurlgrassBlock.id", DefaultProps.idCurlgrassBlock); - CurlgrassBlock = new CurlgrassBlock(idCurlgrassBlock.getInt()).setHardness(0.2F).setStepSound(Block.soundGrassFootstep).setUnlocalizedName("Curlgrass"); + CurlgrassBlock = new CurlgrassBlock(idCurlgrassBlock.getInt()).setHardness(0.0F).setStepSound(Block.soundGrassFootstep).setUnlocalizedName("Curlgrass"); ClientProxy.proxy.registerBlock(CurlgrassBlock); LanguageRegistry.addName(CurlgrassBlock, "Curlgrass"); Property idOreSulphurBlock = Elysium.mainConfiguration.getBlock("idOreSulphurBlock.id", DefaultProps.idOreSulphurBlock); SulphurOreBlock = new SulphurOreBlock(idOreSulphurBlock.getInt(), Material.rock).setHardness(0.2F).setStepSound(Block.soundStoneFootstep).setUnlocalizedName("oreSulphur"); ClientProxy.proxy.registerBlock(SulphurOreBlock); LanguageRegistry.addName(SulphurOreBlock, "Sulphur Ore"); Property idOreCobaltBlock = Elysium.mainConfiguration.getBlock("idOreCobaltBlock.id", DefaultProps.idOreCobaltBlock); /**/ CobaltOreBlock = new SulphurOreBlock(idOreCobaltBlock.getInt(), Material.rock).setHardness(0.2F).setStepSound(Block.soundStoneFootstep).setUnlocalizedName("oreCobalt"); ClientProxy.proxy.registerBlock(CobaltOreBlock); LanguageRegistry.addName(CobaltOreBlock, "Cobalt Ore"); Property idOreIridiumBlock = Elysium.mainConfiguration.getBlock("idOreIridiumBlock.id", DefaultProps.idOreIridiumBlock); IridiumOreBlock = new SulphurOreBlock(idOreIridiumBlock.getInt(), Material.rock).setHardness(0.2F).setStepSound(Block.soundStoneFootstep).setUnlocalizedName("oreIridium"); ClientProxy.proxy.registerBlock(IridiumOreBlock); LanguageRegistry.addName(IridiumOreBlock, "Iridium Ore"); Property idOreSiliconBlock = Elysium.mainConfiguration.getBlock("idOreSiliconBlock.id", DefaultProps.idOreSiliconBlock); SiliconOreBlock = new SulphurOreBlock(idOreSiliconBlock.getInt(), Material.rock).setHardness(0.2F).setStepSound(Block.soundStoneFootstep).setUnlocalizedName("oreSilicon"); ClientProxy.proxy.registerBlock(SiliconOreBlock); LanguageRegistry.addName(SiliconOreBlock, "Silicon Ore"); Property idOreJadeBlock = Elysium.mainConfiguration.getBlock("idOreJadeBlock.id", DefaultProps.idOreJadeBlock); JadeOreBlock = new SulphurOreBlock(idOreJadeBlock.getInt(), Material.rock).setHardness(0.2F).setStepSound(Block.soundStoneFootstep).setUnlocalizedName("oreJade"); ClientProxy.proxy.registerBlock(JadeOreBlock); LanguageRegistry.addName(JadeOreBlock, "Jade Ore"); Property idOreTourmalineBlock = Elysium.mainConfiguration.getBlock("idOreTourmalineBlock.id", DefaultProps.idOreTourmalineBlock); TourmalineOreBlock = new SulphurOreBlock(idOreTourmalineBlock.getInt(), Material.rock).setHardness(0.2F).setStepSound(Block.soundStoneFootstep).setUnlocalizedName("oreTourmaline"); ClientProxy.proxy.registerBlock(TourmalineOreBlock); LanguageRegistry.addName(TourmalineOreBlock, "Tourmaline Ore"); Property idOreBerylBlock = Elysium.mainConfiguration.getBlock("idOreBerylBlock.id", DefaultProps.idOreBerylBlock); BerylOreBlock = new SulphurOreBlock(idOreBerylBlock.getInt(), Material.rock).setHardness(0.2F).setStepSound(Block.soundStoneFootstep).setUnlocalizedName("oreBeryl"); ClientProxy.proxy.registerBlock(BerylOreBlock); LanguageRegistry.addName(BerylOreBlock, "Beryl Ore"); Property idWaterBlock = Elysium.mainConfiguration.getTerrainBlock("terrainGen", "idWaterBlock.id", DefaultProps.idWaterBlock, null); waterStill = new ElysiumBlockStationary(idWaterBlock.getInt(), Material.water).setHardness(100.0F).setLightOpacity(3).setUnlocalizedName("elysian_water"); ClientProxy.proxy.registerBlock(waterStill); LanguageRegistry.addName(waterStill, "Elysium Water Still"); Property idWaterFlowingBlock = Elysium.mainConfiguration.getTerrainBlock("terrainGen", "idWaterFlowingBlock.id", DefaultProps.idWaterFlowingBlock, null); waterMoving = (ElysiumBlockFluid) new ElysiumBlockFlowing(idWaterFlowingBlock.getInt(), Material.water).setHardness(100.0F).setLightOpacity(3).setUnlocalizedName("elysian_water_flow"); ClientProxy.proxy.registerBlock(waterMoving); LanguageRegistry.addName(waterMoving, "Elysium Water Flowing"); Property idPortalCoreBlock = Elysium.mainConfiguration.getBlock("idPortalCoreBlock.id", DefaultProps.idPortalCoreBlock); portalCore = new ElysiumBlockPortalCore(idPortalCoreBlock.getInt(), Material.glass).setHardness(5F).setStepSound(Block.soundGlassFootstep).setUnlocalizedName("portalCore"); ClientProxy.proxy.registerBlock(portalCore); LanguageRegistry.addName(portalCore, "Elysian Portal Block"); Property idShellsBlock = Elysium.mainConfiguration.getBlock("idShellsBlock.id", DefaultProps.idShellsBlock); shellFloatingBlock = new BlockShells(idShellsBlock.getInt()).setHardness(0.0F).setStepSound(Block.soundGlassFootstep).setUnlocalizedName("shell"); ClientProxy.proxy.registerBlock(shellFloatingBlock); LanguageRegistry.addName(shellFloatingBlock, "Shell..."); Block.dragonEgg.setCreativeTab(tabElysium); // MinecraftForge.setToolClass(Item.pickaxeWood, "pickaxe", 0); // Item Registry Property idGracePrismItem = Elysium.mainConfiguration.getItem("idGracePrismItem.id", DefaultProps.idGracePrismItem); GracePrismItem = new ItemGracePrism(idGracePrismItem.getInt()).setUnlocalizedName("gracecrystal"); LanguageRegistry.addName(GracePrismItem, "Grace Prism"); Property idWhistleItem = Elysium.mainConfiguration.getItem("idWhistleItem.id", DefaultProps.idWhistleItem); WhistleItem = new ItemWhistle(idWhistleItem.getInt()).setUnlocalizedName("enderwhistle"); LanguageRegistry.addName(WhistleItem, "Ender Whistle"); Property idPepperSeedItem = Elysium.mainConfiguration.getItem("idPepperSeedItem.id", DefaultProps.idPepperSeedItem); PepperSeedItem = new ElysiumItem(idPepperSeedItem.getInt()).setUnlocalizedName("seeds_pepper"); Property idOverkillItem = Elysium.mainConfiguration.getItem("idOverkillItem.id", DefaultProps.idOverkillItem); OverKillItem = new OverkillItem(idOverkillItem.getInt()).setUnlocalizedName("asd"); LanguageRegistry.addName(OverKillItem, "Overkill Item"); Property idAsphodelPetalsItem = Elysium.mainConfiguration.getItem("idAsphodelPetalsItem.id", DefaultProps.idAsphodelPetalsItem); AsphodelPetalsItem = new ElysiumItem(idAsphodelPetalsItem.getInt()).setUnlocalizedName("asphodelpetal"); LanguageRegistry.addName(AsphodelPetalsItem, "Asphodel Petals"); Property idDebugItem = Elysium.mainConfiguration.getItem("idDebugItem.id", DefaultProps.idDebugItem); DebugItem = new ItemDebug(idDebugItem.getInt()).setUnlocalizedName("debug"); LanguageRegistry.addName(DebugItem, "Modders Item"); // Crafting Registry GameRegistry.addRecipe(new ItemStack(GracePrismItem), new Object[] {"SMS","MDM","SMS", Character.valueOf('S'), Block.whiteStone, Character.valueOf('M'), Item.bucketMilk, Character.valueOf('D'), Item.diamond}); GameRegistry.addShapelessRecipe(new ItemStack(AsphodelPetalsItem, 2), new Object[] {FlowerBlock}); // Entity Registry GameRegistry.registerTileEntity(ElysiumTileEntityPortal.class, "ElysiumTileEntityPortal"); // MinecraftForge.setBlockHarvestLevel(ash, "shovel", 0); // MinecraftForge.setBlockHarvestLevel(blockAsh, "shovel", 0); ClientProxy.proxy.RegisterRenders(); } finally { mainConfiguration.save(); } } @Init public void initialize(FMLInitializationEvent evt) { MinecraftForge.EVENT_BUS.register(new BonemealHandler()); Plants.addGrassPlant(CurlgrassBlock, 0, 30); Plants.addGrassPlant(FlowerBlock, 0, 10); Plants.addGrassSeed(new ItemStack(PepperSeedItem), 10); // new LiquidStacks(); // CoreProxy.proxy.addAnimation(); // LiquidManager.liquids.add(new LiquidData(LiquidStacks.rawCandy, new ItemStack(rawCandyBucket), new ItemStack(Item.bucketEmpty))); // LiquidManager.liquids.add(new LiquidData(LiquidStacks.milk, new ItemStack(Item.bucketMilk), new ItemStack(Item.bucketEmpty))); // CoreProxy.proxy.initializeRendering(); // CoreProxy.proxy.initializeEntityRendering(); /** Register WorldProvider for Dimension **/ DimensionManager.registerProviderType(DimensionID, WorldProviderElysium.class, true); DimensionManager.registerDimension(DimensionID, DimensionID); ElysiumPlainBiome = new BiomeGenElysium(25); GameRegistry.registerWorldGenerator(new ElysiumWorldGen()); } }
false
true
public void loadConfiguration(FMLPreInitializationEvent evt) { // NetworkRegistry.instance().registerGuiHandler(this, guiHandler); // GameRegistry.registerTileEntity(TileMixer.class, "Mixer"); // GameRegistry.registerTileEntity(TileCandyMaker.class, "Candy Maker"); // GameRegistry.addBiome(Halloween); // Version.versionCheck(); mainConfiguration = new ElysiumConfiguration(new File(evt.getModConfigurationDirectory(), "Elysium.cfg")); try { mainConfiguration.load(); Property idDim = Elysium.mainConfiguration.get("dimensionID", "dim", DefaultProps.DimensionID, "This is the id of the dimension change if needed!"); DimensionID = idDim.getInt(); // Block Registry Property idPalestoneBlock = Elysium.mainConfiguration.getTerrainBlock("terrainGen", "palestone.id", DefaultProps.idPalestoneBlock, null); paleStone = (new PalestoneBlock(idPalestoneBlock.getInt(), Material.rock)).setHardness(1.5F).setResistance(10.0F).setStepSound(Block.soundStoneFootstep).setUnlocalizedName("Palestone"); ClientProxy.proxy.registerBlock(paleStone); LanguageRegistry.addName(paleStone, "Palestone"); Property idSoilBlock = Elysium.mainConfiguration.getTerrainBlock("terrainGen", "ElysiumDirt.id", DefaultProps.idSoilBlock, null); soilBlock = (new SoilBlock(idSoilBlock.getInt(), Material.ground)).setHardness(0.5F).setStepSound(Block.soundGravelFootstep).setUnlocalizedName("Gammasoil"); ClientProxy.proxy.registerBlock(soilBlock); LanguageRegistry.addName(soilBlock, "Elysian Soil"); Property idGrassBlock = Elysium.mainConfiguration.getTerrainBlock("terrainGen", "ElysiumGrass.id", DefaultProps.idGrassBlock, null); grassBlock = (new GrassBlock(idGrassBlock.getInt(), Material.ground)).setHardness(0.6F).setStepSound(Block.soundGrassFootstep).setUnlocalizedName("Gammagrass"); ClientProxy.proxy.registerBlock(grassBlock); LanguageRegistry.addName(grassBlock, "Elysian Grass"); Property idLeucosandBlock = Elysium.mainConfiguration.getTerrainBlock("terrainGen", "Leucogrit.id", DefaultProps.idLeucosandBlock, null); LeucosandBlock = (new LeucosandBlock(idLeucosandBlock.getInt(), Material.sand)).setHardness(0.5F).setStepSound(Block.soundSandFootstep).setUnlocalizedName("Leucogrit"); ClientProxy.proxy.registerBlock(LeucosandBlock); LanguageRegistry.addName(LeucosandBlock, "Leucosand"); Property idRiltBlock = Elysium.mainConfiguration.getTerrainBlock("terrainGen", "Rilt.id", DefaultProps.idRiltBlock, null); RiltBlock = (new RiltBlock(idRiltBlock.getInt(), Material.sand)).setHardness(0.6F).setStepSound(Block.soundGravelFootstep).setUnlocalizedName("Rilt"); ClientProxy.proxy.registerBlock(RiltBlock); LanguageRegistry.addName(RiltBlock, "Rilt Block"); Property idFostimberSaplingBlock = Elysium.mainConfiguration.getBlock("FostimberSaplingBlock.id", DefaultProps.idFostimberSaplingBlock); FostimberSaplingBlock = (new FostimberSaplingBlock(idFostimberSaplingBlock.getInt())).setHardness(0F).setUnlocalizedName("fostimber_sapling"); ClientProxy.proxy.registerBlock(FostimberSaplingBlock); LanguageRegistry.addName(FostimberSaplingBlock, "Fostimber Sapling"); Property idFostimberLogBlock = Elysium.mainConfiguration.getBlock("FostimberLog.id", DefaultProps.idFostimberLogBlock); FostimberLogBlock = (new FostimberLogBlock(idFostimberLogBlock.getInt(), Material.wood)).setHardness(2.0F).setStepSound(Block.soundWoodFootstep).setUnlocalizedName("Fostimber Log Top"); ClientProxy.proxy.registerBlock(FostimberLogBlock); LanguageRegistry.addName(FostimberLogBlock, "Fostimber Log"); Property idFostimberLeavesBlock = Elysium.mainConfiguration.getBlock("FostimberLeavesBlock.id", DefaultProps.idFostimberLeavesBlock); FostimberLeavesBlock = (new FostimberLeavesBlock(idFostimberLeavesBlock.getInt(), Material.leaves)).setLightOpacity(1).setHardness(0.2F).setStepSound(Block.soundGrassFootstep).setUnlocalizedName("fostimber_leaves"); ClientProxy.proxy.registerBlock(FostimberLeavesBlock); LanguageRegistry.addName(FostimberLeavesBlock, "Fostimber Leaves"); Property idWoodBlock = Elysium.mainConfiguration.getBlock("idWoodBlock.id", DefaultProps.idWoodBlock); WoodBlock = (new ElysiumBlock(idWoodBlock.getInt(), Material.wood)).setHardness(0.2F).setStepSound(Block.soundGrassFootstep).setUnlocalizedName("fostimber_planks"); ClientProxy.proxy.registerBlock(WoodBlock); LanguageRegistry.addName(WoodBlock, "Wooden Planks"); Property idGastroShellBlock = Elysium.mainConfiguration.getBlock("idGastroShellBlock.id", DefaultProps.idGastroShellBlock); GastroShellBlock = (new GastroShellBlock(idGastroShellBlock.getInt(), Material.leaves)).setHardness(0.2F).setStepSound(Block.soundGrassFootstep).setUnlocalizedName("gastroshellTop"); ClientProxy.proxy.registerBlock(GastroShellBlock); LanguageRegistry.addName(GastroShellBlock, "Gastro Shell"); Property idAsphodelFlowerBlock = Elysium.mainConfiguration.getBlock("idAsphodelFlowerBlock.id", DefaultProps.idAsphodelFlowerBlock); FlowerBlock = (new ElysiumFlowerBlock(idAsphodelFlowerBlock.getInt())).setHardness(0.2F).setStepSound(Block.soundGrassFootstep).setUnlocalizedName("asphodel_flower"); ClientProxy.proxy.registerBlock(FlowerBlock); LanguageRegistry.addName(FlowerBlock, "Asphodel Flower"); Property idCurlgrassBlock = Elysium.mainConfiguration.getBlock("idCurlgrassBlock.id", DefaultProps.idCurlgrassBlock); CurlgrassBlock = new CurlgrassBlock(idCurlgrassBlock.getInt()).setHardness(0.2F).setStepSound(Block.soundGrassFootstep).setUnlocalizedName("Curlgrass"); ClientProxy.proxy.registerBlock(CurlgrassBlock); LanguageRegistry.addName(CurlgrassBlock, "Curlgrass"); Property idOreSulphurBlock = Elysium.mainConfiguration.getBlock("idOreSulphurBlock.id", DefaultProps.idOreSulphurBlock); SulphurOreBlock = new SulphurOreBlock(idOreSulphurBlock.getInt(), Material.rock).setHardness(0.2F).setStepSound(Block.soundStoneFootstep).setUnlocalizedName("oreSulphur"); ClientProxy.proxy.registerBlock(SulphurOreBlock); LanguageRegistry.addName(SulphurOreBlock, "Sulphur Ore"); Property idOreCobaltBlock = Elysium.mainConfiguration.getBlock("idOreCobaltBlock.id", DefaultProps.idOreCobaltBlock); /**/ CobaltOreBlock = new SulphurOreBlock(idOreCobaltBlock.getInt(), Material.rock).setHardness(0.2F).setStepSound(Block.soundStoneFootstep).setUnlocalizedName("oreCobalt"); ClientProxy.proxy.registerBlock(CobaltOreBlock); LanguageRegistry.addName(CobaltOreBlock, "Cobalt Ore"); Property idOreIridiumBlock = Elysium.mainConfiguration.getBlock("idOreIridiumBlock.id", DefaultProps.idOreIridiumBlock); IridiumOreBlock = new SulphurOreBlock(idOreIridiumBlock.getInt(), Material.rock).setHardness(0.2F).setStepSound(Block.soundStoneFootstep).setUnlocalizedName("oreIridium"); ClientProxy.proxy.registerBlock(IridiumOreBlock); LanguageRegistry.addName(IridiumOreBlock, "Iridium Ore"); Property idOreSiliconBlock = Elysium.mainConfiguration.getBlock("idOreSiliconBlock.id", DefaultProps.idOreSiliconBlock); SiliconOreBlock = new SulphurOreBlock(idOreSiliconBlock.getInt(), Material.rock).setHardness(0.2F).setStepSound(Block.soundStoneFootstep).setUnlocalizedName("oreSilicon"); ClientProxy.proxy.registerBlock(SiliconOreBlock); LanguageRegistry.addName(SiliconOreBlock, "Silicon Ore"); Property idOreJadeBlock = Elysium.mainConfiguration.getBlock("idOreJadeBlock.id", DefaultProps.idOreJadeBlock); JadeOreBlock = new SulphurOreBlock(idOreJadeBlock.getInt(), Material.rock).setHardness(0.2F).setStepSound(Block.soundStoneFootstep).setUnlocalizedName("oreJade"); ClientProxy.proxy.registerBlock(JadeOreBlock); LanguageRegistry.addName(JadeOreBlock, "Jade Ore"); Property idOreTourmalineBlock = Elysium.mainConfiguration.getBlock("idOreTourmalineBlock.id", DefaultProps.idOreTourmalineBlock); TourmalineOreBlock = new SulphurOreBlock(idOreTourmalineBlock.getInt(), Material.rock).setHardness(0.2F).setStepSound(Block.soundStoneFootstep).setUnlocalizedName("oreTourmaline"); ClientProxy.proxy.registerBlock(TourmalineOreBlock); LanguageRegistry.addName(TourmalineOreBlock, "Tourmaline Ore"); Property idOreBerylBlock = Elysium.mainConfiguration.getBlock("idOreBerylBlock.id", DefaultProps.idOreBerylBlock); BerylOreBlock = new SulphurOreBlock(idOreBerylBlock.getInt(), Material.rock).setHardness(0.2F).setStepSound(Block.soundStoneFootstep).setUnlocalizedName("oreBeryl"); ClientProxy.proxy.registerBlock(BerylOreBlock); LanguageRegistry.addName(BerylOreBlock, "Beryl Ore"); Property idWaterBlock = Elysium.mainConfiguration.getTerrainBlock("terrainGen", "idWaterBlock.id", DefaultProps.idWaterBlock, null); waterStill = new ElysiumBlockStationary(idWaterBlock.getInt(), Material.water).setHardness(100.0F).setLightOpacity(3).setUnlocalizedName("elysian_water"); ClientProxy.proxy.registerBlock(waterStill); LanguageRegistry.addName(waterStill, "Elysium Water Still"); Property idWaterFlowingBlock = Elysium.mainConfiguration.getTerrainBlock("terrainGen", "idWaterFlowingBlock.id", DefaultProps.idWaterFlowingBlock, null); waterMoving = (ElysiumBlockFluid) new ElysiumBlockFlowing(idWaterFlowingBlock.getInt(), Material.water).setHardness(100.0F).setLightOpacity(3).setUnlocalizedName("elysian_water_flow"); ClientProxy.proxy.registerBlock(waterMoving); LanguageRegistry.addName(waterMoving, "Elysium Water Flowing"); Property idPortalCoreBlock = Elysium.mainConfiguration.getBlock("idPortalCoreBlock.id", DefaultProps.idPortalCoreBlock); portalCore = new ElysiumBlockPortalCore(idPortalCoreBlock.getInt(), Material.glass).setHardness(5F).setStepSound(Block.soundGlassFootstep).setUnlocalizedName("portalCore"); ClientProxy.proxy.registerBlock(portalCore); LanguageRegistry.addName(portalCore, "Elysian Portal Block"); Property idShellsBlock = Elysium.mainConfiguration.getBlock("idShellsBlock.id", DefaultProps.idShellsBlock); shellFloatingBlock = new BlockShells(idShellsBlock.getInt()).setHardness(0.0F).setStepSound(Block.soundGlassFootstep).setUnlocalizedName("shell"); ClientProxy.proxy.registerBlock(shellFloatingBlock); LanguageRegistry.addName(shellFloatingBlock, "Shell..."); Block.dragonEgg.setCreativeTab(tabElysium); // MinecraftForge.setToolClass(Item.pickaxeWood, "pickaxe", 0); // Item Registry Property idGracePrismItem = Elysium.mainConfiguration.getItem("idGracePrismItem.id", DefaultProps.idGracePrismItem); GracePrismItem = new ItemGracePrism(idGracePrismItem.getInt()).setUnlocalizedName("gracecrystal"); LanguageRegistry.addName(GracePrismItem, "Grace Prism"); Property idWhistleItem = Elysium.mainConfiguration.getItem("idWhistleItem.id", DefaultProps.idWhistleItem); WhistleItem = new ItemWhistle(idWhistleItem.getInt()).setUnlocalizedName("enderwhistle"); LanguageRegistry.addName(WhistleItem, "Ender Whistle"); Property idPepperSeedItem = Elysium.mainConfiguration.getItem("idPepperSeedItem.id", DefaultProps.idPepperSeedItem); PepperSeedItem = new ElysiumItem(idPepperSeedItem.getInt()).setUnlocalizedName("seeds_pepper"); Property idOverkillItem = Elysium.mainConfiguration.getItem("idOverkillItem.id", DefaultProps.idOverkillItem); OverKillItem = new OverkillItem(idOverkillItem.getInt()).setUnlocalizedName("asd"); LanguageRegistry.addName(OverKillItem, "Overkill Item"); Property idAsphodelPetalsItem = Elysium.mainConfiguration.getItem("idAsphodelPetalsItem.id", DefaultProps.idAsphodelPetalsItem); AsphodelPetalsItem = new ElysiumItem(idAsphodelPetalsItem.getInt()).setUnlocalizedName("asphodelpetal"); LanguageRegistry.addName(AsphodelPetalsItem, "Asphodel Petals"); Property idDebugItem = Elysium.mainConfiguration.getItem("idDebugItem.id", DefaultProps.idDebugItem); DebugItem = new ItemDebug(idDebugItem.getInt()).setUnlocalizedName("debug"); LanguageRegistry.addName(DebugItem, "Modders Item"); // Crafting Registry GameRegistry.addRecipe(new ItemStack(GracePrismItem), new Object[] {"SMS","MDM","SMS", Character.valueOf('S'), Block.whiteStone, Character.valueOf('M'), Item.bucketMilk, Character.valueOf('D'), Item.diamond}); GameRegistry.addShapelessRecipe(new ItemStack(AsphodelPetalsItem, 2), new Object[] {FlowerBlock}); // Entity Registry GameRegistry.registerTileEntity(ElysiumTileEntityPortal.class, "ElysiumTileEntityPortal"); // MinecraftForge.setBlockHarvestLevel(ash, "shovel", 0); // MinecraftForge.setBlockHarvestLevel(blockAsh, "shovel", 0); ClientProxy.proxy.RegisterRenders(); } finally { mainConfiguration.save(); } }
public void loadConfiguration(FMLPreInitializationEvent evt) { // NetworkRegistry.instance().registerGuiHandler(this, guiHandler); // GameRegistry.registerTileEntity(TileMixer.class, "Mixer"); // GameRegistry.registerTileEntity(TileCandyMaker.class, "Candy Maker"); // GameRegistry.addBiome(Halloween); // Version.versionCheck(); mainConfiguration = new ElysiumConfiguration(new File(evt.getModConfigurationDirectory(), "Elysium.cfg")); try { mainConfiguration.load(); Property idDim = Elysium.mainConfiguration.get("dimensionID", "dim", DefaultProps.DimensionID, "This is the id of the dimension change if needed!"); DimensionID = idDim.getInt(); // Block Registry Property idPalestoneBlock = Elysium.mainConfiguration.getTerrainBlock("terrainGen", "palestone.id", DefaultProps.idPalestoneBlock, null); paleStone = (new PalestoneBlock(idPalestoneBlock.getInt(), Material.rock)).setHardness(1.5F).setResistance(10.0F).setStepSound(Block.soundStoneFootstep).setUnlocalizedName("Palestone"); ClientProxy.proxy.registerBlock(paleStone); LanguageRegistry.addName(paleStone, "Palestone"); Property idSoilBlock = Elysium.mainConfiguration.getTerrainBlock("terrainGen", "ElysiumDirt.id", DefaultProps.idSoilBlock, null); soilBlock = (new SoilBlock(idSoilBlock.getInt(), Material.ground)).setHardness(0.5F).setStepSound(Block.soundGravelFootstep).setUnlocalizedName("Gammasoil"); ClientProxy.proxy.registerBlock(soilBlock); LanguageRegistry.addName(soilBlock, "Elysian Soil"); Property idGrassBlock = Elysium.mainConfiguration.getTerrainBlock("terrainGen", "ElysiumGrass.id", DefaultProps.idGrassBlock, null); grassBlock = (new GrassBlock(idGrassBlock.getInt(), Material.ground)).setHardness(0.6F).setStepSound(Block.soundGrassFootstep).setUnlocalizedName("Gammagrass"); ClientProxy.proxy.registerBlock(grassBlock); LanguageRegistry.addName(grassBlock, "Elysian Grass"); Property idLeucosandBlock = Elysium.mainConfiguration.getTerrainBlock("terrainGen", "Leucogrit.id", DefaultProps.idLeucosandBlock, null); LeucosandBlock = (new LeucosandBlock(idLeucosandBlock.getInt(), Material.sand)).setHardness(0.5F).setStepSound(Block.soundSandFootstep).setUnlocalizedName("Leucogrit"); ClientProxy.proxy.registerBlock(LeucosandBlock); LanguageRegistry.addName(LeucosandBlock, "Leucosand"); Property idRiltBlock = Elysium.mainConfiguration.getTerrainBlock("terrainGen", "Rilt.id", DefaultProps.idRiltBlock, null); RiltBlock = (new RiltBlock(idRiltBlock.getInt(), Material.sand)).setHardness(0.6F).setStepSound(Block.soundGravelFootstep).setUnlocalizedName("Rilt"); ClientProxy.proxy.registerBlock(RiltBlock); LanguageRegistry.addName(RiltBlock, "Rilt Block"); Property idFostimberSaplingBlock = Elysium.mainConfiguration.getBlock("FostimberSaplingBlock.id", DefaultProps.idFostimberSaplingBlock); FostimberSaplingBlock = (new FostimberSaplingBlock(idFostimberSaplingBlock.getInt())).setHardness(0F).setUnlocalizedName("fostimber_sapling"); ClientProxy.proxy.registerBlock(FostimberSaplingBlock); LanguageRegistry.addName(FostimberSaplingBlock, "Fostimber Sapling"); Property idFostimberLogBlock = Elysium.mainConfiguration.getBlock("FostimberLog.id", DefaultProps.idFostimberLogBlock); FostimberLogBlock = (new FostimberLogBlock(idFostimberLogBlock.getInt(), Material.wood)).setHardness(2.0F).setStepSound(Block.soundWoodFootstep).setUnlocalizedName("Fostimber Log Top"); ClientProxy.proxy.registerBlock(FostimberLogBlock); LanguageRegistry.addName(FostimberLogBlock, "Fostimber Log"); Property idFostimberLeavesBlock = Elysium.mainConfiguration.getBlock("FostimberLeavesBlock.id", DefaultProps.idFostimberLeavesBlock); FostimberLeavesBlock = (new FostimberLeavesBlock(idFostimberLeavesBlock.getInt(), Material.leaves)).setLightOpacity(1).setHardness(0.2F).setStepSound(Block.soundGrassFootstep).setUnlocalizedName("fostimber_leaves"); ClientProxy.proxy.registerBlock(FostimberLeavesBlock); LanguageRegistry.addName(FostimberLeavesBlock, "Fostimber Leaves"); Property idWoodBlock = Elysium.mainConfiguration.getBlock("idWoodBlock.id", DefaultProps.idWoodBlock); WoodBlock = (new ElysiumBlock(idWoodBlock.getInt(), Material.wood)).setHardness(0.2F).setStepSound(Block.soundGrassFootstep).setUnlocalizedName("fostimber_planks"); ClientProxy.proxy.registerBlock(WoodBlock); LanguageRegistry.addName(WoodBlock, "Wooden Planks"); Property idGastroShellBlock = Elysium.mainConfiguration.getBlock("idGastroShellBlock.id", DefaultProps.idGastroShellBlock); GastroShellBlock = (new GastroShellBlock(idGastroShellBlock.getInt(), Material.leaves)).setHardness(0.2F).setStepSound(Block.soundGrassFootstep).setUnlocalizedName("gastroshellTop"); ClientProxy.proxy.registerBlock(GastroShellBlock); LanguageRegistry.addName(GastroShellBlock, "Gastro Shell"); Property idAsphodelFlowerBlock = Elysium.mainConfiguration.getBlock("idAsphodelFlowerBlock.id", DefaultProps.idAsphodelFlowerBlock); FlowerBlock = (new ElysiumFlowerBlock(idAsphodelFlowerBlock.getInt())).setHardness(0.0F).setStepSound(Block.soundGrassFootstep).setUnlocalizedName("asphodel_flower"); ClientProxy.proxy.registerBlock(FlowerBlock); LanguageRegistry.addName(FlowerBlock, "Asphodel Flower"); Property idCurlgrassBlock = Elysium.mainConfiguration.getBlock("idCurlgrassBlock.id", DefaultProps.idCurlgrassBlock); CurlgrassBlock = new CurlgrassBlock(idCurlgrassBlock.getInt()).setHardness(0.0F).setStepSound(Block.soundGrassFootstep).setUnlocalizedName("Curlgrass"); ClientProxy.proxy.registerBlock(CurlgrassBlock); LanguageRegistry.addName(CurlgrassBlock, "Curlgrass"); Property idOreSulphurBlock = Elysium.mainConfiguration.getBlock("idOreSulphurBlock.id", DefaultProps.idOreSulphurBlock); SulphurOreBlock = new SulphurOreBlock(idOreSulphurBlock.getInt(), Material.rock).setHardness(0.2F).setStepSound(Block.soundStoneFootstep).setUnlocalizedName("oreSulphur"); ClientProxy.proxy.registerBlock(SulphurOreBlock); LanguageRegistry.addName(SulphurOreBlock, "Sulphur Ore"); Property idOreCobaltBlock = Elysium.mainConfiguration.getBlock("idOreCobaltBlock.id", DefaultProps.idOreCobaltBlock); /**/ CobaltOreBlock = new SulphurOreBlock(idOreCobaltBlock.getInt(), Material.rock).setHardness(0.2F).setStepSound(Block.soundStoneFootstep).setUnlocalizedName("oreCobalt"); ClientProxy.proxy.registerBlock(CobaltOreBlock); LanguageRegistry.addName(CobaltOreBlock, "Cobalt Ore"); Property idOreIridiumBlock = Elysium.mainConfiguration.getBlock("idOreIridiumBlock.id", DefaultProps.idOreIridiumBlock); IridiumOreBlock = new SulphurOreBlock(idOreIridiumBlock.getInt(), Material.rock).setHardness(0.2F).setStepSound(Block.soundStoneFootstep).setUnlocalizedName("oreIridium"); ClientProxy.proxy.registerBlock(IridiumOreBlock); LanguageRegistry.addName(IridiumOreBlock, "Iridium Ore"); Property idOreSiliconBlock = Elysium.mainConfiguration.getBlock("idOreSiliconBlock.id", DefaultProps.idOreSiliconBlock); SiliconOreBlock = new SulphurOreBlock(idOreSiliconBlock.getInt(), Material.rock).setHardness(0.2F).setStepSound(Block.soundStoneFootstep).setUnlocalizedName("oreSilicon"); ClientProxy.proxy.registerBlock(SiliconOreBlock); LanguageRegistry.addName(SiliconOreBlock, "Silicon Ore"); Property idOreJadeBlock = Elysium.mainConfiguration.getBlock("idOreJadeBlock.id", DefaultProps.idOreJadeBlock); JadeOreBlock = new SulphurOreBlock(idOreJadeBlock.getInt(), Material.rock).setHardness(0.2F).setStepSound(Block.soundStoneFootstep).setUnlocalizedName("oreJade"); ClientProxy.proxy.registerBlock(JadeOreBlock); LanguageRegistry.addName(JadeOreBlock, "Jade Ore"); Property idOreTourmalineBlock = Elysium.mainConfiguration.getBlock("idOreTourmalineBlock.id", DefaultProps.idOreTourmalineBlock); TourmalineOreBlock = new SulphurOreBlock(idOreTourmalineBlock.getInt(), Material.rock).setHardness(0.2F).setStepSound(Block.soundStoneFootstep).setUnlocalizedName("oreTourmaline"); ClientProxy.proxy.registerBlock(TourmalineOreBlock); LanguageRegistry.addName(TourmalineOreBlock, "Tourmaline Ore"); Property idOreBerylBlock = Elysium.mainConfiguration.getBlock("idOreBerylBlock.id", DefaultProps.idOreBerylBlock); BerylOreBlock = new SulphurOreBlock(idOreBerylBlock.getInt(), Material.rock).setHardness(0.2F).setStepSound(Block.soundStoneFootstep).setUnlocalizedName("oreBeryl"); ClientProxy.proxy.registerBlock(BerylOreBlock); LanguageRegistry.addName(BerylOreBlock, "Beryl Ore"); Property idWaterBlock = Elysium.mainConfiguration.getTerrainBlock("terrainGen", "idWaterBlock.id", DefaultProps.idWaterBlock, null); waterStill = new ElysiumBlockStationary(idWaterBlock.getInt(), Material.water).setHardness(100.0F).setLightOpacity(3).setUnlocalizedName("elysian_water"); ClientProxy.proxy.registerBlock(waterStill); LanguageRegistry.addName(waterStill, "Elysium Water Still"); Property idWaterFlowingBlock = Elysium.mainConfiguration.getTerrainBlock("terrainGen", "idWaterFlowingBlock.id", DefaultProps.idWaterFlowingBlock, null); waterMoving = (ElysiumBlockFluid) new ElysiumBlockFlowing(idWaterFlowingBlock.getInt(), Material.water).setHardness(100.0F).setLightOpacity(3).setUnlocalizedName("elysian_water_flow"); ClientProxy.proxy.registerBlock(waterMoving); LanguageRegistry.addName(waterMoving, "Elysium Water Flowing"); Property idPortalCoreBlock = Elysium.mainConfiguration.getBlock("idPortalCoreBlock.id", DefaultProps.idPortalCoreBlock); portalCore = new ElysiumBlockPortalCore(idPortalCoreBlock.getInt(), Material.glass).setHardness(5F).setStepSound(Block.soundGlassFootstep).setUnlocalizedName("portalCore"); ClientProxy.proxy.registerBlock(portalCore); LanguageRegistry.addName(portalCore, "Elysian Portal Block"); Property idShellsBlock = Elysium.mainConfiguration.getBlock("idShellsBlock.id", DefaultProps.idShellsBlock); shellFloatingBlock = new BlockShells(idShellsBlock.getInt()).setHardness(0.0F).setStepSound(Block.soundGlassFootstep).setUnlocalizedName("shell"); ClientProxy.proxy.registerBlock(shellFloatingBlock); LanguageRegistry.addName(shellFloatingBlock, "Shell..."); Block.dragonEgg.setCreativeTab(tabElysium); // MinecraftForge.setToolClass(Item.pickaxeWood, "pickaxe", 0); // Item Registry Property idGracePrismItem = Elysium.mainConfiguration.getItem("idGracePrismItem.id", DefaultProps.idGracePrismItem); GracePrismItem = new ItemGracePrism(idGracePrismItem.getInt()).setUnlocalizedName("gracecrystal"); LanguageRegistry.addName(GracePrismItem, "Grace Prism"); Property idWhistleItem = Elysium.mainConfiguration.getItem("idWhistleItem.id", DefaultProps.idWhistleItem); WhistleItem = new ItemWhistle(idWhistleItem.getInt()).setUnlocalizedName("enderwhistle"); LanguageRegistry.addName(WhistleItem, "Ender Whistle"); Property idPepperSeedItem = Elysium.mainConfiguration.getItem("idPepperSeedItem.id", DefaultProps.idPepperSeedItem); PepperSeedItem = new ElysiumItem(idPepperSeedItem.getInt()).setUnlocalizedName("seeds_pepper"); Property idOverkillItem = Elysium.mainConfiguration.getItem("idOverkillItem.id", DefaultProps.idOverkillItem); OverKillItem = new OverkillItem(idOverkillItem.getInt()).setUnlocalizedName("asd"); LanguageRegistry.addName(OverKillItem, "Overkill Item"); Property idAsphodelPetalsItem = Elysium.mainConfiguration.getItem("idAsphodelPetalsItem.id", DefaultProps.idAsphodelPetalsItem); AsphodelPetalsItem = new ElysiumItem(idAsphodelPetalsItem.getInt()).setUnlocalizedName("asphodelpetal"); LanguageRegistry.addName(AsphodelPetalsItem, "Asphodel Petals"); Property idDebugItem = Elysium.mainConfiguration.getItem("idDebugItem.id", DefaultProps.idDebugItem); DebugItem = new ItemDebug(idDebugItem.getInt()).setUnlocalizedName("debug"); LanguageRegistry.addName(DebugItem, "Modders Item"); // Crafting Registry GameRegistry.addRecipe(new ItemStack(GracePrismItem), new Object[] {"SMS","MDM","SMS", Character.valueOf('S'), Block.whiteStone, Character.valueOf('M'), Item.bucketMilk, Character.valueOf('D'), Item.diamond}); GameRegistry.addShapelessRecipe(new ItemStack(AsphodelPetalsItem, 2), new Object[] {FlowerBlock}); // Entity Registry GameRegistry.registerTileEntity(ElysiumTileEntityPortal.class, "ElysiumTileEntityPortal"); // MinecraftForge.setBlockHarvestLevel(ash, "shovel", 0); // MinecraftForge.setBlockHarvestLevel(blockAsh, "shovel", 0); ClientProxy.proxy.RegisterRenders(); } finally { mainConfiguration.save(); } }
diff --git a/src/test/java/org/elasticsearch/index/mapper/copyto/CopyToMapperIntegrationTests.java b/src/test/java/org/elasticsearch/index/mapper/copyto/CopyToMapperIntegrationTests.java index 1bb9e51c68c..9c18a94fc93 100644 --- a/src/test/java/org/elasticsearch/index/mapper/copyto/CopyToMapperIntegrationTests.java +++ b/src/test/java/org/elasticsearch/index/mapper/copyto/CopyToMapperIntegrationTests.java @@ -1,90 +1,90 @@ /* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.index.mapper.copyto; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.aggregations.AggregationBuilders; import org.elasticsearch.search.aggregations.bucket.terms.Terms; import org.elasticsearch.test.ElasticsearchIntegrationTest; import org.junit.Test; import java.io.IOException; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked; import static org.hamcrest.Matchers.equalTo; /** */ public class CopyToMapperIntegrationTests extends ElasticsearchIntegrationTest { @Test public void testDynamicTemplateCopyTo() throws Exception { assertAcked( client().admin().indices().prepareCreate("test-idx") .addMapping("doc", createDynamicTemplateMapping()) ); - int recordCount = randomInt(200); + int recordCount = between(1, 200); for (int i = 0; i < recordCount * 2; i++) { client().prepareIndex("test-idx", "doc", Integer.toString(i)) .setSource("test_field", "test " + i, "even", i % 2 == 0) .get(); } client().admin().indices().prepareRefresh("test-idx").execute().actionGet(); SearchResponse response = client().prepareSearch("test-idx") .setQuery(QueryBuilders.termQuery("even", true)) .addAggregation(AggregationBuilders.terms("test").field("test_field").size(recordCount * 2)) .addAggregation(AggregationBuilders.terms("test_raw").field("test_field_raw").size(recordCount * 2)) .execute().actionGet(); assertThat(response.getHits().totalHits(), equalTo((long) recordCount)); assertThat(((Terms) response.getAggregations().get("test")).buckets().size(), equalTo(recordCount + 1)); assertThat(((Terms) response.getAggregations().get("test_raw")).buckets().size(), equalTo(recordCount)); } private XContentBuilder createDynamicTemplateMapping() throws IOException { return XContentFactory.jsonBuilder().startObject().startObject("doc") .startArray("dynamic_templates") .startObject().startObject("template_raw") .field("match", "*_raw") .field("match_mapping_type", "string") .startObject("mapping").field("type", "string").field("index", "not_analyzed").endObject() .endObject().endObject() .startObject().startObject("template_all") .field("match", "*") .field("match_mapping_type", "string") .startObject("mapping").field("type", "string").field("copy_to", "{name}_raw").endObject() .endObject().endObject() .endArray(); } }
true
true
public void testDynamicTemplateCopyTo() throws Exception { assertAcked( client().admin().indices().prepareCreate("test-idx") .addMapping("doc", createDynamicTemplateMapping()) ); int recordCount = randomInt(200); for (int i = 0; i < recordCount * 2; i++) { client().prepareIndex("test-idx", "doc", Integer.toString(i)) .setSource("test_field", "test " + i, "even", i % 2 == 0) .get(); } client().admin().indices().prepareRefresh("test-idx").execute().actionGet(); SearchResponse response = client().prepareSearch("test-idx") .setQuery(QueryBuilders.termQuery("even", true)) .addAggregation(AggregationBuilders.terms("test").field("test_field").size(recordCount * 2)) .addAggregation(AggregationBuilders.terms("test_raw").field("test_field_raw").size(recordCount * 2)) .execute().actionGet(); assertThat(response.getHits().totalHits(), equalTo((long) recordCount)); assertThat(((Terms) response.getAggregations().get("test")).buckets().size(), equalTo(recordCount + 1)); assertThat(((Terms) response.getAggregations().get("test_raw")).buckets().size(), equalTo(recordCount)); }
public void testDynamicTemplateCopyTo() throws Exception { assertAcked( client().admin().indices().prepareCreate("test-idx") .addMapping("doc", createDynamicTemplateMapping()) ); int recordCount = between(1, 200); for (int i = 0; i < recordCount * 2; i++) { client().prepareIndex("test-idx", "doc", Integer.toString(i)) .setSource("test_field", "test " + i, "even", i % 2 == 0) .get(); } client().admin().indices().prepareRefresh("test-idx").execute().actionGet(); SearchResponse response = client().prepareSearch("test-idx") .setQuery(QueryBuilders.termQuery("even", true)) .addAggregation(AggregationBuilders.terms("test").field("test_field").size(recordCount * 2)) .addAggregation(AggregationBuilders.terms("test_raw").field("test_field_raw").size(recordCount * 2)) .execute().actionGet(); assertThat(response.getHits().totalHits(), equalTo((long) recordCount)); assertThat(((Terms) response.getAggregations().get("test")).buckets().size(), equalTo(recordCount + 1)); assertThat(((Terms) response.getAggregations().get("test_raw")).buckets().size(), equalTo(recordCount)); }
diff --git a/flexodesktop/model/flexofoundation/src/main/java/org/openflexo/foundation/viewpoint/action/DeclareShapeInEditionPattern.java b/flexodesktop/model/flexofoundation/src/main/java/org/openflexo/foundation/viewpoint/action/DeclareShapeInEditionPattern.java index d5a681ba4..bc89dfcc2 100644 --- a/flexodesktop/model/flexofoundation/src/main/java/org/openflexo/foundation/viewpoint/action/DeclareShapeInEditionPattern.java +++ b/flexodesktop/model/flexofoundation/src/main/java/org/openflexo/foundation/viewpoint/action/DeclareShapeInEditionPattern.java @@ -1,577 +1,577 @@ /* * (c) Copyright 2010-2011 AgileBirds * * This file is part of OpenFlexo. * * OpenFlexo 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. * * OpenFlexo 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 OpenFlexo. If not, see <http://www.gnu.org/licenses/>. * */ package org.openflexo.foundation.viewpoint.action; import java.util.Hashtable; import java.util.Vector; import java.util.logging.Logger; import org.openflexo.fge.ShapeGraphicalRepresentation; import org.openflexo.foundation.FlexoEditor; import org.openflexo.foundation.FlexoModelObject; import org.openflexo.foundation.action.FlexoActionType; import org.openflexo.foundation.ontology.FlexoOntology; import org.openflexo.foundation.ontology.OntologicDataType; import org.openflexo.foundation.ontology.OntologyClass; import org.openflexo.foundation.ontology.OntologyDataProperty; import org.openflexo.foundation.ontology.OntologyObject; import org.openflexo.foundation.ontology.OntologyObjectProperty; import org.openflexo.foundation.ontology.OntologyProperty; import org.openflexo.foundation.viewpoint.AddIndividual; import org.openflexo.foundation.viewpoint.AddShape; import org.openflexo.foundation.viewpoint.CheckboxParameter; import org.openflexo.foundation.viewpoint.DataPropertyAssertion; import org.openflexo.foundation.viewpoint.DeclarePatternRole; import org.openflexo.foundation.viewpoint.DropScheme; import org.openflexo.foundation.viewpoint.EditionPattern; import org.openflexo.foundation.viewpoint.EditionScheme; import org.openflexo.foundation.viewpoint.EditionSchemeParameter; import org.openflexo.foundation.viewpoint.ExampleDrawingObject; import org.openflexo.foundation.viewpoint.ExampleDrawingShape; import org.openflexo.foundation.viewpoint.FloatParameter; import org.openflexo.foundation.viewpoint.GraphicalElementPatternRole; import org.openflexo.foundation.viewpoint.IndividualParameter; import org.openflexo.foundation.viewpoint.IndividualPatternRole; import org.openflexo.foundation.viewpoint.IntegerParameter; import org.openflexo.foundation.viewpoint.ObjectPropertyAssertion; import org.openflexo.foundation.viewpoint.ShapePatternRole; import org.openflexo.foundation.viewpoint.TextFieldParameter; import org.openflexo.foundation.viewpoint.URIParameter; import org.openflexo.foundation.viewpoint.binding.ViewPointDataBinding; import org.openflexo.foundation.viewpoint.inspector.CheckboxInspectorEntry; import org.openflexo.foundation.viewpoint.inspector.EditionPatternInspector; import org.openflexo.foundation.viewpoint.inspector.FloatInspectorEntry; import org.openflexo.foundation.viewpoint.inspector.InspectorEntry; import org.openflexo.foundation.viewpoint.inspector.IntegerInspectorEntry; import org.openflexo.foundation.viewpoint.inspector.TextFieldInspectorEntry; import org.openflexo.toolbox.JavaUtils; import org.openflexo.toolbox.StringUtils; public class DeclareShapeInEditionPattern extends DeclareInEditionPattern<DeclareShapeInEditionPattern, ExampleDrawingShape> { private static final Logger logger = Logger.getLogger(DeclareShapeInEditionPattern.class.getPackage().getName()); public static FlexoActionType<DeclareShapeInEditionPattern, ExampleDrawingShape, ExampleDrawingObject> actionType = new FlexoActionType<DeclareShapeInEditionPattern, ExampleDrawingShape, ExampleDrawingObject>( "declare_in_edition_pattern", FlexoActionType.defaultGroup, FlexoActionType.NORMAL_ACTION_TYPE) { /** * Factory method */ @Override public DeclareShapeInEditionPattern makeNewAction(ExampleDrawingShape focusedObject, Vector<ExampleDrawingObject> globalSelection, FlexoEditor editor) { return new DeclareShapeInEditionPattern(focusedObject, globalSelection, editor); } @Override protected boolean isVisibleForSelection(ExampleDrawingShape shape, Vector<ExampleDrawingObject> globalSelection) { return true; } @Override protected boolean isEnabledForSelection(ExampleDrawingShape shape, Vector<ExampleDrawingObject> globalSelection) { return shape != null && shape.getCalc() != null; } }; static { FlexoModelObject.addActionForClass(DeclareShapeInEditionPattern.actionType, ExampleDrawingShape.class); } public static enum NewEditionPatternChoices { MAP_SINGLE_INDIVIDUAL, BLANK_EDITION_PATTERN } public NewEditionPatternChoices patternChoice = NewEditionPatternChoices.MAP_SINGLE_INDIVIDUAL; private String editionPatternName; private OntologyClass concept; private String individualPatternRoleName; public boolean isTopLevel = true; public EditionPattern containerEditionPattern; private String dropSchemeName; private EditionPattern newEditionPattern; private Hashtable<ExampleDrawingObjectEntry, GraphicalElementPatternRole> newGraphicalElementPatternRoles; public Vector<PropertyEntry> propertyEntries = new Vector<PropertyEntry>(); DeclareShapeInEditionPattern(ExampleDrawingShape focusedObject, Vector<ExampleDrawingObject> globalSelection, FlexoEditor editor) { super(actionType, focusedObject, globalSelection, editor); } @Override protected void doAction(Object context) { logger.info("Declare shape in edition pattern"); if (isValid()) { switch (primaryChoice) { case CHOOSE_EXISTING_EDITION_PATTERN: if (getPatternRole() != null) { getPatternRole().updateGraphicalRepresentation(getFocusedObject().getGraphicalRepresentation()); } break; case CREATES_EDITION_PATTERN: switch (patternChoice) { case MAP_SINGLE_INDIVIDUAL: case BLANK_EDITION_PATTERN: // Create new edition pattern newEditionPattern = new EditionPattern(); newEditionPattern.setName(getEditionPatternName()); // Find best URI base candidate PropertyEntry mainPropertyDescriptor = selectBestEntryForURIBaseName(); // Create individual pattern role IndividualPatternRole individualPatternRole = new IndividualPatternRole(); if (patternChoice == NewEditionPatternChoices.MAP_SINGLE_INDIVIDUAL) { individualPatternRole.setPatternRoleName(getIndividualPatternRoleName()); individualPatternRole.setOntologicType(getConcept()); newEditionPattern.addToPatternRoles(individualPatternRole); newEditionPattern.setPrimaryConceptRole(individualPatternRole); } // Create graphical elements pattern role newGraphicalElementPatternRoles = new Hashtable<ExampleDrawingObjectEntry, GraphicalElementPatternRole>(); GraphicalElementPatternRole primaryRepresentationRole = null; for (ExampleDrawingObjectEntry entry : drawingObjectEntries) { if (entry.getSelectThis()) { if (entry.graphicalObject instanceof ExampleDrawingShape) { ShapePatternRole newShapePatternRole = new ShapePatternRole(); newShapePatternRole.setPatternRoleName(entry.patternRoleName); if (mainPropertyDescriptor != null && entry.isMainEntry()) { newShapePatternRole.setLabel(new ViewPointDataBinding(getIndividualPatternRoleName() + "." + mainPropertyDescriptor.property.getName())); } else { newShapePatternRole.setReadOnlyLabel(true); if (StringUtils.isNotEmpty(entry.graphicalObject.getName())) { newShapePatternRole .setLabel(new ViewPointDataBinding("\"" + entry.graphicalObject.getName() + "\"")); } } newShapePatternRole.setExampleLabel(((ShapeGraphicalRepresentation) entry.graphicalObject .getGraphicalRepresentation()).getText()); // We clone here the GR (fixed unfocusable GR bug) newShapePatternRole.setGraphicalRepresentation(((ShapeGraphicalRepresentation<?>) entry.graphicalObject .getGraphicalRepresentation()).clone()); // Forces GR to be displayed in view ((ShapeGraphicalRepresentation<?>) newShapePatternRole.getGraphicalRepresentation()) .setAllowToLeaveBounds(false); newEditionPattern.addToPatternRoles(newShapePatternRole); if (entry.getParentEntry() != null) { newShapePatternRole.setParentShapePatternRole((ShapePatternRole) newGraphicalElementPatternRoles .get(entry.getParentEntry())); } if (entry.isMainEntry()) { primaryRepresentationRole = newShapePatternRole; } newGraphicalElementPatternRoles.put(entry, newShapePatternRole); } } } newEditionPattern.setPrimaryRepresentationRole(primaryRepresentationRole); // Create other individual roles Vector<IndividualPatternRole> otherRoles = new Vector<IndividualPatternRole>(); if (patternChoice == NewEditionPatternChoices.MAP_SINGLE_INDIVIDUAL) { for (PropertyEntry e : propertyEntries) { if (e.selectEntry) { if (e.property instanceof OntologyObjectProperty) { OntologyObject range = e.property.getRange(); if (range instanceof OntologyClass) { IndividualPatternRole newPatternRole = new IndividualPatternRole(); newPatternRole.setPatternRoleName(e.property.getName()); newPatternRole.setOntologicType((OntologyClass) range); newEditionPattern.addToPatternRoles(newPatternRole); otherRoles.add(newPatternRole); } } } } } // Create new drop scheme DropScheme newDropScheme = new DropScheme(); newDropScheme.setName(getDropSchemeName()); newDropScheme.setTopTarget(isTopLevel); if (!isTopLevel) { newDropScheme.setTargetEditionPattern(containerEditionPattern); } // Parameters if (patternChoice == NewEditionPatternChoices.MAP_SINGLE_INDIVIDUAL) { Vector<PropertyEntry> candidates = new Vector<PropertyEntry>(); for (PropertyEntry e : propertyEntries) { - if (e.selectEntry) { + if (e != null && e.selectEntry) { EditionSchemeParameter newParameter = null; if (e.property instanceof OntologyDataProperty) { switch (((OntologyDataProperty) e.property).getDataType()) { case Boolean: newParameter = new CheckboxParameter(); newParameter.setName(e.property.getName()); newParameter.setLabel(e.label); break; case Byte: case Integer: case Long: case Short: newParameter = new IntegerParameter(); newParameter.setName(e.property.getName()); newParameter.setLabel(e.label); break; case Double: case Float: newParameter = new FloatParameter(); newParameter.setName(e.property.getName()); newParameter.setLabel(e.label); break; case String: newParameter = new TextFieldParameter(); newParameter.setName(e.property.getName()); newParameter.setLabel(e.label); break; default: break; } } else if (e.property instanceof OntologyObjectProperty) { OntologyObject range = e.property.getRange(); if (range instanceof OntologyClass) { newParameter = new IndividualParameter(); newParameter.setName(e.property.getName()); newParameter.setLabel(e.label); ((IndividualParameter) newParameter).setConcept((OntologyClass) range); } } if (newParameter != null) { newDropScheme.addToParameters(newParameter); } } } URIParameter uriParameter = new URIParameter(); uriParameter.setName("uri"); uriParameter.setLabel("uri"); if (mainPropertyDescriptor != null) { uriParameter.setBaseURI(new ViewPointDataBinding(mainPropertyDescriptor.property.getName())); } newDropScheme.addToParameters(uriParameter); // Declare pattern role for (IndividualPatternRole r : otherRoles) { DeclarePatternRole action = new DeclarePatternRole(); action.setPatternRole(r); action.setObject(new ViewPointDataBinding("parameters." + r.getName())); newDropScheme.addToActions(action); } // Add individual action AddIndividual newAddIndividual = new AddIndividual(); newAddIndividual.setPatternRole(individualPatternRole); newAddIndividual.setIndividualName(new ViewPointDataBinding("parameters.uri")); for (PropertyEntry e : propertyEntries) { if (e.selectEntry) { if (e.property instanceof OntologyObjectProperty) { OntologyObject range = e.property.getRange(); if (range instanceof OntologyClass) { ObjectPropertyAssertion propertyAssertion = new ObjectPropertyAssertion(); propertyAssertion.setOntologyProperty(e.property); propertyAssertion.setObject(new ViewPointDataBinding("parameters." + e.property.getName())); newAddIndividual.addToObjectAssertions(propertyAssertion); } } else if (e.property instanceof OntologyDataProperty) { DataPropertyAssertion propertyAssertion = new DataPropertyAssertion(); propertyAssertion.setOntologyProperty(e.property); propertyAssertion.setValue(new ViewPointDataBinding("parameters." + e.property.getName())); newAddIndividual.addToDataAssertions(propertyAssertion); } } } newDropScheme.addToActions(newAddIndividual); } // Add shape/connector actions boolean mainPatternRole = true; for (GraphicalElementPatternRole graphicalElementPatternRole : newGraphicalElementPatternRoles.values()) { if (graphicalElementPatternRole instanceof ShapePatternRole) { // Add shape action AddShape newAddShape = new AddShape(); newAddShape.setPatternRole((ShapePatternRole) graphicalElementPatternRole); if (mainPatternRole) { if (isTopLevel) { newAddShape.setContainer(new ViewPointDataBinding(EditionScheme.TOP_LEVEL)); } else { newAddShape.setContainer(new ViewPointDataBinding(EditionScheme.TARGET + "." + containerEditionPattern.getPrimaryRepresentationRole().getPatternRoleName())); } } mainPatternRole = false; newDropScheme.addToActions(newAddShape); } } // Add new drop scheme newEditionPattern.addToEditionSchemes(newDropScheme); // Add inspector EditionPatternInspector inspector = newEditionPattern.getInspector(); inspector.setInspectorTitle(getEditionPatternName()); if (patternChoice == NewEditionPatternChoices.MAP_SINGLE_INDIVIDUAL) { for (PropertyEntry e : propertyEntries) { if (e.selectEntry) { if (e.property instanceof OntologyObjectProperty) { OntologyObject range = e.property.getRange(); if (range instanceof OntologyClass) { InspectorEntry newInspectorEntry = null; newInspectorEntry = new TextFieldInspectorEntry(); newInspectorEntry.setName(e.property.getName()); newInspectorEntry.setLabel(e.label); newInspectorEntry.setIsReadOnly(true); newInspectorEntry.setData(new ViewPointDataBinding(e.property.getName() + ".uriName")); inspector.addToEntries(newInspectorEntry); } } else if (e.property instanceof OntologyDataProperty) { InspectorEntry newInspectorEntry = null; switch (((OntologyDataProperty) e.property).getDataType()) { case Boolean: newInspectorEntry = new CheckboxInspectorEntry(); break; case Byte: case Integer: case Long: case Short: newInspectorEntry = new IntegerInspectorEntry(); break; case Double: case Float: newInspectorEntry = new FloatInspectorEntry(); break; case String: newInspectorEntry = new TextFieldInspectorEntry(); break; default: logger.warning("Not handled: " + ((OntologyDataProperty) e.property).getDataType()); } if (newInspectorEntry != null) { newInspectorEntry.setName(e.property.getName()); newInspectorEntry.setLabel(e.label); newInspectorEntry.setData(new ViewPointDataBinding(getIndividualPatternRoleName() + "." + e.property.getName())); inspector.addToEntries(newInspectorEntry); } } } } } // And add the newly created edition pattern getFocusedObject().getCalc().addToEditionPatterns(newEditionPattern); default: break; } default: logger.warning("Pattern not implemented"); } } else { logger.warning("Focused role is null !"); } } @Override public boolean isValid() { if (getFocusedObject() == null) { return false; } switch (primaryChoice) { case CHOOSE_EXISTING_EDITION_PATTERN: return getEditionPattern() != null && getPatternRole() != null; case CREATES_EDITION_PATTERN: switch (patternChoice) { case MAP_SINGLE_INDIVIDUAL: return StringUtils.isNotEmpty(getEditionPatternName()) && concept != null && StringUtils.isNotEmpty(getIndividualPatternRoleName()) && getSelectedEntriesCount() > 0 && (isTopLevel || containerEditionPattern != null) && StringUtils.isNotEmpty(getDropSchemeName()); case BLANK_EDITION_PATTERN: return StringUtils.isNotEmpty(getEditionPatternName()) && getSelectedEntriesCount() > 0 && (isTopLevel || containerEditionPattern != null) && StringUtils.isNotEmpty(getDropSchemeName()); default: break; } default: return false; } } private ShapePatternRole patternRole; @Override public ShapePatternRole getPatternRole() { return patternRole; } public void setPatternRole(ShapePatternRole patternRole) { this.patternRole = patternRole; } @Override public void resetPatternRole() { this.patternRole = null; } public OntologyClass getConcept() { return concept; } public void setConcept(OntologyClass concept) { this.concept = concept; propertyEntries.clear(); FlexoOntology ownerOntology = concept.getFlexoOntology(); for (OntologyProperty p : concept.getPropertiesTakingMySelfAsDomain()) { if (p.getFlexoOntology() == ownerOntology) { PropertyEntry newEntry = new PropertyEntry(p); propertyEntries.add(newEntry); } } } public String getEditionPatternName() { if (StringUtils.isEmpty(editionPatternName) && concept != null) { return concept.getName(); } return editionPatternName; } public void setEditionPatternName(String editionPatternName) { this.editionPatternName = editionPatternName; } public String getIndividualPatternRoleName() { if (StringUtils.isEmpty(individualPatternRoleName) && concept != null) { return JavaUtils.getVariableName(concept.getName()); } return individualPatternRoleName; } public void setIndividualPatternRoleName(String individualPatternRoleName) { this.individualPatternRoleName = individualPatternRoleName; } /*public String getShapePatternRoleName() { if (StringUtils.isEmpty(shapePatternRoleName)) { return "shape"; } return shapePatternRoleName; } public void setShapePatternRoleName(String shapePatternRoleName) { this.shapePatternRoleName = shapePatternRoleName; }*/ public String getDropSchemeName() { if (StringUtils.isEmpty(dropSchemeName)) { return "drop" + (StringUtils.isEmpty(getEditionPatternName()) ? "" : getEditionPatternName()) + (isTopLevel ? "AtTopLevel" : containerEditionPattern != null ? "In" + containerEditionPattern.getName() : ""); } return dropSchemeName; } public void setDropSchemeName(String dropSchemeName) { this.dropSchemeName = dropSchemeName; } public class PropertyEntry { public OntologyProperty property; public String label; public boolean selectEntry = true; public PropertyEntry(OntologyProperty property) { this.property = property; if (StringUtils.isNotEmpty(property.getDescription())) { label = property.getDescription(); } else { label = property.getName() + "_of_" + getIndividualPatternRoleName(); } } public String getRange() { if (property instanceof OntologyDataProperty) { if (((OntologyDataProperty) property).getDataType() != null) { return ((OntologyDataProperty) property).getDataType().name(); } return ""; } if (property.getRange() != null) { return property.getRange().getName(); } return ""; } } private PropertyEntry selectBestEntryForURIBaseName() { Vector<PropertyEntry> candidates = new Vector<PropertyEntry>(); for (PropertyEntry e : propertyEntries) { if (e.selectEntry && e.property instanceof OntologyDataProperty && ((OntologyDataProperty) e.property).getDataType() == OntologicDataType.String) { candidates.add(e); } } if (candidates.size() > 0) { return candidates.firstElement(); } return null; } public PropertyEntry createPropertyEntry() { PropertyEntry newPropertyEntry = new PropertyEntry(null); propertyEntries.add(newPropertyEntry); return newPropertyEntry; } public PropertyEntry deletePropertyEntry(PropertyEntry aPropertyEntry) { propertyEntries.remove(aPropertyEntry); return aPropertyEntry; } public void selectAllProperties() { for (PropertyEntry e : propertyEntries) { e.selectEntry = true; } } public void selectNoneProperties() { for (PropertyEntry e : propertyEntries) { e.selectEntry = false; } } @Override public EditionPattern getEditionPattern() { if (primaryChoice == DeclareInEditionPatternChoices.CREATES_EDITION_PATTERN) { return newEditionPattern; } return super.getEditionPattern(); }; }
true
true
protected void doAction(Object context) { logger.info("Declare shape in edition pattern"); if (isValid()) { switch (primaryChoice) { case CHOOSE_EXISTING_EDITION_PATTERN: if (getPatternRole() != null) { getPatternRole().updateGraphicalRepresentation(getFocusedObject().getGraphicalRepresentation()); } break; case CREATES_EDITION_PATTERN: switch (patternChoice) { case MAP_SINGLE_INDIVIDUAL: case BLANK_EDITION_PATTERN: // Create new edition pattern newEditionPattern = new EditionPattern(); newEditionPattern.setName(getEditionPatternName()); // Find best URI base candidate PropertyEntry mainPropertyDescriptor = selectBestEntryForURIBaseName(); // Create individual pattern role IndividualPatternRole individualPatternRole = new IndividualPatternRole(); if (patternChoice == NewEditionPatternChoices.MAP_SINGLE_INDIVIDUAL) { individualPatternRole.setPatternRoleName(getIndividualPatternRoleName()); individualPatternRole.setOntologicType(getConcept()); newEditionPattern.addToPatternRoles(individualPatternRole); newEditionPattern.setPrimaryConceptRole(individualPatternRole); } // Create graphical elements pattern role newGraphicalElementPatternRoles = new Hashtable<ExampleDrawingObjectEntry, GraphicalElementPatternRole>(); GraphicalElementPatternRole primaryRepresentationRole = null; for (ExampleDrawingObjectEntry entry : drawingObjectEntries) { if (entry.getSelectThis()) { if (entry.graphicalObject instanceof ExampleDrawingShape) { ShapePatternRole newShapePatternRole = new ShapePatternRole(); newShapePatternRole.setPatternRoleName(entry.patternRoleName); if (mainPropertyDescriptor != null && entry.isMainEntry()) { newShapePatternRole.setLabel(new ViewPointDataBinding(getIndividualPatternRoleName() + "." + mainPropertyDescriptor.property.getName())); } else { newShapePatternRole.setReadOnlyLabel(true); if (StringUtils.isNotEmpty(entry.graphicalObject.getName())) { newShapePatternRole .setLabel(new ViewPointDataBinding("\"" + entry.graphicalObject.getName() + "\"")); } } newShapePatternRole.setExampleLabel(((ShapeGraphicalRepresentation) entry.graphicalObject .getGraphicalRepresentation()).getText()); // We clone here the GR (fixed unfocusable GR bug) newShapePatternRole.setGraphicalRepresentation(((ShapeGraphicalRepresentation<?>) entry.graphicalObject .getGraphicalRepresentation()).clone()); // Forces GR to be displayed in view ((ShapeGraphicalRepresentation<?>) newShapePatternRole.getGraphicalRepresentation()) .setAllowToLeaveBounds(false); newEditionPattern.addToPatternRoles(newShapePatternRole); if (entry.getParentEntry() != null) { newShapePatternRole.setParentShapePatternRole((ShapePatternRole) newGraphicalElementPatternRoles .get(entry.getParentEntry())); } if (entry.isMainEntry()) { primaryRepresentationRole = newShapePatternRole; } newGraphicalElementPatternRoles.put(entry, newShapePatternRole); } } } newEditionPattern.setPrimaryRepresentationRole(primaryRepresentationRole); // Create other individual roles Vector<IndividualPatternRole> otherRoles = new Vector<IndividualPatternRole>(); if (patternChoice == NewEditionPatternChoices.MAP_SINGLE_INDIVIDUAL) { for (PropertyEntry e : propertyEntries) { if (e.selectEntry) { if (e.property instanceof OntologyObjectProperty) { OntologyObject range = e.property.getRange(); if (range instanceof OntologyClass) { IndividualPatternRole newPatternRole = new IndividualPatternRole(); newPatternRole.setPatternRoleName(e.property.getName()); newPatternRole.setOntologicType((OntologyClass) range); newEditionPattern.addToPatternRoles(newPatternRole); otherRoles.add(newPatternRole); } } } } } // Create new drop scheme DropScheme newDropScheme = new DropScheme(); newDropScheme.setName(getDropSchemeName()); newDropScheme.setTopTarget(isTopLevel); if (!isTopLevel) { newDropScheme.setTargetEditionPattern(containerEditionPattern); } // Parameters if (patternChoice == NewEditionPatternChoices.MAP_SINGLE_INDIVIDUAL) { Vector<PropertyEntry> candidates = new Vector<PropertyEntry>(); for (PropertyEntry e : propertyEntries) { if (e.selectEntry) { EditionSchemeParameter newParameter = null; if (e.property instanceof OntologyDataProperty) { switch (((OntologyDataProperty) e.property).getDataType()) { case Boolean: newParameter = new CheckboxParameter(); newParameter.setName(e.property.getName()); newParameter.setLabel(e.label); break; case Byte: case Integer: case Long: case Short: newParameter = new IntegerParameter(); newParameter.setName(e.property.getName()); newParameter.setLabel(e.label); break; case Double: case Float: newParameter = new FloatParameter(); newParameter.setName(e.property.getName()); newParameter.setLabel(e.label); break; case String: newParameter = new TextFieldParameter(); newParameter.setName(e.property.getName()); newParameter.setLabel(e.label); break; default: break; } } else if (e.property instanceof OntologyObjectProperty) { OntologyObject range = e.property.getRange(); if (range instanceof OntologyClass) { newParameter = new IndividualParameter(); newParameter.setName(e.property.getName()); newParameter.setLabel(e.label); ((IndividualParameter) newParameter).setConcept((OntologyClass) range); } } if (newParameter != null) { newDropScheme.addToParameters(newParameter); } } } URIParameter uriParameter = new URIParameter(); uriParameter.setName("uri"); uriParameter.setLabel("uri"); if (mainPropertyDescriptor != null) { uriParameter.setBaseURI(new ViewPointDataBinding(mainPropertyDescriptor.property.getName())); } newDropScheme.addToParameters(uriParameter); // Declare pattern role for (IndividualPatternRole r : otherRoles) { DeclarePatternRole action = new DeclarePatternRole(); action.setPatternRole(r); action.setObject(new ViewPointDataBinding("parameters." + r.getName())); newDropScheme.addToActions(action); } // Add individual action AddIndividual newAddIndividual = new AddIndividual(); newAddIndividual.setPatternRole(individualPatternRole); newAddIndividual.setIndividualName(new ViewPointDataBinding("parameters.uri")); for (PropertyEntry e : propertyEntries) { if (e.selectEntry) { if (e.property instanceof OntologyObjectProperty) { OntologyObject range = e.property.getRange(); if (range instanceof OntologyClass) { ObjectPropertyAssertion propertyAssertion = new ObjectPropertyAssertion(); propertyAssertion.setOntologyProperty(e.property); propertyAssertion.setObject(new ViewPointDataBinding("parameters." + e.property.getName())); newAddIndividual.addToObjectAssertions(propertyAssertion); } } else if (e.property instanceof OntologyDataProperty) { DataPropertyAssertion propertyAssertion = new DataPropertyAssertion(); propertyAssertion.setOntologyProperty(e.property); propertyAssertion.setValue(new ViewPointDataBinding("parameters." + e.property.getName())); newAddIndividual.addToDataAssertions(propertyAssertion); } } } newDropScheme.addToActions(newAddIndividual); } // Add shape/connector actions boolean mainPatternRole = true; for (GraphicalElementPatternRole graphicalElementPatternRole : newGraphicalElementPatternRoles.values()) { if (graphicalElementPatternRole instanceof ShapePatternRole) { // Add shape action AddShape newAddShape = new AddShape(); newAddShape.setPatternRole((ShapePatternRole) graphicalElementPatternRole); if (mainPatternRole) { if (isTopLevel) { newAddShape.setContainer(new ViewPointDataBinding(EditionScheme.TOP_LEVEL)); } else { newAddShape.setContainer(new ViewPointDataBinding(EditionScheme.TARGET + "." + containerEditionPattern.getPrimaryRepresentationRole().getPatternRoleName())); } } mainPatternRole = false; newDropScheme.addToActions(newAddShape); } } // Add new drop scheme newEditionPattern.addToEditionSchemes(newDropScheme); // Add inspector EditionPatternInspector inspector = newEditionPattern.getInspector(); inspector.setInspectorTitle(getEditionPatternName()); if (patternChoice == NewEditionPatternChoices.MAP_SINGLE_INDIVIDUAL) { for (PropertyEntry e : propertyEntries) { if (e.selectEntry) { if (e.property instanceof OntologyObjectProperty) { OntologyObject range = e.property.getRange(); if (range instanceof OntologyClass) { InspectorEntry newInspectorEntry = null; newInspectorEntry = new TextFieldInspectorEntry(); newInspectorEntry.setName(e.property.getName()); newInspectorEntry.setLabel(e.label); newInspectorEntry.setIsReadOnly(true); newInspectorEntry.setData(new ViewPointDataBinding(e.property.getName() + ".uriName")); inspector.addToEntries(newInspectorEntry); } } else if (e.property instanceof OntologyDataProperty) { InspectorEntry newInspectorEntry = null; switch (((OntologyDataProperty) e.property).getDataType()) { case Boolean: newInspectorEntry = new CheckboxInspectorEntry(); break; case Byte: case Integer: case Long: case Short: newInspectorEntry = new IntegerInspectorEntry(); break; case Double: case Float: newInspectorEntry = new FloatInspectorEntry(); break; case String: newInspectorEntry = new TextFieldInspectorEntry(); break; default: logger.warning("Not handled: " + ((OntologyDataProperty) e.property).getDataType()); } if (newInspectorEntry != null) { newInspectorEntry.setName(e.property.getName()); newInspectorEntry.setLabel(e.label); newInspectorEntry.setData(new ViewPointDataBinding(getIndividualPatternRoleName() + "." + e.property.getName())); inspector.addToEntries(newInspectorEntry); } } } } } // And add the newly created edition pattern getFocusedObject().getCalc().addToEditionPatterns(newEditionPattern); default: break; } default: logger.warning("Pattern not implemented"); } } else { logger.warning("Focused role is null !"); } }
protected void doAction(Object context) { logger.info("Declare shape in edition pattern"); if (isValid()) { switch (primaryChoice) { case CHOOSE_EXISTING_EDITION_PATTERN: if (getPatternRole() != null) { getPatternRole().updateGraphicalRepresentation(getFocusedObject().getGraphicalRepresentation()); } break; case CREATES_EDITION_PATTERN: switch (patternChoice) { case MAP_SINGLE_INDIVIDUAL: case BLANK_EDITION_PATTERN: // Create new edition pattern newEditionPattern = new EditionPattern(); newEditionPattern.setName(getEditionPatternName()); // Find best URI base candidate PropertyEntry mainPropertyDescriptor = selectBestEntryForURIBaseName(); // Create individual pattern role IndividualPatternRole individualPatternRole = new IndividualPatternRole(); if (patternChoice == NewEditionPatternChoices.MAP_SINGLE_INDIVIDUAL) { individualPatternRole.setPatternRoleName(getIndividualPatternRoleName()); individualPatternRole.setOntologicType(getConcept()); newEditionPattern.addToPatternRoles(individualPatternRole); newEditionPattern.setPrimaryConceptRole(individualPatternRole); } // Create graphical elements pattern role newGraphicalElementPatternRoles = new Hashtable<ExampleDrawingObjectEntry, GraphicalElementPatternRole>(); GraphicalElementPatternRole primaryRepresentationRole = null; for (ExampleDrawingObjectEntry entry : drawingObjectEntries) { if (entry.getSelectThis()) { if (entry.graphicalObject instanceof ExampleDrawingShape) { ShapePatternRole newShapePatternRole = new ShapePatternRole(); newShapePatternRole.setPatternRoleName(entry.patternRoleName); if (mainPropertyDescriptor != null && entry.isMainEntry()) { newShapePatternRole.setLabel(new ViewPointDataBinding(getIndividualPatternRoleName() + "." + mainPropertyDescriptor.property.getName())); } else { newShapePatternRole.setReadOnlyLabel(true); if (StringUtils.isNotEmpty(entry.graphicalObject.getName())) { newShapePatternRole .setLabel(new ViewPointDataBinding("\"" + entry.graphicalObject.getName() + "\"")); } } newShapePatternRole.setExampleLabel(((ShapeGraphicalRepresentation) entry.graphicalObject .getGraphicalRepresentation()).getText()); // We clone here the GR (fixed unfocusable GR bug) newShapePatternRole.setGraphicalRepresentation(((ShapeGraphicalRepresentation<?>) entry.graphicalObject .getGraphicalRepresentation()).clone()); // Forces GR to be displayed in view ((ShapeGraphicalRepresentation<?>) newShapePatternRole.getGraphicalRepresentation()) .setAllowToLeaveBounds(false); newEditionPattern.addToPatternRoles(newShapePatternRole); if (entry.getParentEntry() != null) { newShapePatternRole.setParentShapePatternRole((ShapePatternRole) newGraphicalElementPatternRoles .get(entry.getParentEntry())); } if (entry.isMainEntry()) { primaryRepresentationRole = newShapePatternRole; } newGraphicalElementPatternRoles.put(entry, newShapePatternRole); } } } newEditionPattern.setPrimaryRepresentationRole(primaryRepresentationRole); // Create other individual roles Vector<IndividualPatternRole> otherRoles = new Vector<IndividualPatternRole>(); if (patternChoice == NewEditionPatternChoices.MAP_SINGLE_INDIVIDUAL) { for (PropertyEntry e : propertyEntries) { if (e.selectEntry) { if (e.property instanceof OntologyObjectProperty) { OntologyObject range = e.property.getRange(); if (range instanceof OntologyClass) { IndividualPatternRole newPatternRole = new IndividualPatternRole(); newPatternRole.setPatternRoleName(e.property.getName()); newPatternRole.setOntologicType((OntologyClass) range); newEditionPattern.addToPatternRoles(newPatternRole); otherRoles.add(newPatternRole); } } } } } // Create new drop scheme DropScheme newDropScheme = new DropScheme(); newDropScheme.setName(getDropSchemeName()); newDropScheme.setTopTarget(isTopLevel); if (!isTopLevel) { newDropScheme.setTargetEditionPattern(containerEditionPattern); } // Parameters if (patternChoice == NewEditionPatternChoices.MAP_SINGLE_INDIVIDUAL) { Vector<PropertyEntry> candidates = new Vector<PropertyEntry>(); for (PropertyEntry e : propertyEntries) { if (e != null && e.selectEntry) { EditionSchemeParameter newParameter = null; if (e.property instanceof OntologyDataProperty) { switch (((OntologyDataProperty) e.property).getDataType()) { case Boolean: newParameter = new CheckboxParameter(); newParameter.setName(e.property.getName()); newParameter.setLabel(e.label); break; case Byte: case Integer: case Long: case Short: newParameter = new IntegerParameter(); newParameter.setName(e.property.getName()); newParameter.setLabel(e.label); break; case Double: case Float: newParameter = new FloatParameter(); newParameter.setName(e.property.getName()); newParameter.setLabel(e.label); break; case String: newParameter = new TextFieldParameter(); newParameter.setName(e.property.getName()); newParameter.setLabel(e.label); break; default: break; } } else if (e.property instanceof OntologyObjectProperty) { OntologyObject range = e.property.getRange(); if (range instanceof OntologyClass) { newParameter = new IndividualParameter(); newParameter.setName(e.property.getName()); newParameter.setLabel(e.label); ((IndividualParameter) newParameter).setConcept((OntologyClass) range); } } if (newParameter != null) { newDropScheme.addToParameters(newParameter); } } } URIParameter uriParameter = new URIParameter(); uriParameter.setName("uri"); uriParameter.setLabel("uri"); if (mainPropertyDescriptor != null) { uriParameter.setBaseURI(new ViewPointDataBinding(mainPropertyDescriptor.property.getName())); } newDropScheme.addToParameters(uriParameter); // Declare pattern role for (IndividualPatternRole r : otherRoles) { DeclarePatternRole action = new DeclarePatternRole(); action.setPatternRole(r); action.setObject(new ViewPointDataBinding("parameters." + r.getName())); newDropScheme.addToActions(action); } // Add individual action AddIndividual newAddIndividual = new AddIndividual(); newAddIndividual.setPatternRole(individualPatternRole); newAddIndividual.setIndividualName(new ViewPointDataBinding("parameters.uri")); for (PropertyEntry e : propertyEntries) { if (e.selectEntry) { if (e.property instanceof OntologyObjectProperty) { OntologyObject range = e.property.getRange(); if (range instanceof OntologyClass) { ObjectPropertyAssertion propertyAssertion = new ObjectPropertyAssertion(); propertyAssertion.setOntologyProperty(e.property); propertyAssertion.setObject(new ViewPointDataBinding("parameters." + e.property.getName())); newAddIndividual.addToObjectAssertions(propertyAssertion); } } else if (e.property instanceof OntologyDataProperty) { DataPropertyAssertion propertyAssertion = new DataPropertyAssertion(); propertyAssertion.setOntologyProperty(e.property); propertyAssertion.setValue(new ViewPointDataBinding("parameters." + e.property.getName())); newAddIndividual.addToDataAssertions(propertyAssertion); } } } newDropScheme.addToActions(newAddIndividual); } // Add shape/connector actions boolean mainPatternRole = true; for (GraphicalElementPatternRole graphicalElementPatternRole : newGraphicalElementPatternRoles.values()) { if (graphicalElementPatternRole instanceof ShapePatternRole) { // Add shape action AddShape newAddShape = new AddShape(); newAddShape.setPatternRole((ShapePatternRole) graphicalElementPatternRole); if (mainPatternRole) { if (isTopLevel) { newAddShape.setContainer(new ViewPointDataBinding(EditionScheme.TOP_LEVEL)); } else { newAddShape.setContainer(new ViewPointDataBinding(EditionScheme.TARGET + "." + containerEditionPattern.getPrimaryRepresentationRole().getPatternRoleName())); } } mainPatternRole = false; newDropScheme.addToActions(newAddShape); } } // Add new drop scheme newEditionPattern.addToEditionSchemes(newDropScheme); // Add inspector EditionPatternInspector inspector = newEditionPattern.getInspector(); inspector.setInspectorTitle(getEditionPatternName()); if (patternChoice == NewEditionPatternChoices.MAP_SINGLE_INDIVIDUAL) { for (PropertyEntry e : propertyEntries) { if (e.selectEntry) { if (e.property instanceof OntologyObjectProperty) { OntologyObject range = e.property.getRange(); if (range instanceof OntologyClass) { InspectorEntry newInspectorEntry = null; newInspectorEntry = new TextFieldInspectorEntry(); newInspectorEntry.setName(e.property.getName()); newInspectorEntry.setLabel(e.label); newInspectorEntry.setIsReadOnly(true); newInspectorEntry.setData(new ViewPointDataBinding(e.property.getName() + ".uriName")); inspector.addToEntries(newInspectorEntry); } } else if (e.property instanceof OntologyDataProperty) { InspectorEntry newInspectorEntry = null; switch (((OntologyDataProperty) e.property).getDataType()) { case Boolean: newInspectorEntry = new CheckboxInspectorEntry(); break; case Byte: case Integer: case Long: case Short: newInspectorEntry = new IntegerInspectorEntry(); break; case Double: case Float: newInspectorEntry = new FloatInspectorEntry(); break; case String: newInspectorEntry = new TextFieldInspectorEntry(); break; default: logger.warning("Not handled: " + ((OntologyDataProperty) e.property).getDataType()); } if (newInspectorEntry != null) { newInspectorEntry.setName(e.property.getName()); newInspectorEntry.setLabel(e.label); newInspectorEntry.setData(new ViewPointDataBinding(getIndividualPatternRoleName() + "." + e.property.getName())); inspector.addToEntries(newInspectorEntry); } } } } } // And add the newly created edition pattern getFocusedObject().getCalc().addToEditionPatterns(newEditionPattern); default: break; } default: logger.warning("Pattern not implemented"); } } else { logger.warning("Focused role is null !"); } }
diff --git a/sokoban/solvers/IDSPusher.java b/sokoban/solvers/IDSPusher.java index df2744b..decd9b5 100644 --- a/sokoban/solvers/IDSPusher.java +++ b/sokoban/solvers/IDSPusher.java @@ -1,368 +1,368 @@ package sokoban.solvers; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedList; import java.util.Queue; import sokoban.Board; import sokoban.Position; import sokoban.ReachableBox; import sokoban.Board.Direction; /** * A solver that pushes boxes around with iterative deepening and * a bloom filter to avoid duplicate states. */ public class IDSPusher implements Solver { private final int DEPTH_LIMIT = 1000; /** * The number of generated nodes */ public static int generatedNodes = 0; private static int remainingDepth; private static Board board; public int getIterationsCount() { return generatedNodes; } /** * Set of visited boards, including the player position */ private HashSet<Long> visitedBoards; /** * Boards that just lead to deadlocks or already visited boards. It * doesn't make sense to visit these in later iterations. */ private HashSet<Long> failedBoards; enum SearchStatus { /** * The search reached the maximum depth, and no solution was found, * so it's inconclusive (a solution could follow, but we don't know). */ Inconclusive, /** * This search resulted in a solution. */ Solution, /** * This search failed without reached the maximum depth, so there's * no point in trying it again with a greater search depth. */ Failed, }; /** * Contains information about a search, whether it is failed, reached a * solution or is inconclusive. */ final static class SearchInfo { final SearchStatus status; final LinkedList<Board.Direction> solution; static SearchInfo Inconclusive = new SearchInfo( SearchStatus.Inconclusive); static SearchInfo Failed = new SearchInfo(SearchStatus.Inconclusive); public SearchInfo(final SearchStatus status) { this.status = status; solution = null; } private SearchInfo() { status = SearchStatus.Solution; solution = new LinkedList<Board.Direction>(); } public static SearchInfo emptySolution() { return new SearchInfo(); } } /** * Recursive Depth-First algorithm * * @param maxDepth The maximum depth. * @return */ private SearchInfo dfs() { generatedNodes++; if (board.getRemainingBoxes() == 0) { // Found a solution return SearchInfo.emptySolution(); } if (remainingDepth <= 0) { return SearchInfo.Inconclusive; } if (!visitedBoards.add(board.getZobristKey())) { // Duplicate state return SearchInfo.Failed; } // True if at least one successor tree was inconclusive. boolean inconclusive = false; final Position source = new Position(board.getPlayerRow(), board.getPlayerCol()); remainingDepth--; // TODO optimize: no need for paths here final byte[][] cells = board.cells; for (final ReachableBox reachable : board.findReachableBoxSquares()) { for (final Direction dir : Board.Direction.values()) { final Position boxFrom = new Position(reachable.position, Board.moves[dir.ordinal()]); final Position boxTo = new Position(boxFrom, Board.moves[dir .ordinal()]); if (Board.is(cells[boxFrom.row][boxFrom.column], Board.BOX) && !Board .is(cells[boxTo.row][boxTo.column], Board.REJECT_BOX)) { // The move is possible // Move the player and push the box board.moveBox(boxFrom, boxTo); board.movePlayer(source, boxFrom); // Check if we got a freeze deadlock - if (freezeDeadlock(from, to)) { + if (freezeDeadlock(boxFrom, boxTo)) { return SearchInfo.Failed; } // Process successor states final SearchInfo result = dfs(); // Restore changes board.moveBox(boxTo, boxFrom); board.movePlayer(boxFrom, source); // Evaluate result switch (result.status) { case Solution: // Found a solution. Return it now! // Add the last movement first result.solution.addFirst(dir); // So we can put the rest in front of it result.solution.addAll(0, reachable.path); return result; case Inconclusive: // Make the parent inconclusive too inconclusive = true; continue; case Failed: // Mark this node as failed failedBoards.add(board.getZobristKey()); continue; } } } } remainingDepth++; if (inconclusive) { // Add all successors that failed to the failed set return SearchInfo.Inconclusive; } else { // All successors failed, so this node is failed failedBoards.add(board.getZobristKey()); return SearchInfo.Failed; } } public String solve(final Board startBoard) { failedBoards = new HashSet<Long>(); long startTime = System.currentTimeMillis(); final int lowerBound = lowerBound(startBoard); System.out.println("lowerBound(): " + lowerBound + " took " + (System.currentTimeMillis() - startTime) + " ms"); System.out.println("IDS depth limit (progress): "); for (int maxDepth = lowerBound; maxDepth < DEPTH_LIMIT; maxDepth += 3) { System.out.print(maxDepth + "."); visitedBoards = new HashSet<Long>(failedBoards); remainingDepth = maxDepth; board = (Board) startBoard.clone(); final SearchInfo result = dfs(); if (result.solution != null) { System.out.println(); return Board.solutionToString(result.solution); } else if (result.status == SearchStatus.Failed) { System.out.println("no solution!"); return null; } } System.out.println("maximum depth reached!"); return null; } private static int lowerBound(final Board board) { final ArrayList<Position> boxes = new ArrayList<Position>(); final Queue<Position> goals = new LinkedList<Position>(); for (int row = 0; row < board.height; row++) { for (int col = 0; col < board.width; col++) { if (Board.is(board.cells[row][col], Board.BOX)) { boxes.add(new Position(row, col)); } if (Board.is(board.cells[row][col], Board.GOAL)) { goals.add(new Position(row, col)); } } } int result = 0; while (!goals.isEmpty()) { final Position goal = goals.poll(); Position minBox = null; int min = Integer.MAX_VALUE; for (final Position box : boxes) { final int tmp = distance(goal, box); if (tmp < min) { min = tmp; minBox = box; } } boxes.remove(minBox); result += min; } return result; } /** * Approximate the distance between two positions * * The distance will be the absolute minimum and are guaranteed to be equal * to or greater then the real distance. * * TODO It might be smarter to implement a search that takes the actual * board into account. * * @param a One of the positions * @param b The other position * @return The approximate distance between the two. */ private static int distance(final Position a, final Position b) { return Math.abs(a.column - b.column) + Math.abs(a.row - b.row); } /** * Check if the move resulted in a freeze deadlock * (two boxes between each other next to a wall) * * This method assumes the move is valid. * * @param from The previous position * @param to The new position * @return True if there is a freeze deadlock */ private boolean freezeDeadlock(Position from, Position to) { boolean blocked = false; // Horisontal // # If there is a wall on the left or on the right side of the box then the box is blocked along this axis if (Board.is(board.cells[to.row][to.column+1], Board.WALL) || Board.is(board.cells[to.row][to.column-1], Board.WALL)) blocked = true; // # If there is a simple deadlock square on both sides (left and right) of the box the box is blocked along this axis else if (Board.is(board.cells[to.row][to.column+1], Board.BOX_TRAP) && Board.is(board.cells[to.row][to.column-1], Board.BOX_TRAP)) blocked = true; // # If there is a box one the left or right side then this box is blocked if the other box is blocked. else { // If there is a box on the right if (Board.is(board.cells[to.row][to.column+1], Board.BOX)) { // check if that box is blocked } if (Board.is(board.cells[to.row][to.column-1], Board.BOX)) { // check if that box is blocked } } // # If there is a wall on the left or on the right side of the box then the box is blocked along this axis if (Board.is(board.cells[to.row+1][to.column], Board.WALL) || Board.is(board.cells[to.row-1][to.column], Board.WALL)) if (blocked) return true; // # If there is a simple deadlock square on both sides (left and right) of the box the box is blocked along this axis else if (Board.is(board.cells[to.row+1][to.column], Board.BOX_TRAP) && Board.is(board.cells[to.row-1][to.column], Board.BOX_TRAP)) if (blocked) return true; // # If there is a box one the left or right side then this box is blocked if the other box is blocked. else { // If there is a box on the right if (Board.is(board.cells[to.row+1][to.column], Board.BOX)) { // check if that box is blocked } if (Board.is(board.cells[to.row-1][to.column], Board.BOX)) { // check if that box is blocked } } return false; // byte WALL_OR_BOX = Board.BOX | Board.WALL; // // if (Board.is(board.cells[to.row+1][to.column], Board.BOX) && !(from.row == to.row+1 && from.column == to.column)) { // // If the box is above // if (Board.is(board.cells[to.row][to.column+1], WALL_OR_BOX) && Board.is(board.cells[to.row+1][to.column+1], WALL_OR_BOX)) { // // If there is a wall to the right of them // return true; // } // if (Board.is(board.cells[to.row][to.column-1], WALL_OR_BOX) && Board.is(board.cells[to.row+1][to.column-1], WALL_OR_BOX)) { // // If there is a wall to the left of them // return true; // } // } // if (Board.is(board.cells[to.row-1][to.column], Board.BOX) && !(from.row == to.row-11 && from.column == to.column)) { // // If the box is below // if (Board.is(board.cells[to.row][to.column+1], WALL_OR_BOX) && Board.is(board.cells[to.row-1][to.column+1], WALL_OR_BOX)) { // // If there is a wall to the right of them // return true; // } // if (Board.is(board.cells[to.row][to.column-1], WALL_OR_BOX) && Board.is(board.cells[to.row-1][to.column-1], WALL_OR_BOX)) { // // If there is a wall to the left of them // return true; // } // } // if (Board.is(board.cells[to.row][to.column+1], Board.BOX)) { // // If the box is to the right // if (Board.is(board.cells[to.row+1][to.column], WALL_OR_BOX) && Board.is(board.cells[to.row+1][to.column+1], WALL_OR_BOX)) { // // If there is a wall above // return true; // } // if (Board.is(board.cells[to.row-1][to.column], WALL_OR_BOX) && Board.is(board.cells[to.row-1][to.column+1], WALL_OR_BOX)) { // // If there is a wall belove // return true; // } // } // if (Board.is(board.cells[to.row][to.column-1], Board.BOX)) { // // If the box is to the left // if (Board.is(board.cells[to.row+1][to.column], WALL_OR_BOX) && Board.is(board.cells[to.row+1][to.column-1], WALL_OR_BOX)) { // // If there is a wall above // return true; // } // if (Board.is(board.cells[to.row-1][to.column], WALL_OR_BOX) && Board.is(board.cells[to.row-1][to.column-1], WALL_OR_BOX)) { // // If there is a wall to below // return true; // } // } // // return false; } }
true
true
private SearchInfo dfs() { generatedNodes++; if (board.getRemainingBoxes() == 0) { // Found a solution return SearchInfo.emptySolution(); } if (remainingDepth <= 0) { return SearchInfo.Inconclusive; } if (!visitedBoards.add(board.getZobristKey())) { // Duplicate state return SearchInfo.Failed; } // True if at least one successor tree was inconclusive. boolean inconclusive = false; final Position source = new Position(board.getPlayerRow(), board.getPlayerCol()); remainingDepth--; // TODO optimize: no need for paths here final byte[][] cells = board.cells; for (final ReachableBox reachable : board.findReachableBoxSquares()) { for (final Direction dir : Board.Direction.values()) { final Position boxFrom = new Position(reachable.position, Board.moves[dir.ordinal()]); final Position boxTo = new Position(boxFrom, Board.moves[dir .ordinal()]); if (Board.is(cells[boxFrom.row][boxFrom.column], Board.BOX) && !Board .is(cells[boxTo.row][boxTo.column], Board.REJECT_BOX)) { // The move is possible // Move the player and push the box board.moveBox(boxFrom, boxTo); board.movePlayer(source, boxFrom); // Check if we got a freeze deadlock if (freezeDeadlock(from, to)) { return SearchInfo.Failed; } // Process successor states final SearchInfo result = dfs(); // Restore changes board.moveBox(boxTo, boxFrom); board.movePlayer(boxFrom, source); // Evaluate result switch (result.status) { case Solution: // Found a solution. Return it now! // Add the last movement first result.solution.addFirst(dir); // So we can put the rest in front of it result.solution.addAll(0, reachable.path); return result; case Inconclusive: // Make the parent inconclusive too inconclusive = true; continue; case Failed: // Mark this node as failed failedBoards.add(board.getZobristKey()); continue; } } } } remainingDepth++; if (inconclusive) { // Add all successors that failed to the failed set return SearchInfo.Inconclusive; } else { // All successors failed, so this node is failed failedBoards.add(board.getZobristKey()); return SearchInfo.Failed; } }
private SearchInfo dfs() { generatedNodes++; if (board.getRemainingBoxes() == 0) { // Found a solution return SearchInfo.emptySolution(); } if (remainingDepth <= 0) { return SearchInfo.Inconclusive; } if (!visitedBoards.add(board.getZobristKey())) { // Duplicate state return SearchInfo.Failed; } // True if at least one successor tree was inconclusive. boolean inconclusive = false; final Position source = new Position(board.getPlayerRow(), board.getPlayerCol()); remainingDepth--; // TODO optimize: no need for paths here final byte[][] cells = board.cells; for (final ReachableBox reachable : board.findReachableBoxSquares()) { for (final Direction dir : Board.Direction.values()) { final Position boxFrom = new Position(reachable.position, Board.moves[dir.ordinal()]); final Position boxTo = new Position(boxFrom, Board.moves[dir .ordinal()]); if (Board.is(cells[boxFrom.row][boxFrom.column], Board.BOX) && !Board .is(cells[boxTo.row][boxTo.column], Board.REJECT_BOX)) { // The move is possible // Move the player and push the box board.moveBox(boxFrom, boxTo); board.movePlayer(source, boxFrom); // Check if we got a freeze deadlock if (freezeDeadlock(boxFrom, boxTo)) { return SearchInfo.Failed; } // Process successor states final SearchInfo result = dfs(); // Restore changes board.moveBox(boxTo, boxFrom); board.movePlayer(boxFrom, source); // Evaluate result switch (result.status) { case Solution: // Found a solution. Return it now! // Add the last movement first result.solution.addFirst(dir); // So we can put the rest in front of it result.solution.addAll(0, reachable.path); return result; case Inconclusive: // Make the parent inconclusive too inconclusive = true; continue; case Failed: // Mark this node as failed failedBoards.add(board.getZobristKey()); continue; } } } } remainingDepth++; if (inconclusive) { // Add all successors that failed to the failed set return SearchInfo.Inconclusive; } else { // All successors failed, so this node is failed failedBoards.add(board.getZobristKey()); return SearchInfo.Failed; } }
diff --git a/src/com/android/settings/carbon/Navbar.java b/src/com/android/settings/carbon/Navbar.java index 34ecb3eaa..0363eb6c9 100644 --- a/src/com/android/settings/carbon/Navbar.java +++ b/src/com/android/settings/carbon/Navbar.java @@ -1,1031 +1,1031 @@ package com.android.settings.carbon; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.net.URISyntaxException; import java.util.ArrayList; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.FragmentTransaction; import android.app.ListFragment; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.PorterDuff; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.StateListDrawable; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.PowerManager; import android.os.RemoteException; import android.os.ServiceManager; import android.preference.CheckBoxPreference; import android.preference.ListPreference; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.Preference.OnPreferenceChangeListener; import android.preference.PreferenceGroup; import android.preference.PreferenceScreen; import android.provider.MediaStore; import android.provider.Settings; import android.text.TextUtils; import android.util.Log; import android.util.StateSet; import android.util.TypedValue; import android.view.IWindowManager; import android.view.HapticFeedbackConstants; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.android.internal.util.carbon.AwesomeConstants; import com.android.internal.util.carbon.AwesomeConstants.AwesomeConstant; import com.android.internal.util.carbon.BackgroundAlphaColorDrawable; import com.android.internal.util.carbon.NavBarHelpers; import com.android.settings.SettingsPreferenceFragment; import com.android.settings.R; import com.android.settings.util.Helpers; import com.android.settings.SettingsActivity; import com.android.settings.util.ShortcutPickerHelper; import com.android.settings.widgets.SeekBarPreference; import com.android.settings.carbon.NavRingTargets; import net.margaritov.preference.colorpicker.ColorPickerPreference; public class Navbar extends SettingsPreferenceFragment implements OnPreferenceChangeListener, ShortcutPickerHelper.OnPickListener { // move these later private static final String PREF_MENU_UNLOCK = "pref_menu_display"; private static final String PREF_NAVBAR_MENU_DISPLAY = "navbar_menu_display"; private static final String NAVIGATION_BAR_COLOR = "nav_bar_color"; private static final String PREF_NAV_COLOR = "nav_button_color"; private static final String NAVIGATION_BAR_ALLCOLOR = "navigation_bar_allcolor"; private static final String PREF_NAV_GLOW_COLOR = "nav_button_glow_color"; private static final String PREF_GLOW_TIMES = "glow_times"; private static final String PREF_NAVBAR_QTY = "navbar_qty"; private static final String ENABLE_NAVIGATION_BAR = "enable_nav_bar"; private static final String NAVIGATION_BAR_HEIGHT = "navigation_bar_height"; private static final String NAVIGATION_BAR_HEIGHT_LANDSCAPE = "navigation_bar_height_landscape"; private static final String NAVIGATION_BAR_WIDTH = "navigation_bar_width"; private static final String NAVIGATION_BAR_WIDGETS = "navigation_bar_widgets"; private static final String KEY_HARDWARE_KEYS = "hardware_keys"; private static final String PREF_MENU_ARROWS = "navigation_bar_menu_arrow_keys"; private static final String NAVBAR_HIDE_ENABLE = "navbar_hide_enable"; private static final String NAVBAR_HIDE_TIMEOUT = "navbar_hide_timeout"; private static final String DRAG_HANDLE_OPACITY = "drag_handle_opacity"; private static final String DRAG_HANDLE_WIDTH = "drag_handle_width"; public static final int REQUEST_PICK_CUSTOM_ICON = 200; public static final int REQUEST_PICK_LANDSCAPE_ICON = 201; private static final int DIALOG_NAVBAR_ENABLE = 203; public static final String PREFS_NAV_BAR = "navbar"; // move these later ColorPickerPreference mNavigationColor; ColorPickerPreference mNavigationBarColor; CheckBoxPreference mColorizeAllIcons; ColorPickerPreference mNavigationBarGlowColor; ListPreference mGlowTimes; ListPreference menuDisplayLocation; ListPreference mNavBarMenuDisplay; ListPreference mNavBarButtonQty; CheckBoxPreference mEnableNavigationBar; ListPreference mNavigationBarHeight; ListPreference mNavigationBarHeightLandscape; ListPreference mNavigationBarWidth; SeekBarPreference mButtonAlpha; Preference mWidthHelp; SeekBarPreference mWidthPort; SeekBarPreference mWidthLand; CheckBoxPreference mMenuArrowKeysCheckBox; Preference mConfigureWidgets; CheckBoxPreference mNavBarHideEnable; ListPreference mNavBarHideTimeout; SeekBarPreference mDragHandleOpacity; SeekBarPreference mDragHandleWidth; // NavBar Buttons Stuff Resources mResources; private ImageView mLeftMenu, mRightMenu; private ImageButton mResetButton, mAddButton,mSaveButton; private LinearLayout mNavBarContainer; private LinearLayout mNavButtonsContainer; private int mNumberofButtons = 0; private PackageManager mPackMan; ArrayList<NavBarButton> mButtons = new ArrayList<NavBarButton>(); ArrayList<ImageButton> mButtonViews = new ArrayList<ImageButton>(); String[] mActions; String[] mActionCodes; private int mPendingButton = -1; public final static int SHOW_LEFT_MENU = 1; public final static int SHOW_RIGHT_MENU = 0; public final static int SHOW_BOTH_MENU = 2; public final static int SHOW_DONT = 4; public static final float STOCK_ALPHA = .7f; private ShortcutPickerHelper mPicker; private static final String TAG = "Navbar"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle(R.string.title_navbar); // Load the preferences from an XML resource addPreferencesFromResource(R.xml.navbar_settings); PreferenceScreen prefs = getPreferenceScreen(); mPicker = new ShortcutPickerHelper(this, this); mPackMan = getPackageManager(); mResources = mContext.getResources(); // Get NavBar Actions mActionCodes = NavBarHelpers.getNavBarActions(); mActions = new String[mActionCodes.length]; int actionqty = mActions.length; for (int i = 0; i < actionqty; i++) { mActions[i] = AwesomeConstants.getProperName(mContext, mActionCodes[i]); } menuDisplayLocation = (ListPreference) findPreference(PREF_MENU_UNLOCK); menuDisplayLocation.setOnPreferenceChangeListener(this); menuDisplayLocation.setValue(Settings.System.getInt(mContentRes, Settings.System.MENU_LOCATION,0) + ""); mNavBarMenuDisplay = (ListPreference) findPreference(PREF_NAVBAR_MENU_DISPLAY); mNavBarMenuDisplay.setOnPreferenceChangeListener(this); mNavBarMenuDisplay.setValue(Settings.System.getInt(mContentRes, Settings.System.MENU_VISIBILITY,0) + ""); mNavBarHideEnable = (CheckBoxPreference) findPreference(NAVBAR_HIDE_ENABLE); mNavBarHideEnable.setChecked(Settings.System.getBoolean(mContentRes, Settings.System.NAV_HIDE_ENABLE, false)); final int defaultDragOpacity = Settings.System.getInt(mContentRes, Settings.System.DRAG_HANDLE_OPACITY,50); mDragHandleOpacity = (SeekBarPreference) findPreference(DRAG_HANDLE_OPACITY); mDragHandleOpacity.setInitValue((int) (defaultDragOpacity)); mDragHandleOpacity.setOnPreferenceChangeListener(this); final int defaultDragWidth = Settings.System.getInt(mContentRes, Settings.System.DRAG_HANDLE_WEIGHT, 5); mDragHandleWidth = (SeekBarPreference) findPreference(DRAG_HANDLE_WIDTH); mDragHandleWidth.setInitValue((int) (defaultDragWidth)); mDragHandleWidth.setOnPreferenceChangeListener(this); mNavBarHideTimeout = (ListPreference) findPreference(NAVBAR_HIDE_TIMEOUT); mNavBarHideTimeout.setOnPreferenceChangeListener(this); mNavBarHideTimeout.setValue(Settings.System.getInt(mContentRes, Settings.System.NAV_HIDE_TIMEOUT, 3000) + ""); boolean hasNavBarByDefault = mContext.getResources().getBoolean( com.android.internal.R.bool.config_showNavigationBar); mEnableNavigationBar = (CheckBoxPreference) findPreference(ENABLE_NAVIGATION_BAR); mEnableNavigationBar.setChecked(Settings.System.getBoolean(mContentRes, Settings.System.NAVIGATION_BAR_SHOW, hasNavBarByDefault)); mNavigationColor = (ColorPickerPreference) findPreference(NAVIGATION_BAR_COLOR); mNavigationColor.setOnPreferenceChangeListener(this); mNavigationBarColor = (ColorPickerPreference) findPreference(PREF_NAV_COLOR); mNavigationBarColor.setOnPreferenceChangeListener(this); mColorizeAllIcons = (CheckBoxPreference) findPreference("navigation_bar_allcolor"); mColorizeAllIcons.setChecked(Settings.System.getBoolean(mContentRes, Settings.System.NAVIGATION_BAR_ALLCOLOR, false)); mNavigationBarGlowColor = (ColorPickerPreference) findPreference(PREF_NAV_GLOW_COLOR); mNavigationBarGlowColor.setOnPreferenceChangeListener(this); mGlowTimes = (ListPreference) findPreference(PREF_GLOW_TIMES); mGlowTimes.setOnPreferenceChangeListener(this); final float defaultButtonAlpha = Settings.System.getFloat(mContentRes, Settings.System.NAVIGATION_BAR_BUTTON_ALPHA,0.6f); mButtonAlpha = (SeekBarPreference) findPreference("button_transparency"); mButtonAlpha.setInitValue((int) (defaultButtonAlpha * 100)); mButtonAlpha.setOnPreferenceChangeListener(this); mWidthHelp = (Preference) findPreference("width_help"); float defaultPort = Settings.System.getFloat(mContentRes, Settings.System.NAVIGATION_BAR_WIDTH_PORT,0f); mWidthPort = (SeekBarPreference) findPreference("width_port"); mWidthPort.setInitValue((int) (defaultPort * 2.5f)); mWidthPort.setOnPreferenceChangeListener(this); float defaultLand = Settings.System.getFloat(mContentRes, Settings.System.NAVIGATION_BAR_WIDTH_LAND,0f); mWidthLand = (SeekBarPreference) findPreference("width_land"); mWidthLand.setInitValue((int) (defaultLand * 2.5f)); mWidthLand.setOnPreferenceChangeListener(this); mNavigationBarHeight = (ListPreference) findPreference("navigation_bar_height"); mNavigationBarHeight.setOnPreferenceChangeListener(this); mNavigationBarHeightLandscape = (ListPreference) findPreference("navigation_bar_height_landscape"); mNavigationBarHeightLandscape.setOnPreferenceChangeListener(this); mNavigationBarWidth = (ListPreference) findPreference("navigation_bar_width"); mNavigationBarWidth.setOnPreferenceChangeListener(this); mConfigureWidgets = findPreference(NAVIGATION_BAR_WIDGETS); mMenuArrowKeysCheckBox = (CheckBoxPreference) findPreference(PREF_MENU_ARROWS); mMenuArrowKeysCheckBox.setChecked(Settings.System.getBoolean(mContentRes, Settings.System.NAVIGATION_BAR_MENU_ARROW_KEYS, true)); // don't allow devices that must use a navigation bar to disable it if (hasNavBarByDefault) { prefs.removePreference(mEnableNavigationBar); } PreferenceGroup pg = (PreferenceGroup) prefs.findPreference("advanced_cat"); if (isTablet(mContext)) { mNavigationBarHeight.setTitle(R.string.system_bar_height_title); mNavigationBarHeight.setSummary(R.string.system_bar_height_summary); - mNavigationBarWidth.setTitle(R.string.system_bar_height_landscape_title); - mNavigationBarWidth.setSummary(R.string.system_bar_height_landscape_summary); - pg.removePreference(mNavigationBarHeightLandscape); + mNavigationBarHeightLandscape.setTitle(R.string.system_bar_height_landscape_title); + mNavigationBarHeightLandscape.setSummary(R.string.system_bar_height_landscape_summary); + pg.removePreference(mNavigationBarWidth); mNavBarHideEnable.setEnabled(false); mDragHandleOpacity.setEnabled(false); mDragHandleWidth.setEnabled(false); mNavBarHideTimeout.setEnabled(false); } else { // Phones&Phablets don't have SystemBar pg.removePreference(mWidthPort); pg.removePreference(mWidthLand); pg.removePreference(mWidthHelp); } if (Integer.parseInt(menuDisplayLocation.getValue()) == 4) { mNavBarMenuDisplay.setEnabled(false); } // Only show the hardware keys config on a device that does not have a navbar IWindowManager windowManager = IWindowManager.Stub.asInterface( ServiceManager.getService(Context.WINDOW_SERVICE)); if (hasNavBarByDefault) { // Let's assume they don't have hardware keys getPreferenceScreen().removePreference(findPreference(KEY_HARDWARE_KEYS)); } refreshSettings(); setHasOptionsMenu(true); updateGlowTimesSummary(); } @Override public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedinstanceState){ View ll = inflater.inflate(R.layout.navbar, container, false); mResetButton = (ImageButton) ll.findViewById(R.id.reset_button); mResetButton.setOnClickListener(mCommandButtons); mAddButton = (ImageButton) ll.findViewById(R.id.add_button); mAddButton.setOnClickListener(mCommandButtons); mSaveButton = (ImageButton) ll.findViewById(R.id.save_button); mSaveButton.setOnClickListener(mCommandButtons); mLeftMenu = (ImageView) ll.findViewById(R.id.left_menu); mNavBarContainer = (LinearLayout) ll.findViewById(R.id.navbar_container); mNavButtonsContainer = (LinearLayout) ll.findViewById(R.id.button_container); mButtonViews.clear(); for (int i = 0; i < mNavButtonsContainer.getChildCount(); i++) { ImageButton ib = (ImageButton) mNavButtonsContainer.getChildAt(i); mButtonViews.add(ib); } mRightMenu = (ImageView) ll.findViewById(R.id.right_menu); if (mButtons.size() == 0){ loadButtons(); } refreshButtons(); return ll; } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.nav_bar, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.reset: Settings.System.putInt(mContentRes, Settings.System.NAVIGATION_BAR_COLOR, -1); Settings.System.putInt(mContentRes, Settings.System.NAVIGATION_BAR_TINT, -1); Settings.System.putInt(mContentRes, Settings.System.NAVIGATION_BAR_GLOW_TINT, -1); Settings.System.putInt(mContentRes, Settings.System.NAVIGATION_BAR_BUTTONS_QTY, 3); Settings.System.putString(mContentRes, Settings.System.NAVIGATION_CUSTOM_ACTIVITIES[0], "**back**"); Settings.System.putString(mContentRes, Settings.System.NAVIGATION_CUSTOM_ACTIVITIES[1], "**home**"); Settings.System.putString(mContentRes, Settings.System.NAVIGATION_CUSTOM_ACTIVITIES[2], "**recents**"); Settings.System.putString(mContentRes, Settings.System.NAVIGATION_LONGPRESS_ACTIVITIES[0], "**null**"); Settings.System.putString(mContentRes, Settings.System.NAVIGATION_LONGPRESS_ACTIVITIES[1], "**null**"); Settings.System.putString(mContentRes, Settings.System.NAVIGATION_LONGPRESS_ACTIVITIES[2], "**null**"); Settings.System.putString(mContentRes, Settings.System.NAVIGATION_CUSTOM_APP_ICONS[0], ""); Settings.System.putString(mContentRes, Settings.System.NAVIGATION_CUSTOM_APP_ICONS[1], ""); Settings.System.putString(mContentRes, Settings.System.NAVIGATION_CUSTOM_APP_ICONS[2], ""); refreshSettings(); return true; default: return super.onContextItemSelected(item); } } @Override public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) { if (preference == mEnableNavigationBar) { Settings.System.putInt(mContentRes, Settings.System.NAVIGATION_BAR_SHOW, ((CheckBoxPreference) preference).isChecked() ? 1 : 0); Helpers.restartSystemUI(); return true; } else if (preference == mColorizeAllIcons) { Settings.System.putBoolean(mContentRes, Settings.System.NAVIGATION_BAR_ALLCOLOR, ((CheckBoxPreference) preference).isChecked() ? true : false); return true; } else if (preference == mNavBarHideEnable) { Settings.System.putBoolean(mContentRes, Settings.System.NAV_HIDE_ENABLE, ((CheckBoxPreference) preference).isChecked()); mDragHandleOpacity.setInitValue(Settings.System.getInt(getActivity().getContentResolver(), Settings.System.DRAG_HANDLE_OPACITY,50)); mDragHandleWidth.setInitValue(Settings.System.getInt(getActivity().getContentResolver(), Settings.System.DRAG_HANDLE_WEIGHT,5)); mNavBarHideTimeout.setValue(Settings.System.getInt(getActivity().getContentResolver(), Settings.System.NAV_HIDE_TIMEOUT, 3000) + ""); refreshSettings(); return true; } else if (preference == mConfigureWidgets) { FragmentTransaction ft = getFragmentManager().beginTransaction(); WidgetConfigurationFragment fragment = new WidgetConfigurationFragment(); ft.addToBackStack("config_widgets"); ft.replace(this.getId(), fragment); ft.commit(); return true; } else if (preference == mMenuArrowKeysCheckBox) { Settings.System.putBoolean(mContentRes, Settings.System.NAVIGATION_BAR_MENU_ARROW_KEYS, ((CheckBoxPreference) preference).isChecked()); return true; } return super.onPreferenceTreeClick(preferenceScreen, preference); } @Override public boolean onPreferenceChange(Preference preference, Object newValue) { if (preference == menuDisplayLocation) { int val = Integer.parseInt((String) newValue); Settings.System.putInt(mContentRes, Settings.System.MENU_LOCATION, val); refreshSettings(); mNavBarMenuDisplay.setEnabled(val < 4 ? true : false); return true; } else if (preference == mNavBarMenuDisplay) { Settings.System.putInt(mContentRes, Settings.System.MENU_VISIBILITY, Integer.parseInt((String) newValue)); return true; } else if (preference == mNavigationBarWidth) { String newVal = (String) newValue; int dp = Integer.parseInt(newVal); int width = mapChosenDpToPixels(dp); Settings.System.putInt(mContentRes, Settings.System.NAVIGATION_BAR_WIDTH, width); return true; } else if (preference == mNavigationBarHeight) { String newVal = (String) newValue; int dp = Integer.parseInt(newVal); int height = mapChosenDpToPixels(dp); Settings.System.putInt(mContentRes, Settings.System.NAVIGATION_BAR_HEIGHT, height); return true; } else if (preference == mNavBarHideTimeout) { int val = Integer.parseInt((String) newValue); Settings.System.putInt(mContentRes, Settings.System.NAV_HIDE_TIMEOUT, val); return true; } else if (preference == mNavigationBarHeightLandscape) { String newVal = (String) newValue; int dp = Integer.parseInt(newVal); int height = mapChosenDpToPixels(dp); Settings.System.putInt(mContentRes, Settings.System.NAVIGATION_BAR_HEIGHT_LANDSCAPE, height); return true; } else if (preference == mNavigationColor) { String hex = ColorPickerPreference.convertToARGB( Integer.valueOf(String.valueOf(newValue))); preference.setSummary(hex); int intHex = ColorPickerPreference.convertToColorInt(hex) & 0x00FFFFFF; Settings.System.putInt(mContentRes, Settings.System.NAVIGATION_BAR_COLOR, intHex); refreshSettings(); return true; } else if (preference == mNavigationBarColor) { String hex = ColorPickerPreference.convertToARGB( Integer.valueOf(String.valueOf(newValue))); preference.setSummary(hex); int intHex = ColorPickerPreference.convertToColorInt(hex); Settings.System.putInt(mContentRes, Settings.System.NAVIGATION_BAR_TINT, intHex); refreshSettings(); return true; } else if (preference == mNavigationBarGlowColor) { String hex = ColorPickerPreference.convertToARGB( Integer.valueOf(String.valueOf(newValue))); preference.setSummary(hex); int intHex = ColorPickerPreference.convertToColorInt(hex); Settings.System.putInt(mContentRes, Settings.System.NAVIGATION_BAR_GLOW_TINT, intHex); refreshSettings(); return true; } else if (preference == mGlowTimes) { // format is (on|off) both in MS String value = (String) newValue; String[] breakIndex = value.split("\\|"); int onTime = Integer.valueOf(breakIndex[0]); int offTime = Integer.valueOf(breakIndex[1]); Settings.System.putInt(mContentRes, Settings.System.NAVIGATION_BAR_GLOW_DURATION[0], offTime); Settings.System.putInt(mContentRes, Settings.System.NAVIGATION_BAR_GLOW_DURATION[1], onTime); updateGlowTimesSummary(); return true; } else if (preference == mButtonAlpha) { float val = Float.parseFloat((String) newValue); Settings.System.putFloat(mContentRes, Settings.System.NAVIGATION_BAR_BUTTON_ALPHA, val * 0.01f); refreshSettings(); return true; } else if (preference == mDragHandleOpacity) { String newVal = (String) newValue; int op = Integer.parseInt(newVal); Settings.System.putInt(mContentRes, Settings.System.DRAG_HANDLE_OPACITY, op); return true; } else if (preference == mDragHandleWidth) { String newVal = (String) newValue; int dp = Integer.parseInt(newVal); //int height = mapChosenDpToPixels(dp); Settings.System.putInt(mContentRes, Settings.System.DRAG_HANDLE_WEIGHT, dp); return true; } else if (preference == mWidthPort) { float val = Float.parseFloat((String) newValue); Settings.System.putFloat(mContentRes, Settings.System.NAVIGATION_BAR_WIDTH_PORT, val * 0.4f); return true; } else if (preference == mWidthLand) { float val = Float.parseFloat((String) newValue); Settings.System.putFloat(mContentRes, Settings.System.NAVIGATION_BAR_WIDTH_LAND, val * 0.4f); return true; } return false; } @Override public Dialog onCreateDialog(int dialogId) { return null; } private void updateGlowTimesSummary() { int resId; String combinedTime = Settings.System.getString(mContentRes, Settings.System.NAVIGATION_BAR_GLOW_DURATION[1]) + "|" + Settings.System.getString(mContentRes, Settings.System.NAVIGATION_BAR_GLOW_DURATION[0]); String[] glowArray = getResources().getStringArray(R.array.glow_times_values); if (glowArray[0].equals(combinedTime)) { resId = R.string.glow_times_off; mGlowTimes.setValueIndex(0); } else if (glowArray[1].equals(combinedTime)) { resId = R.string.glow_times_superquick; mGlowTimes.setValueIndex(1); } else if (glowArray[2].equals(combinedTime)) { resId = R.string.glow_times_quick; mGlowTimes.setValueIndex(2); } else { resId = R.string.glow_times_normal; mGlowTimes.setValueIndex(3); } mGlowTimes.setSummary(getResources().getString(resId)); } public int mapChosenDpToPixels(int dp) { switch (dp) { case 48: return getResources().getDimensionPixelSize(R.dimen.navigation_bar_48); case 44: return getResources().getDimensionPixelSize(R.dimen.navigation_bar_44); case 42: return getResources().getDimensionPixelSize(R.dimen.navigation_bar_42); case 40: return getResources().getDimensionPixelSize(R.dimen.navigation_bar_40); case 36: return getResources().getDimensionPixelSize(R.dimen.navigation_bar_36); case 30: return getResources().getDimensionPixelSize(R.dimen.navigation_bar_30); case 24: return getResources().getDimensionPixelSize(R.dimen.navigation_bar_24); } return -1; } public void refreshSettings() { refreshButtons(); if (!isTablet(mContext)) { mDragHandleOpacity.setEnabled(mNavBarHideEnable.isChecked()); mDragHandleWidth.setEnabled(mNavBarHideEnable.isChecked()); mNavBarHideTimeout.setEnabled(mNavBarHideEnable.isChecked()); } } private Uri getTempFileUri() { return Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "tmp_icon_" + mPendingButton + ".png")); } private String getIconFileName(int index) { return "navbar_icon_" + index + ".png"; } @Override public void onResume() { super.onResume(); } private View.OnClickListener mNavBarClickListener = new View.OnClickListener() { @Override public void onClick(View v) { mPendingButton = mButtonViews.indexOf(v); if (mPendingButton > -1 && mPendingButton < mNumberofButtons) { createDialog(mButtons.get(mPendingButton)); } } }; private void loadButtons(){ mNumberofButtons = Settings.System.getInt(mContentRes, Settings.System.NAVIGATION_BAR_BUTTONS_QTY, 3); mButtons.clear(); for (int i = 0; i < mNumberofButtons; i++) { String click = Settings.System.getString(mContentRes, Settings.System.NAVIGATION_CUSTOM_ACTIVITIES[i]); String longclick = Settings.System.getString(mContentRes, Settings.System.NAVIGATION_LONGPRESS_ACTIVITIES[i]); String iconuri = Settings.System.getString(mContentRes, Settings.System.NAVIGATION_CUSTOM_APP_ICONS[i]); mButtons.add(new NavBarButton(click, longclick, iconuri)); } } public void refreshButtons() { if (mNumberofButtons == 0) { return; } int navBarColor = Settings.System.getInt(mContentRes, Settings.System.NAVIGATION_BAR_COLOR, -1); int navButtonColor = Settings.System.getInt(mContentRes, Settings.System.NAVIGATION_BAR_TINT, -1); float navButtonAlpha = Settings.System.getFloat(mContentRes, Settings.System.NAVIGATION_BAR_BUTTON_ALPHA, STOCK_ALPHA); int glowColor = Settings.System.getInt(mContentRes, Settings.System.NAVIGATION_BAR_GLOW_TINT, 0); float BarAlpha = 1.0f; String alphas[]; String settingValue = Settings.System.getString(mContentRes, Settings.System.NAVIGATION_BAR_ALPHA_CONFIG); if (!TextUtils.isEmpty(settingValue)) { alphas = settingValue.split(";"); BarAlpha = Float.parseFloat(alphas[0]) / 255; } int a = Math.round(BarAlpha * 255); Drawable mBackground = AwesomeConstants.getSystemUIDrawable(mContext, "com.android.systemui:drawable/nav_bar_bg"); if (mBackground instanceof ColorDrawable) { BackgroundAlphaColorDrawable bacd = new BackgroundAlphaColorDrawable( navBarColor > 0 ? navBarColor : ((ColorDrawable) mBackground).getColor()); bacd.setAlpha(a); mNavBarContainer.setBackground(bacd); } else { mBackground.setAlpha(a); mNavBarContainer.setBackground(mBackground); } for (int i = 0; i < mNumberofButtons; i++) { ImageButton ib = mButtonViews.get(i); Drawable d = mButtons.get(i).getIcon(); if (navButtonColor != -1) { d.setColorFilter(navButtonColor, PorterDuff.Mode.SRC_ATOP); } ib.setImageDrawable(d); ib.setOnClickListener(mNavBarClickListener); ib.setVisibility(View.VISIBLE); ib.setAlpha(navButtonAlpha); StateListDrawable sld = new StateListDrawable(); sld.addState(new int[] { android.R.attr.state_pressed }, new ColorDrawable(glowColor)); sld.addState(StateSet.WILD_CARD, mNavBarContainer.getBackground()); ib.setBackground(sld); } for (int i = mNumberofButtons; i < mButtonViews.size(); i++){ ImageButton ib = mButtonViews.get(i); ib.setVisibility(View.GONE); } int menuloc = Settings.System.getInt(mContentRes, Settings.System.MENU_LOCATION, 0); switch (menuloc) { case SHOW_BOTH_MENU: mLeftMenu.setVisibility(View.VISIBLE); mRightMenu.setVisibility(View.VISIBLE); break; case SHOW_LEFT_MENU: mLeftMenu.setVisibility(View.VISIBLE); mRightMenu.setVisibility(View.INVISIBLE); break; case SHOW_RIGHT_MENU: mLeftMenu.setVisibility(View.INVISIBLE); mRightMenu.setVisibility(View.VISIBLE); break; case SHOW_DONT: mLeftMenu.setVisibility(View.GONE); mRightMenu.setVisibility(View.GONE); break; } if (navButtonColor != -1) { mLeftMenu.setColorFilter(navButtonColor); mRightMenu.setColorFilter(navButtonColor); } } private void saveButtons(){ Settings.System.putInt(mContentRes,Settings.System.NAVIGATION_BAR_BUTTONS_QTY, mNumberofButtons); for (int i = 0; i < mNumberofButtons; i++) { NavBarButton button = mButtons.get(i); Settings.System.putString(mContentRes, Settings.System.NAVIGATION_CUSTOM_ACTIVITIES[i], button.getClickAction()); Settings.System.putString(mContentRes, Settings.System.NAVIGATION_LONGPRESS_ACTIVITIES[i], button.getLongAction()); Settings.System.putString(mContentRes, Settings.System.NAVIGATION_CUSTOM_APP_ICONS[i], button.getIconURI()); } } private void createDialog(final NavBarButton button) { final DialogInterface.OnClickListener l = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int item) { onDialogClick(button, item); dialog.dismiss(); } }; String action = mResources.getString(R.string.navbar_actiontitle_menu); action = String.format(action, button.getClickName()); String longpress = mResources.getString(R.string.navbar_longpress_menu); longpress = String.format(longpress, button.getLongName()); String[] items = {action,longpress, mResources.getString(R.string.navbar_icon_menu), mResources.getString(R.string.navbar_delete_menu)}; final AlertDialog dialog = new AlertDialog.Builder(mContext) .setTitle(mResources.getString(R.string.navbar_title_menu)) .setSingleChoiceItems(items, -1, l) .create(); dialog.show(); } private void createActionDialog(final NavBarButton button) { final DialogInterface.OnClickListener l = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int item) { onActionDialogClick(button, item); dialog.dismiss(); } }; final AlertDialog dialog = new AlertDialog.Builder(mContext) .setTitle(mResources.getString(R.string.navbar_title_menu)) .setSingleChoiceItems(mActions, -1, l) .create(); dialog.show(); } private void onDialogClick(NavBarButton button, int command){ switch (command) { case 0: // Set Click Action button.setPickLongPress(false); createActionDialog(button); break; case 1: // Set Long Press Action button.setPickLongPress(true); createActionDialog(button); break; case 2: // set Custom Icon int width = 100; int height = width; Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null); intent.setType("image/*"); intent.putExtra("crop", "true"); intent.putExtra("aspectX", width); intent.putExtra("aspectY", height); intent.putExtra("outputX", width); intent.putExtra("outputY", height); intent.putExtra("scale", true); intent.putExtra(MediaStore.EXTRA_OUTPUT, getTempFileUri()); intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString()); Log.i(TAG, "started for result, should output to: " + getTempFileUri()); startActivityForResult(intent,REQUEST_PICK_CUSTOM_ICON); break; case 3: // Delete Button mButtons.remove(mPendingButton); mNumberofButtons--; break; } refreshButtons(); } private void onActionDialogClick(NavBarButton button, int command){ if (command == mActions.length -1) { // This is the last action - should be **app** mPicker.pickShortcut(); } else { // This should be any other defined action. if (button.getPickLongPress()) { button.setLongPress(AwesomeConstants.AwesomeActions()[command]); } else { button.setClickAction(AwesomeConstants.AwesomeActions()[command]); } } refreshButtons(); } private View.OnClickListener mCommandButtons = new View.OnClickListener() { @Override public void onClick(View v) { int command = v.getId(); switch (command) { case R.id.reset_button: loadButtons(); break; case R.id.add_button: if (mNumberofButtons < 7) { // Maximum buttons is 7 mButtons.add(new NavBarButton("**null**","**null**","")); mNumberofButtons++; } break; case R.id.save_button: saveButtons(); break; } refreshButtons(); } }; private Drawable setIcon(String uri, String action) { if (uri != null && uri.length() > 0) { File f = new File(Uri.parse(uri).getPath()); if (f.exists()) return resize(new BitmapDrawable(mResources, f.getAbsolutePath())); } if (uri != null && !uri.equals("") && uri.startsWith("file")) { // it's an icon the user chose from the gallery here File icon = new File(Uri.parse(uri).getPath()); if (icon.exists()) return resize(new BitmapDrawable(mResources, icon .getAbsolutePath())); } else if (uri != null && !uri.equals("")) { // here they chose another app icon try { return resize(mPackMan.getActivityIcon(Intent.parseUri(uri, 0))); } catch (NameNotFoundException e) { e.printStackTrace(); } catch (URISyntaxException e) { e.printStackTrace(); } // ok use default icons here } return resize(getNavbarIconImage(action)); } private Drawable getNavbarIconImage(String uri) { if (uri == null) uri = AwesomeConstant.ACTION_NULL.value(); if (uri.startsWith("**")) { return AwesomeConstants.getActionIcon(mContext, uri); } else { try { return mPackMan.getActivityIcon(Intent.parseUri(uri, 0)); } catch (NameNotFoundException e) { e.printStackTrace(); } catch (URISyntaxException e) { e.printStackTrace(); } } return mResources.getDrawable(R.drawable.ic_sysbar_null); } @Override public void shortcutPicked(String uri, String friendlyName, Bitmap bmp, boolean isApplication) { NavBarButton button = mButtons.get(mPendingButton); boolean longpress = button.getPickLongPress(); if (!longpress) { button.setClickAction(uri); if (bmp == null) { button.setIconURI(""); } else { String iconName = getIconFileName(mPendingButton); FileOutputStream iconStream = null; try { iconStream = mContext.openFileOutput(iconName, Context.MODE_WORLD_READABLE); } catch (FileNotFoundException e) { return; // NOOOOO } bmp.compress(Bitmap.CompressFormat.PNG, 100, iconStream); button.setIconURI(Uri.fromFile(mContext.getFileStreamPath(iconName)).toString()); } } else { button.setLongPress(uri); } refreshButtons(); } public void onActivityResult(int requestCode, int resultCode, Intent data) { Log.i(TAG, "RequestCode:"+resultCode); if (resultCode == Activity.RESULT_OK) { if (requestCode == ShortcutPickerHelper.REQUEST_PICK_SHORTCUT || requestCode == ShortcutPickerHelper.REQUEST_PICK_APPLICATION || requestCode == ShortcutPickerHelper.REQUEST_CREATE_SHORTCUT) { mPicker.onActivityResult(requestCode, resultCode, data); } else if (requestCode == REQUEST_PICK_CUSTOM_ICON) { String iconName = getIconFileName(mPendingButton); FileOutputStream iconStream = null; try { iconStream = mContext.openFileOutput(iconName, Context.MODE_WORLD_READABLE); } catch (FileNotFoundException e) { return; // NOOOOO } Uri selectedImageUri = getTempFileUri(); try { Log.e(TAG, "Selected image path: " + selectedImageUri.getPath()); Bitmap bitmap = BitmapFactory.decodeFile(selectedImageUri.getPath()); bitmap.compress(Bitmap.CompressFormat.PNG, 100, iconStream); } catch (NullPointerException npe) { Log.e(TAG, "SeletedImageUri was null."); return; } mButtons.get(mPendingButton).setIconURI(Uri.fromFile( new File(mContext.getFilesDir(), iconName)).getPath()); File f = new File(selectedImageUri.getPath()); if (f.exists()) f.delete(); refreshButtons(); } } super.onActivityResult(requestCode, resultCode, data); } private String getProperSummary(String uri) { if (uri == null) return AwesomeConstants.getProperName(mContext, "**null**"); if (uri.startsWith("**")) { return AwesomeConstants.getProperName(mContext, uri); } else { return mPicker.getFriendlyNameForUri(uri); } } private Drawable resize(Drawable image) { int size = 50; int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, size, mResources.getDisplayMetrics()); Bitmap d = ((BitmapDrawable) image).getBitmap(); if (d == null) { return mResources.getDrawable(R.drawable.ic_sysbar_null); } else { Bitmap bitmapOrig = Bitmap.createScaledBitmap(d, px, px, false); return new BitmapDrawable(mResources, bitmapOrig); } } public class NavBarButton { String mClickAction; String mLongPressAction; String mIconURI; String mClickFriendlyName; String mLongPressFriendlyName; Drawable mIcon; boolean mPickingLongPress; public NavBarButton(String clickaction, String longpress, String iconuri ) { mClickAction = clickaction; mLongPressAction = longpress; mIconURI = iconuri; mClickFriendlyName = getProperSummary(mClickAction); mLongPressFriendlyName = getProperSummary (mLongPressAction); mIcon = setIcon(mIconURI,mClickAction); } public void setClickAction(String click) { mClickAction = click; mClickFriendlyName = getProperSummary(mClickAction); // ClickAction was reset - so we should default to stock Icon for now mIconURI = ""; mIcon = setIcon(mIconURI,mClickAction); } public void setLongPress(String action) { mLongPressAction = action; mLongPressFriendlyName = getProperSummary (mLongPressAction); } public void setPickLongPress(boolean pick) { mPickingLongPress = pick; } public boolean getPickLongPress() { return mPickingLongPress; } public void setIconURI (String uri) { mIconURI = uri; mIcon = setIcon(mIconURI,mClickAction); } public String getClickName() { return mClickFriendlyName; } public String getLongName() { return mLongPressFriendlyName; } public Drawable getIcon() { return mIcon; } public String getClickAction() { return mClickAction; } public String getLongAction() { return mLongPressAction; } public String getIconURI() { return mIconURI; } } }
true
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle(R.string.title_navbar); // Load the preferences from an XML resource addPreferencesFromResource(R.xml.navbar_settings); PreferenceScreen prefs = getPreferenceScreen(); mPicker = new ShortcutPickerHelper(this, this); mPackMan = getPackageManager(); mResources = mContext.getResources(); // Get NavBar Actions mActionCodes = NavBarHelpers.getNavBarActions(); mActions = new String[mActionCodes.length]; int actionqty = mActions.length; for (int i = 0; i < actionqty; i++) { mActions[i] = AwesomeConstants.getProperName(mContext, mActionCodes[i]); } menuDisplayLocation = (ListPreference) findPreference(PREF_MENU_UNLOCK); menuDisplayLocation.setOnPreferenceChangeListener(this); menuDisplayLocation.setValue(Settings.System.getInt(mContentRes, Settings.System.MENU_LOCATION,0) + ""); mNavBarMenuDisplay = (ListPreference) findPreference(PREF_NAVBAR_MENU_DISPLAY); mNavBarMenuDisplay.setOnPreferenceChangeListener(this); mNavBarMenuDisplay.setValue(Settings.System.getInt(mContentRes, Settings.System.MENU_VISIBILITY,0) + ""); mNavBarHideEnable = (CheckBoxPreference) findPreference(NAVBAR_HIDE_ENABLE); mNavBarHideEnable.setChecked(Settings.System.getBoolean(mContentRes, Settings.System.NAV_HIDE_ENABLE, false)); final int defaultDragOpacity = Settings.System.getInt(mContentRes, Settings.System.DRAG_HANDLE_OPACITY,50); mDragHandleOpacity = (SeekBarPreference) findPreference(DRAG_HANDLE_OPACITY); mDragHandleOpacity.setInitValue((int) (defaultDragOpacity)); mDragHandleOpacity.setOnPreferenceChangeListener(this); final int defaultDragWidth = Settings.System.getInt(mContentRes, Settings.System.DRAG_HANDLE_WEIGHT, 5); mDragHandleWidth = (SeekBarPreference) findPreference(DRAG_HANDLE_WIDTH); mDragHandleWidth.setInitValue((int) (defaultDragWidth)); mDragHandleWidth.setOnPreferenceChangeListener(this); mNavBarHideTimeout = (ListPreference) findPreference(NAVBAR_HIDE_TIMEOUT); mNavBarHideTimeout.setOnPreferenceChangeListener(this); mNavBarHideTimeout.setValue(Settings.System.getInt(mContentRes, Settings.System.NAV_HIDE_TIMEOUT, 3000) + ""); boolean hasNavBarByDefault = mContext.getResources().getBoolean( com.android.internal.R.bool.config_showNavigationBar); mEnableNavigationBar = (CheckBoxPreference) findPreference(ENABLE_NAVIGATION_BAR); mEnableNavigationBar.setChecked(Settings.System.getBoolean(mContentRes, Settings.System.NAVIGATION_BAR_SHOW, hasNavBarByDefault)); mNavigationColor = (ColorPickerPreference) findPreference(NAVIGATION_BAR_COLOR); mNavigationColor.setOnPreferenceChangeListener(this); mNavigationBarColor = (ColorPickerPreference) findPreference(PREF_NAV_COLOR); mNavigationBarColor.setOnPreferenceChangeListener(this); mColorizeAllIcons = (CheckBoxPreference) findPreference("navigation_bar_allcolor"); mColorizeAllIcons.setChecked(Settings.System.getBoolean(mContentRes, Settings.System.NAVIGATION_BAR_ALLCOLOR, false)); mNavigationBarGlowColor = (ColorPickerPreference) findPreference(PREF_NAV_GLOW_COLOR); mNavigationBarGlowColor.setOnPreferenceChangeListener(this); mGlowTimes = (ListPreference) findPreference(PREF_GLOW_TIMES); mGlowTimes.setOnPreferenceChangeListener(this); final float defaultButtonAlpha = Settings.System.getFloat(mContentRes, Settings.System.NAVIGATION_BAR_BUTTON_ALPHA,0.6f); mButtonAlpha = (SeekBarPreference) findPreference("button_transparency"); mButtonAlpha.setInitValue((int) (defaultButtonAlpha * 100)); mButtonAlpha.setOnPreferenceChangeListener(this); mWidthHelp = (Preference) findPreference("width_help"); float defaultPort = Settings.System.getFloat(mContentRes, Settings.System.NAVIGATION_BAR_WIDTH_PORT,0f); mWidthPort = (SeekBarPreference) findPreference("width_port"); mWidthPort.setInitValue((int) (defaultPort * 2.5f)); mWidthPort.setOnPreferenceChangeListener(this); float defaultLand = Settings.System.getFloat(mContentRes, Settings.System.NAVIGATION_BAR_WIDTH_LAND,0f); mWidthLand = (SeekBarPreference) findPreference("width_land"); mWidthLand.setInitValue((int) (defaultLand * 2.5f)); mWidthLand.setOnPreferenceChangeListener(this); mNavigationBarHeight = (ListPreference) findPreference("navigation_bar_height"); mNavigationBarHeight.setOnPreferenceChangeListener(this); mNavigationBarHeightLandscape = (ListPreference) findPreference("navigation_bar_height_landscape"); mNavigationBarHeightLandscape.setOnPreferenceChangeListener(this); mNavigationBarWidth = (ListPreference) findPreference("navigation_bar_width"); mNavigationBarWidth.setOnPreferenceChangeListener(this); mConfigureWidgets = findPreference(NAVIGATION_BAR_WIDGETS); mMenuArrowKeysCheckBox = (CheckBoxPreference) findPreference(PREF_MENU_ARROWS); mMenuArrowKeysCheckBox.setChecked(Settings.System.getBoolean(mContentRes, Settings.System.NAVIGATION_BAR_MENU_ARROW_KEYS, true)); // don't allow devices that must use a navigation bar to disable it if (hasNavBarByDefault) { prefs.removePreference(mEnableNavigationBar); } PreferenceGroup pg = (PreferenceGroup) prefs.findPreference("advanced_cat"); if (isTablet(mContext)) { mNavigationBarHeight.setTitle(R.string.system_bar_height_title); mNavigationBarHeight.setSummary(R.string.system_bar_height_summary); mNavigationBarWidth.setTitle(R.string.system_bar_height_landscape_title); mNavigationBarWidth.setSummary(R.string.system_bar_height_landscape_summary); pg.removePreference(mNavigationBarHeightLandscape); mNavBarHideEnable.setEnabled(false); mDragHandleOpacity.setEnabled(false); mDragHandleWidth.setEnabled(false); mNavBarHideTimeout.setEnabled(false); } else { // Phones&Phablets don't have SystemBar pg.removePreference(mWidthPort); pg.removePreference(mWidthLand); pg.removePreference(mWidthHelp); } if (Integer.parseInt(menuDisplayLocation.getValue()) == 4) { mNavBarMenuDisplay.setEnabled(false); } // Only show the hardware keys config on a device that does not have a navbar IWindowManager windowManager = IWindowManager.Stub.asInterface( ServiceManager.getService(Context.WINDOW_SERVICE)); if (hasNavBarByDefault) { // Let's assume they don't have hardware keys getPreferenceScreen().removePreference(findPreference(KEY_HARDWARE_KEYS)); } refreshSettings(); setHasOptionsMenu(true); updateGlowTimesSummary(); }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle(R.string.title_navbar); // Load the preferences from an XML resource addPreferencesFromResource(R.xml.navbar_settings); PreferenceScreen prefs = getPreferenceScreen(); mPicker = new ShortcutPickerHelper(this, this); mPackMan = getPackageManager(); mResources = mContext.getResources(); // Get NavBar Actions mActionCodes = NavBarHelpers.getNavBarActions(); mActions = new String[mActionCodes.length]; int actionqty = mActions.length; for (int i = 0; i < actionqty; i++) { mActions[i] = AwesomeConstants.getProperName(mContext, mActionCodes[i]); } menuDisplayLocation = (ListPreference) findPreference(PREF_MENU_UNLOCK); menuDisplayLocation.setOnPreferenceChangeListener(this); menuDisplayLocation.setValue(Settings.System.getInt(mContentRes, Settings.System.MENU_LOCATION,0) + ""); mNavBarMenuDisplay = (ListPreference) findPreference(PREF_NAVBAR_MENU_DISPLAY); mNavBarMenuDisplay.setOnPreferenceChangeListener(this); mNavBarMenuDisplay.setValue(Settings.System.getInt(mContentRes, Settings.System.MENU_VISIBILITY,0) + ""); mNavBarHideEnable = (CheckBoxPreference) findPreference(NAVBAR_HIDE_ENABLE); mNavBarHideEnable.setChecked(Settings.System.getBoolean(mContentRes, Settings.System.NAV_HIDE_ENABLE, false)); final int defaultDragOpacity = Settings.System.getInt(mContentRes, Settings.System.DRAG_HANDLE_OPACITY,50); mDragHandleOpacity = (SeekBarPreference) findPreference(DRAG_HANDLE_OPACITY); mDragHandleOpacity.setInitValue((int) (defaultDragOpacity)); mDragHandleOpacity.setOnPreferenceChangeListener(this); final int defaultDragWidth = Settings.System.getInt(mContentRes, Settings.System.DRAG_HANDLE_WEIGHT, 5); mDragHandleWidth = (SeekBarPreference) findPreference(DRAG_HANDLE_WIDTH); mDragHandleWidth.setInitValue((int) (defaultDragWidth)); mDragHandleWidth.setOnPreferenceChangeListener(this); mNavBarHideTimeout = (ListPreference) findPreference(NAVBAR_HIDE_TIMEOUT); mNavBarHideTimeout.setOnPreferenceChangeListener(this); mNavBarHideTimeout.setValue(Settings.System.getInt(mContentRes, Settings.System.NAV_HIDE_TIMEOUT, 3000) + ""); boolean hasNavBarByDefault = mContext.getResources().getBoolean( com.android.internal.R.bool.config_showNavigationBar); mEnableNavigationBar = (CheckBoxPreference) findPreference(ENABLE_NAVIGATION_BAR); mEnableNavigationBar.setChecked(Settings.System.getBoolean(mContentRes, Settings.System.NAVIGATION_BAR_SHOW, hasNavBarByDefault)); mNavigationColor = (ColorPickerPreference) findPreference(NAVIGATION_BAR_COLOR); mNavigationColor.setOnPreferenceChangeListener(this); mNavigationBarColor = (ColorPickerPreference) findPreference(PREF_NAV_COLOR); mNavigationBarColor.setOnPreferenceChangeListener(this); mColorizeAllIcons = (CheckBoxPreference) findPreference("navigation_bar_allcolor"); mColorizeAllIcons.setChecked(Settings.System.getBoolean(mContentRes, Settings.System.NAVIGATION_BAR_ALLCOLOR, false)); mNavigationBarGlowColor = (ColorPickerPreference) findPreference(PREF_NAV_GLOW_COLOR); mNavigationBarGlowColor.setOnPreferenceChangeListener(this); mGlowTimes = (ListPreference) findPreference(PREF_GLOW_TIMES); mGlowTimes.setOnPreferenceChangeListener(this); final float defaultButtonAlpha = Settings.System.getFloat(mContentRes, Settings.System.NAVIGATION_BAR_BUTTON_ALPHA,0.6f); mButtonAlpha = (SeekBarPreference) findPreference("button_transparency"); mButtonAlpha.setInitValue((int) (defaultButtonAlpha * 100)); mButtonAlpha.setOnPreferenceChangeListener(this); mWidthHelp = (Preference) findPreference("width_help"); float defaultPort = Settings.System.getFloat(mContentRes, Settings.System.NAVIGATION_BAR_WIDTH_PORT,0f); mWidthPort = (SeekBarPreference) findPreference("width_port"); mWidthPort.setInitValue((int) (defaultPort * 2.5f)); mWidthPort.setOnPreferenceChangeListener(this); float defaultLand = Settings.System.getFloat(mContentRes, Settings.System.NAVIGATION_BAR_WIDTH_LAND,0f); mWidthLand = (SeekBarPreference) findPreference("width_land"); mWidthLand.setInitValue((int) (defaultLand * 2.5f)); mWidthLand.setOnPreferenceChangeListener(this); mNavigationBarHeight = (ListPreference) findPreference("navigation_bar_height"); mNavigationBarHeight.setOnPreferenceChangeListener(this); mNavigationBarHeightLandscape = (ListPreference) findPreference("navigation_bar_height_landscape"); mNavigationBarHeightLandscape.setOnPreferenceChangeListener(this); mNavigationBarWidth = (ListPreference) findPreference("navigation_bar_width"); mNavigationBarWidth.setOnPreferenceChangeListener(this); mConfigureWidgets = findPreference(NAVIGATION_BAR_WIDGETS); mMenuArrowKeysCheckBox = (CheckBoxPreference) findPreference(PREF_MENU_ARROWS); mMenuArrowKeysCheckBox.setChecked(Settings.System.getBoolean(mContentRes, Settings.System.NAVIGATION_BAR_MENU_ARROW_KEYS, true)); // don't allow devices that must use a navigation bar to disable it if (hasNavBarByDefault) { prefs.removePreference(mEnableNavigationBar); } PreferenceGroup pg = (PreferenceGroup) prefs.findPreference("advanced_cat"); if (isTablet(mContext)) { mNavigationBarHeight.setTitle(R.string.system_bar_height_title); mNavigationBarHeight.setSummary(R.string.system_bar_height_summary); mNavigationBarHeightLandscape.setTitle(R.string.system_bar_height_landscape_title); mNavigationBarHeightLandscape.setSummary(R.string.system_bar_height_landscape_summary); pg.removePreference(mNavigationBarWidth); mNavBarHideEnable.setEnabled(false); mDragHandleOpacity.setEnabled(false); mDragHandleWidth.setEnabled(false); mNavBarHideTimeout.setEnabled(false); } else { // Phones&Phablets don't have SystemBar pg.removePreference(mWidthPort); pg.removePreference(mWidthLand); pg.removePreference(mWidthHelp); } if (Integer.parseInt(menuDisplayLocation.getValue()) == 4) { mNavBarMenuDisplay.setEnabled(false); } // Only show the hardware keys config on a device that does not have a navbar IWindowManager windowManager = IWindowManager.Stub.asInterface( ServiceManager.getService(Context.WINDOW_SERVICE)); if (hasNavBarByDefault) { // Let's assume they don't have hardware keys getPreferenceScreen().removePreference(findPreference(KEY_HARDWARE_KEYS)); } refreshSettings(); setHasOptionsMenu(true); updateGlowTimesSummary(); }
diff --git a/examples/src/test/java/org/apache/mahout/classifier/sgd/TrainLogisticTest.java b/examples/src/test/java/org/apache/mahout/classifier/sgd/TrainLogisticTest.java index 7257ab082..78454385f 100644 --- a/examples/src/test/java/org/apache/mahout/classifier/sgd/TrainLogisticTest.java +++ b/examples/src/test/java/org/apache/mahout/classifier/sgd/TrainLogisticTest.java @@ -1,161 +1,161 @@ /* * 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.mahout.classifier.sgd; import com.google.common.base.CharMatcher; import com.google.common.base.Charsets; import com.google.common.base.Splitter; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterables; import com.google.common.collect.Sets; import com.google.common.io.Resources; import org.apache.mahout.classifier.AbstractVectorClassifier; import org.apache.mahout.examples.MahoutTestCase; import org.apache.mahout.math.DenseVector; import org.apache.mahout.math.Vector; import org.junit.Test; import java.io.ByteArrayOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.PrintStream; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.List; import java.util.Map; import java.util.Set; public class TrainLogisticTest extends MahoutTestCase { private static final Splitter ON_WHITE_SPACE = Splitter.on(CharMatcher.BREAKING_WHITESPACE).trimResults().omitEmptyStrings(); @Test public void example13_1() throws IOException, NoSuchFieldException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { String outputFile = getTestTempFile("model").getAbsolutePath(); String trainOut = runMain(TrainLogistic.class, new String[]{ "--input", "donut.csv", - " --output", outputFile, - " --target", "color", "--categories", "2" + - "--predictors", "x", "y", + "--output", outputFile, + "--target", "color", "--categories", "2", + "--predictors", "x", "y", "--types", "numeric", "--features", "20", "--passes", "100", "--rate", "50" }); assertTrue(trainOut.contains("x -0.7")); assertTrue(trainOut.contains("y -0.4")); LogisticModelParameters lmp = TrainLogistic.getParameters(); assertEquals(1.0e-4, lmp.getLambda(), 1.0e-9); assertEquals(20, lmp.getNumFeatures()); assertTrue(lmp.useBias()); assertEquals("color", lmp.getTargetVariable()); CsvRecordFactory csv = lmp.getCsvRecordFactory(); assertEquals("[1, 2]", Sets.newTreeSet(csv.getTargetCategories()).toString()); assertEquals("[Intercept Term, x, y]", Sets.newTreeSet(csv.getPredictors()).toString()); // verify model by building dissector AbstractVectorClassifier model = TrainLogistic.getModel(); List<String> data = Resources.readLines(Resources.getResource("donut.csv"), Charsets.UTF_8); Map<String, Double> expectedValues = ImmutableMap.of("x", -0.7, "y", -0.43, "Intercept Term", -0.15); verifyModel(lmp, csv, data, model, expectedValues); // test saved model LogisticModelParameters lmpOut = LogisticModelParameters.loadFrom(new FileReader(outputFile)); CsvRecordFactory csvOut = lmpOut.getCsvRecordFactory(); csvOut.firstLine(data.get(0)); OnlineLogisticRegression lrOut = lmpOut.createRegression(); verifyModel(lmpOut, csvOut, data, lrOut, expectedValues); String output = runMain(RunLogistic.class, new String[]{"--input", "donut.csv", "--model", outputFile, "--auc", "--confusion"}); assertTrue(output.contains("AUC = 0.57")); assertTrue(output.contains("confusion: [[27.0, 13.0], [0.0, 0.0]]")); } @Test public void example13_2() throws InvocationTargetException, IOException, NoSuchMethodException, NoSuchFieldException, IllegalAccessException { String outputFile = getTestTempFile("model").getAbsolutePath(); String trainOut = runMain(TrainLogistic.class, new String[]{ "--input", "donut.csv", "--output", outputFile, "--target", "color", "--categories", "2", "--predictors", "x", "y", "a", "b", "c", "--types", "numeric", "--features", "20", "--passes", "100", "--rate", "50" }); assertTrue(trainOut.contains("a 0.")); assertTrue(trainOut.contains("b -1.")); assertTrue(trainOut.contains("c -25.")); String output = runMain(RunLogistic.class, new String[]{"--input", "donut.csv", "--model", outputFile, "--auc", "--confusion"}); assertTrue(output.contains("AUC = 1.00")); String heldout = runMain(RunLogistic.class, new String[]{"--input", "donut-test.csv", "--model", outputFile, "--auc", "--confusion"}); assertTrue(heldout.contains("AUC = 0.9")); } /** * Runs a class with a public static void main method. We assume that there is an accessible * field named "output" that we can change to redirect output. * * * @param clazz contains the main method. * @param args contains the command line arguments * @return The contents to standard out as a string. * @throws IOException Not possible, but must be declared. * @throws NoSuchFieldException If there isn't an output field. * @throws IllegalAccessException If the output field isn't accessible by us. * @throws NoSuchMethodException If there isn't a main method. * @throws InvocationTargetException If the main method throws an exception. */ private String runMain(Class clazz, String[] args) throws IOException, NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { ByteArrayOutputStream trainOutput = new ByteArrayOutputStream(); PrintStream printStream = new PrintStream(trainOutput); Field outputField = clazz.getDeclaredField("output"); Method main = clazz.getMethod("main", args.getClass()); outputField.set(null, printStream); Object[] argList = {args}; main.invoke(null, argList); printStream.close(); return new String(trainOutput.toByteArray(), Charsets.UTF_8); } private void verifyModel(LogisticModelParameters lmp, CsvRecordFactory csv, List<String> data, AbstractVectorClassifier model, Map<String, Double> expectedValues) { ModelDissector md = new ModelDissector(); for (String line : data.subList(1, data.size())) { Vector v = new DenseVector(lmp.getNumFeatures()); csv.getTraceDictionary().clear(); csv.processLine(line, v); md.update(v, csv.getTraceDictionary(), model); } // check right variables are present List<ModelDissector.Weight> weights = md.summary(10); Set<String> expected = Sets.newHashSet(expectedValues.keySet()); for (ModelDissector.Weight weight : weights) { assertTrue(expected.remove(weight.getFeature())); assertEquals(expectedValues.get(weight.getFeature()), weight.getWeight(), 0.1); } assertEquals(0, expected.size()); } }
true
true
public void example13_1() throws IOException, NoSuchFieldException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { String outputFile = getTestTempFile("model").getAbsolutePath(); String trainOut = runMain(TrainLogistic.class, new String[]{ "--input", "donut.csv", " --output", outputFile, " --target", "color", "--categories", "2" + "--predictors", "x", "y", "--types", "numeric", "--features", "20", "--passes", "100", "--rate", "50" }); assertTrue(trainOut.contains("x -0.7")); assertTrue(trainOut.contains("y -0.4")); LogisticModelParameters lmp = TrainLogistic.getParameters(); assertEquals(1.0e-4, lmp.getLambda(), 1.0e-9); assertEquals(20, lmp.getNumFeatures()); assertTrue(lmp.useBias()); assertEquals("color", lmp.getTargetVariable()); CsvRecordFactory csv = lmp.getCsvRecordFactory(); assertEquals("[1, 2]", Sets.newTreeSet(csv.getTargetCategories()).toString()); assertEquals("[Intercept Term, x, y]", Sets.newTreeSet(csv.getPredictors()).toString()); // verify model by building dissector AbstractVectorClassifier model = TrainLogistic.getModel(); List<String> data = Resources.readLines(Resources.getResource("donut.csv"), Charsets.UTF_8); Map<String, Double> expectedValues = ImmutableMap.of("x", -0.7, "y", -0.43, "Intercept Term", -0.15); verifyModel(lmp, csv, data, model, expectedValues); // test saved model LogisticModelParameters lmpOut = LogisticModelParameters.loadFrom(new FileReader(outputFile)); CsvRecordFactory csvOut = lmpOut.getCsvRecordFactory(); csvOut.firstLine(data.get(0)); OnlineLogisticRegression lrOut = lmpOut.createRegression(); verifyModel(lmpOut, csvOut, data, lrOut, expectedValues); String output = runMain(RunLogistic.class, new String[]{"--input", "donut.csv", "--model", outputFile, "--auc", "--confusion"}); assertTrue(output.contains("AUC = 0.57")); assertTrue(output.contains("confusion: [[27.0, 13.0], [0.0, 0.0]]")); }
public void example13_1() throws IOException, NoSuchFieldException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { String outputFile = getTestTempFile("model").getAbsolutePath(); String trainOut = runMain(TrainLogistic.class, new String[]{ "--input", "donut.csv", "--output", outputFile, "--target", "color", "--categories", "2", "--predictors", "x", "y", "--types", "numeric", "--features", "20", "--passes", "100", "--rate", "50" }); assertTrue(trainOut.contains("x -0.7")); assertTrue(trainOut.contains("y -0.4")); LogisticModelParameters lmp = TrainLogistic.getParameters(); assertEquals(1.0e-4, lmp.getLambda(), 1.0e-9); assertEquals(20, lmp.getNumFeatures()); assertTrue(lmp.useBias()); assertEquals("color", lmp.getTargetVariable()); CsvRecordFactory csv = lmp.getCsvRecordFactory(); assertEquals("[1, 2]", Sets.newTreeSet(csv.getTargetCategories()).toString()); assertEquals("[Intercept Term, x, y]", Sets.newTreeSet(csv.getPredictors()).toString()); // verify model by building dissector AbstractVectorClassifier model = TrainLogistic.getModel(); List<String> data = Resources.readLines(Resources.getResource("donut.csv"), Charsets.UTF_8); Map<String, Double> expectedValues = ImmutableMap.of("x", -0.7, "y", -0.43, "Intercept Term", -0.15); verifyModel(lmp, csv, data, model, expectedValues); // test saved model LogisticModelParameters lmpOut = LogisticModelParameters.loadFrom(new FileReader(outputFile)); CsvRecordFactory csvOut = lmpOut.getCsvRecordFactory(); csvOut.firstLine(data.get(0)); OnlineLogisticRegression lrOut = lmpOut.createRegression(); verifyModel(lmpOut, csvOut, data, lrOut, expectedValues); String output = runMain(RunLogistic.class, new String[]{"--input", "donut.csv", "--model", outputFile, "--auc", "--confusion"}); assertTrue(output.contains("AUC = 0.57")); assertTrue(output.contains("confusion: [[27.0, 13.0], [0.0, 0.0]]")); }
diff --git a/uk.ac.diamond.scisoft.analysis.rcp/src/uk/ac/diamond/scisoft/analysis/rcp/preference/PreferenceInitializer.java b/uk.ac.diamond.scisoft.analysis.rcp/src/uk/ac/diamond/scisoft/analysis/rcp/preference/PreferenceInitializer.java index 1c11692..4f80084 100644 --- a/uk.ac.diamond.scisoft.analysis.rcp/src/uk/ac/diamond/scisoft/analysis/rcp/preference/PreferenceInitializer.java +++ b/uk.ac.diamond.scisoft.analysis.rcp/src/uk/ac/diamond/scisoft/analysis/rcp/preference/PreferenceInitializer.java @@ -1,150 +1,150 @@ /* * Copyright 2012 Diamond Light Source Ltd. * * 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.ac.diamond.scisoft.analysis.rcp.preference; import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.swt.printing.Printer; import org.eclipse.swt.printing.PrinterData; import uk.ac.diamond.scisoft.analysis.rcp.AnalysisRCPActivator; public class PreferenceInitializer extends AbstractPreferenceInitializer { public static final String DELIMITER = "]}¬¬{["; private static final Boolean DEFAULT_SIDEPLOTTER1D_USE_LOG = false; private static final int DEFAULT_GRIDSCAN_BEAMLINE_POSITION = 0; private static final double DEFAULT_GRIDSCAN_RESOLUTION = 10000.0; private static final String DEFAULT_DIFFRACTION_PEAK= "Gaussian"; private static final int DEFAULT_MAX_NUM_PEAKS = 10; private static final int DEFAULT_PIXELOVERLOAD_THRESHOLD = 65535; private static final boolean DEFAULT_SHOW_SCROLLBARS = true; private static final int DEFAULT_COLOURMAP_CHOICE = 1; private static final int DEFAULT_CAMERA_PROJECTION = 0; private static final int DEFAULT_IMAGEXPLORER_COLOURMAP_CHOICE = 0; private static final int DEFAULT_IMAGEEXPLORER_HISTOGRAM_SCALE = 98; private static final int DEFAULT_IMAGEEXPLORER_TIMEDEAY = 1000; private static final String DEFAULT_IMAGEEXPLORER_PLAYBACKVIEW = "Live Plot"; private static final int DEFAULT_IMAGEEXPLORER_PLAYBACKRATE = 1; private static final boolean DEFAULT_COLOURMAP_EXPERT = false; private static final boolean DEFAULT_AUTOHISTOGRAM = true; private static final int DEFAULT_COLOURSCALE_CHOICE = 0; private static final boolean DEFAULT_DIFFRACTION_VIEWER_AUTOSTOPPING = true; private static final int DEFAULT_DIFFRACTION_VIEWER_STOPPING_THRESHOLD= 25; private static final String DEFAULT_STANDARD_NAME_LIST = "Cr2O3"+DELIMITER+"Silicon"+DELIMITER+"Bees Wax"; private static final String DEFAULT_STANDARD_NAME = "Cr2O3"; private static final String DEFAULT_STANDARD_DISTANCES_LIST = "3.645, 2.672, 2.487, 2.181, 1.819, 1.676, 1.467, 1.433"+DELIMITER+"3.6, 2.05, 1.89,1.5,0.25"+DELIMITER+"3.6,2.4"; private static final String DEFAULT_STANDARD_DISTANCES = "3.645, 2.672, 2.487, 2.181, 1.819, 1.676, 1.467, 1.433"; private static final String DEFAULT_FITTING_1D_PEAKTYPE ="Gaussian"; private static final String DEFAULT_FITTING_1D_PEAKLIST = "Gaussian" +DELIMITER+ "Lorentzian" +DELIMITER+"Pearson VII" +DELIMITER+"PseudoVoigt" ; private static final int DEFAULT_FITTING_1D_PEAK_NUM = 10; private static final String DEFAULT_FITTING_1D_ALG_TYPE = "Genetic Algorithm"; private static final String DEFAULT_FITTING_1D_ALG_LIST = "Nelder Mead" +DELIMITER+ "Genetic Algorithm" +DELIMITER+ "Apache Nelder Mead"; private static final int DEFAULT_FITTING_1D_ALG_SMOOTHING = 5; private static final double DEFAULT_FITTING_1D_ALG_ACCURACY = 0.01; private static final boolean DEFAULT_FITTING_1D_AUTO_SMOOTHING = false; private static final boolean DEFAULT_FITTING_1D_AUTO_STOPPING = true; private static final int DEFAULT_FITTING_1D_THRESHOLD = 5; private static final String DEFAULT_FITTING_1D_THRESHOLD_MEASURE = "Area"; private static final String DEFAULT_FITTING_1D_THRESHOLD_MEASURE_LIST = "Height"+DELIMITER+"Area"; public static final int DEFAULT_FITTING_1D_DECIMAL_PLACES = 2; public static final int DEFAULT_ANALYSIS_RPC_SERVER_PORT = 0; public static final String DEFAULT_ANALYSIS_RPC_TEMP_FILE_LOCATION = ""; public static final int DEFAULT_RMI_SERVER_PORT = 0; public static final String DEFAULT_PRINTSETTINGS_PRINTNAME = getDefaultPrinterName(); public static final Double DEFAULT_PRINTSETTINGS_SCALE = 0.5; public static final int DEFAULT_PRINTSETTINGS_RESOLUTION = 2; public static final String DEFAULT_PRINTSETTINGS_ORIENTATION = "Portrait"; @Override public void initializeDefaultPreferences() { IPreferenceStore store = AnalysisRCPActivator.getDefault().getPreferenceStore(); store.setDefault(PreferenceConstants.IGNORE_DATASET_FILTERS, false); store.setDefault(PreferenceConstants.SHOW_XY_COLUMN, false); store.setDefault(PreferenceConstants.SHOW_DATA_SIZE, false); store.setDefault(PreferenceConstants.SHOW_DIMS, false); store.setDefault(PreferenceConstants.SHOW_SHAPE, false); store.setDefault(PreferenceConstants.DATA_FORMAT, "#0.00"); store.setDefault(PreferenceConstants.PLAY_SPEED, 1500); store.setDefault(PreferenceConstants.SIDEPLOTTER1D_USE_LOG_Y, DEFAULT_SIDEPLOTTER1D_USE_LOG); store.setDefault(PreferenceConstants.GRIDSCAN_RESOLUTION_X, DEFAULT_GRIDSCAN_RESOLUTION); store.setDefault(PreferenceConstants.GRIDSCAN_RESOLUTION_Y, DEFAULT_GRIDSCAN_RESOLUTION); store.setDefault(PreferenceConstants.GRIDSCAN_BEAMLINE_POSX, DEFAULT_GRIDSCAN_BEAMLINE_POSITION); store.setDefault(PreferenceConstants.GRIDSCAN_BEAMLINE_POSX, DEFAULT_GRIDSCAN_BEAMLINE_POSITION); store.setDefault(PreferenceConstants.DIFFRACTION_VIEWER_PEAK_TYPE, DEFAULT_DIFFRACTION_PEAK); store.setDefault(PreferenceConstants.DIFFRACTION_VIEWER_MAX_PEAK_NUM, DEFAULT_MAX_NUM_PEAKS); store.setDefault(PreferenceConstants.DIFFRACTION_VIEWER_STANDARD_NAME, DEFAULT_STANDARD_NAME); store.setDefault(PreferenceConstants.DIFFRACTION_VIEWER_STANDARD_NAME_LIST, DEFAULT_STANDARD_NAME_LIST); store.setDefault(PreferenceConstants.DIFFRACTION_VIEWER_STANDARD_DISTANCES,DEFAULT_STANDARD_DISTANCES); store.setDefault(PreferenceConstants.DIFFRACTION_VIEWER_STANDARD_DISTANCES_LIST, DEFAULT_STANDARD_DISTANCES_LIST); store.setDefault(PreferenceConstants.DIFFRACTION_VIEWER_PIXELOVERLOAD_THRESHOLD, DEFAULT_PIXELOVERLOAD_THRESHOLD); store.setDefault(PreferenceConstants.DIFFRACTION_VIEWER_AUTOSTOPPING,DEFAULT_DIFFRACTION_VIEWER_AUTOSTOPPING); store.setDefault(PreferenceConstants.DIFFRACTION_VIEWER_STOPPING_THRESHOLD,DEFAULT_DIFFRACTION_VIEWER_STOPPING_THRESHOLD); store.setDefault(PreferenceConstants.FITTING_1D_PEAKTYPE,DEFAULT_FITTING_1D_PEAKTYPE); store.setDefault(PreferenceConstants.FITTING_1D_PEAKLIST,DEFAULT_FITTING_1D_PEAKLIST); store.setDefault(PreferenceConstants.FITTING_1D_PEAK_NUM, DEFAULT_FITTING_1D_PEAK_NUM); store.setDefault(PreferenceConstants.FITTING_1D_ALG_TYPE,DEFAULT_FITTING_1D_ALG_TYPE); store.setDefault(PreferenceConstants.FITTING_1D_ALG_LIST,DEFAULT_FITTING_1D_ALG_LIST); store.setDefault(PreferenceConstants.FITTING_1D_SMOOTHING_VALUE,DEFAULT_FITTING_1D_ALG_SMOOTHING); store.setDefault(PreferenceConstants.FITTING_1D_ALG_ACCURACY,DEFAULT_FITTING_1D_ALG_ACCURACY); store.setDefault(PreferenceConstants.FITTING_1D_AUTO_SMOOTHING, DEFAULT_FITTING_1D_AUTO_SMOOTHING); store.setDefault(PreferenceConstants.FITTING_1D_AUTO_STOPPING,DEFAULT_FITTING_1D_AUTO_STOPPING); store.setDefault(PreferenceConstants.FITTING_1D_THRESHOLD,DEFAULT_FITTING_1D_THRESHOLD); store.setDefault(PreferenceConstants.FITTING_1D_THRESHOLD_MEASURE,DEFAULT_FITTING_1D_THRESHOLD_MEASURE); store.setDefault(PreferenceConstants.FITTING_1D_THRESHOLD_MEASURE_LIST,DEFAULT_FITTING_1D_THRESHOLD_MEASURE_LIST); store.setDefault(PreferenceConstants.FITTING_1D_DECIMAL_PLACES,DEFAULT_FITTING_1D_DECIMAL_PLACES); store.setDefault(PreferenceConstants.PLOT_VIEWER_PLOT2D_COLOURMAP,DEFAULT_COLOURMAP_CHOICE); store.setDefault(PreferenceConstants.PLOT_VIEWER_PLOT2D_CMAP_EXPERT,DEFAULT_COLOURMAP_EXPERT); store.setDefault(PreferenceConstants.PLOT_VIEWER_PLOT2D_AUTOHISTO,DEFAULT_AUTOHISTOGRAM); store.setDefault(PreferenceConstants.PLOT_VIEWER_PLOT2D_SCALING, DEFAULT_COLOURSCALE_CHOICE); store.setDefault(PreferenceConstants.PLOT_VIEWER_PLOT2D_SHOWSCROLLBAR,DEFAULT_SHOW_SCROLLBARS); store.setDefault(PreferenceConstants.PLOT_VIEWER_MULTI1D_CAMERA_PROJ, DEFAULT_CAMERA_PROJECTION); store.setDefault(PreferenceConstants.IMAGEEXPLORER_COLOURMAP, DEFAULT_IMAGEXPLORER_COLOURMAP_CHOICE); store.setDefault(PreferenceConstants.IMAGEEXPLORER_HISTOGRAMAUTOSCALETHRESHOLD, DEFAULT_IMAGEEXPLORER_HISTOGRAM_SCALE); store.setDefault(PreferenceConstants.IMAGEEXPLORER_TIMEDELAYBETWEENIMAGES, DEFAULT_IMAGEEXPLORER_TIMEDEAY); store.setDefault(PreferenceConstants.IMAGEEXPLORER_PLAYBACKVIEW, DEFAULT_IMAGEEXPLORER_PLAYBACKVIEW); store.setDefault(PreferenceConstants.IMAGEEXPLORER_PLAYBACKRATE,DEFAULT_IMAGEEXPLORER_PLAYBACKRATE); - store.setDefault(PreferenceConstants.ANALYSIS_RPC_SERVER_PORT,DEFAULT_ANALYSIS_RPC_SERVER_PORT); - store.setDefault(PreferenceConstants.ANALYSIS_RPC_TEMP_FILE_LOCATION,DEFAULT_ANALYSIS_RPC_TEMP_FILE_LOCATION); - store.setDefault(PreferenceConstants.RMI_SERVER_PORT,DEFAULT_RMI_SERVER_PORT); + store.setDefault(PreferenceConstants.ANALYSIS_RPC_SERVER_PORT, DEFAULT_ANALYSIS_RPC_SERVER_PORT); + store.setDefault(PreferenceConstants.ANALYSIS_RPC_TEMP_FILE_LOCATION, DEFAULT_ANALYSIS_RPC_TEMP_FILE_LOCATION); + store.setDefault(PreferenceConstants.RMI_SERVER_PORT, DEFAULT_RMI_SERVER_PORT); store.setDefault(PreferenceConstants.PRINTSETTINGS_PRINTER_NAME,DEFAULT_PRINTSETTINGS_PRINTNAME); store.setDefault(PreferenceConstants.PRINTSETTINGS_SCALE,DEFAULT_PRINTSETTINGS_SCALE); store.setDefault(PreferenceConstants.PRINTSETTINGS_RESOLUTION,DEFAULT_PRINTSETTINGS_RESOLUTION); store.setDefault(PreferenceConstants.PRINTSETTINGS_ORIENTATION,DEFAULT_PRINTSETTINGS_ORIENTATION); } private static String getDefaultPrinterName(){ PrinterData pdata = Printer.getDefaultPrinterData(); return pdata == null ? "" : pdata.name; } }
true
true
public void initializeDefaultPreferences() { IPreferenceStore store = AnalysisRCPActivator.getDefault().getPreferenceStore(); store.setDefault(PreferenceConstants.IGNORE_DATASET_FILTERS, false); store.setDefault(PreferenceConstants.SHOW_XY_COLUMN, false); store.setDefault(PreferenceConstants.SHOW_DATA_SIZE, false); store.setDefault(PreferenceConstants.SHOW_DIMS, false); store.setDefault(PreferenceConstants.SHOW_SHAPE, false); store.setDefault(PreferenceConstants.DATA_FORMAT, "#0.00"); store.setDefault(PreferenceConstants.PLAY_SPEED, 1500); store.setDefault(PreferenceConstants.SIDEPLOTTER1D_USE_LOG_Y, DEFAULT_SIDEPLOTTER1D_USE_LOG); store.setDefault(PreferenceConstants.GRIDSCAN_RESOLUTION_X, DEFAULT_GRIDSCAN_RESOLUTION); store.setDefault(PreferenceConstants.GRIDSCAN_RESOLUTION_Y, DEFAULT_GRIDSCAN_RESOLUTION); store.setDefault(PreferenceConstants.GRIDSCAN_BEAMLINE_POSX, DEFAULT_GRIDSCAN_BEAMLINE_POSITION); store.setDefault(PreferenceConstants.GRIDSCAN_BEAMLINE_POSX, DEFAULT_GRIDSCAN_BEAMLINE_POSITION); store.setDefault(PreferenceConstants.DIFFRACTION_VIEWER_PEAK_TYPE, DEFAULT_DIFFRACTION_PEAK); store.setDefault(PreferenceConstants.DIFFRACTION_VIEWER_MAX_PEAK_NUM, DEFAULT_MAX_NUM_PEAKS); store.setDefault(PreferenceConstants.DIFFRACTION_VIEWER_STANDARD_NAME, DEFAULT_STANDARD_NAME); store.setDefault(PreferenceConstants.DIFFRACTION_VIEWER_STANDARD_NAME_LIST, DEFAULT_STANDARD_NAME_LIST); store.setDefault(PreferenceConstants.DIFFRACTION_VIEWER_STANDARD_DISTANCES,DEFAULT_STANDARD_DISTANCES); store.setDefault(PreferenceConstants.DIFFRACTION_VIEWER_STANDARD_DISTANCES_LIST, DEFAULT_STANDARD_DISTANCES_LIST); store.setDefault(PreferenceConstants.DIFFRACTION_VIEWER_PIXELOVERLOAD_THRESHOLD, DEFAULT_PIXELOVERLOAD_THRESHOLD); store.setDefault(PreferenceConstants.DIFFRACTION_VIEWER_AUTOSTOPPING,DEFAULT_DIFFRACTION_VIEWER_AUTOSTOPPING); store.setDefault(PreferenceConstants.DIFFRACTION_VIEWER_STOPPING_THRESHOLD,DEFAULT_DIFFRACTION_VIEWER_STOPPING_THRESHOLD); store.setDefault(PreferenceConstants.FITTING_1D_PEAKTYPE,DEFAULT_FITTING_1D_PEAKTYPE); store.setDefault(PreferenceConstants.FITTING_1D_PEAKLIST,DEFAULT_FITTING_1D_PEAKLIST); store.setDefault(PreferenceConstants.FITTING_1D_PEAK_NUM, DEFAULT_FITTING_1D_PEAK_NUM); store.setDefault(PreferenceConstants.FITTING_1D_ALG_TYPE,DEFAULT_FITTING_1D_ALG_TYPE); store.setDefault(PreferenceConstants.FITTING_1D_ALG_LIST,DEFAULT_FITTING_1D_ALG_LIST); store.setDefault(PreferenceConstants.FITTING_1D_SMOOTHING_VALUE,DEFAULT_FITTING_1D_ALG_SMOOTHING); store.setDefault(PreferenceConstants.FITTING_1D_ALG_ACCURACY,DEFAULT_FITTING_1D_ALG_ACCURACY); store.setDefault(PreferenceConstants.FITTING_1D_AUTO_SMOOTHING, DEFAULT_FITTING_1D_AUTO_SMOOTHING); store.setDefault(PreferenceConstants.FITTING_1D_AUTO_STOPPING,DEFAULT_FITTING_1D_AUTO_STOPPING); store.setDefault(PreferenceConstants.FITTING_1D_THRESHOLD,DEFAULT_FITTING_1D_THRESHOLD); store.setDefault(PreferenceConstants.FITTING_1D_THRESHOLD_MEASURE,DEFAULT_FITTING_1D_THRESHOLD_MEASURE); store.setDefault(PreferenceConstants.FITTING_1D_THRESHOLD_MEASURE_LIST,DEFAULT_FITTING_1D_THRESHOLD_MEASURE_LIST); store.setDefault(PreferenceConstants.FITTING_1D_DECIMAL_PLACES,DEFAULT_FITTING_1D_DECIMAL_PLACES); store.setDefault(PreferenceConstants.PLOT_VIEWER_PLOT2D_COLOURMAP,DEFAULT_COLOURMAP_CHOICE); store.setDefault(PreferenceConstants.PLOT_VIEWER_PLOT2D_CMAP_EXPERT,DEFAULT_COLOURMAP_EXPERT); store.setDefault(PreferenceConstants.PLOT_VIEWER_PLOT2D_AUTOHISTO,DEFAULT_AUTOHISTOGRAM); store.setDefault(PreferenceConstants.PLOT_VIEWER_PLOT2D_SCALING, DEFAULT_COLOURSCALE_CHOICE); store.setDefault(PreferenceConstants.PLOT_VIEWER_PLOT2D_SHOWSCROLLBAR,DEFAULT_SHOW_SCROLLBARS); store.setDefault(PreferenceConstants.PLOT_VIEWER_MULTI1D_CAMERA_PROJ, DEFAULT_CAMERA_PROJECTION); store.setDefault(PreferenceConstants.IMAGEEXPLORER_COLOURMAP, DEFAULT_IMAGEXPLORER_COLOURMAP_CHOICE); store.setDefault(PreferenceConstants.IMAGEEXPLORER_HISTOGRAMAUTOSCALETHRESHOLD, DEFAULT_IMAGEEXPLORER_HISTOGRAM_SCALE); store.setDefault(PreferenceConstants.IMAGEEXPLORER_TIMEDELAYBETWEENIMAGES, DEFAULT_IMAGEEXPLORER_TIMEDEAY); store.setDefault(PreferenceConstants.IMAGEEXPLORER_PLAYBACKVIEW, DEFAULT_IMAGEEXPLORER_PLAYBACKVIEW); store.setDefault(PreferenceConstants.IMAGEEXPLORER_PLAYBACKRATE,DEFAULT_IMAGEEXPLORER_PLAYBACKRATE); store.setDefault(PreferenceConstants.ANALYSIS_RPC_SERVER_PORT,DEFAULT_ANALYSIS_RPC_SERVER_PORT); store.setDefault(PreferenceConstants.ANALYSIS_RPC_TEMP_FILE_LOCATION,DEFAULT_ANALYSIS_RPC_TEMP_FILE_LOCATION); store.setDefault(PreferenceConstants.RMI_SERVER_PORT,DEFAULT_RMI_SERVER_PORT); store.setDefault(PreferenceConstants.PRINTSETTINGS_PRINTER_NAME,DEFAULT_PRINTSETTINGS_PRINTNAME); store.setDefault(PreferenceConstants.PRINTSETTINGS_SCALE,DEFAULT_PRINTSETTINGS_SCALE); store.setDefault(PreferenceConstants.PRINTSETTINGS_RESOLUTION,DEFAULT_PRINTSETTINGS_RESOLUTION); store.setDefault(PreferenceConstants.PRINTSETTINGS_ORIENTATION,DEFAULT_PRINTSETTINGS_ORIENTATION); }
public void initializeDefaultPreferences() { IPreferenceStore store = AnalysisRCPActivator.getDefault().getPreferenceStore(); store.setDefault(PreferenceConstants.IGNORE_DATASET_FILTERS, false); store.setDefault(PreferenceConstants.SHOW_XY_COLUMN, false); store.setDefault(PreferenceConstants.SHOW_DATA_SIZE, false); store.setDefault(PreferenceConstants.SHOW_DIMS, false); store.setDefault(PreferenceConstants.SHOW_SHAPE, false); store.setDefault(PreferenceConstants.DATA_FORMAT, "#0.00"); store.setDefault(PreferenceConstants.PLAY_SPEED, 1500); store.setDefault(PreferenceConstants.SIDEPLOTTER1D_USE_LOG_Y, DEFAULT_SIDEPLOTTER1D_USE_LOG); store.setDefault(PreferenceConstants.GRIDSCAN_RESOLUTION_X, DEFAULT_GRIDSCAN_RESOLUTION); store.setDefault(PreferenceConstants.GRIDSCAN_RESOLUTION_Y, DEFAULT_GRIDSCAN_RESOLUTION); store.setDefault(PreferenceConstants.GRIDSCAN_BEAMLINE_POSX, DEFAULT_GRIDSCAN_BEAMLINE_POSITION); store.setDefault(PreferenceConstants.GRIDSCAN_BEAMLINE_POSX, DEFAULT_GRIDSCAN_BEAMLINE_POSITION); store.setDefault(PreferenceConstants.DIFFRACTION_VIEWER_PEAK_TYPE, DEFAULT_DIFFRACTION_PEAK); store.setDefault(PreferenceConstants.DIFFRACTION_VIEWER_MAX_PEAK_NUM, DEFAULT_MAX_NUM_PEAKS); store.setDefault(PreferenceConstants.DIFFRACTION_VIEWER_STANDARD_NAME, DEFAULT_STANDARD_NAME); store.setDefault(PreferenceConstants.DIFFRACTION_VIEWER_STANDARD_NAME_LIST, DEFAULT_STANDARD_NAME_LIST); store.setDefault(PreferenceConstants.DIFFRACTION_VIEWER_STANDARD_DISTANCES,DEFAULT_STANDARD_DISTANCES); store.setDefault(PreferenceConstants.DIFFRACTION_VIEWER_STANDARD_DISTANCES_LIST, DEFAULT_STANDARD_DISTANCES_LIST); store.setDefault(PreferenceConstants.DIFFRACTION_VIEWER_PIXELOVERLOAD_THRESHOLD, DEFAULT_PIXELOVERLOAD_THRESHOLD); store.setDefault(PreferenceConstants.DIFFRACTION_VIEWER_AUTOSTOPPING,DEFAULT_DIFFRACTION_VIEWER_AUTOSTOPPING); store.setDefault(PreferenceConstants.DIFFRACTION_VIEWER_STOPPING_THRESHOLD,DEFAULT_DIFFRACTION_VIEWER_STOPPING_THRESHOLD); store.setDefault(PreferenceConstants.FITTING_1D_PEAKTYPE,DEFAULT_FITTING_1D_PEAKTYPE); store.setDefault(PreferenceConstants.FITTING_1D_PEAKLIST,DEFAULT_FITTING_1D_PEAKLIST); store.setDefault(PreferenceConstants.FITTING_1D_PEAK_NUM, DEFAULT_FITTING_1D_PEAK_NUM); store.setDefault(PreferenceConstants.FITTING_1D_ALG_TYPE,DEFAULT_FITTING_1D_ALG_TYPE); store.setDefault(PreferenceConstants.FITTING_1D_ALG_LIST,DEFAULT_FITTING_1D_ALG_LIST); store.setDefault(PreferenceConstants.FITTING_1D_SMOOTHING_VALUE,DEFAULT_FITTING_1D_ALG_SMOOTHING); store.setDefault(PreferenceConstants.FITTING_1D_ALG_ACCURACY,DEFAULT_FITTING_1D_ALG_ACCURACY); store.setDefault(PreferenceConstants.FITTING_1D_AUTO_SMOOTHING, DEFAULT_FITTING_1D_AUTO_SMOOTHING); store.setDefault(PreferenceConstants.FITTING_1D_AUTO_STOPPING,DEFAULT_FITTING_1D_AUTO_STOPPING); store.setDefault(PreferenceConstants.FITTING_1D_THRESHOLD,DEFAULT_FITTING_1D_THRESHOLD); store.setDefault(PreferenceConstants.FITTING_1D_THRESHOLD_MEASURE,DEFAULT_FITTING_1D_THRESHOLD_MEASURE); store.setDefault(PreferenceConstants.FITTING_1D_THRESHOLD_MEASURE_LIST,DEFAULT_FITTING_1D_THRESHOLD_MEASURE_LIST); store.setDefault(PreferenceConstants.FITTING_1D_DECIMAL_PLACES,DEFAULT_FITTING_1D_DECIMAL_PLACES); store.setDefault(PreferenceConstants.PLOT_VIEWER_PLOT2D_COLOURMAP,DEFAULT_COLOURMAP_CHOICE); store.setDefault(PreferenceConstants.PLOT_VIEWER_PLOT2D_CMAP_EXPERT,DEFAULT_COLOURMAP_EXPERT); store.setDefault(PreferenceConstants.PLOT_VIEWER_PLOT2D_AUTOHISTO,DEFAULT_AUTOHISTOGRAM); store.setDefault(PreferenceConstants.PLOT_VIEWER_PLOT2D_SCALING, DEFAULT_COLOURSCALE_CHOICE); store.setDefault(PreferenceConstants.PLOT_VIEWER_PLOT2D_SHOWSCROLLBAR,DEFAULT_SHOW_SCROLLBARS); store.setDefault(PreferenceConstants.PLOT_VIEWER_MULTI1D_CAMERA_PROJ, DEFAULT_CAMERA_PROJECTION); store.setDefault(PreferenceConstants.IMAGEEXPLORER_COLOURMAP, DEFAULT_IMAGEXPLORER_COLOURMAP_CHOICE); store.setDefault(PreferenceConstants.IMAGEEXPLORER_HISTOGRAMAUTOSCALETHRESHOLD, DEFAULT_IMAGEEXPLORER_HISTOGRAM_SCALE); store.setDefault(PreferenceConstants.IMAGEEXPLORER_TIMEDELAYBETWEENIMAGES, DEFAULT_IMAGEEXPLORER_TIMEDEAY); store.setDefault(PreferenceConstants.IMAGEEXPLORER_PLAYBACKVIEW, DEFAULT_IMAGEEXPLORER_PLAYBACKVIEW); store.setDefault(PreferenceConstants.IMAGEEXPLORER_PLAYBACKRATE,DEFAULT_IMAGEEXPLORER_PLAYBACKRATE); store.setDefault(PreferenceConstants.ANALYSIS_RPC_SERVER_PORT, DEFAULT_ANALYSIS_RPC_SERVER_PORT); store.setDefault(PreferenceConstants.ANALYSIS_RPC_TEMP_FILE_LOCATION, DEFAULT_ANALYSIS_RPC_TEMP_FILE_LOCATION); store.setDefault(PreferenceConstants.RMI_SERVER_PORT, DEFAULT_RMI_SERVER_PORT); store.setDefault(PreferenceConstants.PRINTSETTINGS_PRINTER_NAME,DEFAULT_PRINTSETTINGS_PRINTNAME); store.setDefault(PreferenceConstants.PRINTSETTINGS_SCALE,DEFAULT_PRINTSETTINGS_SCALE); store.setDefault(PreferenceConstants.PRINTSETTINGS_RESOLUTION,DEFAULT_PRINTSETTINGS_RESOLUTION); store.setDefault(PreferenceConstants.PRINTSETTINGS_ORIENTATION,DEFAULT_PRINTSETTINGS_ORIENTATION); }
diff --git a/uk.ac.diamond.scisoft.analysis/src/uk/ac/diamond/scisoft/analysis/image/AlignImages.java b/uk.ac.diamond.scisoft.analysis/src/uk/ac/diamond/scisoft/analysis/image/AlignImages.java index f0a92a9fe..8c54699fa 100644 --- a/uk.ac.diamond.scisoft.analysis/src/uk/ac/diamond/scisoft/analysis/image/AlignImages.java +++ b/uk.ac.diamond.scisoft.analysis/src/uk/ac/diamond/scisoft/analysis/image/AlignImages.java @@ -1,100 +1,95 @@ /* * Copyright 2011 Diamond Light Source Ltd. * * 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.ac.diamond.scisoft.analysis.image; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.ac.diamond.scisoft.analysis.dataset.AbstractDataset; import uk.ac.diamond.scisoft.analysis.dataset.Image; import uk.ac.diamond.scisoft.analysis.dataset.function.MapToShiftedCartesian; import uk.ac.diamond.scisoft.analysis.io.LoaderFactory; import uk.ac.diamond.scisoft.analysis.roi.RectangularROI; public class AlignImages { private static final Logger logger = LoggerFactory.getLogger(AlignImages.class); /** * Align images * @param images datasets * @param shifted images * @param roi * @param fromStart direction of image alignment: should currently be set to true * (the method needs to be re-modified to take into account the flip mode) * @param preShift * @return shifts */ public static List<double[]> align(final AbstractDataset[] images, final List<AbstractDataset> shifted, final RectangularROI roi, final boolean fromStart, double[] preShift) { List<AbstractDataset> list = new ArrayList<AbstractDataset>(); Collections.addAll(list, images); if (!fromStart) { Collections.reverse(list); } final AbstractDataset anchor = list.get(0); final int length = list.size(); final List<double[]> shift = new ArrayList<double[]>(); - if(preShift!=null){ + if (preShift != null) { shift.add(preShift); }else{ shift.add(new double[] {0., 0.}); } shifted.add(anchor); for (int i = 1; i < length; i++) { AbstractDataset image = list.get(i); double[] s = Image.findTranslation2D(anchor, image, roi); - // We add the preShift to the shift data - if (preShift != null) { - s[0] += preShift[0]; - s[1] += preShift[1]; - } shift.add(s); MapToShiftedCartesian map = new MapToShiftedCartesian(s[0], s[1]); shifted.add(map.value(image).get(0)); } return shift; } /** * Align images * @param files * @param shifted images * @param roi * @param fromStart * @param preShift * @return shifts */ public static List<double[]> align(final String[] files, final List<AbstractDataset> shifted, final RectangularROI roi, final boolean fromStart, final double[] preShift) { AbstractDataset[] images = new AbstractDataset[files.length]; for (int i = 0; i < files.length; i++) { try { images[i] = LoaderFactory.getData(files[i], false, null).getDataset(0); } catch (Exception e) { logger.error("Cannot load file {}", files[i]); throw new IllegalArgumentException("Cannot load file " + files[i]); } } return align(images, shifted, roi, fromStart, preShift); } }
false
true
public static List<double[]> align(final AbstractDataset[] images, final List<AbstractDataset> shifted, final RectangularROI roi, final boolean fromStart, double[] preShift) { List<AbstractDataset> list = new ArrayList<AbstractDataset>(); Collections.addAll(list, images); if (!fromStart) { Collections.reverse(list); } final AbstractDataset anchor = list.get(0); final int length = list.size(); final List<double[]> shift = new ArrayList<double[]>(); if(preShift!=null){ shift.add(preShift); }else{ shift.add(new double[] {0., 0.}); } shifted.add(anchor); for (int i = 1; i < length; i++) { AbstractDataset image = list.get(i); double[] s = Image.findTranslation2D(anchor, image, roi); // We add the preShift to the shift data if (preShift != null) { s[0] += preShift[0]; s[1] += preShift[1]; } shift.add(s); MapToShiftedCartesian map = new MapToShiftedCartesian(s[0], s[1]); shifted.add(map.value(image).get(0)); } return shift; }
public static List<double[]> align(final AbstractDataset[] images, final List<AbstractDataset> shifted, final RectangularROI roi, final boolean fromStart, double[] preShift) { List<AbstractDataset> list = new ArrayList<AbstractDataset>(); Collections.addAll(list, images); if (!fromStart) { Collections.reverse(list); } final AbstractDataset anchor = list.get(0); final int length = list.size(); final List<double[]> shift = new ArrayList<double[]>(); if (preShift != null) { shift.add(preShift); }else{ shift.add(new double[] {0., 0.}); } shifted.add(anchor); for (int i = 1; i < length; i++) { AbstractDataset image = list.get(i); double[] s = Image.findTranslation2D(anchor, image, roi); shift.add(s); MapToShiftedCartesian map = new MapToShiftedCartesian(s[0], s[1]); shifted.add(map.value(image).get(0)); } return shift; }
diff --git a/src/test/cli/cloudify/StockDemoApplicationTest.java b/src/test/cli/cloudify/StockDemoApplicationTest.java index 5a2cce52..887e1f23 100644 --- a/src/test/cli/cloudify/StockDemoApplicationTest.java +++ b/src/test/cli/cloudify/StockDemoApplicationTest.java @@ -1,58 +1,58 @@ package test.cli.cloudify; import org.openspaces.admin.gsc.GridServiceContainer; import org.openspaces.admin.pu.DeploymentStatus; import org.testng.annotations.Test; import com.gigaspaces.cloudify.dsl.utils.ServiceUtils; import framework.tools.SGTestHelper; import framework.utils.LogUtils; public class StockDemoApplicationTest extends AbstractLocalCloudTest { private String STOCK_DEMO_APPLICATION_NAME = "stockdemo"; @Test(timeOut = DEFAULT_TEST_TIMEOUT * 2, enabled = true) public void testStockdemoApplication() throws Exception { String applicationDir = SGTestHelper.getSGTestRootDir() + "/apps/USM/usm/applications/stockdemo"; String command = "connect " + restUrl + ";" + "install-application " + "--verbose -timeout 25 " + applicationDir; CommandTestUtils.runCommandAndWait(command); assertTrue(STOCK_DEMO_APPLICATION_NAME + " is not installed" , admin.getApplications().getApplication("stockdemo") != null); int currentNumberOfInstances; currentNumberOfInstances = getProcessingUnitInstanceCount(ServiceUtils.getAbsolutePUName(STOCK_DEMO_APPLICATION_NAME, "cassandra")); assertTrue("Expected 2 PU instances. Actual number of instances is " + currentNumberOfInstances, currentNumberOfInstances == 1); assertPuStatusInstact("stockdemo.cassandra"); currentNumberOfInstances = getProcessingUnitInstanceCount(ServiceUtils.getAbsolutePUName(STOCK_DEMO_APPLICATION_NAME, "stockAnalyticsMirror")); assertTrue("Expected 1 PU instances. Actual number of instances is " + currentNumberOfInstances, currentNumberOfInstances == 1); assertPuStatusInstact("stockdemo.stockAnalyticsMirror"); currentNumberOfInstances = getProcessingUnitInstanceCount(ServiceUtils.getAbsolutePUName(STOCK_DEMO_APPLICATION_NAME, "stockAnalyticsSpace")); - assertTrue("Expected 1 PU instances. Actual number of instances is " + currentNumberOfInstances, currentNumberOfInstances == 2); + assertTrue("Expected 2 PU instances. Actual number of instances is " + currentNumberOfInstances, currentNumberOfInstances == 2); assertPuStatusInstact("stockdemo.stockAnalyticsSpace"); currentNumberOfInstances = getProcessingUnitInstanceCount(ServiceUtils.getAbsolutePUName(STOCK_DEMO_APPLICATION_NAME, "stockAnalyticsProcessor")); - assertTrue("Expected 1 PU instances. Actual number of instances is " + currentNumberOfInstances, currentNumberOfInstances == 4); + assertTrue("Expected 2 PU instances. Actual number of instances is " + currentNumberOfInstances, currentNumberOfInstances == 2); assertPuStatusInstact("stockdemo.stockAnalyticsProcessor"); currentNumberOfInstances = getProcessingUnitInstanceCount(ServiceUtils.getAbsolutePUName(STOCK_DEMO_APPLICATION_NAME, "StockDemo")); assertTrue("Expected 1 PU instances. Actual number of instances is " + currentNumberOfInstances, currentNumberOfInstances == 1); assertPuStatusInstact("stockdemo.StockDemo"); currentNumberOfInstances = getProcessingUnitInstanceCount(ServiceUtils.getAbsolutePUName(STOCK_DEMO_APPLICATION_NAME, "stockAnalytics")); assertTrue("Expected 1 PU instances. Actual number of instances is " + currentNumberOfInstances, currentNumberOfInstances == 1); assertPuStatusInstact("stockdemo.stockAnalytics"); for (GridServiceContainer gsc : admin.getGridServiceContainers().getContainers()) { LogUtils.scanContainerLogsFor(gsc, "[SEVERE]"); } } private void assertPuStatusInstact(String puName) { assertTrue(admin.getProcessingUnits().getProcessingUnit(puName).getStatus().equals(DeploymentStatus.INTACT)); } }
false
true
public void testStockdemoApplication() throws Exception { String applicationDir = SGTestHelper.getSGTestRootDir() + "/apps/USM/usm/applications/stockdemo"; String command = "connect " + restUrl + ";" + "install-application " + "--verbose -timeout 25 " + applicationDir; CommandTestUtils.runCommandAndWait(command); assertTrue(STOCK_DEMO_APPLICATION_NAME + " is not installed" , admin.getApplications().getApplication("stockdemo") != null); int currentNumberOfInstances; currentNumberOfInstances = getProcessingUnitInstanceCount(ServiceUtils.getAbsolutePUName(STOCK_DEMO_APPLICATION_NAME, "cassandra")); assertTrue("Expected 2 PU instances. Actual number of instances is " + currentNumberOfInstances, currentNumberOfInstances == 1); assertPuStatusInstact("stockdemo.cassandra"); currentNumberOfInstances = getProcessingUnitInstanceCount(ServiceUtils.getAbsolutePUName(STOCK_DEMO_APPLICATION_NAME, "stockAnalyticsMirror")); assertTrue("Expected 1 PU instances. Actual number of instances is " + currentNumberOfInstances, currentNumberOfInstances == 1); assertPuStatusInstact("stockdemo.stockAnalyticsMirror"); currentNumberOfInstances = getProcessingUnitInstanceCount(ServiceUtils.getAbsolutePUName(STOCK_DEMO_APPLICATION_NAME, "stockAnalyticsSpace")); assertTrue("Expected 1 PU instances. Actual number of instances is " + currentNumberOfInstances, currentNumberOfInstances == 2); assertPuStatusInstact("stockdemo.stockAnalyticsSpace"); currentNumberOfInstances = getProcessingUnitInstanceCount(ServiceUtils.getAbsolutePUName(STOCK_DEMO_APPLICATION_NAME, "stockAnalyticsProcessor")); assertTrue("Expected 1 PU instances. Actual number of instances is " + currentNumberOfInstances, currentNumberOfInstances == 4); assertPuStatusInstact("stockdemo.stockAnalyticsProcessor"); currentNumberOfInstances = getProcessingUnitInstanceCount(ServiceUtils.getAbsolutePUName(STOCK_DEMO_APPLICATION_NAME, "StockDemo")); assertTrue("Expected 1 PU instances. Actual number of instances is " + currentNumberOfInstances, currentNumberOfInstances == 1); assertPuStatusInstact("stockdemo.StockDemo"); currentNumberOfInstances = getProcessingUnitInstanceCount(ServiceUtils.getAbsolutePUName(STOCK_DEMO_APPLICATION_NAME, "stockAnalytics")); assertTrue("Expected 1 PU instances. Actual number of instances is " + currentNumberOfInstances, currentNumberOfInstances == 1); assertPuStatusInstact("stockdemo.stockAnalytics"); for (GridServiceContainer gsc : admin.getGridServiceContainers().getContainers()) { LogUtils.scanContainerLogsFor(gsc, "[SEVERE]"); } }
public void testStockdemoApplication() throws Exception { String applicationDir = SGTestHelper.getSGTestRootDir() + "/apps/USM/usm/applications/stockdemo"; String command = "connect " + restUrl + ";" + "install-application " + "--verbose -timeout 25 " + applicationDir; CommandTestUtils.runCommandAndWait(command); assertTrue(STOCK_DEMO_APPLICATION_NAME + " is not installed" , admin.getApplications().getApplication("stockdemo") != null); int currentNumberOfInstances; currentNumberOfInstances = getProcessingUnitInstanceCount(ServiceUtils.getAbsolutePUName(STOCK_DEMO_APPLICATION_NAME, "cassandra")); assertTrue("Expected 2 PU instances. Actual number of instances is " + currentNumberOfInstances, currentNumberOfInstances == 1); assertPuStatusInstact("stockdemo.cassandra"); currentNumberOfInstances = getProcessingUnitInstanceCount(ServiceUtils.getAbsolutePUName(STOCK_DEMO_APPLICATION_NAME, "stockAnalyticsMirror")); assertTrue("Expected 1 PU instances. Actual number of instances is " + currentNumberOfInstances, currentNumberOfInstances == 1); assertPuStatusInstact("stockdemo.stockAnalyticsMirror"); currentNumberOfInstances = getProcessingUnitInstanceCount(ServiceUtils.getAbsolutePUName(STOCK_DEMO_APPLICATION_NAME, "stockAnalyticsSpace")); assertTrue("Expected 2 PU instances. Actual number of instances is " + currentNumberOfInstances, currentNumberOfInstances == 2); assertPuStatusInstact("stockdemo.stockAnalyticsSpace"); currentNumberOfInstances = getProcessingUnitInstanceCount(ServiceUtils.getAbsolutePUName(STOCK_DEMO_APPLICATION_NAME, "stockAnalyticsProcessor")); assertTrue("Expected 2 PU instances. Actual number of instances is " + currentNumberOfInstances, currentNumberOfInstances == 2); assertPuStatusInstact("stockdemo.stockAnalyticsProcessor"); currentNumberOfInstances = getProcessingUnitInstanceCount(ServiceUtils.getAbsolutePUName(STOCK_DEMO_APPLICATION_NAME, "StockDemo")); assertTrue("Expected 1 PU instances. Actual number of instances is " + currentNumberOfInstances, currentNumberOfInstances == 1); assertPuStatusInstact("stockdemo.StockDemo"); currentNumberOfInstances = getProcessingUnitInstanceCount(ServiceUtils.getAbsolutePUName(STOCK_DEMO_APPLICATION_NAME, "stockAnalytics")); assertTrue("Expected 1 PU instances. Actual number of instances is " + currentNumberOfInstances, currentNumberOfInstances == 1); assertPuStatusInstact("stockdemo.stockAnalytics"); for (GridServiceContainer gsc : admin.getGridServiceContainers().getContainers()) { LogUtils.scanContainerLogsFor(gsc, "[SEVERE]"); } }
diff --git a/trunk/java/com/tigervnc/rfb/TightDecoder.java b/trunk/java/com/tigervnc/rfb/TightDecoder.java index 2b97110d..38d63626 100644 --- a/trunk/java/com/tigervnc/rfb/TightDecoder.java +++ b/trunk/java/com/tigervnc/rfb/TightDecoder.java @@ -1,338 +1,338 @@ /* Copyright (C) 2000-2003 Constantin Kaplinsky. All Rights Reserved. * Copyright 2004-2005 Cendio AB. * * This is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this software; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, * USA. */ package com.tigervnc.rfb; import com.tigervnc.rdr.InStream; import com.tigervnc.rdr.ZlibInStream; import java.util.ArrayList; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import javax.imageio.ImageIO; public class TightDecoder extends Decoder { final static int TIGHT_MAX_WIDTH = 2048; // Compression control final static int rfbTightExplicitFilter = 0x04; final static int rfbTightFill = 0x08; final static int rfbTightJpeg = 0x09; final static int rfbTightMaxSubencoding = 0x09; // Filters to improve compression efficiency final static int rfbTightFilterCopy = 0x00; final static int rfbTightFilterPalette = 0x01; final static int rfbTightFilterGradient = 0x02; final static int rfbTightMinToCompress = 12; public TightDecoder(CMsgReader reader_) { reader = reader_; zis = new ZlibInStream[4]; for (int i = 0; i < 4; i++) zis[i] = new ZlibInStream(); } public void readRect(Rect r, CMsgHandler handler) { InStream is = reader.getInStream(); int[] buf = reader.getImageBuf(r.width() * r.height()); boolean cutZeros = false; PixelFormat myFormat = handler.cp.pf(); int bpp = handler.cp.pf().bpp; if (bpp == 32) { if (myFormat.is888()) { cutZeros = true; } } int comp_ctl = is.readU8(); boolean bigEndian = handler.cp.pf().bigEndian; // Flush zlib streams if we are told by the server to do so. for (int i = 0; i < 4; i++) { if ((comp_ctl & 1) != 0) { zis[i].reset(); } comp_ctl >>= 1; } // "Fill" compression type. if (comp_ctl == rfbTightFill) { int pix; if (cutZeros) { - pix = is.readPixel(3, false); + pix = is.readPixel(3, !bigEndian); } else { pix = (bpp == 8) ? is.readOpaque8() : is.readOpaque24B(); } handler.fillRect(r, pix); return; } // "JPEG" compression type. if (comp_ctl == rfbTightJpeg) { // Read length int compressedLen = is.readCompactLength(); if (compressedLen <= 0) vlog.info("Incorrect data received from the server."); // Allocate netbuf and read in data byte[] netbuf = new byte[compressedLen]; is.readBytes(netbuf, 0, compressedLen); // Create an Image object from the JPEG data. BufferedImage jpeg = new BufferedImage(r.width(), r.height(), BufferedImage.TYPE_4BYTE_ABGR_PRE); jpeg.setAccelerationPriority(1); try { jpeg = ImageIO.read(new ByteArrayInputStream(netbuf)); } catch (java.io.IOException e) { e.printStackTrace(); } jpeg.getRGB(0, 0, r.width(), r.height(), buf, 0, r.width()); handler.imageRect(r, buf); return; } // Quit on unsupported compression type. if (comp_ctl > rfbTightMaxSubencoding) { throw new Exception("TightDecoder: bad subencoding value received"); } // "Basic" compression type. int palSize = 0; int[] palette = new int[256]; boolean useGradient = false; if ((comp_ctl & rfbTightExplicitFilter) != 0) { int filterId = is.readU8(); switch (filterId) { case rfbTightFilterPalette: palSize = is.readU8() + 1; if (cutZeros) { - is.readPixels(palette, palSize, 3, false); + is.readPixels(palette, palSize, 3, !bigEndian); } else { for (int i = 0; i < palSize; i++) { palette[i] = (bpp == 8) ? is.readOpaque8() : is.readOpaque24B(); } } break; case rfbTightFilterGradient: useGradient = true; break; case rfbTightFilterCopy: break; default: throw new Exception("TightDecoder: unknown filter code recieved"); } } int bppp = bpp; if (palSize != 0) { bppp = (palSize <= 2) ? 1 : 8; } else if (cutZeros) { bppp = 24; } // Determine if the data should be decompressed or just copied. int rowSize = (r.width() * bppp + 7) / 8; int dataSize = r.height() * rowSize; int streamId = -1; InStream input; if (dataSize < rfbTightMinToCompress) { input = is; } else { int length = is.readCompactLength(); streamId = comp_ctl & 0x03; zis[streamId].setUnderlying(is, length); input = (ZlibInStream)zis[streamId]; } if (palSize == 0) { // Truecolor data. if (useGradient) { vlog.info("useGradient"); if (bpp == 32 && cutZeros) { vlog.info("FilterGradient24"); FilterGradient24(r, input, dataSize, buf, handler); } else { vlog.info("FilterGradient"); FilterGradient(r, input, dataSize, buf, handler); } } else { if (cutZeros) { - input.readPixels(buf, r.area(), 3, false); + input.readPixels(buf, r.area(), 3, !bigEndian); } else { for (int ptr=0; ptr < dataSize; ptr++) buf[ptr] = input.readU8(); } } } else { int x, y, b; int ptr = 0; int bits; if (palSize <= 2) { // 2-color palette for (y = 0; y < r.height(); y++) { for (x = 0; x < r.width() / 8; x++) { bits = input.readU8(); for(b = 7; b >= 0; b--) { buf[ptr++] = palette[bits >> b & 1]; } } if (r.width() % 8 != 0) { bits = input.readU8(); for (b = 7; b >= 8 - r.width() % 8; b--) { buf[ptr++] = palette[bits >> b & 1]; } } } } else { // 256-color palette for (y = 0; y < r.height(); y++) { for (x = 0; x < r.width(); x++) { buf[ptr++] = palette[input.readU8()]; } } } } handler.imageRect(r, buf); if (streamId != -1) { zis[streamId].reset(); } } private CMsgReader reader; private ZlibInStream[] zis; static LogWriter vlog = new LogWriter("TightDecoder"); // // Decode data processed with the "Gradient" filter. // final private void FilterGradient24(Rect r, InStream is, int dataSize, int[] buf, CMsgHandler handler) { int x, y, c; int[] prevRow = new int[TIGHT_MAX_WIDTH * 3]; int[] thisRow = new int[TIGHT_MAX_WIDTH * 3]; int[] pix = new int[3]; int[] est = new int[3]; PixelFormat myFormat = handler.cp.pf(); // Allocate netbuf and read in data int[] netbuf = new int[dataSize]; is.readBytes(netbuf, 0, dataSize); int rectHeight = r.height(); int rectWidth = r.width(); for (y = 0; y < rectHeight; y++) { /* First pixel in a row */ for (c = 0; c < 3; c++) { pix[c] = netbuf[y*rectWidth*3+c] + prevRow[c]; thisRow[c] = pix[c]; } if (myFormat.bigEndian) { buf[y*rectWidth] = 0xff000000 | (pix[2] & 0xff)<<16 | (pix[1] & 0xff)<<8 | (pix[0] & 0xff); } else { buf[y*rectWidth] = 0xff000000 | (pix[0] & 0xff)<<16 | (pix[1] & 0xff)<<8 | (pix[2] & 0xff); } /* Remaining pixels of a row */ for (x = 1; x < rectWidth; x++) { for (c = 0; c < 3; c++) { est[c] = prevRow[x*3+c] + pix[c] - prevRow[(x-1)*3+c]; if (est[c] > 0xFF) { est[c] = 0xFF; } else if (est[c] < 0) { est[c] = 0; } pix[c] = netbuf[(y*rectWidth+x)*3+c] + est[c]; thisRow[x*3+c] = pix[c]; } if (myFormat.bigEndian) { buf[y*rectWidth+x] = 0xff000000 | (pix[2] & 0xff)<<16 | (pix[1] & 0xff)<<8 | (pix[0] & 0xff); } else { buf[y*rectWidth+x] = 0xff000000 | (pix[0] & 0xff)<<16 | (pix[1] & 0xff)<<8 | (pix[2] & 0xff); } } System.arraycopy(thisRow, 0, prevRow, 0, prevRow.length); } } final private void FilterGradient(Rect r, InStream is, int dataSize, int[] buf, CMsgHandler handler) { int x, y, c; int[] prevRow = new int[TIGHT_MAX_WIDTH]; int[] thisRow = new int[TIGHT_MAX_WIDTH]; int[] pix = new int[3]; int[] est = new int[3]; PixelFormat myFormat = handler.cp.pf(); // Allocate netbuf and read in data int[] netbuf = new int[dataSize]; is.readBytes(netbuf, 0, dataSize); int rectHeight = r.height(); int rectWidth = r.width(); for (y = 0; y < rectHeight; y++) { /* First pixel in a row */ if (myFormat.bigEndian) { buf[y*rectWidth] = 0xff000000 | (pix[2] & 0xff)<<16 | (pix[1] & 0xff)<<8 | (pix[0] & 0xff); } else { buf[y*rectWidth] = 0xff000000 | (pix[0] & 0xff)<<16 | (pix[1] & 0xff)<<8 | (pix[2] & 0xff); } for (c = 0; c < 3; c++) pix[c] += prevRow[c]; /* Remaining pixels of a row */ for (x = 1; x < rectWidth; x++) { for (c = 0; c < 3; c++) { est[c] = prevRow[x*3+c] + pix[c] - prevRow[(x-1)*3+c]; if (est[c] > 255) { est[c] = 255; } else if (est[c] < 0) { est[c] = 0; } } // FIXME? System.arraycopy(pix, 0, netbuf, 0, netbuf.length); for (c = 0; c < 3; c++) pix[c] += est[c]; System.arraycopy(thisRow, x*3, pix, 0, pix.length); if (myFormat.bigEndian) { buf[y*rectWidth+x] = 0xff000000 | (pix[2] & 0xff)<<16 | (pix[1] & 0xff)<<8 | (pix[0] & 0xff); } else { buf[y*rectWidth+x] = 0xff000000 | (pix[0] & 0xff)<<16 | (pix[1] & 0xff)<<8 | (pix[2] & 0xff); } } System.arraycopy(thisRow, 0, prevRow, 0, prevRow.length); } } }
false
true
public void readRect(Rect r, CMsgHandler handler) { InStream is = reader.getInStream(); int[] buf = reader.getImageBuf(r.width() * r.height()); boolean cutZeros = false; PixelFormat myFormat = handler.cp.pf(); int bpp = handler.cp.pf().bpp; if (bpp == 32) { if (myFormat.is888()) { cutZeros = true; } } int comp_ctl = is.readU8(); boolean bigEndian = handler.cp.pf().bigEndian; // Flush zlib streams if we are told by the server to do so. for (int i = 0; i < 4; i++) { if ((comp_ctl & 1) != 0) { zis[i].reset(); } comp_ctl >>= 1; } // "Fill" compression type. if (comp_ctl == rfbTightFill) { int pix; if (cutZeros) { pix = is.readPixel(3, false); } else { pix = (bpp == 8) ? is.readOpaque8() : is.readOpaque24B(); } handler.fillRect(r, pix); return; } // "JPEG" compression type. if (comp_ctl == rfbTightJpeg) { // Read length int compressedLen = is.readCompactLength(); if (compressedLen <= 0) vlog.info("Incorrect data received from the server."); // Allocate netbuf and read in data byte[] netbuf = new byte[compressedLen]; is.readBytes(netbuf, 0, compressedLen); // Create an Image object from the JPEG data. BufferedImage jpeg = new BufferedImage(r.width(), r.height(), BufferedImage.TYPE_4BYTE_ABGR_PRE); jpeg.setAccelerationPriority(1); try { jpeg = ImageIO.read(new ByteArrayInputStream(netbuf)); } catch (java.io.IOException e) { e.printStackTrace(); } jpeg.getRGB(0, 0, r.width(), r.height(), buf, 0, r.width()); handler.imageRect(r, buf); return; } // Quit on unsupported compression type. if (comp_ctl > rfbTightMaxSubencoding) { throw new Exception("TightDecoder: bad subencoding value received"); } // "Basic" compression type. int palSize = 0; int[] palette = new int[256]; boolean useGradient = false; if ((comp_ctl & rfbTightExplicitFilter) != 0) { int filterId = is.readU8(); switch (filterId) { case rfbTightFilterPalette: palSize = is.readU8() + 1; if (cutZeros) { is.readPixels(palette, palSize, 3, false); } else { for (int i = 0; i < palSize; i++) { palette[i] = (bpp == 8) ? is.readOpaque8() : is.readOpaque24B(); } } break; case rfbTightFilterGradient: useGradient = true; break; case rfbTightFilterCopy: break; default: throw new Exception("TightDecoder: unknown filter code recieved"); } } int bppp = bpp; if (palSize != 0) { bppp = (palSize <= 2) ? 1 : 8; } else if (cutZeros) { bppp = 24; } // Determine if the data should be decompressed or just copied. int rowSize = (r.width() * bppp + 7) / 8; int dataSize = r.height() * rowSize; int streamId = -1; InStream input; if (dataSize < rfbTightMinToCompress) { input = is; } else { int length = is.readCompactLength(); streamId = comp_ctl & 0x03; zis[streamId].setUnderlying(is, length); input = (ZlibInStream)zis[streamId]; } if (palSize == 0) { // Truecolor data. if (useGradient) { vlog.info("useGradient"); if (bpp == 32 && cutZeros) { vlog.info("FilterGradient24"); FilterGradient24(r, input, dataSize, buf, handler); } else { vlog.info("FilterGradient"); FilterGradient(r, input, dataSize, buf, handler); } } else { if (cutZeros) { input.readPixels(buf, r.area(), 3, false); } else { for (int ptr=0; ptr < dataSize; ptr++) buf[ptr] = input.readU8(); } } } else { int x, y, b; int ptr = 0; int bits; if (palSize <= 2) { // 2-color palette for (y = 0; y < r.height(); y++) { for (x = 0; x < r.width() / 8; x++) { bits = input.readU8(); for(b = 7; b >= 0; b--) { buf[ptr++] = palette[bits >> b & 1]; } } if (r.width() % 8 != 0) { bits = input.readU8(); for (b = 7; b >= 8 - r.width() % 8; b--) { buf[ptr++] = palette[bits >> b & 1]; } } } } else { // 256-color palette for (y = 0; y < r.height(); y++) { for (x = 0; x < r.width(); x++) { buf[ptr++] = palette[input.readU8()]; } } } } handler.imageRect(r, buf); if (streamId != -1) { zis[streamId].reset(); } }
public void readRect(Rect r, CMsgHandler handler) { InStream is = reader.getInStream(); int[] buf = reader.getImageBuf(r.width() * r.height()); boolean cutZeros = false; PixelFormat myFormat = handler.cp.pf(); int bpp = handler.cp.pf().bpp; if (bpp == 32) { if (myFormat.is888()) { cutZeros = true; } } int comp_ctl = is.readU8(); boolean bigEndian = handler.cp.pf().bigEndian; // Flush zlib streams if we are told by the server to do so. for (int i = 0; i < 4; i++) { if ((comp_ctl & 1) != 0) { zis[i].reset(); } comp_ctl >>= 1; } // "Fill" compression type. if (comp_ctl == rfbTightFill) { int pix; if (cutZeros) { pix = is.readPixel(3, !bigEndian); } else { pix = (bpp == 8) ? is.readOpaque8() : is.readOpaque24B(); } handler.fillRect(r, pix); return; } // "JPEG" compression type. if (comp_ctl == rfbTightJpeg) { // Read length int compressedLen = is.readCompactLength(); if (compressedLen <= 0) vlog.info("Incorrect data received from the server."); // Allocate netbuf and read in data byte[] netbuf = new byte[compressedLen]; is.readBytes(netbuf, 0, compressedLen); // Create an Image object from the JPEG data. BufferedImage jpeg = new BufferedImage(r.width(), r.height(), BufferedImage.TYPE_4BYTE_ABGR_PRE); jpeg.setAccelerationPriority(1); try { jpeg = ImageIO.read(new ByteArrayInputStream(netbuf)); } catch (java.io.IOException e) { e.printStackTrace(); } jpeg.getRGB(0, 0, r.width(), r.height(), buf, 0, r.width()); handler.imageRect(r, buf); return; } // Quit on unsupported compression type. if (comp_ctl > rfbTightMaxSubencoding) { throw new Exception("TightDecoder: bad subencoding value received"); } // "Basic" compression type. int palSize = 0; int[] palette = new int[256]; boolean useGradient = false; if ((comp_ctl & rfbTightExplicitFilter) != 0) { int filterId = is.readU8(); switch (filterId) { case rfbTightFilterPalette: palSize = is.readU8() + 1; if (cutZeros) { is.readPixels(palette, palSize, 3, !bigEndian); } else { for (int i = 0; i < palSize; i++) { palette[i] = (bpp == 8) ? is.readOpaque8() : is.readOpaque24B(); } } break; case rfbTightFilterGradient: useGradient = true; break; case rfbTightFilterCopy: break; default: throw new Exception("TightDecoder: unknown filter code recieved"); } } int bppp = bpp; if (palSize != 0) { bppp = (palSize <= 2) ? 1 : 8; } else if (cutZeros) { bppp = 24; } // Determine if the data should be decompressed or just copied. int rowSize = (r.width() * bppp + 7) / 8; int dataSize = r.height() * rowSize; int streamId = -1; InStream input; if (dataSize < rfbTightMinToCompress) { input = is; } else { int length = is.readCompactLength(); streamId = comp_ctl & 0x03; zis[streamId].setUnderlying(is, length); input = (ZlibInStream)zis[streamId]; } if (palSize == 0) { // Truecolor data. if (useGradient) { vlog.info("useGradient"); if (bpp == 32 && cutZeros) { vlog.info("FilterGradient24"); FilterGradient24(r, input, dataSize, buf, handler); } else { vlog.info("FilterGradient"); FilterGradient(r, input, dataSize, buf, handler); } } else { if (cutZeros) { input.readPixels(buf, r.area(), 3, !bigEndian); } else { for (int ptr=0; ptr < dataSize; ptr++) buf[ptr] = input.readU8(); } } } else { int x, y, b; int ptr = 0; int bits; if (palSize <= 2) { // 2-color palette for (y = 0; y < r.height(); y++) { for (x = 0; x < r.width() / 8; x++) { bits = input.readU8(); for(b = 7; b >= 0; b--) { buf[ptr++] = palette[bits >> b & 1]; } } if (r.width() % 8 != 0) { bits = input.readU8(); for (b = 7; b >= 8 - r.width() % 8; b--) { buf[ptr++] = palette[bits >> b & 1]; } } } } else { // 256-color palette for (y = 0; y < r.height(); y++) { for (x = 0; x < r.width(); x++) { buf[ptr++] = palette[input.readU8()]; } } } } handler.imageRect(r, buf); if (streamId != -1) { zis[streamId].reset(); } }
diff --git a/src/com/nextcentury/TripletExtraction/CoreNlpPOSTagger.java b/src/com/nextcentury/TripletExtraction/CoreNlpPOSTagger.java index 9c574fd..8659b4e 100644 --- a/src/com/nextcentury/TripletExtraction/CoreNlpPOSTagger.java +++ b/src/com/nextcentury/TripletExtraction/CoreNlpPOSTagger.java @@ -1,97 +1,97 @@ package com.nextcentury.TripletExtraction; import java.util.ArrayList; import java.util.List; import java.util.Properties; import org.apache.log4j.Logger; import edu.stanford.nlp.ling.CoreLabel; import edu.stanford.nlp.ling.CoreAnnotations.PartOfSpeechAnnotation; import edu.stanford.nlp.ling.CoreAnnotations.SentencesAnnotation; import edu.stanford.nlp.ling.CoreAnnotations.TokensAnnotation; import edu.stanford.nlp.pipeline.Annotation; import edu.stanford.nlp.pipeline.StanfordCoreNLP; import edu.stanford.nlp.util.CoreMap; public class CoreNlpPOSTagger{ private static Logger log = Logger.getLogger(TestDriver.class); Properties props; StanfordCoreNLP pipeline; public CoreNlpPOSTagger() { props = new Properties(); props.put("annotators", "tokenize, ssplit, pos"); pipeline = new StanfordCoreNLP(props); } public List<TaggedToken> getTaggedText(String text) { ArrayList<TaggedToken> result = new ArrayList<TaggedToken>(); Annotation document1 = new Annotation(text); pipeline.annotate(document1); List<CoreMap> sentences = document1.get(SentencesAnnotation.class); for(CoreMap sentence : sentences) { for (CoreLabel token: sentence.get(TokensAnnotation.class)) { result.add(new TaggedToken(token.get(PartOfSpeechAnnotation.class), token.toString())); } } return result; } public String getTaggedSentenceString(String text) { List<TaggedToken> tagged = getTaggedText(text); String resultString = ""; for(TaggedToken token : tagged) { resultString = resultString + "[" + token.tag + "]" + token.token + " "; } resultString = resultString.trim(); return resultString; } public List<TaggedToken[]> getTaggedSentences(String text) { ArrayList<TaggedToken> result = new ArrayList<TaggedToken>(); ArrayList<TaggedToken[]> output = new ArrayList<TaggedToken[]>(); Annotation document1 = new Annotation(text); pipeline.annotate(document1); List<CoreMap> sentences = document1.get(SentencesAnnotation.class); for(CoreMap sentence : sentences) { for (CoreLabel token: sentence.get(TokensAnnotation.class)) { result.add(new TaggedToken(token.get(PartOfSpeechAnnotation.class), token.toString())); } output.add((TaggedToken[]) result.toArray()); result.removeAll(result); } return output; } public List<String> getTaggedSentencesString(String text) { ArrayList<String> result = new ArrayList<String>(); Annotation document1 = new Annotation(text); pipeline.annotate(document1); List<CoreMap> sentences = document1.get(SentencesAnnotation.class); String resultString = ""; TaggedToken taggedToken; for(CoreMap sentence : sentences) { for (CoreLabel token: sentence.get(TokensAnnotation.class)) { taggedToken = new TaggedToken(token.get(PartOfSpeechAnnotation.class), token.toString()); - resultString += resultString + "[" + taggedToken.tag + "]" + taggedToken.token + " "; + resultString = resultString + "[" + taggedToken.tag + "]" + taggedToken.token + " "; } result.add(resultString); resultString = ""; } return result ; } }
true
true
public List<String> getTaggedSentencesString(String text) { ArrayList<String> result = new ArrayList<String>(); Annotation document1 = new Annotation(text); pipeline.annotate(document1); List<CoreMap> sentences = document1.get(SentencesAnnotation.class); String resultString = ""; TaggedToken taggedToken; for(CoreMap sentence : sentences) { for (CoreLabel token: sentence.get(TokensAnnotation.class)) { taggedToken = new TaggedToken(token.get(PartOfSpeechAnnotation.class), token.toString()); resultString += resultString + "[" + taggedToken.tag + "]" + taggedToken.token + " "; } result.add(resultString); resultString = ""; } return result ; }
public List<String> getTaggedSentencesString(String text) { ArrayList<String> result = new ArrayList<String>(); Annotation document1 = new Annotation(text); pipeline.annotate(document1); List<CoreMap> sentences = document1.get(SentencesAnnotation.class); String resultString = ""; TaggedToken taggedToken; for(CoreMap sentence : sentences) { for (CoreLabel token: sentence.get(TokensAnnotation.class)) { taggedToken = new TaggedToken(token.get(PartOfSpeechAnnotation.class), token.toString()); resultString = resultString + "[" + taggedToken.tag + "]" + taggedToken.token + " "; } result.add(resultString); resultString = ""; } return result ; }
diff --git a/tests/gov.redhawk.eclipsecorba.library.tests/src/gov/redhawk/eclipsecorba/library/tests/PreferenceNodePathSetTest.java b/tests/gov.redhawk.eclipsecorba.library.tests/src/gov/redhawk/eclipsecorba/library/tests/PreferenceNodePathSetTest.java index 29b15d5a2..ba7b9fc56 100644 --- a/tests/gov.redhawk.eclipsecorba.library.tests/src/gov/redhawk/eclipsecorba/library/tests/PreferenceNodePathSetTest.java +++ b/tests/gov.redhawk.eclipsecorba.library.tests/src/gov/redhawk/eclipsecorba/library/tests/PreferenceNodePathSetTest.java @@ -1,100 +1,100 @@ /**  * This file is protected by Copyright.   * Please refer to the COPYRIGHT file distributed with this source distribution.  *   * This file is part of REDHAWK IDE.  *   * 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. * */ // BEGIN GENERATED CODE package gov.redhawk.eclipsecorba.library.tests; import gov.redhawk.eclipsecorba.library.LibraryFactory; import gov.redhawk.eclipsecorba.library.PreferenceNodePathSet; import junit.framework.Assert; import junit.textui.TestRunner; import org.eclipse.core.runtime.preferences.InstanceScope; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.common.util.URI; /** * <!-- begin-user-doc --> * A test case for the model object '<em><b>Preference Node Path Set</b></em>'. * <!-- end-user-doc --> * @generated */ public class PreferenceNodePathSetTest extends PathTest { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static void main(String[] args) { TestRunner.run(PreferenceNodePathSetTest.class); } /** * Constructs a new Preference Node Path Set test case with the given name. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public PreferenceNodePathSetTest(String name) { super(name); } /** * Returns the fixture for this Preference Node Path Set test case. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected PreferenceNodePathSet getFixture() { return (PreferenceNodePathSet)fixture; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see junit.framework.TestCase#setUp() * @generated */ @Override protected void setUp() throws Exception { setFixture(LibraryFactory.eINSTANCE.createPreferenceNodePathSet()); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see junit.framework.TestCase#tearDown() * @generated */ @Override protected void tearDown() throws Exception { setFixture(null); } @Override public void testGetDerivedPath() { - InstanceScope.INSTANCE.getNode("gov.redhawk.eclipsecorba.library.tests").put("IdlIncludePath", "helloWorld"); + new InstanceScope().getNode("gov.redhawk.eclipsecorba.library.tests").put("IdlIncludePath", "helloWorld"); final PreferenceNodePathSet pathSet = this.getFixture(); pathSet.setDelimiter(";"); pathSet.setFileUri(true); pathSet.setKey("IdlIncludePath"); pathSet.setQualifier("gov.redhawk.eclipsecorba.library.tests"); pathSet.setReplaceEnv(true); final EList<URI> derrivedPath = pathSet.getDerivedPath(); Assert.assertTrue(derrivedPath.size() > 0); } } //PreferenceNodePathSetTest
true
true
public void testGetDerivedPath() { InstanceScope.INSTANCE.getNode("gov.redhawk.eclipsecorba.library.tests").put("IdlIncludePath", "helloWorld"); final PreferenceNodePathSet pathSet = this.getFixture(); pathSet.setDelimiter(";"); pathSet.setFileUri(true); pathSet.setKey("IdlIncludePath"); pathSet.setQualifier("gov.redhawk.eclipsecorba.library.tests"); pathSet.setReplaceEnv(true); final EList<URI> derrivedPath = pathSet.getDerivedPath(); Assert.assertTrue(derrivedPath.size() > 0); }
public void testGetDerivedPath() { new InstanceScope().getNode("gov.redhawk.eclipsecorba.library.tests").put("IdlIncludePath", "helloWorld"); final PreferenceNodePathSet pathSet = this.getFixture(); pathSet.setDelimiter(";"); pathSet.setFileUri(true); pathSet.setKey("IdlIncludePath"); pathSet.setQualifier("gov.redhawk.eclipsecorba.library.tests"); pathSet.setReplaceEnv(true); final EList<URI> derrivedPath = pathSet.getDerivedPath(); Assert.assertTrue(derrivedPath.size() > 0); }
diff --git a/src/br/univali/portugol/nucleo/analise/semantica/AnalisadorSemantico.java b/src/br/univali/portugol/nucleo/analise/semantica/AnalisadorSemantico.java index 55dc04f..19e4bc6 100644 --- a/src/br/univali/portugol/nucleo/analise/semantica/AnalisadorSemantico.java +++ b/src/br/univali/portugol/nucleo/analise/semantica/AnalisadorSemantico.java @@ -1,2160 +1,2170 @@ package br.univali.portugol.nucleo.analise.semantica; import br.univali.portugol.nucleo.analise.semantica.avisos.AvisoSimboloGlobalOcultado; import br.univali.portugol.nucleo.analise.semantica.avisos.AvisoValorExpressaoSeraConvertido; import br.univali.portugol.nucleo.analise.semantica.erros.ErroInclusaoBiblioteca; import br.univali.portugol.nucleo.asa.NoInclusaoBiblioteca; import br.univali.portugol.nucleo.analise.semantica.erros.ErroInicializacaoInvalida; import br.univali.portugol.nucleo.analise.semantica.erros.ErroNumeroParametrosFuncao; import br.univali.portugol.nucleo.analise.semantica.erros.ErroOperacaoComExpressaoConstante; import br.univali.portugol.nucleo.analise.semantica.erros.ErroParametroRedeclarado; import br.univali.portugol.nucleo.analise.semantica.erros.ErroPassagemParametroInvalida; import br.univali.portugol.nucleo.analise.semantica.erros.ErroQuantificadorParametroFuncao; import br.univali.portugol.nucleo.analise.semantica.erros.ErroReferenciaInvalida; import br.univali.portugol.nucleo.analise.semantica.erros.ErroSemanticoNaoTratado; import br.univali.portugol.nucleo.analise.semantica.erros.ErroSimboloNaoDeclarado; import br.univali.portugol.nucleo.analise.semantica.erros.ErroSimboloNaoInicializado; import br.univali.portugol.nucleo.analise.semantica.erros.ErroSimboloRedeclarado; import br.univali.portugol.nucleo.analise.semantica.erros.ErroTipoParametroIncompativel; import br.univali.portugol.nucleo.analise.semantica.erros.ErroTiposIncompativeis; import br.univali.portugol.nucleo.analise.semantica.erros.ExcecaoImpossivelDeterminarTipoDado; import br.univali.portugol.nucleo.analise.semantica.erros.ExcecaoValorSeraConvertido; import br.univali.portugol.nucleo.analise.sintatica.AnalisadorSintatico; import br.univali.portugol.nucleo.asa.*; import br.univali.portugol.nucleo.bibliotecas.base.GerenciadorBibliotecas; import br.univali.portugol.nucleo.bibliotecas.base.ErroCarregamentoBiblioteca; import br.univali.portugol.nucleo.bibliotecas.base.MetaDadosBiblioteca; import br.univali.portugol.nucleo.bibliotecas.base.MetaDadosConstante; import br.univali.portugol.nucleo.bibliotecas.base.MetaDadosFuncao; import br.univali.portugol.nucleo.bibliotecas.base.MetaDadosParametro; import br.univali.portugol.nucleo.bibliotecas.base.MetaDadosParametros; import br.univali.portugol.nucleo.mensagens.AvisoAnalise; import br.univali.portugol.nucleo.mensagens.ErroSemantico; import br.univali.portugol.nucleo.simbolos.*; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.TreeMap; /** * Esta classe percorre a ASA gerada a partir do código fonte para detectar erros de semântica. * * * @version 2.0 * * @see AnalisadorSintatico * @see ObservadorAnaliseSemantica */ public final class AnalisadorSemantico implements VisitanteASA { private boolean declarandoSimbolosGlobais; private Memoria memoria; private List<ObservadorAnaliseSemantica> observadores; private static final List<String> funcoesReservadas = getLista(); private TabelaCompatibilidadeTipos tabelaCompatibilidadeTipos = TabelaCompatibilidadeTiposPortugol.INSTANCE; private ArvoreSintaticaAbstrata asa; private Map<String, MetaDadosBiblioteca> metaDadosBibliotecas; private Funcao funcaoAtual; private TipoDado tipoDadoEscolha; private boolean declarandoVetor; private boolean declarandoMatriz; private boolean passandoReferencia = false; private boolean passandoParametro = false; public AnalisadorSemantico() { memoria = new Memoria(); metaDadosBibliotecas = new TreeMap<String, MetaDadosBiblioteca>(); observadores = new ArrayList<ObservadorAnaliseSemantica>(); } /** * Permite adicionar um observador à análise semântica. Os observadores serão notificados sobre cada * erro semântico encontrado no código fonte e deverão tratá-los apropriadamente, exibindo-os em uma * IDE, por exemplo. * * @param observadorAnaliseSemantica o observador da análise semântica a ser registrado. * @since 1.0 */ public void adicionarObservador(ObservadorAnaliseSemantica observadorAnaliseSemantica) { if (!observadores.contains(observadorAnaliseSemantica)) { observadores.add(observadorAnaliseSemantica); } } /** * Remove um observador da análise previamente registrado utilizando o método * {@link AnalisadorSemantico#adicionarObservador(br.univali.portugol.nucleo.analise.semantica.ObservadorAnaliseSemantica) }. * Uma vez removido, o observador não será mais notificado dos erros semânticos encontrados durante a análise. * * @param observadorAnaliseSemantica um observador de análise semântica previamente registrado. * @since 1.0 */ public void removerObservador(ObservadorAnaliseSemantica observadorAnaliseSemantica) { observadores.remove(observadorAnaliseSemantica); } private void notificarAviso(AvisoAnalise aviso) { for (ObservadorAnaliseSemantica observadorAnaliseSemantica: observadores) { observadorAnaliseSemantica.tratarAviso(aviso); } } private void notificarErroSemantico(ErroSemantico erroSemantico) { for (ObservadorAnaliseSemantica observadorAnaliseSemantica: observadores) { observadorAnaliseSemantica.tratarErroSemantico(erroSemantico); } } /** * Realiza a análise semântica de uma ASA. Este método não retorna valor e não gera exceções. * Para capturar os erros semânticos gerados durante a análise, deve-se registrar um ou mais * obsrvadores de análise utilizando o método * {@link AnalisadorSemantico#adicionarObservador(br.univali.portugol.nucleo.analise.semantica.ObservadorAnaliseSemantica) }. * * @param asa a ASA que será percorrida em busca de erros semânticos. * @since 1.0 */ public void analisar(ArvoreSintaticaAbstrata asa) { this.asa = asa; if (asa != null) { try { asa.aceitar(this); } catch (Exception excecao) { notificarErroSemantico(new ErroSemanticoNaoTratado(excecao)); } } } @Override public Object visitar(ArvoreSintaticaAbstrataPrograma asap) throws ExcecaoVisitaASA { for (NoInclusaoBiblioteca inclusao : asap.getListaInclusoesBibliotecas()) { inclusao.aceitar(this); } // Executa a primeira vez para declarar as funções na tabela de símbolos declarandoSimbolosGlobais = true; for (NoDeclaracao declaracao : asap.getListaDeclaracoesGlobais()) { declaracao.aceitar(this); } declarandoSimbolosGlobais = false; // Executa a segunda vez para analizar os blocos das funções for (NoDeclaracao declaracao : asap.getListaDeclaracoesGlobais()) { declaracao.aceitar(this); } return null; } @Override public Object visitar(NoCadeia noCadeia) throws ExcecaoVisitaASA { return TipoDado.CADEIA; } @Override public Object visitar(NoCaracter noCaracter) throws ExcecaoVisitaASA { return TipoDado.CARACTER; } @Override public Object visitar(NoCaso noCaso) throws ExcecaoVisitaASA { if (noCaso.getExpressao() != null) { TipoDado tipoDado = (TipoDado) noCaso.getExpressao().aceitar(this); if ((tipoDadoEscolha == TipoDado.INTEIRO) || (tipoDadoEscolha == TipoDado.CARACTER)){ if (tipoDado != tipoDadoEscolha){ notificarErroSemantico(new ErroTiposIncompativeis(noCaso, tipoDado, tipoDadoEscolha)); } } else { if ((tipoDado != TipoDado.INTEIRO) && (tipoDado != TipoDado.CARACTER)){ notificarErroSemantico(new ErroTiposIncompativeis(noCaso, tipoDado, TipoDado.INTEIRO, TipoDado.CARACTER)); } } } analisarListaBlocos(noCaso.getBlocos()); return null; } @Override public Object visitar(NoChamadaFuncao chamadaFuncao) throws ExcecaoVisitaASA { if (funcaoExiste(chamadaFuncao)) { verificarQuantidadeParametros(chamadaFuncao); verificarTiposParametros(chamadaFuncao); verificarQuantificador(chamadaFuncao); verificarModoAcesso(chamadaFuncao); verificarParametrosObsoletos(chamadaFuncao); return obterTipoRetornoFuncao(chamadaFuncao); } else { notificarErroSemantico(new ErroSimboloNaoDeclarado(chamadaFuncao)); throw new ExcecaoVisitaASA(new ExcecaoImpossivelDeterminarTipoDado(), asa, chamadaFuncao); } } private void verificarModoAcesso(NoChamadaFuncao chamadaFuncao) { List<ModoAcesso> modosAcessoEsperados = obterModosAcessoEsperados(chamadaFuncao); List<ModoAcesso> modosAcessoPassados = obterModosAcessoPassados(chamadaFuncao); int cont = Math.min(modosAcessoEsperados.size(), modosAcessoPassados.size()); for (int indice = 0; indice < cont; indice++) { ModoAcesso modoAcessoEsperado = modosAcessoEsperados.get(indice); ModoAcesso modoAcessoPassado = modosAcessoPassados.get(indice); if (modoAcessoEsperado == ModoAcesso.POR_REFERENCIA && modoAcessoPassado == ModoAcesso.POR_VALOR) { notificarErroSemantico(new ErroPassagemParametroInvalida(chamadaFuncao.getParametros().get(indice), obterNomeParametro(chamadaFuncao, indice), chamadaFuncao.getNome())); } } } private List<ModoAcesso> obterModosAcessoPassados(NoChamadaFuncao chamadaFuncao) { List<ModoAcesso> modosAcesso = new ArrayList<ModoAcesso>(); if (chamadaFuncao.getParametros() != null) { for (NoExpressao parametro : chamadaFuncao.getParametros()) { if (parametro instanceof NoReferenciaVariavel) { NoReferenciaVariavel noReferenciaVariavel = (NoReferenciaVariavel) parametro; if (noReferenciaVariavel.getEscopo() == null) { try { Simbolo simbolo = memoria.getSimbolo(noReferenciaVariavel.getNome()); if (simbolo.constante()) { modosAcesso.add(ModoAcesso.POR_VALOR); } else modosAcesso.add(ModoAcesso.POR_REFERENCIA); } catch (ExcecaoSimboloNaoDeclarado excecao) { // Não faz nada aqui } } else { modosAcesso.add(ModoAcesso.POR_VALOR); } } else { modosAcesso.add(ModoAcesso.POR_VALOR); } } } return modosAcesso; } private List<ModoAcesso> obterModosAcessoEsperados(NoChamadaFuncao chamadaFuncao) { List<ModoAcesso> modosAcesso = new ArrayList<ModoAcesso>(); if (chamadaFuncao.getEscopo() == null) { if (!funcoesReservadas.contains(chamadaFuncao.getNome())) { try { Funcao funcao = (Funcao) memoria.getSimbolo(chamadaFuncao.getNome()); for (NoDeclaracaoParametro parametro : funcao.getParametros()) { modosAcesso.add(parametro.getModoAcesso()); } } catch (ExcecaoSimboloNaoDeclarado ex) { // Não faz nada aqui } } } else { MetaDadosBiblioteca metaDadosBiblioteca = metaDadosBibliotecas.get(chamadaFuncao.getEscopo()); MetaDadosFuncao metaDadosFuncao = metaDadosBiblioteca.obterMetaDadosFuncoes().obter(chamadaFuncao.getNome()); MetaDadosParametros metaDadosParametros = metaDadosFuncao.obterMetaDadosParametros(); for (MetaDadosParametro metaDadosParametro : metaDadosParametros) { modosAcesso.add(metaDadosParametro.getModoAcesso()); } } return modosAcesso; } private TipoDado obterTipoRetornoFuncao(NoChamadaFuncao chamadaFuncao) { if (chamadaFuncao.getEscopo() == null) { if (funcoesReservadas.contains(chamadaFuncao.getNome())) { return TipoDado.VAZIO; } else { try { Funcao funcao = (Funcao) memoria.getSimbolo(chamadaFuncao.getNome()); return funcao.getTipoDado(); } catch (ExcecaoSimboloNaoDeclarado excecao) { // Não faz nada aqui } } } else { MetaDadosBiblioteca metaDadosBiblioteca = metaDadosBibliotecas.get(chamadaFuncao.getEscopo()); MetaDadosFuncao metaDadosFuncao = metaDadosBiblioteca.obterMetaDadosFuncoes().obter(chamadaFuncao.getNome()); return metaDadosFuncao.getTipoDado(); } return null; } private void verificarParametrosObsoletos(final NoChamadaFuncao chamadaFuncao) { int parametrosEsperados = obterNumeroParametrosEsperados(chamadaFuncao); int parametrosPassados = (chamadaFuncao.getParametros() != null)? chamadaFuncao.getParametros().size() : 0; int inicio = Math.min(parametrosEsperados, parametrosPassados); if (chamadaFuncao.getParametros() != null) { for (int indice = inicio; indice < parametrosPassados; indice++) { NoExpressao parametro = chamadaFuncao.getParametros().get(indice); notificarErroSemantico(new ErroSemantico(parametro.getTrechoCodigoFonte()) { @Override protected String construirMensagem() { return String.format("A expressão é obsoleta na chamada da função \"%s\", pois extrapola o número de parâmetros esperados pela função", chamadaFuncao.getNome()); } }); } } } private void verificarQuantificador(NoChamadaFuncao chamadaFuncao) { List<Quantificador> quantificadoresEsperados = obterQuantificadoresEsperados(chamadaFuncao); List<Quantificador> quantificadoresPassados = obterQuantificadoresPassados(chamadaFuncao); int cont = Math.min(quantificadoresEsperados.size(), quantificadoresPassados.size()); for (int indice = 0; indice < cont; indice++) { Quantificador quantificadorPassado = quantificadoresPassados.get(indice); Quantificador quantificadorEsperado = quantificadoresEsperados.get(indice); if (quantificadorPassado != quantificadorEsperado) { notificarErroSemantico(new ErroQuantificadorParametroFuncao(chamadaFuncao, indice, obterNomeParametro(chamadaFuncao, indice), quantificadorEsperado, quantificadorPassado)); } } } private List<Quantificador> obterQuantificadoresEsperados(NoChamadaFuncao chamadaFuncao) { List<Quantificador> quantificadores = new ArrayList<Quantificador>(); if (chamadaFuncao.getEscopo() == null) { if (!funcoesReservadas.contains(chamadaFuncao.getNome())) { try { Funcao funcao = (Funcao) memoria.getSimbolo(chamadaFuncao.getNome()); for (NoDeclaracaoParametro declaracaoParametro : funcao.getParametros()) { quantificadores.add(declaracaoParametro.getQuantificador()); } } catch(ExcecaoSimboloNaoDeclarado ex) { // Não faz nada aqui } } } else { MetaDadosBiblioteca metaDadosBiblioteca = metaDadosBibliotecas.get(chamadaFuncao.getEscopo()); MetaDadosFuncao metaDadosFuncao = metaDadosBiblioteca.obterMetaDadosFuncoes().obter(chamadaFuncao.getNome()); MetaDadosParametros metaDadosParametros = metaDadosFuncao.obterMetaDadosParametros(); for (MetaDadosParametro metaDadosParametro : metaDadosParametros) { quantificadores.add(metaDadosParametro.getQuantificador()); } } return quantificadores; } private List<Quantificador> obterQuantificadoresPassados(NoChamadaFuncao chamadaFuncao) { List<Quantificador> quantificadores = new ArrayList<Quantificador>(); if (chamadaFuncao.getParametros() != null) { for (NoExpressao parametroPassado : chamadaFuncao.getParametros()) { try { if (parametroPassado instanceof NoReferenciaVariavel) { String nome = ((NoReferenciaVariavel) parametroPassado).getNome(); Simbolo simbolo = memoria.getSimbolo(nome); if (simbolo instanceof Variavel) { quantificadores.add(Quantificador.VALOR); } else if (simbolo instanceof Vetor) { quantificadores.add(Quantificador.VETOR); } else if (simbolo instanceof Matriz) { quantificadores.add(Quantificador.MATRIZ); } } else if (parametroPassado instanceof NoVetor) { quantificadores.add(Quantificador.VETOR); } else if (parametroPassado instanceof NoMatriz) { quantificadores.add(Quantificador.MATRIZ); } else { quantificadores.add(Quantificador.VALOR); } } catch (ExcecaoSimboloNaoDeclarado ex) { // Não faz nada aqui } } } return quantificadores; } private void verificarTiposParametros(NoChamadaFuncao chamadaFuncao) throws ExcecaoVisitaASA { List<ModoAcesso> modosAcesso = obterModosAcessoEsperados(chamadaFuncao); List<TipoDado> tiposEsperados = obterTiposParametrosEsperados(chamadaFuncao); List<TipoDado> tiposPassado = obterTiposParametrosPassados(chamadaFuncao, modosAcesso); int cont = Math.min(tiposEsperados.size(),tiposPassado.size()); for (int indice = 0; indice < cont; indice++) { TipoDado tipoPassado = tiposPassado.get(indice); TipoDado tipoEsperado = tiposEsperados.get(indice); ModoAcesso modoAcesso = modosAcesso.get(indice); if (tipoPassado != null) { try { tabelaCompatibilidadeTipos.obterTipoRetornoPassagemParametro(tipoEsperado, tipoPassado); } catch (ExcecaoValorSeraConvertido excecao) { if (modoAcesso == ModoAcesso.POR_REFERENCIA) { notificarErroSemantico(new ErroTipoParametroIncompativel(chamadaFuncao.getNome(), obterNomeParametro(chamadaFuncao, indice), chamadaFuncao.getParametros().get(indice), tipoEsperado, tipoPassado)); } else { notificarAviso(new AvisoValorExpressaoSeraConvertido(chamadaFuncao.getParametros().get(indice).getTrechoCodigoFonte(), chamadaFuncao, tipoPassado, tipoEsperado, obterNomeParametro(chamadaFuncao, indice))); } } catch (ExcecaoImpossivelDeterminarTipoDado excecao) { notificarErroSemantico(new ErroTipoParametroIncompativel(chamadaFuncao.getNome(), obterNomeParametro(chamadaFuncao, indice), chamadaFuncao.getParametros().get(indice), tipoEsperado, tipoPassado)); } } } } private String obterNomeParametro(NoChamadaFuncao chamadaFuncao, int indice) { if (chamadaFuncao.getEscopo() == null) { try { Funcao funcao = (Funcao) memoria.getSimbolo(chamadaFuncao.getNome()); return funcao.getParametros().get(indice).getNome(); } catch(ExcecaoSimboloNaoDeclarado ex) { // Não deve cair aqui nunca } } else { MetaDadosBiblioteca metaDadosBiblioteca = metaDadosBibliotecas.get(chamadaFuncao.getEscopo()); MetaDadosFuncao metaDadosFuncao = metaDadosBiblioteca.obterMetaDadosFuncoes().obter(chamadaFuncao.getNome()); MetaDadosParametros metaDadosParametros = metaDadosFuncao.obterMetaDadosParametros(); return metaDadosParametros.obter(indice).getNome(); } return ""; } private List<TipoDado> obterTiposParametrosEsperados(NoChamadaFuncao chamadaFuncao) { List<TipoDado> tipos = new ArrayList<TipoDado>(); if (chamadaFuncao.getEscopo() == null) { if (!funcoesReservadas.contains(chamadaFuncao.getNome())) { try { Funcao funcao = (Funcao) memoria.getSimbolo(chamadaFuncao.getNome()); List<NoDeclaracaoParametro> parametros = funcao.getParametros(); if (parametros != null) { for (NoDeclaracaoParametro parametro : parametros) { tipos.add(parametro.getTipoDado()); } } } catch(ExcecaoSimboloNaoDeclarado ex) { // Não deve cair aqui nunca } } } else { MetaDadosBiblioteca metaDadosBiblioteca = metaDadosBibliotecas.get(chamadaFuncao.getEscopo()); MetaDadosFuncao metaDadosFuncao = metaDadosBiblioteca.obterMetaDadosFuncoes().obter(chamadaFuncao.getNome()); MetaDadosParametros metaDadosParametros = metaDadosFuncao.obterMetaDadosParametros(); for (MetaDadosParametro metaDadosParametro : metaDadosParametros) { tipos.add(metaDadosParametro.getTipoDado()); } } return tipos; } private List<TipoDado> obterTiposParametrosPassados(NoChamadaFuncao chamadaFuncao, List<ModoAcesso> modosAcesso) throws ExcecaoVisitaASA { List<TipoDado> tipos = new ArrayList<TipoDado>(); if (chamadaFuncao.getParametros() != null) { for (int indice = 0; indice < chamadaFuncao.getParametros().size(); indice++) { NoExpressao parametro = chamadaFuncao.getParametros().get(indice); if (chamadaFuncao.getEscopo() == null && funcoesReservadas.contains(chamadaFuncao.getNome())) { passandoReferencia = false; } else { if (indice < modosAcesso.size()) { passandoReferencia = modosAcesso.get(indice) == ModoAcesso.POR_REFERENCIA; } else passandoReferencia = false; } try { if (parametro instanceof NoReferenciaVariavel && chamadaFuncao.getNome().equals("leia")) { String nome = ((NoReferenciaVariavel) parametro).getNome(); try { Simbolo variavel = memoria.getSimbolo(nome); variavel.setInicializado(true); } catch (ExcecaoSimboloNaoDeclarado excecaoSimboloNaoDeclarado) { // Não faz nada } } passandoParametro = (chamadaFuncao.getEscopo() == null && !funcoesReservadas.contains(chamadaFuncao.getNome())); tipos.add( (TipoDado) parametro.aceitar(this)); passandoParametro = false; } catch(ExcecaoVisitaASA ex) { if (ex.getCause() instanceof ExcecaoImpossivelDeterminarTipoDado) { tipos.add(null); } else { throw ex; } } passandoReferencia = false; } } return tipos; } private void verificarQuantidadeParametros(NoChamadaFuncao chamadaFuncao) { int esperados = obterNumeroParametrosEsperados(chamadaFuncao); int passados = (chamadaFuncao.getParametros() != null)? chamadaFuncao.getParametros().size() : 0; if ((esperados == Integer.MAX_VALUE && passados == 0) || (esperados != Integer.MAX_VALUE && passados != esperados)) { notificarErroSemantico(new ErroNumeroParametrosFuncao(passados, esperados, chamadaFuncao)); } } private int obterNumeroParametrosEsperados(NoChamadaFuncao chamadaFuncao) { if (chamadaFuncao.getEscopo() == null) { if (funcoesReservadas.contains(chamadaFuncao.getNome())) { if (chamadaFuncao.getNome().equals("limpa")) { return 0; } else { return Integer.MAX_VALUE; } } try { Funcao funcao = (Funcao) memoria.getSimbolo(chamadaFuncao.getNome()); List<NoDeclaracaoParametro> parametros = funcao.getParametros(); if (parametros != null) { return parametros.size(); } else { return 0; } } catch (ExcecaoSimboloNaoDeclarado ex) { return -1; } } else { MetaDadosBiblioteca metaDadosBiblioteca = metaDadosBibliotecas.get(chamadaFuncao.getEscopo()); MetaDadosFuncao metaDadosFuncao = metaDadosBiblioteca.obterMetaDadosFuncoes().obter(chamadaFuncao.getNome()); return metaDadosFuncao.obterMetaDadosParametros().quantidade(); } } private boolean funcaoExiste(NoChamadaFuncao chamadaFuncao) throws ExcecaoVisitaASA { if (chamadaFuncao.getEscopo() == null) { if (funcoesReservadas.contains(chamadaFuncao.getNome())) { return true; } else { try { memoria.getSimbolo(chamadaFuncao.getNome()); return true; } catch(ExcecaoSimboloNaoDeclarado ex) { return false; } } } else { MetaDadosBiblioteca metaDadosBiblioteca = metaDadosBibliotecas.get(chamadaFuncao.getEscopo()); if (metaDadosBiblioteca != null) { MetaDadosFuncao metaDadosFuncao = metaDadosBiblioteca.obterMetaDadosFuncoes().obter(chamadaFuncao.getNome()); return (metaDadosFuncao != null); } else { notificarErroSemantico(new ErroInclusaoBiblioteca(chamadaFuncao.getTrechoCodigoFonteNome(), new Exception(String.format("A biblioteca '%s' não foi incluída no programa", chamadaFuncao.getEscopo())))); throw new ExcecaoVisitaASA(new ExcecaoImpossivelDeterminarTipoDado(), asa, chamadaFuncao); } } } @Override public Object visitar(NoDeclaracaoFuncao declaracaoFuncao) throws ExcecaoVisitaASA { if (declarandoSimbolosGlobais) { String nome = declaracaoFuncao.getNome(); TipoDado tipoDado = declaracaoFuncao.getTipoDado(); Quantificador quantificador = declaracaoFuncao.getQuantificador(); Funcao funcao = new Funcao(nome, tipoDado, quantificador, declaracaoFuncao.getParametros(), declaracaoFuncao); funcao.setTrechoCodigoFonteNome(declaracaoFuncao.getTrechoCodigoFonteNome()); funcao.setTrechoCodigoFonteTipoDado(declaracaoFuncao.getTrechoCodigoFonteTipoDado()); try { Simbolo simbolo = memoria.getSimbolo(nome); notificarErroSemantico(new ErroSimboloRedeclarado(funcao, simbolo)); funcao.setRedeclarado(true); } catch (ExcecaoSimboloNaoDeclarado excecaoSimboloNaoDeclarado) { memoria.adicionarSimbolo(funcao); } } else { try { funcaoAtual = (Funcao) memoria.getSimbolo(declaracaoFuncao.getNome()); memoria.empilharFuncao(); List<NoDeclaracaoParametro> parametros = declaracaoFuncao.getParametros(); for (NoDeclaracaoParametro noDeclaracaoParametro : parametros) { noDeclaracaoParametro.aceitar(this); } analisarListaBlocos(declaracaoFuncao.getBlocos()); } catch (ExcecaoSimboloNaoDeclarado excecaoSimboloNaoDeclarado) { throw new ExcecaoVisitaASA(excecaoSimboloNaoDeclarado, asa, declaracaoFuncao); } finally { memoria.desempilharFuncao(); } } return null; } @Override public Object visitar(NoDeclaracaoMatriz noDeclaracaoMatriz) throws ExcecaoVisitaASA { if (declarandoSimbolosGlobais == memoria.isEscopoGlobal()) { String nome = noDeclaracaoMatriz.getNome(); TipoDado tipoDados = noDeclaracaoMatriz.getTipoDado(); Integer linhas = null; Integer colunas = null; if ((noDeclaracaoMatriz.getNumeroLinhas() != null && !(noDeclaracaoMatriz.getNumeroLinhas()instanceof NoInteiro)) && (noDeclaracaoMatriz.getNumeroColunas()) != null && !(noDeclaracaoMatriz.getNumeroColunas()instanceof NoInteiro)){ notificarErroSemantico(new ErroSemantico(noDeclaracaoMatriz.getNumeroLinhas().getTrechoCodigoFonte()) { @Override protected String construirMensagem() { return "A número de linhas ou colunas da matriz deve ser um valor inteiro constante"; } }); } else { if (noDeclaracaoMatriz.getNumeroLinhas()!= null) linhas = ((NoInteiro)noDeclaracaoMatriz.getNumeroLinhas()).getValor(); if (noDeclaracaoMatriz.getNumeroColunas() != null) colunas = ((NoInteiro)noDeclaracaoMatriz.getNumeroColunas()).getValor(); } Matriz matriz = new Matriz(nome, tipoDados, noDeclaracaoMatriz, 1, 1); matriz.setTrechoCodigoFonteNome(noDeclaracaoMatriz.getTrechoCodigoFonteNome()); matriz.setTrechoCodigoFonteTipoDado(noDeclaracaoMatriz.getTrechoCodigoFonteTipoDado()); try { Simbolo simboloExistente = memoria.getSimbolo(nome); final boolean global = memoria.isGlobal(simboloExistente); final boolean local = memoria.isLocal(simboloExistente); memoria.empilharEscopo(); memoria.adicionarSimbolo(matriz); final boolean global1 = memoria.isGlobal(matriz); final boolean local1 = memoria.isLocal(matriz); if ( (global && global1) || (local && local1) ) { matriz.setRedeclarado(true); notificarErroSemantico(new ErroSimboloRedeclarado(matriz, simboloExistente)); memoria.desempilharEscopo(); } else { memoria.desempilharEscopo(); memoria.adicionarSimbolo(matriz); Simbolo simboloGlobal = memoria.isGlobal(simboloExistente)? simboloExistente : matriz; Simbolo simboloLocal = memoria.isGlobal(simboloExistente)? matriz : simboloExistente; notificarAviso(new AvisoSimboloGlobalOcultado(simboloGlobal, simboloLocal, noDeclaracaoMatriz)); } } catch (ExcecaoSimboloNaoDeclarado excecaoSimboloNaoDeclarado) { if (funcoesReservadas.contains(nome)) { matriz.setRedeclarado(true); Funcao funcaoSistam = new Funcao(nome, TipoDado.VAZIO, Quantificador.VETOR, null, null); notificarErroSemantico(new ErroSimboloRedeclarado(matriz, funcaoSistam)); } else { memoria.adicionarSimbolo(matriz); } } if (noDeclaracaoMatriz.constante() && noDeclaracaoMatriz.getInicializacao() == null) { NoReferenciaVariavel referencia = new NoReferenciaVariavel(null, nome); referencia.setTrechoCodigoFonteNome(noDeclaracaoMatriz.getTrechoCodigoFonteNome()); notificarErroSemantico(new ErroSimboloNaoInicializado(referencia, matriz)); } if (noDeclaracaoMatriz.getInicializacao() != null) { if (noDeclaracaoMatriz.getInicializacao() instanceof NoMatriz) { NoExpressao inicializacao = noDeclaracaoMatriz.getInicializacao(); NoReferenciaVariavel referencia = new NoReferenciaVariavel(null, nome); referencia.setTrechoCodigoFonteNome(noDeclaracaoMatriz.getTrechoCodigoFonteNome()); NoOperacao operacao = new NoOperacaoAtribuicao(referencia, inicializacao); if (linhas != null){ if (linhas != ((NoMatriz)inicializacao).getValores().size()) { final int pLinhas = linhas; final String pNome = nome; notificarErroSemantico(new ErroSemantico(noDeclaracaoMatriz.getInicializacao().getTrechoCodigoFonte()) { @Override protected String construirMensagem() { return String.format("A inicialização da matriz \"%s\" deve possuir %d linhas", pNome, pLinhas); } }); } } if (colunas != null) { for (int lin = 0; lin < ((NoMatriz)inicializacao).getValores().size(); lin++) { if (colunas != ((NoMatriz)inicializacao).getValores().get(lin).size()) { final int pColunas = colunas; final String pNome = nome; final int pLin = lin; notificarErroSemantico(new ErroSemantico(noDeclaracaoMatriz.getInicializacao().getTrechoCodigoFonte()) { @Override protected String construirMensagem() { return String.format("A linha %d na inicialização da matriz \"%s\" deve possuir %d elementos", pLin, pNome, pColunas); } }); } } } try { this.declarandoMatriz = true; operacao.aceitar(this); this.declarandoMatriz = false; } catch (ExcecaoVisitaASA excecao) { if (!(excecao.getCause() instanceof ExcecaoImpossivelDeterminarTipoDado)) { throw excecao; } } } else { notificarErroSemantico(new ErroInicializacaoInvalida(noDeclaracaoMatriz)); } } matriz.setConstante(noDeclaracaoMatriz.constante()); } return null; } @Override public Object visitar(NoDeclaracaoVariavel declaracaoVariavel) throws ExcecaoVisitaASA { if (declarandoSimbolosGlobais == memoria.isEscopoGlobal()) { String nome = declaracaoVariavel.getNome(); TipoDado tipoDados = declaracaoVariavel.getTipoDado(); Variavel variavel = new Variavel(nome, tipoDados, declaracaoVariavel); variavel.setTrechoCodigoFonteNome(declaracaoVariavel.getTrechoCodigoFonteNome()); variavel.setTrechoCodigoFonteTipoDado(declaracaoVariavel.getTrechoCodigoFonteTipoDado()); try { Simbolo simboloExistente = memoria.getSimbolo(nome); final boolean global = memoria.isGlobal(simboloExistente); final boolean local = memoria.isLocal(simboloExistente); memoria.empilharEscopo(); memoria.adicionarSimbolo(variavel); final boolean global1 = memoria.isGlobal(variavel); final boolean local1 = memoria.isLocal(variavel); if ( (global && global1) || (local && local1) ) { variavel.setRedeclarado(true); notificarErroSemantico(new ErroSimboloRedeclarado(variavel, simboloExistente)); memoria.desempilharEscopo(); } else { memoria.desempilharEscopo(); memoria.adicionarSimbolo(variavel); Simbolo simboloGlobal = memoria.isGlobal(simboloExistente)? simboloExistente : variavel; Simbolo simboloLocal = memoria.isGlobal(simboloExistente)? variavel : simboloExistente; notificarAviso(new AvisoSimboloGlobalOcultado(simboloGlobal, simboloLocal, declaracaoVariavel)); } } catch (ExcecaoSimboloNaoDeclarado excecaoSimboloNaoDeclarado) { if (funcoesReservadas.contains(nome)) { variavel.setRedeclarado(true); Funcao funcaoSistam = new Funcao(nome, TipoDado.VAZIO, Quantificador.VETOR, null, null); notificarErroSemantico(new ErroSimboloRedeclarado(variavel, funcaoSistam)); } else { memoria.adicionarSimbolo(variavel); } } if (declaracaoVariavel.constante() && declaracaoVariavel.getInicializacao() == null) { NoReferenciaVariavel referencia = new NoReferenciaVariavel(null, nome); referencia.setTrechoCodigoFonteNome(declaracaoVariavel.getTrechoCodigoFonteNome()); notificarErroSemantico(new ErroSimboloNaoInicializado(referencia, variavel)); } if (declaracaoVariavel.getInicializacao() != null) { // Posteriormente restringir na gramática para não permitir atribuir vetor ou matriz a uma variável comum if (!(declaracaoVariavel.getInicializacao() instanceof NoVetor) && !(declaracaoVariavel.getInicializacao() instanceof NoMatriz)) { NoExpressao inicializacao = declaracaoVariavel.getInicializacao(); NoReferenciaVariavel referencia = new NoReferenciaVariavel(null, nome); referencia.setTrechoCodigoFonteNome(declaracaoVariavel.getTrechoCodigoFonteNome()); NoOperacao operacao = new NoOperacaoAtribuicao(referencia, inicializacao); memoria.empilharEscopo(); memoria.adicionarSimbolo(variavel); try { operacao.aceitar(this); } catch (ExcecaoVisitaASA excecao) { if (!(excecao.getCause() instanceof ExcecaoImpossivelDeterminarTipoDado)) { throw excecao; } } memoria.desempilharEscopo(); } else { notificarErroSemantico(new ErroInicializacaoInvalida(declaracaoVariavel)); } } variavel.setConstante(declaracaoVariavel.constante()); } return null; } @Override public Object visitar(NoDeclaracaoVetor noDeclaracaoVetor) throws ExcecaoVisitaASA { if (declarandoSimbolosGlobais == memoria.isEscopoGlobal()) { String nome = noDeclaracaoVetor.getNome(); TipoDado tipoDados = noDeclaracaoVetor.getTipoDado(); Integer tamanho = null; if (noDeclaracaoVetor.getTamanho() != null && !(noDeclaracaoVetor.getTamanho() instanceof NoInteiro)){ notificarErroSemantico(new ErroSemantico() { @Override protected String construirMensagem() { return "O tamanho do vetor deve ser um valor inteiro constante"; } }); } else { if (noDeclaracaoVetor.getTamanho() != null) tamanho = ((NoInteiro)noDeclaracaoVetor.getTamanho()).getValor(); } Vetor vetor = new Vetor(nome, tipoDados, noDeclaracaoVetor,1); vetor.setTrechoCodigoFonteNome(noDeclaracaoVetor.getTrechoCodigoFonteNome()); vetor.setTrechoCodigoFonteTipoDado(noDeclaracaoVetor.getTrechoCodigoFonteTipoDado()); try { Simbolo simboloExistente = memoria.getSimbolo(nome); final boolean global = memoria.isGlobal(simboloExistente); final boolean local = memoria.isLocal(simboloExistente); memoria.empilharEscopo(); memoria.adicionarSimbolo(vetor); final boolean global1 = memoria.isGlobal(vetor); final boolean local1 = memoria.isLocal(vetor); if ( (global && global1) || (local && local1) ) { vetor.setRedeclarado(true); notificarErroSemantico(new ErroSimboloRedeclarado(vetor, simboloExistente)); memoria.desempilharEscopo(); } else { memoria.desempilharEscopo(); memoria.adicionarSimbolo(vetor); Simbolo simboloGlobal = memoria.isGlobal(simboloExistente)? simboloExistente : vetor; Simbolo simboloLocal = memoria.isGlobal(simboloExistente)? vetor : simboloExistente; notificarAviso(new AvisoSimboloGlobalOcultado(simboloGlobal, simboloLocal, noDeclaracaoVetor)); } } catch (ExcecaoSimboloNaoDeclarado excecaoSimboloNaoDeclarado) { if (funcoesReservadas.contains(nome)) { vetor.setRedeclarado(true); Funcao funcaoSistam = new Funcao(nome, TipoDado.VAZIO, Quantificador.VETOR, null, null); notificarErroSemantico(new ErroSimboloRedeclarado(vetor, funcaoSistam)); } else { memoria.adicionarSimbolo(vetor); } } if (noDeclaracaoVetor.constante() && noDeclaracaoVetor.getInicializacao() == null) { NoReferenciaVariavel referencia = new NoReferenciaVariavel(null, nome); referencia.setTrechoCodigoFonteNome(noDeclaracaoVetor.getTrechoCodigoFonteNome()); notificarErroSemantico(new ErroSimboloNaoInicializado(referencia, vetor)); } if (noDeclaracaoVetor.getInicializacao() != null) { if (noDeclaracaoVetor.getInicializacao() instanceof NoVetor) { NoExpressao inicializacao = noDeclaracaoVetor.getInicializacao(); NoReferenciaVariavel referencia = new NoReferenciaVariavel(null, nome); referencia.setTrechoCodigoFonteNome(noDeclaracaoVetor.getTrechoCodigoFonteNome()); NoOperacao operacao = new NoOperacaoAtribuicao(referencia, inicializacao); if (tamanho != null){ if (tamanho != ((NoVetor)inicializacao).getValores().size()){ final int pTamanho = tamanho; final String pNome = nome; notificarErroSemantico(new ErroSemantico(noDeclaracaoVetor.getInicializacao().getTrechoCodigoFonte()) { @Override protected String construirMensagem() { return String.format("A inicializaçao do vetor \"%s\" deve possuir %d elemento(s)", pNome, pTamanho); } }); } } try { this.declarandoVetor = true; operacao.aceitar(this); this.declarandoVetor = false; } catch (ExcecaoVisitaASA excecao) { if (!(excecao.getCause() instanceof ExcecaoImpossivelDeterminarTipoDado)) { throw excecao; } } } else { notificarErroSemantico(new ErroInicializacaoInvalida(noDeclaracaoVetor)); } } vetor.setConstante(noDeclaracaoVetor.constante()); } return null; } @Override public Object visitar(NoEnquanto noEnquanto) throws ExcecaoVisitaASA { TipoDado tipoDadoCondicao = (TipoDado) noEnquanto.getCondicao().aceitar(this); if (tipoDadoCondicao != TipoDado.LOGICO) { notificarErroSemantico(new ErroTiposIncompativeis(noEnquanto, tipoDadoCondicao)); } analisarListaBlocos(noEnquanto.getBlocos()); return null; } @Override public Object visitar(NoEscolha noEscolha) throws ExcecaoVisitaASA { tipoDadoEscolha = (TipoDado) noEscolha.getExpressao().aceitar(this); if ((tipoDadoEscolha != TipoDado.INTEIRO) && (tipoDadoEscolha != TipoDado.CARACTER)){ notificarErroSemantico(new ErroTiposIncompativeis(noEscolha, tipoDadoEscolha,TipoDado.INTEIRO,TipoDado.CARACTER)); } List<NoCaso> casos = noEscolha.getCasos(); for (NoCaso noCaso : casos) { noCaso.aceitar(this); } return null; } @Override public Object visitar(NoFacaEnquanto noFacaEnquanto) throws ExcecaoVisitaASA { analisarListaBlocos(noFacaEnquanto.getBlocos()); TipoDado tipoDadoCondicao = (TipoDado) noFacaEnquanto.getCondicao().aceitar(this); if (tipoDadoCondicao != TipoDado.LOGICO) { notificarErroSemantico(new ErroTiposIncompativeis(noFacaEnquanto, tipoDadoCondicao)); } return null; } @Override public Object visitar(NoInteiro noInteiro) throws ExcecaoVisitaASA { return TipoDado.INTEIRO; } @Override public Object visitar(NoLogico noLogico) throws ExcecaoVisitaASA { return TipoDado.LOGICO; } @Override public Object visitar(NoMatriz noMatriz) throws ExcecaoVisitaASA { List<List<Object>> valores = noMatriz.getValores(); if (valores != null && !valores.isEmpty()){ try { TipoDado tipoMatriz = (TipoDado) ((NoExpressao) valores.get(0).get(0)).aceitar(this); for (List<Object> valList : valores) { for (int i = 0; i < valList.size(); i++) { TipoDado tipoDadoElemento = (TipoDado) ((NoExpressao) valList.get(i)).aceitar(this); if (tipoMatriz != tipoDadoElemento) { notificarErroSemantico(new ErroSemantico(noMatriz.getTrechoCodigoFonte()) { @Override protected String construirMensagem() { return "A inicialização da matriz possui mais de um tipo de dado"; } }); throw new ExcecaoVisitaASA(new ExcecaoImpossivelDeterminarTipoDado(), asa, noMatriz); } } } return tipoMatriz; } catch (Exception excecao) { //excecao.printStackTrace(System.out); throw new ExcecaoVisitaASA(new ExcecaoImpossivelDeterminarTipoDado(), asa, noMatriz); } } else { notificarErroSemantico(new ErroSemantico(noMatriz.getTrechoCodigoFonte()) { @Override protected String construirMensagem() { return "A inicialização da matriz não possui elementos"; } }); throw new ExcecaoVisitaASA(new ExcecaoImpossivelDeterminarTipoDado(), asa, noMatriz); } } @Override public Object visitar(NoMenosUnario noMenosUnario) throws ExcecaoVisitaASA { TipoDado tipo = (TipoDado) noMenosUnario.getExpressao().aceitar(this); if (!tipo.equals(TipoDado.INTEIRO) && !tipo.equals(TipoDado.REAL)){ notificarErroSemantico(new ErroTiposIncompativeis(noMenosUnario, tipo, TipoDado.INTEIRO, TipoDado.REAL)); throw new ExcecaoVisitaASA(new ExcecaoImpossivelDeterminarTipoDado(), asa, noMenosUnario); } return tipo; } @Override public Object visitar(NoNao noNao) throws ExcecaoVisitaASA { TipoDado tipo = (TipoDado) noNao.getExpressao().aceitar(this); if (tipo != TipoDado.LOGICO){ notificarErroSemantico(new ErroTiposIncompativeis(noNao, tipo, TipoDado.LOGICO)); throw new ExcecaoVisitaASA(new ExcecaoImpossivelDeterminarTipoDado(), asa, noNao); } return tipo; } @Override public Object visitar(NoOperacaoLogicaIgualdade noOperacao) throws ExcecaoVisitaASA { return recuperaTipoNoOperacao(noOperacao); } @Override public Object visitar(NoOperacaoLogicaDiferenca noOperacao) throws ExcecaoVisitaASA { return recuperaTipoNoOperacao(noOperacao); } @Override public Object visitar(final NoOperacaoAtribuicao noOperacao) throws ExcecaoVisitaASA { TipoDado tipoDadoRetorno; TipoDado operandoEsquerdo = null; TipoDado operandoDireito = null; Simbolo simbolo = null; boolean inicializadoAnterior = false; if (!(noOperacao.getOperandoEsquerdo() instanceof NoReferencia)){ notificarErroSemantico(new ErroOperacaoComExpressaoConstante(noOperacao, noOperacao.getOperandoEsquerdo())); - } else { + } else { try { if (noOperacao.getOperandoEsquerdo() instanceof NoReferenciaVariavel) { simbolo = memoria.getSimbolo(((NoReferencia)noOperacao.getOperandoEsquerdo()).getNome()); inicializadoAnterior = simbolo.inicializado(); simbolo.setInicializado(true); if (simbolo instanceof Variavel){ if (simbolo.constante()) { final Simbolo pSimbolo = simbolo; notificarErroSemantico(new ErroSemantico(noOperacao.getOperandoDireito().getTrechoCodigoFonte()) { @Override protected String construirMensagem() { StringBuilder sb = new StringBuilder(); if (pSimbolo instanceof Variavel) { sb.append("\""); sb.append(pSimbolo.getNome()); sb.append("\" é uma constante, e portanto, não pode ter seu valor alterado após a inicialização"); } else if (pSimbolo instanceof Vetor) { sb.append("O vetor \""); sb.append(pSimbolo.getNome()); sb.append("\" é constante e, portanto, não pode ter seus valores alterados após a inicialização"); } else if (pSimbolo instanceof Matriz) { sb.append("A matriz \""); sb.append(pSimbolo.getNome()); sb.append("\" é constante e, portanto, não pode ter seu valor alterado após a inicialização"); } return sb.toString(); } }); } if ((noOperacao.getOperandoDireito() instanceof NoMatriz) || (noOperacao.getOperandoDireito() instanceof NoVetor)) notificarErroSemantico(new ErroSemantico(noOperacao.getOperandoDireito().getTrechoCodigoFonte()) { @Override protected String construirMensagem() { return "não é possível atribuir uma matriz ou um vetor a uma variável"; } }); } else if (simbolo instanceof Vetor) { if (!(noOperacao.getOperandoDireito() instanceof NoVetor)){ notificarErroSemantico(new ErroSemantico(noOperacao.getOperandoDireito().getTrechoCodigoFonte()) { @Override protected String construirMensagem() { return "O vetor deve ser inicializado com um vetor literal"; } }); } } else if (simbolo instanceof Matriz) { if (!simbolo.inicializado() && !(noOperacao.getOperandoDireito() instanceof NoMatriz)){ notificarErroSemantico(new ErroSemantico(noOperacao.getOperandoDireito().getTrechoCodigoFonte()) { @Override protected String construirMensagem() { return "A matriz deve ser inicializada com uma matriz literal"; } }); } } } else if (noOperacao.getOperandoEsquerdo() instanceof NoReferenciaMatriz || noOperacao.getOperandoEsquerdo() instanceof NoReferenciaVetor) { if (noOperacao.getOperandoDireito() instanceof NoVetor) { notificarErroSemantico(new ErroSemantico(noOperacao.getOperandoDireito().getTrechoCodigoFonte()) { @Override protected String construirMensagem() { return "Deve-se atribuir um valor à uma posição do vetor"; } }); } else if (noOperacao.getOperandoDireito() instanceof NoMatriz ) { notificarErroSemantico(new ErroSemantico(noOperacao.getOperandoDireito().getTrechoCodigoFonte()) { @Override protected String construirMensagem() { return "Deve-se atribuir um valor à uma posição da matriz"; } }); } } + else if (noOperacao.getOperandoEsquerdo() instanceof NoChamadaFuncao) { + notificarErroSemantico(new ErroSemantico(noOperacao.getOperandoEsquerdo().getTrechoCodigoFonte()) + { + @Override + protected String construirMensagem() + { + return "Não é possível atribuir uma expressão a uma chamada de função."; + } + }); + } } catch (ExcecaoSimboloNaoDeclarado excecaoSimboloNaoDeclarado) { // Não faz nada } } try { operandoEsquerdo = (TipoDado) noOperacao.getOperandoEsquerdo().aceitar(this); } catch (ExcecaoVisitaASA excecao) { if (!(excecao.getCause() instanceof ExcecaoImpossivelDeterminarTipoDado)) { throw excecao; } } if (simbolo != null) { simbolo.setInicializado(inicializadoAnterior); } try { operandoDireito = (TipoDado) noOperacao.getOperandoDireito().aceitar(this); } catch (ExcecaoVisitaASA excecao) { if (!(excecao.getCause() instanceof ExcecaoImpossivelDeterminarTipoDado)) { throw excecao; } } if (operandoEsquerdo != null && operandoDireito != null) { try { tipoDadoRetorno = tabelaCompatibilidadeTipos.obterTipoRetornoOperacao(noOperacao.getClass(), operandoEsquerdo, operandoDireito); } catch (ExcecaoValorSeraConvertido excecao) { notificarAviso(new AvisoValorExpressaoSeraConvertido(noOperacao.getOperandoDireito().getTrechoCodigoFonte(), noOperacao, excecao.getTipoEntrada(), excecao.getTipoSaida())); tipoDadoRetorno = excecao.getTipoSaida(); } catch (ExcecaoImpossivelDeterminarTipoDado excecao) { notificarErroSemantico(new ErroTiposIncompativeis(noOperacao, operandoEsquerdo, operandoDireito)); throw new ExcecaoVisitaASA(excecao, asa, noOperacao); } } else { throw new ExcecaoVisitaASA(new ExcecaoImpossivelDeterminarTipoDado(), asa, noOperacao); } if (simbolo != null) { simbolo.setInicializado(true); } return tipoDadoRetorno; } @Override public Object visitar(NoOperacaoLogicaE noOperacao) throws ExcecaoVisitaASA { return recuperaTipoNoOperacao(noOperacao); } @Override public Object visitar(NoOperacaoLogicaOU noOperacao) throws ExcecaoVisitaASA { return recuperaTipoNoOperacao(noOperacao); } @Override public Object visitar(NoOperacaoLogicaMaior noOperacao) throws ExcecaoVisitaASA { return recuperaTipoNoOperacao(noOperacao); } @Override public Object visitar(NoOperacaoLogicaMaiorIgual noOperacao) throws ExcecaoVisitaASA { return recuperaTipoNoOperacao(noOperacao); } @Override public Object visitar(NoOperacaoLogicaMenor noOperacao) throws ExcecaoVisitaASA { return recuperaTipoNoOperacao(noOperacao); } @Override public Object visitar(NoOperacaoLogicaMenorIgual noOperacao) throws ExcecaoVisitaASA { return recuperaTipoNoOperacao(noOperacao); } @Override public Object visitar(NoOperacaoSoma noOperacao) throws ExcecaoVisitaASA { return recuperaTipoNoOperacao(noOperacao); } @Override public Object visitar(NoOperacaoSubtracao noOperacao) throws ExcecaoVisitaASA { return recuperaTipoNoOperacao(noOperacao); } @Override public Object visitar(NoOperacaoDivisao noOperacao) throws ExcecaoVisitaASA { return recuperaTipoNoOperacao(noOperacao); } @Override public Object visitar(NoOperacaoMultiplicacao noOperacao) throws ExcecaoVisitaASA { return recuperaTipoNoOperacao(noOperacao); } @Override public Object visitar(NoOperacaoModulo noOperacao) throws ExcecaoVisitaASA { return recuperaTipoNoOperacao(noOperacao); } @Override public Object visitar(NoOperacaoBitwiseLeftShift noOperacao) throws ExcecaoVisitaASA { return recuperaTipoNoOperacao(noOperacao); } @Override public Object visitar(NoOperacaoBitwiseRightShift noOperacao) throws ExcecaoVisitaASA { return recuperaTipoNoOperacao(noOperacao); } @Override public Object visitar(NoOperacaoBitwiseE noOperacao) throws ExcecaoVisitaASA { return recuperaTipoNoOperacao(noOperacao); } @Override public Object visitar(NoOperacaoBitwiseOu noOperacao) throws ExcecaoVisitaASA { return recuperaTipoNoOperacao(noOperacao); } @Override public Object visitar(NoOperacaoBitwiseXOR noOperacao) throws ExcecaoVisitaASA { return recuperaTipoNoOperacao(noOperacao); } @Override public Object visitar(NoBitwiseNao noOperacaoBitwiseNao) throws ExcecaoVisitaASA { TipoDado tipo = (TipoDado) noOperacaoBitwiseNao.getExpressao().aceitar(this); if (tipo != TipoDado.INTEIRO){ notificarErroSemantico(new ErroTiposIncompativeis(noOperacaoBitwiseNao, tipo, TipoDado.LOGICO)); throw new ExcecaoVisitaASA(new ExcecaoImpossivelDeterminarTipoDado(), asa, noOperacaoBitwiseNao); } return tipo; } @Override public Object visitar(NoPara noPara) throws ExcecaoVisitaASA { memoria.empilharEscopo(); try { if (noPara.getInicializacao() != null) { noPara.getInicializacao().aceitar(this); } } catch (ExcecaoVisitaASA excecao) { if (!(excecao.getCause() instanceof ExcecaoImpossivelDeterminarTipoDado)) throw excecao; } try { TipoDado tipoDadoCondicao = (TipoDado) noPara.getCondicao().aceitar(this); if (tipoDadoCondicao != TipoDado.LOGICO) { notificarErroSemantico(new ErroTiposIncompativeis(noPara, tipoDadoCondicao)); } } catch (ExcecaoVisitaASA excecao) { if (!(excecao.getCause() instanceof ExcecaoImpossivelDeterminarTipoDado)) throw excecao; } try { noPara.getIncremento().aceitar(this); } catch (ExcecaoVisitaASA excecao) { if (!(excecao.getCause() instanceof ExcecaoImpossivelDeterminarTipoDado)) throw excecao; } analisarListaBlocos(noPara.getBlocos()); memoria.desempilharEscopo(); return null; } @Override public Object visitar(NoPare noPare) throws ExcecaoVisitaASA { return null; } @Override public Object visitar(NoPercorra noPercorra) throws ExcecaoVisitaASA { throw new UnsupportedOperationException("Not supported yet."); } @Override public Object visitar(NoReal noReal) throws ExcecaoVisitaASA { return TipoDado.REAL; } @Override public Object visitar(NoReferenciaMatriz noReferenciaMatriz) throws ExcecaoVisitaASA { try { TipoDado tipoLinha = (TipoDado) noReferenciaMatriz.getLinha().aceitar(this); TipoDado tipoColuna = (TipoDado) noReferenciaMatriz.getColuna().aceitar(this); if (tipoLinha != TipoDado.INTEIRO && tipoColuna != TipoDado.INTEIRO) { notificarErroSemantico(new ErroTiposIncompativeis(noReferenciaMatriz, tipoLinha, TipoDado.INTEIRO, tipoColuna, TipoDado.INTEIRO)); } } catch (ExcecaoVisitaASA excecao) { if (!(excecao.getCause() instanceof ExcecaoImpossivelDeterminarTipoDado)) { throw excecao; } } try { Simbolo simbolo = memoria.getSimbolo(noReferenciaMatriz.getNome()); if (!(simbolo instanceof Matriz)) { notificarErroSemantico(new ErroReferenciaInvalida(noReferenciaMatriz, simbolo)); } return simbolo.getTipoDado(); } catch (ExcecaoSimboloNaoDeclarado excecaoSimboloNaoDeclarado) { notificarErroSemantico(new ErroSimboloNaoDeclarado(noReferenciaMatriz)); } throw new ExcecaoVisitaASA(new ExcecaoImpossivelDeterminarTipoDado(), asa, noReferenciaMatriz); } @Override public Object visitar(NoReferenciaVariavel noReferenciaVariavel) throws ExcecaoVisitaASA { if (noReferenciaVariavel.getEscopo() == null) { try { return analisarReferenciaVariavelPrograma(noReferenciaVariavel); } catch (ExcecaoImpossivelDeterminarTipoDado ex) { throw new ExcecaoVisitaASA(ex, asa, noReferenciaVariavel); } } else { return analisarReferenciaVariavelBiblioteca(noReferenciaVariavel); } } @Override public Object visitar(NoReferenciaVetor noReferenciaVetor) throws ExcecaoVisitaASA { try { TipoDado tipoIndice = (TipoDado) noReferenciaVetor.getIndice().aceitar(this); if (tipoIndice != TipoDado.INTEIRO) { notificarErroSemantico(new ErroTiposIncompativeis(noReferenciaVetor, tipoIndice, TipoDado.INTEIRO)); } } catch (ExcecaoVisitaASA excecao) { if (!(excecao.getCause() instanceof ExcecaoImpossivelDeterminarTipoDado)) { throw excecao; } } try { Simbolo simbolo = memoria.getSimbolo(noReferenciaVetor.getNome()); if (!(simbolo instanceof Vetor)) { notificarErroSemantico(new ErroReferenciaInvalida(noReferenciaVetor, simbolo)); } return simbolo.getTipoDado(); } catch (ExcecaoSimboloNaoDeclarado excecaoSimboloNaoDeclarado) { notificarErroSemantico(new ErroSimboloNaoDeclarado(noReferenciaVetor)); } throw new ExcecaoVisitaASA(new ExcecaoImpossivelDeterminarTipoDado(), asa, noReferenciaVetor); } @Override public Object visitar(NoRetorne noRetorne) throws ExcecaoVisitaASA { TipoDado tipoDadoRetorno = TipoDado.VAZIO; if (noRetorne.getExpressao() != null) { tipoDadoRetorno = (TipoDado) noRetorne.getExpressao().aceitar(this); } if (funcaoAtual.getTipoDado() != tipoDadoRetorno) { notificarErroSemantico(new ErroTiposIncompativeis(noRetorne, new String[] { funcaoAtual.getNome() }, funcaoAtual.getTipoDado(), tipoDadoRetorno)); } return null; } @Override public Object visitar(NoSe noSe) throws ExcecaoVisitaASA { TipoDado tipoDadoCondicao = (TipoDado) noSe.getCondicao().aceitar(this); if (tipoDadoCondicao != TipoDado.LOGICO) { notificarErroSemantico(new ErroTiposIncompativeis(noSe, tipoDadoCondicao)); } analisarListaBlocos(noSe.getBlocosVerdadeiros()); analisarListaBlocos(noSe.getBlocosFalsos()); return null; } @Override public Object visitar(NoVetor noVetor) throws ExcecaoVisitaASA { List<NoExpressao> valores = (List) noVetor.getValores(); if (valores != null && !valores.isEmpty()) { try { TipoDado tipoDadoVetor = (TipoDado) ((NoExpressao) valores.get(0)).aceitar(this); for (int i = 1; i < valores.size(); i++) { TipoDado tipoDadoElemento = (TipoDado) ((NoExpressao) valores.get(i)).aceitar(this); if (tipoDadoElemento != tipoDadoVetor) { notificarErroSemantico(new ErroSemantico(noVetor.getTrechoCodigoFonte()) { @Override protected String construirMensagem() { return "A inicialização do vetor possui mais de um tipo de dado"; } }); throw new ExcecaoVisitaASA(new ExcecaoImpossivelDeterminarTipoDado(), asa, noVetor); } } return tipoDadoVetor; } catch (Exception excecao) { //excecao.printStackTrace(System.out); throw new ExcecaoVisitaASA(new ExcecaoImpossivelDeterminarTipoDado(), asa, noVetor); } } else { //TODO Fazer essa verificaçao no Sintatico (Portugol.g) notificarErroSemantico(new ErroSemantico(noVetor.getTrechoCodigoFonte()) { @Override protected String construirMensagem() { return "A inicialização do vetor não possui elementos"; } }); throw new ExcecaoVisitaASA(new ExcecaoImpossivelDeterminarTipoDado(), asa, noVetor); } } @Override public Object visitar(NoDeclaracaoParametro noDeclaracaoParametro) throws ExcecaoVisitaASA { String nome = noDeclaracaoParametro.getNome(); TipoDado tipoDado = noDeclaracaoParametro.getTipoDado(); Quantificador quantificador = noDeclaracaoParametro.getQuantificador(); Simbolo simbolo = null; if (quantificador == Quantificador.VALOR) { simbolo = new Variavel(nome, tipoDado, noDeclaracaoParametro); } else if (quantificador == Quantificador.VETOR) { simbolo = new Vetor(nome, tipoDado, noDeclaracaoParametro, 0, new ArrayList<Object>()); } else if (quantificador == Quantificador.MATRIZ) { simbolo = new Matriz(nome, tipoDado, noDeclaracaoParametro, 0, 0, new ArrayList<List<Object>>()); } try { Simbolo simboloExistente = memoria.getSimbolo(nome); final boolean global = memoria.isGlobal(simboloExistente); final boolean local = memoria.isLocal(simboloExistente); memoria.empilharEscopo(); memoria.adicionarSimbolo(simbolo); final boolean global1 = memoria.isGlobal(simbolo); final boolean local1 = memoria.isLocal(simbolo); if ( (global && global1) || (local && local1) ) { simbolo.setRedeclarado(true); notificarErroSemantico(new ErroParametroRedeclarado(noDeclaracaoParametro, funcaoAtual)); memoria.desempilharEscopo(); } else { memoria.desempilharEscopo(); memoria.adicionarSimbolo(simbolo); simbolo.setInicializado(true); Simbolo simboloGlobal = memoria.isGlobal(simboloExistente)? simboloExistente : simbolo; Simbolo simboloLocal = memoria.isGlobal(simboloExistente)? simbolo : simboloExistente; notificarAviso(new AvisoSimboloGlobalOcultado(simboloGlobal, simboloLocal, noDeclaracaoParametro)); } } catch (ExcecaoSimboloNaoDeclarado excecaoSimboloNaoDeclarado) { simbolo.setInicializado(true); memoria.adicionarSimbolo(simbolo); } return null; } private static List<String> getLista() { List<String> funcoes = new ArrayList<String>(); funcoes.add("leia"); funcoes.add("escreva"); funcoes.add("limpa"); return funcoes; } private TipoDado recuperaTipoNoOperacao(NoOperacao noOperacao) throws ExcecaoVisitaASA { TipoDado operandoEsquerdo = null; TipoDado operandoDireito = null; try { operandoEsquerdo = (TipoDado) noOperacao.getOperandoEsquerdo().aceitar(this); } catch (ExcecaoVisitaASA excecao) { if (!(excecao.getCause() instanceof ExcecaoImpossivelDeterminarTipoDado)) { throw excecao; } } try { operandoDireito = (TipoDado) noOperacao.getOperandoDireito().aceitar(this); } catch (ExcecaoVisitaASA excecao) { if (!(excecao.getCause() instanceof ExcecaoImpossivelDeterminarTipoDado)) { throw excecao; } } if (operandoEsquerdo != null && operandoDireito != null) { try { return tabelaCompatibilidadeTipos.obterTipoRetornoOperacao(noOperacao.getClass(), operandoEsquerdo, operandoDireito); } catch (ExcecaoValorSeraConvertido excecao) { notificarAviso(new AvisoValorExpressaoSeraConvertido(noOperacao, excecao.getTipoEntrada(), excecao.getTipoSaida())); return excecao.getTipoSaida(); } catch (ExcecaoImpossivelDeterminarTipoDado excecao) { notificarErroSemantico(new ErroTiposIncompativeis(noOperacao, operandoEsquerdo, operandoDireito)); throw new ExcecaoVisitaASA(excecao, asa, noOperacao); } } else { throw new ExcecaoVisitaASA(new ExcecaoImpossivelDeterminarTipoDado(), asa, noOperacao); } } private void analisarListaBlocos(List<NoBloco> blocos) throws ExcecaoVisitaASA { if (blocos == null) { return; } memoria.empilharEscopo(); for (NoBloco noBloco : blocos) { try { noBloco.aceitar(this); } catch (ExcecaoVisitaASA excecao) { if (!(excecao.getCause() instanceof ExcecaoImpossivelDeterminarTipoDado)) { throw excecao; } } } memoria.desempilharEscopo(); } @Override public Object visitar(NoInclusaoBiblioteca noInclusaoBiblioteca) throws ExcecaoVisitaASA { String nome = noInclusaoBiblioteca.getNome(); String alias = noInclusaoBiblioteca.getAlias(); try { try { memoria.getSimbolo(nome); notificarErroSemantico(new ErroInclusaoBiblioteca(noInclusaoBiblioteca.getTrechoCodigoFonteNome(), new Exception(String.format("o identificador \"%s\" já está sendo utilizado", nome)))); } catch (ExcecaoSimboloNaoDeclarado excecao) { MetaDadosBiblioteca metaDadosBiblioteca = GerenciadorBibliotecas.getInstance().obterMetaDadosBiblioteca(nome); if (metaDadosBibliotecas.containsKey(nome)) { notificarErroSemantico(new ErroInclusaoBiblioteca(noInclusaoBiblioteca.getTrechoCodigoFonteNome(), new Exception(String.format("A biblioteca \"%s\" já foi incluída", nome)))); } else { metaDadosBibliotecas.put(nome, metaDadosBiblioteca); } if (alias != null) { try { memoria.getSimbolo(nome); notificarErroSemantico(new ErroInclusaoBiblioteca(noInclusaoBiblioteca.getTrechoCodigoFonteNome(), new Exception(String.format("o identificador \"%s\" já está sendo utilizado", nome)))); } catch (ExcecaoSimboloNaoDeclarado excecao2) { if (metaDadosBibliotecas.containsKey(alias)) { notificarErroSemantico(new ErroInclusaoBiblioteca(noInclusaoBiblioteca.getTrechoCodigoFonteAlias(), new Exception(String.format("O alias \"%s\" já está sendo utilizado pela biblioteca \"%s\"", alias, metaDadosBibliotecas.get(alias).getNome())))); } else { metaDadosBibliotecas.put(alias, metaDadosBiblioteca); } } } } } catch (ErroCarregamentoBiblioteca erro) { notificarErroSemantico(new ErroInclusaoBiblioteca(noInclusaoBiblioteca.getTrechoCodigoFonteNome(), erro)); } return null; } private TipoDado analisarReferenciaVariavelPrograma(NoReferenciaVariavel noReferenciaVariavel) throws ExcecaoImpossivelDeterminarTipoDado { try { Simbolo simbolo = memoria.getSimbolo(noReferenciaVariavel.getNome()); if (!simbolo.inicializado()){ notificarErroSemantico(new ErroSimboloNaoInicializado(noReferenciaVariavel,simbolo)); } if (!(simbolo instanceof Variavel) && !declarandoVetor && !declarandoMatriz && !passandoReferencia && !passandoParametro) { notificarErroSemantico(new ErroReferenciaInvalida(noReferenciaVariavel, simbolo)); } return simbolo.getTipoDado(); } catch (ExcecaoSimboloNaoDeclarado excecaoSimboloNaoDeclarado) { notificarErroSemantico(new ErroSimboloNaoDeclarado(noReferenciaVariavel)); } throw new ExcecaoImpossivelDeterminarTipoDado(); } private TipoDado analisarReferenciaVariavelBiblioteca(NoReferenciaVariavel noReferenciaVariavel) throws ExcecaoVisitaASA { final String escopo = noReferenciaVariavel.getEscopo(); final String nome = noReferenciaVariavel.getNome(); final MetaDadosBiblioteca metaDadosBiblioteca = metaDadosBibliotecas.get(escopo); if (metaDadosBiblioteca != null) { MetaDadosConstante metaDadosConstante = metaDadosBiblioteca.getMetaDadosConstantes().obter(nome); if (metaDadosConstante != null) { return metaDadosConstante.getTipoDado(); } notificarErroSemantico(new ErroSemantico(noReferenciaVariavel.getTrechoCodigoFonteNome()) { @Override protected String construirMensagem() { return String.format("A constante \"%s\" não existe na biblioteca \"%s\"", nome, metaDadosBiblioteca.getNome()); } }); } else { notificarErroSemantico(new ErroSemantico(noReferenciaVariavel.getTrechoCodigoFonteNome()) { @Override protected String construirMensagem() { return String.format("A biblioteca \"%s\" não foi incluída no programa", escopo); } }); } throw new ExcecaoVisitaASA(new ExcecaoImpossivelDeterminarTipoDado(), asa, noReferenciaVariavel); } }
false
true
public Object visitar(final NoOperacaoAtribuicao noOperacao) throws ExcecaoVisitaASA { TipoDado tipoDadoRetorno; TipoDado operandoEsquerdo = null; TipoDado operandoDireito = null; Simbolo simbolo = null; boolean inicializadoAnterior = false; if (!(noOperacao.getOperandoEsquerdo() instanceof NoReferencia)){ notificarErroSemantico(new ErroOperacaoComExpressaoConstante(noOperacao, noOperacao.getOperandoEsquerdo())); } else { try { if (noOperacao.getOperandoEsquerdo() instanceof NoReferenciaVariavel) { simbolo = memoria.getSimbolo(((NoReferencia)noOperacao.getOperandoEsquerdo()).getNome()); inicializadoAnterior = simbolo.inicializado(); simbolo.setInicializado(true); if (simbolo instanceof Variavel){ if (simbolo.constante()) { final Simbolo pSimbolo = simbolo; notificarErroSemantico(new ErroSemantico(noOperacao.getOperandoDireito().getTrechoCodigoFonte()) { @Override protected String construirMensagem() { StringBuilder sb = new StringBuilder(); if (pSimbolo instanceof Variavel) { sb.append("\""); sb.append(pSimbolo.getNome()); sb.append("\" é uma constante, e portanto, não pode ter seu valor alterado após a inicialização"); } else if (pSimbolo instanceof Vetor) { sb.append("O vetor \""); sb.append(pSimbolo.getNome()); sb.append("\" é constante e, portanto, não pode ter seus valores alterados após a inicialização"); } else if (pSimbolo instanceof Matriz) { sb.append("A matriz \""); sb.append(pSimbolo.getNome()); sb.append("\" é constante e, portanto, não pode ter seu valor alterado após a inicialização"); } return sb.toString(); } }); } if ((noOperacao.getOperandoDireito() instanceof NoMatriz) || (noOperacao.getOperandoDireito() instanceof NoVetor)) notificarErroSemantico(new ErroSemantico(noOperacao.getOperandoDireito().getTrechoCodigoFonte()) { @Override protected String construirMensagem() { return "não é possível atribuir uma matriz ou um vetor a uma variável"; } }); } else if (simbolo instanceof Vetor) { if (!(noOperacao.getOperandoDireito() instanceof NoVetor)){ notificarErroSemantico(new ErroSemantico(noOperacao.getOperandoDireito().getTrechoCodigoFonte()) { @Override protected String construirMensagem() { return "O vetor deve ser inicializado com um vetor literal"; } }); } } else if (simbolo instanceof Matriz) { if (!simbolo.inicializado() && !(noOperacao.getOperandoDireito() instanceof NoMatriz)){ notificarErroSemantico(new ErroSemantico(noOperacao.getOperandoDireito().getTrechoCodigoFonte()) { @Override protected String construirMensagem() { return "A matriz deve ser inicializada com uma matriz literal"; } }); } } } else if (noOperacao.getOperandoEsquerdo() instanceof NoReferenciaMatriz || noOperacao.getOperandoEsquerdo() instanceof NoReferenciaVetor) { if (noOperacao.getOperandoDireito() instanceof NoVetor) { notificarErroSemantico(new ErroSemantico(noOperacao.getOperandoDireito().getTrechoCodigoFonte()) { @Override protected String construirMensagem() { return "Deve-se atribuir um valor à uma posição do vetor"; } }); } else if (noOperacao.getOperandoDireito() instanceof NoMatriz ) { notificarErroSemantico(new ErroSemantico(noOperacao.getOperandoDireito().getTrechoCodigoFonte()) { @Override protected String construirMensagem() { return "Deve-se atribuir um valor à uma posição da matriz"; } }); } } } catch (ExcecaoSimboloNaoDeclarado excecaoSimboloNaoDeclarado) { // Não faz nada } } try { operandoEsquerdo = (TipoDado) noOperacao.getOperandoEsquerdo().aceitar(this); } catch (ExcecaoVisitaASA excecao) { if (!(excecao.getCause() instanceof ExcecaoImpossivelDeterminarTipoDado)) { throw excecao; } } if (simbolo != null) { simbolo.setInicializado(inicializadoAnterior); } try { operandoDireito = (TipoDado) noOperacao.getOperandoDireito().aceitar(this); } catch (ExcecaoVisitaASA excecao) { if (!(excecao.getCause() instanceof ExcecaoImpossivelDeterminarTipoDado)) { throw excecao; } } if (operandoEsquerdo != null && operandoDireito != null) { try { tipoDadoRetorno = tabelaCompatibilidadeTipos.obterTipoRetornoOperacao(noOperacao.getClass(), operandoEsquerdo, operandoDireito); } catch (ExcecaoValorSeraConvertido excecao) { notificarAviso(new AvisoValorExpressaoSeraConvertido(noOperacao.getOperandoDireito().getTrechoCodigoFonte(), noOperacao, excecao.getTipoEntrada(), excecao.getTipoSaida())); tipoDadoRetorno = excecao.getTipoSaida(); } catch (ExcecaoImpossivelDeterminarTipoDado excecao) { notificarErroSemantico(new ErroTiposIncompativeis(noOperacao, operandoEsquerdo, operandoDireito)); throw new ExcecaoVisitaASA(excecao, asa, noOperacao); } } else { throw new ExcecaoVisitaASA(new ExcecaoImpossivelDeterminarTipoDado(), asa, noOperacao); } if (simbolo != null) { simbolo.setInicializado(true); } return tipoDadoRetorno; }
public Object visitar(final NoOperacaoAtribuicao noOperacao) throws ExcecaoVisitaASA { TipoDado tipoDadoRetorno; TipoDado operandoEsquerdo = null; TipoDado operandoDireito = null; Simbolo simbolo = null; boolean inicializadoAnterior = false; if (!(noOperacao.getOperandoEsquerdo() instanceof NoReferencia)){ notificarErroSemantico(new ErroOperacaoComExpressaoConstante(noOperacao, noOperacao.getOperandoEsquerdo())); } else { try { if (noOperacao.getOperandoEsquerdo() instanceof NoReferenciaVariavel) { simbolo = memoria.getSimbolo(((NoReferencia)noOperacao.getOperandoEsquerdo()).getNome()); inicializadoAnterior = simbolo.inicializado(); simbolo.setInicializado(true); if (simbolo instanceof Variavel){ if (simbolo.constante()) { final Simbolo pSimbolo = simbolo; notificarErroSemantico(new ErroSemantico(noOperacao.getOperandoDireito().getTrechoCodigoFonte()) { @Override protected String construirMensagem() { StringBuilder sb = new StringBuilder(); if (pSimbolo instanceof Variavel) { sb.append("\""); sb.append(pSimbolo.getNome()); sb.append("\" é uma constante, e portanto, não pode ter seu valor alterado após a inicialização"); } else if (pSimbolo instanceof Vetor) { sb.append("O vetor \""); sb.append(pSimbolo.getNome()); sb.append("\" é constante e, portanto, não pode ter seus valores alterados após a inicialização"); } else if (pSimbolo instanceof Matriz) { sb.append("A matriz \""); sb.append(pSimbolo.getNome()); sb.append("\" é constante e, portanto, não pode ter seu valor alterado após a inicialização"); } return sb.toString(); } }); } if ((noOperacao.getOperandoDireito() instanceof NoMatriz) || (noOperacao.getOperandoDireito() instanceof NoVetor)) notificarErroSemantico(new ErroSemantico(noOperacao.getOperandoDireito().getTrechoCodigoFonte()) { @Override protected String construirMensagem() { return "não é possível atribuir uma matriz ou um vetor a uma variável"; } }); } else if (simbolo instanceof Vetor) { if (!(noOperacao.getOperandoDireito() instanceof NoVetor)){ notificarErroSemantico(new ErroSemantico(noOperacao.getOperandoDireito().getTrechoCodigoFonte()) { @Override protected String construirMensagem() { return "O vetor deve ser inicializado com um vetor literal"; } }); } } else if (simbolo instanceof Matriz) { if (!simbolo.inicializado() && !(noOperacao.getOperandoDireito() instanceof NoMatriz)){ notificarErroSemantico(new ErroSemantico(noOperacao.getOperandoDireito().getTrechoCodigoFonte()) { @Override protected String construirMensagem() { return "A matriz deve ser inicializada com uma matriz literal"; } }); } } } else if (noOperacao.getOperandoEsquerdo() instanceof NoReferenciaMatriz || noOperacao.getOperandoEsquerdo() instanceof NoReferenciaVetor) { if (noOperacao.getOperandoDireito() instanceof NoVetor) { notificarErroSemantico(new ErroSemantico(noOperacao.getOperandoDireito().getTrechoCodigoFonte()) { @Override protected String construirMensagem() { return "Deve-se atribuir um valor à uma posição do vetor"; } }); } else if (noOperacao.getOperandoDireito() instanceof NoMatriz ) { notificarErroSemantico(new ErroSemantico(noOperacao.getOperandoDireito().getTrechoCodigoFonte()) { @Override protected String construirMensagem() { return "Deve-se atribuir um valor à uma posição da matriz"; } }); } } else if (noOperacao.getOperandoEsquerdo() instanceof NoChamadaFuncao) { notificarErroSemantico(new ErroSemantico(noOperacao.getOperandoEsquerdo().getTrechoCodigoFonte()) { @Override protected String construirMensagem() { return "Não é possível atribuir uma expressão a uma chamada de função."; } }); } } catch (ExcecaoSimboloNaoDeclarado excecaoSimboloNaoDeclarado) { // Não faz nada } } try { operandoEsquerdo = (TipoDado) noOperacao.getOperandoEsquerdo().aceitar(this); } catch (ExcecaoVisitaASA excecao) { if (!(excecao.getCause() instanceof ExcecaoImpossivelDeterminarTipoDado)) { throw excecao; } } if (simbolo != null) { simbolo.setInicializado(inicializadoAnterior); } try { operandoDireito = (TipoDado) noOperacao.getOperandoDireito().aceitar(this); } catch (ExcecaoVisitaASA excecao) { if (!(excecao.getCause() instanceof ExcecaoImpossivelDeterminarTipoDado)) { throw excecao; } } if (operandoEsquerdo != null && operandoDireito != null) { try { tipoDadoRetorno = tabelaCompatibilidadeTipos.obterTipoRetornoOperacao(noOperacao.getClass(), operandoEsquerdo, operandoDireito); } catch (ExcecaoValorSeraConvertido excecao) { notificarAviso(new AvisoValorExpressaoSeraConvertido(noOperacao.getOperandoDireito().getTrechoCodigoFonte(), noOperacao, excecao.getTipoEntrada(), excecao.getTipoSaida())); tipoDadoRetorno = excecao.getTipoSaida(); } catch (ExcecaoImpossivelDeterminarTipoDado excecao) { notificarErroSemantico(new ErroTiposIncompativeis(noOperacao, operandoEsquerdo, operandoDireito)); throw new ExcecaoVisitaASA(excecao, asa, noOperacao); } } else { throw new ExcecaoVisitaASA(new ExcecaoImpossivelDeterminarTipoDado(), asa, noOperacao); } if (simbolo != null) { simbolo.setInicializado(true); } return tipoDadoRetorno; }
diff --git a/src/volpes/ldk/client/TiledLoader.java b/src/volpes/ldk/client/TiledLoader.java index 6a38db1..3c09224 100644 --- a/src/volpes/ldk/client/TiledLoader.java +++ b/src/volpes/ldk/client/TiledLoader.java @@ -1,173 +1,175 @@ /* * Copyright (C) 2013 Lasse Dissing Hansen * * 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 volpes.ldk.client; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import volpes.ldk.utils.ImageOptimizer; import volpes.ldk.utils.Parsers; import volpes.ldk.utils.VFS; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.*; import java.nio.file.Path; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @auther Lasse Dissing Hansen */ public class TiledLoader implements ResourceLoader{ private Map<String,TiledMap> maps = new HashMap<String,TiledMap>(); private int numberOfLoadedObjects = 0; @Override public void initialize() { //To change body of implemented methods use File | Settings | File Templates. } @Override public void shutdown() { //To change body of implemented methods use File | Settings | File Templates. } @Override public Object get(String id) { return maps.get(id); } @Override public void load(Element xmlElement) { String id = xmlElement.getAttribute("id"); String path = xmlElement.getTextContent(); - if (path == null || path.length() == 0) + if (path == null || path.length() == 0) { System.err.println("Image resource [" + id + "] has invalid path"); + return; + } InputStream is; try { is = VFS.getFile(path); } catch (IOException e) { System.err.println("Unable to open file " + id + " at " + path); return; } Document doc = Parsers.parseXML(is); //Get map info Element infoElement = (Element)doc.getFirstChild(); int width = Integer.parseInt(infoElement.getAttribute("width")); int height = Integer.parseInt(infoElement.getAttribute("height")); int tilewidth = Integer.parseInt(infoElement.getAttribute("tilewidth")); int tileheight = Integer.parseInt(infoElement.getAttribute("tileheight")); //Check if map is supported String orientation = infoElement.getAttribute("orientation"); if (!orientation.equalsIgnoreCase("orthogonal")) { System.err.println("The tiled map " + id + " is not orthogonal and is therefore not supported"); return; } float version = Float.parseFloat(infoElement.getAttribute("version")); if (version != 1.0) { System.out.println("This Tiled map does not of version 1.0 and might contain unsupported features"); } //Load tileSets NodeList tileSetNodes = doc.getElementsByTagName("tileset"); List<TileSet> tileSets = parseTileSets(tileSetNodes,new File(path).toPath().toAbsolutePath().getParent()); //Load layers NodeList layerNodes = doc.getElementsByTagName("layer"); List<Layer> layers = parseLayers(layerNodes); TiledMap map = new TiledMap(width,height,tilewidth,tileheight,layers,tileSets); maps.put(id,map); numberOfLoadedObjects++; } private BufferedImage loadTileset(String path, Path tilePath) { Path pathObj = tilePath.resolve(new File(path).toPath()); try { InputStream is = VFS.getFile(pathObj.toFile().getPath()); BufferedImage set = ImageIO.read(is); return ImageOptimizer.optimize(set); } catch (IOException e) { e.printStackTrace(); return null; } } private List<TileSet> parseTileSets(NodeList tileSetNodes, Path relativTo) { List<TileSet> tileSets = new ArrayList<TileSet>(); for (int i = 0; i < tileSetNodes.getLength(); i++) { Node tileSetNode = tileSetNodes.item(i); Element tileSetElm = (Element)tileSetNode; Element imageNode = (Element)tileSetNode.getChildNodes().item(1); String imgPath = imageNode.getAttribute("source"); //imgPath = imgPath.substring(2, imgPath.length()); String name = imageNode.hasAttribute("name") ? imageNode.getAttribute("name") : ""; int tileWidth = Integer.parseInt(tileSetElm.getAttribute("tilewidth")); int tileHeight = Integer.parseInt(tileSetElm.getAttribute("tileheight")); int spacing = tileSetElm.hasAttribute("spacing") ? Integer.parseInt(tileSetElm.getAttribute("spacing")) : 0; int margin = tileSetElm.hasAttribute("margin") ? Integer.parseInt(tileSetElm.getAttribute("margin")) : 0; TileSet set = new TileSet(name,loadTileset(imgPath,relativTo),tileWidth,tileHeight,spacing,margin); tileSets.add(set); } return tileSets; } private List<Layer> parseLayers(NodeList layerNodes) { List<Layer> layers = new ArrayList<Layer>(); for (int i = 0; i < layerNodes.getLength();i++) { Node layerNode = layerNodes.item(i); NodeList tileNodes = layerNode.getChildNodes().item(1).getChildNodes(); //Jumps over <data> tag layers.add(loadLayer(tileNodes)); } return layers; } private Layer loadLayer(NodeList tileNodes) throws LDKException{ List<Integer> tiles = new ArrayList<Integer>(); for (int index = 0; index < tileNodes.getLength(); index++) { Node tileNode = tileNodes.item(index); if (tileNode.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element)tileNode; if (element.getTagName().equalsIgnoreCase("tile")) { tiles.add(Integer.parseInt(element.getAttribute("gid"))); } } } return new Layer(tiles); } @Override public String getLoaderID() { return "tiledmap"; //To change body of implemented methods use File | Settings | File Templates. } @Override public int getNumberOfLoadedObjects() { return numberOfLoadedObjects; //To change body of implemented methods use File | Settings | File Templates. } }
false
true
public void load(Element xmlElement) { String id = xmlElement.getAttribute("id"); String path = xmlElement.getTextContent(); if (path == null || path.length() == 0) System.err.println("Image resource [" + id + "] has invalid path"); InputStream is; try { is = VFS.getFile(path); } catch (IOException e) { System.err.println("Unable to open file " + id + " at " + path); return; } Document doc = Parsers.parseXML(is); //Get map info Element infoElement = (Element)doc.getFirstChild(); int width = Integer.parseInt(infoElement.getAttribute("width")); int height = Integer.parseInt(infoElement.getAttribute("height")); int tilewidth = Integer.parseInt(infoElement.getAttribute("tilewidth")); int tileheight = Integer.parseInt(infoElement.getAttribute("tileheight")); //Check if map is supported String orientation = infoElement.getAttribute("orientation"); if (!orientation.equalsIgnoreCase("orthogonal")) { System.err.println("The tiled map " + id + " is not orthogonal and is therefore not supported"); return; } float version = Float.parseFloat(infoElement.getAttribute("version")); if (version != 1.0) { System.out.println("This Tiled map does not of version 1.0 and might contain unsupported features"); } //Load tileSets NodeList tileSetNodes = doc.getElementsByTagName("tileset"); List<TileSet> tileSets = parseTileSets(tileSetNodes,new File(path).toPath().toAbsolutePath().getParent()); //Load layers NodeList layerNodes = doc.getElementsByTagName("layer"); List<Layer> layers = parseLayers(layerNodes); TiledMap map = new TiledMap(width,height,tilewidth,tileheight,layers,tileSets); maps.put(id,map); numberOfLoadedObjects++; }
public void load(Element xmlElement) { String id = xmlElement.getAttribute("id"); String path = xmlElement.getTextContent(); if (path == null || path.length() == 0) { System.err.println("Image resource [" + id + "] has invalid path"); return; } InputStream is; try { is = VFS.getFile(path); } catch (IOException e) { System.err.println("Unable to open file " + id + " at " + path); return; } Document doc = Parsers.parseXML(is); //Get map info Element infoElement = (Element)doc.getFirstChild(); int width = Integer.parseInt(infoElement.getAttribute("width")); int height = Integer.parseInt(infoElement.getAttribute("height")); int tilewidth = Integer.parseInt(infoElement.getAttribute("tilewidth")); int tileheight = Integer.parseInt(infoElement.getAttribute("tileheight")); //Check if map is supported String orientation = infoElement.getAttribute("orientation"); if (!orientation.equalsIgnoreCase("orthogonal")) { System.err.println("The tiled map " + id + " is not orthogonal and is therefore not supported"); return; } float version = Float.parseFloat(infoElement.getAttribute("version")); if (version != 1.0) { System.out.println("This Tiled map does not of version 1.0 and might contain unsupported features"); } //Load tileSets NodeList tileSetNodes = doc.getElementsByTagName("tileset"); List<TileSet> tileSets = parseTileSets(tileSetNodes,new File(path).toPath().toAbsolutePath().getParent()); //Load layers NodeList layerNodes = doc.getElementsByTagName("layer"); List<Layer> layers = parseLayers(layerNodes); TiledMap map = new TiledMap(width,height,tilewidth,tileheight,layers,tileSets); maps.put(id,map); numberOfLoadedObjects++; }
diff --git a/steamcraft/blocks/BlockTile.java b/steamcraft/blocks/BlockTile.java index ecc6e9f..f438eb4 100644 --- a/steamcraft/blocks/BlockTile.java +++ b/steamcraft/blocks/BlockTile.java @@ -1,12 +1,12 @@ package steamcraft.blocks; import net.minecraft.block.Block; import net.minecraft.block.material.Material; public class BlockTile extends Block{ public BlockTile() { super(Material.rock); setResistance(10F); - setStepSound(Block.soundTypeGrass); + setStepSound(Block.soundTypeStone); } }
true
true
public BlockTile() { super(Material.rock); setResistance(10F); setStepSound(Block.soundTypeGrass); }
public BlockTile() { super(Material.rock); setResistance(10F); setStepSound(Block.soundTypeStone); }
diff --git a/src/com/sohail/alam/http/server/LocalFileFetcher.java b/src/com/sohail/alam/http/server/LocalFileFetcher.java index dc25749..d0955c9 100644 --- a/src/com/sohail/alam/http/server/LocalFileFetcher.java +++ b/src/com/sohail/alam/http/server/LocalFileFetcher.java @@ -1,118 +1,118 @@ package com.sohail.alam.http.server; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import static com.sohail.alam.http.common.LoggerManager.LOGGER; /** * User: Sohail Alam * Version: 1.0.0 * Date: 21/9/13 * Time: 8:37 PM */ public class LocalFileFetcher { public static final LocalFileFetcher FETCHER = new LocalFileFetcher(); /** * Instantiates a new Local file fetcher. */ private LocalFileFetcher() { LOGGER.trace("LocalFileFetcher Constructor Initialized"); } /** * Normalize a given relative path String to get the actual path String * * @param path the path * * @return the normalized path */ private String normalizePath(String path) { String normalizedPath = new String(); // Make Sure Path Starts with a slash (/) if (!path.startsWith("/")) { path = "/" + path; } // Make sure path does not ends in "/" if (path.endsWith("/")) { path = path.substring(0, path.lastIndexOf("/")); } // ./www/somePath if (path.startsWith("/" + ServerProperties.PROP.webappPath())) { normalizedPath = "." + path; } else { normalizedPath = "./www" + path; } LOGGER.debug("Normalizing Path '{}' to '{}'", path, normalizedPath); return normalizedPath; } /** * Get bytes of the file. * * @param path the relative path of the file, which will be normalized automatically * @param callback the callback * * @return the byte[] containing the file data */ public <T extends LocalFileFetcherCallback> void fetch(String path, T callback) { final byte[] fileBytes; final File file = new File(this.normalizePath(path)); FileInputStream is = null; try { is = new FileInputStream(file); fileBytes = new byte[is.available()]; is.read(fileBytes); LOGGER.debug("File '{}' Fetched Successfully - {} bytes", path, fileBytes.length); callback.fetchSuccess(path, fileBytes); } catch (FileNotFoundException e) { LOGGER.debug("Exception Caught: {}", e.getMessage()); - callback.exceptionCaught(path, e); + callback.fileNotFound(path, e); } catch (IOException e) { LOGGER.debug("Exception Caught: {}", e.getMessage()); callback.exceptionCaught(path, e); } finally { if (is != null) { try { is.close(); } catch (IOException ignored) { LOGGER.debug("IO Exception Caught while closing Input Stream in finally, Nothing can be done here"); } } } } /** * The interface Local file fetcher callback which must be used to receive callbacks */ public interface LocalFileFetcherCallback { /** * Fetch success is called when a file is read successfully and * the data is ready to be delivered. * * @param path the path from which the file was read (Normalized Path) * @param data the data as byte array */ public void fetchSuccess(String path, byte[] data); /** * Fetch failed is called whenever there was an error reading the file * * @param path the path from which the file was to be read (Normalized Path) * @param cause the throwable object containing the cause */ public void fileNotFound(String path, Throwable cause); /** * Exception caught. * * @param path the path * @param cause the cause */ public void exceptionCaught(String path, Throwable cause); } }
true
true
public <T extends LocalFileFetcherCallback> void fetch(String path, T callback) { final byte[] fileBytes; final File file = new File(this.normalizePath(path)); FileInputStream is = null; try { is = new FileInputStream(file); fileBytes = new byte[is.available()]; is.read(fileBytes); LOGGER.debug("File '{}' Fetched Successfully - {} bytes", path, fileBytes.length); callback.fetchSuccess(path, fileBytes); } catch (FileNotFoundException e) { LOGGER.debug("Exception Caught: {}", e.getMessage()); callback.exceptionCaught(path, e); } catch (IOException e) { LOGGER.debug("Exception Caught: {}", e.getMessage()); callback.exceptionCaught(path, e); } finally { if (is != null) { try { is.close(); } catch (IOException ignored) { LOGGER.debug("IO Exception Caught while closing Input Stream in finally, Nothing can be done here"); } } } }
public <T extends LocalFileFetcherCallback> void fetch(String path, T callback) { final byte[] fileBytes; final File file = new File(this.normalizePath(path)); FileInputStream is = null; try { is = new FileInputStream(file); fileBytes = new byte[is.available()]; is.read(fileBytes); LOGGER.debug("File '{}' Fetched Successfully - {} bytes", path, fileBytes.length); callback.fetchSuccess(path, fileBytes); } catch (FileNotFoundException e) { LOGGER.debug("Exception Caught: {}", e.getMessage()); callback.fileNotFound(path, e); } catch (IOException e) { LOGGER.debug("Exception Caught: {}", e.getMessage()); callback.exceptionCaught(path, e); } finally { if (is != null) { try { is.close(); } catch (IOException ignored) { LOGGER.debug("IO Exception Caught while closing Input Stream in finally, Nothing can be done here"); } } } }
diff --git a/src/main/java/org/javadrop/packaging/impl/RPMPackagerStrategy.java b/src/main/java/org/javadrop/packaging/impl/RPMPackagerStrategy.java index 2edf149..bc3f7bd 100644 --- a/src/main/java/org/javadrop/packaging/impl/RPMPackagerStrategy.java +++ b/src/main/java/org/javadrop/packaging/impl/RPMPackagerStrategy.java @@ -1,222 +1,223 @@ /******************************************************************************* * Copyright 2011 iovation * * 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.javadrop.packaging.impl; import java.io.File; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.logging.Log; import org.apache.tools.ant.Project; import org.freecompany.redline.ant.RedlineTask; import org.freecompany.redline.ant.RpmFileSet; import org.javadrop.runner.RunnerStrategy; import org.javadrop.runner.impl.JavaAppStrategy; import org.javadrop.runner.impl.JettyStrategy; import org.javadrop.runner.impl.MainServiceStrategy; /** * This packager strategy uses the 'redline' java rpm generation code to make an * RPM. * * The 'mapping' this rpm strategy uses is simple. It takes the destination * files and mirrors them on the * * @author gcooperpdx * */ public class RPMPackagerStrategy extends BasePackagerStrategy { @Override public void postProcessArtifacts(RunnerStrategy runner, File workingDirectory) { // Rename any files necessary. Map<File, File> mapFiles = runner.getArtifactRenames(workingDirectory); for (Entry<File, File> mapFile : mapFiles.entrySet()) { File oldFile = mapFile.getKey(); File newFile = mapFile.getValue(); newFile.getParentFile().mkdirs(); oldFile.renameTo(newFile); } } @Override public void createPackage(File packagerDirectory, File workingDirectory, Collection<RunnerStrategy> runners, Log log) throws MojoExecutionException { // TODO Bunch of items that need to be parameterized properly. // File filename = new File(packagerDirectory, // "rpmtest-1.0-1.noarch.rpm"); if (packagerDirectory == null) { get_log().error("'packagerDirectory' is null"); throw new MojoExecutionException("'packagerDirectory' is null"); } Project project = new Project(); //project.setCoreLoader(getClass().getClassLoader()); project.setCoreLoader(ClassLoader.getSystemClassLoader()); project.init(); RedlineTask task = new RedlineTask(); task.setProject(project); task.setDestination(packagerDirectory); task.setName(getRequiredParam("PKG_NAME")); task.setArchitecture("NOARCH"); task.setLicense("proprietary"); // RPM has VERY SUBTLE and very bad behavior with text in the version. It appears to work but doesn't upon // rpm -e task.setVersion(getRequiredParam("PKG_VERSION").replaceFirst("-SNAPSHOT", "")); task.setRelease(getRequiredParam("PKG_RELEASE")); task.setGroup("Application/Office"); task.setSourcePackage(getRequiredParam("PKG_NAME") + getRequiredParam("PKG_VERSION") + ".src.rpm"); task.setPreInstallScript(new File(workingDirectory + File.separator + "rpm" + File.separator + "preinstall.sh")); task.setPostInstallScript(new File(workingDirectory + File.separator + "rpm" + File.separator + "postinstall.sh")); task.setPostUninstallScript(new File(workingDirectory + File.separator + "rpm" + File.separator + "postremove.sh")); // Get the mapping for the files that the runner(s) need to install. for (RunnerStrategy runner : runners) { Map<File, Collection<File>> installSet = runner .getInstallSet(workingDirectory); for (Map.Entry<File, Collection<File>> instEntry : installSet .entrySet()) { String leafDirName = instEntry.getKey().getName(); File installDir; if (isServiceDir(leafDirName)) { installDir = new File(getServiceDirectory()); } else { installDir = new File(getInstallLoc() + File.separator + leafDirName); } // If destination directory isn't available, bail. for (File destFile : instEntry.getValue()) { RpmFileSet fs = new RpmFileSet(); // fs.setDir(installDir); fs.setPrefix(installDir.getAbsolutePath()); // getInstallLoc() // + // installDir.getinstEntry.get"/etc"); File sourceFile = new File(instEntry.getKey().getName() + File.separator + destFile.getName()); fs.setFile(sourceFile); // File("source/test/prein.sh")); File sourceDir = new File(workingDirectory.getPath() + File.separator + instEntry.getKey()); fs.setDir(sourceDir); fs.setConfig(true); fs.setNoReplace(true); fs.setDoc(true); fs.setGroup(getGroup()); fs.setGid(getGid()); fs.setUserName(getUser()); fs.setUid(getUid()); + fs.setFileMode("0755"); task.addRpmfileset(fs); } } } // Create the rpm task.execute(); } /** * Strips the '-SNAPSHOT' text from a string * @param snapshotStr String that MAY have '-SNAPSHOT' inside of it * @return The string with -SNAPSHOT removed */ private String snapshotStripped(String requiredParam) { return requiredParam.replaceFirst("-SNAPSHOT", ""); } /** * Checks to see if the given directory 'leaf' name is that of the service * script directory for the system. * * @param dirName * Leaf name of the directory in question * @return True if 'dirName' is the name of the os-specific location for * service scripts */ private boolean isServiceDir(String dirName) { return "init.d".equals(dirName); } /** * Get the directory that contains the service launching scripts. Currently * this is very CentOS oriented * * @return The system-specific path for where the service start scripts are. */ private String getServiceDirectory() { return File.separator + "etc" + File.separator + "rc.d" + File.separator + "init.d"; } @Override public Map<File, File> getConversionFiles(File outputDirectory, RunnerStrategy runner) { Map<File, File> conversionFiles = new HashMap<File, File>(); if ((runner instanceof MainServiceStrategy) || (runner instanceof JettyStrategy) || (runner instanceof JavaAppStrategy)) { conversionFiles.put(new File(getPrefix() + File.separator + "postinstall.vm"), new File(outputDirectory + File.separator + "rpm" + File.separator + "postinstall.sh")); conversionFiles.put(new File(getPrefix() + File.separator + "postremove.vm"), new File(outputDirectory + File.separator + "rpm" + File.separator + "postremove.sh")); conversionFiles.put(new File(getPrefix() + File.separator + "preinstall.vm"), new File(outputDirectory + File.separator + "rpm" + File.separator + "preinstall.sh")); } return conversionFiles; } /** * Returns the install location * * @return Where the package is to be installed... As a string. * @throws MojoExecutionException * Thrown if required variable is missing */ protected String getRequiredParam(String parameter) throws MojoExecutionException { String value = packagerVariables.get(parameter); if (value == null) { throw new MojoExecutionException("Missing required parameter: " + parameter); } return value; } private String getPrefix() { return "org" + File.separator + "javadrop" + File.separator + "packagerstrategy" + File.separator + "rpm"; } }
true
true
public void createPackage(File packagerDirectory, File workingDirectory, Collection<RunnerStrategy> runners, Log log) throws MojoExecutionException { // TODO Bunch of items that need to be parameterized properly. // File filename = new File(packagerDirectory, // "rpmtest-1.0-1.noarch.rpm"); if (packagerDirectory == null) { get_log().error("'packagerDirectory' is null"); throw new MojoExecutionException("'packagerDirectory' is null"); } Project project = new Project(); //project.setCoreLoader(getClass().getClassLoader()); project.setCoreLoader(ClassLoader.getSystemClassLoader()); project.init(); RedlineTask task = new RedlineTask(); task.setProject(project); task.setDestination(packagerDirectory); task.setName(getRequiredParam("PKG_NAME")); task.setArchitecture("NOARCH"); task.setLicense("proprietary"); // RPM has VERY SUBTLE and very bad behavior with text in the version. It appears to work but doesn't upon // rpm -e task.setVersion(getRequiredParam("PKG_VERSION").replaceFirst("-SNAPSHOT", "")); task.setRelease(getRequiredParam("PKG_RELEASE")); task.setGroup("Application/Office"); task.setSourcePackage(getRequiredParam("PKG_NAME") + getRequiredParam("PKG_VERSION") + ".src.rpm"); task.setPreInstallScript(new File(workingDirectory + File.separator + "rpm" + File.separator + "preinstall.sh")); task.setPostInstallScript(new File(workingDirectory + File.separator + "rpm" + File.separator + "postinstall.sh")); task.setPostUninstallScript(new File(workingDirectory + File.separator + "rpm" + File.separator + "postremove.sh")); // Get the mapping for the files that the runner(s) need to install. for (RunnerStrategy runner : runners) { Map<File, Collection<File>> installSet = runner .getInstallSet(workingDirectory); for (Map.Entry<File, Collection<File>> instEntry : installSet .entrySet()) { String leafDirName = instEntry.getKey().getName(); File installDir; if (isServiceDir(leafDirName)) { installDir = new File(getServiceDirectory()); } else { installDir = new File(getInstallLoc() + File.separator + leafDirName); } // If destination directory isn't available, bail. for (File destFile : instEntry.getValue()) { RpmFileSet fs = new RpmFileSet(); // fs.setDir(installDir); fs.setPrefix(installDir.getAbsolutePath()); // getInstallLoc() // + // installDir.getinstEntry.get"/etc"); File sourceFile = new File(instEntry.getKey().getName() + File.separator + destFile.getName()); fs.setFile(sourceFile); // File("source/test/prein.sh")); File sourceDir = new File(workingDirectory.getPath() + File.separator + instEntry.getKey()); fs.setDir(sourceDir); fs.setConfig(true); fs.setNoReplace(true); fs.setDoc(true); fs.setGroup(getGroup()); fs.setGid(getGid()); fs.setUserName(getUser()); fs.setUid(getUid()); task.addRpmfileset(fs); } } } // Create the rpm task.execute(); }
public void createPackage(File packagerDirectory, File workingDirectory, Collection<RunnerStrategy> runners, Log log) throws MojoExecutionException { // TODO Bunch of items that need to be parameterized properly. // File filename = new File(packagerDirectory, // "rpmtest-1.0-1.noarch.rpm"); if (packagerDirectory == null) { get_log().error("'packagerDirectory' is null"); throw new MojoExecutionException("'packagerDirectory' is null"); } Project project = new Project(); //project.setCoreLoader(getClass().getClassLoader()); project.setCoreLoader(ClassLoader.getSystemClassLoader()); project.init(); RedlineTask task = new RedlineTask(); task.setProject(project); task.setDestination(packagerDirectory); task.setName(getRequiredParam("PKG_NAME")); task.setArchitecture("NOARCH"); task.setLicense("proprietary"); // RPM has VERY SUBTLE and very bad behavior with text in the version. It appears to work but doesn't upon // rpm -e task.setVersion(getRequiredParam("PKG_VERSION").replaceFirst("-SNAPSHOT", "")); task.setRelease(getRequiredParam("PKG_RELEASE")); task.setGroup("Application/Office"); task.setSourcePackage(getRequiredParam("PKG_NAME") + getRequiredParam("PKG_VERSION") + ".src.rpm"); task.setPreInstallScript(new File(workingDirectory + File.separator + "rpm" + File.separator + "preinstall.sh")); task.setPostInstallScript(new File(workingDirectory + File.separator + "rpm" + File.separator + "postinstall.sh")); task.setPostUninstallScript(new File(workingDirectory + File.separator + "rpm" + File.separator + "postremove.sh")); // Get the mapping for the files that the runner(s) need to install. for (RunnerStrategy runner : runners) { Map<File, Collection<File>> installSet = runner .getInstallSet(workingDirectory); for (Map.Entry<File, Collection<File>> instEntry : installSet .entrySet()) { String leafDirName = instEntry.getKey().getName(); File installDir; if (isServiceDir(leafDirName)) { installDir = new File(getServiceDirectory()); } else { installDir = new File(getInstallLoc() + File.separator + leafDirName); } // If destination directory isn't available, bail. for (File destFile : instEntry.getValue()) { RpmFileSet fs = new RpmFileSet(); // fs.setDir(installDir); fs.setPrefix(installDir.getAbsolutePath()); // getInstallLoc() // + // installDir.getinstEntry.get"/etc"); File sourceFile = new File(instEntry.getKey().getName() + File.separator + destFile.getName()); fs.setFile(sourceFile); // File("source/test/prein.sh")); File sourceDir = new File(workingDirectory.getPath() + File.separator + instEntry.getKey()); fs.setDir(sourceDir); fs.setConfig(true); fs.setNoReplace(true); fs.setDoc(true); fs.setGroup(getGroup()); fs.setGid(getGid()); fs.setUserName(getUser()); fs.setUid(getUid()); fs.setFileMode("0755"); task.addRpmfileset(fs); } } } // Create the rpm task.execute(); }
diff --git a/src/main/java/cn/sunjiachao/s7blog/modules/comment/controller/CommentController.java b/src/main/java/cn/sunjiachao/s7blog/modules/comment/controller/CommentController.java index 5a92de5..e7cc2f3 100644 --- a/src/main/java/cn/sunjiachao/s7blog/modules/comment/controller/CommentController.java +++ b/src/main/java/cn/sunjiachao/s7blog/modules/comment/controller/CommentController.java @@ -1,41 +1,45 @@ package cn.sunjiachao.s7blog.modules.comment.controller; import cn.sunjiachao.s7blog.modules.comment.service.ICommentService; import cn.sunjiachao.s7common.model.Comment; import cn.sunjiachao.s7common.model.dto.JsonResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import java.util.Date; import java.util.List; @Controller public class CommentController { @Autowired private ICommentService commentService; @Autowired private JsonResponse result; @RequestMapping(method = RequestMethod.POST, value = "/comment/post") @ResponseBody public JsonResponse postComment(Comment comment) { comment.setCreateTime(new Date()); comment.setGuestName("test"); - commentService.createNewComment(comment); - result.setMessage("发表留言成功!"); + try { + commentService.createNewComment(comment); + result.setMessage("发表留言成功!"); + } catch (Exception ex) { + result.setMessage("发表留言失败啦!"); + } return result; } @RequestMapping(method = RequestMethod.GET, value = "/comment/listByBlog") @ResponseBody public List<Comment> listCommentsByBlog(int blogId) { List<Comment> comments = commentService.getCommentsByBlog(blogId); return comments; } }
true
true
public JsonResponse postComment(Comment comment) { comment.setCreateTime(new Date()); comment.setGuestName("test"); commentService.createNewComment(comment); result.setMessage("发表留言成功!"); return result; }
public JsonResponse postComment(Comment comment) { comment.setCreateTime(new Date()); comment.setGuestName("test"); try { commentService.createNewComment(comment); result.setMessage("发表留言成功!"); } catch (Exception ex) { result.setMessage("发表留言失败啦!"); } return result; }
diff --git a/demos/web/src/main/java/org/apache/karaf/web/WebAppListener.java b/demos/web/src/main/java/org/apache/karaf/web/WebAppListener.java index 1c4e7666..15116b04 100644 --- a/demos/web/src/main/java/org/apache/karaf/web/WebAppListener.java +++ b/demos/web/src/main/java/org/apache/karaf/web/WebAppListener.java @@ -1,58 +1,60 @@ /* * 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.karaf.web; import java.io.File; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import org.apache.karaf.main.Main; public class WebAppListener implements ServletContextListener { private Main main; public void contextInitialized(ServletContextEvent sce) { try { System.err.println("contextInitialized"); String root = new File(sce.getServletContext().getRealPath("/") + "WEB-INF/karaf").getAbsolutePath(); System.err.println("Root: " + root); System.setProperty("karaf.home", root); System.setProperty("karaf.base", root); + System.setProperty("storage.location", root + "/instances"); System.setProperty("karaf.startLocalConsole", "false"); System.setProperty("karaf.startRemoteShell", "true"); + System.setProperty("karaf.lock", "false"); main = new Main(new String[0]); main.launch(); } catch (Exception e) { main = null; e.printStackTrace(); } } public void contextDestroyed(ServletContextEvent sce) { try { System.err.println("contextDestroyed"); if (main != null) { main.destroy(false); } } catch (Exception e) { e.printStackTrace(); } } }
false
true
public void contextInitialized(ServletContextEvent sce) { try { System.err.println("contextInitialized"); String root = new File(sce.getServletContext().getRealPath("/") + "WEB-INF/karaf").getAbsolutePath(); System.err.println("Root: " + root); System.setProperty("karaf.home", root); System.setProperty("karaf.base", root); System.setProperty("karaf.startLocalConsole", "false"); System.setProperty("karaf.startRemoteShell", "true"); main = new Main(new String[0]); main.launch(); } catch (Exception e) { main = null; e.printStackTrace(); } }
public void contextInitialized(ServletContextEvent sce) { try { System.err.println("contextInitialized"); String root = new File(sce.getServletContext().getRealPath("/") + "WEB-INF/karaf").getAbsolutePath(); System.err.println("Root: " + root); System.setProperty("karaf.home", root); System.setProperty("karaf.base", root); System.setProperty("storage.location", root + "/instances"); System.setProperty("karaf.startLocalConsole", "false"); System.setProperty("karaf.startRemoteShell", "true"); System.setProperty("karaf.lock", "false"); main = new Main(new String[0]); main.launch(); } catch (Exception e) { main = null; e.printStackTrace(); } }
diff --git a/src/de/sofd/viskit/test/CachingDicomImageListViewModelElement.java b/src/de/sofd/viskit/test/CachingDicomImageListViewModelElement.java index 7758397..de176c7 100644 --- a/src/de/sofd/viskit/test/CachingDicomImageListViewModelElement.java +++ b/src/de/sofd/viskit/test/CachingDicomImageListViewModelElement.java @@ -1,142 +1,142 @@ package de.sofd.viskit.test; import de.sofd.draw2d.Drawing; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map.Entry; import javax.imageio.ImageIO; import javax.imageio.ImageReader; import javax.imageio.stream.ImageInputStream; import org.dcm4che2.data.DicomObject; import org.dcm4che2.data.Tag; import org.dcm4che2.data.UID; import org.dcm4che2.io.DicomOutputStream; import org.dcm4che2.media.FileMetaInformation; /** * Implements getDicomObject(), getImage() as caching delegators to the (subclass-provided) * new methods getBackendDicomObjectKey(), getBackendDicomObject(). * * @author olaf */ public abstract class CachingDicomImageListViewModelElement implements DicomImageListViewModelElement { /** * Returns a key that uniquely identifies the DicomObject returned by getBackendDicomObject(). * The key will be used for caching those backend DicomObjects. * This key should be constant under equals()/hashCode() throughout the lifetime of <i>this</i>. This method will * be called often, so it should operate quickly (as opposed to getBackendDicomObject()). It * should work without calling getBackendDicomObject(). * * @return */ protected abstract Object getBackendDicomObjectKey(); /** * Extract from the backend and return the DicomObject. This method should not cache the * results or anything like that (this base class will do that), so it may be time-consuming. * * @return */ protected abstract DicomObject getBackendDicomObject(); /** * Same as {@link #getBackendDicomObject() }, but for the image. Default implementation * extracts the image from the getDicomObject(). * * @return */ protected BufferedImage getBackendImage() { Iterator it = ImageIO.getImageReadersByFormatName("DICOM"); if (!it.hasNext()) { throw new IllegalStateException("The DICOM image I/O filter (from dcm4che1) must be available to read images."); } - DicomObject dcmObj = getDicomObject(); + DicomObject dcmObj = getBackendDicomObject(); // extract the BufferedImage from the received imageDicomObject ByteArrayOutputStream bos = new ByteArrayOutputStream(200000); DicomOutputStream dos = new DicomOutputStream(bos); try { String tsuid = dcmObj.getString(Tag.TransferSyntaxUID); if (null == tsuid) { tsuid = UID.ImplicitVRLittleEndian; } FileMetaInformation fmi = new FileMetaInformation(dcmObj); fmi = new FileMetaInformation(fmi.getMediaStorageSOPClassUID(), fmi.getMediaStorageSOPInstanceUID(), tsuid); dos.writeFileMetaInformation(fmi.getDicomObject()); dos.writeDataset(dcmObj, tsuid); dos.close(); ImageReader reader = (ImageReader) it.next(); ImageInputStream in = ImageIO.createImageInputStream(new ByteArrayInputStream(bos.toByteArray())); if (null == in) { throw new IllegalStateException("The DICOM image I/O filter (from dcm4che1) must be available to read images."); } try { reader.setInput(in); return reader.read(0); } finally { in.close(); } } catch (IOException e) { throw new IllegalStateException("error trying to extract image from DICOM object", e); } } private final Drawing roiDrawing = new Drawing(); // TODO: use a utility library for the cache private static class LRUMemoryCache<K,V> extends LinkedHashMap<K,V> { private final int maxSize; public LRUMemoryCache(int maxSize) { this.maxSize = maxSize; } @Override protected boolean removeEldestEntry(Entry<K,V> eldest) { return this.size() > maxSize; } } // TODO: unify the two caches into one private static LRUMemoryCache<Object, DicomObject> rawDcmObjectCache = new LRUMemoryCache<Object, DicomObject>(50); private static LRUMemoryCache<Object, BufferedImage> rawImageCache = new LRUMemoryCache<Object, BufferedImage>(50); @Override public DicomObject getDicomObject() { DicomObject result = rawDcmObjectCache.get(getBackendDicomObjectKey()); if (result == null) { result = getBackendDicomObject(); rawDcmObjectCache.put(getBackendDicomObjectKey(), result); } return result; } @Override public BufferedImage getImage() { BufferedImage result = rawImageCache.get(getBackendDicomObjectKey()); if (result == null) { result = getBackendImage(); rawImageCache.put(getBackendDicomObjectKey(), result); } return result; } @Override public Drawing getRoiDrawing() { return roiDrawing; } }
true
true
protected BufferedImage getBackendImage() { Iterator it = ImageIO.getImageReadersByFormatName("DICOM"); if (!it.hasNext()) { throw new IllegalStateException("The DICOM image I/O filter (from dcm4che1) must be available to read images."); } DicomObject dcmObj = getDicomObject(); // extract the BufferedImage from the received imageDicomObject ByteArrayOutputStream bos = new ByteArrayOutputStream(200000); DicomOutputStream dos = new DicomOutputStream(bos); try { String tsuid = dcmObj.getString(Tag.TransferSyntaxUID); if (null == tsuid) { tsuid = UID.ImplicitVRLittleEndian; } FileMetaInformation fmi = new FileMetaInformation(dcmObj); fmi = new FileMetaInformation(fmi.getMediaStorageSOPClassUID(), fmi.getMediaStorageSOPInstanceUID(), tsuid); dos.writeFileMetaInformation(fmi.getDicomObject()); dos.writeDataset(dcmObj, tsuid); dos.close(); ImageReader reader = (ImageReader) it.next(); ImageInputStream in = ImageIO.createImageInputStream(new ByteArrayInputStream(bos.toByteArray())); if (null == in) { throw new IllegalStateException("The DICOM image I/O filter (from dcm4che1) must be available to read images."); } try { reader.setInput(in); return reader.read(0); } finally { in.close(); } } catch (IOException e) { throw new IllegalStateException("error trying to extract image from DICOM object", e); } }
protected BufferedImage getBackendImage() { Iterator it = ImageIO.getImageReadersByFormatName("DICOM"); if (!it.hasNext()) { throw new IllegalStateException("The DICOM image I/O filter (from dcm4che1) must be available to read images."); } DicomObject dcmObj = getBackendDicomObject(); // extract the BufferedImage from the received imageDicomObject ByteArrayOutputStream bos = new ByteArrayOutputStream(200000); DicomOutputStream dos = new DicomOutputStream(bos); try { String tsuid = dcmObj.getString(Tag.TransferSyntaxUID); if (null == tsuid) { tsuid = UID.ImplicitVRLittleEndian; } FileMetaInformation fmi = new FileMetaInformation(dcmObj); fmi = new FileMetaInformation(fmi.getMediaStorageSOPClassUID(), fmi.getMediaStorageSOPInstanceUID(), tsuid); dos.writeFileMetaInformation(fmi.getDicomObject()); dos.writeDataset(dcmObj, tsuid); dos.close(); ImageReader reader = (ImageReader) it.next(); ImageInputStream in = ImageIO.createImageInputStream(new ByteArrayInputStream(bos.toByteArray())); if (null == in) { throw new IllegalStateException("The DICOM image I/O filter (from dcm4che1) must be available to read images."); } try { reader.setInput(in); return reader.read(0); } finally { in.close(); } } catch (IOException e) { throw new IllegalStateException("error trying to extract image from DICOM object", e); } }
diff --git a/src/eu/bryants/anthony/toylanguage/parser/LanguageTokenizer.java b/src/eu/bryants/anthony/toylanguage/parser/LanguageTokenizer.java index c446fda..5aef7bb 100644 --- a/src/eu/bryants/anthony/toylanguage/parser/LanguageTokenizer.java +++ b/src/eu/bryants/anthony/toylanguage/parser/LanguageTokenizer.java @@ -1,916 +1,916 @@ package eu.bryants.anthony.toylanguage.parser; import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import java.math.BigInteger; import java.util.HashMap; import java.util.Map; import parser.ParseException; import parser.Token; import parser.Tokenizer; import eu.bryants.anthony.toylanguage.ast.terminal.FloatingLiteral; import eu.bryants.anthony.toylanguage.ast.terminal.IntegerLiteral; import eu.bryants.anthony.toylanguage.ast.terminal.Name; /* * Created on 30 Jun 2010 */ /** * The tokenizer for the language. This contains everything necessary to parse and read tokens in order from a given Reader. * @author Anthony Bryant */ public class LanguageTokenizer extends Tokenizer<ParseType> { private static final Map<String, ParseType> KEYWORDS = new HashMap<String, ParseType>(); static { KEYWORDS.put("boolean", ParseType.BOOLEAN_KEYWORD); KEYWORDS.put("break", ParseType.BREAK_KEYWORD); KEYWORDS.put("byte", ParseType.BYTE_KEYWORD); KEYWORDS.put("cast", ParseType.CAST_KEYWORD); KEYWORDS.put("compound", ParseType.COMPOUND_KEYWORD); KEYWORDS.put("continue", ParseType.CONTINUE_KEYWORD); KEYWORDS.put("double", ParseType.DOUBLE_KEYWORD); KEYWORDS.put("else", ParseType.ELSE_KEYWORD); KEYWORDS.put("false", ParseType.FALSE_KEYWORD); KEYWORDS.put("float", ParseType.FLOAT_KEYWORD); KEYWORDS.put("if", ParseType.IF_KEYWORD); KEYWORDS.put("int", ParseType.INT_KEYWORD); KEYWORDS.put("long", ParseType.LONG_KEYWORD); KEYWORDS.put("new", ParseType.NEW_KEYWORD); KEYWORDS.put("return", ParseType.RETURN_KEYWORD); KEYWORDS.put("short", ParseType.SHORT_KEYWORD); KEYWORDS.put("true", ParseType.TRUE_KEYWORD); KEYWORDS.put("ubyte", ParseType.UBYTE_KEYWORD); KEYWORDS.put("uint", ParseType.UINT_KEYWORD); KEYWORDS.put("ulong", ParseType.ULONG_KEYWORD); KEYWORDS.put("ushort", ParseType.USHORT_KEYWORD); KEYWORDS.put("void", ParseType.VOID_KEYWORD); KEYWORDS.put("while", ParseType.WHILE_KEYWORD); } private RandomAccessReader reader; private int currentLine; private int currentColumn; /** * Creates a new LanguageTokenizer with the specified reader. * @param reader - the reader to read the input from */ public LanguageTokenizer(Reader reader) { this.reader = new RandomAccessReader(reader); currentLine = 1; currentColumn = 1; } /** * Skips all whitespace and comment characters at the start of the stream, while updating the current position in the file. * @throws IOException - if an error occurs while reading */ private void skipWhitespaceAndComments() throws IOException, LanguageParseException { int index = 0; while (true) { int nextChar = reader.read(index); if (nextChar < 0) { reader.discard(index); return; } else if (nextChar == '\r') { currentLine++; currentColumn = 1; // skip the line feed, since it is immediately following a carriage return int secondChar = reader.read(index + 1); if (secondChar == '\n') { index++; } index++; continue; } else if (nextChar == '\n') { currentLine++; currentColumn = 1; index++; continue; } else if (nextChar == '\t') { reader.discard(index); // discard so that getting the current line works throw new LanguageParseException("Tabs are not permitted in this language.", new LexicalPhrase(currentLine, reader.getCurrentLine(), currentColumn)); } else if (Character.isWhitespace(nextChar)) { currentColumn++; index++; continue; } else if (nextChar == '/') { int secondChar = reader.read(index + 1); if (secondChar == '*') { currentColumn += 2; index += 2; // skip to the end of the comment: "*/" int commentChar = reader.read(index); while (commentChar >= 0) { if (commentChar == '*') { currentColumn++; index++; int secondCommentChar = reader.read(index); if (secondCommentChar == '/') { currentColumn++; index++; break; } } else if (commentChar == '\r') { currentLine++; currentColumn = 1; // skip the line feed, since it is immediately following a carriage return int secondCommentChar = reader.read(index + 1); if (secondCommentChar == '\n') { index++; } index++; } else if (commentChar == '\n') { currentLine++; currentColumn = 1; index++; } else if (commentChar == '\t') { reader.discard(index); // discard so that getting the current line works correctly throw new LanguageParseException("Tabs are not permitted in this language.", new LexicalPhrase(currentLine, reader.getCurrentLine(), currentColumn)); } else { currentColumn++; index++; } commentChar = reader.read(index); } continue; } else if (secondChar == '/') { index += 2; // skip to the end of the comment: "\n" or "\r" int commentChar = reader.read(index); while (commentChar >= 0) { if (commentChar == '\r') { currentLine++; currentColumn = 1; // skip the line feed, since it is immediately following a carriage return int secondCommentChar = reader.read(index + 1); if (secondCommentChar == '\n') { index++; } index++; break; } else if (commentChar == '\n') { currentLine++; currentColumn = 1; index++; break; } else if (commentChar == '\t') { reader.discard(index); // discard so that getting the current line works correctly throw new LanguageParseException("Tabs are not permitted in this language.", new LexicalPhrase(currentLine, reader.getCurrentLine(), currentColumn)); } else { currentColumn++; index++; } commentChar = reader.read(index); } continue; } else { reader.discard(index); return; } } // finished parsing comments else { reader.discard(index); return; } } } /** * Reads a name token from the start of the reader. * This method assumes that all whitespace and comments have just been discarded, * and the currentLine and currentColumn are up to date. * @return a Token read from the input stream, or null if no Token could be read * @throws IOException - if an error occurs while reading from the stream * @throws LanguageParseException - if an invalid character sequence is detected */ private Token<ParseType> readNameOrKeyword() throws IOException, LanguageParseException { int nextChar = reader.read(0); if (nextChar < 0 || (!Character.isLetter(nextChar) && nextChar != '_')) { // there is no name here, so return null return null; } // we have the start of a name, so allocate a buffer for it StringBuffer buffer = new StringBuffer(); buffer.append((char) nextChar); int index = 1; nextChar = reader.read(index); while (Character.isLetterOrDigit(nextChar) || nextChar == '_') { buffer.append((char) nextChar); index++; nextChar = reader.read(index); } // we will not be reading any more as part of the name, so discard the used characters reader.discard(index); // update the tokenizer's current location in the file currentColumn += index; // we have a full name or keyword, so compare it against a list of keywords to find out which String name = buffer.toString(); ParseType keyword = KEYWORDS.get(name); if (keyword != null) { return new Token<ParseType>(keyword, new LexicalPhrase(currentLine, reader.getCurrentLine(), currentColumn - index, currentColumn)); } // check if the name is an underscore, and if it is then return it if (name.equals("_")) { return new Token<ParseType>(ParseType.UNDERSCORE, new LexicalPhrase(currentLine, reader.getCurrentLine(), currentColumn - index, currentColumn)); } // we have a name, so return it return new Token<ParseType>(ParseType.NAME, new Name(name, new LexicalPhrase(currentLine, reader.getCurrentLine(), currentColumn - index, currentColumn))); } /** * Reads an integer literal from the start of the reader. * This method assumes that all whitespace and comments have just been discarded, * and the currentLine and currentColumn are up to date. * @return a Token read from the input stream, or null if no Token could be read * @throws IOException - if an error occurs while reading from the stream * @throws LanguageParseException - if an unexpected character sequence is detected inside the integer literal */ private Token<ParseType> readIntegerLiteral() throws IOException, LanguageParseException { int nextChar = reader.read(0); int index = 1; if (nextChar == '0') { StringBuffer buffer = new StringBuffer(); buffer.append((char) nextChar); int secondChar = reader.read(index); index++; int base; switch (secondChar) { case 'b': case 'B': base = 2; break; case 'o': case 'O': base = 8; break; case 'x': case 'X': base = 16; break; default: base = 10; break; } if (base != 10) { buffer.append((char) secondChar); BigInteger value = readInteger(buffer, index, base); reader.discard(buffer.length()); currentColumn += buffer.length(); if (value == null) { // there was no value after the 0b, 0o, or 0x, so we have a parse error String baseString = "integer"; if (base == 2) { baseString = "binary"; } else if (base == 8) { baseString = "octal"; } else if (base == 16) { baseString = "hex"; } throw new LanguageParseException("Unexpected end of " + baseString + " literal.", new LexicalPhrase(currentLine, reader.getCurrentLine(), currentColumn)); } IntegerLiteral literal = new IntegerLiteral(value, buffer.toString(), new LexicalPhrase(currentLine, reader.getCurrentLine(), currentColumn - buffer.length(), currentColumn)); return new Token<ParseType>(ParseType.INTEGER_LITERAL, literal); } // backtrack an index, as we do not have b, o, or x as the second character in the literal // this makes it easier to parse the decimal literal without ignoring the character after the 0 index--; BigInteger value = readInteger(buffer, index, 10); if (value == null) { // there was no value after the initial 0, so set the value to 0 value = BigInteger.valueOf(0); } reader.discard(buffer.length()); currentColumn += buffer.length(); IntegerLiteral literal = new IntegerLiteral(value, buffer.toString(), new LexicalPhrase(currentLine, reader.getCurrentLine(), currentColumn - buffer.length(), currentColumn)); return new Token<ParseType>(ParseType.INTEGER_LITERAL, literal); } // backtrack an index, as we do not have 0 as the first character in the literal // this makes it easier to parse the decimal literal without ignoring the first character index--; StringBuffer buffer = new StringBuffer(); BigInteger value = readInteger(buffer, index, 10); if (value == null) { // this is not an integer literal return null; } reader.discard(buffer.length()); currentColumn += buffer.length(); IntegerLiteral literal = new IntegerLiteral(value, buffer.toString(), new LexicalPhrase(currentLine, reader.getCurrentLine(), currentColumn - buffer.length(), currentColumn)); return new Token<ParseType>(ParseType.INTEGER_LITERAL, literal); } /** * Reads an integer in the specified radix from the stream, and calculates its value as well as appending it to the buffer. * @param buffer - the buffer to append the raw string to * @param startIndex - the index in the reader to start at * @param radix - the radix to read the number in * @return the value of the integer, or null if there was no numeric value * @throws IOException - if there is an error reading from the stream */ private BigInteger readInteger(StringBuffer buffer, int startIndex, int radix) throws IOException { int index = startIndex; BigInteger value = BigInteger.valueOf(0); boolean hasNumeral = false; while (true) { int nextChar = reader.read(index); int digit = Character.digit(nextChar, radix); if (digit < 0) { break; } hasNumeral = true; buffer.append((char) nextChar); value = value.multiply(BigInteger.valueOf(radix)).add(BigInteger.valueOf(digit)); index++; } if (hasNumeral) { return value; } return null; } /** * Reads a floating literal from the start of the reader. * This method assumes that all whitespace and comments have just been discarded, * and the currentLine and currentColumn are up to date. * @return a Token read from the input stream, or null if no Token could be read * @throws IOException - if an error occurs while reading from the stream */ private Token<ParseType> readFloatingLiteral() throws IOException { int nextChar; int index = 0; StringBuffer buffer = new StringBuffer(); boolean hasInitialNumber = false; while (true) { nextChar = reader.read(index); int digitValue = Character.digit(nextChar, 10); if (digitValue < 0) { // we do not have a digit in the range 0-9 break; } hasInitialNumber = true; buffer.append((char) nextChar); index++; } boolean hasFractionalPart = false; if (nextChar == '.') { buffer.append('.'); index++; while (true) { nextChar = reader.read(index); int digitValue = Character.digit(nextChar, 10); if (digitValue < 0) { // we do not have a digit in the range 0-9 if (!hasFractionalPart) { // there is no fractional part to this number, so it is not a valid floating point literal return null; } break; } hasFractionalPart = true; buffer.append((char) nextChar); index++; } } boolean hasExponent = false; if (nextChar == 'e' || nextChar == 'E') { int indexBeforeExponent = index; StringBuffer exponentialBuffer = new StringBuffer(); exponentialBuffer.append((char) nextChar); index++; nextChar = reader.read(index); if (nextChar == '+' || nextChar == '-') { exponentialBuffer.append((char) nextChar); index++; } while (true) { nextChar = reader.read(index); int digitValue = Character.digit(nextChar, 10); if (digitValue < 0) { // we do not have a digit in the range 0-9 break; } hasExponent = true; exponentialBuffer.append((char) nextChar); index++; } // only add the exponent if it all exists if (hasExponent) { buffer.append(exponentialBuffer); } else { index = indexBeforeExponent; } } if (hasFractionalPart || (hasInitialNumber && hasExponent)) { String floatingPointText = buffer.toString(); reader.discard(index); currentColumn += index; FloatingLiteral literal = new FloatingLiteral(floatingPointText, new LexicalPhrase(currentLine, reader.getCurrentLine(), currentColumn - index, currentColumn)); return new Token<ParseType>(ParseType.FLOATING_LITERAL, literal); } // there was no valid floating literal, so do not return a Token return null; } /** * Reads a symbol token from the start of the reader. * This method assumes that all whitespace and comments have just been discarded, * and the currentLine and currentColumn are up to date. * @return a Token read from the input stream, or null if no Token could be read * @throws IOException - if an error occurs while reading from the stream */ private Token<ParseType> readSymbol() throws IOException { int nextChar = reader.read(0); if (nextChar < 0) { // there is no symbol here, just the end of the file return null; } if (nextChar == '&') { int secondChar = reader.read(1); if (secondChar == '&') { return makeSymbolToken(ParseType.DOUBLE_AMPERSAND, 2); } return makeSymbolToken(ParseType.AMPERSAND, 1); } if (nextChar == '^') { return makeSymbolToken(ParseType.CARET, 1); } if (nextChar == ':') { return makeSymbolToken(ParseType.COLON, 1); } if (nextChar == ',') { return makeSymbolToken(ParseType.COMMA, 1); } if (nextChar == '.') { return makeSymbolToken(ParseType.DOT, 1); } if (nextChar == '=') { int secondChar = reader.read(1); if (secondChar == '=') { return makeSymbolToken(ParseType.DOUBLE_EQUALS, 2); } return makeSymbolToken(ParseType.EQUALS, 1); } if (nextChar == '!') { int secondChar = reader.read(1); if (secondChar == '=') { return makeSymbolToken(ParseType.EXCLAIMATION_MARK_EQUALS, 2); } return makeSymbolToken(ParseType.EXCLAIMATION_MARK, 1); } if (nextChar == '/') { return makeSymbolToken(ParseType.FORWARD_SLASH, 1); } if (nextChar == '<') { int secondChar = reader.read(1); if (secondChar == '=') { return makeSymbolToken(ParseType.LANGLE_EQUALS, 2); } if (secondChar == '<') { return makeSymbolToken(ParseType.DOUBLE_LANGLE, 2); } return makeSymbolToken(ParseType.LANGLE, 1); } if (nextChar == '{') { return makeSymbolToken(ParseType.LBRACE, 1); } if (nextChar == '(') { return makeSymbolToken(ParseType.LPAREN, 1); } if (nextChar == '[') { return makeSymbolToken(ParseType.LSQUARE, 1); } if (nextChar == '-') { int secondChar = reader.read(1); if (secondChar == '-') { return makeSymbolToken(ParseType.DOUBLE_MINUS, 2); } return makeSymbolToken(ParseType.MINUS, 1); } if (nextChar == '%') { int secondChar = reader.read(1); if (secondChar == '%') { return makeSymbolToken(ParseType.DOUBLE_PERCENT, 2); } return makeSymbolToken(ParseType.PERCENT, 1); } if (nextChar == '|') { int secondChar = reader.read(1); if (secondChar == '|') { return makeSymbolToken(ParseType.DOUBLE_PIPE, 2); } return makeSymbolToken(ParseType.PIPE, 1); } if (nextChar == '+') { int secondChar = reader.read(1); if (secondChar == '+') { return makeSymbolToken(ParseType.DOUBLE_PLUS, 2); } return makeSymbolToken(ParseType.PLUS, 1); } if (nextChar == '?') { return makeSymbolToken(ParseType.QUESTION_MARK, 1); } if (nextChar == '>') { int secondChar = reader.read(1); if (secondChar == '=') { return makeSymbolToken(ParseType.RANGLE_EQUALS, 2); } if (secondChar == '>') { int thirdChar = reader.read(2); if (thirdChar == '>') { - return makeSymbolToken(ParseType.TRIPLE_RANGLE, 2); + return makeSymbolToken(ParseType.TRIPLE_RANGLE, 3); } return makeSymbolToken(ParseType.DOUBLE_RANGLE, 2); } return makeSymbolToken(ParseType.RANGLE, 1); } if (nextChar == '}') { return makeSymbolToken(ParseType.RBRACE, 1); } if (nextChar == ')') { return makeSymbolToken(ParseType.RPAREN, 1); } if (nextChar == ']') { return makeSymbolToken(ParseType.RSQUARE, 1); } if (nextChar == ';') { return makeSymbolToken(ParseType.SEMICOLON, 1); } if (nextChar == '*') { return makeSymbolToken(ParseType.STAR, 1); } if (nextChar == '~') { return makeSymbolToken(ParseType.TILDE, 1); } // none of the symbols matched, so return null return null; } /** * Convenience method which readSymbol() uses to create its Tokens. * This assumes that the symbol does not span multiple lines, and is exactly <code>length</code> columns long. * @param parseType - the ParseType of the token to create. * @param length - the length of the symbol * @return the Token created * @throws IOException - if there is an error discarding the characters that were read in */ private Token<ParseType> makeSymbolToken(ParseType parseType, int length) throws IOException { reader.discard(length); currentColumn += length; return new Token<ParseType>(parseType, new LexicalPhrase(currentLine, reader.getCurrentLine(), currentColumn - length, currentColumn)); } /** * @see parser.Tokenizer#generateToken() */ @Override protected Token<ParseType> generateToken() throws ParseException { try { skipWhitespaceAndComments(); Token<ParseType> token = readNameOrKeyword(); if (token != null) { return token; } token = readFloatingLiteral(); if (token != null) { return token; } token = readIntegerLiteral(); if (token != null) { return token; } token = readSymbol(); if (token != null) { return token; } int nextChar = reader.read(0); if (nextChar < 0) { // a value of less than 0 means the end of input, so return a token with type null return new Token<ParseType>(null, new LexicalPhrase(currentLine, reader.getCurrentLine(), currentColumn)); } throw new LanguageParseException("Unexpected character while parsing: '" + (char) nextChar + "'", new LexicalPhrase(currentLine, reader.getCurrentLine(), currentColumn)); } catch (IOException e) { throw new LanguageParseException("An IO Exception occured while reading the source code.", e, new LexicalPhrase(currentLine, "", currentColumn)); } } /** * Closes this LanguageTokenizer. * @throws IOException - if there is an error closing the underlying stream */ public void close() throws IOException { reader.close(); } /** * A class that provides a sort of random-access interface to a stream. * It keeps a buffer of characters, and lazily reads the stream into it. * It allows single character reads from anywhere in the stream, and also supports discarding from the start of the buffer. * @author Anthony Bryant */ private static final class RandomAccessReader { private Reader reader; private StringBuffer lookahead; private String currentLine; /** * Creates a new RandomAccessReader to read from the specified Reader * @param reader - the Reader to read from */ public RandomAccessReader(Reader reader) { this.reader = new BufferedReader(reader); lookahead = new StringBuffer(); } /** * Reads the character at the specified offset. * @param offset - the offset to read the character at * @return the character read from the stream, or -1 if the end of the stream was reached * @throws IOException - if an error occurs while reading from the underlying reader */ public int read(int offset) throws IOException { int result = ensureContains(offset + 1); if (result < 0) { return result; } return lookahead.charAt(offset); } /** * Discards all of the characters in this reader before the specified offset. * After calling this, the character previously returned from read(offset) will be returned from read(0). * @param offset - the offset to delete all of the characters before, must be >= 0 * @throws IOException - if an error occurs while reading from the underlying reader */ public void discard(int offset) throws IOException { int result = ensureContains(offset); if (result < offset) { throw new IndexOutOfBoundsException("Tried to discard past the end of a RandomAccessReader"); } updateCurrentLine(offset); lookahead.delete(0, offset); } /** * @return the current line that is at offset 0 in this reader * @throws IOException - if an error occurs while reading from the underlying reader */ public String getCurrentLine() throws IOException { if (currentLine == null) { updateCurrentLine(0); } return currentLine; } /** * Ensures that the lookahead contains at least the specified number of characters. * @param length - the number of characters to ensure are in the lookahead * @return the number of characters now in the lookahead buffer, or -1 if the end of the stream has been reached * @throws IOException - if an error occurs while reading from the underlying reader */ private int ensureContains(int length) throws IOException { if (length <= 0 || length < lookahead.length()) { return lookahead.length(); } char[] buffer = new char[length - lookahead.length()]; int readChars = reader.read(buffer); if (readChars < 0) { return readChars; } lookahead.append(buffer, 0, readChars); return lookahead.length(); } /** * Updates the current line to be the line at the specified offset. * @param offset - the offset to update currentLine from * @throws IOException - if an error occurs while reading from the underlying reader */ private void updateCurrentLine(int offset) throws IOException { ensureContains(offset); ensureNewLineAfter(offset); int start = -1; // start at offset - 1 so that if we start on a \n we count backwards from there for (int i = offset - 1; i >= 0; i--) { if (lookahead.charAt(i) == '\n') { start = i + 1; break; } } if (start < 0) { if (currentLine != null) { return; } start = 0; } int end = offset; while (end < lookahead.length() && lookahead.charAt(end) != '\n') { end++; } currentLine = lookahead.substring(start, end); } /** * Ensures that the lookahead buffer contains a newline after (or at) the specified index. * @param offset - the offset to ensure there is a newline after. * @throws IOException - if an error occurs while reading from the underlying reader */ private void ensureNewLineAfter(int offset) throws IOException { // after this many characters in lookahead, we will stop trying to read another newline final int MAX_LOOKAHEAD_LENGTH = 10000; for (int i = offset; i < lookahead.length(); i++) { if (lookahead.charAt(i) == '\n') { return; } } while (lookahead.length() < MAX_LOOKAHEAD_LENGTH) { int nextChar = reader.read(); if (nextChar < 0) { // end of stream, just leave lookahead as it was return; } lookahead.append((char) nextChar); if (nextChar == '\n' && lookahead.length() >= offset) { return; } } } /** * Closes the underlying stream of this RandomAccessReader * @throws IOException - if an error occurs while reading from the underlying reader */ public void close() throws IOException { reader.close(); } } }
true
true
private Token<ParseType> readSymbol() throws IOException { int nextChar = reader.read(0); if (nextChar < 0) { // there is no symbol here, just the end of the file return null; } if (nextChar == '&') { int secondChar = reader.read(1); if (secondChar == '&') { return makeSymbolToken(ParseType.DOUBLE_AMPERSAND, 2); } return makeSymbolToken(ParseType.AMPERSAND, 1); } if (nextChar == '^') { return makeSymbolToken(ParseType.CARET, 1); } if (nextChar == ':') { return makeSymbolToken(ParseType.COLON, 1); } if (nextChar == ',') { return makeSymbolToken(ParseType.COMMA, 1); } if (nextChar == '.') { return makeSymbolToken(ParseType.DOT, 1); } if (nextChar == '=') { int secondChar = reader.read(1); if (secondChar == '=') { return makeSymbolToken(ParseType.DOUBLE_EQUALS, 2); } return makeSymbolToken(ParseType.EQUALS, 1); } if (nextChar == '!') { int secondChar = reader.read(1); if (secondChar == '=') { return makeSymbolToken(ParseType.EXCLAIMATION_MARK_EQUALS, 2); } return makeSymbolToken(ParseType.EXCLAIMATION_MARK, 1); } if (nextChar == '/') { return makeSymbolToken(ParseType.FORWARD_SLASH, 1); } if (nextChar == '<') { int secondChar = reader.read(1); if (secondChar == '=') { return makeSymbolToken(ParseType.LANGLE_EQUALS, 2); } if (secondChar == '<') { return makeSymbolToken(ParseType.DOUBLE_LANGLE, 2); } return makeSymbolToken(ParseType.LANGLE, 1); } if (nextChar == '{') { return makeSymbolToken(ParseType.LBRACE, 1); } if (nextChar == '(') { return makeSymbolToken(ParseType.LPAREN, 1); } if (nextChar == '[') { return makeSymbolToken(ParseType.LSQUARE, 1); } if (nextChar == '-') { int secondChar = reader.read(1); if (secondChar == '-') { return makeSymbolToken(ParseType.DOUBLE_MINUS, 2); } return makeSymbolToken(ParseType.MINUS, 1); } if (nextChar == '%') { int secondChar = reader.read(1); if (secondChar == '%') { return makeSymbolToken(ParseType.DOUBLE_PERCENT, 2); } return makeSymbolToken(ParseType.PERCENT, 1); } if (nextChar == '|') { int secondChar = reader.read(1); if (secondChar == '|') { return makeSymbolToken(ParseType.DOUBLE_PIPE, 2); } return makeSymbolToken(ParseType.PIPE, 1); } if (nextChar == '+') { int secondChar = reader.read(1); if (secondChar == '+') { return makeSymbolToken(ParseType.DOUBLE_PLUS, 2); } return makeSymbolToken(ParseType.PLUS, 1); } if (nextChar == '?') { return makeSymbolToken(ParseType.QUESTION_MARK, 1); } if (nextChar == '>') { int secondChar = reader.read(1); if (secondChar == '=') { return makeSymbolToken(ParseType.RANGLE_EQUALS, 2); } if (secondChar == '>') { int thirdChar = reader.read(2); if (thirdChar == '>') { return makeSymbolToken(ParseType.TRIPLE_RANGLE, 2); } return makeSymbolToken(ParseType.DOUBLE_RANGLE, 2); } return makeSymbolToken(ParseType.RANGLE, 1); } if (nextChar == '}') { return makeSymbolToken(ParseType.RBRACE, 1); } if (nextChar == ')') { return makeSymbolToken(ParseType.RPAREN, 1); } if (nextChar == ']') { return makeSymbolToken(ParseType.RSQUARE, 1); } if (nextChar == ';') { return makeSymbolToken(ParseType.SEMICOLON, 1); } if (nextChar == '*') { return makeSymbolToken(ParseType.STAR, 1); } if (nextChar == '~') { return makeSymbolToken(ParseType.TILDE, 1); } // none of the symbols matched, so return null return null; }
private Token<ParseType> readSymbol() throws IOException { int nextChar = reader.read(0); if (nextChar < 0) { // there is no symbol here, just the end of the file return null; } if (nextChar == '&') { int secondChar = reader.read(1); if (secondChar == '&') { return makeSymbolToken(ParseType.DOUBLE_AMPERSAND, 2); } return makeSymbolToken(ParseType.AMPERSAND, 1); } if (nextChar == '^') { return makeSymbolToken(ParseType.CARET, 1); } if (nextChar == ':') { return makeSymbolToken(ParseType.COLON, 1); } if (nextChar == ',') { return makeSymbolToken(ParseType.COMMA, 1); } if (nextChar == '.') { return makeSymbolToken(ParseType.DOT, 1); } if (nextChar == '=') { int secondChar = reader.read(1); if (secondChar == '=') { return makeSymbolToken(ParseType.DOUBLE_EQUALS, 2); } return makeSymbolToken(ParseType.EQUALS, 1); } if (nextChar == '!') { int secondChar = reader.read(1); if (secondChar == '=') { return makeSymbolToken(ParseType.EXCLAIMATION_MARK_EQUALS, 2); } return makeSymbolToken(ParseType.EXCLAIMATION_MARK, 1); } if (nextChar == '/') { return makeSymbolToken(ParseType.FORWARD_SLASH, 1); } if (nextChar == '<') { int secondChar = reader.read(1); if (secondChar == '=') { return makeSymbolToken(ParseType.LANGLE_EQUALS, 2); } if (secondChar == '<') { return makeSymbolToken(ParseType.DOUBLE_LANGLE, 2); } return makeSymbolToken(ParseType.LANGLE, 1); } if (nextChar == '{') { return makeSymbolToken(ParseType.LBRACE, 1); } if (nextChar == '(') { return makeSymbolToken(ParseType.LPAREN, 1); } if (nextChar == '[') { return makeSymbolToken(ParseType.LSQUARE, 1); } if (nextChar == '-') { int secondChar = reader.read(1); if (secondChar == '-') { return makeSymbolToken(ParseType.DOUBLE_MINUS, 2); } return makeSymbolToken(ParseType.MINUS, 1); } if (nextChar == '%') { int secondChar = reader.read(1); if (secondChar == '%') { return makeSymbolToken(ParseType.DOUBLE_PERCENT, 2); } return makeSymbolToken(ParseType.PERCENT, 1); } if (nextChar == '|') { int secondChar = reader.read(1); if (secondChar == '|') { return makeSymbolToken(ParseType.DOUBLE_PIPE, 2); } return makeSymbolToken(ParseType.PIPE, 1); } if (nextChar == '+') { int secondChar = reader.read(1); if (secondChar == '+') { return makeSymbolToken(ParseType.DOUBLE_PLUS, 2); } return makeSymbolToken(ParseType.PLUS, 1); } if (nextChar == '?') { return makeSymbolToken(ParseType.QUESTION_MARK, 1); } if (nextChar == '>') { int secondChar = reader.read(1); if (secondChar == '=') { return makeSymbolToken(ParseType.RANGLE_EQUALS, 2); } if (secondChar == '>') { int thirdChar = reader.read(2); if (thirdChar == '>') { return makeSymbolToken(ParseType.TRIPLE_RANGLE, 3); } return makeSymbolToken(ParseType.DOUBLE_RANGLE, 2); } return makeSymbolToken(ParseType.RANGLE, 1); } if (nextChar == '}') { return makeSymbolToken(ParseType.RBRACE, 1); } if (nextChar == ')') { return makeSymbolToken(ParseType.RPAREN, 1); } if (nextChar == ']') { return makeSymbolToken(ParseType.RSQUARE, 1); } if (nextChar == ';') { return makeSymbolToken(ParseType.SEMICOLON, 1); } if (nextChar == '*') { return makeSymbolToken(ParseType.STAR, 1); } if (nextChar == '~') { return makeSymbolToken(ParseType.TILDE, 1); } // none of the symbols matched, so return null return null; }
diff --git a/eclipse/plugins/net.sf.orcc.backends/src/net/sf/orcc/backends/transform/ssa/ConstantPropagator.java b/eclipse/plugins/net.sf.orcc.backends/src/net/sf/orcc/backends/transform/ssa/ConstantPropagator.java index 30a5874c2..651e7d63d 100644 --- a/eclipse/plugins/net.sf.orcc.backends/src/net/sf/orcc/backends/transform/ssa/ConstantPropagator.java +++ b/eclipse/plugins/net.sf.orcc.backends/src/net/sf/orcc/backends/transform/ssa/ConstantPropagator.java @@ -1,68 +1,67 @@ /* * Copyright (c) 2011, IRISA * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the IRISA nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY * WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ package net.sf.orcc.backends.transform.ssa; import net.sf.orcc.ir.ExprVar; import net.sf.orcc.ir.Expression; import net.sf.orcc.ir.InstAssign; import net.sf.orcc.ir.Use; import net.sf.orcc.ir.util.AbstractIrVisitor; import net.sf.orcc.ir.util.IrUtil; import net.sf.orcc.util.util.EcoreHelper; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.util.EcoreUtil; /** * Replace variables with constant value by their value. * * @author Herve Yviquel * */ public class ConstantPropagator extends AbstractIrVisitor<Void> { @Override public Void caseInstAssign(InstAssign assign) { Expression value = assign.getValue(); if (value.isExprBool() || value.isExprFloat() || value.isExprInt() || value.isExprString()) { EList<Use> targetUses = assign.getTarget().getVariable().getUses(); while (!targetUses.isEmpty()) { ExprVar expr = EcoreHelper.getContainerOfType( targetUses.get(0), ExprVar.class); EcoreUtil.replace(expr, IrUtil.copy(value)); IrUtil.delete(expr); } - EcoreUtil.remove(assign.getTarget()); IrUtil.delete(assign); indexInst--; } return null; } }
true
true
public Void caseInstAssign(InstAssign assign) { Expression value = assign.getValue(); if (value.isExprBool() || value.isExprFloat() || value.isExprInt() || value.isExprString()) { EList<Use> targetUses = assign.getTarget().getVariable().getUses(); while (!targetUses.isEmpty()) { ExprVar expr = EcoreHelper.getContainerOfType( targetUses.get(0), ExprVar.class); EcoreUtil.replace(expr, IrUtil.copy(value)); IrUtil.delete(expr); } EcoreUtil.remove(assign.getTarget()); IrUtil.delete(assign); indexInst--; } return null; }
public Void caseInstAssign(InstAssign assign) { Expression value = assign.getValue(); if (value.isExprBool() || value.isExprFloat() || value.isExprInt() || value.isExprString()) { EList<Use> targetUses = assign.getTarget().getVariable().getUses(); while (!targetUses.isEmpty()) { ExprVar expr = EcoreHelper.getContainerOfType( targetUses.get(0), ExprVar.class); EcoreUtil.replace(expr, IrUtil.copy(value)); IrUtil.delete(expr); } IrUtil.delete(assign); indexInst--; } return null; }
diff --git a/src/test/java/org/jrivets/event/SerialChannelTest.java b/src/test/java/org/jrivets/event/SerialChannelTest.java index 068dfe1..a213b12 100644 --- a/src/test/java/org/jrivets/event/SerialChannelTest.java +++ b/src/test/java/org/jrivets/event/SerialChannelTest.java @@ -1,103 +1,106 @@ package org.jrivets.event; import java.util.ArrayList; import java.util.Random; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicInteger; import org.jrivets.event.OnEvent; import org.jrivets.event.SerialEventChannel; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class SerialChannelTest { private final ExecutorService executor = Executors.newFixedThreadPool(2); private SerialEventChannel channel; private ArrayList<Integer> events = new ArrayList<Integer>(); @Before public void init() { channel = new SerialEventChannel("testChannel", 10, executor); channel.addSubscriber(this); } @SuppressWarnings("unused") @OnEvent private synchronized void onEventInteger(Integer i) { events.add(i); notify(); } @Test public synchronized void sendIntegerItself() throws InterruptedException { Random rnd = new Random(); Integer expectedInt = new Integer(rnd.nextInt()); channel.publish(expectedInt); wait(10000L); assertEquals(expectedInt, events.get(0)); } @Test public synchronized void checkOrder() throws InterruptedException { Integer i1 = 1; Integer i2 = 2; channel.publish(i1); channel.publish(i2); wait(10000L); if (events.size() < 2) { wait(10000L); } assertEquals(i1, events.get(0)); assertEquals(i2, events.get(1)); } @Test public void blockerTest() throws InterruptedException { final AtomicInteger counter = new AtomicInteger(0); synchronized (this) { executor.execute(new Runnable() { @Override public void run() { for (int i = 0; i < 20; i++) { counter.addAndGet(1); channel.publish(new Integer(i)); } } }); while (counter.get() < 12) { Thread.sleep(10L); } Thread.sleep(50L); assertEquals(12, counter.get()); } while (counter.get() < 20) { Thread.sleep(10L); } + while (events.size() < 20) { + Thread.sleep(10L); + } assertEquals(20, events.size()); for (int i = 0; i < 20 ; i++) { assertEquals(new Integer(i), events.get(i)); } } @Test public synchronized void waitingTimeout() throws InterruptedException { channel.setWaitingTimeout(600000L); // 1 minute! Integer expectedInt = new Integer(1); channel.publish(expectedInt); wait(10000L); assertEquals(expectedInt, events.get(0)); while(!SerialEventChannel.State.PROCESSING_WAITING.equals(channel.getState())) { Thread.sleep(50); // allow the handled go to sleep } expectedInt = new Integer(2); channel.publish(expectedInt); wait(10000L); assertEquals(expectedInt, events.get(1)); } }
true
true
public void blockerTest() throws InterruptedException { final AtomicInteger counter = new AtomicInteger(0); synchronized (this) { executor.execute(new Runnable() { @Override public void run() { for (int i = 0; i < 20; i++) { counter.addAndGet(1); channel.publish(new Integer(i)); } } }); while (counter.get() < 12) { Thread.sleep(10L); } Thread.sleep(50L); assertEquals(12, counter.get()); } while (counter.get() < 20) { Thread.sleep(10L); } assertEquals(20, events.size()); for (int i = 0; i < 20 ; i++) { assertEquals(new Integer(i), events.get(i)); } }
public void blockerTest() throws InterruptedException { final AtomicInteger counter = new AtomicInteger(0); synchronized (this) { executor.execute(new Runnable() { @Override public void run() { for (int i = 0; i < 20; i++) { counter.addAndGet(1); channel.publish(new Integer(i)); } } }); while (counter.get() < 12) { Thread.sleep(10L); } Thread.sleep(50L); assertEquals(12, counter.get()); } while (counter.get() < 20) { Thread.sleep(10L); } while (events.size() < 20) { Thread.sleep(10L); } assertEquals(20, events.size()); for (int i = 0; i < 20 ; i++) { assertEquals(new Integer(i), events.get(i)); } }
diff --git a/com/core/test/Main.java b/com/core/test/Main.java index 90dda5c..ea38add 100644 --- a/com/core/test/Main.java +++ b/com/core/test/Main.java @@ -1,73 +1,74 @@ package com.core.test; import com.core.lesson.*; import com.core.util.ResourceManager; import com.core.util.Utils; import org.json.JSONObject; import org.json.JSONException; import org.json.JSONArray; import java.io.*; import java.util.HashMap; import java.util.Calendar; import java.util.Date; import java.text.DateFormat; import java.text.SimpleDateFormat; public class Main { private static int testStartPage = 6; public static void main(String[] args) { Lesson lesson = new Lesson(); ApplicationJSON application = new ApplicationJSON(ResourceManager.getJSON("application.json")); int feedBackID = application.getPageByType("FeedbackPage"); int[] testIDs = application.getPagesByType("SpeakingQuestionPage"); int[] surveyIDs = application.getPagesByType("SurveyPage"); try { lesson.getDialog().setTitle(application.getTitle()); //pages JSONArray pages = application.getPages(); int totalTest = application.getTestsCount(); int testCnt = 0; for(int i=0; i<pages.length(); i++) { JSONObject page = pages.getJSONObject(i); String type = page.getString("type"); if (type.equals("SpeakingQuestionPage")) { page.put("totalTest", totalTest); testCnt++; page.put("id", testCnt); } LessonPageDescriptor p = PageFactory.createPage(type, page); if (i < pages.length() - 1) { p.setNextPageDescriptor(Integer.toString(i+2)); } lesson.registerLessonPage(Integer.toString(i+1), p); } lesson.setCurrentPage("1"); int ret = lesson.showModalDialog(); HashMap submit = lesson.getModel().getPageSubmit(); String userID = (String) ((HashMap)submit.get("1")).get("userID"); String str = ""; if (testIDs != null) { for(int i=0; i<testIDs.length; i++) { str += Utils.Hash2String((HashMap)submit.get(Integer.toString(testIDs[i]))); } Utils.WriteFile(ResourceManager.getUserTestFile(userID), str); } for(int i=0; i<surveyIDs.length; i++) { HashMap page = (HashMap)submit.get(Integer.toString(surveyIDs[i])); if (page != null) { Utils.WriteFile(ResourceManager.getSurveyFile(userID), Utils.Hash2CSV(page)); } } - Utils.WriteFile(ResourceManager.getQueryFile(userID), Utils.Hash2String((HashMap)submit.get(Integer.toString(feedBackID)))); + if (feedBackID != -1) + Utils.WriteFile(ResourceManager.getQueryFile(userID), Utils.Hash2String((HashMap)submit.get(Integer.toString(feedBackID)))); System.out.println("Dialog return code is (0=Finish,1=Error): " + ret); } catch (JSONException e) { lesson.getDialog().setTitle("Oral Completion Test"); } System.exit(0); } }
true
true
public static void main(String[] args) { Lesson lesson = new Lesson(); ApplicationJSON application = new ApplicationJSON(ResourceManager.getJSON("application.json")); int feedBackID = application.getPageByType("FeedbackPage"); int[] testIDs = application.getPagesByType("SpeakingQuestionPage"); int[] surveyIDs = application.getPagesByType("SurveyPage"); try { lesson.getDialog().setTitle(application.getTitle()); //pages JSONArray pages = application.getPages(); int totalTest = application.getTestsCount(); int testCnt = 0; for(int i=0; i<pages.length(); i++) { JSONObject page = pages.getJSONObject(i); String type = page.getString("type"); if (type.equals("SpeakingQuestionPage")) { page.put("totalTest", totalTest); testCnt++; page.put("id", testCnt); } LessonPageDescriptor p = PageFactory.createPage(type, page); if (i < pages.length() - 1) { p.setNextPageDescriptor(Integer.toString(i+2)); } lesson.registerLessonPage(Integer.toString(i+1), p); } lesson.setCurrentPage("1"); int ret = lesson.showModalDialog(); HashMap submit = lesson.getModel().getPageSubmit(); String userID = (String) ((HashMap)submit.get("1")).get("userID"); String str = ""; if (testIDs != null) { for(int i=0; i<testIDs.length; i++) { str += Utils.Hash2String((HashMap)submit.get(Integer.toString(testIDs[i]))); } Utils.WriteFile(ResourceManager.getUserTestFile(userID), str); } for(int i=0; i<surveyIDs.length; i++) { HashMap page = (HashMap)submit.get(Integer.toString(surveyIDs[i])); if (page != null) { Utils.WriteFile(ResourceManager.getSurveyFile(userID), Utils.Hash2CSV(page)); } } Utils.WriteFile(ResourceManager.getQueryFile(userID), Utils.Hash2String((HashMap)submit.get(Integer.toString(feedBackID)))); System.out.println("Dialog return code is (0=Finish,1=Error): " + ret); } catch (JSONException e) { lesson.getDialog().setTitle("Oral Completion Test"); } System.exit(0); }
public static void main(String[] args) { Lesson lesson = new Lesson(); ApplicationJSON application = new ApplicationJSON(ResourceManager.getJSON("application.json")); int feedBackID = application.getPageByType("FeedbackPage"); int[] testIDs = application.getPagesByType("SpeakingQuestionPage"); int[] surveyIDs = application.getPagesByType("SurveyPage"); try { lesson.getDialog().setTitle(application.getTitle()); //pages JSONArray pages = application.getPages(); int totalTest = application.getTestsCount(); int testCnt = 0; for(int i=0; i<pages.length(); i++) { JSONObject page = pages.getJSONObject(i); String type = page.getString("type"); if (type.equals("SpeakingQuestionPage")) { page.put("totalTest", totalTest); testCnt++; page.put("id", testCnt); } LessonPageDescriptor p = PageFactory.createPage(type, page); if (i < pages.length() - 1) { p.setNextPageDescriptor(Integer.toString(i+2)); } lesson.registerLessonPage(Integer.toString(i+1), p); } lesson.setCurrentPage("1"); int ret = lesson.showModalDialog(); HashMap submit = lesson.getModel().getPageSubmit(); String userID = (String) ((HashMap)submit.get("1")).get("userID"); String str = ""; if (testIDs != null) { for(int i=0; i<testIDs.length; i++) { str += Utils.Hash2String((HashMap)submit.get(Integer.toString(testIDs[i]))); } Utils.WriteFile(ResourceManager.getUserTestFile(userID), str); } for(int i=0; i<surveyIDs.length; i++) { HashMap page = (HashMap)submit.get(Integer.toString(surveyIDs[i])); if (page != null) { Utils.WriteFile(ResourceManager.getSurveyFile(userID), Utils.Hash2CSV(page)); } } if (feedBackID != -1) Utils.WriteFile(ResourceManager.getQueryFile(userID), Utils.Hash2String((HashMap)submit.get(Integer.toString(feedBackID)))); System.out.println("Dialog return code is (0=Finish,1=Error): " + ret); } catch (JSONException e) { lesson.getDialog().setTitle("Oral Completion Test"); } System.exit(0); }
diff --git a/tests/com.ebmwebsourcing.petals.tests.common/src/com/ebmwebsourcing/petals/tests/common/SUCreator.java b/tests/com.ebmwebsourcing.petals.tests.common/src/com/ebmwebsourcing/petals/tests/common/SUCreator.java index 8c224c8f..6d697f28 100644 --- a/tests/com.ebmwebsourcing.petals.tests.common/src/com/ebmwebsourcing/petals/tests/common/SUCreator.java +++ b/tests/com.ebmwebsourcing.petals.tests.common/src/com/ebmwebsourcing/petals/tests/common/SUCreator.java @@ -1,81 +1,82 @@ package com.ebmwebsourcing.petals.tests.common; import org.eclipse.swtbot.eclipse.finder.SWTWorkbenchBot; import org.eclipse.swtbot.eclipse.finder.widgets.SWTBotEditor; import org.eclipse.swtbot.eclipse.finder.widgets.SWTBotView; import org.eclipse.swtbot.swt.finder.SWTBot; import org.eclipse.swtbot.swt.finder.exceptions.WidgetNotFoundException; import org.eclipse.swtbot.swt.finder.waits.ICondition; import org.eclipse.swtbot.swt.finder.widgets.SWTBotCombo; import org.eclipse.swtbot.swt.finder.widgets.SWTBotTree; public class SUCreator { public static SUDesc createFileTransferEndpoint(final SWTWorkbenchBot bot) { final SUDesc su = new SUDesc(); final SWTBotEditor currentEditor = getCurrentEditor(bot); su.setServiceName("TestFileTransferService" + System.currentTimeMillis()); bot.menu("File").menu("New").menu("Service Unit").click(); bot.button("Next >"); // wait for button to appear. SWTBotCombo componentCombo = bot.comboBox(1); componentCombo.setSelection("File Transfer // petals-bc-filetransfer"); - su.setWsdlName("getFiles.wsdl"); bot.button("Next >").click(); bot.ccomboBox(3).setText(su.getServiceName()); su.setEndpoint(su.getServiceName() + "Endpoint"); bot.text().setText(su.getEndpoint()); bot.button("Next >").click(); su.setProjectName(bot.text().getText()); bot.button("Next >").click(); - bot.text(2).setText("testFolder"); + bot.comboBox().setSelection(1); + su.setWsdlName("GetFiles.wsdl"); + bot.text(0).setText("testFolder"); bot.button("Next >").click(); bot.button("Finish").click(); bot.waitUntil(new ICondition() { @Override public boolean test() throws Exception { return bot.activeEditor() != currentEditor; } @Override public void init(SWTBot bot) { } @Override public String getFailureMessage() { return null; } }); SWTBotView view = bot.viewById("com.ebmwebsourcing.petals.common.projects"); view.show(); view.setFocus(); final SWTBotTree tree = bot.tree(1); bot.waitUntil(new ICondition() { @Override public boolean test() throws Exception { tree.getTreeItem("Service Units").expand().getNode(su.getProjectName()); return true; } @Override public void init(SWTBot bot) { } @Override public String getFailureMessage() { return "SU not accessible in Petals Navigator view"; } }); return su; } private static SWTBotEditor getCurrentEditor(SWTWorkbenchBot bot) { try { return bot.activeEditor(); } catch (WidgetNotFoundException ex) { return null; } } }
false
true
public static SUDesc createFileTransferEndpoint(final SWTWorkbenchBot bot) { final SUDesc su = new SUDesc(); final SWTBotEditor currentEditor = getCurrentEditor(bot); su.setServiceName("TestFileTransferService" + System.currentTimeMillis()); bot.menu("File").menu("New").menu("Service Unit").click(); bot.button("Next >"); // wait for button to appear. SWTBotCombo componentCombo = bot.comboBox(1); componentCombo.setSelection("File Transfer // petals-bc-filetransfer"); su.setWsdlName("getFiles.wsdl"); bot.button("Next >").click(); bot.ccomboBox(3).setText(su.getServiceName()); su.setEndpoint(su.getServiceName() + "Endpoint"); bot.text().setText(su.getEndpoint()); bot.button("Next >").click(); su.setProjectName(bot.text().getText()); bot.button("Next >").click(); bot.text(2).setText("testFolder"); bot.button("Next >").click(); bot.button("Finish").click(); bot.waitUntil(new ICondition() { @Override public boolean test() throws Exception { return bot.activeEditor() != currentEditor; } @Override public void init(SWTBot bot) { } @Override public String getFailureMessage() { return null; } }); SWTBotView view = bot.viewById("com.ebmwebsourcing.petals.common.projects"); view.show(); view.setFocus(); final SWTBotTree tree = bot.tree(1); bot.waitUntil(new ICondition() { @Override public boolean test() throws Exception { tree.getTreeItem("Service Units").expand().getNode(su.getProjectName()); return true; } @Override public void init(SWTBot bot) { } @Override public String getFailureMessage() { return "SU not accessible in Petals Navigator view"; } }); return su; }
public static SUDesc createFileTransferEndpoint(final SWTWorkbenchBot bot) { final SUDesc su = new SUDesc(); final SWTBotEditor currentEditor = getCurrentEditor(bot); su.setServiceName("TestFileTransferService" + System.currentTimeMillis()); bot.menu("File").menu("New").menu("Service Unit").click(); bot.button("Next >"); // wait for button to appear. SWTBotCombo componentCombo = bot.comboBox(1); componentCombo.setSelection("File Transfer // petals-bc-filetransfer"); bot.button("Next >").click(); bot.ccomboBox(3).setText(su.getServiceName()); su.setEndpoint(su.getServiceName() + "Endpoint"); bot.text().setText(su.getEndpoint()); bot.button("Next >").click(); su.setProjectName(bot.text().getText()); bot.button("Next >").click(); bot.comboBox().setSelection(1); su.setWsdlName("GetFiles.wsdl"); bot.text(0).setText("testFolder"); bot.button("Next >").click(); bot.button("Finish").click(); bot.waitUntil(new ICondition() { @Override public boolean test() throws Exception { return bot.activeEditor() != currentEditor; } @Override public void init(SWTBot bot) { } @Override public String getFailureMessage() { return null; } }); SWTBotView view = bot.viewById("com.ebmwebsourcing.petals.common.projects"); view.show(); view.setFocus(); final SWTBotTree tree = bot.tree(1); bot.waitUntil(new ICondition() { @Override public boolean test() throws Exception { tree.getTreeItem("Service Units").expand().getNode(su.getProjectName()); return true; } @Override public void init(SWTBot bot) { } @Override public String getFailureMessage() { return "SU not accessible in Petals Navigator view"; } }); return su; }
diff --git a/components/bio-formats/src/loci/formats/codec/CodecOptions.java b/components/bio-formats/src/loci/formats/codec/CodecOptions.java index 1fbf3aa33..077339aa4 100644 --- a/components/bio-formats/src/loci/formats/codec/CodecOptions.java +++ b/components/bio-formats/src/loci/formats/codec/CodecOptions.java @@ -1,145 +1,146 @@ // // CodecOptions.java // /* OME Bio-Formats package for reading and converting biological file formats. Copyright (C) 2005-@year@ UW-Madison LOCI and Glencoe Software, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package loci.formats.codec; import java.awt.image.ColorModel; /** * Options for compressing and decompressing data. * * <dl><dt><b>Source code:</b></dt> * <dd><a href="http://trac.openmicroscopy.org.uk/ome/browser/bioformats.git/components/bio-formats/src/loci/formats/codec/CodecOptions.java">Trac</a>, * <a href="http://git.openmicroscopy.org/?p=bioformats.git;a=blob;f=components/bio-formats/src/loci/formats/codec/CodecOptions.java;hb=HEAD">Gitweb</a></dd></dl> */ public class CodecOptions { /** Width, in pixels, of the image. (READ/WRITE) */ public int width; /** Height, in pixels, of the image. (READ/WRITE) */ public int height; /** Number of channels. (READ/WRITE) */ public int channels; /** Number of bits per channel. (READ/WRITE) */ public int bitsPerSample; /** Indicates endianness of pixel data. (READ/WRITE) */ public boolean littleEndian; /** Indicates whether or not channels are interleaved. (READ/WRITE) */ public boolean interleaved; /** Indicates whether or not the pixel data is signed. (READ/WRITE) */ public boolean signed; /** * Tile width as it would be provided to: * {@link javax.imageio.ImageWriteParam#setTiling(int, int, int, int)} * (WRITE). */ public int tileWidth; /** * Tile height as it would be provided to: * {@link javax.imageio.ImageWriteParam#setTiling(int, int, int, int)} * (WRITE). */ public int tileHeight; /** * Horizontal offset of the tile grid as it would be provided to: * {@link javax.imageio.ImageWriteParam#setTiling(int, int, int, int)} * (WRITE). */ public int tileGridXOffset; /** * Vertical offset of the tile grid as it would be provided to: * {@link javax.imageio.ImageWriteParam#setTiling(int, int, int, int)} * (WRITE). */ public int tileGridYOffset; /** * If compressing, this is the maximum number of raw bytes to compress. * If decompressing, this is the maximum number of raw bytes to return. * (READ/WRITE). */ public int maxBytes; /** Pixels for preceding image (READ/WRITE). */ public byte[] previousImage; /** * Used with codecs allowing lossy and lossless compression. * Default is set to true (WRITE). */ public boolean lossless; /** Color model to use when constructing an image (WRITE).*/ public ColorModel colorModel; /** Compression quality level as it would be provided to: * {@link javax.imageio.ImageWriteParam#compressionQuality} (WRITE). */ public double quality; // -- Constructors -- /** Construct a new CodecOptions. */ public CodecOptions() { } /** Construct a new CodecOptions using the given CodecOptions. */ public CodecOptions(CodecOptions options) { this.width = options.width; this.height = options.height; this.channels = options.channels; this.bitsPerSample = options.bitsPerSample; this.littleEndian = options.littleEndian; this.interleaved = options.interleaved; this.signed = options.signed; this.maxBytes = options.maxBytes; this.previousImage = options.previousImage; this.lossless = options.lossless; this.colorModel = options.colorModel; + this.quality = options.quality; this.tileWidth = options.tileWidth; this.tileHeight = options.tileHeight; this.tileGridXOffset = options.tileGridXOffset; this.tileGridYOffset = options.tileGridYOffset; } // -- Static methods -- /** Return CodecOptions with reasonable default values. */ public static CodecOptions getDefaultOptions() { CodecOptions options = new CodecOptions(); options.littleEndian = false; options.interleaved = false; options.lossless = true; return options; } }
true
true
public CodecOptions(CodecOptions options) { this.width = options.width; this.height = options.height; this.channels = options.channels; this.bitsPerSample = options.bitsPerSample; this.littleEndian = options.littleEndian; this.interleaved = options.interleaved; this.signed = options.signed; this.maxBytes = options.maxBytes; this.previousImage = options.previousImage; this.lossless = options.lossless; this.colorModel = options.colorModel; this.tileWidth = options.tileWidth; this.tileHeight = options.tileHeight; this.tileGridXOffset = options.tileGridXOffset; this.tileGridYOffset = options.tileGridYOffset; }
public CodecOptions(CodecOptions options) { this.width = options.width; this.height = options.height; this.channels = options.channels; this.bitsPerSample = options.bitsPerSample; this.littleEndian = options.littleEndian; this.interleaved = options.interleaved; this.signed = options.signed; this.maxBytes = options.maxBytes; this.previousImage = options.previousImage; this.lossless = options.lossless; this.colorModel = options.colorModel; this.quality = options.quality; this.tileWidth = options.tileWidth; this.tileHeight = options.tileHeight; this.tileGridXOffset = options.tileGridXOffset; this.tileGridYOffset = options.tileGridYOffset; }
diff --git a/src/com/android/phone/NotificationMgr.java b/src/com/android/phone/NotificationMgr.java index 78a6c6ce..1cff4fe0 100644 --- a/src/com/android/phone/NotificationMgr.java +++ b/src/com/android/phone/NotificationMgr.java @@ -1,1460 +1,1454 @@ /* * Copyright (C) 2006 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.phone; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.StatusBarManager; import android.content.AsyncQueryHandler; import android.content.ComponentName; import android.content.ContentResolver; import android.content.ContentUris; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.media.AudioManager; import android.net.Uri; import android.os.PowerManager; import android.os.SystemProperties; import android.preference.PreferenceManager; import android.provider.CallLog.Calls; import android.provider.ContactsContract.Contacts; import android.provider.ContactsContract.PhoneLookup; import android.provider.Settings; import android.telephony.PhoneNumberUtils; import android.telephony.ServiceState; import android.text.TextUtils; import android.util.Log; import android.widget.ImageView; import android.widget.Toast; import com.android.internal.telephony.Call; import com.android.internal.telephony.CallManager; import com.android.internal.telephony.CallerInfo; import com.android.internal.telephony.CallerInfoAsyncQuery; import com.android.internal.telephony.Connection; import com.android.internal.telephony.Phone; import com.android.internal.telephony.PhoneBase; import com.android.internal.telephony.TelephonyCapabilities; /** * NotificationManager-related utility code for the Phone app. * * This is a singleton object which acts as the interface to the * framework's NotificationManager, and is used to display status bar * icons and control other status bar-related behavior. * * @see PhoneApp.notificationMgr */ public class NotificationMgr implements CallerInfoAsyncQuery.OnQueryCompleteListener{ private static final String LOG_TAG = "NotificationMgr"; private static final boolean DBG = (PhoneApp.DBG_LEVEL >= 1) && (SystemProperties.getInt("ro.debuggable", 0) == 1); private static final String[] CALL_LOG_PROJECTION = new String[] { Calls._ID, Calls.NUMBER, Calls.DATE, Calls.DURATION, Calls.TYPE, }; // notification types static final int MISSED_CALL_NOTIFICATION = 1; static final int IN_CALL_NOTIFICATION = 2; static final int MMI_NOTIFICATION = 3; static final int NETWORK_SELECTION_NOTIFICATION = 4; static final int VOICEMAIL_NOTIFICATION = 5; static final int CALL_FORWARD_NOTIFICATION = 6; static final int DATA_DISCONNECTED_ROAMING_NOTIFICATION = 7; static final int SELECTED_OPERATOR_FAIL_NOTIFICATION = 8; /** The singleton NotificationMgr instance. */ private static NotificationMgr sInstance; private PhoneApp mApp; private Phone mPhone; private CallManager mCM; private Context mContext; private NotificationManager mNotificationManager; private StatusBarManager mStatusBarManager; private PowerManager mPowerManager; private Toast mToast; private boolean mShowingSpeakerphoneIcon; private boolean mShowingMuteIcon; public StatusBarHelper statusBarHelper; // used to track the missed call counter, default to 0. private int mNumberMissedCalls = 0; // Currently-displayed resource IDs for some status bar icons (or zero // if no notification is active): private int mInCallResId; // used to track the notification of selected network unavailable private boolean mSelectedUnavailableNotify = false; // Retry params for the getVoiceMailNumber() call; see updateMwi(). private static final int MAX_VM_NUMBER_RETRIES = 5; private static final int VM_NUMBER_RETRY_DELAY_MILLIS = 10000; private int mVmNumberRetriesRemaining = MAX_VM_NUMBER_RETRIES; // Query used to look up caller-id info for the "call log" notification. private QueryHandler mQueryHandler = null; private static final int CALL_LOG_TOKEN = -1; private static final int CONTACT_TOKEN = -2; /** * Private constructor (this is a singleton). * @see init() */ private NotificationMgr(PhoneApp app) { mApp = app; mContext = app; mNotificationManager = (NotificationManager) app.getSystemService(Context.NOTIFICATION_SERVICE); mStatusBarManager = (StatusBarManager) app.getSystemService(Context.STATUS_BAR_SERVICE); mPowerManager = (PowerManager) app.getSystemService(Context.POWER_SERVICE); mPhone = app.phone; // TODO: better style to use mCM.getDefaultPhone() everywhere instead mCM = app.mCM; statusBarHelper = new StatusBarHelper(); } /** * Initialize the singleton NotificationMgr instance. * * This is only done once, at startup, from PhoneApp.onCreate(). * From then on, the NotificationMgr instance is available via the * PhoneApp's public "notificationMgr" field, which is why there's no * getInstance() method here. */ /* package */ static NotificationMgr init(PhoneApp app) { synchronized (NotificationMgr.class) { if (sInstance == null) { sInstance = new NotificationMgr(app); // Update the notifications that need to be touched at startup. sInstance.updateNotificationsAtStartup(); } else { Log.wtf(LOG_TAG, "init() called multiple times! sInstance = " + sInstance); } return sInstance; } } /** * Helper class that's a wrapper around the framework's * StatusBarManager.disable() API. * * This class is used to control features like: * * - Disabling the status bar "notification windowshade" * while the in-call UI is up * * - Disabling notification alerts (audible or vibrating) * while a phone call is active * * - Disabling navigation via the system bar (the "soft buttons" at * the bottom of the screen on devices with no hard buttons) * * We control these features through a single point of control to make * sure that the various StatusBarManager.disable() calls don't * interfere with each other. */ public class StatusBarHelper { // Current desired state of status bar / system bar behavior private boolean mIsNotificationEnabled = true; private boolean mIsExpandedViewEnabled = true; private boolean mIsSystemBarNavigationEnabled = true; private StatusBarHelper () { } /** * Enables or disables auditory / vibrational alerts. * * (We disable these any time a voice call is active, regardless * of whether or not the in-call UI is visible.) */ public void enableNotificationAlerts(boolean enable) { if (mIsNotificationEnabled != enable) { mIsNotificationEnabled = enable; updateStatusBar(); } } /** * Enables or disables the expanded view of the status bar * (i.e. the ability to pull down the "notification windowshade"). * * (This feature is disabled by the InCallScreen while the in-call * UI is active.) */ public void enableExpandedView(boolean enable) { if (mIsExpandedViewEnabled != enable) { mIsExpandedViewEnabled = enable; updateStatusBar(); } } /** * Enables or disables the navigation via the system bar (the * "soft buttons" at the bottom of the screen) * * (This feature is disabled while an incoming call is ringing, * because it's easy to accidentally touch the system bar while * pulling the phone out of your pocket.) */ public void enableSystemBarNavigation(boolean enable) { if (mIsSystemBarNavigationEnabled != enable) { mIsSystemBarNavigationEnabled = enable; updateStatusBar(); } } /** * Updates the status bar to reflect the current desired state. */ private void updateStatusBar() { int state = StatusBarManager.DISABLE_NONE; if (!mIsExpandedViewEnabled) { state |= StatusBarManager.DISABLE_EXPAND; } if (!mIsNotificationEnabled) { state |= StatusBarManager.DISABLE_NOTIFICATION_ALERTS; } if (!mIsSystemBarNavigationEnabled) { // Disable *all* possible navigation via the system bar. state |= StatusBarManager.DISABLE_HOME; state |= StatusBarManager.DISABLE_RECENT; state |= StatusBarManager.DISABLE_BACK; } if (DBG) log("updateStatusBar: state = 0x" + Integer.toHexString(state)); mStatusBarManager.disable(state); } } /** * Makes sure phone-related notifications are up to date on a * freshly-booted device. */ private void updateNotificationsAtStartup() { if (DBG) log("updateNotificationsAtStartup()..."); // instantiate query handler mQueryHandler = new QueryHandler(mContext.getContentResolver()); // setup query spec, look for all Missed calls that are new. StringBuilder where = new StringBuilder("type="); where.append(Calls.MISSED_TYPE); where.append(" AND new=1"); // start the query if (DBG) log("- start call log query..."); mQueryHandler.startQuery(CALL_LOG_TOKEN, null, Calls.CONTENT_URI, CALL_LOG_PROJECTION, where.toString(), null, Calls.DEFAULT_SORT_ORDER); // Update (or cancel) the in-call notification if (DBG) log("- updating in-call notification at startup..."); updateInCallNotification(); // Depend on android.app.StatusBarManager to be set to // disable(DISABLE_NONE) upon startup. This will be the // case even if the phone app crashes. } /** The projection to use when querying the phones table */ static final String[] PHONES_PROJECTION = new String[] { PhoneLookup.NUMBER, PhoneLookup.DISPLAY_NAME, PhoneLookup._ID }; /** * Class used to run asynchronous queries to re-populate the notifications we care about. * There are really 3 steps to this: * 1. Find the list of missed calls * 2. For each call, run a query to retrieve the caller's name. * 3. For each caller, try obtaining photo. */ private class QueryHandler extends AsyncQueryHandler implements ContactsAsyncHelper.OnImageLoadCompleteListener { /** * Used to store relevant fields for the Missed Call * notifications. */ private class NotificationInfo { public String name; public String number; /** * Type of the call. {@link android.provider.CallLog.Calls#INCOMING_TYPE} * {@link android.provider.CallLog.Calls#OUTGOING_TYPE}, or * {@link android.provider.CallLog.Calls#MISSED_TYPE}. */ public String type; public long date; } public QueryHandler(ContentResolver cr) { super(cr); } /** * Handles the query results. */ @Override protected void onQueryComplete(int token, Object cookie, Cursor cursor) { // TODO: it would be faster to use a join here, but for the purposes // of this small record set, it should be ok. // Note that CursorJoiner is not useable here because the number // comparisons are not strictly equals; the comparisons happen in // the SQL function PHONE_NUMBERS_EQUAL, which is not available for // the CursorJoiner. // Executing our own query is also feasible (with a join), but that // will require some work (possibly destabilizing) in Contacts // Provider. // At this point, we will execute subqueries on each row just as // CallLogActivity.java does. switch (token) { case CALL_LOG_TOKEN: if (DBG) log("call log query complete."); // initial call to retrieve the call list. if (cursor != null) { while (cursor.moveToNext()) { // for each call in the call log list, create // the notification object and query contacts NotificationInfo n = getNotificationInfo (cursor); if (DBG) log("query contacts for number: " + n.number); mQueryHandler.startQuery(CONTACT_TOKEN, n, Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, n.number), PHONES_PROJECTION, null, null, PhoneLookup.NUMBER); } if (DBG) log("closing call log cursor."); cursor.close(); } break; case CONTACT_TOKEN: if (DBG) log("contact query complete."); // subqueries to get the caller name. if ((cursor != null) && (cookie != null)){ NotificationInfo n = (NotificationInfo) cookie; Uri personUri = null; if (cursor.moveToFirst()) { n.name = cursor.getString( cursor.getColumnIndexOrThrow(PhoneLookup.DISPLAY_NAME)); long person_id = cursor.getLong( cursor.getColumnIndexOrThrow(PhoneLookup._ID)); if (DBG) { log("contact :" + n.name + " found for phone: " + n.number + ". id : " + person_id); } personUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, person_id); } if (personUri != null) { if (DBG) { log("Start obtaining picture for the missed call. Uri: " + personUri); } // Now try to obtain a photo for this person. // ContactsAsyncHelper will do that and call onImageLoadComplete() // after that. ContactsAsyncHelper.startObtainPhotoAsync( 0, mContext, personUri, this, n); } else { if (DBG) { log("Failed to find Uri for obtaining photo." + " Just send notification without it."); } // We couldn't find person Uri, so we're sure we cannot obtain a photo. // Call notifyMissedCall() right now. notifyMissedCall(n.name, n.number, n.type, null, null, n.date); } if (DBG) log("closing contact cursor."); cursor.close(); } break; default: } } @Override public void onImageLoadComplete( int token, Drawable photo, Bitmap photoIcon, Object cookie) { if (DBG) log("Finished loading image: " + photo); NotificationInfo n = (NotificationInfo) cookie; notifyMissedCall(n.name, n.number, n.type, photo, photoIcon, n.date); } /** * Factory method to generate a NotificationInfo object given a * cursor from the call log table. */ private final NotificationInfo getNotificationInfo(Cursor cursor) { NotificationInfo n = new NotificationInfo(); n.name = null; n.number = cursor.getString(cursor.getColumnIndexOrThrow(Calls.NUMBER)); n.type = cursor.getString(cursor.getColumnIndexOrThrow(Calls.TYPE)); n.date = cursor.getLong(cursor.getColumnIndexOrThrow(Calls.DATE)); // make sure we update the number depending upon saved values in // CallLog.addCall(). If either special values for unknown or // private number are detected, we need to hand off the message // to the missed call notification. if ( (n.number.equals(CallerInfo.UNKNOWN_NUMBER)) || (n.number.equals(CallerInfo.PRIVATE_NUMBER)) || (n.number.equals(CallerInfo.PAYPHONE_NUMBER)) ) { n.number = null; } if (DBG) log("NotificationInfo constructed for number: " + n.number); return n; } } /** * Configures a Notification to emit the blinky green message-waiting/ * missed-call signal. */ private static void configureLedNotification(Notification note) { note.flags |= Notification.FLAG_SHOW_LIGHTS; note.defaults |= Notification.DEFAULT_LIGHTS; } /** * Displays a notification about a missed call. * * @param name the contact name. * @param number the phone number * @param type the type of the call. {@link android.provider.CallLog.Calls#INCOMING_TYPE} * {@link android.provider.CallLog.Calls#OUTGOING_TYPE}, or * {@link android.provider.CallLog.Calls#MISSED_TYPE} * @param photo picture which may be used for the notification (when photoIcon is null). * This also can be null when the picture itself isn't available. If photoIcon is available * it should be prioritized (because this may be too huge for notification). * See also {@link ContactsAsyncHelper}. * @param photoIcon picture which should be used for the notification. Can be null. This is * the most suitable for {@link android.app.Notification.Builder#setLargeIcon(Bitmap)}, this * should be used when non-null. * @param date the time when the missed call happened */ /* package */ void notifyMissedCall( String name, String number, String type, Drawable photo, Bitmap photoIcon, long date) { // When the user clicks this notification, we go to the call log. final Intent callLogIntent = PhoneApp.createCallLogIntent(); // Never display the missed call notification on non-voice-capable // devices, even if the device does somehow manage to get an // incoming call. if (!PhoneApp.sVoiceCapable) { if (DBG) log("notifyMissedCall: non-voice-capable device, not posting notification"); return; } // STOPSHIP: must be inside DBG/VDBG block. // if (DBG) { log("notifyMissedCall(). name: " + name + ", number: " + number + ", label: " + type + ", photo: " + photo + ", photoIcon: " + photoIcon + ", date: " + date); // } // title resource id int titleResId; // the text in the notification's line 1 and 2. String expandedText, callName; // increment number of missed calls. mNumberMissedCalls++; // get the name for the ticker text // i.e. "Missed call from <caller name or number>" if (name != null && TextUtils.isGraphic(name)) { callName = name; } else if (!TextUtils.isEmpty(number)){ callName = number; } else { // use "unknown" if the caller is unidentifiable. callName = mContext.getString(R.string.unknown); } // display the first line of the notification: // 1 missed call: call name // more than 1 missed call: <number of calls> + "missed calls" if (mNumberMissedCalls == 1) { titleResId = R.string.notification_missedCallTitle; expandedText = callName; } else { titleResId = R.string.notification_missedCallsTitle; expandedText = mContext.getString(R.string.notification_missedCallsMsg, mNumberMissedCalls); } Notification.Builder builder = new Notification.Builder(mContext); builder.setSmallIcon(android.R.drawable.stat_notify_missed_call) .setTicker(mContext.getString(R.string.notification_missedCallTicker, callName)) .setWhen(date) .setContentTitle(mContext.getText(titleResId)) .setContentText(expandedText) .setContentIntent(PendingIntent.getActivity(mContext, 0, callLogIntent, 0)) .setAutoCancel(true) .setDeleteIntent(createClearMissedCallsIntent()); if (!TextUtils.isEmpty(number) && mNumberMissedCalls == 1) { // TODO: use DBG log("Add actions with the number " + number); builder.addAction(R.drawable.ic_ab_dialer_holo_dark, mContext.getString(R.string.notification_missedCall_call_back), PhoneApp.getCallBackPendingIntent(mContext, number)); builder.addAction(R.drawable.ic_text_holo_dark, mContext.getString(R.string.notification_missedCall_message), PhoneApp.getSendSmsFromNotificationPendingIntent(mContext, number)); if (photoIcon != null) { builder.setLargeIcon(photoIcon); } else if (photo instanceof BitmapDrawable) { builder.setLargeIcon(((BitmapDrawable) photo).getBitmap()); } } else { // TODO: use DBG log("Suppress actions. number: " + number + ", missedCalls: " + mNumberMissedCalls); } Notification notification = builder.getNotification(); configureLedNotification(notification); mNotificationManager.notify(MISSED_CALL_NOTIFICATION, notification); } /** Returns an intent to be invoked when the missed call notification is cleared. */ private PendingIntent createClearMissedCallsIntent() { Intent intent = new Intent(mContext, ClearMissedCallsService.class); intent.setAction(ClearMissedCallsService.ACTION_CLEAR_MISSED_CALLS); return PendingIntent.getService(mContext, 0, intent, 0); } /** * Cancels the "missed call" notification. * * @see ITelephony.cancelMissedCallsNotification() */ void cancelMissedCallNotification() { // reset the number of missed calls to 0. mNumberMissedCalls = 0; mNotificationManager.cancel(MISSED_CALL_NOTIFICATION); } private void notifySpeakerphone() { if (!mShowingSpeakerphoneIcon) { mStatusBarManager.setIcon("speakerphone", android.R.drawable.stat_sys_speakerphone, 0, mContext.getString(R.string.accessibility_speakerphone_enabled)); mShowingSpeakerphoneIcon = true; } } private void cancelSpeakerphone() { if (mShowingSpeakerphoneIcon) { mStatusBarManager.removeIcon("speakerphone"); mShowingSpeakerphoneIcon = false; } } /** * Shows or hides the "speakerphone" notification in the status bar, * based on the actual current state of the speaker. * * If you already know the current speaker state (e.g. if you just * called AudioManager.setSpeakerphoneOn() yourself) then you should * directly call {@link #updateSpeakerNotification(boolean)} instead. * * (But note that the status bar icon is *never* shown while the in-call UI * is active; it only appears if you bail out to some other activity.) */ private void updateSpeakerNotification() { AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE); boolean showNotification = (mPhone.getState() == Phone.State.OFFHOOK) && audioManager.isSpeakerphoneOn(); if (DBG) log(showNotification ? "updateSpeakerNotification: speaker ON" : "updateSpeakerNotification: speaker OFF (or not offhook)"); updateSpeakerNotification(showNotification); } /** * Shows or hides the "speakerphone" notification in the status bar. * * @param showNotification if true, call notifySpeakerphone(); * if false, call cancelSpeakerphone(). * * Use {@link updateSpeakerNotification()} to update the status bar * based on the actual current state of the speaker. * * (But note that the status bar icon is *never* shown while the in-call UI * is active; it only appears if you bail out to some other activity.) */ public void updateSpeakerNotification(boolean showNotification) { if (DBG) log("updateSpeakerNotification(" + showNotification + ")..."); // Regardless of the value of the showNotification param, suppress // the status bar icon if the the InCallScreen is the foreground // activity, since the in-call UI already provides an onscreen // indication of the speaker state. (This reduces clutter in the // status bar.) if (mApp.isShowingCallScreen()) { cancelSpeakerphone(); return; } if (showNotification) { notifySpeakerphone(); } else { cancelSpeakerphone(); } } private void notifyMute() { if (!mShowingMuteIcon) { mStatusBarManager.setIcon("mute", android.R.drawable.stat_notify_call_mute, 0, mContext.getString(R.string.accessibility_call_muted)); mShowingMuteIcon = true; } } private void cancelMute() { if (mShowingMuteIcon) { mStatusBarManager.removeIcon("mute"); mShowingMuteIcon = false; } } /** * Shows or hides the "mute" notification in the status bar, * based on the current mute state of the Phone. * * (But note that the status bar icon is *never* shown while the in-call UI * is active; it only appears if you bail out to some other activity.) */ void updateMuteNotification() { // Suppress the status bar icon if the the InCallScreen is the // foreground activity, since the in-call UI already provides an // onscreen indication of the mute state. (This reduces clutter // in the status bar.) if (mApp.isShowingCallScreen()) { cancelMute(); return; } if ((mCM.getState() == Phone.State.OFFHOOK) && PhoneUtils.getMute()) { if (DBG) log("updateMuteNotification: MUTED"); notifyMute(); } else { if (DBG) log("updateMuteNotification: not muted (or not offhook)"); cancelMute(); } } /** * Updates the phone app's status bar notification based on the * current telephony state, or cancels the notification if the phone * is totally idle. * * This method will never actually launch the incoming-call UI. * (Use updateNotificationAndLaunchIncomingCallUi() for that.) */ public void updateInCallNotification() { // allowFullScreenIntent=false means *don't* allow the incoming // call UI to be launched. updateInCallNotification(false); } /** * Updates the phone app's status bar notification *and* launches the * incoming call UI in response to a new incoming call. * * This is just like updateInCallNotification(), with one exception: * If an incoming call is ringing (or call-waiting), the notification * will also include a "fullScreenIntent" that will cause the * InCallScreen to be launched immediately, unless the current * foreground activity is marked as "immersive". * * (This is the mechanism that actually brings up the incoming call UI * when we receive a "new ringing connection" event from the telephony * layer.) * * Watch out: this method should ONLY be called directly from the code * path in CallNotifier that handles the "new ringing connection" * event from the telephony layer. All other places that update the * in-call notification (like for phone state changes) should call * updateInCallNotification() instead. (This ensures that we don't * end up launching the InCallScreen multiple times for a single * incoming call, which could cause slow responsiveness and/or visible * glitches.) * * Also note that this method is safe to call even if the phone isn't * actually ringing (or, more likely, if an incoming call *was* * ringing briefly but then disconnected). In that case, we'll simply * update or cancel the in-call notification based on the current * phone state. * * @see #updateInCallNotification(boolean) */ public void updateNotificationAndLaunchIncomingCallUi() { // Set allowFullScreenIntent=true to indicate that we *should* // launch the incoming call UI if necessary. updateInCallNotification(true); } /** * Helper method for updateInCallNotification() and * updateNotificationAndLaunchIncomingCallUi(): Update the phone app's * status bar notification based on the current telephony state, or * cancels the notification if the phone is totally idle. * * @param allowFullScreenIntent If true, *and* an incoming call is * ringing, the notification will include a "fullScreenIntent" * pointing at the InCallScreen (which will cause the InCallScreen * to be launched.) * Watch out: This should be set to true *only* when directly * handling the "new ringing connection" event from the telephony * layer (see updateNotificationAndLaunchIncomingCallUi().) */ private void updateInCallNotification(boolean allowFullScreenIntent) { int resId; if (DBG) log("updateInCallNotification(allowFullScreenIntent = " + allowFullScreenIntent + ")..."); // Never display the "ongoing call" notification on // non-voice-capable devices, even if the phone is actually // offhook (like during a non-interactive OTASP call.) if (!PhoneApp.sVoiceCapable) { if (DBG) log("- non-voice-capable device; suppressing notification."); return; } // If the phone is idle, completely clean up all call-related // notifications. if (mCM.getState() == Phone.State.IDLE) { cancelInCall(); cancelMute(); cancelSpeakerphone(); return; } final boolean hasRingingCall = mCM.hasActiveRingingCall(); final boolean hasActiveCall = mCM.hasActiveFgCall(); final boolean hasHoldingCall = mCM.hasActiveBgCall(); if (DBG) { log(" - hasRingingCall = " + hasRingingCall); log(" - hasActiveCall = " + hasActiveCall); log(" - hasHoldingCall = " + hasHoldingCall); } // Suppress the in-call notification if the InCallScreen is the // foreground activity, since it's already obvious that you're on a // call. (The status bar icon is needed only if you navigate *away* // from the in-call UI.) - // - // Note: we should not use isShowingCallScreen() here, since it will - // return false when the screen turns off during user's on the InCallScreen, - // which will cause a brief flicker of the icon in the status bar when - // the screen turns back on (due to the prox sensor, for example) while - // still on the InCallScreen. - boolean suppressNotification = mApp.isShowingCallScreenForProximity(); + boolean suppressNotification = mApp.isShowingCallScreen(); // if (DBG) log("- suppressNotification: initial value: " + suppressNotification); // ...except for a couple of cases where we *never* suppress the // notification: // // - If there's an incoming ringing call: always show the // notification, since the in-call notification is what actually // launches the incoming call UI in the first place (see // notification.fullScreenIntent below.) This makes sure that we'll // correctly handle the case where a new incoming call comes in but // the InCallScreen is already in the foreground. if (hasRingingCall) suppressNotification = false; // - If "voice privacy" mode is active: always show the notification, // since that's the only "voice privacy" indication we have. boolean enhancedVoicePrivacy = mApp.notifier.getVoicePrivacyState(); // if (DBG) log("updateInCallNotification: enhancedVoicePrivacy = " + enhancedVoicePrivacy); if (enhancedVoicePrivacy) suppressNotification = false; if (suppressNotification) { if (DBG) log("- suppressNotification = true; reducing clutter in status bar..."); cancelInCall(); // Suppress the mute and speaker status bar icons too // (also to reduce clutter in the status bar.) cancelSpeakerphone(); cancelMute(); return; } // Display the appropriate icon in the status bar, // based on the current phone and/or bluetooth state. if (hasRingingCall) { // There's an incoming ringing call. resId = R.drawable.stat_sys_phone_call; } else if (!hasActiveCall && hasHoldingCall) { // There's only one call, and it's on hold. if (enhancedVoicePrivacy) { resId = R.drawable.stat_sys_vp_phone_call_on_hold; } else { resId = R.drawable.stat_sys_phone_call_on_hold; } } else { if (enhancedVoicePrivacy) { resId = R.drawable.stat_sys_vp_phone_call; } else { resId = R.drawable.stat_sys_phone_call; } } // Note we can't just bail out now if (resId == mInCallResId), // since even if the status icon hasn't changed, some *other* // notification-related info may be different from the last time // we were here (like the caller-id info of the foreground call, // if the user swapped calls...) if (DBG) log("- Updating status bar icon: resId = " + resId); mInCallResId = resId; // Even if both lines are in use, we only show a single item in // the expanded Notifications UI. It's labeled "Ongoing call" // (or "On hold" if there's only one call, and it's on hold.) // Also, we don't have room to display caller-id info from two // different calls. So if both lines are in use, display info // from the foreground call. And if there's a ringing call, // display that regardless of the state of the other calls. Call currentCall; if (hasRingingCall) { currentCall = mCM.getFirstActiveRingingCall(); } else if (hasActiveCall) { currentCall = mCM.getActiveFgCall(); } else { currentCall = mCM.getFirstActiveBgCall(); } Connection currentConn = currentCall.getEarliestConnection(); final Notification.Builder builder = new Notification.Builder(mContext); builder.setSmallIcon(mInCallResId).setOngoing(true); // PendingIntent that can be used to launch the InCallScreen. The // system fires off this intent if the user pulls down the windowshade // and clicks the notification's expanded view. It's also used to // launch the InCallScreen immediately when when there's an incoming // call (see the "fullScreenIntent" field below). PendingIntent inCallPendingIntent = PendingIntent.getActivity(mContext, 0, PhoneApp.createInCallIntent(), 0); builder.setContentIntent(inCallPendingIntent); // Update icon on the left of the notification. // - If it is directly available from CallerInfo, we'll just use that. // - If it is not, use the same icon as in the status bar. CallerInfo callerInfo = null; if (currentConn != null) { Object o = currentConn.getUserData(); if (o instanceof CallerInfo) { callerInfo = (CallerInfo) o; } else if (o instanceof PhoneUtils.CallerInfoToken) { callerInfo = ((PhoneUtils.CallerInfoToken) o).currentInfo; } else { Log.w(LOG_TAG, "CallerInfo isn't available while Call object is available."); } } boolean largeIconWasSet = false; if (callerInfo != null) { // In most cases, the user will see the notification after CallerInfo is already // available, so photo will be available from this block. if (callerInfo.isCachedPhotoCurrent) { // .. and in that case CallerInfo's cachedPhotoIcon should also be available. // If it happens not, then try using cachedPhoto, assuming Drawable coming from // ContactProvider will be BitmapDrawable. if (callerInfo.cachedPhotoIcon != null) { builder.setLargeIcon(callerInfo.cachedPhotoIcon); largeIconWasSet = true; } else if (callerInfo.cachedPhoto instanceof BitmapDrawable) { if (DBG) log("- BitmapDrawable found for large icon"); Bitmap bitmap = ((BitmapDrawable) callerInfo.cachedPhoto).getBitmap(); builder.setLargeIcon(bitmap); largeIconWasSet = true; } else { if (DBG) { log("- Failed to fetch icon from CallerInfo's cached photo." + " (cachedPhotoIcon: " + callerInfo.cachedPhotoIcon + ", cachedPhoto: " + callerInfo.cachedPhoto + ")." + " Ignore it."); } } } if (!largeIconWasSet && callerInfo.photoResource > 0) { if (DBG) { log("- BitmapDrawable nor person Id not found for large icon." + " Use photoResource: " + callerInfo.photoResource); } Drawable drawable = mContext.getResources().getDrawable(callerInfo.photoResource); if (drawable instanceof BitmapDrawable) { Bitmap bitmap = ((BitmapDrawable) callerInfo.cachedPhoto).getBitmap(); builder.setLargeIcon(bitmap); largeIconWasSet = true; } else { if (DBG) { log("- PhotoResource was found but it didn't return BitmapDrawable." + " Ignore it"); } } } } else { if (DBG) log("- CallerInfo not found. Use the same icon as in the status bar."); } // Failed to fetch Bitmap. if (!largeIconWasSet && DBG) { log("- No useful Bitmap was found for the photo." + " Use the same icon as in the status bar."); } // If the connection is valid, then build what we need for the // content text of notification, and start the chronometer. // Otherwise, don't bother and just stick with content title. if (currentConn != null) { if (DBG) log("- Updating context text and chronometer."); if (hasRingingCall) { // Incoming call is ringing. builder.setContentText(mContext.getString(R.string.notification_incoming_call)); builder.setUsesChronometer(false); } else if (hasHoldingCall && !hasActiveCall) { // Only one call, and it's on hold. builder.setContentText(mContext.getString(R.string.notification_on_hold)); builder.setUsesChronometer(false); } else { // We show the elapsed time of the current call using Chronometer. builder.setUsesChronometer(true); // Determine the "start time" of the current connection. // We can't use currentConn.getConnectTime(), because (1) that's // in the currentTimeMillis() time base, and (2) it's zero when // the phone first goes off hook, since the getConnectTime counter // doesn't start until the DIALING -> ACTIVE transition. // Instead we start with the current connection's duration, // and translate that into the elapsedRealtime() timebase. long callDurationMsec = currentConn.getDurationMillis(); builder.setWhen(System.currentTimeMillis() - callDurationMsec); builder.setContentText(mContext.getString(R.string.notification_ongoing_call)); } } else if (DBG) { Log.w(LOG_TAG, "updateInCallNotification: null connection, can't set exp view line 1."); } // display conference call string if this call is a conference // call, otherwise display the connection information. // Line 2 of the expanded view (smaller text). This is usually a // contact name or phone number. String expandedViewLine2 = ""; // TODO: it may not make sense for every point to make separate // checks for isConferenceCall, so we need to think about // possibly including this in startGetCallerInfo or some other // common point. if (PhoneUtils.isConferenceCall(currentCall)) { // if this is a conference call, just use that as the caller name. expandedViewLine2 = mContext.getString(R.string.card_title_conf_call); } else { // If necessary, start asynchronous query to do the caller-id lookup. PhoneUtils.CallerInfoToken cit = PhoneUtils.startGetCallerInfo(mContext, currentCall, this, this); expandedViewLine2 = PhoneUtils.getCompactNameFromCallerInfo(cit.currentInfo, mContext); // Note: For an incoming call, the very first time we get here we // won't have a contact name yet, since we only just started the // caller-id query. So expandedViewLine2 will start off as a raw // phone number, but we'll update it very quickly when the query // completes (see onQueryComplete() below.) } if (DBG) log("- Updating expanded view: line 2 '" + /*expandedViewLine2*/ "xxxxxxx" + "'"); builder.setContentTitle(expandedViewLine2); // TODO: We also need to *update* this notification in some cases, // like when a call ends on one line but the other is still in use // (ie. make sure the caller info here corresponds to the active // line), and maybe even when the user swaps calls (ie. if we only // show info here for the "current active call".) // Activate a couple of special Notification features if an // incoming call is ringing: if (hasRingingCall) { if (DBG) log("- Using hi-pri notification for ringing call!"); // This is a high-priority event that should be shown even if the // status bar is hidden or if an immersive activity is running. builder.setPriority(Notification.PRIORITY_HIGH); // If an immersive activity is running, we have room for a single // line of text in the small notification popup window. // We use expandedViewLine2 for this (i.e. the name or number of // the incoming caller), since that's more relevant than // expandedViewLine1 (which is something generic like "Incoming // call".) builder.setTicker(expandedViewLine2); if (allowFullScreenIntent) { // Ok, we actually want to launch the incoming call // UI at this point (in addition to simply posting a notification // to the status bar). Setting fullScreenIntent will cause // the InCallScreen to be launched immediately *unless* the // current foreground activity is marked as "immersive". if (DBG) log("- Setting fullScreenIntent: " + inCallPendingIntent); builder.setFullScreenIntent(inCallPendingIntent, true); // Ugly hack alert: // // The NotificationManager has the (undocumented) behavior // that it will *ignore* the fullScreenIntent field if you // post a new Notification that matches the ID of one that's // already active. Unfortunately this is exactly what happens // when you get an incoming call-waiting call: the // "ongoing call" notification is already visible, so the // InCallScreen won't get launched in this case! // (The result: if you bail out of the in-call UI while on a // call and then get a call-waiting call, the incoming call UI // won't come up automatically.) // // The workaround is to just notice this exact case (this is a // call-waiting call *and* the InCallScreen is not in the // foreground) and manually cancel the in-call notification // before (re)posting it. // // TODO: there should be a cleaner way of avoiding this // problem (see discussion in bug 3184149.) Call ringingCall = mCM.getFirstActiveRingingCall(); if ((ringingCall.getState() == Call.State.WAITING) && !mApp.isShowingCallScreen()) { Log.i(LOG_TAG, "updateInCallNotification: call-waiting! force relaunch..."); // Cancel the IN_CALL_NOTIFICATION immediately before // (re)posting it; this seems to force the // NotificationManager to launch the fullScreenIntent. mNotificationManager.cancel(IN_CALL_NOTIFICATION); } } } else { // not ringing call // TODO: use "if (DBG)" for this comment. log("Will show \"hang-up\" action in the ongoing active call Notification"); // TODO: use better asset. builder.addAction(R.drawable.ic_end_call, mContext.getText(R.string.notification_action_end_call), PhoneApp.createHangUpOngoingCallPendingIntent(mContext)); } Notification notification = builder.getNotification(); if (DBG) log("Notifying IN_CALL_NOTIFICATION: " + notification); mNotificationManager.notify(IN_CALL_NOTIFICATION, notification); // Finally, refresh the mute and speakerphone notifications (since // some phone state changes can indirectly affect the mute and/or // speaker state). updateSpeakerNotification(); updateMuteNotification(); } /** * Implemented for CallerInfoAsyncQuery.OnQueryCompleteListener interface. * refreshes the contentView when called. */ @Override public void onQueryComplete(int token, Object cookie, CallerInfo ci){ if (DBG) log("CallerInfo query complete (for NotificationMgr), " + "updating in-call notification.."); if (DBG) log("- cookie: " + cookie); if (DBG) log("- ci: " + ci); if (cookie == this) { // Ok, this is the caller-id query we fired off in // updateInCallNotification(), presumably when an incoming call // first appeared. If the caller-id info matched any contacts, // compactName should now be a real person name rather than a raw // phone number: if (DBG) log("- compactName is now: " + PhoneUtils.getCompactNameFromCallerInfo(ci, mContext)); // Now that our CallerInfo object has been fully filled-in, // refresh the in-call notification. if (DBG) log("- updating notification after query complete..."); updateInCallNotification(); } else { Log.w(LOG_TAG, "onQueryComplete: caller-id query from unknown source! " + "cookie = " + cookie); } } /** * Take down the in-call notification. * @see updateInCallNotification() */ private void cancelInCall() { if (DBG) log("cancelInCall()..."); mNotificationManager.cancel(IN_CALL_NOTIFICATION); mInCallResId = 0; } /** * Completely take down the in-call notification *and* the mute/speaker * notifications as well, to indicate that the phone is now idle. */ /* package */ void cancelCallInProgressNotifications() { if (DBG) log("cancelCallInProgressNotifications()..."); if (mInCallResId == 0) { return; } if (DBG) log("cancelCallInProgressNotifications: " + mInCallResId); cancelInCall(); cancelMute(); cancelSpeakerphone(); } /** * Updates the message waiting indicator (voicemail) notification. * * @param visible true if there are messages waiting */ /* package */ void updateMwi(boolean visible) { if (DBG) log("updateMwi(): " + visible); if (visible) { int resId = android.R.drawable.stat_notify_voicemail; // This Notification can get a lot fancier once we have more // information about the current voicemail messages. // (For example, the current voicemail system can't tell // us the caller-id or timestamp of a message, or tell us the // message count.) // But for now, the UI is ultra-simple: if the MWI indication // is supposed to be visible, just show a single generic // notification. String notificationTitle = mContext.getString(R.string.notification_voicemail_title); String vmNumber = mPhone.getVoiceMailNumber(); if (DBG) log("- got vm number: '" + vmNumber + "'"); // Watch out: vmNumber may be null, for two possible reasons: // // (1) This phone really has no voicemail number // // (2) This phone *does* have a voicemail number, but // the SIM isn't ready yet. // // Case (2) *does* happen in practice if you have voicemail // messages when the device first boots: we get an MWI // notification as soon as we register on the network, but the // SIM hasn't finished loading yet. // // So handle case (2) by retrying the lookup after a short // delay. if ((vmNumber == null) && !mPhone.getIccRecordsLoaded()) { if (DBG) log("- Null vm number: SIM records not loaded (yet)..."); // TODO: rather than retrying after an arbitrary delay, it // would be cleaner to instead just wait for a // SIM_RECORDS_LOADED notification. // (Unfortunately right now there's no convenient way to // get that notification in phone app code. We'd first // want to add a call like registerForSimRecordsLoaded() // to Phone.java and GSMPhone.java, and *then* we could // listen for that in the CallNotifier class.) // Limit the number of retries (in case the SIM is broken // or missing and can *never* load successfully.) if (mVmNumberRetriesRemaining-- > 0) { if (DBG) log(" - Retrying in " + VM_NUMBER_RETRY_DELAY_MILLIS + " msec..."); mApp.notifier.sendMwiChangedDelayed(VM_NUMBER_RETRY_DELAY_MILLIS); return; } else { Log.w(LOG_TAG, "NotificationMgr.updateMwi: getVoiceMailNumber() failed after " + MAX_VM_NUMBER_RETRIES + " retries; giving up."); // ...and continue with vmNumber==null, just as if the // phone had no VM number set up in the first place. } } if (TelephonyCapabilities.supportsVoiceMessageCount(mPhone)) { int vmCount = mPhone.getVoiceMessageCount(); String titleFormat = mContext.getString(R.string.notification_voicemail_title_count); notificationTitle = String.format(titleFormat, vmCount); } String notificationText; if (TextUtils.isEmpty(vmNumber)) { notificationText = mContext.getString( R.string.notification_voicemail_no_vm_number); } else { notificationText = String.format( mContext.getString(R.string.notification_voicemail_text_format), PhoneNumberUtils.formatNumber(vmNumber)); } Intent intent = new Intent(Intent.ACTION_CALL, Uri.fromParts(Constants.SCHEME_VOICEMAIL, "", null)); PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, intent, 0); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext); Uri ringtoneUri; String uriString = prefs.getString( CallFeaturesSetting.BUTTON_VOICEMAIL_NOTIFICATION_RINGTONE_KEY, null); if (!TextUtils.isEmpty(uriString)) { ringtoneUri = Uri.parse(uriString); } else { ringtoneUri = Settings.System.DEFAULT_NOTIFICATION_URI; } Notification.Builder builder = new Notification.Builder(mContext); builder.setSmallIcon(resId) .setWhen(System.currentTimeMillis()) .setContentTitle(notificationTitle) .setContentText(notificationText) .setContentIntent(pendingIntent) .setSound(ringtoneUri); Notification notification = builder.getNotification(); String vibrateWhen = prefs.getString( CallFeaturesSetting.BUTTON_VOICEMAIL_NOTIFICATION_VIBRATE_WHEN_KEY, "never"); boolean vibrateAlways = vibrateWhen.equals("always"); boolean vibrateSilent = vibrateWhen.equals("silent"); AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE); boolean nowSilent = audioManager.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE; if (vibrateAlways || (vibrateSilent && nowSilent)) { notification.defaults |= Notification.DEFAULT_VIBRATE; } notification.flags |= Notification.FLAG_NO_CLEAR; configureLedNotification(notification); mNotificationManager.notify(VOICEMAIL_NOTIFICATION, notification); } else { mNotificationManager.cancel(VOICEMAIL_NOTIFICATION); } } /** * Updates the message call forwarding indicator notification. * * @param visible true if there are messages waiting */ /* package */ void updateCfi(boolean visible) { if (DBG) log("updateCfi(): " + visible); if (visible) { // If Unconditional Call Forwarding (forward all calls) for VOICE // is enabled, just show a notification. We'll default to expanded // view for now, so the there is less confusion about the icon. If // it is deemed too weird to have CF indications as expanded views, // then we'll flip the flag back. // TODO: We may want to take a look to see if the notification can // display the target to forward calls to. This will require some // effort though, since there are multiple layers of messages that // will need to propagate that information. Notification notification; final boolean showExpandedNotification = true; if (showExpandedNotification) { Intent intent = new Intent(Intent.ACTION_MAIN); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setClassName("com.android.phone", "com.android.phone.CallFeaturesSetting"); notification = new Notification( R.drawable.stat_sys_phone_call_forward, // icon null, // tickerText 0); // The "timestamp" of this notification is meaningless; // we only care about whether CFI is currently on or not. notification.setLatestEventInfo( mContext, // context mContext.getString(R.string.labelCF), // expandedTitle mContext.getString(R.string.sum_cfu_enabled_indicator), // expandedText PendingIntent.getActivity(mContext, 0, intent, 0)); // contentIntent } else { notification = new Notification( R.drawable.stat_sys_phone_call_forward, // icon null, // tickerText System.currentTimeMillis() // when ); } notification.flags |= Notification.FLAG_ONGOING_EVENT; // also implies FLAG_NO_CLEAR mNotificationManager.notify( CALL_FORWARD_NOTIFICATION, notification); } else { mNotificationManager.cancel(CALL_FORWARD_NOTIFICATION); } } /** * Shows the "data disconnected due to roaming" notification, which * appears when you lose data connectivity because you're roaming and * you have the "data roaming" feature turned off. */ /* package */ void showDataDisconnectedRoaming() { if (DBG) log("showDataDisconnectedRoaming()..."); // "Mobile network settings" screen / dialog Intent intent = new Intent(mContext, com.android.phone.MobileNetworkSettings.class); Notification notification = new Notification( android.R.drawable.stat_sys_warning, // icon null, // tickerText System.currentTimeMillis()); notification.setLatestEventInfo( mContext, // Context mContext.getString(R.string.roaming), // expandedTitle mContext.getString(R.string.roaming_reenable_message), // expandedText PendingIntent.getActivity(mContext, 0, intent, 0)); // contentIntent mNotificationManager.notify( DATA_DISCONNECTED_ROAMING_NOTIFICATION, notification); } /** * Turns off the "data disconnected due to roaming" notification. */ /* package */ void hideDataDisconnectedRoaming() { if (DBG) log("hideDataDisconnectedRoaming()..."); mNotificationManager.cancel(DATA_DISCONNECTED_ROAMING_NOTIFICATION); } /** * Display the network selection "no service" notification * @param operator is the numeric operator number */ private void showNetworkSelection(String operator) { if (DBG) log("showNetworkSelection(" + operator + ")..."); String titleText = mContext.getString( R.string.notification_network_selection_title); String expandedText = mContext.getString( R.string.notification_network_selection_text, operator); Notification notification = new Notification(); notification.icon = android.R.drawable.stat_sys_warning; notification.when = 0; notification.flags = Notification.FLAG_ONGOING_EVENT; notification.tickerText = null; // create the target network operators settings intent Intent intent = new Intent(Intent.ACTION_MAIN); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); // Use NetworkSetting to handle the selection intent intent.setComponent(new ComponentName("com.android.phone", "com.android.phone.NetworkSetting")); PendingIntent pi = PendingIntent.getActivity(mContext, 0, intent, 0); notification.setLatestEventInfo(mContext, titleText, expandedText, pi); mNotificationManager.notify(SELECTED_OPERATOR_FAIL_NOTIFICATION, notification); } /** * Turn off the network selection "no service" notification */ private void cancelNetworkSelection() { if (DBG) log("cancelNetworkSelection()..."); mNotificationManager.cancel(SELECTED_OPERATOR_FAIL_NOTIFICATION); } /** * Update notification about no service of user selected operator * * @param serviceState Phone service state */ void updateNetworkSelection(int serviceState) { if (TelephonyCapabilities.supportsNetworkSelection(mPhone)) { // get the shared preference of network_selection. // empty is auto mode, otherwise it is the operator alpha name // in case there is no operator name, check the operator numeric SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(mContext); String networkSelection = sp.getString(PhoneBase.NETWORK_SELECTION_NAME_KEY, ""); if (TextUtils.isEmpty(networkSelection)) { networkSelection = sp.getString(PhoneBase.NETWORK_SELECTION_KEY, ""); } if (DBG) log("updateNetworkSelection()..." + "state = " + serviceState + " new network " + networkSelection); if (serviceState == ServiceState.STATE_OUT_OF_SERVICE && !TextUtils.isEmpty(networkSelection)) { if (!mSelectedUnavailableNotify) { showNetworkSelection(networkSelection); mSelectedUnavailableNotify = true; } } else { if (mSelectedUnavailableNotify) { cancelNetworkSelection(); mSelectedUnavailableNotify = false; } } } } /* package */ void postTransientNotification(int notifyId, CharSequence msg) { if (mToast != null) { mToast.cancel(); } mToast = Toast.makeText(mContext, msg, Toast.LENGTH_LONG); mToast.show(); } private void log(String msg) { Log.d(LOG_TAG, msg); } }
true
true
private void updateInCallNotification(boolean allowFullScreenIntent) { int resId; if (DBG) log("updateInCallNotification(allowFullScreenIntent = " + allowFullScreenIntent + ")..."); // Never display the "ongoing call" notification on // non-voice-capable devices, even if the phone is actually // offhook (like during a non-interactive OTASP call.) if (!PhoneApp.sVoiceCapable) { if (DBG) log("- non-voice-capable device; suppressing notification."); return; } // If the phone is idle, completely clean up all call-related // notifications. if (mCM.getState() == Phone.State.IDLE) { cancelInCall(); cancelMute(); cancelSpeakerphone(); return; } final boolean hasRingingCall = mCM.hasActiveRingingCall(); final boolean hasActiveCall = mCM.hasActiveFgCall(); final boolean hasHoldingCall = mCM.hasActiveBgCall(); if (DBG) { log(" - hasRingingCall = " + hasRingingCall); log(" - hasActiveCall = " + hasActiveCall); log(" - hasHoldingCall = " + hasHoldingCall); } // Suppress the in-call notification if the InCallScreen is the // foreground activity, since it's already obvious that you're on a // call. (The status bar icon is needed only if you navigate *away* // from the in-call UI.) // // Note: we should not use isShowingCallScreen() here, since it will // return false when the screen turns off during user's on the InCallScreen, // which will cause a brief flicker of the icon in the status bar when // the screen turns back on (due to the prox sensor, for example) while // still on the InCallScreen. boolean suppressNotification = mApp.isShowingCallScreenForProximity(); // if (DBG) log("- suppressNotification: initial value: " + suppressNotification); // ...except for a couple of cases where we *never* suppress the // notification: // // - If there's an incoming ringing call: always show the // notification, since the in-call notification is what actually // launches the incoming call UI in the first place (see // notification.fullScreenIntent below.) This makes sure that we'll // correctly handle the case where a new incoming call comes in but // the InCallScreen is already in the foreground. if (hasRingingCall) suppressNotification = false; // - If "voice privacy" mode is active: always show the notification, // since that's the only "voice privacy" indication we have. boolean enhancedVoicePrivacy = mApp.notifier.getVoicePrivacyState(); // if (DBG) log("updateInCallNotification: enhancedVoicePrivacy = " + enhancedVoicePrivacy); if (enhancedVoicePrivacy) suppressNotification = false; if (suppressNotification) { if (DBG) log("- suppressNotification = true; reducing clutter in status bar..."); cancelInCall(); // Suppress the mute and speaker status bar icons too // (also to reduce clutter in the status bar.) cancelSpeakerphone(); cancelMute(); return; } // Display the appropriate icon in the status bar, // based on the current phone and/or bluetooth state. if (hasRingingCall) { // There's an incoming ringing call. resId = R.drawable.stat_sys_phone_call; } else if (!hasActiveCall && hasHoldingCall) { // There's only one call, and it's on hold. if (enhancedVoicePrivacy) { resId = R.drawable.stat_sys_vp_phone_call_on_hold; } else { resId = R.drawable.stat_sys_phone_call_on_hold; } } else { if (enhancedVoicePrivacy) { resId = R.drawable.stat_sys_vp_phone_call; } else { resId = R.drawable.stat_sys_phone_call; } } // Note we can't just bail out now if (resId == mInCallResId), // since even if the status icon hasn't changed, some *other* // notification-related info may be different from the last time // we were here (like the caller-id info of the foreground call, // if the user swapped calls...) if (DBG) log("- Updating status bar icon: resId = " + resId); mInCallResId = resId; // Even if both lines are in use, we only show a single item in // the expanded Notifications UI. It's labeled "Ongoing call" // (or "On hold" if there's only one call, and it's on hold.) // Also, we don't have room to display caller-id info from two // different calls. So if both lines are in use, display info // from the foreground call. And if there's a ringing call, // display that regardless of the state of the other calls. Call currentCall; if (hasRingingCall) { currentCall = mCM.getFirstActiveRingingCall(); } else if (hasActiveCall) { currentCall = mCM.getActiveFgCall(); } else { currentCall = mCM.getFirstActiveBgCall(); } Connection currentConn = currentCall.getEarliestConnection(); final Notification.Builder builder = new Notification.Builder(mContext); builder.setSmallIcon(mInCallResId).setOngoing(true); // PendingIntent that can be used to launch the InCallScreen. The // system fires off this intent if the user pulls down the windowshade // and clicks the notification's expanded view. It's also used to // launch the InCallScreen immediately when when there's an incoming // call (see the "fullScreenIntent" field below). PendingIntent inCallPendingIntent = PendingIntent.getActivity(mContext, 0, PhoneApp.createInCallIntent(), 0); builder.setContentIntent(inCallPendingIntent); // Update icon on the left of the notification. // - If it is directly available from CallerInfo, we'll just use that. // - If it is not, use the same icon as in the status bar. CallerInfo callerInfo = null; if (currentConn != null) { Object o = currentConn.getUserData(); if (o instanceof CallerInfo) { callerInfo = (CallerInfo) o; } else if (o instanceof PhoneUtils.CallerInfoToken) { callerInfo = ((PhoneUtils.CallerInfoToken) o).currentInfo; } else { Log.w(LOG_TAG, "CallerInfo isn't available while Call object is available."); } } boolean largeIconWasSet = false; if (callerInfo != null) { // In most cases, the user will see the notification after CallerInfo is already // available, so photo will be available from this block. if (callerInfo.isCachedPhotoCurrent) { // .. and in that case CallerInfo's cachedPhotoIcon should also be available. // If it happens not, then try using cachedPhoto, assuming Drawable coming from // ContactProvider will be BitmapDrawable. if (callerInfo.cachedPhotoIcon != null) { builder.setLargeIcon(callerInfo.cachedPhotoIcon); largeIconWasSet = true; } else if (callerInfo.cachedPhoto instanceof BitmapDrawable) { if (DBG) log("- BitmapDrawable found for large icon"); Bitmap bitmap = ((BitmapDrawable) callerInfo.cachedPhoto).getBitmap(); builder.setLargeIcon(bitmap); largeIconWasSet = true; } else { if (DBG) { log("- Failed to fetch icon from CallerInfo's cached photo." + " (cachedPhotoIcon: " + callerInfo.cachedPhotoIcon + ", cachedPhoto: " + callerInfo.cachedPhoto + ")." + " Ignore it."); } } } if (!largeIconWasSet && callerInfo.photoResource > 0) { if (DBG) { log("- BitmapDrawable nor person Id not found for large icon." + " Use photoResource: " + callerInfo.photoResource); } Drawable drawable = mContext.getResources().getDrawable(callerInfo.photoResource); if (drawable instanceof BitmapDrawable) { Bitmap bitmap = ((BitmapDrawable) callerInfo.cachedPhoto).getBitmap(); builder.setLargeIcon(bitmap); largeIconWasSet = true; } else { if (DBG) { log("- PhotoResource was found but it didn't return BitmapDrawable." + " Ignore it"); } } } } else { if (DBG) log("- CallerInfo not found. Use the same icon as in the status bar."); } // Failed to fetch Bitmap. if (!largeIconWasSet && DBG) { log("- No useful Bitmap was found for the photo." + " Use the same icon as in the status bar."); } // If the connection is valid, then build what we need for the // content text of notification, and start the chronometer. // Otherwise, don't bother and just stick with content title. if (currentConn != null) { if (DBG) log("- Updating context text and chronometer."); if (hasRingingCall) { // Incoming call is ringing. builder.setContentText(mContext.getString(R.string.notification_incoming_call)); builder.setUsesChronometer(false); } else if (hasHoldingCall && !hasActiveCall) { // Only one call, and it's on hold. builder.setContentText(mContext.getString(R.string.notification_on_hold)); builder.setUsesChronometer(false); } else { // We show the elapsed time of the current call using Chronometer. builder.setUsesChronometer(true); // Determine the "start time" of the current connection. // We can't use currentConn.getConnectTime(), because (1) that's // in the currentTimeMillis() time base, and (2) it's zero when // the phone first goes off hook, since the getConnectTime counter // doesn't start until the DIALING -> ACTIVE transition. // Instead we start with the current connection's duration, // and translate that into the elapsedRealtime() timebase. long callDurationMsec = currentConn.getDurationMillis(); builder.setWhen(System.currentTimeMillis() - callDurationMsec); builder.setContentText(mContext.getString(R.string.notification_ongoing_call)); } } else if (DBG) { Log.w(LOG_TAG, "updateInCallNotification: null connection, can't set exp view line 1."); } // display conference call string if this call is a conference // call, otherwise display the connection information. // Line 2 of the expanded view (smaller text). This is usually a // contact name or phone number. String expandedViewLine2 = ""; // TODO: it may not make sense for every point to make separate // checks for isConferenceCall, so we need to think about // possibly including this in startGetCallerInfo or some other // common point. if (PhoneUtils.isConferenceCall(currentCall)) { // if this is a conference call, just use that as the caller name. expandedViewLine2 = mContext.getString(R.string.card_title_conf_call); } else { // If necessary, start asynchronous query to do the caller-id lookup. PhoneUtils.CallerInfoToken cit = PhoneUtils.startGetCallerInfo(mContext, currentCall, this, this); expandedViewLine2 = PhoneUtils.getCompactNameFromCallerInfo(cit.currentInfo, mContext); // Note: For an incoming call, the very first time we get here we // won't have a contact name yet, since we only just started the // caller-id query. So expandedViewLine2 will start off as a raw // phone number, but we'll update it very quickly when the query // completes (see onQueryComplete() below.) } if (DBG) log("- Updating expanded view: line 2 '" + /*expandedViewLine2*/ "xxxxxxx" + "'"); builder.setContentTitle(expandedViewLine2); // TODO: We also need to *update* this notification in some cases, // like when a call ends on one line but the other is still in use // (ie. make sure the caller info here corresponds to the active // line), and maybe even when the user swaps calls (ie. if we only // show info here for the "current active call".) // Activate a couple of special Notification features if an // incoming call is ringing: if (hasRingingCall) { if (DBG) log("- Using hi-pri notification for ringing call!"); // This is a high-priority event that should be shown even if the // status bar is hidden or if an immersive activity is running. builder.setPriority(Notification.PRIORITY_HIGH); // If an immersive activity is running, we have room for a single // line of text in the small notification popup window. // We use expandedViewLine2 for this (i.e. the name or number of // the incoming caller), since that's more relevant than // expandedViewLine1 (which is something generic like "Incoming // call".) builder.setTicker(expandedViewLine2); if (allowFullScreenIntent) { // Ok, we actually want to launch the incoming call // UI at this point (in addition to simply posting a notification // to the status bar). Setting fullScreenIntent will cause // the InCallScreen to be launched immediately *unless* the // current foreground activity is marked as "immersive". if (DBG) log("- Setting fullScreenIntent: " + inCallPendingIntent); builder.setFullScreenIntent(inCallPendingIntent, true); // Ugly hack alert: // // The NotificationManager has the (undocumented) behavior // that it will *ignore* the fullScreenIntent field if you // post a new Notification that matches the ID of one that's // already active. Unfortunately this is exactly what happens // when you get an incoming call-waiting call: the // "ongoing call" notification is already visible, so the // InCallScreen won't get launched in this case! // (The result: if you bail out of the in-call UI while on a // call and then get a call-waiting call, the incoming call UI // won't come up automatically.) // // The workaround is to just notice this exact case (this is a // call-waiting call *and* the InCallScreen is not in the // foreground) and manually cancel the in-call notification // before (re)posting it. // // TODO: there should be a cleaner way of avoiding this // problem (see discussion in bug 3184149.) Call ringingCall = mCM.getFirstActiveRingingCall(); if ((ringingCall.getState() == Call.State.WAITING) && !mApp.isShowingCallScreen()) { Log.i(LOG_TAG, "updateInCallNotification: call-waiting! force relaunch..."); // Cancel the IN_CALL_NOTIFICATION immediately before // (re)posting it; this seems to force the // NotificationManager to launch the fullScreenIntent. mNotificationManager.cancel(IN_CALL_NOTIFICATION); } } } else { // not ringing call // TODO: use "if (DBG)" for this comment. log("Will show \"hang-up\" action in the ongoing active call Notification"); // TODO: use better asset. builder.addAction(R.drawable.ic_end_call, mContext.getText(R.string.notification_action_end_call), PhoneApp.createHangUpOngoingCallPendingIntent(mContext)); } Notification notification = builder.getNotification(); if (DBG) log("Notifying IN_CALL_NOTIFICATION: " + notification); mNotificationManager.notify(IN_CALL_NOTIFICATION, notification); // Finally, refresh the mute and speakerphone notifications (since // some phone state changes can indirectly affect the mute and/or // speaker state). updateSpeakerNotification(); updateMuteNotification(); }
private void updateInCallNotification(boolean allowFullScreenIntent) { int resId; if (DBG) log("updateInCallNotification(allowFullScreenIntent = " + allowFullScreenIntent + ")..."); // Never display the "ongoing call" notification on // non-voice-capable devices, even if the phone is actually // offhook (like during a non-interactive OTASP call.) if (!PhoneApp.sVoiceCapable) { if (DBG) log("- non-voice-capable device; suppressing notification."); return; } // If the phone is idle, completely clean up all call-related // notifications. if (mCM.getState() == Phone.State.IDLE) { cancelInCall(); cancelMute(); cancelSpeakerphone(); return; } final boolean hasRingingCall = mCM.hasActiveRingingCall(); final boolean hasActiveCall = mCM.hasActiveFgCall(); final boolean hasHoldingCall = mCM.hasActiveBgCall(); if (DBG) { log(" - hasRingingCall = " + hasRingingCall); log(" - hasActiveCall = " + hasActiveCall); log(" - hasHoldingCall = " + hasHoldingCall); } // Suppress the in-call notification if the InCallScreen is the // foreground activity, since it's already obvious that you're on a // call. (The status bar icon is needed only if you navigate *away* // from the in-call UI.) boolean suppressNotification = mApp.isShowingCallScreen(); // if (DBG) log("- suppressNotification: initial value: " + suppressNotification); // ...except for a couple of cases where we *never* suppress the // notification: // // - If there's an incoming ringing call: always show the // notification, since the in-call notification is what actually // launches the incoming call UI in the first place (see // notification.fullScreenIntent below.) This makes sure that we'll // correctly handle the case where a new incoming call comes in but // the InCallScreen is already in the foreground. if (hasRingingCall) suppressNotification = false; // - If "voice privacy" mode is active: always show the notification, // since that's the only "voice privacy" indication we have. boolean enhancedVoicePrivacy = mApp.notifier.getVoicePrivacyState(); // if (DBG) log("updateInCallNotification: enhancedVoicePrivacy = " + enhancedVoicePrivacy); if (enhancedVoicePrivacy) suppressNotification = false; if (suppressNotification) { if (DBG) log("- suppressNotification = true; reducing clutter in status bar..."); cancelInCall(); // Suppress the mute and speaker status bar icons too // (also to reduce clutter in the status bar.) cancelSpeakerphone(); cancelMute(); return; } // Display the appropriate icon in the status bar, // based on the current phone and/or bluetooth state. if (hasRingingCall) { // There's an incoming ringing call. resId = R.drawable.stat_sys_phone_call; } else if (!hasActiveCall && hasHoldingCall) { // There's only one call, and it's on hold. if (enhancedVoicePrivacy) { resId = R.drawable.stat_sys_vp_phone_call_on_hold; } else { resId = R.drawable.stat_sys_phone_call_on_hold; } } else { if (enhancedVoicePrivacy) { resId = R.drawable.stat_sys_vp_phone_call; } else { resId = R.drawable.stat_sys_phone_call; } } // Note we can't just bail out now if (resId == mInCallResId), // since even if the status icon hasn't changed, some *other* // notification-related info may be different from the last time // we were here (like the caller-id info of the foreground call, // if the user swapped calls...) if (DBG) log("- Updating status bar icon: resId = " + resId); mInCallResId = resId; // Even if both lines are in use, we only show a single item in // the expanded Notifications UI. It's labeled "Ongoing call" // (or "On hold" if there's only one call, and it's on hold.) // Also, we don't have room to display caller-id info from two // different calls. So if both lines are in use, display info // from the foreground call. And if there's a ringing call, // display that regardless of the state of the other calls. Call currentCall; if (hasRingingCall) { currentCall = mCM.getFirstActiveRingingCall(); } else if (hasActiveCall) { currentCall = mCM.getActiveFgCall(); } else { currentCall = mCM.getFirstActiveBgCall(); } Connection currentConn = currentCall.getEarliestConnection(); final Notification.Builder builder = new Notification.Builder(mContext); builder.setSmallIcon(mInCallResId).setOngoing(true); // PendingIntent that can be used to launch the InCallScreen. The // system fires off this intent if the user pulls down the windowshade // and clicks the notification's expanded view. It's also used to // launch the InCallScreen immediately when when there's an incoming // call (see the "fullScreenIntent" field below). PendingIntent inCallPendingIntent = PendingIntent.getActivity(mContext, 0, PhoneApp.createInCallIntent(), 0); builder.setContentIntent(inCallPendingIntent); // Update icon on the left of the notification. // - If it is directly available from CallerInfo, we'll just use that. // - If it is not, use the same icon as in the status bar. CallerInfo callerInfo = null; if (currentConn != null) { Object o = currentConn.getUserData(); if (o instanceof CallerInfo) { callerInfo = (CallerInfo) o; } else if (o instanceof PhoneUtils.CallerInfoToken) { callerInfo = ((PhoneUtils.CallerInfoToken) o).currentInfo; } else { Log.w(LOG_TAG, "CallerInfo isn't available while Call object is available."); } } boolean largeIconWasSet = false; if (callerInfo != null) { // In most cases, the user will see the notification after CallerInfo is already // available, so photo will be available from this block. if (callerInfo.isCachedPhotoCurrent) { // .. and in that case CallerInfo's cachedPhotoIcon should also be available. // If it happens not, then try using cachedPhoto, assuming Drawable coming from // ContactProvider will be BitmapDrawable. if (callerInfo.cachedPhotoIcon != null) { builder.setLargeIcon(callerInfo.cachedPhotoIcon); largeIconWasSet = true; } else if (callerInfo.cachedPhoto instanceof BitmapDrawable) { if (DBG) log("- BitmapDrawable found for large icon"); Bitmap bitmap = ((BitmapDrawable) callerInfo.cachedPhoto).getBitmap(); builder.setLargeIcon(bitmap); largeIconWasSet = true; } else { if (DBG) { log("- Failed to fetch icon from CallerInfo's cached photo." + " (cachedPhotoIcon: " + callerInfo.cachedPhotoIcon + ", cachedPhoto: " + callerInfo.cachedPhoto + ")." + " Ignore it."); } } } if (!largeIconWasSet && callerInfo.photoResource > 0) { if (DBG) { log("- BitmapDrawable nor person Id not found for large icon." + " Use photoResource: " + callerInfo.photoResource); } Drawable drawable = mContext.getResources().getDrawable(callerInfo.photoResource); if (drawable instanceof BitmapDrawable) { Bitmap bitmap = ((BitmapDrawable) callerInfo.cachedPhoto).getBitmap(); builder.setLargeIcon(bitmap); largeIconWasSet = true; } else { if (DBG) { log("- PhotoResource was found but it didn't return BitmapDrawable." + " Ignore it"); } } } } else { if (DBG) log("- CallerInfo not found. Use the same icon as in the status bar."); } // Failed to fetch Bitmap. if (!largeIconWasSet && DBG) { log("- No useful Bitmap was found for the photo." + " Use the same icon as in the status bar."); } // If the connection is valid, then build what we need for the // content text of notification, and start the chronometer. // Otherwise, don't bother and just stick with content title. if (currentConn != null) { if (DBG) log("- Updating context text and chronometer."); if (hasRingingCall) { // Incoming call is ringing. builder.setContentText(mContext.getString(R.string.notification_incoming_call)); builder.setUsesChronometer(false); } else if (hasHoldingCall && !hasActiveCall) { // Only one call, and it's on hold. builder.setContentText(mContext.getString(R.string.notification_on_hold)); builder.setUsesChronometer(false); } else { // We show the elapsed time of the current call using Chronometer. builder.setUsesChronometer(true); // Determine the "start time" of the current connection. // We can't use currentConn.getConnectTime(), because (1) that's // in the currentTimeMillis() time base, and (2) it's zero when // the phone first goes off hook, since the getConnectTime counter // doesn't start until the DIALING -> ACTIVE transition. // Instead we start with the current connection's duration, // and translate that into the elapsedRealtime() timebase. long callDurationMsec = currentConn.getDurationMillis(); builder.setWhen(System.currentTimeMillis() - callDurationMsec); builder.setContentText(mContext.getString(R.string.notification_ongoing_call)); } } else if (DBG) { Log.w(LOG_TAG, "updateInCallNotification: null connection, can't set exp view line 1."); } // display conference call string if this call is a conference // call, otherwise display the connection information. // Line 2 of the expanded view (smaller text). This is usually a // contact name or phone number. String expandedViewLine2 = ""; // TODO: it may not make sense for every point to make separate // checks for isConferenceCall, so we need to think about // possibly including this in startGetCallerInfo or some other // common point. if (PhoneUtils.isConferenceCall(currentCall)) { // if this is a conference call, just use that as the caller name. expandedViewLine2 = mContext.getString(R.string.card_title_conf_call); } else { // If necessary, start asynchronous query to do the caller-id lookup. PhoneUtils.CallerInfoToken cit = PhoneUtils.startGetCallerInfo(mContext, currentCall, this, this); expandedViewLine2 = PhoneUtils.getCompactNameFromCallerInfo(cit.currentInfo, mContext); // Note: For an incoming call, the very first time we get here we // won't have a contact name yet, since we only just started the // caller-id query. So expandedViewLine2 will start off as a raw // phone number, but we'll update it very quickly when the query // completes (see onQueryComplete() below.) } if (DBG) log("- Updating expanded view: line 2 '" + /*expandedViewLine2*/ "xxxxxxx" + "'"); builder.setContentTitle(expandedViewLine2); // TODO: We also need to *update* this notification in some cases, // like when a call ends on one line but the other is still in use // (ie. make sure the caller info here corresponds to the active // line), and maybe even when the user swaps calls (ie. if we only // show info here for the "current active call".) // Activate a couple of special Notification features if an // incoming call is ringing: if (hasRingingCall) { if (DBG) log("- Using hi-pri notification for ringing call!"); // This is a high-priority event that should be shown even if the // status bar is hidden or if an immersive activity is running. builder.setPriority(Notification.PRIORITY_HIGH); // If an immersive activity is running, we have room for a single // line of text in the small notification popup window. // We use expandedViewLine2 for this (i.e. the name or number of // the incoming caller), since that's more relevant than // expandedViewLine1 (which is something generic like "Incoming // call".) builder.setTicker(expandedViewLine2); if (allowFullScreenIntent) { // Ok, we actually want to launch the incoming call // UI at this point (in addition to simply posting a notification // to the status bar). Setting fullScreenIntent will cause // the InCallScreen to be launched immediately *unless* the // current foreground activity is marked as "immersive". if (DBG) log("- Setting fullScreenIntent: " + inCallPendingIntent); builder.setFullScreenIntent(inCallPendingIntent, true); // Ugly hack alert: // // The NotificationManager has the (undocumented) behavior // that it will *ignore* the fullScreenIntent field if you // post a new Notification that matches the ID of one that's // already active. Unfortunately this is exactly what happens // when you get an incoming call-waiting call: the // "ongoing call" notification is already visible, so the // InCallScreen won't get launched in this case! // (The result: if you bail out of the in-call UI while on a // call and then get a call-waiting call, the incoming call UI // won't come up automatically.) // // The workaround is to just notice this exact case (this is a // call-waiting call *and* the InCallScreen is not in the // foreground) and manually cancel the in-call notification // before (re)posting it. // // TODO: there should be a cleaner way of avoiding this // problem (see discussion in bug 3184149.) Call ringingCall = mCM.getFirstActiveRingingCall(); if ((ringingCall.getState() == Call.State.WAITING) && !mApp.isShowingCallScreen()) { Log.i(LOG_TAG, "updateInCallNotification: call-waiting! force relaunch..."); // Cancel the IN_CALL_NOTIFICATION immediately before // (re)posting it; this seems to force the // NotificationManager to launch the fullScreenIntent. mNotificationManager.cancel(IN_CALL_NOTIFICATION); } } } else { // not ringing call // TODO: use "if (DBG)" for this comment. log("Will show \"hang-up\" action in the ongoing active call Notification"); // TODO: use better asset. builder.addAction(R.drawable.ic_end_call, mContext.getText(R.string.notification_action_end_call), PhoneApp.createHangUpOngoingCallPendingIntent(mContext)); } Notification notification = builder.getNotification(); if (DBG) log("Notifying IN_CALL_NOTIFICATION: " + notification); mNotificationManager.notify(IN_CALL_NOTIFICATION, notification); // Finally, refresh the mute and speakerphone notifications (since // some phone state changes can indirectly affect the mute and/or // speaker state). updateSpeakerNotification(); updateMuteNotification(); }
diff --git a/src/com/settlers/TextureManager.java b/src/com/settlers/TextureManager.java index 223074f..25ad420 100644 --- a/src/com/settlers/TextureManager.java +++ b/src/com/settlers/TextureManager.java @@ -1,387 +1,389 @@ package com.settlers; import java.util.Hashtable; import javax.microedition.khronos.opengles.GL10; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.graphics.Paint; import android.graphics.BitmapFactory.Options; import android.opengl.GLUtils; public class TextureManager { private enum Type { NONE, BACKGROUND, SHORE, TILE, LIGHT, TRADER, RESOURCE, ROBBER, ROLL, ROAD, TOWN, CITY, ORNAMENT, BUTTONBG, BUTTON } public enum Location { BOTTOM_LEFT, TOP_LEFT, TOP_RIGHT, BOTTOM_RIGHT } public enum Background { NONE, WAVES, WAVES_HORIZONTAL } private Hashtable<Integer, Bitmap> bitmap; private Hashtable<Integer, Integer> resource; private Hashtable<Integer, Square> square; private static int hash(Type type, int variant) { return variant << 6 | type.ordinal(); } private Bitmap get(Type type, int variant) { return bitmap.get(hash(type, variant)); } private void add(Type type, int variant, int id, Resources res) { int key = hash(type, variant); Bitmap bitmap = BitmapFactory.decodeResource(res, id, new Options()); this.bitmap.put(key, bitmap); this.resource.put(key, id); this.square.put(key, new Square(id, 0, 0, type.ordinal(), (float) bitmap.getWidth() / (float) Geometry.TILE_SIZE, (float) bitmap.getHeight() / (float) Geometry.TILE_SIZE)); } public TextureManager(Resources res) { // initialize hash table bitmap = new Hashtable<Integer, Bitmap>(); resource = new Hashtable<Integer, Integer>(); square = new Hashtable<Integer, Square>(); // load large tile textures add(Type.SHORE, 0, R.drawable.tile_shore, res); add(Type.TILE, Hexagon.Type.DESERT.ordinal(), R.drawable.tile_desert, res); add(Type.TILE, Hexagon.Type.WOOL.ordinal(), R.drawable.tile_wool, res); add(Type.TILE, Hexagon.Type.GRAIN.ordinal(), R.drawable.tile_grain, res); add(Type.TILE, Hexagon.Type.LUMBER.ordinal(), R.drawable.tile_lumber, res); add(Type.TILE, Hexagon.Type.BRICK.ordinal(), R.drawable.tile_brick, res); add(Type.TILE, Hexagon.Type.ORE.ordinal(), R.drawable.tile_ore, res); add(Type.TILE, Hexagon.Type.DIM.ordinal(), R.drawable.tile_dim, res); add(Type.LIGHT, 0, R.drawable.tile_light, res); // load roll number textures add(Type.ROLL, 2, R.drawable.roll_2, res); add(Type.ROLL, 3, R.drawable.roll_3, res); add(Type.ROLL, 4, R.drawable.roll_4, res); add(Type.ROLL, 5, R.drawable.roll_5, res); add(Type.ROLL, 6, R.drawable.roll_6, res); add(Type.ROLL, 8, R.drawable.roll_8, res); add(Type.ROLL, 9, R.drawable.roll_9, res); add(Type.ROLL, 10, R.drawable.roll_10, res); add(Type.ROLL, 11, R.drawable.roll_11, res); add(Type.ROLL, 12, R.drawable.roll_12, res); // load robber textures add(Type.ROBBER, 0, R.drawable.tile_robber, res); // load button textures add(Type.BUTTONBG, UIButton.Background.BACKDROP.ordinal(), R.drawable.button_backdrop, res); add(Type.BUTTONBG, UIButton.Background.PRESSED.ordinal(), R.drawable.button_press, res); add(Type.BUTTON, UIButton.Type.INFO.ordinal(), R.drawable.button_status, res); add(Type.BUTTON, UIButton.Type.ROLL.ordinal(), R.drawable.button_roll, res); add(Type.BUTTON, UIButton.Type.ROAD.ordinal(), R.drawable.button_road, res); add(Type.BUTTON, UIButton.Type.TOWN.ordinal(), R.drawable.button_settlement, res); add(Type.BUTTON, UIButton.Type.CITY.ordinal(), R.drawable.button_city, res); add(Type.BUTTON, UIButton.Type.DEVCARD.ordinal(), R.drawable.button_development, res); add(Type.BUTTON, UIButton.Type.TRADE.ordinal(), R.drawable.button_trade, res); add(Type.BUTTON, UIButton.Type.ENDTURN.ordinal(), R.drawable.button_endturn, res); add(Type.BUTTON, UIButton.Type.CANCEL.ordinal(), R.drawable.button_cancel, res); // load large town textures add(Type.TOWN, Player.Color.SELECT.ordinal(), R.drawable.settlement_purple, res); add(Type.TOWN, Player.Color.RED.ordinal(), R.drawable.settlement_red, res); add(Type.TOWN, Player.Color.BLUE.ordinal(), + R.drawable.settlement_blue, res); + add(Type.TOWN, Player.Color.GREEN.ordinal(), R.drawable.settlement_green, res); add(Type.TOWN, Player.Color.ORANGE.ordinal(), R.drawable.settlement_orange, res); // load large city textures add(Type.CITY, Player.Color.SELECT.ordinal(), R.drawable.city_purple, res); add(Type.CITY, Player.Color.RED.ordinal(), R.drawable.city_red, res); add(Type.CITY, Player.Color.BLUE.ordinal(), R.drawable.city_blue, res); add(Type.CITY, Player.Color.GREEN.ordinal(), R.drawable.city_green, res); add(Type.CITY, Player.Color.ORANGE.ordinal(), R.drawable.city_orange, res); // load large resource icons add(Type.RESOURCE, Hexagon.Type.LUMBER.ordinal(), R.drawable.res_lumber, res); add(Type.RESOURCE, Hexagon.Type.WOOL.ordinal(), R.drawable.res_wool, res); add(Type.RESOURCE, Hexagon.Type.GRAIN.ordinal(), R.drawable.res_grain, res); add(Type.RESOURCE, Hexagon.Type.BRICK.ordinal(), R.drawable.res_brick, res); add(Type.RESOURCE, Hexagon.Type.ORE.ordinal(), R.drawable.res_ore, res); add(Type.RESOURCE, Hexagon.Type.ANY.ordinal(), R.drawable.trader_any, res); // load large trader textures add(Type.TRADER, Trader.Position.NORTH.ordinal(), R.drawable.trader_north, res); add(Type.TRADER, Trader.Position.SOUTH.ordinal(), R.drawable.trader_south, res); add(Type.TRADER, Trader.Position.NORTHEAST.ordinal(), R.drawable.trader_northeast, res); add(Type.TRADER, Trader.Position.NORTHWEST.ordinal(), R.drawable.trader_northwest, res); add(Type.TRADER, Trader.Position.SOUTHEAST.ordinal(), R.drawable.trader_southeast, res); add(Type.TRADER, Trader.Position.SOUTHWEST.ordinal(), R.drawable.trader_southwest, res); // load corner ornaments add(Type.ORNAMENT, Location.BOTTOM_LEFT.ordinal(), R.drawable.bl_corner, res); add(Type.ORNAMENT, Location.TOP_LEFT.ordinal(), R.drawable.tl_corner, res); add(Type.ORNAMENT, Location.TOP_RIGHT.ordinal(), R.drawable.tr_corner, res); } // private static void shorten(int[] points, double factor) { // int center = (points[0] + points[1]) / 2; // points[0] = (int) (center - factor * (center - points[0])); // points[1] = (int) (center - factor * (center - points[1])); // } public static int getColor(Player.Color color) { switch (color) { case RED: return Color.rgb(0xBE, 0x28, 0x20); case BLUE: return Color.rgb(0x37, 0x57, 0xB3); case GREEN: return Color.rgb(0x13, 0xA6, 0x19); case ORANGE: return Color.rgb(0xE9, 0xD3, 0x03); default: return Color.rgb(0x87, 0x87, 0x87); } } public static int darken(int color, double factor) { return Color.argb(Color.alpha(color), (int) (Color.red(color) * factor), (int) (Color.green(color) * factor), (int) (Color.blue(color) * factor)); } public static void setPaintColor(Paint paint, Player.Color color) { paint.setColor(getColor(color)); } // public void draw(Background background, Canvas canvas, Geometry geometry) // { // if (background == Background.NONE) { // canvas.drawColor(Color.BLACK); // return; // } // // Bitmap bitmap = get(Type.BACKGROUND, hash(background)); // int xsize = bitmap.getWidth(); // int ysize = bitmap.getHeight(); // // int width = geometry.getWidth(); // int height = geometry.getHeight(); // // for (int y = 0; y < height; y += ysize) { // for (int x = 0; x < width; x += xsize) // canvas.drawBitmap(bitmap, x, y, null); // } // } // public void draw(UIButton button, Player.Color player, Canvas canvas) { // Bitmap background = get(Type.BUTTONBG, // hash(UIButton.Background.BACKDROP)); // Bitmap pressed = get(Type.BUTTONBG, hash(UIButton.Background.PRESSED)); // // button.draw(canvas, background, pressed); // } public void draw(Location location, int x, int y, GL10 gl) { Bitmap image = get(Type.ORNAMENT, location.ordinal()); int dx = x; int dy = y; if (location == Location.BOTTOM_RIGHT || location == Location.TOP_RIGHT) dx -= image.getWidth() / 2; if (location == Location.BOTTOM_LEFT || location == Location.BOTTOM_RIGHT) dy -= image.getHeight() / 2; gl.glPushMatrix(); gl.glTranslatef(dx, dy, 0); square.get(location.ordinal()).render(gl); gl.glPopMatrix(); } public void draw(Hexagon hexagon, GL10 gl, Geometry geometry, int lastRoll) { gl.glPushMatrix(); int id = hexagon.getId(); gl.glTranslatef(geometry.getHexagonX(id), geometry.getHexagonY(id), 0); square.get(hash(Type.SHORE, 0)).render(gl); square.get(hash(Type.TILE, hexagon.getType().ordinal())).render(gl); int roll = hexagon.getRoll(); if (hexagon.hasRobber()) square.get(hash(Type.ROBBER, 0)).render(gl); else if (lastRoll != 0 && roll == lastRoll) square.get(hash(Type.LIGHT, 0)).render(gl); if (roll != 0 && roll != 7) square.get(hash(Type.ROLL, roll)).render(gl); gl.glPopMatrix(); } public void draw(Trader trader, GL10 gl, Geometry geometry) { int id = trader.getIndex(); // draw shore access notches gl.glPushMatrix(); gl.glTranslatef(geometry.getTraderX(id), geometry.getTraderY(id), 0); square.get(hash(Type.TRADER, trader.getPosition().ordinal())) .render(gl); gl.glPopMatrix(); // draw type icon gl.glPushMatrix(); gl.glTranslatef((float) geometry.getTraderIconOffsetX(id), (float) geometry.getTraderIconOffsetY(id), 0); square.get(hash(Type.RESOURCE, trader.getType().ordinal())).render(gl); gl.glPopMatrix(); } // public void draw(Edge edge, boolean build, Canvas canvas, Geometry // geometry) { // int[] x = new int[2]; // int[] y = new int[2]; // x[0] = geometry.getVertexX(edge.getVertex1().getIndex()); // x[1] = geometry.getVertexX(edge.getVertex2().getIndex()); // y[0] = geometry.getVertexY(edge.getVertex1().getIndex()); // y[1] = geometry.getVertexY(edge.getVertex2().getIndex()); // // shorten(x, 0.55); // shorten(y, 0.55); // // Paint paint = new Paint(); // Player owner = edge.getOwner(); // // paint.setAntiAlias(true); // paint.setStrokeCap(Paint.Cap.SQUARE); // // // draw black backdrop // if (owner != null || build) { // paint.setARGB(255, 0, 0, 0); // paint.setStrokeWidth((int) (geometry.getUnitSize() // * geometry.getZoom() / 7)); // canvas.drawLine(x[0], y[0], x[1], y[1], paint); // } // // // set size // paint.setStrokeWidth((int) (geometry.getUnitSize() * geometry.getZoom() / // 12)); // shorten(x, 0.95); // shorten(y, 0.95); // // // set the color // if (owner != null) // setPaintColor(paint, owner.getColor()); // else // setPaintColor(paint, Player.Color.SELECT); // // // draw road // if (owner != null || build) // canvas.drawLine(x[0], y[0], x[1], y[1], paint); // // // // debug label // // paint.setColor(Color.WHITE); // // paint.setTextSize(20); // // canvas.drawText("E" + edge.getIndex(), (x[0] + x[1]) / 2, (y[0] + // // y[1]) / 2, paint); // } public void draw(Vertex vertex, boolean buildTown, boolean buildCity, GL10 gl, Geometry geometry) { Type type = Type.NONE; if (vertex.getBuilding() == Vertex.CITY || buildCity) type = Type.CITY; else if (vertex.getBuilding() == Vertex.TOWN || buildTown) type = Type.TOWN; Player.Color color; Player owner = vertex.getOwner(); if (buildTown || buildCity) color = Player.Color.SELECT; else if (owner != null) color = owner.getColor(); else color = Player.Color.NONE; Square object = square.get(hash(type, color.ordinal())); if (object != null) { gl.glPushMatrix(); int id = vertex.getIndex(); gl.glTranslatef(geometry.getVertexX(id), geometry.getVertexY(id), 0); object.render(gl); gl.glPopMatrix(); } } public Bitmap get(UIButton.Type type) { return get(Type.BUTTON, type.ordinal()); } public Bitmap get(Hexagon.Type type) { return get(Type.RESOURCE, type.ordinal()); } public void initGL(GL10 gl) { for (Integer key : bitmap.keySet()) { gl.glBindTexture(GL10.GL_TEXTURE_2D, resource.get(key)); gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR); gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR); gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_REPEAT); gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_REPEAT); gl.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE, GL10.GL_MODULATE); GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap.get(key), 0); } } }
true
true
public TextureManager(Resources res) { // initialize hash table bitmap = new Hashtable<Integer, Bitmap>(); resource = new Hashtable<Integer, Integer>(); square = new Hashtable<Integer, Square>(); // load large tile textures add(Type.SHORE, 0, R.drawable.tile_shore, res); add(Type.TILE, Hexagon.Type.DESERT.ordinal(), R.drawable.tile_desert, res); add(Type.TILE, Hexagon.Type.WOOL.ordinal(), R.drawable.tile_wool, res); add(Type.TILE, Hexagon.Type.GRAIN.ordinal(), R.drawable.tile_grain, res); add(Type.TILE, Hexagon.Type.LUMBER.ordinal(), R.drawable.tile_lumber, res); add(Type.TILE, Hexagon.Type.BRICK.ordinal(), R.drawable.tile_brick, res); add(Type.TILE, Hexagon.Type.ORE.ordinal(), R.drawable.tile_ore, res); add(Type.TILE, Hexagon.Type.DIM.ordinal(), R.drawable.tile_dim, res); add(Type.LIGHT, 0, R.drawable.tile_light, res); // load roll number textures add(Type.ROLL, 2, R.drawable.roll_2, res); add(Type.ROLL, 3, R.drawable.roll_3, res); add(Type.ROLL, 4, R.drawable.roll_4, res); add(Type.ROLL, 5, R.drawable.roll_5, res); add(Type.ROLL, 6, R.drawable.roll_6, res); add(Type.ROLL, 8, R.drawable.roll_8, res); add(Type.ROLL, 9, R.drawable.roll_9, res); add(Type.ROLL, 10, R.drawable.roll_10, res); add(Type.ROLL, 11, R.drawable.roll_11, res); add(Type.ROLL, 12, R.drawable.roll_12, res); // load robber textures add(Type.ROBBER, 0, R.drawable.tile_robber, res); // load button textures add(Type.BUTTONBG, UIButton.Background.BACKDROP.ordinal(), R.drawable.button_backdrop, res); add(Type.BUTTONBG, UIButton.Background.PRESSED.ordinal(), R.drawable.button_press, res); add(Type.BUTTON, UIButton.Type.INFO.ordinal(), R.drawable.button_status, res); add(Type.BUTTON, UIButton.Type.ROLL.ordinal(), R.drawable.button_roll, res); add(Type.BUTTON, UIButton.Type.ROAD.ordinal(), R.drawable.button_road, res); add(Type.BUTTON, UIButton.Type.TOWN.ordinal(), R.drawable.button_settlement, res); add(Type.BUTTON, UIButton.Type.CITY.ordinal(), R.drawable.button_city, res); add(Type.BUTTON, UIButton.Type.DEVCARD.ordinal(), R.drawable.button_development, res); add(Type.BUTTON, UIButton.Type.TRADE.ordinal(), R.drawable.button_trade, res); add(Type.BUTTON, UIButton.Type.ENDTURN.ordinal(), R.drawable.button_endturn, res); add(Type.BUTTON, UIButton.Type.CANCEL.ordinal(), R.drawable.button_cancel, res); // load large town textures add(Type.TOWN, Player.Color.SELECT.ordinal(), R.drawable.settlement_purple, res); add(Type.TOWN, Player.Color.RED.ordinal(), R.drawable.settlement_red, res); add(Type.TOWN, Player.Color.BLUE.ordinal(), R.drawable.settlement_green, res); add(Type.TOWN, Player.Color.ORANGE.ordinal(), R.drawable.settlement_orange, res); // load large city textures add(Type.CITY, Player.Color.SELECT.ordinal(), R.drawable.city_purple, res); add(Type.CITY, Player.Color.RED.ordinal(), R.drawable.city_red, res); add(Type.CITY, Player.Color.BLUE.ordinal(), R.drawable.city_blue, res); add(Type.CITY, Player.Color.GREEN.ordinal(), R.drawable.city_green, res); add(Type.CITY, Player.Color.ORANGE.ordinal(), R.drawable.city_orange, res); // load large resource icons add(Type.RESOURCE, Hexagon.Type.LUMBER.ordinal(), R.drawable.res_lumber, res); add(Type.RESOURCE, Hexagon.Type.WOOL.ordinal(), R.drawable.res_wool, res); add(Type.RESOURCE, Hexagon.Type.GRAIN.ordinal(), R.drawable.res_grain, res); add(Type.RESOURCE, Hexagon.Type.BRICK.ordinal(), R.drawable.res_brick, res); add(Type.RESOURCE, Hexagon.Type.ORE.ordinal(), R.drawable.res_ore, res); add(Type.RESOURCE, Hexagon.Type.ANY.ordinal(), R.drawable.trader_any, res); // load large trader textures add(Type.TRADER, Trader.Position.NORTH.ordinal(), R.drawable.trader_north, res); add(Type.TRADER, Trader.Position.SOUTH.ordinal(), R.drawable.trader_south, res); add(Type.TRADER, Trader.Position.NORTHEAST.ordinal(), R.drawable.trader_northeast, res); add(Type.TRADER, Trader.Position.NORTHWEST.ordinal(), R.drawable.trader_northwest, res); add(Type.TRADER, Trader.Position.SOUTHEAST.ordinal(), R.drawable.trader_southeast, res); add(Type.TRADER, Trader.Position.SOUTHWEST.ordinal(), R.drawable.trader_southwest, res); // load corner ornaments add(Type.ORNAMENT, Location.BOTTOM_LEFT.ordinal(), R.drawable.bl_corner, res); add(Type.ORNAMENT, Location.TOP_LEFT.ordinal(), R.drawable.tl_corner, res); add(Type.ORNAMENT, Location.TOP_RIGHT.ordinal(), R.drawable.tr_corner, res); }
public TextureManager(Resources res) { // initialize hash table bitmap = new Hashtable<Integer, Bitmap>(); resource = new Hashtable<Integer, Integer>(); square = new Hashtable<Integer, Square>(); // load large tile textures add(Type.SHORE, 0, R.drawable.tile_shore, res); add(Type.TILE, Hexagon.Type.DESERT.ordinal(), R.drawable.tile_desert, res); add(Type.TILE, Hexagon.Type.WOOL.ordinal(), R.drawable.tile_wool, res); add(Type.TILE, Hexagon.Type.GRAIN.ordinal(), R.drawable.tile_grain, res); add(Type.TILE, Hexagon.Type.LUMBER.ordinal(), R.drawable.tile_lumber, res); add(Type.TILE, Hexagon.Type.BRICK.ordinal(), R.drawable.tile_brick, res); add(Type.TILE, Hexagon.Type.ORE.ordinal(), R.drawable.tile_ore, res); add(Type.TILE, Hexagon.Type.DIM.ordinal(), R.drawable.tile_dim, res); add(Type.LIGHT, 0, R.drawable.tile_light, res); // load roll number textures add(Type.ROLL, 2, R.drawable.roll_2, res); add(Type.ROLL, 3, R.drawable.roll_3, res); add(Type.ROLL, 4, R.drawable.roll_4, res); add(Type.ROLL, 5, R.drawable.roll_5, res); add(Type.ROLL, 6, R.drawable.roll_6, res); add(Type.ROLL, 8, R.drawable.roll_8, res); add(Type.ROLL, 9, R.drawable.roll_9, res); add(Type.ROLL, 10, R.drawable.roll_10, res); add(Type.ROLL, 11, R.drawable.roll_11, res); add(Type.ROLL, 12, R.drawable.roll_12, res); // load robber textures add(Type.ROBBER, 0, R.drawable.tile_robber, res); // load button textures add(Type.BUTTONBG, UIButton.Background.BACKDROP.ordinal(), R.drawable.button_backdrop, res); add(Type.BUTTONBG, UIButton.Background.PRESSED.ordinal(), R.drawable.button_press, res); add(Type.BUTTON, UIButton.Type.INFO.ordinal(), R.drawable.button_status, res); add(Type.BUTTON, UIButton.Type.ROLL.ordinal(), R.drawable.button_roll, res); add(Type.BUTTON, UIButton.Type.ROAD.ordinal(), R.drawable.button_road, res); add(Type.BUTTON, UIButton.Type.TOWN.ordinal(), R.drawable.button_settlement, res); add(Type.BUTTON, UIButton.Type.CITY.ordinal(), R.drawable.button_city, res); add(Type.BUTTON, UIButton.Type.DEVCARD.ordinal(), R.drawable.button_development, res); add(Type.BUTTON, UIButton.Type.TRADE.ordinal(), R.drawable.button_trade, res); add(Type.BUTTON, UIButton.Type.ENDTURN.ordinal(), R.drawable.button_endturn, res); add(Type.BUTTON, UIButton.Type.CANCEL.ordinal(), R.drawable.button_cancel, res); // load large town textures add(Type.TOWN, Player.Color.SELECT.ordinal(), R.drawable.settlement_purple, res); add(Type.TOWN, Player.Color.RED.ordinal(), R.drawable.settlement_red, res); add(Type.TOWN, Player.Color.BLUE.ordinal(), R.drawable.settlement_blue, res); add(Type.TOWN, Player.Color.GREEN.ordinal(), R.drawable.settlement_green, res); add(Type.TOWN, Player.Color.ORANGE.ordinal(), R.drawable.settlement_orange, res); // load large city textures add(Type.CITY, Player.Color.SELECT.ordinal(), R.drawable.city_purple, res); add(Type.CITY, Player.Color.RED.ordinal(), R.drawable.city_red, res); add(Type.CITY, Player.Color.BLUE.ordinal(), R.drawable.city_blue, res); add(Type.CITY, Player.Color.GREEN.ordinal(), R.drawable.city_green, res); add(Type.CITY, Player.Color.ORANGE.ordinal(), R.drawable.city_orange, res); // load large resource icons add(Type.RESOURCE, Hexagon.Type.LUMBER.ordinal(), R.drawable.res_lumber, res); add(Type.RESOURCE, Hexagon.Type.WOOL.ordinal(), R.drawable.res_wool, res); add(Type.RESOURCE, Hexagon.Type.GRAIN.ordinal(), R.drawable.res_grain, res); add(Type.RESOURCE, Hexagon.Type.BRICK.ordinal(), R.drawable.res_brick, res); add(Type.RESOURCE, Hexagon.Type.ORE.ordinal(), R.drawable.res_ore, res); add(Type.RESOURCE, Hexagon.Type.ANY.ordinal(), R.drawable.trader_any, res); // load large trader textures add(Type.TRADER, Trader.Position.NORTH.ordinal(), R.drawable.trader_north, res); add(Type.TRADER, Trader.Position.SOUTH.ordinal(), R.drawable.trader_south, res); add(Type.TRADER, Trader.Position.NORTHEAST.ordinal(), R.drawable.trader_northeast, res); add(Type.TRADER, Trader.Position.NORTHWEST.ordinal(), R.drawable.trader_northwest, res); add(Type.TRADER, Trader.Position.SOUTHEAST.ordinal(), R.drawable.trader_southeast, res); add(Type.TRADER, Trader.Position.SOUTHWEST.ordinal(), R.drawable.trader_southwest, res); // load corner ornaments add(Type.ORNAMENT, Location.BOTTOM_LEFT.ordinal(), R.drawable.bl_corner, res); add(Type.ORNAMENT, Location.TOP_LEFT.ordinal(), R.drawable.tl_corner, res); add(Type.ORNAMENT, Location.TOP_RIGHT.ordinal(), R.drawable.tr_corner, res); }
diff --git a/src/main/java/org/youthnet/export/util/CSVUtil.java b/src/main/java/org/youthnet/export/util/CSVUtil.java index b880780..c78cd91 100644 --- a/src/main/java/org/youthnet/export/util/CSVUtil.java +++ b/src/main/java/org/youthnet/export/util/CSVUtil.java @@ -1,311 +1,311 @@ package org.youthnet.export.util; import org.youthnet.export.domain.CSVable; import org.youthnet.export.domain.vb25.ContainsOid; import org.youthnet.export.domain.vb25.ContainsOrgid; import org.youthnet.export.domain.vb25.ContainsVid; import org.youthnet.export.domain.vb3.ContainsDiscriminator; import org.youthnet.export.domain.vb3.ContainsValue; import org.youthnet.export.domain.vb3.ContainsVb2id; import org.youthnet.export.io.CSVFileReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * User: karl * Date: 06-Jul-2010 */ public class CSVUtil { private CSVUtil() { } public static <T extends CSVable> List<T> createDomainList(String filePath, Class<T> type) { List<T> domainObjects = null; CSVFileReader csvFileReader = null; try { csvFileReader = new CSVFileReader(new FileReader(filePath)); domainObjects = new ArrayList<T>(); String record = ""; T domainObject = null; while ((record = csvFileReader.readRecord()) != null) { try { domainObject = type.newInstance(); domainObject.init(record); domainObjects.add(domainObject); } catch (InstantiationException e) { System.out.println("Could not instantiate " + type.getName() + ". Error: " + e.getMessage()); break; } catch (IllegalAccessException e) { System.out.println("Could not access " + type.getName() + ". Error: " + e.getMessage()); break; } } } catch (IOException e) { System.out.println("File " + filePath + " not found. Error: " + e.getMessage()); } finally { if (csvFileReader != null) { try { csvFileReader.close(); } catch (IOException e) { System.out.println("Could not close file stream. Error: " + e.getMessage()); } } } return domainObjects; } public static <T extends ContainsVid & CSVable> Map<Long, List<T>> createVidMap(String filePath, Class<T> type) { Map<Long, List<T>> vidMap = null; CSVFileReader csvFileReader = null; try { csvFileReader = new CSVFileReader(new FileReader(filePath)); vidMap = new HashMap<Long, List<T>>(); String record = ""; T domainObject = null; while ((record = csvFileReader.readRecord()) != null) { try { domainObject = type.newInstance(); domainObject.init(record); if (vidMap.get(domainObject.getVid()) == null) vidMap.put(domainObject.getVid(), new ArrayList<T>()); vidMap.get(domainObject.getVid()).add(domainObject); } catch (InstantiationException e) { System.out.println("Could not instantiate " + type.getName() + ". Error: " + e.getMessage()); break; } catch (IllegalAccessException e) { System.out.println("Could not access " + type.getName() + ". Error: " + e.getMessage()); break; } } } catch (IOException e) { System.out.println("File " + filePath + " not found. Error: " + e.getMessage()); } finally { if (csvFileReader != null) { try { csvFileReader.close(); } catch (IOException e) { System.out.println("Could not close file stream. Error: " + e.getMessage()); } } } return vidMap; } public static <T extends ContainsOid & CSVable> Map<Long, List<T>> createOidMap(String filePath, Class<T> type) { Map<Long, List<T>> oidMap = null; CSVFileReader csvFileReader = null; try { csvFileReader = new CSVFileReader(new FileReader(filePath)); oidMap = new HashMap<Long, List<T>>(); String record = ""; T domainObject = null; while ((record = csvFileReader.readRecord()) != null) { try { domainObject = type.newInstance(); domainObject.init(record); if (oidMap.get(domainObject.getOid()) == null) oidMap.put(domainObject.getOid(), new ArrayList<T>()); oidMap.get(domainObject.getOid()).add(domainObject); } catch (InstantiationException e) { System.out.println("Could not instantiate " + type.getName() + ". Error: " + e.getMessage()); break; } catch (IllegalAccessException e) { System.out.println("Could not access " + type.getName() + ". Error: " + e.getMessage()); break; } } } catch (IOException e) { System.out.println("File " + filePath + " not found. Error: " + e.getMessage()); } finally { if (csvFileReader != null) { try { csvFileReader.close(); } catch (IOException e) { System.out.println("Could not close file stream. Error: " + e.getMessage()); } } } return oidMap; } public static <T extends ContainsOrgid & CSVable> Map<Long, List<T>> createOrgidMap(String filePath, Class<T> type) { Map<Long, List<T>> orgidMap = null; CSVFileReader csvFileReader = null; try { csvFileReader = new CSVFileReader(new FileReader(filePath)); orgidMap = new HashMap<Long, List<T>>(); String record = ""; T domainObject = null; while ((record = csvFileReader.readRecord()) != null) { try { domainObject = type.newInstance(); domainObject.init(record); if (orgidMap.get(domainObject.getOrgid()) == null) orgidMap.put(domainObject.getOrgid(), new ArrayList<T>()); orgidMap.get(domainObject.getOrgid()).add(domainObject); } catch (InstantiationException e) { System.out.println("Could not instantiate " + type.getName() + ". Error: " + e.getMessage()); break; } catch (IllegalAccessException e) { System.out.println("Could not access " + type.getName() + ". Error: " + e.getMessage()); break; } } } catch (IOException e) { System.out.println("File " + filePath + " not found. Error: " + e.getMessage()); } finally { if (csvFileReader != null) { try { csvFileReader.close(); } catch (IOException e) { System.out.println("Could not close file stream. Error: " + e.getMessage()); } } } return orgidMap; } public static <T extends ContainsVb2id & CSVable> Map<Long, List<T>> createVb2idListMap(String filePath, Class<T> type) { Map<Long, List<T>> orgidMap = null; CSVFileReader csvFileReader = null; try { csvFileReader = new CSVFileReader(new FileReader(filePath)); orgidMap = new HashMap<Long, List<T>>(); String record = ""; T domainObject = null; while ((record = csvFileReader.readRecord()) != null) { try { domainObject = type.newInstance(); domainObject.init(record); if (orgidMap.get(domainObject.getVbase2Id()) == null) orgidMap.put(domainObject.getVbase2Id(), new ArrayList<T>()); orgidMap.get(domainObject.getVbase2Id()).add(domainObject); } catch (InstantiationException e) { System.out.println("Could not instantiate " + type.getName() + ". Error: " + e.getMessage()); break; } catch (IllegalAccessException e) { System.out.println("Could not access " + type.getName() + ". Error: " + e.getMessage()); break; } } } catch (IOException e) { System.out.println("File " + filePath + " not found. Error: " + e.getMessage()); } finally { if (csvFileReader != null) { try { csvFileReader.close(); } catch (IOException e) { System.out.println("Could not close file stream. Error: " + e.getMessage()); } } } return orgidMap; } public static <T extends ContainsVb2id & CSVable> Map<Long, T> createVb2idMap(String filePath, Class<T> type) { Map<Long, T> orgidMap = null; CSVFileReader csvFileReader = null; try { csvFileReader = new CSVFileReader(new FileReader(filePath)); orgidMap = new HashMap<Long, T>(); String record = ""; T domainObject = null; while ((record = csvFileReader.readRecord()) != null) { try { domainObject = type.newInstance(); domainObject.init(record); orgidMap.put(domainObject.getVbase2Id(), domainObject); } catch (InstantiationException e) { System.out.println("Could not instantiate " + type.getName() + ". Error: " + e.getMessage()); break; } catch (IllegalAccessException e) { System.out.println("Could not access " + type.getName() + ". Error: " + e.getMessage()); break; } } } catch (IOException e) { System.out.println("File " + filePath + " not found. Error: " + e.getMessage()); } finally { if (csvFileReader != null) { try { csvFileReader.close(); } catch (IOException e) { System.out.println("Could not close file stream. Error: " + e.getMessage()); } } } return orgidMap; } public static <T extends ContainsDiscriminator & ContainsValue & CSVable> Map<String, Map<String, T>> createDiscriminatorValueMap(String filePath, Class<T> type) { Map<String, Map<String, T>> discValMap = null; CSVFileReader csvFileReader = null; try { csvFileReader = new CSVFileReader(new FileReader(filePath)); discValMap = new HashMap<String, Map<String, T>>(); String record = ""; T domainObject = null; while ((record = csvFileReader.readRecord()) != null) { try { domainObject = type.newInstance(); domainObject.init(record); - if (discValMap.get(domainObject.getDiscriminator()) == null) + if (discValMap.get(domainObject.getDiscriminator().toLowerCase()) == null) discValMap.put(domainObject.getDiscriminator().toLowerCase(), new HashMap<String, T>()); discValMap.get(domainObject.getDiscriminator().toLowerCase()).put( domainObject.getValue().toLowerCase(), domainObject); } catch (InstantiationException e) { System.out.println("Could not instantiate " + type.getName() + ". Error: " + e.getMessage()); break; } catch (IllegalAccessException e) { System.out.println("Could not access " + type.getName() + ". Error: " + e.getMessage()); break; } } } catch (IOException e) { System.out.println("File " + filePath + " not found. Error: " + e.getMessage()); } finally { if (csvFileReader != null) { try { csvFileReader.close(); } catch (IOException e) { System.out.println("Could not close file stream. Error: " + e.getMessage()); } } } return discValMap; } }
true
true
public static <T extends ContainsDiscriminator & ContainsValue & CSVable> Map<String, Map<String, T>> createDiscriminatorValueMap(String filePath, Class<T> type) { Map<String, Map<String, T>> discValMap = null; CSVFileReader csvFileReader = null; try { csvFileReader = new CSVFileReader(new FileReader(filePath)); discValMap = new HashMap<String, Map<String, T>>(); String record = ""; T domainObject = null; while ((record = csvFileReader.readRecord()) != null) { try { domainObject = type.newInstance(); domainObject.init(record); if (discValMap.get(domainObject.getDiscriminator()) == null) discValMap.put(domainObject.getDiscriminator().toLowerCase(), new HashMap<String, T>()); discValMap.get(domainObject.getDiscriminator().toLowerCase()).put( domainObject.getValue().toLowerCase(), domainObject); } catch (InstantiationException e) { System.out.println("Could not instantiate " + type.getName() + ". Error: " + e.getMessage()); break; } catch (IllegalAccessException e) { System.out.println("Could not access " + type.getName() + ". Error: " + e.getMessage()); break; } } } catch (IOException e) { System.out.println("File " + filePath + " not found. Error: " + e.getMessage()); } finally { if (csvFileReader != null) { try { csvFileReader.close(); } catch (IOException e) { System.out.println("Could not close file stream. Error: " + e.getMessage()); } } } return discValMap; }
public static <T extends ContainsDiscriminator & ContainsValue & CSVable> Map<String, Map<String, T>> createDiscriminatorValueMap(String filePath, Class<T> type) { Map<String, Map<String, T>> discValMap = null; CSVFileReader csvFileReader = null; try { csvFileReader = new CSVFileReader(new FileReader(filePath)); discValMap = new HashMap<String, Map<String, T>>(); String record = ""; T domainObject = null; while ((record = csvFileReader.readRecord()) != null) { try { domainObject = type.newInstance(); domainObject.init(record); if (discValMap.get(domainObject.getDiscriminator().toLowerCase()) == null) discValMap.put(domainObject.getDiscriminator().toLowerCase(), new HashMap<String, T>()); discValMap.get(domainObject.getDiscriminator().toLowerCase()).put( domainObject.getValue().toLowerCase(), domainObject); } catch (InstantiationException e) { System.out.println("Could not instantiate " + type.getName() + ". Error: " + e.getMessage()); break; } catch (IllegalAccessException e) { System.out.println("Could not access " + type.getName() + ". Error: " + e.getMessage()); break; } } } catch (IOException e) { System.out.println("File " + filePath + " not found. Error: " + e.getMessage()); } finally { if (csvFileReader != null) { try { csvFileReader.close(); } catch (IOException e) { System.out.println("Could not close file stream. Error: " + e.getMessage()); } } } return discValMap; }
diff --git a/src_new/org/argouml/ui/NavigatorPane.java b/src_new/org/argouml/ui/NavigatorPane.java index 0549474..1eaf92a 100644 --- a/src_new/org/argouml/ui/NavigatorPane.java +++ b/src_new/org/argouml/ui/NavigatorPane.java @@ -1,360 +1,359 @@ // Copyright (c) 1996-99 The Regents of the University of California. All // Rights Reserved. Permission to use, copy, modify, and distribute this // software and its documentation without fee, and without a written // agreement is hereby granted, provided that the above copyright notice // and this paragraph appear in all copies. This software program and // documentation are copyrighted by The Regents of the University of // California. The software program and documentation are supplied "AS // IS", without any accompanying services from The Regents. The Regents // does not warrant that the operation of the program will be // uninterrupted or error-free. The end-user understands that the program // was developed for research purposes and is advised not to rely // exclusively on the program for any reason. IN NO EVENT SHALL THE // UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, // SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, // ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF // THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF // SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE // PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF // CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, // UPDATES, ENHANCEMENTS, OR MODIFICATIONS. package org.argouml.ui; import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.tree.*; import ru.novosoft.uml.model_management.*; import ru.novosoft.uml.foundation.core.*; import ru.novosoft.uml.behavior.common_behavior.*; import ru.novosoft.uml.behavior.use_cases.*; import ru.novosoft.uml.behavior.state_machines.*; import org.tigris.gef.base.Diagram; import org.tigris.gef.ui.*; import org.argouml.uml.ui.*; import org.argouml.uml.diagram.ui.*; /** The upper-left pane of the main Argo/UML window. This shows the * contents of the current project in one of several ways that are * determined by NavPerspectives. */ public class NavigatorPane extends JPanel implements ItemListener, TreeSelectionListener { //, CellEditorListener //////////////////////////////////////////////////////////////// // constants public static int MAX_HISTORY = 10; //////////////////////////////////////////////////////////////// // instance variables // vector of TreeModels protected Vector _perspectives = new Vector(); protected ToolBar _toolbar = new ToolBar(); protected JComboBox _combo = new JComboBox(); protected Object _root = null; protected Vector _navHistory = new Vector(); protected int _historyIndex = 0; protected NavPerspective _curPerspective = null; protected DisplayTextTree _tree = new DisplayTextTree(); // protected Action _navBack = Actions.NavBack; // protected Action _navForw = Actions.NavForw; // protected Action _navConfig = Actions.NavConfig; public static int _clicksInNavPane = 0; public static int _navPerspectivesChanged = 0; //////////////////////////////////////////////////////////////// // constructors public NavigatorPane() { setLayout(new BorderLayout()); //_toolbar.add(new JLabel("Perspective ")); _toolbar.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0)); _toolbar.add(_combo); _toolbar.add(Actions.NavBack); _toolbar.add(Actions.NavForw); _toolbar.add(Actions.NavConfig); add(_toolbar, BorderLayout.NORTH); add(new JScrollPane(_tree), BorderLayout.CENTER); _combo.addItemListener(this); _tree.setRootVisible(false); _tree.setShowsRootHandles(true); _tree.addTreeSelectionListener(this); _tree.addMouseListener(new NavigatorMouseListener()); _tree.addKeyListener(new NavigatorKeyListener()); //_tree.addActionListener(new NavigatorActionListener()); //_tree.setEditable(true); //_tree.getCellEditor().addCellEditorListener(this); } //////////////////////////////////////////////////////////////// // accessors public void setRoot(Object r) { _root = r; if (_curPerspective != null) { _curPerspective.setRoot(_root); _tree.setModel(_curPerspective); //forces a redraw } clearHistory(); } public Object getRoot() { return _root; } public Vector getPerspectives() { return _perspectives; } public void setPerspectives(Vector pers) { _perspectives = pers; NavPerspective oldCurPers = _curPerspective; if(_combo.getItemCount() > 0) _combo.removeAllItems(); java.util.Enumeration persEnum = _perspectives.elements(); while (persEnum.hasMoreElements()) _combo.addItem(persEnum.nextElement()); if (_perspectives == null || _perspectives.isEmpty()) _curPerspective = null; else if (oldCurPers != null && _perspectives.contains(oldCurPers)) setCurPerspective(oldCurPers); else setCurPerspective((NavPerspective) _perspectives.elementAt(0)); updateTree(); } public NavPerspective getCurPerspective() { return _curPerspective; } public void setCurPerspective(NavPerspective per) { _curPerspective = per; if (_perspectives == null || !_perspectives.contains(per)) return; _combo.setSelectedItem(_curPerspective); } public Object getSelectedObject() { return _tree.getLastSelectedPathComponent(); } public void forceUpdate() { _tree.forceUpdate(); } /** This is pretty limited, it is really only useful for selecting * the default diagram when the user does New. A general function * to select a given object would have to find the shortest path to * it. */ public void setSelection(Object level1, Object level2) { Object objs[] = new Object[3]; objs[0] = _root; objs[1] = level1; objs[2] = level2; TreePath path = new TreePath(objs); _tree.setSelectionPath(path); } public Dimension getPreferredSize() { return new Dimension(220, 500); } public Dimension getMinimumSize() { return new Dimension(120, 100); } //////////////////////////////////////////////////////////////// // event handlers /** called when the user selects a perspective from the perspective * combo. */ public void itemStateChanged(ItemEvent e) { updateTree(); _navPerspectivesChanged++; } /** called when the user selects an item in the tree, by clicking or * otherwise. */ public void valueChanged(TreeSelectionEvent e) { //needs-more-work: should fire its own event and ProjectBrowser //should register a listener //ProjectBrowser.TheInstance.setTarget(getSelectedObject()); //ProjectBrowser.TheInstance.setTarget(getSelectedObject()); } /** called when the user clicks once on an item in the tree. */ public void mySingleClick(int row, TreePath path) { //needs-more-work: should fire its own event and ProjectBrowser //should register a listener Object sel = getSelectedObject(); if (sel == null) return; if (sel instanceof Diagram) { myDoubleClick(row, path); return; } ProjectBrowser.TheInstance.select(sel); _clicksInNavPane++; } /** called when the user clicks twice on an item in the tree. */ public void myDoubleClick(int row, TreePath path) { //needs-more-work: should fire its own event and ProjectBrowser //should register a listener Object sel = getSelectedObject(); if (sel == null) return; addToHistory(sel); ProjectBrowser.TheInstance.setTarget(sel); repaint(); } public void navDown() { int row = _tree.getMinSelectionRow(); if (row == _tree.getRowCount()) row = 0; else row = row + 1; _tree.setSelectionRow(row); ProjectBrowser.TheInstance.select(getSelectedObject()); } public void navUp() { int row = _tree.getMinSelectionRow(); if (row == 0) row = _tree.getRowCount(); else row = row - 1; _tree.setSelectionRow(row); ProjectBrowser.TheInstance.select(getSelectedObject()); } public void clearHistory() { _historyIndex = 0; _navHistory.removeAllElements(); } public void addToHistory(Object sel) { if (_navHistory.size() == 0) _navHistory.addElement(ProjectBrowser.TheInstance.getTarget()); while (_navHistory.size() -1 > _historyIndex) { _navHistory.removeElementAt(_navHistory.size() - 1); } if (_navHistory.size() > MAX_HISTORY) { _navHistory.removeElementAt(0); } _navHistory.addElement(sel); _historyIndex = _navHistory.size() - 1; } public boolean canNavBack() { return _navHistory.size() > 0 && _historyIndex > 0; } public void navBack() { _historyIndex = Math.max(0, _historyIndex - 1); if (_navHistory.size() <= _historyIndex) return; Object oldTarget = _navHistory.elementAt(_historyIndex); ProjectBrowser.TheInstance.setTarget(oldTarget); } public boolean canNavForw() { return _historyIndex < _navHistory.size() - 1; } public void navForw() { _historyIndex = Math.min(_navHistory.size() - 1, _historyIndex + 1); Object oldTarget = _navHistory.elementAt(_historyIndex); ProjectBrowser.TheInstance.setTarget(oldTarget); } //////////////////////////////////////////////////////////////// // internal methods protected void updateTree() { NavPerspective tm = (NavPerspective) _combo.getSelectedItem(); //if (tm == _curPerspective) return; _curPerspective = tm; if (_curPerspective == null) { //System.out.println("null perspective!"); _tree.setVisible(false); } else { _curPerspective.setRoot(_root); _tree.setModel(_curPerspective); _tree.setVisible(true); // blinks? } } //////////////////////////////////////////////////////////////// // inner classes class NavigatorMouseListener extends MouseAdapter { public void mouseClicked(MouseEvent me) { // // if this platform's popup trigger is occurs on a click // then do the popup if(me.isPopupTrigger()) { me.consume(); showPopupMenu(me); } else { // // otherwise expand the tree? //� //if (me.isConsumed()) return; int row = _tree.getRowForLocation(me.getX(), me.getY()); TreePath path = _tree.getPathForLocation(me.getX(), me.getY()); if (row != -1) { if (me.getClickCount() == 1) mySingleClick(row, path); else if (me.getClickCount() >= 2) myDoubleClick(row, path); //me.consume(); } } } public void showPopupMenu(MouseEvent me) { //TreeCellEditor tce = _tree.getCellEditor(); JPopupMenu popup = new JPopupMenu("test"); Object obj = getSelectedObject(); - if (obj instanceof PopupGenerator) { - Vector actions = ((PopupGenerator)obj).getPopUpActions(me); - int size = actions.size(); - for (int i = 0; i < size; ++i) { - popup.add((AbstractAction) actions.elementAt(i)); - } - } + if (obj instanceof PopupGenerator) { + Vector actions = ((PopupGenerator)obj).getPopUpActions(me); + for(Enumeration e = actions.elements(); e.hasMoreElements(); ) { + popup.add((AbstractAction) e.nextElement()); + } + } else if (obj instanceof MClassifier || obj instanceof MUseCase || obj instanceof MActor || obj instanceof MPackage || obj instanceof MStateVertex || obj instanceof MInstance) { popup.add(new ActionGoToDetails("Properties")); popup.add(new ActionAddExistingNode("Add to Diagram",obj)); popup.add(ActionRemoveFromModel.SINGLETON); } else if (obj instanceof MModelElement || obj instanceof Diagram) { popup.add(new ActionGoToDetails("Properties")); popup.add(ActionRemoveFromModel.SINGLETON); } popup.show(_tree,me.getX(),me.getY()); } public void mousePressed(MouseEvent me) { if (me.isPopupTrigger()) { me.consume(); showPopupMenu(me); } } public void mouseReleased(MouseEvent me) { if (me.isPopupTrigger()) { me.consume(); showPopupMenu(me); } } } /* end class NavigatorMouseListener */ class NavigatorKeyListener extends KeyAdapter { // maybe use keyTyped? public void keyPressed(KeyEvent e) { //System.out.println("got key: " + e.getKeyCode()); int code = e.getKeyCode(); if (code == KeyEvent.VK_ENTER || code == KeyEvent.VK_SPACE) { Object newTarget = getSelectedObject(); if (newTarget != null) ProjectBrowser.TheInstance.select(newTarget); } } } } /* end class NavigatorPane */
true
true
public void showPopupMenu(MouseEvent me) { //TreeCellEditor tce = _tree.getCellEditor(); JPopupMenu popup = new JPopupMenu("test"); Object obj = getSelectedObject(); if (obj instanceof PopupGenerator) { Vector actions = ((PopupGenerator)obj).getPopUpActions(me); int size = actions.size(); for (int i = 0; i < size; ++i) { popup.add((AbstractAction) actions.elementAt(i)); } } else if (obj instanceof MClassifier || obj instanceof MUseCase || obj instanceof MActor || obj instanceof MPackage || obj instanceof MStateVertex || obj instanceof MInstance) { popup.add(new ActionGoToDetails("Properties")); popup.add(new ActionAddExistingNode("Add to Diagram",obj)); popup.add(ActionRemoveFromModel.SINGLETON); } else if (obj instanceof MModelElement || obj instanceof Diagram) { popup.add(new ActionGoToDetails("Properties")); popup.add(ActionRemoveFromModel.SINGLETON); } popup.show(_tree,me.getX(),me.getY()); }
public void showPopupMenu(MouseEvent me) { //TreeCellEditor tce = _tree.getCellEditor(); JPopupMenu popup = new JPopupMenu("test"); Object obj = getSelectedObject(); if (obj instanceof PopupGenerator) { Vector actions = ((PopupGenerator)obj).getPopUpActions(me); for(Enumeration e = actions.elements(); e.hasMoreElements(); ) { popup.add((AbstractAction) e.nextElement()); } } else if (obj instanceof MClassifier || obj instanceof MUseCase || obj instanceof MActor || obj instanceof MPackage || obj instanceof MStateVertex || obj instanceof MInstance) { popup.add(new ActionGoToDetails("Properties")); popup.add(new ActionAddExistingNode("Add to Diagram",obj)); popup.add(ActionRemoveFromModel.SINGLETON); } else if (obj instanceof MModelElement || obj instanceof Diagram) { popup.add(new ActionGoToDetails("Properties")); popup.add(ActionRemoveFromModel.SINGLETON); } popup.show(_tree,me.getX(),me.getY()); }
diff --git a/src/main/org/jboss/joinpoint/plugins/reflect/ReflectJoinpointFactory.java b/src/main/org/jboss/joinpoint/plugins/reflect/ReflectJoinpointFactory.java index 9d57802..16844e6 100644 --- a/src/main/org/jboss/joinpoint/plugins/reflect/ReflectJoinpointFactory.java +++ b/src/main/org/jboss/joinpoint/plugins/reflect/ReflectJoinpointFactory.java @@ -1,91 +1,91 @@ /* * JBoss, the OpenSource J2EE webOS * * Distributable under LGPL license. * See terms of license at gnu.org. */ package org.jboss.joinpoint.plugins.reflect; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Map; import org.jboss.joinpoint.spi.ConstructorJoinpoint; import org.jboss.joinpoint.spi.FieldGetJoinpoint; import org.jboss.joinpoint.spi.FieldSetJoinpoint; import org.jboss.joinpoint.spi.JoinpointException; import org.jboss.joinpoint.spi.JoinpointFactory; import org.jboss.joinpoint.spi.MethodJoinpoint; import org.jboss.reflect.spi.ClassInfo; import org.jboss.reflect.spi.ConstructorInfo; import org.jboss.reflect.spi.FieldInfo; import org.jboss.reflect.spi.MethodInfo; /** * A join point factory based on reflection * * @author <a href="mailto:[email protected]">Adrian Brock</a> */ public class ReflectJoinpointFactory implements JoinpointFactory { /** The class info */ protected ClassInfo classInfo; public static void handleErrors(String context, Class[] parameters, Object[] arguments, Throwable t) throws Throwable { if (t instanceof IllegalArgumentException) { ArrayList expected = new ArrayList(); Class[] parameterTypes = parameters; for (int i = 0; i < parameterTypes.length; ++i) expected.add(parameterTypes[i].getName()); ArrayList actual = new ArrayList(); if (arguments != null) { for (int i = 0; i < arguments.length; ++i) { if (arguments[i] == null) actual.add(null); else - actual.add(arguments.getClass().getName()); + actual.add(arguments[i].getClass().getName()); } } throw new IllegalArgumentException("Wrong arguments. " + context + " expected=" + expected + " actual=" + actual); } else if (t instanceof InvocationTargetException) { throw ((InvocationTargetException) t).getTargetException(); } throw t; } public ReflectJoinpointFactory(ClassInfo classInfo) { this.classInfo = classInfo; } public ClassInfo getClassInfo() { return classInfo; } public ConstructorJoinpoint getConstructorJoinpoint(ConstructorInfo constructorInfo, Map metadata) throws JoinpointException { return new ReflectConstructorJoinPoint(constructorInfo); } public FieldGetJoinpoint getFieldGetJoinpoint(FieldInfo fieldInfo) throws JoinpointException { return new ReflectFieldGetJoinPoint(fieldInfo); } public FieldSetJoinpoint getFieldSetJoinpoint(FieldInfo fieldInfo) throws JoinpointException { return new ReflectFieldSetJoinPoint(fieldInfo); } public MethodJoinpoint getMethodJoinpoint(MethodInfo methodInfo) throws JoinpointException { return new ReflectMethodJoinPoint(methodInfo); } }
true
true
public static void handleErrors(String context, Class[] parameters, Object[] arguments, Throwable t) throws Throwable { if (t instanceof IllegalArgumentException) { ArrayList expected = new ArrayList(); Class[] parameterTypes = parameters; for (int i = 0; i < parameterTypes.length; ++i) expected.add(parameterTypes[i].getName()); ArrayList actual = new ArrayList(); if (arguments != null) { for (int i = 0; i < arguments.length; ++i) { if (arguments[i] == null) actual.add(null); else actual.add(arguments.getClass().getName()); } } throw new IllegalArgumentException("Wrong arguments. " + context + " expected=" + expected + " actual=" + actual); } else if (t instanceof InvocationTargetException) { throw ((InvocationTargetException) t).getTargetException(); } throw t; }
public static void handleErrors(String context, Class[] parameters, Object[] arguments, Throwable t) throws Throwable { if (t instanceof IllegalArgumentException) { ArrayList expected = new ArrayList(); Class[] parameterTypes = parameters; for (int i = 0; i < parameterTypes.length; ++i) expected.add(parameterTypes[i].getName()); ArrayList actual = new ArrayList(); if (arguments != null) { for (int i = 0; i < arguments.length; ++i) { if (arguments[i] == null) actual.add(null); else actual.add(arguments[i].getClass().getName()); } } throw new IllegalArgumentException("Wrong arguments. " + context + " expected=" + expected + " actual=" + actual); } else if (t instanceof InvocationTargetException) { throw ((InvocationTargetException) t).getTargetException(); } throw t; }
diff --git a/src/com/wolvencraft/prison/mines/cmd/EditCommand.java b/src/com/wolvencraft/prison/mines/cmd/EditCommand.java index 1fcd1e0..8789d8a 100644 --- a/src/com/wolvencraft/prison/mines/cmd/EditCommand.java +++ b/src/com/wolvencraft/prison/mines/cmd/EditCommand.java @@ -1,222 +1,223 @@ package com.wolvencraft.prison.mines.cmd; import java.text.DecimalFormat; 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) { if(Util.isNumeric(args[2])) percent = Double.parseDouble(args[2]); else { try { percent = Double.parseDouble(args[2].replace("%", "")); } 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; } DecimalFormat dFormat = new DecimalFormat("#.########"); percent = Double.valueOf(dFormat.format(percent)); 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.round(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) { if(Util.isNumeric(args[2])) percent = Double.parseDouble(args[2]); else { try { percent = Double.parseDouble(args[2].replace("%", "")); } 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.round(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) { getHelp(); 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.parseTime(args[1]); if(seconds == -1) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; } curMine.setCooldownPeriod(seconds); Message.sendFormattedMine("Reset cooldown set to " + ChatColor.GREEN + Util.parseSeconds(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 atribute 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) { if(Util.isNumeric(args[2])) percent = Double.parseDouble(args[2]); else { try { percent = Double.parseDouble(args[2].replace("%", "")); } 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; } DecimalFormat dFormat = new DecimalFormat("#.########"); percent = Double.valueOf(dFormat.format(percent)); 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.round(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) { if(Util.isNumeric(args[2])) percent = Double.parseDouble(args[2]); else { try { percent = Double.parseDouble(args[2].replace("%", "")); } 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.round(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) { getHelp(); 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.parseTime(args[1]); if(seconds == -1) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; } curMine.setCooldownPeriod(seconds); Message.sendFormattedMine("Reset cooldown set to " + ChatColor.GREEN + Util.parseSeconds(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); 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) { if(Util.isNumeric(args[2])) percent = Double.parseDouble(args[2]); else { try { percent = Double.parseDouble(args[2].replace("%", "")); } 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; } DecimalFormat dFormat = new DecimalFormat("#.########"); percent = Double.valueOf(dFormat.format(percent)); 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.round(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) { if(Util.isNumeric(args[2])) percent = Double.parseDouble(args[2]); else { try { percent = Double.parseDouble(args[2].replace("%", "")); } 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.round(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) { getHelp(); 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.parseTime(args[1]); if(seconds == -1) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; } curMine.setCooldownPeriod(seconds); Message.sendFormattedMine("Reset cooldown set to " + ChatColor.GREEN + Util.parseSeconds(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/source/src/ca/idi/tekla/TeclaPrefs.java b/source/src/ca/idi/tekla/TeclaPrefs.java index eba173b..57c1c01 100644 --- a/source/src/ca/idi/tekla/TeclaPrefs.java +++ b/source/src/ca/idi/tekla/TeclaPrefs.java @@ -1,373 +1,381 @@ /* * Copyright (C) 2008-2009 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 ca.idi.tekla; //FIXME: Tecla Access - Solve backup elsewhere //import android.backup.BackupManager; import ca.idi.tecla.sdk.SepManager; import ca.idi.tekla.R; import ca.idi.tekla.sep.SwitchEventProvider; import ca.idi.tekla.util.NavKbdTimeoutDialog; import ca.idi.tekla.util.Persistence; import ca.idi.tekla.util.ScanSpeedDialog; import android.app.ProgressDialog; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.CheckBoxPreference; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.PreferenceGroup; import android.preference.PreferenceScreen; import android.text.AutoText; import android.util.Log; public class TeclaPrefs extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener { /** * Tag used for logging in this class */ private static final String CLASS_TAG = "Prefs: "; private static final String QUICK_FIXES_KEY = "quick_fixes"; private static final String SHOW_SUGGESTIONS_KEY = "show_suggestions"; private static final String PREDICTION_SETTINGS_KEY = "prediction_settings"; private CheckBoxPreference mQuickFixes; private CheckBoxPreference mShowSuggestions; private CheckBoxPreference mPrefVoiceInput; private CheckBoxPreference mPrefVariantsKey; private CheckBoxPreference mPrefPersistentKeyboard; private Preference mPrefAutohideTimeout; private CheckBoxPreference mPrefConnectToShield; private CheckBoxPreference mPrefFullScreenSwitch; private CheckBoxPreference mPrefSelfScanning; private CheckBoxPreference mPrefInverseScanning; private ProgressDialog mProgressDialog; private BluetoothAdapter mBluetoothAdapter; private boolean mShieldFound; private String mShieldAddress, mShieldName; private ScanSpeedDialog mScanSpeedDialog; private NavKbdTimeoutDialog mAutohideTimeoutDialog; @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); if (TeclaApp.DEBUG) android.os.Debug.waitForDebugger(); init(); } private void init() { addPreferencesFromResource(R.layout.activity_prefs); mQuickFixes = (CheckBoxPreference) findPreference(QUICK_FIXES_KEY); mShowSuggestions = (CheckBoxPreference) findPreference(SHOW_SUGGESTIONS_KEY); mPrefVoiceInput = (CheckBoxPreference) findPreference(Persistence.PREF_VOICE_INPUT); mPrefVariantsKey = (CheckBoxPreference) findPreference(Persistence.PREF_VARIANTS_KEY); mPrefPersistentKeyboard = (CheckBoxPreference) findPreference(Persistence.PREF_PERSISTENT_KEYBOARD); mPrefAutohideTimeout = (Preference) findPreference(Persistence.PREF_AUTOHIDE_TIMEOUT); mAutohideTimeoutDialog = new NavKbdTimeoutDialog(this); mAutohideTimeoutDialog.setContentView(R.layout.dialog_autohide_timeout); mPrefConnectToShield = (CheckBoxPreference) findPreference(Persistence.PREF_CONNECT_TO_SHIELD); mPrefFullScreenSwitch = (CheckBoxPreference) findPreference(Persistence.PREF_FULLSCREEN_SWITCH); mPrefSelfScanning = (CheckBoxPreference) findPreference(Persistence.PREF_SELF_SCANNING); mPrefInverseScanning = (CheckBoxPreference) findPreference(Persistence.PREF_INVERSE_SCANNING); mScanSpeedDialog = new ScanSpeedDialog(this); mScanSpeedDialog.setContentView(R.layout.dialog_scan_speed); mProgressDialog = new ProgressDialog(this); // DETERMINE WHICH PREFERENCES SHOULD BE ENABLED // If Tecla Access IME is not selected disable all alternative input preferences if (!TeclaApp.getInstance().isDefaultIME()) { //Tecla Access is not selected mPrefPersistentKeyboard.setEnabled(false); mPrefAutohideTimeout.setEnabled(false); mPrefFullScreenSwitch.setEnabled(false); mPrefConnectToShield.setEnabled(false); mPrefSelfScanning.setEnabled(false); mPrefInverseScanning.setEnabled(false); TeclaApp.getInstance().showToast(R.string.tecla_notselected); } // If no voice apps available, disable voice input if (!(TeclaApp.getInstance().isVoiceInputSupported() && TeclaApp.getInstance().isVoiceActionsInstalled())) { if (mPrefVoiceInput.isChecked()) mPrefVoiceInput.setChecked(false); mPrefVoiceInput.setEnabled(false); mPrefVoiceInput.setSummary(R.string.no_voice_input_available); } // If Bluetooth disabled or unsupported disable Shield connection mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (mBluetoothAdapter == null) { mPrefConnectToShield.setSummary(R.string.shield_connect_summary_BT_nosupport); mPrefConnectToShield.setEnabled(false); } else if (!mBluetoothAdapter.isEnabled()) { mPrefConnectToShield.setSummary(R.string.shield_connect_summary_BT_disabled); mPrefConnectToShield.setEnabled(false); } else { mPrefConnectToShield.setSummary(R.string.shield_connect_summary); } // If no alternative input selected, disable scanning if (!mPrefConnectToShield.isChecked() && !mPrefFullScreenSwitch.isChecked()) { mPrefSelfScanning.setEnabled(false); mPrefInverseScanning.setEnabled(false); } //Tecla Access Intents & Intent Filters registerReceiver(mReceiver, new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)); registerReceiver(mReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND)); registerReceiver(mReceiver, new IntentFilter(SwitchEventProvider.ACTION_SHIELD_CONNECTED)); registerReceiver(mReceiver, new IntentFilter(SwitchEventProvider.ACTION_SHIELD_DISCONNECTED)); getPreferenceManager().getSharedPreferences().registerOnSharedPreferenceChangeListener(TeclaPrefs.this); } @Override protected void onResume() { super.onResume(); int autoTextSize = AutoText.getSize(getListView()); if (autoTextSize < 1) { ((PreferenceGroup) findPreference(PREDICTION_SETTINGS_KEY)) .removePreference(mQuickFixes); } else { mShowSuggestions.setDependency(QUICK_FIXES_KEY); } } @Override protected void onPause() { super.onPause(); finish(); } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(mReceiver); getPreferenceManager().getSharedPreferences().unregisterOnSharedPreferenceChangeListener( TeclaPrefs.this); } private void discoverShield() { mShieldFound = false; if (mBluetoothAdapter.isDiscovering()) mBluetoothAdapter.cancelDiscovery(); mBluetoothAdapter.startDiscovery(); showDiscoveryDialog(); } // All intents will be processed here private BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(BluetoothDevice.ACTION_FOUND) && !mShieldFound) { BluetoothDevice dev = intent.getExtras().getParcelable(BluetoothDevice.EXTRA_DEVICE); if ((dev.getName() != null) && ( dev.getName().startsWith(SwitchEventProvider.SHIELD_PREFIX_2) || dev.getName().startsWith(SwitchEventProvider.SHIELD_PREFIX_3) )) { if (TeclaApp.DEBUG) Log.d(TeclaApp.TAG, CLASS_TAG + "Found a Tecla Access Shield candidate"); mShieldFound = true; mShieldAddress = dev.getAddress(); mShieldName = dev.getName(); if (mBluetoothAdapter.isDiscovering()) mBluetoothAdapter.cancelDiscovery(); } } if (intent.getAction().equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) { if (mShieldFound) { // Shield found, try to connect if (!mProgressDialog.isShowing()) mProgressDialog.show(); mProgressDialog.setMessage(getString(R.string.connecting_tecla_shield) + " " + mShieldName); if(!SepManager.start(TeclaPrefs.this, mShieldAddress)) { // Could not connect to switch closeDialog(); TeclaApp.getInstance().showToast(R.string.couldnt_connect_shield); } } else { // Shield not found closeDialog(); mPrefConnectToShield.setChecked(false); TeclaApp.getInstance().showToast(R.string.no_shields_inrange); } } if (intent.getAction().equals(SwitchEventProvider.ACTION_SHIELD_CONNECTED)) { if (TeclaApp.DEBUG) Log.d(TeclaApp.TAG, CLASS_TAG + "Successfully started SEP"); mPrefPersistentKeyboard.setChecked(true); closeDialog(); TeclaApp.getInstance().showToast(R.string.shield_connected); // Enable scanning checkboxes so they can be turned on/off mPrefSelfScanning.setEnabled(true); mPrefInverseScanning.setEnabled(true); } if (intent.getAction().equals(SwitchEventProvider.ACTION_SHIELD_DISCONNECTED)) { if (TeclaApp.DEBUG) Log.d(TeclaApp.TAG, CLASS_TAG + "SEP broadcast stopped"); closeDialog(); } } }; @Override public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) { if (preference.getKey().equals(Persistence.PREF_SCAN_DELAY_INT)) { mScanSpeedDialog.show(); } if (preference.getKey().equals(Persistence.PREF_AUTOHIDE_TIMEOUT)) { mAutohideTimeoutDialog.show(); } return super.onPreferenceTreeClick(preferenceScreen, preference); } public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (key.equals(Persistence.PREF_VOICE_INPUT) || key.equals(Persistence.PREF_VARIANTS_KEY)) { if (mPrefPersistentKeyboard.isChecked() || mPrefVariantsKey.isChecked()) { if (mPrefPersistentKeyboard.isChecked()) { //Reset IME TeclaApp.getInstance().requestHideIMEView(); TeclaApp.getInstance().requestShowIMEView(); } } } if (key.equals(Persistence.PREF_PERSISTENT_KEYBOARD)) { if (mPrefPersistentKeyboard.isChecked()) { mPrefAutohideTimeout.setEnabled(true); // Show keyboard immediately TeclaApp.getInstance().requestShowIMEView(); } else { mPrefAutohideTimeout.setEnabled(false); mPrefSelfScanning.setChecked(false); mPrefSelfScanning.setEnabled(false); mPrefInverseScanning.setChecked(false); mPrefInverseScanning.setEnabled(false); mPrefFullScreenSwitch.setChecked(false); mPrefConnectToShield.setChecked(false); TeclaApp.getInstance().requestHideIMEView(); } } if (key.equals(Persistence.PREF_AUTOHIDE_TIMEOUT)) { if (mPrefPersistentKeyboard.isChecked()) { // Show keyboard immediately if Tecla Access IME is selected TeclaApp.getInstance().requestShowIMEView(); } else { mPrefSelfScanning.setChecked(false); mPrefSelfScanning.setEnabled(false); mPrefInverseScanning.setChecked(false); mPrefInverseScanning.setEnabled(false); mPrefFullScreenSwitch.setChecked(false); mPrefConnectToShield.setChecked(false); TeclaApp.getInstance().requestHideIMEView(); } } if (key.equals(Persistence.PREF_CONNECT_TO_SHIELD)) { if (mPrefConnectToShield.isChecked()) { // Connect to shield but also keep connection alive discoverShield(); } else { // FIXME: Tecla Access - Find out how to disconnect // switch event provider without breaking // connection with other potential clients. // Should perhaps use Binding? closeDialog(); if (!mPrefFullScreenSwitch.isChecked()) { mPrefSelfScanning.setChecked(false); mPrefSelfScanning.setEnabled(false); mPrefInverseScanning.setChecked(false); mPrefInverseScanning.setEnabled(false); } SepManager.stop(getApplicationContext()); } } if (key.equals(Persistence.PREF_FULLSCREEN_SWITCH)) { if (mPrefFullScreenSwitch.isChecked()) { mPrefPersistentKeyboard.setChecked(true); TeclaApp.getInstance().startFullScreenSwitchMode(); mPrefSelfScanning.setEnabled(true); mPrefInverseScanning.setEnabled(true); if (!(mPrefSelfScanning.isChecked() || mPrefInverseScanning.isChecked())) { mPrefSelfScanning.setChecked(true); } mPrefAutohideTimeout.setEnabled(false); TeclaApp.persistence.setNeverHideNavigationKeyboard(); } else { if (!mPrefConnectToShield.isChecked()) { mPrefSelfScanning.setChecked(false); mPrefSelfScanning.setEnabled(false); mPrefInverseScanning.setChecked(false); mPrefInverseScanning.setEnabled(false); } if (mPrefPersistentKeyboard.isChecked()) { mPrefAutohideTimeout.setEnabled(true); } TeclaApp.getInstance().stopFullScreenSwitchMode(); } } if (key.equals(Persistence.PREF_SELF_SCANNING)) { if (mPrefSelfScanning.isChecked()) { mPrefInverseScanning.setChecked(false); TeclaApp.getInstance().startScanningTeclaIME(); } else { TeclaApp.getInstance().stopScanningTeclaIME(); if (!mPrefInverseScanning.isChecked()) { mPrefFullScreenSwitch.setChecked(false); if (!mPrefConnectToShield.isChecked()) { mPrefSelfScanning.setEnabled(false); } } } } if (key.equals(Persistence.PREF_INVERSE_SCANNING)) { if (mPrefInverseScanning.isChecked()) { mPrefSelfScanning.setChecked(false); TeclaApp.persistence.setInverseScanningChanged(); + } else { + TeclaApp.getInstance().stopScanningTeclaIME(); + if (!mPrefSelfScanning.isChecked()) { + mPrefFullScreenSwitch.setChecked(false); + if (!mPrefConnectToShield.isChecked()) { + mPrefInverseScanning.setEnabled(false); + } + } } } //FIXME: Tecla Access - Solve backup elsewhere //(new BackupManager(getApplicationContext())).dataChanged(); } private void showDiscoveryDialog() { mProgressDialog = ProgressDialog.show(this, "", getString(R.string.searching_for_shields), true, true); } private void closeDialog() { if (mProgressDialog != null && mProgressDialog.isShowing()) mProgressDialog.dismiss(); } }
true
true
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (key.equals(Persistence.PREF_VOICE_INPUT) || key.equals(Persistence.PREF_VARIANTS_KEY)) { if (mPrefPersistentKeyboard.isChecked() || mPrefVariantsKey.isChecked()) { if (mPrefPersistentKeyboard.isChecked()) { //Reset IME TeclaApp.getInstance().requestHideIMEView(); TeclaApp.getInstance().requestShowIMEView(); } } } if (key.equals(Persistence.PREF_PERSISTENT_KEYBOARD)) { if (mPrefPersistentKeyboard.isChecked()) { mPrefAutohideTimeout.setEnabled(true); // Show keyboard immediately TeclaApp.getInstance().requestShowIMEView(); } else { mPrefAutohideTimeout.setEnabled(false); mPrefSelfScanning.setChecked(false); mPrefSelfScanning.setEnabled(false); mPrefInverseScanning.setChecked(false); mPrefInverseScanning.setEnabled(false); mPrefFullScreenSwitch.setChecked(false); mPrefConnectToShield.setChecked(false); TeclaApp.getInstance().requestHideIMEView(); } } if (key.equals(Persistence.PREF_AUTOHIDE_TIMEOUT)) { if (mPrefPersistentKeyboard.isChecked()) { // Show keyboard immediately if Tecla Access IME is selected TeclaApp.getInstance().requestShowIMEView(); } else { mPrefSelfScanning.setChecked(false); mPrefSelfScanning.setEnabled(false); mPrefInverseScanning.setChecked(false); mPrefInverseScanning.setEnabled(false); mPrefFullScreenSwitch.setChecked(false); mPrefConnectToShield.setChecked(false); TeclaApp.getInstance().requestHideIMEView(); } } if (key.equals(Persistence.PREF_CONNECT_TO_SHIELD)) { if (mPrefConnectToShield.isChecked()) { // Connect to shield but also keep connection alive discoverShield(); } else { // FIXME: Tecla Access - Find out how to disconnect // switch event provider without breaking // connection with other potential clients. // Should perhaps use Binding? closeDialog(); if (!mPrefFullScreenSwitch.isChecked()) { mPrefSelfScanning.setChecked(false); mPrefSelfScanning.setEnabled(false); mPrefInverseScanning.setChecked(false); mPrefInverseScanning.setEnabled(false); } SepManager.stop(getApplicationContext()); } } if (key.equals(Persistence.PREF_FULLSCREEN_SWITCH)) { if (mPrefFullScreenSwitch.isChecked()) { mPrefPersistentKeyboard.setChecked(true); TeclaApp.getInstance().startFullScreenSwitchMode(); mPrefSelfScanning.setEnabled(true); mPrefInverseScanning.setEnabled(true); if (!(mPrefSelfScanning.isChecked() || mPrefInverseScanning.isChecked())) { mPrefSelfScanning.setChecked(true); } mPrefAutohideTimeout.setEnabled(false); TeclaApp.persistence.setNeverHideNavigationKeyboard(); } else { if (!mPrefConnectToShield.isChecked()) { mPrefSelfScanning.setChecked(false); mPrefSelfScanning.setEnabled(false); mPrefInverseScanning.setChecked(false); mPrefInverseScanning.setEnabled(false); } if (mPrefPersistentKeyboard.isChecked()) { mPrefAutohideTimeout.setEnabled(true); } TeclaApp.getInstance().stopFullScreenSwitchMode(); } } if (key.equals(Persistence.PREF_SELF_SCANNING)) { if (mPrefSelfScanning.isChecked()) { mPrefInverseScanning.setChecked(false); TeclaApp.getInstance().startScanningTeclaIME(); } else { TeclaApp.getInstance().stopScanningTeclaIME(); if (!mPrefInverseScanning.isChecked()) { mPrefFullScreenSwitch.setChecked(false); if (!mPrefConnectToShield.isChecked()) { mPrefSelfScanning.setEnabled(false); } } } } if (key.equals(Persistence.PREF_INVERSE_SCANNING)) { if (mPrefInverseScanning.isChecked()) { mPrefSelfScanning.setChecked(false); TeclaApp.persistence.setInverseScanningChanged(); } } //FIXME: Tecla Access - Solve backup elsewhere //(new BackupManager(getApplicationContext())).dataChanged(); }
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (key.equals(Persistence.PREF_VOICE_INPUT) || key.equals(Persistence.PREF_VARIANTS_KEY)) { if (mPrefPersistentKeyboard.isChecked() || mPrefVariantsKey.isChecked()) { if (mPrefPersistentKeyboard.isChecked()) { //Reset IME TeclaApp.getInstance().requestHideIMEView(); TeclaApp.getInstance().requestShowIMEView(); } } } if (key.equals(Persistence.PREF_PERSISTENT_KEYBOARD)) { if (mPrefPersistentKeyboard.isChecked()) { mPrefAutohideTimeout.setEnabled(true); // Show keyboard immediately TeclaApp.getInstance().requestShowIMEView(); } else { mPrefAutohideTimeout.setEnabled(false); mPrefSelfScanning.setChecked(false); mPrefSelfScanning.setEnabled(false); mPrefInverseScanning.setChecked(false); mPrefInverseScanning.setEnabled(false); mPrefFullScreenSwitch.setChecked(false); mPrefConnectToShield.setChecked(false); TeclaApp.getInstance().requestHideIMEView(); } } if (key.equals(Persistence.PREF_AUTOHIDE_TIMEOUT)) { if (mPrefPersistentKeyboard.isChecked()) { // Show keyboard immediately if Tecla Access IME is selected TeclaApp.getInstance().requestShowIMEView(); } else { mPrefSelfScanning.setChecked(false); mPrefSelfScanning.setEnabled(false); mPrefInverseScanning.setChecked(false); mPrefInverseScanning.setEnabled(false); mPrefFullScreenSwitch.setChecked(false); mPrefConnectToShield.setChecked(false); TeclaApp.getInstance().requestHideIMEView(); } } if (key.equals(Persistence.PREF_CONNECT_TO_SHIELD)) { if (mPrefConnectToShield.isChecked()) { // Connect to shield but also keep connection alive discoverShield(); } else { // FIXME: Tecla Access - Find out how to disconnect // switch event provider without breaking // connection with other potential clients. // Should perhaps use Binding? closeDialog(); if (!mPrefFullScreenSwitch.isChecked()) { mPrefSelfScanning.setChecked(false); mPrefSelfScanning.setEnabled(false); mPrefInverseScanning.setChecked(false); mPrefInverseScanning.setEnabled(false); } SepManager.stop(getApplicationContext()); } } if (key.equals(Persistence.PREF_FULLSCREEN_SWITCH)) { if (mPrefFullScreenSwitch.isChecked()) { mPrefPersistentKeyboard.setChecked(true); TeclaApp.getInstance().startFullScreenSwitchMode(); mPrefSelfScanning.setEnabled(true); mPrefInverseScanning.setEnabled(true); if (!(mPrefSelfScanning.isChecked() || mPrefInverseScanning.isChecked())) { mPrefSelfScanning.setChecked(true); } mPrefAutohideTimeout.setEnabled(false); TeclaApp.persistence.setNeverHideNavigationKeyboard(); } else { if (!mPrefConnectToShield.isChecked()) { mPrefSelfScanning.setChecked(false); mPrefSelfScanning.setEnabled(false); mPrefInverseScanning.setChecked(false); mPrefInverseScanning.setEnabled(false); } if (mPrefPersistentKeyboard.isChecked()) { mPrefAutohideTimeout.setEnabled(true); } TeclaApp.getInstance().stopFullScreenSwitchMode(); } } if (key.equals(Persistence.PREF_SELF_SCANNING)) { if (mPrefSelfScanning.isChecked()) { mPrefInverseScanning.setChecked(false); TeclaApp.getInstance().startScanningTeclaIME(); } else { TeclaApp.getInstance().stopScanningTeclaIME(); if (!mPrefInverseScanning.isChecked()) { mPrefFullScreenSwitch.setChecked(false); if (!mPrefConnectToShield.isChecked()) { mPrefSelfScanning.setEnabled(false); } } } } if (key.equals(Persistence.PREF_INVERSE_SCANNING)) { if (mPrefInverseScanning.isChecked()) { mPrefSelfScanning.setChecked(false); TeclaApp.persistence.setInverseScanningChanged(); } else { TeclaApp.getInstance().stopScanningTeclaIME(); if (!mPrefSelfScanning.isChecked()) { mPrefFullScreenSwitch.setChecked(false); if (!mPrefConnectToShield.isChecked()) { mPrefInverseScanning.setEnabled(false); } } } } //FIXME: Tecla Access - Solve backup elsewhere //(new BackupManager(getApplicationContext())).dataChanged(); }
diff --git a/hk2/core/src/java/com/sun/enterprise/module/Module.java b/hk2/core/src/java/com/sun/enterprise/module/Module.java index e9d534f29..04ab5ac7f 100644 --- a/hk2/core/src/java/com/sun/enterprise/module/Module.java +++ b/hk2/core/src/java/com/sun/enterprise/module/Module.java @@ -1,577 +1,584 @@ /* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (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/CDDLv1.0.html or * glassfish/bootstrap/legal/CDDLv1.0.txt. * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * Header Notice in each file and include the License file * at glassfish/bootstrap/legal/CDDLv1.0.txt. * If applicable, add the following below the CDDL Header, * with the fields enclosed by brackets [] replaced by * you own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Copyright 2006 Sun Microsystems, Inc. All rights reserved. */ package com.sun.enterprise.module; import com.sun.enterprise.module.ModuleMetadata.InhabitantsDescriptor; import com.sun.enterprise.module.impl.Utils; import com.sun.hk2.component.Holder; import com.sun.hk2.component.InhabitantsParser; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.lang.ref.WeakReference; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Level; import java.util.logging.Logger; /** * A module represents a set of resources accessible to third party modules. * Each module has a module definition which defines its name, its list of * exported resources and its dependencies to other modules. * A module instance stores references to the class loader instances giving * access to the module's implementation. * A module instance belongs to a <code>ModuleRegistry</code> which can be used * to get the list of available modules and/or get particular module * implementation. * Modules can only satisfy their dependencies within the <code>ModuleRegistry * </code> instance they are registered in. * * @author Jerome Dochez */ public final class Module { private ModuleDefinition moduleDef; private WeakReference<ClassLoader> publicCL; private volatile ModuleClassLoader privateCL; /** * Lazily loaded provider {@link Class}es from {@link ModuleMetadata}. * The key is the service class name. We can't use {@link Class} because that would cause leaks. */ private final Map<String,List<Class>> serviceClasses = new ConcurrentHashMap<String,List<Class>>(); /** * {@link ModulesRegistry} that owns this module. * Always non-null. */ private final ModulesRegistry registry; private ModuleState state; private final List<Module> dependencies = new ArrayList<Module>(); private final ArrayList<ModuleChangeListener> listeners = new ArrayList<ModuleChangeListener>(); private final HashMap<String,Long> lastModifieds = new HashMap<String,Long>(); private boolean shared=true; private boolean sticky=false; private LifecyclePolicy lifecyclePolicy = null; /** Creates a new instance of Module */ public Module(ModulesRegistry registry, ModuleDefinition info) { assert registry!=null && info!=null; this.registry = registry; moduleDef = info; for (URI lib : info.getLocations()) { File f = new File(lib); if (f.exists()) { lastModifieds.put(f.getAbsolutePath(), f.lastModified()); } } state = ModuleState.NEW; } /** * Return the <code>ClassLoader</code> instance associated with this module. * Only designated public interfaces will be loaded and returned by * this classloader * @return the public <code>ClassLoader</code> */ public ClassLoader getClassLoader() { ClassLoader r=null; if (publicCL!=null) r = publicCL.get(); if (r!=null) return r; ClassLoaderFacade facade = AccessController.doPrivileged(new PrivilegedAction<ClassLoaderFacade>() { public ClassLoaderFacade run() { return new ClassLoaderFacade(getPrivateClassLoader()); } }); facade.setPublicPkgs(moduleDef.getPublicInterfaces()); publicCL = new WeakReference<ClassLoader>(facade); return facade; } /** * Return the private class loader for this module. This class loader will * be loading all the classes which are not explicitely exported in the * module definition * @return the private <code>ClassLoader</code> instance */ /*package*/ ModuleClassLoader getPrivateClassLoader() { if (privateCL==null) { synchronized(this) { if(privateCL==null) { URI[] locations = moduleDef.getLocations(); URL[] urlLocations = new URL[locations.length]; for (int i=0;i<locations.length;i++) { try { urlLocations[i] = locations[i].toURL(); } catch(MalformedURLException e) { e.printStackTrace(); return null; } } final URL[] urls = urlLocations.clone(); privateCL = AccessController.doPrivileged(new PrivilegedAction<ModuleClassLoader>() { public ModuleClassLoader run() { return new ModuleClassLoader( Module.this, urls, registry.getParentClassLoader()); } }); } } } return privateCL; } /** * Returns the module definition for this module instance * @return the module definition */ public com.sun.enterprise.module.ModuleDefinition getModuleDefinition() { return moduleDef; } /** * Returns the registry owning this module * @return the registry owning the module */ public ModulesRegistry getRegistry() { return registry; } /** * Detach this module from its registry. This does not free any of the * loaded resources. Only proper release of all references to the public * class loader will ensure module being garbage collected. * Detached modules are orphan and will be garbage collected if resources * are properly disposed. */ public void detach() { registry.remove(this); } /** * Return a String representation * @return a descriptive String about myself */ public String toString() { return "Module :" + moduleDef.getName() + "::" + (privateCL==null?"none":privateCL.toString()); } /** * Add a new module change listener * @param listener the listener */ public void addListener(ModuleChangeListener listener) { listeners.add(listener); } /** * Unregister a module change listener * @param listener the listener to unregister */ public void removeListener(ModuleChangeListener listener) { listeners.remove(listener); } /** * fires a ModuleChange event to all listeners */ protected void fireChangeEvent() { ArrayList<ModuleChangeListener> list = new ArrayList<ModuleChangeListener>(listeners); for (ModuleChangeListener listener : list) { listener.changed(this); } // registry listens by default registry.changed(this); } /** * Trigger manual refresh mechanism, the module will check all its * URLs and generate change events if any of them has changed. This * will allow the owning registry to force a module upgrade at next * module request. */ public void refresh() { URI[] urls = moduleDef.getLocations(); for (URI lib : urls) { File f = new File(lib); if (f.exists() && lastModifieds.containsKey(f.getAbsolutePath())) { if (lastModifieds.get(f.getAbsolutePath()) !=f.lastModified()) { //Utils.getDefaultLogger().info("Changed : " + this); fireChangeEvent(); // detach for now... detach(); return; } } } } /** * Gets the metadata of this module. */ public ModuleMetadata getMetadata() { return moduleDef.getMetadata(); } /** * Parses all the inhabitants descriptors of the given name in this module. */ void parseInhabitants(String name,InhabitantsParser parser) throws IOException { Holder<ClassLoader> holder = new Holder<ClassLoader>() { public ClassLoader get() { return getPrivateClassLoader(); } }; for (InhabitantsDescriptor d : getMetadata().getHabitats(name)) parser.parse(d.createScanner(),holder); } /** * Ensure that this module is {@link ModuleState#RESOLVED resolved}. * * <p> * If the module is already resolved, this method does nothing. * Otherwise, iterate over all declared ModuleDependency instances and use the * associated <code>ModuleRegistry</code> to resolve it. After successful * completion of this method, the module state is * {@link ModuleState#RESOLVED}. * * @throws <code>ResolveError</code> if any of the declared dependency of this module * cannot be satisfied */ public synchronized void resolve() throws ResolveError { // already resolved ? if (state==ModuleState.ERROR) throw new ResolveError("Module " + getName() + " is in ERROR state"); if (state.compareTo(ModuleState.RESOLVED)>=0) return; if (state==ModuleState.VALIDATING) { Utils.identifyCyclicDependency(this, Logger.getAnonymousLogger()); throw new ResolveError("Cyclic dependency with " + getName()); } state = ModuleState.VALIDATING; if (moduleDef.getImportPolicyClassName()!=null) { try { Class<ImportPolicy> importPolicyClass = (Class<ImportPolicy>) getPrivateClassLoader().loadClass(moduleDef.getImportPolicyClassName()); ImportPolicy importPolicy = importPolicyClass.newInstance(); importPolicy.prepare(this); } catch(ClassNotFoundException e) { + state = ModuleState.ERROR; throw new ResolveError(e); } catch(java.lang.InstantiationException e) { + state = ModuleState.ERROR; throw new ResolveError(e); } catch(IllegalAccessException e) { + state = ModuleState.ERROR; throw new ResolveError(e); } } for (ModuleDependency dependency : moduleDef.getDependencies()) { Module depModule = registry.makeModuleFor(dependency.getName(), null); if (depModule==null) { + state = ModuleState.ERROR; throw new ResolveError(dependency + " referenced from " + moduleDef.getName() + " is not resolved"); } addImport(depModule); } state = ModuleState.RESOLVED; // time to initialize the lifecycle instance if (moduleDef.getLifecyclePolicyClassName()!=null) { try { Class<LifecyclePolicy> lifecyclePolicyClass = (Class<LifecyclePolicy>) getPrivateClassLoader().loadClass(moduleDef.getLifecyclePolicyClassName()); lifecyclePolicy = lifecyclePolicyClass.newInstance(); } catch(ClassNotFoundException e) { + state = ModuleState.ERROR; throw new ResolveError("ClassNotFound : " + e.getMessage(), e); } catch(java.lang.InstantiationException e) { + state = ModuleState.ERROR; throw new ResolveError(e); } catch(IllegalAccessException e) { + state = ModuleState.ERROR; throw new ResolveError(e); } - lifecyclePolicy.load(this); + lifecyclePolicy.load(this); } //Logger.global.info("Module " + getName() + " resolved"); // module resolution complete. notify listeners for (ModuleLifecycleListener listener : registry.lifecycleListeners) listener.moduleStarted(this); } /** * Forces module startup. In most cases, the runtime will take care * of starting modules when they are first used. There could be cases where * code need to manually start a sub module. Invoking this method will * move the module to the {@link ModuleState#READY ModuleState.READY}, the * {@link LifecyclePolicy#start Lifecycle.start} method will be invoked. */ public void start() throws ResolveError { if (state==ModuleState.READY) return; // ensure RESOLVED state resolve(); state = ModuleState.READY; try { for (Module subModules : dependencies) { subModules.start(); } } catch(ResolveError e) { state = ModuleState.RESOLVED; throw e; } if (lifecyclePolicy!=null) { lifecyclePolicy.start(this); } //Logger.global.info("Module " + getName() + " started"); } /** * Forces module stop. In most cases, the runtime will take care of stopping * modules when the last module user released its interest. However, in * certain cases, it may be interesting to manually stop the module. * Stopping the module means that the module is removed from the registry, * the class loader references are released (note : the class loaders will * only be released if all instances of any class loaded by them are gc'ed). * If a <code>LifecyclePolicy</code> for this module is defined, the * {@link LifecyclePolicy#stop(Module) Lifecycle.stop(Module)} * method will be called and finally the module state will be * returned to {@link ModuleState#NEW ModuleState.NEW}. * * @return true if unloading was successful */ public boolean stop() { if (sticky) { return false; } if (lifecyclePolicy!=null) { lifecyclePolicy.stop(this); lifecyclePolicy=null; } detach(); // we do NOT stop our sub modules which are shared... for (Module subModule : dependencies) { if (!subModule.isShared()) { subModule.stop(); } } // release all sub modules class loaders privateCL = null; publicCL = null; dependencies.clear(); state = ModuleState.NEW; return true; } /** * Returns the list of imported modules * @return the list of imported modules */ public List<Module> getImports() { return dependencies; } /** * Create and add a new module to this module's list of * imports. * @param dependency new module's definition */ public Module addImport(ModuleDependency dependency) { Module newModule; if (dependency.isShared()) { newModule = registry.makeModuleFor(dependency.getName(), dependency.getVersion()); } else { newModule = registry.newPrivateModuleFor(dependency.getName(), dependency.getVersion()); } addImport(newModule); return newModule; } /** * Returns the module's state * @return the module's state */ public ModuleState getState() { return state; } public void addImport(Module module) { //if (Utils.isLoggable(Level.INFO)) { // Utils.getDefaultLogger().info("For module" + getName() + " adding new dependent " + module.getName()); //} if (!dependencies.contains(module)) { dependencies.add(module); getPrivateClassLoader().addDelegate(module.getClassLoader()); } } public void removeImport(Module module) { if (dependencies.contains(module)) { dependencies.remove(module); getPrivateClassLoader().removeDelegate(module.getClassLoader()); } } /** * Short-cut for {@code getModuleDefinition().getName()}. */ public String getName() { if (getModuleDefinition()!=null) { return getModuleDefinition().getName(); } return "unknown module"; } /** * Returns true if this module is sharable. A sharable module means that * onlu one instance of the module classloader will be used by all users. * * @return true if this module is sharable. */ public boolean isShared() { return shared; } /** * Sets the sharable flag. Setting the flag to false means that the moodule * class loader should not be shared among module owners. * @param sharable set to true to share the module */ void setShared(boolean sharable) { this.shared = sharable; } /** * Returns true if the module is sticky. A sticky module cannot be stopped or * unloaded. Once a sticky module is loaded or started, it will stay in the * JVM until it exists. * @return true is the module is sticky */ public boolean isSticky() { return sticky; } /** * Sets the sticky flag. * @param sticky true if the module should stick around */ public void setSticky(boolean sticky) { this.sticky = sticky; } @SuppressWarnings({"unchecked"}) public <T> Iterable<Class<? extends T>> getProvidersClass(Class<T> serviceClass) { return (Iterable)getProvidersClass(serviceClass.getName()); } public Iterable<Class> getProvidersClass(String name) { List<Class> r = serviceClasses.get(name); if(r!=null) return r; // the worst case scenario in the race situation is we end up creating the same list twice, // which is not a big deal. for( String provider : getMetadata().getEntry(name).providerNames) { if(r==null) r = new ArrayList<Class>(); try { r.add(getPrivateClassLoader().loadClass(provider)); } catch (ClassNotFoundException e) { Utils.getDefaultLogger().log(Level.SEVERE, "Failed to load "+provider+" from "+getName(),e); } } if(r==null) r = Collections.emptyList(); serviceClasses.put(name, r); return r; } /** * Returns true if this module has any provider for the given service class. */ public boolean hasProvider(Class serviceClass) { String name = serviceClass.getName(); List<Class> v = serviceClasses.get(name); if(v!=null && !v.isEmpty()) return true; return getMetadata().getEntry(name).hasProvider(); } void dumpState(PrintStream writer) { writer.println("Module " + getName() + " Dump"); writer.println("State " + getState()); for (Module imported : getImports()) { writer.println("Depends on " + imported.getName()); } if (publicCL!=null) { ClassLoaderFacade cloader = (ClassLoaderFacade) publicCL.get(); cloader.dumpState(writer); } } /** * Finds the {@link Module} that owns the given class. * * @return * null if the class is loaded outside the module system. */ public static Module find(Class clazz) { ClassLoader cl = clazz.getClassLoader(); if(cl==null) return null; if (cl instanceof ModuleClassLoader) return ((ModuleClassLoader) cl).getOwner(); return null; } }
false
true
public synchronized void resolve() throws ResolveError { // already resolved ? if (state==ModuleState.ERROR) throw new ResolveError("Module " + getName() + " is in ERROR state"); if (state.compareTo(ModuleState.RESOLVED)>=0) return; if (state==ModuleState.VALIDATING) { Utils.identifyCyclicDependency(this, Logger.getAnonymousLogger()); throw new ResolveError("Cyclic dependency with " + getName()); } state = ModuleState.VALIDATING; if (moduleDef.getImportPolicyClassName()!=null) { try { Class<ImportPolicy> importPolicyClass = (Class<ImportPolicy>) getPrivateClassLoader().loadClass(moduleDef.getImportPolicyClassName()); ImportPolicy importPolicy = importPolicyClass.newInstance(); importPolicy.prepare(this); } catch(ClassNotFoundException e) { throw new ResolveError(e); } catch(java.lang.InstantiationException e) { throw new ResolveError(e); } catch(IllegalAccessException e) { throw new ResolveError(e); } } for (ModuleDependency dependency : moduleDef.getDependencies()) { Module depModule = registry.makeModuleFor(dependency.getName(), null); if (depModule==null) { throw new ResolveError(dependency + " referenced from " + moduleDef.getName() + " is not resolved"); } addImport(depModule); } state = ModuleState.RESOLVED; // time to initialize the lifecycle instance if (moduleDef.getLifecyclePolicyClassName()!=null) { try { Class<LifecyclePolicy> lifecyclePolicyClass = (Class<LifecyclePolicy>) getPrivateClassLoader().loadClass(moduleDef.getLifecyclePolicyClassName()); lifecyclePolicy = lifecyclePolicyClass.newInstance(); } catch(ClassNotFoundException e) { throw new ResolveError("ClassNotFound : " + e.getMessage(), e); } catch(java.lang.InstantiationException e) { throw new ResolveError(e); } catch(IllegalAccessException e) { throw new ResolveError(e); } lifecyclePolicy.load(this); } //Logger.global.info("Module " + getName() + " resolved"); // module resolution complete. notify listeners for (ModuleLifecycleListener listener : registry.lifecycleListeners) listener.moduleStarted(this); }
public synchronized void resolve() throws ResolveError { // already resolved ? if (state==ModuleState.ERROR) throw new ResolveError("Module " + getName() + " is in ERROR state"); if (state.compareTo(ModuleState.RESOLVED)>=0) return; if (state==ModuleState.VALIDATING) { Utils.identifyCyclicDependency(this, Logger.getAnonymousLogger()); throw new ResolveError("Cyclic dependency with " + getName()); } state = ModuleState.VALIDATING; if (moduleDef.getImportPolicyClassName()!=null) { try { Class<ImportPolicy> importPolicyClass = (Class<ImportPolicy>) getPrivateClassLoader().loadClass(moduleDef.getImportPolicyClassName()); ImportPolicy importPolicy = importPolicyClass.newInstance(); importPolicy.prepare(this); } catch(ClassNotFoundException e) { state = ModuleState.ERROR; throw new ResolveError(e); } catch(java.lang.InstantiationException e) { state = ModuleState.ERROR; throw new ResolveError(e); } catch(IllegalAccessException e) { state = ModuleState.ERROR; throw new ResolveError(e); } } for (ModuleDependency dependency : moduleDef.getDependencies()) { Module depModule = registry.makeModuleFor(dependency.getName(), null); if (depModule==null) { state = ModuleState.ERROR; throw new ResolveError(dependency + " referenced from " + moduleDef.getName() + " is not resolved"); } addImport(depModule); } state = ModuleState.RESOLVED; // time to initialize the lifecycle instance if (moduleDef.getLifecyclePolicyClassName()!=null) { try { Class<LifecyclePolicy> lifecyclePolicyClass = (Class<LifecyclePolicy>) getPrivateClassLoader().loadClass(moduleDef.getLifecyclePolicyClassName()); lifecyclePolicy = lifecyclePolicyClass.newInstance(); } catch(ClassNotFoundException e) { state = ModuleState.ERROR; throw new ResolveError("ClassNotFound : " + e.getMessage(), e); } catch(java.lang.InstantiationException e) { state = ModuleState.ERROR; throw new ResolveError(e); } catch(IllegalAccessException e) { state = ModuleState.ERROR; throw new ResolveError(e); } lifecyclePolicy.load(this); } //Logger.global.info("Module " + getName() + " resolved"); // module resolution complete. notify listeners for (ModuleLifecycleListener listener : registry.lifecycleListeners) listener.moduleStarted(this); }
diff --git a/ide/org.codehaus.groovy.eclipse.codeassist.completion/src/org/codehaus/groovy/eclipse/codeassist/completion/jdt/AbstractGroovyCompletionProcessor.java b/ide/org.codehaus.groovy.eclipse.codeassist.completion/src/org/codehaus/groovy/eclipse/codeassist/completion/jdt/AbstractGroovyCompletionProcessor.java index 00f9a1b63..669f2f5f0 100644 --- a/ide/org.codehaus.groovy.eclipse.codeassist.completion/src/org/codehaus/groovy/eclipse/codeassist/completion/jdt/AbstractGroovyCompletionProcessor.java +++ b/ide/org.codehaus.groovy.eclipse.codeassist.completion/src/org/codehaus/groovy/eclipse/codeassist/completion/jdt/AbstractGroovyCompletionProcessor.java @@ -1,455 +1,455 @@ /******************************************************************************* * Copyright 2003-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package org.codehaus.groovy.eclipse.codeassist.completion.jdt; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.ModuleNode; import org.codehaus.groovy.eclipse.core.GroovyCore; import org.codehaus.groovy.eclipse.core.ISourceBuffer; import org.codehaus.groovy.eclipse.core.context.ISourceCodeContext; import org.codehaus.groovy.eclipse.core.context.impl.SourceCodeContextFactory; import org.codehaus.groovy.eclipse.core.types.Field; import org.codehaus.groovy.eclipse.core.types.GroovyDeclaration; import org.codehaus.groovy.eclipse.core.types.LocalVariable; import org.codehaus.groovy.eclipse.core.types.Member; import org.codehaus.groovy.eclipse.core.types.Method; import org.codehaus.groovy.eclipse.core.types.Modifiers; import org.codehaus.groovy.eclipse.core.types.Parameter; import org.codehaus.groovy.eclipse.core.types.Property; import org.codehaus.groovy.eclipse.core.util.ExpressionFinder; import org.codehaus.groovy.eclipse.core.util.ParseException; import org.codehaus.jdt.groovy.model.GroovyCompilationUnit; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jdt.core.CompletionProposal; import org.eclipse.jdt.core.Signature; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.javaeditor.EditorHighlightingSynchronizer; import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor; import org.eclipse.jdt.internal.ui.text.java.JavaMethodCompletionProposal; import org.eclipse.jdt.internal.ui.text.java.ProposalContextInformation; import org.eclipse.jdt.ui.text.java.ContentAssistInvocationContext; import org.eclipse.jdt.ui.text.java.IJavaCompletionProposalComputer; import org.eclipse.jdt.ui.text.java.JavaContentAssistInvocationContext; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.Region; import org.eclipse.jface.text.contentassist.IContextInformation; import org.eclipse.jface.text.link.LinkedModeModel; import org.eclipse.jface.text.link.LinkedModeUI; import org.eclipse.jface.text.link.LinkedPosition; import org.eclipse.jface.text.link.LinkedPositionGroup; import org.eclipse.jface.viewers.StyledString; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.texteditor.link.EditorLinkedModeUI; @SuppressWarnings("nls") public abstract class AbstractGroovyCompletionProcessor implements IJavaCompletionProposalComputer { /** * Largely copied from FilledArgumentNamesMethodProposal * @author Andrew Eisenberg * @created Aug 11, 2009 * */ protected class GroovyMethodCompletionProposal extends JavaMethodCompletionProposal { private int[] fArgumentOffsets; private int[] fArgumentLengths; private IRegion fSelectedRegion; // initialized by apply() public GroovyMethodCompletionProposal(CompletionProposal proposal, JavaContentAssistInvocationContext context) { super(proposal, context); } @Override protected StyledString computeDisplayString() { return super.computeDisplayString().append(getStyledGroovy()); } @Override protected IContextInformation computeContextInformation() { if ((fProposal.getKind() == CompletionProposal.METHOD_REF || fProposal.getKind() == CompletionProposal.CONSTRUCTOR_INVOCATION) && hasParameters()) { ProposalContextInformation contextInformation= new ProposalContextInformation(fProposal); if (fContextInformationPosition != 0 && fProposal.getCompletion().length == 0) contextInformation.setContextInformationPosition(fContextInformationPosition); return contextInformation; } return super.computeContextInformation(); } private StyledString getStyledGroovy() { return new StyledString(" (Groovy)", StyledString.DECORATIONS_STYLER); } /* * @see ICompletionProposalExtension#apply(IDocument, char) */ public void apply(IDocument document, char trigger, int offset) { super.apply(document, trigger, offset); int baseOffset= getReplacementOffset(); String replacement= getReplacementString(); if (fArgumentOffsets != null && getTextViewer() != null) { try { LinkedModeModel model= new LinkedModeModel(); for (int i= 0; i != fArgumentOffsets.length; i++) { LinkedPositionGroup group= new LinkedPositionGroup(); group.addPosition(new LinkedPosition(document, baseOffset + fArgumentOffsets[i], fArgumentLengths[i], LinkedPositionGroup.NO_STOP)); model.addGroup(group); } model.forceInstall(); JavaEditor editor= getJavaEditor(); if (editor != null) { model.addLinkingListener(new EditorHighlightingSynchronizer(editor)); } LinkedModeUI ui= new EditorLinkedModeUI(model, getTextViewer()); ui.setExitPosition(getTextViewer(), baseOffset + replacement.length(), 0, Integer.MAX_VALUE); ui.setExitPolicy(new ExitPolicy(')', document)); ui.setDoContextInfo(true); ui.setCyclingMode(LinkedModeUI.CYCLE_WHEN_NO_PARENT); ui.enter(); fSelectedRegion= ui.getSelectedRegion(); } catch (BadLocationException e) { JavaPlugin.log(e); openErrorDialog(e); } } else { fSelectedRegion= new Region(baseOffset + replacement.length(), 0); } } /** * Groovify this replacement string * Remove parens if this method has parameters * If the first parameter is a closure, then use { } */ @Override protected String computeReplacementString() { if (!hasArgumentList()) { return super.computeReplacementString(); } // we're inserting a method plus the argument list - respect formatter preferences StringBuffer buffer= new StringBuffer(); appendMethodNameReplacement(buffer); FormatterPrefs prefs= getFormatterPrefs(); if (hasParameters()) { // remove the openning paren buffer.replace(buffer.length()-1, buffer.length(), ""); // add space if not already there if (!prefs.beforeOpeningParen) { buffer.append(" "); } // now add the parameters char[][] parameterNames= fProposal.findParameterNames(null); char[][] parameterTypes = Signature.getParameterTypes(fProposal.getSignature()); int count= parameterNames.length; fArgumentOffsets= new int[count]; fArgumentLengths= new int[count]; for (int i= 0; i != count; i++) { if (i != 0) { if (prefs.beforeComma) { buffer.append(SPACE); } buffer.append(COMMA); if (prefs.afterComma) { buffer.append(SPACE); } } fArgumentOffsets[i]= buffer.length(); - if (new String(parameterTypes[i]).equals("Lgroovy.lang.Closure;")) { + if (new String(Signature.getSignatureSimpleName(parameterTypes[i])).equals("Closure")) { buffer.append("{ }"); fArgumentLengths[i] = 3; if (i == 0) { setCursorPosition(buffer.length()-2); } } else { if (i == 0) { setCursorPosition(buffer.length()); } buffer.append(parameterNames[i]); fArgumentLengths[i] = parameterNames[i].length; } } } else { if (prefs.inEmptyList) { buffer.append(SPACE); } buffer.append(RPAREN); } return buffer.toString(); } /* * @see org.eclipse.jdt.internal.ui.text.java.JavaMethodCompletionProposal#needsLinkedMode() */ protected boolean needsLinkedMode() { return false; // we handle it ourselves } /** * Returns the currently active java editor, or <code>null</code> if it * cannot be determined. * * @return the currently active java editor, or <code>null</code> */ private JavaEditor getJavaEditor() { IEditorPart part= JavaPlugin.getActivePage().getActiveEditor(); if (part instanceof JavaEditor) return (JavaEditor) part; else return null; } /* * @see ICompletionProposal#getSelection(IDocument) */ public Point getSelection(IDocument document) { if (fSelectedRegion == null) return new Point(getReplacementOffset(), 0); return new Point(fSelectedRegion.getOffset(), fSelectedRegion.getLength()); } private void openErrorDialog(BadLocationException e) { Shell shell= getTextViewer().getTextWidget().getShell(); MessageDialog.openError(shell, "Error inserting parameters", e.getMessage()); } } /** * Remove types that are equal. There is no control over if the different implementations of IMemberLookup will * equal result, so this method merges the duplicates if they exist. * * @param types * @return */ protected GroovyDeclaration[] mergeTypes(GroovyDeclaration[] types) { if (types.length < 1) { return types; } Arrays.sort(types); List<GroovyDeclaration> results = new ArrayList<GroovyDeclaration>(); results.add(types[0]); for (int i = 1; i < types.length; ++i) { if (!isSimilar(types[i-1], types[i])) { results.add(types[i]); } } removeCompilerMethods(results); // HACK: emp - must be base type. This is really wanting to be an interface at some stage. Class<?> cls = types[0].getClass(); if (cls.getName().startsWith("org.codehaus.groovy.eclipse.core.types.Java")) { cls = cls.getSuperclass(); } return (GroovyDeclaration[]) results.toArray((GroovyDeclaration[])Array.newInstance(cls, results.size())); } private boolean isSimilar(GroovyDeclaration type1, GroovyDeclaration type2) { if (type1 instanceof Method && type2 instanceof Method) { Method method1 = (Method) type1; Method method2 = (Method) type2; if (! method1.getName().equals(method2.getName())) { return false; } if (method1.getParameters().length != method2.getParameters().length) { return false; } Parameter[] params1 = method1.getParameters(); Parameter[] params2 = method2.getParameters(); for (int i = 0; i < params1.length; i++) { if (!params1[i].getSignature() .equals(params2[i].getSignature())) { return false; } } return true; } else { return type1.equals(type2); } } /** * class$ and super$ and this$ methods must be removed. * @param results */ protected void removeCompilerMethods(List<GroovyDeclaration> results) { for (Iterator<GroovyDeclaration> iter = results.iterator(); iter.hasNext();) { String name = iter.next().getName(); if (name.startsWith("<clinit>") || name.startsWith("class$") || name.startsWith("super$") || name.startsWith("this$")) { iter.remove(); } } } protected boolean isScriptOrClosureContext(ISourceCodeContext sourceContext) { try { return sourceContext.getId().equals(ISourceCodeContext.CLOSURE_SCOPE) || ((ClassNode) sourceContext.getASTPath()[1]).isScript(); } catch (Exception e) { // any reason for failure means we are not in a script return false; } } protected Image getImageForType(GroovyDeclaration type) { if (type instanceof LocalVariable) { return JavaPluginImages.get(JavaPluginImages.IMG_OBJS_LOCAL_VARIABLE); } if (type instanceof Field) { if (test(type.getModifiers(), Modifiers.ACC_PUBLIC)) { return JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PUBLIC); } else if (test(type.getModifiers(), Modifiers.ACC_PROTECTED)) { return JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PROTECTED); } else if (test(type.getModifiers(), Modifiers.ACC_PRIVATE)) { return JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PRIVATE); } return JavaPluginImages.get(JavaPluginImages.IMG_FIELD_DEFAULT); } else if (type instanceof Property) { // TODO: need compound icon with 'r' and 'w' on it to indicate property and access. if (test(type.getModifiers(), Modifiers.ACC_PUBLIC)) { return JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PUBLIC); } else if (test(type.getModifiers(), Modifiers.ACC_PROTECTED)) { return JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PROTECTED); } else if (test(type.getModifiers(), Modifiers.ACC_PRIVATE)) { return JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PRIVATE); } return JavaPluginImages.get(JavaPluginImages.IMG_FIELD_DEFAULT); } else if (type instanceof Method) { if (test(type.getModifiers(), Modifiers.ACC_PUBLIC)) { return JavaPluginImages.get(JavaPluginImages.IMG_MISC_PUBLIC); } else if (test(type.getModifiers(), Modifiers.ACC_PROTECTED)) { return JavaPluginImages.get(JavaPluginImages.IMG_MISC_PROTECTED); } else if (test(type.getModifiers(), Modifiers.ACC_PRIVATE)) { return JavaPluginImages.get(JavaPluginImages.IMG_MISC_PRIVATE); } return JavaPluginImages.get(JavaPluginImages.IMG_MISC_DEFAULT); } return null; } protected boolean test(int flags, int mask) { return (flags & mask) != 0; } protected String createReplaceString(GroovyDeclaration method) { return method.getName() + "()"; } protected StyledString createDisplayString(Member member) { StringBuffer sb = new StringBuffer(member.getName()); sb.append(" ").append(toSimpleTypeName(member.getSignature())).append(" - ").append( toSimpleTypeName(member.getDeclaringClass().getSignature())).append(" (Groovy)"); return new StyledString(sb.toString()); } protected String toSimpleTypeName( final String t ) { String type = t; if (type.charAt(0) == '[') { type = Signature.toString(type); } int ix = type.lastIndexOf('.'); if (ix != -1) { return type.substring(ix + 1); } return type; } protected String findCompletionExpression(ExpressionFinder finder, int offset, ISourceBuffer buffer) { try{ return finder.findForCompletions(buffer, offset - 1); } catch (ParseException e) { // can ignore. probably just invalid code that is being completed at GroovyCore.trace("Cannot complete code:" + e.getMessage()); } return null; } protected ISourceCodeContext[] createContexts(ModuleNode moduleNode, ISourceBuffer buffer, int offset) { SourceCodeContextFactory factory = new SourceCodeContextFactory(); return factory.createContexts(buffer, moduleNode, new Region(offset, 0)); } protected ModuleNode getCurrentModuleNode(JavaContentAssistInvocationContext context) { return ((GroovyCompilationUnit) context.getCompilationUnit()).getModuleNode(); } public String getErrorMessage() { return null; } public void sessionEnded() { // do nothing } public void sessionStarted() { // do nothing } private static final List<IContextInformation> NO_CONTEXTS= Collections.emptyList(); public List<IContextInformation> computeContextInformation( ContentAssistInvocationContext context, IProgressMonitor monitor) { return NO_CONTEXTS; } }
true
true
protected String computeReplacementString() { if (!hasArgumentList()) { return super.computeReplacementString(); } // we're inserting a method plus the argument list - respect formatter preferences StringBuffer buffer= new StringBuffer(); appendMethodNameReplacement(buffer); FormatterPrefs prefs= getFormatterPrefs(); if (hasParameters()) { // remove the openning paren buffer.replace(buffer.length()-1, buffer.length(), ""); // add space if not already there if (!prefs.beforeOpeningParen) { buffer.append(" "); } // now add the parameters char[][] parameterNames= fProposal.findParameterNames(null); char[][] parameterTypes = Signature.getParameterTypes(fProposal.getSignature()); int count= parameterNames.length; fArgumentOffsets= new int[count]; fArgumentLengths= new int[count]; for (int i= 0; i != count; i++) { if (i != 0) { if (prefs.beforeComma) { buffer.append(SPACE); } buffer.append(COMMA); if (prefs.afterComma) { buffer.append(SPACE); } } fArgumentOffsets[i]= buffer.length(); if (new String(parameterTypes[i]).equals("Lgroovy.lang.Closure;")) { buffer.append("{ }"); fArgumentLengths[i] = 3; if (i == 0) { setCursorPosition(buffer.length()-2); } } else { if (i == 0) { setCursorPosition(buffer.length()); } buffer.append(parameterNames[i]); fArgumentLengths[i] = parameterNames[i].length; } } } else { if (prefs.inEmptyList) { buffer.append(SPACE); } buffer.append(RPAREN); } return buffer.toString(); }
protected String computeReplacementString() { if (!hasArgumentList()) { return super.computeReplacementString(); } // we're inserting a method plus the argument list - respect formatter preferences StringBuffer buffer= new StringBuffer(); appendMethodNameReplacement(buffer); FormatterPrefs prefs= getFormatterPrefs(); if (hasParameters()) { // remove the openning paren buffer.replace(buffer.length()-1, buffer.length(), ""); // add space if not already there if (!prefs.beforeOpeningParen) { buffer.append(" "); } // now add the parameters char[][] parameterNames= fProposal.findParameterNames(null); char[][] parameterTypes = Signature.getParameterTypes(fProposal.getSignature()); int count= parameterNames.length; fArgumentOffsets= new int[count]; fArgumentLengths= new int[count]; for (int i= 0; i != count; i++) { if (i != 0) { if (prefs.beforeComma) { buffer.append(SPACE); } buffer.append(COMMA); if (prefs.afterComma) { buffer.append(SPACE); } } fArgumentOffsets[i]= buffer.length(); if (new String(Signature.getSignatureSimpleName(parameterTypes[i])).equals("Closure")) { buffer.append("{ }"); fArgumentLengths[i] = 3; if (i == 0) { setCursorPosition(buffer.length()-2); } } else { if (i == 0) { setCursorPosition(buffer.length()); } buffer.append(parameterNames[i]); fArgumentLengths[i] = parameterNames[i].length; } } } else { if (prefs.inEmptyList) { buffer.append(SPACE); } buffer.append(RPAREN); } return buffer.toString(); }
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/resources/manager/ProjectResources.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/resources/manager/ProjectResources.java index 9052672d3..dce262288 100644 --- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/resources/manager/ProjectResources.java +++ b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/resources/manager/ProjectResources.java @@ -1,832 +1,832 @@ /* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Eclipse 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/org/documents/epl-v10.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 com.android.ide.eclipse.adt.internal.resources.manager; import com.android.ide.eclipse.adt.internal.resources.IResourceRepository; import com.android.ide.eclipse.adt.internal.resources.ResourceItem; import com.android.ide.eclipse.adt.internal.resources.ResourceType; import com.android.ide.eclipse.adt.internal.resources.configurations.FolderConfiguration; import com.android.ide.eclipse.adt.internal.resources.configurations.LanguageQualifier; import com.android.ide.eclipse.adt.internal.resources.configurations.RegionQualifier; import com.android.ide.eclipse.adt.internal.resources.configurations.ResourceQualifier; import com.android.ide.eclipse.adt.internal.resources.manager.files.IAbstractFolder; import com.android.layoutlib.api.IResourceValue; import com.android.layoutlib.utils.ResourceValue; import org.eclipse.core.resources.IFolder; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; /** * Represents the resources of a project. This is a file view of the resources, with handling * for the alternate resource types. For a compiled view use CompiledResources. */ public class ProjectResources implements IResourceRepository { private final HashMap<ResourceFolderType, List<ResourceFolder>> mFolderMap = new HashMap<ResourceFolderType, List<ResourceFolder>>(); private final HashMap<ResourceType, List<ProjectResourceItem>> mResourceMap = new HashMap<ResourceType, List<ProjectResourceItem>>(); /** Map of (name, id) for resources of type {@link ResourceType#ID} coming from R.java */ private Map<String, Map<String, Integer>> mResourceValueMap; /** Map of (id, [name, resType]) for all resources coming from R.java */ private Map<Integer, String[]> mResIdValueToNameMap; /** Map of (int[], name) for styleable resources coming from R.java */ private Map<IntArrayWrapper, String> mStyleableValueToNameMap; /** Cached list of {@link IdResourceItem}. This is mix of IdResourceItem created by * {@link MultiResourceFile} for ids coming from XML files under res/values and * {@link IdResourceItem} created manually, from the list coming from R.java */ private final ArrayList<IdResourceItem> mIdResourceList = new ArrayList<IdResourceItem>(); private final boolean mIsFrameworkRepository; private final IntArrayWrapper mWrapper = new IntArrayWrapper(null); public ProjectResources(boolean isFrameworkRepository) { mIsFrameworkRepository = isFrameworkRepository; } public boolean isSystemRepository() { return mIsFrameworkRepository; } /** * Adds a Folder Configuration to the project. * @param type The resource type. * @param config The resource configuration. * @param folder The workspace folder object. * @return the {@link ResourceFolder} object associated to this folder. */ protected ResourceFolder add(ResourceFolderType type, FolderConfiguration config, IAbstractFolder folder) { // get the list for the resource type List<ResourceFolder> list = mFolderMap.get(type); if (list == null) { list = new ArrayList<ResourceFolder>(); ResourceFolder cf = new ResourceFolder(type, config, folder, mIsFrameworkRepository); list.add(cf); mFolderMap.put(type, list); return cf; } // look for an already existing folder configuration. for (ResourceFolder cFolder : list) { if (cFolder.mConfiguration.equals(config)) { // config already exist. Nothing to be done really, besides making sure // the IFolder object is up to date. cFolder.mFolder = folder; return cFolder; } } // If we arrive here, this means we didn't find a matching configuration. // So we add one. ResourceFolder cf = new ResourceFolder(type, config, folder, mIsFrameworkRepository); list.add(cf); return cf; } /** * Removes a {@link ResourceFolder} associated with the specified {@link IAbstractFolder}. * @param type The type of the folder * @param folder the IFolder object. */ protected void removeFolder(ResourceFolderType type, IFolder folder) { // get the list of folders for the resource type. List<ResourceFolder> list = mFolderMap.get(type); if (list != null) { int count = list.size(); for (int i = 0 ; i < count ; i++) { ResourceFolder resFolder = list.get(i); if (resFolder.getFolder().getIFolder().equals(folder)) { // we found the matching ResourceFolder. we need to remove it. list.remove(i); // we now need to invalidate this resource type. // The easiest way is to touch one of the other folders of the same type. if (list.size() > 0) { list.get(0).touch(); } else { // if the list is now empty, and we have a single ResouceType out of this // ResourceFolderType, then we are done. // However, if another ResourceFolderType can generate similar ResourceType // than this, we need to update those ResourceTypes as well. // For instance, if the last "drawable-*" folder is deleted, we need to // refresh the ResourceItem associated with ResourceType.DRAWABLE. // Those can be found in ResourceFolderType.DRAWABLE but also in // ResourceFolderType.VALUES. // If we don't find a single folder to touch, then it's fine, as the top // level items (the list of generated resource types) is not cached // (for now) // get the lists of ResourceTypes generated by this ResourceFolderType ResourceType[] resTypes = FolderTypeRelationship.getRelatedResourceTypes( type); // for each of those, make sure to find one folder to touch so that the // list of ResourceItem associated with the type is rebuilt. for (ResourceType resType : resTypes) { // get the list of folder that can generate this type ResourceFolderType[] folderTypes = FolderTypeRelationship.getRelatedFolders(resType); // we only need to touch one folder in any of those (since it's one // folder per type, not per folder type). for (ResourceFolderType folderType : folderTypes) { List<ResourceFolder> resFolders = mFolderMap.get(folderType); if (resFolders != null && resFolders.size() > 0) { resFolders.get(0).touch(); break; } } } } // we're done updating/touching, we can stop break; } } } } /** * Returns a list of {@link ResourceFolder} for a specific {@link ResourceFolderType}. * @param type The {@link ResourceFolderType} */ public List<ResourceFolder> getFolders(ResourceFolderType type) { return mFolderMap.get(type); } /* (non-Javadoc) * @see com.android.ide.eclipse.editors.resources.IResourceRepository#getAvailableResourceTypes() */ public ResourceType[] getAvailableResourceTypes() { ArrayList<ResourceType> list = new ArrayList<ResourceType>(); // For each key, we check if there's a single ResourceType match. // If not, we look for the actual content to give us the resource type. for (ResourceFolderType folderType : mFolderMap.keySet()) { ResourceType types[] = FolderTypeRelationship.getRelatedResourceTypes(folderType); if (types.length == 1) { // before we add it we check if it's not already present, since a ResourceType // could be created from multiple folders, even for the folders that only create // one type of resource (drawable for instance, can be created from drawable/ and // values/) if (list.indexOf(types[0]) == -1) { list.add(types[0]); } } else { // there isn't a single resource type out of this folder, so we look for all // content. List<ResourceFolder> folders = mFolderMap.get(folderType); if (folders != null) { for (ResourceFolder folder : folders) { Collection<ResourceType> folderContent = folder.getResourceTypes(); // then we add them, but only if they aren't already in the list. for (ResourceType folderResType : folderContent) { if (list.indexOf(folderResType) == -1) { list.add(folderResType); } } } } } } // in case ResourceType.ID haven't been added yet because there's no id defined // in XML, we check on the list of compiled id resources. if (list.indexOf(ResourceType.ID) == -1 && mResourceValueMap != null) { Map<String, Integer> map = mResourceValueMap.get(ResourceType.ID.getName()); if (map != null && map.size() > 0) { list.add(ResourceType.ID); } } // at this point the list is full of ResourceType defined in the files. // We need to sort it. Collections.sort(list); return list.toArray(new ResourceType[list.size()]); } /* (non-Javadoc) * @see com.android.ide.eclipse.editors.resources.IResourceRepository#getResources(com.android.ide.eclipse.common.resources.ResourceType) */ public ProjectResourceItem[] getResources(ResourceType type) { checkAndUpdate(type); if (type == ResourceType.ID) { synchronized (mIdResourceList) { return mIdResourceList.toArray(new ProjectResourceItem[mIdResourceList.size()]); } } List<ProjectResourceItem> items = mResourceMap.get(type); return items.toArray(new ProjectResourceItem[items.size()]); } /* (non-Javadoc) * @see com.android.ide.eclipse.editors.resources.IResourceRepository#hasResources(com.android.ide.eclipse.common.resources.ResourceType) */ public boolean hasResources(ResourceType type) { checkAndUpdate(type); if (type == ResourceType.ID) { synchronized (mIdResourceList) { return mIdResourceList.size() > 0; } } List<ProjectResourceItem> items = mResourceMap.get(type); return (items != null && items.size() > 0); } /** * Returns the {@link ResourceFolder} associated with a {@link IFolder}. * @param folder The {@link IFolder} object. * @return the {@link ResourceFolder} or null if it was not found. */ public ResourceFolder getResourceFolder(IFolder folder) { for (List<ResourceFolder> list : mFolderMap.values()) { for (ResourceFolder resFolder : list) { if (resFolder.getFolder().getIFolder().equals(folder)) { return resFolder; } } } return null; } /** * Returns the {@link ResourceFile} matching the given name, {@link ResourceFolderType} and * configuration. * <p/>This only works with files generating one resource named after the file (for instance, * layouts, bitmap based drawable, xml, anims). * @return the matching file or <code>null</code> if no match was found. */ public ResourceFile getMatchingFile(String name, ResourceFolderType type, FolderConfiguration config) { // get the folders for the given type List<ResourceFolder> folders = mFolderMap.get(type); // look for folders containing a file with the given name. ArrayList<ResourceFolder> matchingFolders = new ArrayList<ResourceFolder>(); // remove the folders that do not have a file with the given name, or if their config // is incompatible. for (int i = 0 ; i < folders.size(); i++) { ResourceFolder folder = folders.get(i); if (folder.hasFile(name) == true) { matchingFolders.add(folder); } } // from those, get the folder with a config matching the given reference configuration. Resource match = findMatchingConfiguredResource(matchingFolders, config); // do we have a matching folder? if (match instanceof ResourceFolder) { // get the ResourceFile from the filename return ((ResourceFolder)match).getFile(name); } return null; } /** * Returns the resources values matching a given {@link FolderConfiguration}. * @param referenceConfig the configuration that each value must match. */ public Map<String, Map<String, IResourceValue>> getConfiguredResources( FolderConfiguration referenceConfig) { Map<String, Map<String, IResourceValue>> map = new HashMap<String, Map<String, IResourceValue>>(); // special case for Id since there's a mix of compiled id (declared inline) and id declared // in the XML files. if (mIdResourceList.size() > 0) { Map<String, IResourceValue> idMap = new HashMap<String, IResourceValue>(); String idType = ResourceType.ID.getName(); for (IdResourceItem id : mIdResourceList) { // FIXME: cache the ResourceValue! idMap.put(id.getName(), new ResourceValue(idType, id.getName(), mIsFrameworkRepository)); } map.put(ResourceType.ID.getName(), idMap); } Set<ResourceType> keys = mResourceMap.keySet(); for (ResourceType key : keys) { // we don't process ID resources since we already did it above. if (key != ResourceType.ID) { map.put(key.getName(), getConfiguredResource(key, referenceConfig)); } } return map; } /** * Loads all the resources. Essentially this forces to load the values from the * {@link ResourceFile} objects to make sure they are up to date and loaded * in {@link #mResourceMap}. */ public void loadAll() { // gets all the resource types available. ResourceType[] types = getAvailableResourceTypes(); // loop on them and load them for (ResourceType type: types) { checkAndUpdate(type); } } /** * Resolves a compiled resource id into the resource name and type * @param id * @return an array of 2 strings { name, type } or null if the id could not be resolved */ public String[] resolveResourceValue(int id) { if (mResIdValueToNameMap != null) { return mResIdValueToNameMap.get(id); } return null; } /** * Resolves a compiled resource id of type int[] into the resource name. */ public String resolveResourceValue(int[] id) { if (mStyleableValueToNameMap != null) { mWrapper.set(id); return mStyleableValueToNameMap.get(mWrapper); } return null; } /** * Returns the value of a resource by its type and name. */ public Integer getResourceValue(String type, String name) { if (mResourceValueMap != null) { Map<String, Integer> map = mResourceValueMap.get(type); if (map != null) { return map.get(name); } } return null; } /** * Returns the sorted list of languages used in the resources. */ public SortedSet<String> getLanguages() { SortedSet<String> set = new TreeSet<String>(); Collection<List<ResourceFolder>> folderList = mFolderMap.values(); for (List<ResourceFolder> folderSubList : folderList) { for (ResourceFolder folder : folderSubList) { FolderConfiguration config = folder.getConfiguration(); LanguageQualifier lang = config.getLanguageQualifier(); if (lang != null) { set.add(lang.getStringValue()); } } } return set; } /** * Returns the sorted list of regions used in the resources with the given language. * @param currentLanguage the current language the region must be associated with. */ public SortedSet<String> getRegions(String currentLanguage) { SortedSet<String> set = new TreeSet<String>(); Collection<List<ResourceFolder>> folderList = mFolderMap.values(); for (List<ResourceFolder> folderSubList : folderList) { for (ResourceFolder folder : folderSubList) { FolderConfiguration config = folder.getConfiguration(); // get the language LanguageQualifier lang = config.getLanguageQualifier(); if (lang != null && lang.getStringValue().equals(currentLanguage)) { RegionQualifier region = config.getRegionQualifier(); if (region != null) { set.add(region.getStringValue()); } } } } return set; } /** * Returns a map of (resource name, resource value) for the given {@link ResourceType}. * <p/>The values returned are taken from the resource files best matching a given * {@link FolderConfiguration}. * @param type the type of the resources. * @param referenceConfig the configuration to best match. */ private Map<String, IResourceValue> getConfiguredResource(ResourceType type, FolderConfiguration referenceConfig) { // get the resource item for the given type List<ProjectResourceItem> items = mResourceMap.get(type); // create the map HashMap<String, IResourceValue> map = new HashMap<String, IResourceValue>(); for (ProjectResourceItem item : items) { // get the source files generating this resource List<ResourceFile> list = item.getSourceFileList(); // look for the best match for the given configuration Resource match = findMatchingConfiguredResource(list, referenceConfig); if (match instanceof ResourceFile) { ResourceFile matchResFile = (ResourceFile)match; // get the value of this configured resource. IResourceValue value = matchResFile.getValue(type, item.getName()); if (value != null) { map.put(item.getName(), value); } } } return map; } /** * Returns the best matching {@link Resource}. * @param resources the list of {@link Resource} to choose from. * @param referenceConfig the {@link FolderConfiguration} to match. * @see http://d.android.com/guide/topics/resources/resources-i18n.html#best-match */ private Resource findMatchingConfiguredResource(List<? extends Resource> resources, FolderConfiguration referenceConfig) { // // 1: eliminate resources that contradict the reference configuration // 2: pick next qualifier type // 3: check if any resources use this qualifier, if no, back to 2, else move on to 4. // 4: eliminate resources that don't use this qualifier. // 5: if more than one resource left, go back to 2. // // The precedence of the qualifiers is more important than the number of qualifiers that // exactly match the device. // 1: eliminate resources that contradict ArrayList<Resource> matchingResources = new ArrayList<Resource>(); for (int i = 0 ; i < resources.size(); i++) { Resource res = resources.get(i); if (res.getConfiguration().isMatchFor(referenceConfig)) { matchingResources.add(res); } } // if there is only one match, just take it if (matchingResources.size() == 1) { return matchingResources.get(0); } else if (matchingResources.size() == 0) { return null; } // 2. Loop on the qualifiers, and eliminate matches final int count = FolderConfiguration.getQualifierCount(); for (int q = 0 ; q < count ; q++) { // look to see if one resource has this qualifier. // At the same time also record the best match value for the qualifier (if applicable). // The reference value, to find the best match. // Note that this qualifier could be null. In which case any qualifier found in the // possible match, will all be considered best match. ResourceQualifier referenceQualifier = referenceConfig.getQualifier(q); boolean found = false; ResourceQualifier bestMatch = null; // this is to store the best match. for (Resource res : matchingResources) { ResourceQualifier qualifier = res.getConfiguration().getQualifier(q); if (qualifier != null) { // set the flag. found = true; // Now check for a best match. If the reference qualifier is null , // any qualifier is a "best" match (we don't need to record all of them. // Instead the non compatible ones are removed below) if (referenceQualifier != null) { if (qualifier.isBetterMatchThan(bestMatch, referenceQualifier)) { bestMatch = qualifier; } } } } // 4. If a resources has a qualifier at the current index, remove all the resources that // do not have one, or whose qualifier value does not equal the best match found above // unless there's no reference qualifier, in which case they are all considered // "best" match. if (found) { for (int i = 0 ; i < matchingResources.size(); ) { Resource res = matchingResources.get(i); ResourceQualifier qualifier = res.getConfiguration().getQualifier(q); if (qualifier == null) { // this resources has no qualifier of this type: rejected. matchingResources.remove(res); } else if (referenceQualifier != null && bestMatch != null && bestMatch.equals(qualifier) == false) { // there's a reference qualifier and there is a better match for it than // this resource, so we reject it. matchingResources.remove(res); } else { // looks like we keep this resource, move on to the next one. i++; } } // at this point we may have run out of matching resources before going // through all the qualifiers. if (matchingResources.size() < 2) { break; } } } // Because we accept resources whose configuration have qualifiers where the reference // configuration doesn't, we can end up with more than one match. In this case, we just // take the first one. if (matchingResources.size() == 0) { return null; } - return matchingResources.get(1); + return matchingResources.get(0); } /** * Checks if the list of {@link ResourceItem}s for the specified {@link ResourceType} needs * to be updated. * @param type the Resource Type. */ private void checkAndUpdate(ResourceType type) { // get the list of folder that can output this type ResourceFolderType[] folderTypes = FolderTypeRelationship.getRelatedFolders(type); for (ResourceFolderType folderType : folderTypes) { List<ResourceFolder> folders = mFolderMap.get(folderType); if (folders != null) { for (ResourceFolder folder : folders) { if (folder.isTouched()) { // if this folder is touched we need to update all the types that can // be generated from a file in this folder. // This will include 'type' obviously. ResourceType[] resTypes = FolderTypeRelationship.getRelatedResourceTypes( folderType); for (ResourceType resType : resTypes) { update(resType); } return; } } } } } /** * Updates the list of {@link ResourceItem} objects associated with a {@link ResourceType}. * This will reset the touch status of all the folders that can generate this resource type. * @param type the Resource Type. */ private void update(ResourceType type) { // get the cache list, and lets make a backup List<ProjectResourceItem> items = mResourceMap.get(type); List<ProjectResourceItem> backup = new ArrayList<ProjectResourceItem>(); if (items == null) { items = new ArrayList<ProjectResourceItem>(); mResourceMap.put(type, items); } else { // backup the list backup.addAll(items); // we reset the list itself. items.clear(); } // get the list of folder that can output this type ResourceFolderType[] folderTypes = FolderTypeRelationship.getRelatedFolders(type); for (ResourceFolderType folderType : folderTypes) { List<ResourceFolder> folders = mFolderMap.get(folderType); if (folders != null) { for (ResourceFolder folder : folders) { items.addAll(folder.getResources(type, this)); folder.resetTouch(); } } } // now items contains the new list. We "merge" it with the backup list. // Basically, we need to keep the old instances of ResourceItem (where applicable), // but replace them by the content of the new items. // This will let the resource explorer keep the expanded state of the nodes whose data // is a ResourceItem object. if (backup.size() > 0) { // this is not going to change as we're only replacing instances. int count = items.size(); for (int i = 0 ; i < count;) { // get the "new" item ProjectResourceItem item = items.get(i); // look for a similar item in the old list. ProjectResourceItem foundOldItem = null; for (ProjectResourceItem oldItem : backup) { if (oldItem.getName().equals(item.getName())) { foundOldItem = oldItem; break; } } if (foundOldItem != null) { // erase the data of the old item with the data from the new one. foundOldItem.replaceWith(item); // remove the old and new item from their respective lists items.remove(i); backup.remove(foundOldItem); // add the old item to the new list items.add(foundOldItem); } else { // this is a new item, we skip to the next object i++; } } } // if this is the ResourceType.ID, we create the actual list, from this list and // the compiled resource list. if (type == ResourceType.ID) { mergeIdResources(); } else { // else this is the list that will actually be displayed, so we sort it. Collections.sort(items); } } /** * Looks up an existing {@link ProjectResourceItem} by {@link ResourceType} and name. * @param type the Resource Type. * @param name the Resource name. * @return the existing ResourceItem or null if no match was found. */ protected ProjectResourceItem findResourceItem(ResourceType type, String name) { List<ProjectResourceItem> list = mResourceMap.get(type); for (ProjectResourceItem item : list) { if (name.equals(item.getName())) { return item; } } return null; } /** * Sets compiled resource information. * @param resIdValueToNameMap a map of compiled resource id to resource name. * The map is acquired by the {@link ProjectResources} object. * @param styleableValueMap * @param resourceValueMap a map of (name, id) for resources of type {@link ResourceType#ID}. * The list is acquired by the {@link ProjectResources} object. */ void setCompiledResources(Map<Integer, String[]> resIdValueToNameMap, Map<IntArrayWrapper, String> styleableValueMap, Map<String, Map<String, Integer>> resourceValueMap) { mResourceValueMap = resourceValueMap; mResIdValueToNameMap = resIdValueToNameMap; mStyleableValueToNameMap = styleableValueMap; mergeIdResources(); } /** * Merges the list of ID resource coming from R.java and the list of ID resources * coming from XML declaration into the cached list {@link #mIdResourceList}. */ void mergeIdResources() { // get the list of IDs coming from XML declaration. Those ids are present in // mCompiledIdResources already, so we'll need to use those instead of creating // new IdResourceItem List<ProjectResourceItem> xmlIdResources = mResourceMap.get(ResourceType.ID); synchronized (mIdResourceList) { // copy the currently cached items. ArrayList<IdResourceItem> oldItems = new ArrayList<IdResourceItem>(); oldItems.addAll(mIdResourceList); // empty the current list mIdResourceList.clear(); // get the list of compile id resources. Map<String, Integer> idMap = null; if (mResourceValueMap != null) { idMap = mResourceValueMap.get(ResourceType.ID.getName()); } if (idMap == null) { if (xmlIdResources != null) { for (ProjectResourceItem resourceItem : xmlIdResources) { // check the actual class just for safety. if (resourceItem instanceof IdResourceItem) { mIdResourceList.add((IdResourceItem)resourceItem); } } } } else { // loop on the full list of id, and look for a match in the old list, // in the list coming from XML (in case a new XML item was created.) Set<String> idSet = idMap.keySet(); idLoop: for (String idResource : idSet) { // first look in the XML list in case an id went from inline to XML declared. if (xmlIdResources != null) { for (ProjectResourceItem resourceItem : xmlIdResources) { if (resourceItem instanceof IdResourceItem && resourceItem.getName().equals(idResource)) { mIdResourceList.add((IdResourceItem)resourceItem); continue idLoop; } } } // if we haven't found it, look in the old items. int count = oldItems.size(); for (int i = 0 ; i < count ; i++) { IdResourceItem resourceItem = oldItems.get(i); if (resourceItem.getName().equals(idResource)) { oldItems.remove(i); mIdResourceList.add(resourceItem); continue idLoop; } } // if we haven't found it, it looks like it's a new id that was // declared inline. mIdResourceList.add(new IdResourceItem(idResource, true /* isDeclaredInline */)); } } // now we sort the list Collections.sort(mIdResourceList); } } }
true
true
private Resource findMatchingConfiguredResource(List<? extends Resource> resources, FolderConfiguration referenceConfig) { // // 1: eliminate resources that contradict the reference configuration // 2: pick next qualifier type // 3: check if any resources use this qualifier, if no, back to 2, else move on to 4. // 4: eliminate resources that don't use this qualifier. // 5: if more than one resource left, go back to 2. // // The precedence of the qualifiers is more important than the number of qualifiers that // exactly match the device. // 1: eliminate resources that contradict ArrayList<Resource> matchingResources = new ArrayList<Resource>(); for (int i = 0 ; i < resources.size(); i++) { Resource res = resources.get(i); if (res.getConfiguration().isMatchFor(referenceConfig)) { matchingResources.add(res); } } // if there is only one match, just take it if (matchingResources.size() == 1) { return matchingResources.get(0); } else if (matchingResources.size() == 0) { return null; } // 2. Loop on the qualifiers, and eliminate matches final int count = FolderConfiguration.getQualifierCount(); for (int q = 0 ; q < count ; q++) { // look to see if one resource has this qualifier. // At the same time also record the best match value for the qualifier (if applicable). // The reference value, to find the best match. // Note that this qualifier could be null. In which case any qualifier found in the // possible match, will all be considered best match. ResourceQualifier referenceQualifier = referenceConfig.getQualifier(q); boolean found = false; ResourceQualifier bestMatch = null; // this is to store the best match. for (Resource res : matchingResources) { ResourceQualifier qualifier = res.getConfiguration().getQualifier(q); if (qualifier != null) { // set the flag. found = true; // Now check for a best match. If the reference qualifier is null , // any qualifier is a "best" match (we don't need to record all of them. // Instead the non compatible ones are removed below) if (referenceQualifier != null) { if (qualifier.isBetterMatchThan(bestMatch, referenceQualifier)) { bestMatch = qualifier; } } } } // 4. If a resources has a qualifier at the current index, remove all the resources that // do not have one, or whose qualifier value does not equal the best match found above // unless there's no reference qualifier, in which case they are all considered // "best" match. if (found) { for (int i = 0 ; i < matchingResources.size(); ) { Resource res = matchingResources.get(i); ResourceQualifier qualifier = res.getConfiguration().getQualifier(q); if (qualifier == null) { // this resources has no qualifier of this type: rejected. matchingResources.remove(res); } else if (referenceQualifier != null && bestMatch != null && bestMatch.equals(qualifier) == false) { // there's a reference qualifier and there is a better match for it than // this resource, so we reject it. matchingResources.remove(res); } else { // looks like we keep this resource, move on to the next one. i++; } } // at this point we may have run out of matching resources before going // through all the qualifiers. if (matchingResources.size() < 2) { break; } } } // Because we accept resources whose configuration have qualifiers where the reference // configuration doesn't, we can end up with more than one match. In this case, we just // take the first one. if (matchingResources.size() == 0) { return null; } return matchingResources.get(1); }
private Resource findMatchingConfiguredResource(List<? extends Resource> resources, FolderConfiguration referenceConfig) { // // 1: eliminate resources that contradict the reference configuration // 2: pick next qualifier type // 3: check if any resources use this qualifier, if no, back to 2, else move on to 4. // 4: eliminate resources that don't use this qualifier. // 5: if more than one resource left, go back to 2. // // The precedence of the qualifiers is more important than the number of qualifiers that // exactly match the device. // 1: eliminate resources that contradict ArrayList<Resource> matchingResources = new ArrayList<Resource>(); for (int i = 0 ; i < resources.size(); i++) { Resource res = resources.get(i); if (res.getConfiguration().isMatchFor(referenceConfig)) { matchingResources.add(res); } } // if there is only one match, just take it if (matchingResources.size() == 1) { return matchingResources.get(0); } else if (matchingResources.size() == 0) { return null; } // 2. Loop on the qualifiers, and eliminate matches final int count = FolderConfiguration.getQualifierCount(); for (int q = 0 ; q < count ; q++) { // look to see if one resource has this qualifier. // At the same time also record the best match value for the qualifier (if applicable). // The reference value, to find the best match. // Note that this qualifier could be null. In which case any qualifier found in the // possible match, will all be considered best match. ResourceQualifier referenceQualifier = referenceConfig.getQualifier(q); boolean found = false; ResourceQualifier bestMatch = null; // this is to store the best match. for (Resource res : matchingResources) { ResourceQualifier qualifier = res.getConfiguration().getQualifier(q); if (qualifier != null) { // set the flag. found = true; // Now check for a best match. If the reference qualifier is null , // any qualifier is a "best" match (we don't need to record all of them. // Instead the non compatible ones are removed below) if (referenceQualifier != null) { if (qualifier.isBetterMatchThan(bestMatch, referenceQualifier)) { bestMatch = qualifier; } } } } // 4. If a resources has a qualifier at the current index, remove all the resources that // do not have one, or whose qualifier value does not equal the best match found above // unless there's no reference qualifier, in which case they are all considered // "best" match. if (found) { for (int i = 0 ; i < matchingResources.size(); ) { Resource res = matchingResources.get(i); ResourceQualifier qualifier = res.getConfiguration().getQualifier(q); if (qualifier == null) { // this resources has no qualifier of this type: rejected. matchingResources.remove(res); } else if (referenceQualifier != null && bestMatch != null && bestMatch.equals(qualifier) == false) { // there's a reference qualifier and there is a better match for it than // this resource, so we reject it. matchingResources.remove(res); } else { // looks like we keep this resource, move on to the next one. i++; } } // at this point we may have run out of matching resources before going // through all the qualifiers. if (matchingResources.size() < 2) { break; } } } // Because we accept resources whose configuration have qualifiers where the reference // configuration doesn't, we can end up with more than one match. In this case, we just // take the first one. if (matchingResources.size() == 0) { return null; } return matchingResources.get(0); }
diff --git a/examples/org.eclipse.ocl.examples.pivot/src/org/eclipse/ocl/examples/pivot/prettyprint/PrettyPrinter.java b/examples/org.eclipse.ocl.examples.pivot/src/org/eclipse/ocl/examples/pivot/prettyprint/PrettyPrinter.java index fb4264d6bb..6c1d3bed31 100644 --- a/examples/org.eclipse.ocl.examples.pivot/src/org/eclipse/ocl/examples/pivot/prettyprint/PrettyPrinter.java +++ b/examples/org.eclipse.ocl.examples.pivot/src/org/eclipse/ocl/examples/pivot/prettyprint/PrettyPrinter.java @@ -1,798 +1,799 @@ /** * <copyright> * * Copyright (c) 2011 E.D.Willink 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: * E.D. Willink - Initial API and implementation * * </copyright> * * $Id: PrettyPrintTypeVisitor.java,v 1.7 2011/05/22 21:06:19 ewillink Exp $ */ package org.eclipse.ocl.examples.pivot.prettyprint; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.util.EcoreUtil; import org.eclipse.ocl.examples.pivot.Element; import org.eclipse.ocl.examples.pivot.ExpressionInOcl; import org.eclipse.ocl.examples.pivot.Iteration; import org.eclipse.ocl.examples.pivot.NamedElement; import org.eclipse.ocl.examples.pivot.Namespace; import org.eclipse.ocl.examples.pivot.OclExpression; import org.eclipse.ocl.examples.pivot.Operation; import org.eclipse.ocl.examples.pivot.Parameter; import org.eclipse.ocl.examples.pivot.PivotConstants; import org.eclipse.ocl.examples.pivot.PivotPackage; import org.eclipse.ocl.examples.pivot.Precedence; import org.eclipse.ocl.examples.pivot.TemplateBinding; import org.eclipse.ocl.examples.pivot.TemplateParameter; import org.eclipse.ocl.examples.pivot.TemplateParameterSubstitution; import org.eclipse.ocl.examples.pivot.TemplateSignature; import org.eclipse.ocl.examples.pivot.TemplateableElement; import org.eclipse.ocl.examples.pivot.Type; import org.eclipse.ocl.examples.pivot.TypedMultiplicityElement; import org.eclipse.ocl.examples.pivot.manager.MetaModelManager; import org.eclipse.ocl.examples.pivot.prettyprint.PrettyPrintOptions.Global; import org.eclipse.ocl.examples.pivot.util.AbstractVisitor; import org.eclipse.ocl.examples.pivot.util.Visitable; import org.eclipse.ocl.examples.pivot.utilities.PathElement; import org.eclipse.ocl.examples.pivot.utilities.PivotUtil; /** * The PrettyPrinter supports pretty printing. * PrettyPrintOptions may be used to configure the printing. */ public class PrettyPrinter { public static final String NULL_PLACEHOLDER = "<null>"; public static List<String> reservedNameList = Arrays.asList("and", "else", "endif", "false", "if", "implies", "in", "invalid", "let", "not", "null", "or", "self", "then", "true", "xor"); public static List<String> restrictedNameList = Arrays.asList("Bag", "Boolean", "Collection", "Integer", "OclAny", "OclInvalid", "OclVoid", "OrderedSet", "Real", "Sequence", "Set", "String", "Tuple", "UnlimitedNatural"); public static interface Factory { AbstractVisitor<Object, PrettyPrinter> createPrettyPrintVisitor(PrettyPrinter printer); } private static Map<EPackage, Factory> factoryMap = new HashMap<EPackage, Factory>(); public static void addFactory(EPackage ePackage, Factory factory) { factoryMap.put(ePackage, factory); } private static class Fragment { private final int depth; private final String prefix; // null for manditory continuation of previous fragment private final String text; private final String suffix; private Fragment parent = null; private List<Fragment> children = null; private boolean lineWrap = true; private boolean exdented = false; public Fragment(Fragment parent, int depth, String prefix, String text, String suffix) { this.parent = parent; this.depth = depth; this.prefix = prefix; this.text = text; this.suffix = suffix; } public Fragment addChild(String prefix, String text, String suffix) { // assert (prefix.length() + text.length() + suffix.length()) > 0; if (children == null) { children = new ArrayList<Fragment>(); } Fragment child = new Fragment(this, depth+1, prefix, text, suffix); children.add(child); return child; } public void configureLineWrapping(int spacesPerIndent, int lineLength) { int firstColumn = depth * spacesPerIndent; int lastColumn = firstColumn + text.length(); if (prefix != null) { lastColumn += prefix.length(); } if (suffix != null) { lastColumn += suffix.length(); } if (children != null) { for (Fragment child : children) { child.lineWrap = true; child.configureLineWrapping(spacesPerIndent, lineLength); } int allChildrenLength = getChildrenLength(true); if (lastColumn + allChildrenLength <= lineLength) { // System.out.println(depth + " '" + prefix + "'+'" + text + "'+'" + suffix + "' " // + lastColumn + "+" + allChildrenLength + "<=" + lineLength); for (Fragment child : children) { child.lineWrap = false; } } else { // System.out.println(depth + " '" + prefix + "'+'" + text + "'+'" + suffix + "' " // + lastColumn + "+" + allChildrenLength + ">" + lineLength); // int firstChildLength = getChildLength(0); // if (lastColumn + allChildrenLength <= lineLength) { for (Fragment child : children) { child.lineWrap = child.exdented; } // } } // while (lastColumn < lineLength) { // lastColumn = getChildrenLength(spacesPerIndent, lineLength, lastColumn); // } } else { // System.out.println(depth + " '" + prefix + "'+'" + text + "'+'" + suffix + "' " // + lastColumn); } if (parent == null) { lineWrap = false; } } public int getChildrenLength(Boolean concatenate) { int childrenLength = 0; for (int iChild = 0; iChild < children.size(); iChild++) { int childLength = getChildLength(iChild); if (concatenate == Boolean.TRUE) { childrenLength += childLength; } else if (childLength > childrenLength) { childrenLength = childLength; } } return childrenLength; } public int getChildLength(int iChild) { Fragment child = children.get(iChild); int childLength = child.length(); for (int jChild = iChild+1; jChild < children.size(); jChild++) { Fragment nextChild = children.get(jChild); if ((nextChild.prefix != null) && nextChild.lineWrap) { break; } childLength += child.length(); } return childLength; } public int length() { int length = text.length(); if (prefix != null) { length += prefix.length(); } if (suffix != null) { length += suffix.length(); } if (children != null) { length += getChildrenLength(null); } return length; } public Fragment getParent() { return parent; } @Override public String toString() { StringBuilder s = new StringBuilder(); toString(s, null, " "); return s.toString(); } public String toString(StringBuilder s, String newLine, String indent) { if ((lineWrap || (newLine != null)) && (prefix != null)) { if (lineWrap) { newLine = "\n"; } s.append(newLine); if (text.length() > 0) { if ((newLine != null) && newLine.equals("\n")) { for (int i = 1; i < depth; i++) { s.append(indent); } } else { s.append(prefix); } } else if (prefix.length() > 0) { s.append(prefix); } } s.append(text); // newLine = suffix != null ? lineWrap ? "\n" : suffix : null; newLine = suffix; if (children != null) { for (Fragment child : children) { newLine = child.toString(s, newLine, indent); } } return newLine; } } public static PrettyPrinter createNamePrinter(Element element, PrettyPrintOptions options) { return new PrettyPrinter(options, Mode.NAME, element); } public static PrettyPrinter createPrinter(Element element, PrettyPrintOptions options) { return new PrettyPrinter(options, Mode.FULL, element); } public static Global createOptions(Namespace scope) { PrettyPrintOptions.Global options = new PrettyPrintOptions.Global(scope); options.addReservedNames(PrettyPrinter.reservedNameList); options.addRestrictedNames(PrettyPrinter.reservedNameList); options.setUseParentheses(true); return options; } public static String print(Element element) { return print(element, createOptions(null)); } public static String print(Element element, Namespace namespace) { return print(element, createOptions(namespace)); } public static String print(Element element, PrettyPrintOptions options) { if (element == null) { return NULL_PLACEHOLDER; } PrettyPrinter printer = new PrettyPrinter(options, Mode.FULL, element); try { printer.appendElement(element); return printer.toString(); } catch (Exception e) { e.printStackTrace(); return printer.toString() + " ... " + e.getClass().getName() + " - " + e.getLocalizedMessage(); } } public static String printName(Element element) { return printName(element, createOptions(null)); } public static String printName(Element element, Namespace namespace) { return printName(element, createOptions(namespace)); } public static String printName(Element element, PrettyPrintOptions options) { if (element == null) { return NULL_PLACEHOLDER; } PrettyPrinter printer = createNamePrinter(element, options); try { printer.appendElement(element); return printer.toString(); } catch (Exception e) { e.printStackTrace(); return printer.toString() + " ... " + e.getClass().getName() + " - " + e.getLocalizedMessage(); } } public static String printType(Element element) { return printType(element, createOptions(null)); } public static String printType(Element element, Namespace namespace) { return printType(element, createOptions(namespace)); } public static String printType(Element element, PrettyPrintOptions options) { if (element == null) { return NULL_PLACEHOLDER; } PrettyPrinter printer = new PrettyPrinter(options, Mode.TYPE, element); try { printer.appendElement(element); return printer.toString(); } catch (Exception e) { e.printStackTrace(); return printer.toString() + " ... " + e.getClass().getName() + " - " + e.getLocalizedMessage(); } } private enum Mode { TYPE, NAME, FULL }; private final PrettyPrintOptions options; private String pendingPrefix = ""; private StringBuilder pendingText; protected Fragment fragment; private Mode mode; private final AbstractVisitor<Object, PrettyPrinter> visitor; private Namespace scope; private Precedence currentPrecedence = null; /** * Initializes me. * @param element */ private PrettyPrinter(PrettyPrintOptions options, Mode mode, Element element) { this.options = options; this.mode = mode; this.scope = options.getScope(); pendingText = new StringBuilder(); fragment = new Fragment(null, 0, "", "", ""); EObject rootObject = EcoreUtil.getRootContainer(element); // root is a dialect-dependent Model class. EPackage rootPackage = rootObject.eClass().getEPackage(); // rootPackage is dialect-dependent EPackage. Factory factory = factoryMap.get(rootPackage); this.visitor = factory.createPrettyPrintVisitor(this); } public void append(Number number) { if (number != null) { append(number.toString()); } else { append(NULL_PLACEHOLDER); } } protected void append(String string) { if (string != null) { pendingText.append(string); } else { pendingText.append(NULL_PLACEHOLDER); } } public void appendElement(Element element) { visitor.safeVisit(element); } public void appendMultiplicity(int lower, int upper) { PivotUtil.appendMultiplicity(pendingText, lower, upper); } public void appendName(NamedElement object) { appendName(object, options.getRestrictedNames()); } public void appendName(NamedElement object, Set<String> keywords) { append(getName(object, keywords)); } public void appendParameters(Operation operation, boolean withNames) { append("("); String prefix = ""; //$NON-NLS-1$ if (operation instanceof Iteration) { Iteration iteration = (Iteration)operation; for (Parameter parameter : iteration.getOwnedIterator()) { append(prefix); if (withNames) { appendName(parameter); append(" : "); } appendTypedMultiplicity(parameter); prefix = ", "; } if (iteration.getOwnedAccumulator().size() > 0) { prefix = "; "; for (Parameter parameter : iteration.getOwnedAccumulator()) { if (withNames) { appendName(parameter); append(" : "); } append(prefix); appendTypedMultiplicity(parameter); prefix = ", "; } } prefix = " | "; } for (Parameter parameter : operation.getOwnedParameter()) { append(prefix); if (withNames) { appendName(parameter); append(" : "); } appendTypedMultiplicity(parameter); prefix = ", "; } append(")"); } public void appendParent(EObject scope, Element element, String parentSeparator) { // FIXME Use appendQualifiedName instead Mode savedMode = pushMode(Mode.TYPE); try { for (EObject eObject = scope; eObject != null; eObject = eObject.eContainer()) { if (element == eObject) { return; } } // if (toString().length() >= MONIKER_OVERFLOW_LIMIT) { // append(OVERFLOW_MARKER); // } if (element == null) { append(NULL_PLACEHOLDER); } else { // EObject parent = element.eContainer(); - EObject parent = PivotUtil.getNamespace(element.eContainer()); + EObject unspecializedElement = element instanceof TemplateableElement ? ((TemplateableElement)element).getUnspecializedElement() : element; + EObject parent = PivotUtil.getNamespace((unspecializedElement != null ? unspecializedElement : element).eContainer()); if (parent instanceof org.eclipse.ocl.examples.pivot.Package) { String name = ((org.eclipse.ocl.examples.pivot.Package)parent).getName(); if (PivotConstants.ORPHANAGE_NAME.equals(name)) { return; } if (PivotPackage.eNAME.equals(name)) { return; } if ("ocl".equals(name)) { // FIXME constant needed return; } } if ((element instanceof Operation) && (parent instanceof Type) && PivotConstants.ORPHANAGE_NAME.equals(((Type)parent).getName())) { Operation operation = (Operation)element; append(operation.getOwningType().getName()); appendTemplateBindings(operation); append(parentSeparator); return; } MetaModelManager metaModelManager = options.getGlobalOptions().getMetaModelManager(); if ((metaModelManager != null) && (parent instanceof Type)) { parent = (Namespace) metaModelManager.getPrimaryType((Type) parent); } if (parent == scope) { return; } if (parent instanceof Visitable) { List<PathElement> parentPath = PathElement.getPath(parent, metaModelManager); int iMax = parentPath.size(); int i = 0; if (scope != null) { List<PathElement> scopePath = PathElement.getPath(scope, metaModelManager); i = PathElement.getCommonLength(parentPath, scopePath); } if (i < iMax) { // append(parentPath.get(i++).getName()); appendElement(parentPath.get(i++).getElement()); while (i < iMax) { append("::"); // append(parentPath.get(i++).getName()); appendElement(parentPath.get(i++).getElement()); } } // safeVisit((Visitable) parent); } else { assert element instanceof org.eclipse.ocl.examples.pivot.Package || element instanceof ExpressionInOcl : element.eClass().getName(); } } append(parentSeparator); } finally { popMode(savedMode); } } public void appendQualifiedType(Element element) { Mode savedMode = pushMode(Mode.TYPE); try { MetaModelManager metaModelManager = options.getGlobalOptions().getMetaModelManager(); Namespace parent = PivotUtil.getNamespace(element.eContainer()); List<PathElement> parentPath = PathElement.getPath(parent, metaModelManager); int iMax = parentPath.size(); int i = 0; Namespace scope = options.getScope(); if (scope != null) { List<PathElement> scopePath = PathElement.getPath(scope, metaModelManager); i = PathElement.getCommonLength(parentPath, scopePath); } if ((i == 0) && (i < iMax)) { PathElement rootPathElement = parentPath.get(0); String name = rootPathElement.getName(); String alias = options.getAlias((Namespace)rootPathElement.getElement()); if (alias != null) { append(getName(alias, options.getReservedNames())); append("::"); i++; } else if (PivotConstants.ORPHANAGE_NAME.equals(name)) { i++; } else if (PivotPackage.eNAME.equals(name)) { i++; } else if ("ocl".equals(name)) { // FIXME constant needed i++; } else { URI uri = rootPathElement.getElement().eResource().getURI(); if (uri != null) { if (PivotUtil.isPivotURI(uri)) { uri = PivotUtil.getNonPivotURI(uri); } URI baseURI = options.getBaseURI(); if (baseURI != null) { uri = uri.deresolve(baseURI); } append(getName(uri.toString(), options.getReservedNames())); append("::"); i++; } } } while (i < iMax) { appendElement(parentPath.get(i++).getElement()); append("::"); } appendElement(element); } finally { popMode(savedMode); } } public void appendTemplateBindings(TemplateableElement typeRef) { Mode savedMode = pushMode(Mode.TYPE); try { List<TemplateBinding> templateBindings = typeRef.getTemplateBinding(); if (!templateBindings.isEmpty()) { append("("); String prefix = ""; //$NON-NLS-1$ for (TemplateBinding templateBinding : templateBindings) { for (TemplateParameterSubstitution templateParameterSubstitution : templateBinding.getParameterSubstitution()) { append(prefix); Namespace savedScope = pushScope((Namespace) typeRef); try { appendElement(templateParameterSubstitution.getActual()); // appendName((NamedElement) templateParameterSubstitution.getActual()); // FIXME cast, selective scope } finally { popScope(savedScope); } prefix = ", "; } } append(")"); } } finally { popMode(savedMode); } } public void appendTemplateParameters(TemplateableElement templateableElement) { TemplateSignature templateSignature = templateableElement.getOwnedTemplateSignature(); if (templateSignature != null) { List<TemplateParameter> templateParameters = templateSignature.getOwnedParameter(); if (!templateParameters.isEmpty()) { append("("); String prefix = ""; //$NON-NLS-1$ for (TemplateParameter templateParameter : templateParameters) { append(prefix); // emittedTemplateParameter(templateParameter); // appendName((NamedElement) templateParameter.getParameteredElement(), restrictedNames); Namespace savedScope = pushScope((Namespace) templateableElement); try { appendElement(templateParameter); } finally { popScope(savedScope); } prefix = ", "; } append(")"); } } } public void appendTypedMultiplicity(TypedMultiplicityElement object) { int lower = object.getLower().intValue(); int upper = object.getUpper().intValue(); if (upper != 1) { if (object.isOrdered()) { if (object.isUnique()) { append("OrderedSet"); } else { append("Sequence"); } } else { if (object.isUnique()) { append("Set"); } else { append("Bag"); } } append("("); appendElement(object.getType()); if ((lower > 0) || (upper >= 0)) { appendMultiplicity(lower, upper); } append(")"); } else { appendElement(object.getType()); appendMultiplicity(lower, upper); } } public Precedence getCurrentPrecedence() { return currentPrecedence; } public Set<String> getReservedNames() { return options.getReservedNames(); } public Set<String> getRestrictedNames() { return options.getRestrictedNames(); } public Namespace getScope() { return scope; } /** * Emit text to the current indented region. * Start a new indented region. * * If it is not necessary to start a new-line after text, emit suffix instead of the new-line. */ public void push(String text, String suffix) { append(text); // if ((pendingPrefix.length() > 0) || (pendingText.length() > 0)) { fragment = fragment.addChild(pendingPrefix, pendingText.toString(), suffix); fragment.exdented = true; pendingPrefix = ""; pendingText.setLength(0); // } } /** * Flush the current indented region. * Emit text exdented with respect to the current indented region. * Start a new indented region. * * If it is not necessary to start a new-line before text, emit prefix instead of the new-line. * * If it is not necessary to start a new-line after text, emit suffix instead of the new-line. */ public void exdent(String prefix, String text, String suffix) { assert (fragment != null) && (fragment.getParent() != null); if (((pendingPrefix != null) && (pendingPrefix.length() > 0)) || (pendingText.length() > 0)) { fragment.addChild(pendingPrefix, pendingText.toString(), ""); pendingPrefix = ""; pendingText.setLength(0); } if ((prefix.length() > 0) || (text.length() > 0)) { fragment = fragment.getParent().addChild(prefix, text.toString(), suffix); fragment.exdented = true; } } public String getName(NamedElement object, Set<String> keywords) { if (object == null) { return NULL_PLACEHOLDER; } return getName(object.getName(), keywords); } public String getName(String name, Set<String> keywords) { if ((keywords == null) || (!keywords.contains(name)) && PivotUtil.isValidIdentifier(name)) { return name; } StringBuilder s = new StringBuilder(); s.append("_'"); s.append(PivotUtil.convertToOCLString(name)); s.append("'"); return s.toString(); } /** * Flush the current indented region. * Emit text indented with respect to the current indented region. * Start a new indented region. * * If it is not necessary to start a new-line before text, emit prefix instead of the new-line. * * If it is not necessary to start a new-line after text, emit suffix instead of the new-line. */ public void next(String prefix, String text, String suffix) { assert fragment != null; if (((pendingPrefix != null) && (pendingPrefix.length() > 0)) || (pendingText.length() > 0)) { fragment.addChild(pendingPrefix, pendingText.toString(), ""); pendingPrefix = ""; pendingText.setLength(0); } // if ((prefix.length() > 0) || (text.length() > 0)) { fragment.addChild(prefix, text, suffix); // } } /** * Flush the current indented region. * Resume output with one less indentation depth. */ public void pop() { assert fragment != null; if (((pendingPrefix != null) && (pendingPrefix.length() > 0)) || (pendingText.length() > 0)) { fragment.addChild(pendingPrefix, pendingText.toString(), ""); } pendingPrefix = ""; pendingText.setLength(0); assert fragment.getParent() != null; fragment = fragment.getParent(); } public void popMode(Mode oldMode) { mode = oldMode; } public void popScope(Namespace oldScope) { scope = oldScope; } public void precedenceVisit(OclExpression expression, Precedence newPrecedence) { Precedence savedPrecedcence = currentPrecedence; try { currentPrecedence = newPrecedence; appendElement(expression); } finally { currentPrecedence = savedPrecedcence; } } public Mode pushMode(Mode newMode) { Mode oldMode = mode; mode = newMode; return oldMode; } public Namespace pushScope(Namespace newScope) { Namespace oldscope = scope; scope = newScope; return oldscope; } public boolean showNames() { return (mode == Mode.NAME) || (mode == Mode.FULL); } @Override public String toString() { if (fragment == null) { return pendingPrefix + pendingText.toString(); } fragment.configureLineWrapping(options.getIndentStep().length(), options.getLinelength()); StringBuilder s = new StringBuilder(); String newLine = fragment.toString(s, null, " "); return s.toString() + newLine + pendingPrefix + pendingText.toString(); } public String toString(String indent, int lineLength) { if (fragment == null) { return pendingPrefix + pendingText.toString(); } fragment.configureLineWrapping(indent.length(), lineLength); StringBuilder s = new StringBuilder(); fragment.toString(s, null, indent); // System.out.println(s.toString() + "--" + pendingPrefix + "--" + pendingText.toString()); return s.toString() + pendingPrefix + pendingText.toString(); } }
true
true
public void appendParent(EObject scope, Element element, String parentSeparator) { // FIXME Use appendQualifiedName instead Mode savedMode = pushMode(Mode.TYPE); try { for (EObject eObject = scope; eObject != null; eObject = eObject.eContainer()) { if (element == eObject) { return; } } // if (toString().length() >= MONIKER_OVERFLOW_LIMIT) { // append(OVERFLOW_MARKER); // } if (element == null) { append(NULL_PLACEHOLDER); } else { // EObject parent = element.eContainer(); EObject parent = PivotUtil.getNamespace(element.eContainer()); if (parent instanceof org.eclipse.ocl.examples.pivot.Package) { String name = ((org.eclipse.ocl.examples.pivot.Package)parent).getName(); if (PivotConstants.ORPHANAGE_NAME.equals(name)) { return; } if (PivotPackage.eNAME.equals(name)) { return; } if ("ocl".equals(name)) { // FIXME constant needed return; } } if ((element instanceof Operation) && (parent instanceof Type) && PivotConstants.ORPHANAGE_NAME.equals(((Type)parent).getName())) { Operation operation = (Operation)element; append(operation.getOwningType().getName()); appendTemplateBindings(operation); append(parentSeparator); return; } MetaModelManager metaModelManager = options.getGlobalOptions().getMetaModelManager(); if ((metaModelManager != null) && (parent instanceof Type)) { parent = (Namespace) metaModelManager.getPrimaryType((Type) parent); } if (parent == scope) { return; } if (parent instanceof Visitable) { List<PathElement> parentPath = PathElement.getPath(parent, metaModelManager); int iMax = parentPath.size(); int i = 0; if (scope != null) { List<PathElement> scopePath = PathElement.getPath(scope, metaModelManager); i = PathElement.getCommonLength(parentPath, scopePath); } if (i < iMax) { // append(parentPath.get(i++).getName()); appendElement(parentPath.get(i++).getElement()); while (i < iMax) { append("::"); // append(parentPath.get(i++).getName()); appendElement(parentPath.get(i++).getElement()); } } // safeVisit((Visitable) parent); } else { assert element instanceof org.eclipse.ocl.examples.pivot.Package || element instanceof ExpressionInOcl : element.eClass().getName(); } } append(parentSeparator); } finally { popMode(savedMode); } }
public void appendParent(EObject scope, Element element, String parentSeparator) { // FIXME Use appendQualifiedName instead Mode savedMode = pushMode(Mode.TYPE); try { for (EObject eObject = scope; eObject != null; eObject = eObject.eContainer()) { if (element == eObject) { return; } } // if (toString().length() >= MONIKER_OVERFLOW_LIMIT) { // append(OVERFLOW_MARKER); // } if (element == null) { append(NULL_PLACEHOLDER); } else { // EObject parent = element.eContainer(); EObject unspecializedElement = element instanceof TemplateableElement ? ((TemplateableElement)element).getUnspecializedElement() : element; EObject parent = PivotUtil.getNamespace((unspecializedElement != null ? unspecializedElement : element).eContainer()); if (parent instanceof org.eclipse.ocl.examples.pivot.Package) { String name = ((org.eclipse.ocl.examples.pivot.Package)parent).getName(); if (PivotConstants.ORPHANAGE_NAME.equals(name)) { return; } if (PivotPackage.eNAME.equals(name)) { return; } if ("ocl".equals(name)) { // FIXME constant needed return; } } if ((element instanceof Operation) && (parent instanceof Type) && PivotConstants.ORPHANAGE_NAME.equals(((Type)parent).getName())) { Operation operation = (Operation)element; append(operation.getOwningType().getName()); appendTemplateBindings(operation); append(parentSeparator); return; } MetaModelManager metaModelManager = options.getGlobalOptions().getMetaModelManager(); if ((metaModelManager != null) && (parent instanceof Type)) { parent = (Namespace) metaModelManager.getPrimaryType((Type) parent); } if (parent == scope) { return; } if (parent instanceof Visitable) { List<PathElement> parentPath = PathElement.getPath(parent, metaModelManager); int iMax = parentPath.size(); int i = 0; if (scope != null) { List<PathElement> scopePath = PathElement.getPath(scope, metaModelManager); i = PathElement.getCommonLength(parentPath, scopePath); } if (i < iMax) { // append(parentPath.get(i++).getName()); appendElement(parentPath.get(i++).getElement()); while (i < iMax) { append("::"); // append(parentPath.get(i++).getName()); appendElement(parentPath.get(i++).getElement()); } } // safeVisit((Visitable) parent); } else { assert element instanceof org.eclipse.ocl.examples.pivot.Package || element instanceof ExpressionInOcl : element.eClass().getName(); } } append(parentSeparator); } finally { popMode(savedMode); } }
diff --git a/se/sics/mspsim/cli/WindowTarget.java b/se/sics/mspsim/cli/WindowTarget.java index 6c287f0..460f29e 100644 --- a/se/sics/mspsim/cli/WindowTarget.java +++ b/se/sics/mspsim/cli/WindowTarget.java @@ -1,79 +1,87 @@ package se.sics.mspsim.cli; import javax.swing.JFrame; import javax.swing.JTextArea; import se.sics.mspsim.extutil.jfreechart.LineChart; import se.sics.mspsim.extutil.jfreechart.LineSampleChart; public class WindowTarget implements LineListener { private JFrame window; private String targetName; // Default in the current version - TODO: replace with better private JTextArea jta = new JTextArea(40,40); private WindowDataHandler dataHandler = null; public WindowTarget(String name) { window = new JFrame(name); window.getContentPane().add(jta); window.pack(); window.setVisible(true); targetName = name; } @Override public void lineRead(String line) { if (line == null) return; if (line.startsWith("#!")) { line = line.substring(2); String[] parts = CommandParser.parseLine(line); String cmd = parts[0]; if ("bounds".equals(cmd)) { try { window.setBounds(Integer.parseInt(parts[1]), Integer.parseInt(parts[2]), Integer.parseInt(parts[3]), Integer.parseInt(parts[4])); } catch (Exception e) { System.err.println("Could not set bounds: " + line); } } else if ("title".equals(cmd)) { String args = CommandParser.toString(parts, 1, parts.length); window.setTitle(args); if (dataHandler != null) { dataHandler.setProperty("title", new String[] {args}); } } else if ("type".equals(cmd)) { if ("line-sample".equals(parts[1])) { dataHandler = new LineSampleChart(); } else if ("line".equals(parts[1])) { dataHandler = new LineChart(); + } else { + System.err.println("Unknown window data handler type: " + parts[1]); } if (dataHandler != null) { System.out.println("Replacing window data handler! " + parts[1] + " " + dataHandler); window.getContentPane().removeAll(); window.getContentPane().add(dataHandler.getComponent()); + String title = window.getTitle(); + if (title != null) { + // Set title for the new data handler + dataHandler.setProperty("title", new String[] { title }); + } + window.repaint(); } } else if (dataHandler != null) { dataHandler.handleCommand(parts); } } else if (!line.startsWith("#")){ if (dataHandler != null) { dataHandler.lineRead(line); } else { jta.append(line + '\n'); } } } public void close() { // TODO Notify all the currently active "streams" of lines to this windows data-handlers window.setVisible(false); window.dispose(); window.removeAll(); window = null; } public String getName() { return targetName; } }
false
true
public void lineRead(String line) { if (line == null) return; if (line.startsWith("#!")) { line = line.substring(2); String[] parts = CommandParser.parseLine(line); String cmd = parts[0]; if ("bounds".equals(cmd)) { try { window.setBounds(Integer.parseInt(parts[1]), Integer.parseInt(parts[2]), Integer.parseInt(parts[3]), Integer.parseInt(parts[4])); } catch (Exception e) { System.err.println("Could not set bounds: " + line); } } else if ("title".equals(cmd)) { String args = CommandParser.toString(parts, 1, parts.length); window.setTitle(args); if (dataHandler != null) { dataHandler.setProperty("title", new String[] {args}); } } else if ("type".equals(cmd)) { if ("line-sample".equals(parts[1])) { dataHandler = new LineSampleChart(); } else if ("line".equals(parts[1])) { dataHandler = new LineChart(); } if (dataHandler != null) { System.out.println("Replacing window data handler! " + parts[1] + " " + dataHandler); window.getContentPane().removeAll(); window.getContentPane().add(dataHandler.getComponent()); } } else if (dataHandler != null) { dataHandler.handleCommand(parts); } } else if (!line.startsWith("#")){ if (dataHandler != null) { dataHandler.lineRead(line); } else { jta.append(line + '\n'); } } }
public void lineRead(String line) { if (line == null) return; if (line.startsWith("#!")) { line = line.substring(2); String[] parts = CommandParser.parseLine(line); String cmd = parts[0]; if ("bounds".equals(cmd)) { try { window.setBounds(Integer.parseInt(parts[1]), Integer.parseInt(parts[2]), Integer.parseInt(parts[3]), Integer.parseInt(parts[4])); } catch (Exception e) { System.err.println("Could not set bounds: " + line); } } else if ("title".equals(cmd)) { String args = CommandParser.toString(parts, 1, parts.length); window.setTitle(args); if (dataHandler != null) { dataHandler.setProperty("title", new String[] {args}); } } else if ("type".equals(cmd)) { if ("line-sample".equals(parts[1])) { dataHandler = new LineSampleChart(); } else if ("line".equals(parts[1])) { dataHandler = new LineChart(); } else { System.err.println("Unknown window data handler type: " + parts[1]); } if (dataHandler != null) { System.out.println("Replacing window data handler! " + parts[1] + " " + dataHandler); window.getContentPane().removeAll(); window.getContentPane().add(dataHandler.getComponent()); String title = window.getTitle(); if (title != null) { // Set title for the new data handler dataHandler.setProperty("title", new String[] { title }); } window.repaint(); } } else if (dataHandler != null) { dataHandler.handleCommand(parts); } } else if (!line.startsWith("#")){ if (dataHandler != null) { dataHandler.lineRead(line); } else { jta.append(line + '\n'); } } }
diff --git a/parser/src/main/java/parser/flatzinc/ParseAndSolve.java b/parser/src/main/java/parser/flatzinc/ParseAndSolve.java index 01d9a3b55..e88df0f5a 100644 --- a/parser/src/main/java/parser/flatzinc/ParseAndSolve.java +++ b/parser/src/main/java/parser/flatzinc/ParseAndSolve.java @@ -1,229 +1,229 @@ /* * Copyright (c) 1999-2012, Ecole des Mines de Nantes * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Ecole des Mines de Nantes 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 REGENTS 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 REGENTS AND 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 parser.flatzinc; import gnu.trove.map.hash.THashMap; import org.antlr.runtime.ANTLRInputStream; import org.antlr.runtime.CommonTokenStream; import org.antlr.runtime.RecognitionException; import org.antlr.runtime.tree.CommonTree; import org.antlr.runtime.tree.CommonTreeNodeStream; import org.kohsuke.args4j.Argument; import org.kohsuke.args4j.CmdLineException; import org.kohsuke.args4j.CmdLineParser; import org.kohsuke.args4j.Option; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import parser.flatzinc.ast.Exit; import parser.flatzinc.ast.GoalConf; import solver.Solver; import solver.explanations.ExplanationFactory; import solver.propagation.hardcoded.PropagatorEngine; import solver.propagation.hardcoded.SevenQueuesPropagatorEngine; import solver.propagation.hardcoded.VariableEngine; import solver.search.loop.monitors.AverageCSV; import solver.search.strategy.pattern.SearchPattern; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; /** * <br/> * * @author Charles Prud'homme * @since 27/01/11 */ public class ParseAndSolve { protected static final Logger LOGGER = LoggerFactory.getLogger("fzn"); // receives other command line parameters than options @Argument protected List<String> instances = new ArrayList<String>(); @Option(name = "-a", aliases = {"--all"}, usage = "Search for all solutions.", required = false) protected boolean all = false; @Option(name = "-i", aliases = {"--ignore-search"}, usage = "Ignore search strategy.", required = false) protected boolean free = false; @Option(name = "-bbss", usage = "Black box search strategy:\n1(*): activity based\n2: impact based\n3: dom/wdeg", required = false) protected int bbss = 1; @Option(name = "-dv", usage = "Use same decision variables as declared in file (default false)", required = false) protected boolean decision_vars = false; @Option(name = "-seed", usage = "Seed for randomness", required = false) protected long seed = 29091981L; @Option(name = "-p", aliases = {"--nb-cores"}, usage = "Number of cores available for parallel search", required = false) protected int nb_cores = 1; @Option(name = "-tl", aliases = {"--time-limit"}, usage = "Time limit.", required = false) protected long tl = -1; @Option(name = "-e", aliases = {"--engine"}, usage = "Engine Number.\n0: constraint\n1: variable\n2: 7q cstrs\n3: 8q cstrs." + "\n4: 8q vars\n5: abs\n6: arcs\n-1: default", required = false) protected byte eng = -1; @Option(name = "-csv", usage = "CSV file path to trace the results.", required = false) protected String csv = ""; @Option(name = "-sp", usage = "Search pattern.", required = false) protected SearchPattern searchp = SearchPattern.NONE; @Option(name = "-exp", usage = "Explanation engine.", required = false) protected ExplanationFactory expeng = ExplanationFactory.NONE; @Option(name = "-l", aliases = {"--loop"}, usage = "Loooooop.", required = false) protected long l = 1; private boolean userinterruption = true; public static void main(String[] args) throws IOException, InterruptedException, URISyntaxException, RecognitionException { new ParseAndSolve().doMain(args); } public void doMain(String[] args) throws IOException, RecognitionException { CmdLineParser parser = new CmdLineParser(this); parser.setUsageWidth(160); try { parser.parseArgument(args); } catch (CmdLineException e) { System.err.println(e.getMessage()); System.err.println("ParseAndSolve [options...] fzn_instance..."); parser.printUsage(System.err); System.err.println("\nCheck MiniZinc is correctly installed."); System.err.println(); return; } parseandsolve(); } public void buildParser(InputStream is, Solver mSolver, THashMap<String, Object> map, GoalConf gc) { try { // Create an input character stream from standard in ANTLRInputStream input = new ANTLRInputStream(is); // Create an ExprLexer that feeds from that stream FlatzincLexer lexer = new FlatzincLexer(input); // Create a stream of tokens fed by the lexer CommonTokenStream tokens = new CommonTokenStream(lexer); // Create a parser that feeds off the token stream FlatzincParser parser = new FlatzincParser(tokens); // Begin parsing at rule prog, get return value structure FlatzincParser.flatzinc_model_return r = parser.flatzinc_model(); // WALK RESULTING TREE CommonTree t = (CommonTree) r.getTree(); // get tree from parser // Create a tree node stream from resulting tree CommonTreeNodeStream nodes = new CommonTreeNodeStream(t); FlatzincWalker walker = new FlatzincWalker(nodes); // create a tree parser walker.flatzinc_model(mSolver, map, gc); // launch at start rule prog } catch (IOException io) { Exit.log(io.getMessage()); } catch (RecognitionException re) { Exit.log(re.getMessage()); } } protected void parseandsolve() throws IOException { for (final String instance : instances) { AverageCSV acsv = null; if (!csv.equals("")) { acsv = new AverageCSV(csv, l); final AverageCSV finalAcsv = acsv; Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { if (isUserinterruption()) { finalAcsv.record(instance, ";**ERROR**;"); } } }); } GoalConf gc = new GoalConf(free, bbss, decision_vars, all, seed, searchp, tl); for (int i = 0; i < l; i++) { LOGGER.info("% parse instance..."); Solver solver = new Solver(); long creationTime = -System.nanoTime(); THashMap<String, Object> map = new THashMap<String, Object>(); buildParser(new FileInputStream(new File(instance)), solver, map, gc); makeEngine(solver); if (!csv.equals("")) { assert acsv != null; acsv.setSolver(solver); } expeng.make(solver); LOGGER.info("% solve instance..."); solver.getSearchLoop().getMeasures().setReadingTimeCount(creationTime + System.nanoTime()); - solver.getSearchLoop().launch((!solver.getSearchLoop().getObjectivemanager().isOptimization()) || !gc.all); + solver.getSearchLoop().launch((!solver.getSearchLoop().getObjectivemanager().isOptimization()) && !gc.all); } if (!csv.equals("")) { assert acsv != null; acsv.record(instance, gc.getDescription()); } } userinterruption = false; } protected void makeEngine(Solver solver) { switch (eng) { case 0: // let the default propagation strategy, break; case 1: solver.set(new PropagatorEngine(solver)); break; case 2: solver.set(new VariableEngine(solver)); break; case 3: solver.set(new SevenQueuesPropagatorEngine(solver)); break; case -1: default: if (solver.getNbCstrs() > solver.getNbVars()) { solver.set(new VariableEngine(solver)); } else { solver.set(new PropagatorEngine(solver)); } } } private boolean isUserinterruption() { return userinterruption; } }
true
true
protected void parseandsolve() throws IOException { for (final String instance : instances) { AverageCSV acsv = null; if (!csv.equals("")) { acsv = new AverageCSV(csv, l); final AverageCSV finalAcsv = acsv; Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { if (isUserinterruption()) { finalAcsv.record(instance, ";**ERROR**;"); } } }); } GoalConf gc = new GoalConf(free, bbss, decision_vars, all, seed, searchp, tl); for (int i = 0; i < l; i++) { LOGGER.info("% parse instance..."); Solver solver = new Solver(); long creationTime = -System.nanoTime(); THashMap<String, Object> map = new THashMap<String, Object>(); buildParser(new FileInputStream(new File(instance)), solver, map, gc); makeEngine(solver); if (!csv.equals("")) { assert acsv != null; acsv.setSolver(solver); } expeng.make(solver); LOGGER.info("% solve instance..."); solver.getSearchLoop().getMeasures().setReadingTimeCount(creationTime + System.nanoTime()); solver.getSearchLoop().launch((!solver.getSearchLoop().getObjectivemanager().isOptimization()) || !gc.all); } if (!csv.equals("")) { assert acsv != null; acsv.record(instance, gc.getDescription()); } } userinterruption = false; }
protected void parseandsolve() throws IOException { for (final String instance : instances) { AverageCSV acsv = null; if (!csv.equals("")) { acsv = new AverageCSV(csv, l); final AverageCSV finalAcsv = acsv; Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { if (isUserinterruption()) { finalAcsv.record(instance, ";**ERROR**;"); } } }); } GoalConf gc = new GoalConf(free, bbss, decision_vars, all, seed, searchp, tl); for (int i = 0; i < l; i++) { LOGGER.info("% parse instance..."); Solver solver = new Solver(); long creationTime = -System.nanoTime(); THashMap<String, Object> map = new THashMap<String, Object>(); buildParser(new FileInputStream(new File(instance)), solver, map, gc); makeEngine(solver); if (!csv.equals("")) { assert acsv != null; acsv.setSolver(solver); } expeng.make(solver); LOGGER.info("% solve instance..."); solver.getSearchLoop().getMeasures().setReadingTimeCount(creationTime + System.nanoTime()); solver.getSearchLoop().launch((!solver.getSearchLoop().getObjectivemanager().isOptimization()) && !gc.all); } if (!csv.equals("")) { assert acsv != null; acsv.record(instance, gc.getDescription()); } } userinterruption = false; }
diff --git a/src/java/org/smoothbuild/command/err/CommandLineError.java b/src/java/org/smoothbuild/command/err/CommandLineError.java index dcca4a1c..5f382f82 100644 --- a/src/java/org/smoothbuild/command/err/CommandLineError.java +++ b/src/java/org/smoothbuild/command/err/CommandLineError.java @@ -1,9 +1,9 @@ package org.smoothbuild.command.err; import org.smoothbuild.problem.Error; public class CommandLineError extends Error { public CommandLineError(String message) { - super(null, "Incorrect command line:\n" + message); + super(null, "Incorrect command line\n " + message); } }
true
true
public CommandLineError(String message) { super(null, "Incorrect command line:\n" + message); }
public CommandLineError(String message) { super(null, "Incorrect command line\n " + message); }
diff --git a/src/main/java/org/powertac/factoredcustomer/DefaultUtilityOptimizer.java b/src/main/java/org/powertac/factoredcustomer/DefaultUtilityOptimizer.java index 2a37d82..149e8e4 100644 --- a/src/main/java/org/powertac/factoredcustomer/DefaultUtilityOptimizer.java +++ b/src/main/java/org/powertac/factoredcustomer/DefaultUtilityOptimizer.java @@ -1,566 +1,570 @@ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ package org.powertac.factoredcustomer; import java.util.Collections; import java.util.Map; import java.util.HashMap; import java.util.List; import java.util.ArrayList; import java.util.Random; import org.apache.log4j.Logger; import org.powertac.common.Tariff; import org.powertac.common.TariffSubscription; import org.powertac.common.TimeService; import org.powertac.common.Timeslot; import org.powertac.common.repo.RandomSeedRepo; import org.powertac.common.repo.TariffSubscriptionRepo; import org.powertac.common.repo.TimeslotRepo; import org.powertac.common.interfaces.TariffMarket; import org.powertac.common.enumerations.PowerType; import org.powertac.common.spring.SpringApplicationContext; import org.powertac.common.state.Domain; import org.powertac.common.state.StateChange; import org.powertac.factoredcustomer.interfaces.*; import org.powertac.factoredcustomer.TariffSubscriberStructure.AllocationMethod; /** * Key class responsible for managing the tariff(s) for one customer across * multiple capacity bundles if necessary. * * @author Prashant Reddy */ @Domain class DefaultUtilityOptimizer implements UtilityOptimizer { protected Logger log = Logger.getLogger(DefaultUtilityOptimizer.class.getName()); protected final FactoredCustomerService factoredCustomerService; protected final TariffMarket tariffMarketService; protected final TariffSubscriptionRepo tariffSubscriptionRepo; protected final TimeslotRepo timeslotRepo; protected final RandomSeedRepo randomSeedRepo; protected static final int NUM_HOURS_IN_DAY = 24; protected static final long MEAN_TARIFF_DURATION = 5; // number of days protected final CustomerStructure customerStructure; protected final List<CapacityBundle> capacityBundles; protected final List<Tariff> ignoredTariffs = new ArrayList<Tariff>(); protected Random inertiaSampler; protected Random tariffSelector; protected final List<Tariff> allTariffs = new ArrayList<Tariff>(); private int tariffEvaluationCounter = 0; DefaultUtilityOptimizer(CustomerStructure structure, List<CapacityBundle> bundles) { customerStructure = structure; capacityBundles = bundles; factoredCustomerService = (FactoredCustomerService) SpringApplicationContext.getBean("factoredCustomerService"); tariffMarketService = (TariffMarket) SpringApplicationContext.getBean("tariffMarketService"); tariffSubscriptionRepo = (TariffSubscriptionRepo) SpringApplicationContext.getBean("tariffSubscriptionRepo"); timeslotRepo = (TimeslotRepo) SpringApplicationContext.getBean("timeslotRepo"); randomSeedRepo = (RandomSeedRepo) SpringApplicationContext.getBean("randomSeedRepo"); } @Override public void initialize() { inertiaSampler = new Random(randomSeedRepo.getRandomSeed("factoredcustomer.DefaultUtilityOptimizer", customerStructure.structureId, "InertiaSampler").getValue()); tariffSelector = new Random(randomSeedRepo.getRandomSeed("factoredcustomer.DefaultUtilityOptimizer", customerStructure.structureId, "TariffSelector").getValue()); subscribeDefault(); } ///////////////// TARIFF EVALUATION ////////////////////// @StateChange protected void subscribe(Tariff tariff, CapacityBundle bundle, int customerCount, boolean verbose) { tariffMarketService.subscribeToTariff(tariff, bundle.getCustomerInfo(), customerCount); if (verbose) log.info(bundle.getName() + ": Subscribed " + customerCount + " customers to tariff " + tariff.getId() + " successfully"); } @StateChange protected void unsubscribe(TariffSubscription subscription, CapacityBundle bundle, int customerCount, boolean verbose) { subscription.unsubscribe(customerCount); if (verbose) log.info(bundle.getName() + ": Unsubscribed " + customerCount + " customers from tariff " + subscription.getTariff().getId() + " successfully"); } /** @Override hook **/ protected void subscribeDefault() { for (CapacityBundle bundle: capacityBundles) { PowerType powerType = bundle.getPowerType(); if (tariffMarketService.getDefaultTariff(powerType) != null) { log.info(bundle.getName() + ": Subscribing " + bundle.getPopulation() + " customers to default " + powerType + " tariff"); subscribe(tariffMarketService.getDefaultTariff(powerType), bundle, bundle.getPopulation(), false); } else { log.info(bundle.getName() + ": No default tariff for power type " + powerType + "; trying generic type"); PowerType genericType = powerType.getGenericType(); if (tariffMarketService.getDefaultTariff(genericType) == null) { log.error(bundle.getName() + ": No default tariff for generic power type " + genericType + " either!"); } else { log.info(bundle.getName() + ": Subscribing " + bundle.getPopulation() + " customers to default " + genericType + " tariff"); subscribe(tariffMarketService.getDefaultTariff(genericType), bundle, bundle.getPopulation(), false); } } } } @Override public void handleNewTariffs (List<Tariff> newTariffs) { ++tariffEvaluationCounter; for (Tariff tariff: newTariffs) { allTariffs.add(tariff); } for (CapacityBundle bundle: capacityBundles) { evaluateTariffs(bundle, newTariffs); } } private void evaluateTariffs(CapacityBundle bundle, List<Tariff> newTariffs) { if ((tariffEvaluationCounter % bundle.getSubscriberStructure().reconsiderationPeriod) == 0) { reevaluateAllTariffs(bundle); } else if (! ignoredTariffs.isEmpty()) { evaluateCurrentTariffs(bundle, newTariffs); } else if (! newTariffs.isEmpty()) { boolean ignoringNewTariffs = true; for (Tariff tariff: newTariffs) { if (isTariffApplicable(tariff, bundle)) { ignoringNewTariffs = false; evaluateCurrentTariffs(bundle, newTariffs); break; } } if (ignoringNewTariffs) log.info(bundle.getName() + ": New tariffs are not applicable; skipping evaluation"); } } private void reevaluateAllTariffs(CapacityBundle bundle) { log.info(bundle.getName() + ": Reevaluating all tariffs for " + bundle.getPowerType() + " subscriptions"); List<Tariff> evalTariffs = new ArrayList<Tariff>(); for (Tariff tariff: allTariffs) { if (! tariff.isRevoked() && ! tariff.isExpired() && isTariffApplicable(tariff, bundle)) { evalTariffs.add(tariff); } } assertNotEmpty(bundle, evalTariffs); manageSubscriptions(bundle, evalTariffs); } private boolean isTariffApplicable(Tariff tariff, CapacityBundle bundle) { PowerType bundlePowerType = bundle.getCustomerInfo().getPowerType(); if (tariff.getPowerType() == bundlePowerType || tariff.getPowerType() == bundlePowerType.getGenericType()) { return true; } return false; } private void evaluateCurrentTariffs(CapacityBundle bundle, List<Tariff> newTariffs) { if (bundle.getSubscriberStructure().inertiaDistribution != null) { double inertia = bundle.getSubscriberStructure().inertiaDistribution.drawSample(); if (inertiaSampler.nextDouble() < inertia) { log.info(bundle.getName() + ": Skipping " + bundle.getCustomerInfo().getPowerType() + " tariff reevaluation due to inertia"); for (Tariff newTariff: newTariffs) { ignoredTariffs.add(newTariff); } return; } } // Include previously ignored tariffs and currently subscribed tariffs in evaluation. // Use map instead of list to eliminate duplicate tariffs. Map<Long, Tariff> currTariffs = new HashMap<Long, Tariff>(); for (Tariff ignoredTariff: ignoredTariffs) { currTariffs.put(ignoredTariff.getId(), ignoredTariff); } ignoredTariffs.clear(); List<TariffSubscription> subscriptions = tariffSubscriptionRepo.findSubscriptionsForCustomer(bundle.getCustomerInfo()); for (TariffSubscription subscription: subscriptions) { currTariffs.put(subscription.getTariff().getId(), subscription.getTariff()); } for (Tariff newTariff: newTariffs) { currTariffs.put(newTariff.getId(), newTariff); } List<Tariff> evalTariffs = new ArrayList<Tariff>(); for (Tariff tariff: currTariffs.values()) { if (isTariffApplicable(tariff, bundle)) { evalTariffs.add(tariff); } } assertNotEmpty(bundle, evalTariffs); manageSubscriptions(bundle, evalTariffs); } private void assertNotEmpty(CapacityBundle bundle, List<Tariff> evalTariffs) { if (evalTariffs.isEmpty()) { throw new Error(bundle.getName() + ": The evaluation tariffs list is unexpectedly empty!"); } } private void manageSubscriptions(CapacityBundle bundle, List<Tariff> evalTariffs) { Collections.shuffle(evalTariffs); PowerType powerType = bundle.getCustomerInfo().getPowerType(); List<Long> tariffIds = new ArrayList<Long>(evalTariffs.size()); for (Tariff tariff: evalTariffs) tariffIds.add(tariff.getId()); logAllocationDetails(bundle.getName() + ": " + powerType + " tariffs for evaluation: " + tariffIds); List<Double> estimatedPayments = estimatePayments(bundle, evalTariffs); logAllocationDetails(bundle.getName() + ": Estimated payments for evaluated tariffs: " + estimatedPayments); List<Integer> allocations = determineAllocations(bundle, evalTariffs, estimatedPayments); logAllocationDetails(bundle.getName() + ": Allocations for evaluated tariffs: " + allocations); int overAllocations = 0; for (int i=0; i < evalTariffs.size(); ++i) { Tariff evalTariff = evalTariffs.get(i); int allocation = allocations.get(i); TariffSubscription subscription = tariffSubscriptionRepo.findSubscriptionForTariffAndCustomer(evalTariff, bundle.getCustomerInfo()); // could be null int currentCommitted = (subscription != null) ? subscription.getCustomersCommitted() : 0; int numChange = allocation - currentCommitted; log.debug(bundle.getName() + ": evalTariff = " + evalTariff.getId() + ", numChange = " + numChange + ", currentCommitted = " + currentCommitted + ", allocation = " + allocation); if (numChange == 0) { if (currentCommitted > 0) { log.info(bundle.getName() + ": Maintaining " + currentCommitted + " " + powerType + " customers in tariff " + evalTariff.getId()); } else { log.info(bundle.getName() + ": Not allocating any " + powerType + " customers to tariff " + evalTariff.getId()); } } else if (numChange > 0) { if (evalTariff.isExpired()) { overAllocations += numChange; if (currentCommitted > 0) { log.info(bundle.getName() + ": Maintaining " + currentCommitted + " " + powerType + " customers in expired tariff " + evalTariff.getId()); } log.info(bundle.getName() + ": Reallocating " + numChange + " " + powerType + " customers from expired tariff " + evalTariff.getId() + " to other tariffs"); } else { log.info(bundle.getName() + ": Subscribing " + numChange + " " + powerType + " customers to tariff " + evalTariff.getId()); subscribe(evalTariff, bundle, numChange, false); } } else if (numChange < 0) { log.info(bundle.getName() + ": Unsubscribing " + -numChange + " " + powerType + " customers from tariff " + evalTariff.getId()); unsubscribe(subscription, bundle, -numChange, false); } } if (overAllocations > 0) { int minIndex = 0; double minEstimate = Double.POSITIVE_INFINITY; for (int i=0; i < estimatedPayments.size(); ++i) { if (estimatedPayments.get(i) < minEstimate && ! evalTariffs.get(i).isExpired()) { minIndex = i; minEstimate = estimatedPayments.get(i); } } log.info(bundle.getName() + ": Subscribing " + overAllocations + " over-allocated customers to tariff " + evalTariffs.get(minIndex).getId()); subscribe(evalTariffs.get(minIndex), bundle, overAllocations, false); } } private List<Double> estimatePayments(CapacityBundle bundle, List<Tariff> evalTariffs) { List<Double> estimatedPayments = new ArrayList<Double>(evalTariffs.size()); for (int i=0; i < evalTariffs.size(); ++i) { Tariff tariff = evalTariffs.get(i); if (tariff.isExpired()) { if (bundle.getCustomerInfo().getPowerType().isConsumption()) { estimatedPayments.add(Double.POSITIVE_INFINITY); // assume worst case } else { // PRODUCTION or STORAGE estimatedPayments.add(Double.NEGATIVE_INFINITY); // assume worst case } } else { double fixedPayments = estimateFixedTariffPayments(tariff); double variablePayment = forecastDailyUsageCharge(bundle, tariff); double totalPayment = truncateTo2Decimals(fixedPayments + variablePayment); estimatedPayments.add(totalPayment); } } return estimatedPayments; } private double estimateFixedTariffPayments(Tariff tariff) { double lifecyclePayment = tariff.getEarlyWithdrawPayment() + tariff.getSignupPayment(); double minDuration; if (tariff.getMinDuration() == 0) minDuration = MEAN_TARIFF_DURATION * TimeService.DAY; else minDuration = tariff.getMinDuration(); return ((double) tariff.getPeriodicPayment() + (lifecyclePayment / minDuration)); } private double forecastDailyUsageCharge(CapacityBundle bundle, Tariff tariff) { Timeslot hourlyTimeslot = timeslotRepo.currentTimeslot(); double totalUsage = 0.0; double totalCharge = 0.0; for (CapacityOriginator capacityOriginator: bundle.getCapacityOriginators()) { CapacityProfile forecast = capacityOriginator.getCurrentForecast(); for (int i=0; i < CapacityProfile.NUM_TIMESLOTS; ++i) { double usageSign = bundle.getPowerType().isConsumption() ? +1 : -1; double hourlyUsage = usageSign * forecast.getCapacity(i); totalCharge += tariff.getUsageCharge(hourlyTimeslot.getStartInstant(), hourlyUsage, totalUsage); totalUsage += hourlyUsage; } } return totalCharge; } private List<Integer> determineAllocations(CapacityBundle bundle, List<Tariff> evalTariffs, List<Double> estimatedPayments) { if (evalTariffs.size() == 1) { List<Integer> allocations = new ArrayList<Integer>(); allocations.add(bundle.getPopulation()); return allocations; } else { if (bundle.getSubscriberStructure().allocationMethod == AllocationMethod.TOTAL_ORDER) { return determineTotalOrderAllocations(bundle, evalTariffs, estimatedPayments); } else { // LOGIT_CHOICE return determineLogitChoiceAllocations(bundle, evalTariffs, estimatedPayments); } } } private List<Integer> determineTotalOrderAllocations(CapacityBundle bundle, List<Tariff> evalTariffs, List<Double> estimatedPayments) { int numTariffs = evalTariffs.size(); List<Double> allocationRule; if (bundle.getSubscriberStructure().totalOrderRules.isEmpty()) { allocationRule = new ArrayList<Double>(numTariffs); allocationRule.add(1.0); for (int i=1; i < numTariffs; ++i) { allocationRule.add(0.0); } } else if (numTariffs <= bundle.getSubscriberStructure().totalOrderRules.size()) { allocationRule = bundle.getSubscriberStructure().totalOrderRules.get(numTariffs - 1); } else { allocationRule = new ArrayList<Double>(numTariffs); List<Double> largestRule = bundle.getSubscriberStructure().totalOrderRules.get(bundle.getSubscriberStructure().totalOrderRules.size() - 1); for (int i=0; i < numTariffs; ++i) { if (i < largestRule.size()) { allocationRule.add(largestRule.get(i)); } else { allocationRule.add(0.0); } } } // payments are positive for production, so sorting is still valid List<Double> sortedPayments = new ArrayList<Double>(numTariffs); for (double estimatedPayment: estimatedPayments) { sortedPayments.add(estimatedPayment); } Collections.sort(sortedPayments, Collections.reverseOrder()); // we want descending order List<Integer> allocations = new ArrayList<Integer>(numTariffs); for (int i=0; i < numTariffs; ++i) { if (allocationRule.get(i) > 0) { double nextBest = sortedPayments.get(i); for (int j=0; j < numTariffs; ++j) { if (estimatedPayments.get(j) == nextBest) { allocations.add((int) Math.round(bundle.getCustomerInfo().getPopulation() * allocationRule.get(i))); } } } else allocations.add(0); } return allocations; } private List<Integer> determineLogitChoiceAllocations(CapacityBundle bundle, List<Tariff> evalTariffs, List<Double> estimatedPayments) { // logit choice model: p_i = e^(lambda * utility_i) / sum_i(e^(lambda * utility_i)) int numTariffs = evalTariffs.size(); double bestPayment = Collections.max(estimatedPayments); double worstPayment = Collections.min(estimatedPayments); List<Double> probabilities = new ArrayList<Double>(numTariffs); if (bestPayment - worstPayment < 0.01) { // i.e., approximately zero for (int i=0; i < numTariffs; ++i) { probabilities.add(1.0 / numTariffs); } } else { double sumPayments = 0.0; for (int i=0; i < numTariffs; ++i) { sumPayments += estimatedPayments.get(i); } double meanPayment = sumPayments / numTariffs; double lambda = bundle.getSubscriberStructure().logitChoiceRationality; // [0.0 = irrational, 1.0 = perfectly rational] List<Double> numerators = new ArrayList<Double>(numTariffs); double denominator = 0.0; for (int i=0; i < numTariffs; ++i) { double basis = Math.max((bestPayment - meanPayment), (meanPayment - worstPayment)); double utility = ((estimatedPayments.get(i) - meanPayment) / basis) * 3.0; // [-3.0, +3.0] double numerator = Math.exp(lambda * utility); numerators.add(numerator); denominator += numerator; } for (int i=0; i < numTariffs; ++i) { probabilities.add(numerators.get(i) / denominator); } } // Now determine allocations based on above probabilities List<Integer> allocations = new ArrayList<Integer>(numTariffs); int population = bundle.getPopulation(); if (bundle.getCustomerInfo().isMultiContracting()) { int sumAllocations = 0; for (int i=0; i < numTariffs; ++i) { int allocation; if (i < (numTariffs - 1)) { allocation = (int) Math.round(population * probabilities.get(i)); + if ((sumAllocations + allocation) > population) { + allocation = population - sumAllocations; + } sumAllocations += allocation; + if (sumAllocations == population) break; } else { allocation = population - sumAllocations; } allocations.add(allocation); } } else { double r = ((double) tariffSelector.nextInt(100) / 100.0); // [0.0, 1.0] double cumProbability = 0.0; for (int i=0; i < numTariffs; ++i) { cumProbability += probabilities.get(i); if (r <= cumProbability) { allocations.add(population); for (int j=i+1; j < numTariffs; ++j) { allocations.add(0); } break; } else { allocations.add(0); } } } return allocations; } ///////////////// TIMESLOT ACTIVITY ////////////////////// @Override public void handleNewTimeslot(Timeslot timeslot) { checkRevokedSubscriptions(); usePower(timeslot); } private void checkRevokedSubscriptions() { for (CapacityBundle bundle: capacityBundles) { List<TariffSubscription> revoked = tariffSubscriptionRepo.getRevokedSubscriptionList(bundle.getCustomerInfo()); for (TariffSubscription revokedSubscription : revoked) { revokedSubscription.handleRevokedTariff(); } } } private void usePower(Timeslot timeslot) { for (CapacityBundle bundle: capacityBundles) { List<TariffSubscription> subscriptions = tariffSubscriptionRepo.findSubscriptionsForCustomer(bundle.getCustomerInfo()); double totalCapacity = 0.0; double totalUsageCharge = 0.0; for (TariffSubscription subscription: subscriptions) { if (subscription.getCustomersCommitted() > 0) { double usageSign = bundle.getPowerType().isConsumption() ? +1 : -1; double currCapacity = usageSign * useCapacity(subscription, bundle); if (factoredCustomerService.getUsageChargesLogging() == true) { double charge = subscription.getTariff().getUsageCharge(currCapacity, subscription.getTotalUsage(), false); totalUsageCharge += charge; } subscription.usePower(currCapacity); totalCapacity += currCapacity; } } log.info(bundle.getName() + ": Total " + bundle.getPowerType() + " capacity for timeslot " + timeslot.getSerialNumber() + " = " + totalCapacity); logUsageCharges(bundle.getName() + ": Total " + bundle.getPowerType() + " usage charge for timeslot " + timeslot.getSerialNumber() + " = " + totalUsageCharge); } } public double useCapacity(TariffSubscription subscription, CapacityBundle bundle) { double capacity = 0; for (CapacityOriginator capacityOriginator: bundle.getCapacityOriginators()) { capacity += capacityOriginator.useCapacity(subscription); } return capacity; } protected String getCustomerName() { return customerStructure.name; } protected double truncateTo2Decimals(double x) { double fract, whole; if (x > 0) { whole = Math.floor(x); fract = Math.floor((x - whole) * 100) / 100; } else { whole = Math.ceil(x); fract = Math.ceil((x - whole) * 100) / 100; } return whole + fract; } private void logAllocationDetails(String msg) { if (factoredCustomerService.getAllocationDetailsLogging() == true) { log.info(msg); } } private void logUsageCharges(String msg) { if (factoredCustomerService.getUsageChargesLogging() == true) { log.info(msg); } } @Override public String toString() { return this.getClass().getCanonicalName() + ":" + getCustomerName(); } } // end class
false
true
private List<Integer> determineLogitChoiceAllocations(CapacityBundle bundle, List<Tariff> evalTariffs, List<Double> estimatedPayments) { // logit choice model: p_i = e^(lambda * utility_i) / sum_i(e^(lambda * utility_i)) int numTariffs = evalTariffs.size(); double bestPayment = Collections.max(estimatedPayments); double worstPayment = Collections.min(estimatedPayments); List<Double> probabilities = new ArrayList<Double>(numTariffs); if (bestPayment - worstPayment < 0.01) { // i.e., approximately zero for (int i=0; i < numTariffs; ++i) { probabilities.add(1.0 / numTariffs); } } else { double sumPayments = 0.0; for (int i=0; i < numTariffs; ++i) { sumPayments += estimatedPayments.get(i); } double meanPayment = sumPayments / numTariffs; double lambda = bundle.getSubscriberStructure().logitChoiceRationality; // [0.0 = irrational, 1.0 = perfectly rational] List<Double> numerators = new ArrayList<Double>(numTariffs); double denominator = 0.0; for (int i=0; i < numTariffs; ++i) { double basis = Math.max((bestPayment - meanPayment), (meanPayment - worstPayment)); double utility = ((estimatedPayments.get(i) - meanPayment) / basis) * 3.0; // [-3.0, +3.0] double numerator = Math.exp(lambda * utility); numerators.add(numerator); denominator += numerator; } for (int i=0; i < numTariffs; ++i) { probabilities.add(numerators.get(i) / denominator); } } // Now determine allocations based on above probabilities List<Integer> allocations = new ArrayList<Integer>(numTariffs); int population = bundle.getPopulation(); if (bundle.getCustomerInfo().isMultiContracting()) { int sumAllocations = 0; for (int i=0; i < numTariffs; ++i) { int allocation; if (i < (numTariffs - 1)) { allocation = (int) Math.round(population * probabilities.get(i)); sumAllocations += allocation; } else { allocation = population - sumAllocations; } allocations.add(allocation); } } else { double r = ((double) tariffSelector.nextInt(100) / 100.0); // [0.0, 1.0] double cumProbability = 0.0; for (int i=0; i < numTariffs; ++i) { cumProbability += probabilities.get(i); if (r <= cumProbability) { allocations.add(population); for (int j=i+1; j < numTariffs; ++j) { allocations.add(0); } break; } else { allocations.add(0); } } } return allocations; }
private List<Integer> determineLogitChoiceAllocations(CapacityBundle bundle, List<Tariff> evalTariffs, List<Double> estimatedPayments) { // logit choice model: p_i = e^(lambda * utility_i) / sum_i(e^(lambda * utility_i)) int numTariffs = evalTariffs.size(); double bestPayment = Collections.max(estimatedPayments); double worstPayment = Collections.min(estimatedPayments); List<Double> probabilities = new ArrayList<Double>(numTariffs); if (bestPayment - worstPayment < 0.01) { // i.e., approximately zero for (int i=0; i < numTariffs; ++i) { probabilities.add(1.0 / numTariffs); } } else { double sumPayments = 0.0; for (int i=0; i < numTariffs; ++i) { sumPayments += estimatedPayments.get(i); } double meanPayment = sumPayments / numTariffs; double lambda = bundle.getSubscriberStructure().logitChoiceRationality; // [0.0 = irrational, 1.0 = perfectly rational] List<Double> numerators = new ArrayList<Double>(numTariffs); double denominator = 0.0; for (int i=0; i < numTariffs; ++i) { double basis = Math.max((bestPayment - meanPayment), (meanPayment - worstPayment)); double utility = ((estimatedPayments.get(i) - meanPayment) / basis) * 3.0; // [-3.0, +3.0] double numerator = Math.exp(lambda * utility); numerators.add(numerator); denominator += numerator; } for (int i=0; i < numTariffs; ++i) { probabilities.add(numerators.get(i) / denominator); } } // Now determine allocations based on above probabilities List<Integer> allocations = new ArrayList<Integer>(numTariffs); int population = bundle.getPopulation(); if (bundle.getCustomerInfo().isMultiContracting()) { int sumAllocations = 0; for (int i=0; i < numTariffs; ++i) { int allocation; if (i < (numTariffs - 1)) { allocation = (int) Math.round(population * probabilities.get(i)); if ((sumAllocations + allocation) > population) { allocation = population - sumAllocations; } sumAllocations += allocation; if (sumAllocations == population) break; } else { allocation = population - sumAllocations; } allocations.add(allocation); } } else { double r = ((double) tariffSelector.nextInt(100) / 100.0); // [0.0, 1.0] double cumProbability = 0.0; for (int i=0; i < numTariffs; ++i) { cumProbability += probabilities.get(i); if (r <= cumProbability) { allocations.add(population); for (int j=i+1; j < numTariffs; ++j) { allocations.add(0); } break; } else { allocations.add(0); } } } return allocations; }
diff --git a/grails/test/web/org/codehaus/groovy/grails/web/pages/GroovyPageResourceLoaderTests.java b/grails/test/web/org/codehaus/groovy/grails/web/pages/GroovyPageResourceLoaderTests.java index acc1990d8..ffcd8fed5 100644 --- a/grails/test/web/org/codehaus/groovy/grails/web/pages/GroovyPageResourceLoaderTests.java +++ b/grails/test/web/org/codehaus/groovy/grails/web/pages/GroovyPageResourceLoaderTests.java @@ -1,40 +1,40 @@ /* Copyright 2004-2005 Graeme Rocher * * 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.codehaus.groovy.grails.web.pages; import junit.framework.TestCase; /** * Tests for the development ResourceLoader instance of Groovy Server Pages. * * @author Graeme Rocher * @since 0.5 * * <p/> * Created: Feb 26, 2007 * Time: 5:44:06 PM */ public class GroovyPageResourceLoaderTests extends TestCase { public void testGetRealLocationInProject() { GroovyPageResourceLoader rl = new GroovyPageResourceLoader(); - assertEquals("/grails-app/views/layouts/main.gsp", rl.getRealLocationInProject("/WEB-INF/grails-app/views/layouts/main.gsp")); - assertEquals("/grails-app/views/books/list.gsp", rl.getRealLocationInProject("/WEB-INF/grails-app/views/books/list.gsp")); - assertEquals("/grails-app/views/_template.gsp",rl.getRealLocationInProject( "/WEB-INF/grails-app/views/_template.gsp")); - assertEquals("/web-app/other.gsp", rl.getRealLocationInProject("/other.gsp")); - assertEquals("/web-app/somedir/other.gsp",rl.getRealLocationInProject( "/somedir/other.gsp")); + assertEquals("grails-app/views/layouts/main.gsp", rl.getRealLocationInProject("/WEB-INF/grails-app/views/layouts/main.gsp")); + assertEquals("grails-app/views/books/list.gsp", rl.getRealLocationInProject("/WEB-INF/grails-app/views/books/list.gsp")); + assertEquals("grails-app/views/_template.gsp",rl.getRealLocationInProject( "/WEB-INF/grails-app/views/_template.gsp")); + assertEquals("web-app/other.gsp", rl.getRealLocationInProject("/other.gsp")); + assertEquals("web-app/somedir/other.gsp",rl.getRealLocationInProject( "/somedir/other.gsp")); } }
true
true
public void testGetRealLocationInProject() { GroovyPageResourceLoader rl = new GroovyPageResourceLoader(); assertEquals("/grails-app/views/layouts/main.gsp", rl.getRealLocationInProject("/WEB-INF/grails-app/views/layouts/main.gsp")); assertEquals("/grails-app/views/books/list.gsp", rl.getRealLocationInProject("/WEB-INF/grails-app/views/books/list.gsp")); assertEquals("/grails-app/views/_template.gsp",rl.getRealLocationInProject( "/WEB-INF/grails-app/views/_template.gsp")); assertEquals("/web-app/other.gsp", rl.getRealLocationInProject("/other.gsp")); assertEquals("/web-app/somedir/other.gsp",rl.getRealLocationInProject( "/somedir/other.gsp")); }
public void testGetRealLocationInProject() { GroovyPageResourceLoader rl = new GroovyPageResourceLoader(); assertEquals("grails-app/views/layouts/main.gsp", rl.getRealLocationInProject("/WEB-INF/grails-app/views/layouts/main.gsp")); assertEquals("grails-app/views/books/list.gsp", rl.getRealLocationInProject("/WEB-INF/grails-app/views/books/list.gsp")); assertEquals("grails-app/views/_template.gsp",rl.getRealLocationInProject( "/WEB-INF/grails-app/views/_template.gsp")); assertEquals("web-app/other.gsp", rl.getRealLocationInProject("/other.gsp")); assertEquals("web-app/somedir/other.gsp",rl.getRealLocationInProject( "/somedir/other.gsp")); }
diff --git a/aop-mc-int/src/main/org/jboss/aop/microcontainer/beans/beanmetadatafactory/StackBeanMetaDataFactory.java b/aop-mc-int/src/main/org/jboss/aop/microcontainer/beans/beanmetadatafactory/StackBeanMetaDataFactory.java index bd27bfb9..ddf5e11e 100644 --- a/aop-mc-int/src/main/org/jboss/aop/microcontainer/beans/beanmetadatafactory/StackBeanMetaDataFactory.java +++ b/aop-mc-int/src/main/org/jboss/aop/microcontainer/beans/beanmetadatafactory/StackBeanMetaDataFactory.java @@ -1,105 +1,105 @@ /* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.aop.microcontainer.beans.beanmetadatafactory; import java.util.ArrayList; import java.util.List; import org.jboss.aop.microcontainer.beans.Stack; import org.jboss.beans.metadata.plugins.AbstractBeanMetaData; import org.jboss.beans.metadata.plugins.AbstractInjectionValueMetaData; import org.jboss.beans.metadata.plugins.AbstractListMetaData; import org.jboss.beans.metadata.spi.BeanMetaData; /** * * @author <a href="[email protected]">Kabir Khan</a> * @version $Revision: 1.1 $ */ public class StackBeanMetaDataFactory extends AspectManagerAwareBeanMetaDataFactory { private static final long serialVersionUID = 1L; private List<BaseInterceptorData> interceptors = new ArrayList<BaseInterceptorData>(); public StackBeanMetaDataFactory() { //Meeded to satisfy validation in BeanFactoryHandler.endElement() setBeanClass("IGNORED"); } @Override public List<BeanMetaData> getBeans() { ArrayList<BeanMetaData> result = new ArrayList<BeanMetaData>(); //Create AspectBinding AbstractBeanMetaData stack = new AbstractBeanMetaData(); stack.setName(name); BeanMetaDataUtil.setSimpleProperty(stack, "name", name); stack.setBean(Stack.class.getName()); util.setAspectManagerProperty(stack, "manager"); result.add(stack); if (interceptors.size() > 0) { AbstractListMetaData almd = new AbstractListMetaData(); int i = 0; for (BaseInterceptorData interceptor : interceptors) { AbstractBeanMetaData bmd = new AbstractBeanMetaData(interceptor.getBeanClassName()); String intName = name + "$" + i++; bmd.setName(intName); util.setAspectManagerProperty(bmd, "manager"); BeanMetaDataUtil.setSimpleProperty(bmd, "forStack", Boolean.TRUE); if (interceptor instanceof AdviceData) { BeanMetaDataUtil.DependencyBuilder db = new BeanMetaDataUtil.DependencyBuilder(bmd, "aspect", interceptor.getRefName()); BeanMetaDataUtil.setDependencyProperty(db); if (((AdviceData)interceptor).getAdviceMethod() != null) { BeanMetaDataUtil.setSimpleProperty(bmd, "aspectMethod", ((AdviceData)interceptor).getAdviceMethod()); } BeanMetaDataUtil.setSimpleProperty(bmd, "type", ((AdviceData)interceptor).getType()); } else { BeanMetaDataUtil.DependencyBuilder db = new BeanMetaDataUtil.DependencyBuilder(bmd, "stack", interceptor.getRefName()); BeanMetaDataUtil.setDependencyProperty(db); } result.add(bmd); almd.add(new AbstractInjectionValueMetaData(intName)); - BeanMetaDataUtil.setSimpleProperty(stack, "advices", almd); } + BeanMetaDataUtil.setSimpleProperty(stack, "advices", almd); } return result; } public void addInterceptor(BaseInterceptorData interceptorData) { interceptors.add(interceptorData); } }
false
true
public List<BeanMetaData> getBeans() { ArrayList<BeanMetaData> result = new ArrayList<BeanMetaData>(); //Create AspectBinding AbstractBeanMetaData stack = new AbstractBeanMetaData(); stack.setName(name); BeanMetaDataUtil.setSimpleProperty(stack, "name", name); stack.setBean(Stack.class.getName()); util.setAspectManagerProperty(stack, "manager"); result.add(stack); if (interceptors.size() > 0) { AbstractListMetaData almd = new AbstractListMetaData(); int i = 0; for (BaseInterceptorData interceptor : interceptors) { AbstractBeanMetaData bmd = new AbstractBeanMetaData(interceptor.getBeanClassName()); String intName = name + "$" + i++; bmd.setName(intName); util.setAspectManagerProperty(bmd, "manager"); BeanMetaDataUtil.setSimpleProperty(bmd, "forStack", Boolean.TRUE); if (interceptor instanceof AdviceData) { BeanMetaDataUtil.DependencyBuilder db = new BeanMetaDataUtil.DependencyBuilder(bmd, "aspect", interceptor.getRefName()); BeanMetaDataUtil.setDependencyProperty(db); if (((AdviceData)interceptor).getAdviceMethod() != null) { BeanMetaDataUtil.setSimpleProperty(bmd, "aspectMethod", ((AdviceData)interceptor).getAdviceMethod()); } BeanMetaDataUtil.setSimpleProperty(bmd, "type", ((AdviceData)interceptor).getType()); } else { BeanMetaDataUtil.DependencyBuilder db = new BeanMetaDataUtil.DependencyBuilder(bmd, "stack", interceptor.getRefName()); BeanMetaDataUtil.setDependencyProperty(db); } result.add(bmd); almd.add(new AbstractInjectionValueMetaData(intName)); BeanMetaDataUtil.setSimpleProperty(stack, "advices", almd); } } return result; }
public List<BeanMetaData> getBeans() { ArrayList<BeanMetaData> result = new ArrayList<BeanMetaData>(); //Create AspectBinding AbstractBeanMetaData stack = new AbstractBeanMetaData(); stack.setName(name); BeanMetaDataUtil.setSimpleProperty(stack, "name", name); stack.setBean(Stack.class.getName()); util.setAspectManagerProperty(stack, "manager"); result.add(stack); if (interceptors.size() > 0) { AbstractListMetaData almd = new AbstractListMetaData(); int i = 0; for (BaseInterceptorData interceptor : interceptors) { AbstractBeanMetaData bmd = new AbstractBeanMetaData(interceptor.getBeanClassName()); String intName = name + "$" + i++; bmd.setName(intName); util.setAspectManagerProperty(bmd, "manager"); BeanMetaDataUtil.setSimpleProperty(bmd, "forStack", Boolean.TRUE); if (interceptor instanceof AdviceData) { BeanMetaDataUtil.DependencyBuilder db = new BeanMetaDataUtil.DependencyBuilder(bmd, "aspect", interceptor.getRefName()); BeanMetaDataUtil.setDependencyProperty(db); if (((AdviceData)interceptor).getAdviceMethod() != null) { BeanMetaDataUtil.setSimpleProperty(bmd, "aspectMethod", ((AdviceData)interceptor).getAdviceMethod()); } BeanMetaDataUtil.setSimpleProperty(bmd, "type", ((AdviceData)interceptor).getType()); } else { BeanMetaDataUtil.DependencyBuilder db = new BeanMetaDataUtil.DependencyBuilder(bmd, "stack", interceptor.getRefName()); BeanMetaDataUtil.setDependencyProperty(db); } result.add(bmd); almd.add(new AbstractInjectionValueMetaData(intName)); } BeanMetaDataUtil.setSimpleProperty(stack, "advices", almd); } return result; }
diff --git a/org.eclipse.mylyn.tasks.core/src/org/eclipse/mylyn/internal/tasks/core/TaskRepositoryChangeEvent.java b/org.eclipse.mylyn.tasks.core/src/org/eclipse/mylyn/internal/tasks/core/TaskRepositoryChangeEvent.java index 422e75e10..f12dfeeec 100644 --- a/org.eclipse.mylyn.tasks.core/src/org/eclipse/mylyn/internal/tasks/core/TaskRepositoryChangeEvent.java +++ b/org.eclipse.mylyn.tasks.core/src/org/eclipse/mylyn/internal/tasks/core/TaskRepositoryChangeEvent.java @@ -1,47 +1,47 @@ /******************************************************************************* * Copyright (c) 2009 Tasktop Technologies 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: * Tasktop Technologies - initial API and implementation *******************************************************************************/ package org.eclipse.mylyn.internal.tasks.core; import java.util.EventObject; import org.eclipse.core.runtime.Assert; import org.eclipse.mylyn.tasks.core.TaskRepository; /** * @author Steffen Pingel */ public class TaskRepositoryChangeEvent extends EventObject { private static final long serialVersionUID = -8177578930986469693L; private final TaskRepository repository; private final TaskRepositoryDelta delta; - TaskRepositoryChangeEvent(Object source, TaskRepository repository, TaskRepositoryDelta delta) { + public TaskRepositoryChangeEvent(Object source, TaskRepository repository, TaskRepositoryDelta delta) { super(source); Assert.isNotNull(source); Assert.isNotNull(repository); Assert.isNotNull(delta); this.repository = repository; this.delta = delta; } public TaskRepository getRepository() { return repository; } public TaskRepositoryDelta getDelta() { return delta; } }
true
true
TaskRepositoryChangeEvent(Object source, TaskRepository repository, TaskRepositoryDelta delta) { super(source); Assert.isNotNull(source); Assert.isNotNull(repository); Assert.isNotNull(delta); this.repository = repository; this.delta = delta; }
public TaskRepositoryChangeEvent(Object source, TaskRepository repository, TaskRepositoryDelta delta) { super(source); Assert.isNotNull(source); Assert.isNotNull(repository); Assert.isNotNull(delta); this.repository = repository; this.delta = delta; }
diff --git a/MPAnalyzer/src/jp/ac/osaka_u/ist/sdl/mpanalyzer/gui/rlist/RList.java b/MPAnalyzer/src/jp/ac/osaka_u/ist/sdl/mpanalyzer/gui/rlist/RList.java index ea80c68..b2cb7ef 100644 --- a/MPAnalyzer/src/jp/ac/osaka_u/ist/sdl/mpanalyzer/gui/rlist/RList.java +++ b/MPAnalyzer/src/jp/ac/osaka_u/ist/sdl/mpanalyzer/gui/rlist/RList.java @@ -1,103 +1,104 @@ package jp.ac.osaka_u.ist.sdl.mpanalyzer.gui.rlist; import java.awt.Color; import java.awt.GridLayout; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.SortedSet; import java.util.TreeSet; import javax.swing.ButtonGroup; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JScrollPane; import javax.swing.border.LineBorder; import javax.swing.border.TitledBorder; import jp.ac.osaka_u.ist.sdl.mpanalyzer.data.Revision; import jp.ac.osaka_u.ist.sdl.mpanalyzer.db.ReadOnlyDAO; public class RList extends JPanel { final public JScrollPane scrollPane; final ButtonGroup group; final Map<JRadioButton, Revision> buttonRevisionMap; public RList() { super(); this.group = new ButtonGroup(); this.buttonRevisionMap = new HashMap<JRadioButton, Revision>(); try { final SortedSet<Revision> revisions = new TreeSet<Revision>( new Comparator<Revision>() { @Override public int compare(final Revision r1, final Revision r2) { if (r1.number < r2.number) { return 1; } else if (r1.number > r2.number) { return -1; } else { return 0; } } }); - final int threshold = 100; +// final int threshold = 100; revisions.addAll(ReadOnlyDAO.getInstance().getRevisions()); - this.setLayout(new GridLayout( - revisions.size() < threshold ? revisions.size() : threshold, - 1)); +// this.setLayout(new GridLayout( +// revisions.size() < threshold ? revisions.size() : threshold, +// 1)); + this.setLayout(new GridLayout(revisions.size(), 1)); int number = 0; for (final Revision revision : revisions) { final StringBuilder text = new StringBuilder(); text.append(revision.number); text.append(" ("); text.append(revision.date); text.append(")"); final JRadioButton button = new JRadioButton(text.toString(), true); this.group.add(button); this.add(button); this.buttonRevisionMap.put(button, revision); if (100 < ++number) { break; } } } catch (final Exception e) { this.add(new JLabel("Error happened in getting revisions.")); } this.scrollPane = new JScrollPane(); this.scrollPane.setViewportView(this); this.scrollPane .setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); this.scrollPane .setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); this.scrollPane.setBorder(new TitledBorder(new LineBorder(Color.black), "Revisions")); } public final long getSelectedRevision() { for (final Entry<JRadioButton, Revision> entry : this.buttonRevisionMap .entrySet()) { if (entry.getKey().isSelected()) { return entry.getValue().number; } } return 0; // Object[] selectedObjects = this.group.getSelection() // .getSelectedObjects(); // if (null != selectedObjects) { // return Long.parseLong((String) selectedObjects[0]); // } else { // return 0; // } } }
false
true
public RList() { super(); this.group = new ButtonGroup(); this.buttonRevisionMap = new HashMap<JRadioButton, Revision>(); try { final SortedSet<Revision> revisions = new TreeSet<Revision>( new Comparator<Revision>() { @Override public int compare(final Revision r1, final Revision r2) { if (r1.number < r2.number) { return 1; } else if (r1.number > r2.number) { return -1; } else { return 0; } } }); final int threshold = 100; revisions.addAll(ReadOnlyDAO.getInstance().getRevisions()); this.setLayout(new GridLayout( revisions.size() < threshold ? revisions.size() : threshold, 1)); int number = 0; for (final Revision revision : revisions) { final StringBuilder text = new StringBuilder(); text.append(revision.number); text.append(" ("); text.append(revision.date); text.append(")"); final JRadioButton button = new JRadioButton(text.toString(), true); this.group.add(button); this.add(button); this.buttonRevisionMap.put(button, revision); if (100 < ++number) { break; } } } catch (final Exception e) { this.add(new JLabel("Error happened in getting revisions.")); } this.scrollPane = new JScrollPane(); this.scrollPane.setViewportView(this); this.scrollPane .setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); this.scrollPane .setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); this.scrollPane.setBorder(new TitledBorder(new LineBorder(Color.black), "Revisions")); }
public RList() { super(); this.group = new ButtonGroup(); this.buttonRevisionMap = new HashMap<JRadioButton, Revision>(); try { final SortedSet<Revision> revisions = new TreeSet<Revision>( new Comparator<Revision>() { @Override public int compare(final Revision r1, final Revision r2) { if (r1.number < r2.number) { return 1; } else if (r1.number > r2.number) { return -1; } else { return 0; } } }); // final int threshold = 100; revisions.addAll(ReadOnlyDAO.getInstance().getRevisions()); // this.setLayout(new GridLayout( // revisions.size() < threshold ? revisions.size() : threshold, // 1)); this.setLayout(new GridLayout(revisions.size(), 1)); int number = 0; for (final Revision revision : revisions) { final StringBuilder text = new StringBuilder(); text.append(revision.number); text.append(" ("); text.append(revision.date); text.append(")"); final JRadioButton button = new JRadioButton(text.toString(), true); this.group.add(button); this.add(button); this.buttonRevisionMap.put(button, revision); if (100 < ++number) { break; } } } catch (final Exception e) { this.add(new JLabel("Error happened in getting revisions.")); } this.scrollPane = new JScrollPane(); this.scrollPane.setViewportView(this); this.scrollPane .setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); this.scrollPane .setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); this.scrollPane.setBorder(new TitledBorder(new LineBorder(Color.black), "Revisions")); }
diff --git a/common/plugins/org.jboss.tools.common.model/src/org/jboss/tools/common/model/filesystems/impl/JarFolderImpl.java b/common/plugins/org.jboss.tools.common.model/src/org/jboss/tools/common/model/filesystems/impl/JarFolderImpl.java index f60e5e545..bc2ea2ea8 100644 --- a/common/plugins/org.jboss.tools.common.model/src/org/jboss/tools/common/model/filesystems/impl/JarFolderImpl.java +++ b/common/plugins/org.jboss.tools.common.model/src/org/jboss/tools/common/model/filesystems/impl/JarFolderImpl.java @@ -1,187 +1,187 @@ /******************************************************************************* * Copyright (c) 2007 Exadel, Inc. and Red Hat, Inc. * Distributed under license by Red Hat, Inc. All rights reserved. * This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Exadel, Inc. and Red Hat, Inc. - initial API and implementation ******************************************************************************/ package org.jboss.tools.common.model.filesystems.impl; import java.util.*; import org.jboss.tools.common.model.*; import org.jboss.tools.common.model.impl.*; import org.jboss.tools.common.model.loaders.*; import org.jboss.tools.common.model.util.*; import org.jboss.tools.common.model.filesystems.*; public class JarFolderImpl extends RegularObjectImpl implements FolderLoader { private static final long serialVersionUID = 7958999905551184060L; protected boolean loaded = false; public JarFolderImpl() {} public int getFileType() { return FOLDER; } protected Comparator<XModelObject> createComparator() { return new FileObjectComparator(); } protected JarSystemImpl getJarSystem() { JarFolderImpl folder = (JarFolderImpl)getParent(); return (folder == null) ? null : folder.getJarSystem(); } public boolean isObjectEditable() { return false; } protected String getAbsolutePath() { String p = (getParent() == null) ? null : ((JarFolderImpl)getParent()).getAbsolutePath(); if(p != null && p.length() > 0) p += XModelObjectConstants.SEPARATOR; return (p == null) ? null : p + name(); } public BodySource getBodySource(String filename) { String path = getAbsolutePath(); if(path == null) return null; String cpath = (path.length() == 0) ? filename : path + XModelObjectConstants.SEPARATOR + filename; return new JarBodySource(getJarSystem().getJarAccess(), cpath); } protected void loadChildren() { if(loaded || !isActive()) return; JarAccess jar = getJarSystem().getJarAccess(); if(!jar.isLoaded()) return; jar.lockJar(); String path = getAbsolutePath(); String[] cs = jar.getChildren(path); Properties p = new Properties(); for (int i = 0; i < cs.length && !loaded; i++) { boolean d = cs[i].endsWith(XModelObjectConstants.SEPARATOR); if(d) cs[i] = cs[i].substring(0, cs[i].length() - 1); if(children.getObject(FilePathHelper.toPathPath(cs[i])) != null) { continue; } if(d) { p.clear(); p.setProperty(XModelObjectConstants.ATTR_NAME, cs[i]); XModelObject c = getModel().createModelObject("JarFolder", p); //$NON-NLS-1$ addChild(c); } else { createFileObject(jar, path, cs[i], true); } } fire = true; jar.unlockJar(); loaded = true; } private XModelObject createFileObject(JarAccess jar, String path, String name, boolean add) { String cpath = (path.length() == 0) ? name : path + XModelObjectConstants.SEPARATOR + name; Properties p = new Properties(); FolderImpl.parseFileName(p, name); String ext = p.getProperty(XModelObjectConstants.ATTR_NAME_EXTENSION); String body = null; String entity = getModel().getEntityRecognizer().getEntityName(new EntityRecognizerContext(name, ext, body)); if("FileAny".equals(entity)) { //$NON-NLS-1$ if(jar.getSize(cpath) > 100000) entity = XModelObjectConstants.ENT_FILE_ANY_LONG; else if(jar.isTextEntry(cpath, 100)) entity = "FileTXT"; //$NON-NLS-1$ - } else /*if(entity == null)*/ { + } else if(!"FileCLASS".equals(entity)) { //$NON-NLS-1$ body = jar.getContent(cpath); entity = getModel().getEntityRecognizer().getEntityName(new EntityRecognizerContext(name, ext, body)); } if(entity == null || getModel().getMetaData().getEntity(entity) == null) entity = "FileAny"; //$NON-NLS-1$ XModelObject c = getModel().createModelObject(entity, p); if(FolderImpl.isLateloadFile2(c)) { FileAnyImpl ci = (FileAnyImpl)c; ci.setBodySource(new JarBodySource(jar, cpath)); } else { XObjectLoader loader = XModelObjectLoaderUtil.getObjectLoader(c); if(loader != null) { if(body == null) body = jar.getContent(cpath); XModelObjectLoaderUtil.setTempBody(c, body); loader.load(c); } } if(add) { addChild(c); } else { ((XModelObjectImpl)c).setParent_0(this); } return c; } public XModelObject createValidChildCopy(XModelObject child) { JarAccess jar = getJarSystem().getJarAccess(); if(!jar.isLoaded()) return null; jar.lockJar(); String path = getAbsolutePath(); String item = FileAnyImpl.toFileName(child); XModelObject copy = createFileObject(jar, path, item, false); jar.unlockJar(); return copy; } protected boolean fire = false; protected void fireStructureChanged(int kind, Object info) { if(fire) super.fireStructureChanged(kind, info); } public boolean hasChildren() { boolean q = super.hasChildren(); if (q || loaded) return q; loadChildren(); return super.hasChildren(); } public String getPathPart() { String s = super.getPathPart(); return FilePathHelper.toPathPath(s); } public XModelObject getChildByPathPart(String pathpart) { pathpart = FilePathHelper.toPathPath(pathpart); return super.getChildByPathPart(pathpart); } public boolean update() { return true; } public boolean save() { return true; } public boolean isRemoved() { return false; } } class JarBodySource implements BodySource { private JarAccess jar = null; private String path = null; public JarBodySource(JarAccess jar, String path) { this.jar = jar; this.path = path; } public String get() { return jar.getContent(path); } public boolean write(Object object) { return true; } }
true
true
private XModelObject createFileObject(JarAccess jar, String path, String name, boolean add) { String cpath = (path.length() == 0) ? name : path + XModelObjectConstants.SEPARATOR + name; Properties p = new Properties(); FolderImpl.parseFileName(p, name); String ext = p.getProperty(XModelObjectConstants.ATTR_NAME_EXTENSION); String body = null; String entity = getModel().getEntityRecognizer().getEntityName(new EntityRecognizerContext(name, ext, body)); if("FileAny".equals(entity)) { //$NON-NLS-1$ if(jar.getSize(cpath) > 100000) entity = XModelObjectConstants.ENT_FILE_ANY_LONG; else if(jar.isTextEntry(cpath, 100)) entity = "FileTXT"; //$NON-NLS-1$ } else /*if(entity == null)*/ { body = jar.getContent(cpath); entity = getModel().getEntityRecognizer().getEntityName(new EntityRecognizerContext(name, ext, body)); } if(entity == null || getModel().getMetaData().getEntity(entity) == null) entity = "FileAny"; //$NON-NLS-1$ XModelObject c = getModel().createModelObject(entity, p); if(FolderImpl.isLateloadFile2(c)) { FileAnyImpl ci = (FileAnyImpl)c; ci.setBodySource(new JarBodySource(jar, cpath)); } else { XObjectLoader loader = XModelObjectLoaderUtil.getObjectLoader(c); if(loader != null) { if(body == null) body = jar.getContent(cpath); XModelObjectLoaderUtil.setTempBody(c, body); loader.load(c); } } if(add) { addChild(c); } else { ((XModelObjectImpl)c).setParent_0(this); } return c; }
private XModelObject createFileObject(JarAccess jar, String path, String name, boolean add) { String cpath = (path.length() == 0) ? name : path + XModelObjectConstants.SEPARATOR + name; Properties p = new Properties(); FolderImpl.parseFileName(p, name); String ext = p.getProperty(XModelObjectConstants.ATTR_NAME_EXTENSION); String body = null; String entity = getModel().getEntityRecognizer().getEntityName(new EntityRecognizerContext(name, ext, body)); if("FileAny".equals(entity)) { //$NON-NLS-1$ if(jar.getSize(cpath) > 100000) entity = XModelObjectConstants.ENT_FILE_ANY_LONG; else if(jar.isTextEntry(cpath, 100)) entity = "FileTXT"; //$NON-NLS-1$ } else if(!"FileCLASS".equals(entity)) { //$NON-NLS-1$ body = jar.getContent(cpath); entity = getModel().getEntityRecognizer().getEntityName(new EntityRecognizerContext(name, ext, body)); } if(entity == null || getModel().getMetaData().getEntity(entity) == null) entity = "FileAny"; //$NON-NLS-1$ XModelObject c = getModel().createModelObject(entity, p); if(FolderImpl.isLateloadFile2(c)) { FileAnyImpl ci = (FileAnyImpl)c; ci.setBodySource(new JarBodySource(jar, cpath)); } else { XObjectLoader loader = XModelObjectLoaderUtil.getObjectLoader(c); if(loader != null) { if(body == null) body = jar.getContent(cpath); XModelObjectLoaderUtil.setTempBody(c, body); loader.load(c); } } if(add) { addChild(c); } else { ((XModelObjectImpl)c).setParent_0(this); } return c; }
diff --git a/luaj-vm/src/core/org/luaj/lib/PackageLib.java b/luaj-vm/src/core/org/luaj/lib/PackageLib.java index b491ae9..7cf165c 100644 --- a/luaj-vm/src/core/org/luaj/lib/PackageLib.java +++ b/luaj-vm/src/core/org/luaj/lib/PackageLib.java @@ -1,419 +1,419 @@ /******************************************************************************* * Copyright (c) 2007 LuaJ. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/ package org.luaj.lib; import java.io.InputStream; import java.io.PrintStream; import java.util.Vector; import org.luaj.vm.CallInfo; import org.luaj.vm.LBoolean; import org.luaj.vm.LFunction; import org.luaj.vm.LNil; import org.luaj.vm.LString; import org.luaj.vm.LTable; import org.luaj.vm.LValue; import org.luaj.vm.Lua; import org.luaj.vm.LuaState; import org.luaj.vm.Platform; public class PackageLib extends LFunction { public static final String DEFAULT_LUA_PATH = "?.luac;?.lua"; public static InputStream STDIN = null; public static PrintStream STDOUT = System.out; public static LTable LOADED = null; private static final LString _M = new LString("_M"); private static final LString _NAME = new LString("_NAME"); private static final LString _PACKAGE = new LString("_PACKAGE"); private static final LString _DOT = new LString("."); private static final LString _EMPTY = new LString(""); private static final LString __INDEX = new LString("__index"); private static final LString _LOADERS = new LString("loaders"); private static final LString _PRELOAD = new LString("preload"); private static final LString _PATH = new LString("path"); private static final LValue _SENTINEL = _EMPTY; private static final LString _LUA_PATH = new LString(DEFAULT_LUA_PATH); private static final String[] NAMES = { "package", "module", "require", "loadlib", "seeall", "preload_loader", "lua_loader", "java_loader", }; private static final int INSTALL = 0; private static final int MODULE = 1; private static final int REQUIRE = 2; private static final int LOADLIB = 3; private static final int SEEALL = 4; private static final int PRELOAD_LOADER = 5; private static final int LUA_LOADER = 6; private static final int JAVA_LOADER = 7; // all functions in package share this environment private static LTable pckg; public static void install( LTable globals ) { for ( int i=1; i<=REQUIRE; i++ ) globals.put( NAMES[i], new PackageLib(i) ); pckg = new LTable(); for ( int i=LOADLIB; i<=SEEALL; i++ ) pckg.put( NAMES[i], new PackageLib(i) ); LOADED = new LTable(); pckg.put( "loaded", LOADED ); pckg.put( _PRELOAD, new LTable() ); LTable loaders = new LTable(3,0); for ( int i=PRELOAD_LOADER; i<=JAVA_LOADER; i++ ) loaders.luaInsertPos(0, new PackageLib(i) ); pckg.put( "loaders", loaders ); pckg.put( _PATH, _LUA_PATH ); globals.put( "package", pckg ); } public static void setLuaPath( String newLuaPath ) { pckg.put( _PATH, new LString(newLuaPath) ); } private final int id; private PackageLib( int id ) { this.id = id; } public String toString() { return NAMES[id]+"()"; } public boolean luaStackCall( LuaState vm ) { switch ( id ) { case INSTALL: install(vm._G); break; case MODULE: module(vm); break; case REQUIRE: require(vm); break; case LOADLIB: loadlib(vm); break; case SEEALL: { if ( ! vm.istable(2) ) vm.error( "table expected, got "+vm.typename(2) ); LTable t = vm.totable(2); LTable m = t.luaGetMetatable(); if ( m == null ) t.luaSetMetatable(m = new LTable()); m.put(__INDEX, vm._G); vm.resettop(); break; } case PRELOAD_LOADER: { loader_preload(vm); break; } case LUA_LOADER: { loader_Lua(vm); break; } case JAVA_LOADER: { loader_Java(vm); break; } default: LuaState.vmerror( "bad package id" ); } return false; } // ======================== Module, Package loading ============================= /** * module (name [, ...]) * * Creates a module. If there is a table in package.loaded[name], this table * is the module. Otherwise, if there is a global table t with the given * name, this table is the module. Otherwise creates a new table t and sets * it as the value of the global name and the value of package.loaded[name]. * This function also initializes t._NAME with the given name, t._M with the * module (t itself), and t._PACKAGE with the package name (the full module * name minus last component; see below). Finally, module sets t as the new * environment of the current function and the new value of * package.loaded[name], so that require returns t. * * If name is a compound name (that is, one with components separated by * dots), module creates (or reuses, if they already exist) tables for each * component. For instance, if name is a.b.c, then module stores the module * table in field c of field b of global a. * * This function may receive optional options after the module name, where * each option is a function to be applied over the module. */ public static void module(LuaState vm) { LString modname = vm.tolstring(2); int n = vm.gettop(); LValue value = LOADED.get(modname); LTable module; if ( value.luaGetType() != Lua.LUA_TTABLE ) { /* not found? */ /* try global variable (and create one if it does not exist) */ module = findtable( vm._G, modname ); if ( module == null ) vm.error( "name conflict for module '"+modname+"'" ); LOADED.luaSetTable(vm, LOADED, modname, module); } else { module = (LTable) value; } /* check whether table already has a _NAME field */ LValue name = module.luaGetTable(vm, module, _NAME); if ( name.isNil() ) { modinit( vm, module, modname ); } // set the environment of the current function CallInfo ci = vm.getStackFrame(0); ci.closure.env = module; // apply the functions for ( int i=3; i<=n; i++ ) { vm.pushvalue( i ); /* get option (a function) */ vm.pushlvalue( module ); /* module */ vm.call( 1, 0 ); } // returns no results vm.resettop(); } /** * * @param table the table at which to start the search * @param fname the name to look up or create, such as "abc.def.ghi" * @return the table for that name, possible a new one, or null if a non-table has that name already. */ private static LTable findtable(LTable table, LString fname) { int b, e=(-1); do { e = fname.indexOf(_DOT, b=e+1 ); if ( e < 0 ) e = fname.m_length; LString key = fname.substring(b, e); LValue val = table.get(key); if ( val.isNil() ) { /* no such field? */ LTable field = new LTable(); /* new table for field */ table.put(key, field); table = field; } else if ( val.luaGetType() != Lua.LUA_TTABLE ) { /* field has a non-table value? */ return null; } else { table = (LTable) val; } } while ( e < fname.m_length ); return table; } private static void modinit(LuaState vm, LTable module, LString modname) { /* module._M = module */ module.luaSetTable(vm, module, _M, module); int e = modname.lastIndexOf(_DOT); module.luaSetTable(vm, module, _NAME, modname ); module.luaSetTable(vm, module, _PACKAGE, (e<0? _EMPTY: modname.substring(0,e+1)) ); } /** * require (modname) * * Loads the given module. The function starts by looking into the package.loaded table to * determine whether modname is already loaded. If it is, then require returns the value * stored at package.loaded[modname]. Otherwise, it tries to find a loader for the module. * * To find a loader, require is guided by the package.loaders array. By changing this array, * we can change how require looks for a module. The following explanation is based on the * default configuration for package.loaders. * * First require queries package.preload[modname]. If it has a value, this value * (which should be a function) is the loader. Otherwise require searches for a Lua loader * using the path stored in package.path. If that also fails, it searches for a C loader * using the path stored in package.cpath. If that also fails, it tries an all-in-one loader * (see package.loaders). * * Once a loader is found, require calls the loader with a single argument, modname. * If the loader returns any value, require assigns the returned value to package.loaded[modname]. * If the loader returns no value and has not assigned any value to package.loaded[modname], * then require assigns true to this entry. In any case, require returns the final value of * package.loaded[modname]. * * If there is any error loading or running the module, or if it cannot find any loader for * the module, then require signals an error. */ public void require( LuaState vm ) { LString name = vm.tolstring(2); LValue loaded = LOADED.get(name); if ( loaded.toJavaBoolean() ) { if ( loaded == _SENTINEL ) vm.error("loop or previous error loading module '"+name+"'"); vm.resettop(); vm.pushlvalue( loaded ); return; } vm.resettop(); /* else must load it; iterate over available loaders */ LValue val = pckg.luaGetTable(vm, pckg, _LOADERS); if ( ! val.isTable() ) vm.error( "'package.loaders' must be a table" ); vm.pushlvalue(val); Vector v = new Vector(); for ( int i=1; true; i++ ) { vm.rawgeti(1, i); if ( vm.isnil(-1) ) { vm.error( "module '"+name+"' not found: "+v ); } /* call loader with module name as argument */ vm.pushlstring(name); vm.call(1, 1); if ( vm.isfunction(-1) ) break; /* module loaded successfully */ if ( vm.isstring(-1) ) /* loader returned error message? */ v.addElement(vm.tolstring(-1)); /* accumulate it */ vm.pop(1); } // load the module using the loader LOADED.luaSetTable(vm, LOADED, name, _SENTINEL); vm.pushlstring( name ); /* pass name as argument to module */ vm.call( 1, 1 ); /* run loaded module */ if ( ! vm.isnil(-1) ) /* non-nil return? */ LOADED.luaSetTable(vm, LOADED, name, vm.topointer(-1) ); /* _LOADED[name] = returned value */ - if ( LOADED.luaGetTable(vm, LOADED, name) == _SENTINEL ) { /* module did not set a value? */ - LOADED.luaSetTable(vm, LOADED, name, LBoolean.TRUE ); /* _LOADED[name] = true */ - vm.pushboolean(true); + LValue result = LOADED.luaGetTable(vm, LOADED, name); + if ( result == _SENTINEL ) { /* module did not set a value? */ + LOADED.luaSetTable(vm, LOADED, name, result=LBoolean.TRUE ); /* _LOADED[name] = true */ } - vm.replace(1); - vm.settop(1); + vm.resettop(); + vm.pushlvalue(result); } public static void loadlib( LuaState vm ) { vm.error( "loadlib not implemented" ); } private void loader_preload( LuaState vm ) { LString name = vm.tolstring(2); LValue preload = pckg.luaGetTable(vm, pckg, _PRELOAD); if ( ! preload.isTable() ) vm.error("package.preload '"+name+"' must be a table"); LValue val = preload.luaGetTable(vm, preload, name); if ( val.isNil() ) vm.pushstring("\n\tno field package.preload['"+name+"']"); vm.resettop(); vm.pushlvalue(val); } private void loader_Lua( LuaState vm ) { String name = vm.tostring(2); InputStream is = findfile( vm, name, _PATH ); if ( is != null ) { String filename = vm.tostring(-1); if ( ! BaseLib.loadis(vm, is, filename) ) loaderror( vm, filename ); } vm.insert(1); vm.settop(1); } private void loader_Java( LuaState vm ) { String name = vm.tostring(2); Class c = null; LValue v = null; try { c = Class.forName(name); v = (LValue) c.newInstance(); vm.pushlvalue( v ); } catch ( ClassNotFoundException cnfe ) { vm.pushstring("\n\tno class '"+name+"'" ); } catch ( Exception e ) { vm.pushstring("\n\tjava load failed on '"+name+"', "+e ); } vm.insert(1); vm.settop(1); } private InputStream findfile(LuaState vm, String name, LString pname) { Platform p = Platform.getInstance(); LValue pkg = pckg.luaGetTable(vm, pckg, pname); if ( ! pkg.isString() ) vm.error("package."+pname+" must be a string"); String path = pkg.toJavaString(); int e = -1; int n = path.length(); StringBuffer sb = null; name = name.replace('.','/'); while ( e < n ) { // find next template int b = e+1; e = path.indexOf(';',b); if ( e < 0 ) e = path.length(); String template = path.substring(b,e); // create filename int q = template.indexOf('?'); String filename = template; if ( q >= 0 ) { filename = template.substring(0,q) + name + template.substring(q+1); } // try opening the file InputStream is = p.openFile(filename); if ( is != null ) { vm.pushstring(filename); return is; } // report error if ( sb == null ) sb = new StringBuffer(); sb.append( "\n\tno file '"+filename+"'"); } // not found, push error on stack and return vm.pushstring(sb.toString()); return null; } private static void loaderror(LuaState vm, String filename) { vm.error( "error loading module '"+vm.tostring(1)+"' from file '"+filename+"':\n\t"+vm.tostring(-1) ); } }
false
true
public void require( LuaState vm ) { LString name = vm.tolstring(2); LValue loaded = LOADED.get(name); if ( loaded.toJavaBoolean() ) { if ( loaded == _SENTINEL ) vm.error("loop or previous error loading module '"+name+"'"); vm.resettop(); vm.pushlvalue( loaded ); return; } vm.resettop(); /* else must load it; iterate over available loaders */ LValue val = pckg.luaGetTable(vm, pckg, _LOADERS); if ( ! val.isTable() ) vm.error( "'package.loaders' must be a table" ); vm.pushlvalue(val); Vector v = new Vector(); for ( int i=1; true; i++ ) { vm.rawgeti(1, i); if ( vm.isnil(-1) ) { vm.error( "module '"+name+"' not found: "+v ); } /* call loader with module name as argument */ vm.pushlstring(name); vm.call(1, 1); if ( vm.isfunction(-1) ) break; /* module loaded successfully */ if ( vm.isstring(-1) ) /* loader returned error message? */ v.addElement(vm.tolstring(-1)); /* accumulate it */ vm.pop(1); } // load the module using the loader LOADED.luaSetTable(vm, LOADED, name, _SENTINEL); vm.pushlstring( name ); /* pass name as argument to module */ vm.call( 1, 1 ); /* run loaded module */ if ( ! vm.isnil(-1) ) /* non-nil return? */ LOADED.luaSetTable(vm, LOADED, name, vm.topointer(-1) ); /* _LOADED[name] = returned value */ if ( LOADED.luaGetTable(vm, LOADED, name) == _SENTINEL ) { /* module did not set a value? */ LOADED.luaSetTable(vm, LOADED, name, LBoolean.TRUE ); /* _LOADED[name] = true */ vm.pushboolean(true); } vm.replace(1); vm.settop(1); }
public void require( LuaState vm ) { LString name = vm.tolstring(2); LValue loaded = LOADED.get(name); if ( loaded.toJavaBoolean() ) { if ( loaded == _SENTINEL ) vm.error("loop or previous error loading module '"+name+"'"); vm.resettop(); vm.pushlvalue( loaded ); return; } vm.resettop(); /* else must load it; iterate over available loaders */ LValue val = pckg.luaGetTable(vm, pckg, _LOADERS); if ( ! val.isTable() ) vm.error( "'package.loaders' must be a table" ); vm.pushlvalue(val); Vector v = new Vector(); for ( int i=1; true; i++ ) { vm.rawgeti(1, i); if ( vm.isnil(-1) ) { vm.error( "module '"+name+"' not found: "+v ); } /* call loader with module name as argument */ vm.pushlstring(name); vm.call(1, 1); if ( vm.isfunction(-1) ) break; /* module loaded successfully */ if ( vm.isstring(-1) ) /* loader returned error message? */ v.addElement(vm.tolstring(-1)); /* accumulate it */ vm.pop(1); } // load the module using the loader LOADED.luaSetTable(vm, LOADED, name, _SENTINEL); vm.pushlstring( name ); /* pass name as argument to module */ vm.call( 1, 1 ); /* run loaded module */ if ( ! vm.isnil(-1) ) /* non-nil return? */ LOADED.luaSetTable(vm, LOADED, name, vm.topointer(-1) ); /* _LOADED[name] = returned value */ LValue result = LOADED.luaGetTable(vm, LOADED, name); if ( result == _SENTINEL ) { /* module did not set a value? */ LOADED.luaSetTable(vm, LOADED, name, result=LBoolean.TRUE ); /* _LOADED[name] = true */ } vm.resettop(); vm.pushlvalue(result); }
diff --git a/src/org/joval/plugin/RemotePlugin.java b/src/org/joval/plugin/RemotePlugin.java index 7624ad32..11183dbf 100755 --- a/src/org/joval/plugin/RemotePlugin.java +++ b/src/org/joval/plugin/RemotePlugin.java @@ -1,82 +1,84 @@ // Copyright (C) 2011 jOVAL.org. All rights reserved. // This software is licensed under the AGPL 3.0 license available at http://www.joval.org/agpl_v3.txt package org.joval.plugin; import java.io.File; import java.io.IOException; import java.net.ConnectException; import java.net.UnknownHostException; import java.util.Properties; import org.slf4j.cal10n.LocLogger; import org.joval.discovery.SessionFactory; import org.joval.intf.identity.ICredentialStore; import org.joval.util.JOVALMsg; import org.joval.util.JOVALSystem; /** * Implementation of an IPlugin for remote scanning. * * @author David A. Solin * @version %I% %G% */ public class RemotePlugin extends BasePlugin { private static SessionFactory sessionFactory = new SessionFactory(); /** * Set a location where the RemotePlugin class can store host discovery information. */ public static void setDataDirectory(File dir) throws IOException { sessionFactory.setDataDirectory(dir); } /** * Set the ICredentialStore for the RemotePlugin class. */ public static void setCredentialStore(ICredentialStore cs) { sessionFactory.setCredentialStore(cs); } /** * Add an SSH gateway through which the destination must be contacted. */ public static void addRoute(String destination, String gateway) { sessionFactory.addRoute(destination, gateway); } protected String hostname; /** * Create a remote plugin. */ public RemotePlugin(String hostname) { super(); this.hostname = hostname; } // Overrides @Override public void setLogger(LocLogger logger) { super.setLogger(logger); sessionFactory.setLogger(logger); } // Implement IPlugin /** * Creation of the session is deferred until this point because it can be a blocking, time-consuming operation. By * doing that as part of the connect routine, it happens inside of the IEngine's run method, which can be wrapped inside * a Thread. */ public void connect() throws ConnectException { try { - session = sessionFactory.createSession(hostname); + if (session == null) { + session = sessionFactory.createSession(hostname); + } super.connect(); } catch (UnknownHostException e) { throw new ConnectException(e.getMessage()); } } }
true
true
public void connect() throws ConnectException { try { session = sessionFactory.createSession(hostname); super.connect(); } catch (UnknownHostException e) { throw new ConnectException(e.getMessage()); } }
public void connect() throws ConnectException { try { if (session == null) { session = sessionFactory.createSession(hostname); } super.connect(); } catch (UnknownHostException e) { throw new ConnectException(e.getMessage()); } }
diff --git a/modules/org.restlet/src/org/restlet/service/ConverterService.java b/modules/org.restlet/src/org/restlet/service/ConverterService.java index afa7e528b..7565922d1 100644 --- a/modules/org.restlet/src/org/restlet/service/ConverterService.java +++ b/modules/org.restlet/src/org/restlet/service/ConverterService.java @@ -1,258 +1,263 @@ /** * Copyright 2005-2009 Noelios Technologies. * * The contents of this file are subject to the terms of one of the following * open source licenses: LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL 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.opensource.org/licenses/lgpl-3.0.html * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1.php * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1.php * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0.php * * 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.service; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import org.restlet.Context; import org.restlet.engine.Engine; import org.restlet.engine.converter.ConverterHelper; import org.restlet.engine.converter.ConverterUtils; import org.restlet.engine.resource.VariantInfo; import org.restlet.representation.Representation; import org.restlet.representation.Variant; import org.restlet.resource.UniformResource; /** * Application service converting between representation and regular Java * objects. The conversion can work in both directions.<br> * <br> * By default, the following conversions are supported. Additional ones can be * plugged into the engine. * * @author Jerome Louvel */ public class ConverterService extends Service { /** * Constructor. */ public ConverterService() { super(); } /** * Constructor. * * @param enabled * True if the service has been enabled. */ public ConverterService(boolean enabled) { super(enabled); } /** * Returns the list of object classes that can be converted from a given * variant. * * @param source * The source variant. * @return The list of object class that can be converted. */ public List<Class<?>> getObjectClasses(Variant source) { List<Class<?>> result = null; List<Class<?>> helperObjectClasses = null; for (ConverterHelper ch : Engine.getInstance() .getRegisteredConverters()) { helperObjectClasses = ch.getObjectClasses(source); if (helperObjectClasses != null) { if (result == null) { result = new ArrayList<Class<?>>(); } result.addAll(helperObjectClasses); } } return result; } /** * Returns the list of variants that can be converted from a given object * class. * * @param source * The source class. * @param target * The expected representation metadata. * @return The list of variants that can be converted. */ public List<? extends Variant> getVariants(Class<?> source, Variant target) { return ConverterUtils.getVariants(source, target); } /** * Converts a Representation into a regular Java object. * * @param source * The source representation to convert. * @return The converted Java object. * @throws IOException */ public Object toObject(Representation source) throws IOException { return toObject(source, null, null); } /** * Converts a Representation into a regular Java object. * * @param <T> * The expected class of the Java object. * @param source * The source representation to convert. * @param target * The target class of the Java object. * @param resource * The parent resource. * @return The converted Java object. * @throws IOException */ public <T> T toObject(Representation source, Class<T> target, UniformResource resource) throws IOException { T result = null; if ((source != null) && source.isAvailable()) { ConverterHelper ch = ConverterUtils.getBestHelper(source, target, resource); if (ch != null) { Context.getCurrentLogger().fine( "The following converter was selected for the " + source + " representation: " + ch); result = ch.toObject(source, target, resource); if (result instanceof Representation) { Representation resultRepresentation = (Representation) result; // Copy the variant metadata resultRepresentation.setCharacterSet(source .getCharacterSet()); resultRepresentation.setMediaType(source.getMediaType()); resultRepresentation.getEncodings().addAll( source.getEncodings()); resultRepresentation.getLanguages().addAll( source.getLanguages()); } } else { Context.getCurrentLogger().info( "Unable to find a converter for this representation : " + source); } } return result; } /** * Converts a regular Java object into a Representation. The converter will * use the preferred variant of the selected converter. * * @param source * The source object to convert. * @return The converted representation. */ public Representation toRepresentation(Object source) { return toRepresentation(source, null, null); } /** * Converts a regular Java object into a Representation. * * @param source * The source object to convert. * @param target * The target representation variant. * @param resource * The parent resource. * @return The converted representation. */ public Representation toRepresentation(Object source, Variant target, UniformResource resource) { Representation result = null; ConverterHelper ch = ConverterUtils.getBestHelper(source, target, resource); if (ch != null) { try { Context.getCurrentLogger().fine( "The following converter was selected for the " + source + " object: " + ch); if (target == null) { List<VariantInfo> variants = ch.getVariants(source .getClass()); if ((variants != null) && !variants.isEmpty()) { - target = resource.getClientInfo().getPreferredVariant( - variants, resource.getMetadataService()); + if (resource != null) { + target = resource.getClientInfo() + .getPreferredVariant(variants, + resource.getMetadataService()); + } else { + target = variants.get(0); + } } else { target = new Variant(); } } result = ch.toRepresentation(source, target, resource); if (result != null) { // Copy the variant metadata if necessary if (result.getCharacterSet() == null) { result.setCharacterSet(target.getCharacterSet()); } if (result.getMediaType() == null) { result.setMediaType(target.getMediaType()); } if (result.getEncodings().isEmpty()) { result.getEncodings().addAll(target.getEncodings()); } if (result.getLanguages().isEmpty()) { result.getLanguages().addAll(target.getLanguages()); } } } catch (IOException e) { Context.getCurrentLogger().log(Level.WARNING, "Unable to convert object to a representation", e); } } else { Context.getCurrentLogger().warning( "Unable to find a converter for this object : " + source); } return result; } }
true
true
public Representation toRepresentation(Object source, Variant target, UniformResource resource) { Representation result = null; ConverterHelper ch = ConverterUtils.getBestHelper(source, target, resource); if (ch != null) { try { Context.getCurrentLogger().fine( "The following converter was selected for the " + source + " object: " + ch); if (target == null) { List<VariantInfo> variants = ch.getVariants(source .getClass()); if ((variants != null) && !variants.isEmpty()) { target = resource.getClientInfo().getPreferredVariant( variants, resource.getMetadataService()); } else { target = new Variant(); } } result = ch.toRepresentation(source, target, resource); if (result != null) { // Copy the variant metadata if necessary if (result.getCharacterSet() == null) { result.setCharacterSet(target.getCharacterSet()); } if (result.getMediaType() == null) { result.setMediaType(target.getMediaType()); } if (result.getEncodings().isEmpty()) { result.getEncodings().addAll(target.getEncodings()); } if (result.getLanguages().isEmpty()) { result.getLanguages().addAll(target.getLanguages()); } } } catch (IOException e) { Context.getCurrentLogger().log(Level.WARNING, "Unable to convert object to a representation", e); } } else { Context.getCurrentLogger().warning( "Unable to find a converter for this object : " + source); } return result; }
public Representation toRepresentation(Object source, Variant target, UniformResource resource) { Representation result = null; ConverterHelper ch = ConverterUtils.getBestHelper(source, target, resource); if (ch != null) { try { Context.getCurrentLogger().fine( "The following converter was selected for the " + source + " object: " + ch); if (target == null) { List<VariantInfo> variants = ch.getVariants(source .getClass()); if ((variants != null) && !variants.isEmpty()) { if (resource != null) { target = resource.getClientInfo() .getPreferredVariant(variants, resource.getMetadataService()); } else { target = variants.get(0); } } else { target = new Variant(); } } result = ch.toRepresentation(source, target, resource); if (result != null) { // Copy the variant metadata if necessary if (result.getCharacterSet() == null) { result.setCharacterSet(target.getCharacterSet()); } if (result.getMediaType() == null) { result.setMediaType(target.getMediaType()); } if (result.getEncodings().isEmpty()) { result.getEncodings().addAll(target.getEncodings()); } if (result.getLanguages().isEmpty()) { result.getLanguages().addAll(target.getLanguages()); } } } catch (IOException e) { Context.getCurrentLogger().log(Level.WARNING, "Unable to convert object to a representation", e); } } else { Context.getCurrentLogger().warning( "Unable to find a converter for this object : " + source); } return result; }
diff --git a/src/bindings/org/gnome/gtk/TextBuffer.java b/src/bindings/org/gnome/gtk/TextBuffer.java index 324a0d84..ac65dd51 100644 --- a/src/bindings/org/gnome/gtk/TextBuffer.java +++ b/src/bindings/org/gnome/gtk/TextBuffer.java @@ -1,743 +1,746 @@ /* * TextBuffer.java * * Copyright (c) 2007-2008 Operational Dynamics Consulting Pty Ltd, and Others * * The code in this file, and the library it is a part of, are made available * to you by the authors under the terms of the "GNU General Public Licence, * version 2" plus the "Classpath Exception" (you may link to this code as a * library into other programs provided you don't make a derivation of it). * See the LICENCE file for the terms governing usage and redistribution. */ package org.gnome.gtk; import org.gnome.gdk.Pixbuf; import org.gnome.glib.Object; import static org.gnome.gtk.TextTagTable.getDefaultTable; /** * A TextBuffer is a powerful mechanism for storing and manipulating text. It * exists primarily to be the model that backs the view of one or more * paragraphs as presented by the {@link TextView} Widget. Together, these * make for a powerful text display and text editing capability, but it does * come at the cost of considerable come complexity. * * <h2>Usage</h2> * * Creating a TextBuffer is straight forward, as is placing text in it: * * <pre> * TextBuffer buffer; * * buffer = new TextBuffer(); * buffer.setText(&quot;Hello world!&quot;); * </pre> * * Of course, you rarely just want to write an entire body of text in one go. * To insert text in a more piecemeal fashion we use one of the * <code>insert()</code> family of methods, but before we can do so, we need * to indicate <i>where</i> we want to insert that text. This is the role of * {@link TextIter} class. * * <pre> * TextIter pointer; * * pointer = buffer.getIterStart(); * buffer.insert(pointer, &quot;This is the beginning&quot;); * </pre> * * Note that TextIters are not persistent; as soon as any change is made to * the TextBuffer all TextIters are invalidated and you'll need to acquire new * ones. If you need a stable reference to a particular position in the text, * create a TextMark with {@link #createMark(TextIter, boolean) createMark()}. * * <p> * As you might expect, a TextBuffer has a notion of a cursor which indicates * the (user's) current insertion point. You can get the TextMark representing * the cursor, and can use it to insert text or otherwise manipulate a * position by converting it to a valid TextIter: * * <pre> * TextMark cursor; * * cursor = buffer.getInsert(); * ... * pointer = cursor.getIter(); * buffer.insert(pointer, &quot;This text was inserted at the cursor&quot;); * </pre> * * The <code>insertAtCursor()</code> method is a shortcut for this. * * <p> * There are an incredibly wide range of methods available on the TextIter * class for manipulating the position into the TextBuffer that it represents * and for finding out more information about the nature of the text at that * point. TextIter's {@link TextIter#forwardLine() forwardLine()} is one * example; you could use it to count the non-empty lines in a TextBuffer: * * <pre> * int paragraphs; * ... * * pointer = buffer.getIterStart(); * paragraphs = 0; * * while (pointer.forwardLine()) { * if (pointer.startsWord()) { * paragraphs++; * } * } * </pre> * * Although trivial, this raises a pitfall you need to be aware of: lines of * text in a TextBuffer are <i>not</i> the same as wrapped visible lines in a * TextView. Lines in a TextBuffer are a sequences of characters separated by * newlines (you don't need a <code>'\n'</code> at the end of the TextBuffer; * the end is an implicit line termination). When presented in a TextView with * word wrapping enabled, however, each of these lines may take up more than * one line on the screen. The term paragraph is used there; see * {@link TextIter#forwardDisplayLine(TextView) forwardDisplayLine()} to move * a TextIter to the next displayed line within a paragraph as shown on screen * in a TextView. * * <p> * Finally, formatting and other properties can be set on ranges of text. See * {@link TextTag}. While these are mostly about visual presentation, they are * nevertheless set by applying TextTags to text in the TextBuffer via the * {@link #applyTag(TextTag, TextIter, TextIter) applyTag()} and * {@link #insert(TextIter, String, TextTag) insert()} methods here. * * <p> * <i>These APIs can be somewhat frustrating to use as the methods you need * (relative to the order you need them in) tend to be scattered around * between TextView, TextBuffer, and TextIter. It was tempting to try and * normalize these to a common interface, but in the end we deferred to being * faithful to the placement of methods in the underlying library's classes. * We have done our best to cross reference our documentation to help you find * the "next" logical element when you need it, but if you find yourself * struggling to find something and think this documentation could benefit * from another such pointer, please feel free to suggest it.</i> * * @author Andrew Cowie * @author Stefan Prelle * @since 4.0.9 */ /* * Judging by the GTK documentation, almost everything in this class works * through the default signal handlers. Thus if we expose any signals we must * a) make sure that the documentation of the corresponding methods here * mentions that behaviour could change, b) warn people in the signal's * documentation that they could massively screw things up, and c) write test * coverage to guard against this sort of thing. Based on all that, I'm not * going to be in a rush to see any of those internal signals exposed in our * public API. */ public class TextBuffer extends Object { /** * This constant is used to identify cells in the TextBuffer that are not * actually characters - in other words, Widgets and Pixbufs. The * placeholder is Unicode value <code>0xFFFC</code>, the "Object * Replacement Character" from the Special block. You might see it as * &#65532; in other contexts. * * @since 4.0.9 */ public static final char OBJECT_REPLACEMENT_CHARACTER = 0xFFFC; private final boolean usingDefaultTable; protected TextBuffer(long pointer) { super(pointer); usingDefaultTable = false; } /** * Create a new TextBuffer. * * <p> * This will use the default built-in TextTagTable (shared by all * TextBuffers constructed with this call) which in turn will be populated * with tags created using the no-arg {@link TextTag#TextTag() TextTag} * constructor. This is a convenience; if you need to segregate TextTags * used by different TextBuffers then just use the other TextBuffer * constructor. * * @since 4.0.9 */ public TextBuffer() { super(GtkTextBuffer.createTextBuffer(getDefaultTable())); usingDefaultTable = true; } /** * Create a new TextBuffer. Uses (or reuses) the supplied TextTagTable; * you can add more TextTags to it later. * * @since 4.0.9 */ public TextBuffer(TextTagTable tags) { super(GtkTextBuffer.createTextBuffer(tags)); usingDefaultTable = false; } /** * Replace the entire current contents of the TextBuffer. * * @since 4.0.9 */ public void setText(String text) { GtkTextBuffer.setText(this, text, -1); } /** * Returns the text in the range <code>start</code> .. <code>end</code>. * Excludes undisplayed text (text marked with tags that set the * <var>invisibility</var> attribute) if <code>includeHidden</code> is * <code>false</code>. Does not include characters representing embedded * images, so indexes into the returned string do not correspond to * indexes into the TextBuffer. * * @since 4.0.9 */ public String getText(TextIter start, TextIter end, boolean includeHidden) { return GtkTextBuffer.getText(this, start, end, includeHidden); } /** * Returns the text in the TextBuffer in its entirety. This is merely a * convenience function that calls * {@link #getText(TextIter, TextIter, boolean)} from buffer start to end * with <code>includeHidden</code> being <code>true</code>. * * @since 4.0.9 */ public String getText() { return getText(getIterStart(), getIterEnd(), true); } /** * Marks the content as changed. This is primarily used to <i>unset</i> * this property, making it <code>false</code>. See {@link #getModified() * getModified()} for details. * * @since 4.0.9 */ public void setModified(boolean modified) { GtkTextBuffer.setModified(this, modified); } /** * Find out if the TextBuffer's content has changed. This is actually * defined as "has the TextBuffer changed since the last call to * {@link #setModified(boolean) setModified(false)}"; operations which * change the TextBuffer will toggle this property, and you can of course * manually set it with {@link #setModified(boolean) setModified(true)}. * * <p> * This can be used to record whether a file being edited has been * modified and is not yet saved to disk (although most applications would * probably track that state more robustly, this can at least feed * information into that process). * * @since 4.0.9 */ public boolean getModified() { return GtkTextBuffer.getModified(this); } /** * Returns a pointer to the beginning of the TextBuffer. * * @since 4.0.9 */ public TextIter getIterStart() { final TextIter iter; iter = new TextIter(this); GtkTextBuffer.getStartIter(this, iter); return iter; } /** * Returns a pointer to the end of the TextBuffer. * * @since 4.0.9 */ /* * The naming of this method is inverted so as to correspond with the * naming pattern established in TreeModel. */ public TextIter getIterEnd() { final TextIter iter; iter = new TextIter(this); GtkTextBuffer.getEndIter(this, iter); return iter; } /** * Create a new TextMark at the position of the supplied TextIter. * * <p> * The <code>gravity</code> parameter is interesting. It specifies whether * you want the TextMark to have left-gravity. If {@link TextMark#LEFT * LEFT} (<code>true</code>), then the TextMark will remain pointing to * the same location if text is inserted at this point. If * {@link TextMark#RIGHT RIGHT} (<code>false</code>), then as text is * inserted at this point the TextMark will move to the right. The * standard behaviour of the blinking cursor we all stare at all day long * following us as we type is an example of right-gravity. */ public TextMark createMark(TextIter where, boolean gravity) { return GtkTextBuffer.createMark(this, null, where, gravity); } void deleteMark(TextMark mark) { GtkTextBuffer.deleteMark(this, mark); } /** * Insert a text at a given position. All {@link TextIter} behind the * position move accordingly, while marks keep their position. * * @since 4.0.9 */ public void insert(TextIter position, String text) { GtkTextBuffer.insert(this, position, text, -1); } /** * Insert text as for {@link #insert(TextIter, String) insert()} but * simultaneously apply the formatting described by <code>tag</code>. You * can specify <code>null</code> TextTag if you actually want to skip * applying formatting, but in that case you'd probably rather just use * {@link #insert(TextIter, String) insert()}. * * @since 4.0.9 */ public void insert(TextIter position, String text, TextTag tag) { checkTag(tag); GtkTextBuffer.insertWithTags(this, position, text, -1, tag); } /** * Insert the text at the current cursor position. * * @since 4.0.9 */ public void insertAtCursor(String text) { GtkTextBuffer.insertAtCursor(this, text, -1); } /** * Like {@link #insert(TextIter, String) insert()}, but the insertion will * not occur if <code>pos</code> points to a non-editable location in the * buffer - meaning that it is enclosed in TextTags that mark the area * non-editable.<br/> * * @param pos * Position to insert at. * @param text * Text to insert. * @param defaultEditability * How shall the area be handled, if there are no tags * affecting the <var>editable</var> property at the given * location. You probably want to use <code>true</code> unless * you used TextView's {@link TextView#setEditable(boolean) * setEditable()} to change the default setting in the display * Widget you're using. * @since 4.0.9 */ public void insertInteractive(TextIter pos, String text, boolean defaultEditability) { GtkTextBuffer.insertInteractive(this, pos, text, -1, defaultEditability); } /** * Inserts an image at the cursor position. * * @since 4.0.9 */ public void insert(TextIter position, Pixbuf image) { GtkTextBuffer.insertPixbuf(this, position, image); } /** * Insert a Widget into the TextBuffer. * * <p> * Since multiple TextViews can present information from a given * TextBuffer, you need to specify <code>which</code> TextView you want * the image to appear in. * * <p> * Don't forget to <code>show()</code> the Widget. * * <p> * <i>Widgets, of course, are neither text nor image data; they need to * appear in a Container hierarchy. Thus adding a Widget is actually a * function of TextView. All the other methods that conceptually insert * things into a TextBuffer are here, however, so we include this as a * convenience. This is just a wrapper around TextView's</i> * {@link TextView#add(Widget, TextIter) add()}. * * @since 4.0.9 */ /* * FUTURE Can anyone think of a way to get rid of the need to specify the * TextView? */ public void insert(TextIter position, Widget child, TextView which) { which.add(child, position); } /** * Returns the current cursor position. Is also used at the start position * of a selected text. * * <p> * You can call {@link #getIter(TextMark) getIter()} to convert the * <var>insert</var> TextMark to an TextIter. * * @since 4.0.9 */ public TextMark getInsert() { return GtkTextBuffer.getInsert(this); } /** * Returns the end of the current selection. If you need the beginning of * the selection use {@link #getInsert() getInsert()}. * * <p> * Under ordinary circumstances you could think the * <var>selection-bound</var> TextMark as being the beginning of a * selection, and the <var>insert</var> mark as the end, but if the user * (or you, programmatically) has selected "backwards" then this TextMark * will be further ahead in the TextBuffer than the insertion one. * * <p> * You can call {@link #getIter(TextMark) getIter()} to convert the * TextMark to an TextIter. * * @since 4.0.9 */ public TextMark getSelectionBound() { return GtkTextBuffer.getSelectionBound(this); } /** * Returns whether or not the TextBuffer has a selection * * @since 4.0.9 */ public boolean getHasSelection() { return GtkTextBuffer.getHasSelection(this); } /** * Converts a {@link TextMark TextMark} into a valid {@link TextIter * TextIter} that you can use to point into the TextBuffer in its current * state. * * @since 4.0.9 */ /* * This method is more compactly named so as to correspond with the naming * pattern already established in TreeModel. */ public TextIter getIter(TextMark mark) { final TextIter iter; iter = new TextIter(this); GtkTextBuffer.getIterAtMark(this, iter, mark); return iter; } /** * Get a TextIter pointing at the position <code>offset</code> characters * into the TextBuffer. * * @since 4.0.9 */ public TextIter getIter(int offset) { final TextIter iter; iter = new TextIter(this); GtkTextBuffer.getIterAtOffset(this, iter, offset); return iter; } /* * Validate that the TextTag being submitted for application is legal for * use in this TextBuffer. FUTURE we could cache the table in the * constructors if this becomes a hot spot. */ private void checkTag(TextTag tag) { + if (tag == null) { + return; + } if (usingDefaultTable) { if (tag.table != getDefaultTable()) { throw new IllegalArgumentException("\n" + "You cannot apply a TextTag created with the no-arg TextTag() constructor\n" + "to a TextBuffer not likewise constructed with the no-arg TextBuffer()\n" + "constructor."); } } else { if (tag.table != GtkTextBuffer.getTagTable(this)) { throw new IllegalArgumentException("\n" + "You can only apply a TextTag to a TextBuffer created with the same\n" + "TextTagTable."); } } } /** * Apply the selected tag on the area in the TextBuffer between the start * and end positions. * * @since 4.0.9 */ public void applyTag(TextTag tag, TextIter start, TextIter end) { checkTag(tag); GtkTextBuffer.applyTag(this, tag, start, end); } /** * Select a range of text. The <var>selection-bound</var> mark will be * placed at <code>start</code>, and the <var>insert</var> mark will be * placed at <code>end</code>. * * <p> * Note that this should be used in preference to manually manipulating * the two marks with {@link #moveMark() moveMark()} calls; doing it that * way results in transient selections appearing which are different than * what you wish to see. * * <p> * See {@link #placeCursor(TextIter) placeCursor()} if you just want to * move the two marks to the same location; and, assuming the TextBuffer * is showing in a TextView, this will move the cursor. * * <p> * <i>The native GTK function has these arguments reversed but start and * end make more sense in consecutive order.</i> * * @since 4.0.9 */ public void selectRange(TextIter start, TextIter end) { GtkTextBuffer.selectRange(this, end, start); } /** * Remove the effect of the supplied <code>tag</code> from across the * range between <code>start</code> and <code>end</code>. The order of the * two TextIters doesn't actually matter; they are just bounds. * * @since 4.0.9 */ public void removeTag(TextTag tag, TextIter start, TextIter end) { GtkTextBuffer.removeTag(this, tag, start, end); } /** * Create a new TextChildAnchor at <code>location</code>. Once you have an * anchor for where you want the Widget, you use TextView's * {@link TextView#add(Widget, TextChildAnchor) add()} to load a Widget * into it. * * @since 4.0.9 */ /* * This is already a convenience method according to the GTK docs. Uh, * "good". Thanks. Means we don't need another constructor in * TextChildAnchor. */ TextChildAnchor createChildAnchor(TextIter location) { return GtkTextBuffer.createChildAnchor(this, location); } /** * Move the cursor (ie, the <var>selection-bound</var> and * <var>insert</var> marks) to the given location. * * <p> * This is more than just a convenience function; like * {@link #selectRange(TextIter, TextIter) selectRange()} it carries out * the move without intermediate state of part of the text being selected * while the individual TextMarks are being moved. * * <p> * See also TextView's {@link TextView#placeCursorOnscreen() * placeCursorOnscreen()} if you just want to force the cursor into the * currently showing section of the text. * * @since 4.0.9 */ public void placeCursor(TextIter location) { GtkTextBuffer.placeCursor(this, location); } /** * Returns the number of characters in this buffer. * * @since 4.0.9 */ public int getCharCount() { return GtkTextBuffer.getCharCount(this); } /** * Returns the number of text lines in this buffer. * * @since 4.0.9 */ public int getLineCount() { return GtkTextBuffer.getLineCount(this); } /** * The signal emitted when the contents of the TextBuffer have changed. * * @author Andrew Cowie * @since 4.0.9 */ public interface Changed extends GtkTextBuffer.ChangedSignal { public void onChanged(TextBuffer source); } /** * Hook up a handler for <code>TextBuffer.Changed</code> signals. * * @since 4.0.9 */ public void connect(TextBuffer.Changed handler) { GtkTextBuffer.connect(this, handler, false); } /** * Signal emitted when text is inserted into the TextBuffer. * * <p> * You must leave the TextIter <code>pointer</code> in a valid state; that * is, if you do something in your signal handler that changes the * TextBuffer, you must revalidate <code>pos</code> before returning. * * <p> * <i>The default handler for this signal is where the mechanism to * actually insert text into the TextBuffer lives.</i> * * @author Andrew Cowie * @since 4.0.9 */ /* * FIXME How do you do that? */ public interface InsertText { public void onInsertText(TextBuffer source, TextIter pointer, String text); } /** * Hook up a handler for <code>TextBuffer.InsertText</code> signals. This * will be invoked before the default handler is run, that is, before the * new text is actually inserted into the TextBuffer. * * @since 4.0.9 */ public void connect(TextBuffer.InsertText handler) { GtkTextBuffer.connect(this, new InsertTextHandler(handler), false); } /** * Hook up a handler for <code>TextBuffer.InsertText</code> signals that * will be called <i>after</i> the default handler. * * @since 4.0.9 */ public void connectAfter(TextBuffer.InsertText handler) { GtkTextBuffer.connect(this, new InsertTextHandler(handler), true); } /* * Trim off the length parameter which is unnecessary in Java. */ private static class InsertTextHandler implements GtkTextBuffer.InsertTextSignal { private final InsertText handler; private InsertTextHandler(InsertText handler) { this.handler = handler; } public void onInsertText(TextBuffer source, TextIter pos, String text, int length) { handler.onInsertText(source, pos, text); } } /** * Signal emitted when one or more characters are deleted. * * <p> * You can get a String representing the the removed characters by * calling: * * <pre> * deleted = buffer.getText(start, end, false); * </pre> * * <p> * Note that in the case of a user action which attempts to delete text in * a TextView that is not <var>editable</var> or within a range of * characters affected by TextTags with the <var>editable</var> property * set to <code>false</code> then the action will be inhibited and this * signal will not be raised. * * @author Andrew Cowie * @since 4.0.9 */ /* * TODO Can anyone explain how to stop a deletion from occurring in * response to the value of the text between start and end? The default * handler will nuke the text. */ public interface DeleteRange extends GtkTextBuffer.DeleteRangeSignal { public void onDeleteRange(TextBuffer source, TextIter start, TextIter end); } /** * Hook up a handler for <code>TextBuffer.DeleteRange</code> signals on * this TextBuffer. * * @since 4.0.9 */ public void connect(TextBuffer.DeleteRange handler) { GtkTextBuffer.connect(this, handler, false); } /** * Delete text between <code>start</code> and <code>end</code>. (The order * of the two TextIters doesn't matter; this method will delete between * the two regardless). * * <p> * The two TextIters passed to <code>delete()</code> will be reset so as * to point to the location where the text was removed. This can be a * useful feature; since it mutates the TextBuffer, calling this method * will invalidate all other TextIters. * * @since 4.0.9 */ public void delete(TextIter start, TextIter end) { GtkTextBuffer.delete(this, start, end); } }
true
true
private void checkTag(TextTag tag) { if (usingDefaultTable) { if (tag.table != getDefaultTable()) { throw new IllegalArgumentException("\n" + "You cannot apply a TextTag created with the no-arg TextTag() constructor\n" + "to a TextBuffer not likewise constructed with the no-arg TextBuffer()\n" + "constructor."); } } else { if (tag.table != GtkTextBuffer.getTagTable(this)) { throw new IllegalArgumentException("\n" + "You can only apply a TextTag to a TextBuffer created with the same\n" + "TextTagTable."); } } }
private void checkTag(TextTag tag) { if (tag == null) { return; } if (usingDefaultTable) { if (tag.table != getDefaultTable()) { throw new IllegalArgumentException("\n" + "You cannot apply a TextTag created with the no-arg TextTag() constructor\n" + "to a TextBuffer not likewise constructed with the no-arg TextBuffer()\n" + "constructor."); } } else { if (tag.table != GtkTextBuffer.getTagTable(this)) { throw new IllegalArgumentException("\n" + "You can only apply a TextTag to a TextBuffer created with the same\n" + "TextTagTable."); } } }
diff --git a/src/jogl/classes/com/jogamp/opengl/util/GLArrayDataWrapper.java b/src/jogl/classes/com/jogamp/opengl/util/GLArrayDataWrapper.java index 7d08ad08f..f3fa5012f 100644 --- a/src/jogl/classes/com/jogamp/opengl/util/GLArrayDataWrapper.java +++ b/src/jogl/classes/com/jogamp/opengl/util/GLArrayDataWrapper.java @@ -1,393 +1,393 @@ /** * Copyright 2010 JogAmp Community. 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. * * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of JogAmp Community. */ package com.jogamp.opengl.util; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.nio.ShortBuffer; import javax.media.opengl.GL; import javax.media.opengl.GL2ES1; import javax.media.opengl.GL2ES2; import javax.media.opengl.GLArrayData; import javax.media.opengl.GLException; import javax.media.opengl.GLProfile; import javax.media.opengl.fixedfunc.GLPointerFuncUtil; import jogamp.opengl.Debug; public class GLArrayDataWrapper implements GLArrayData { public static final boolean DEBUG = Debug.debug("GLArrayData"); /** * Create a VBO, using a predefined fixed function array index, wrapping the given data. * * @param index The GL array index * @param comps The array component number * @param dataType The array index GL data type * @param normalized Whether the data shall be normalized * @param stride * @param buffer the user define data * @param vboName * @param vboOffset * @param vboUsage {@link GL2ES2#GL_STREAM_DRAW}, {@link GL#GL_STATIC_DRAW} or {@link GL#GL_DYNAMIC_DRAW} * @param vboTarget {@link GL#GL_ARRAY_BUFFER} or {@link GL#GL_ELEMENT_ARRAY_BUFFER} * @return the new create instance * * @throws GLException */ public static GLArrayDataWrapper createFixed(int index, int comps, int dataType, boolean normalized, int stride, Buffer buffer, int vboName, long vboOffset, int vboUsage, int vboTarget) throws GLException { GLArrayDataWrapper adc = new GLArrayDataWrapper(); adc.init(null, index, comps, dataType, normalized, stride, buffer, false, vboName, vboOffset, vboUsage, vboTarget); return adc; } /** * Create a VBO, using a custom GLSL array attribute name, wrapping the given data. * * @param name The custom name for the GL attribute, maybe null if gpuBufferTarget is {@link GL#GL_ELEMENT_ARRAY_BUFFER} * @param comps The array component number * @param dataType The array index GL data type * @param normalized Whether the data shall be normalized * @param stride * @param buffer the user define data * @param vboName * @param vboOffset * @param vboUsage {@link GL2ES2#GL_STREAM_DRAW}, {@link GL#GL_STATIC_DRAW} or {@link GL#GL_DYNAMIC_DRAW} * @param vboTarget {@link GL#GL_ARRAY_BUFFER} or {@link GL#GL_ELEMENT_ARRAY_BUFFER} * @return the new create instance * @throws GLException */ public static GLArrayDataWrapper createGLSL(String name, int comps, int dataType, boolean normalized, int stride, Buffer buffer, int vboName, long vboOffset, int vboUsage, int vboTarget) throws GLException { GLArrayDataWrapper adc = new GLArrayDataWrapper(); adc.init(name, -1, comps, dataType, normalized, stride, buffer, true, vboName, vboOffset, vboUsage, vboTarget); return adc; } /** * Validates this instance's parameter. Called automatically by {@link GLArrayDataClient} and {@link GLArrayDataServer}. * {@link GLArrayDataWrapper} does not validate it's instance by itself. * * @param glp the GLProfile to use * @param throwException whether to throw an exception if this instance has invalid parameter or not * @return true if this instance has invalid parameter, otherwise false */ public final boolean validate(GLProfile glp, boolean throwException) { if(!alive) { if(throwException) { throw new GLException("Instance !alive "+this); } return false; } if(this.isVertexAttribute() && !glp.hasGLSL()) { if(throwException) { throw new GLException("GLSL not supported on "+glp+", "+this); } return false; } return glp.isValidArrayDataType(getIndex(), getComponentCount(), getComponentType(), isVertexAttribute(), throwException); } @Override public void associate(Object obj, boolean enable) { // nop } // // Data read access // @Override public final boolean isVertexAttribute() { return isVertexAttribute; } @Override public final int getIndex() { return index; } @Override public final int getLocation() { return location; } @Override public final int setLocation(int v) { location = v; return location; } @Override public final int setLocation(GL2ES2 gl, int program) { location = gl.glGetAttribLocation(program, name); return location; } @Override public final int setLocation(GL2ES2 gl, int program, int location) { this.location = location; gl.glBindAttribLocation(program, location, name); return location; } @Override public final String getName() { return name; } @Override public final long getVBOOffset() { return vboEnabled?vboOffset:0; } @Override public final int getVBOName() { return vboEnabled?vboName:0; } @Override public final boolean isVBO() { return vboEnabled; } @Override public final int getVBOUsage() { return vboEnabled?vboUsage:0; } @Override public final int getVBOTarget() { return vboEnabled?vboTarget:0; } @Override public final Buffer getBuffer() { return buffer; } @Override public final int getComponentCount() { return components; } @Override public final int getComponentType() { return componentType; } @Override public final int getComponentSizeInBytes() { return componentByteSize; } @Override public final int getElementCount() { if(null==buffer) return 0; return ( buffer.position()==0 ) ? ( buffer.limit() / components ) : ( buffer.position() / components ) ; } @Override public final int getSizeInBytes() { if(null==buffer) return 0; return ( buffer.position()==0 ) ? ( buffer.limit() * componentByteSize ) : ( buffer.position() * componentByteSize ) ; } @Override public final boolean getNormalized() { return normalized; } @Override public final int getStride() { return strideB; } public final Class<?> getBufferClass() { return componentClazz; } @Override public void destroy(GL gl) { buffer = null; vboName=0; vboEnabled=false; vboOffset=0; alive = false; } @Override public String toString() { return "GLArrayDataWrapper["+name+ ", index "+index+ ", location "+location+ ", isVertexAttribute "+isVertexAttribute+ ", dataType 0x"+Integer.toHexString(componentType)+ ", bufferClazz "+componentClazz+ ", elements "+getElementCount()+ ", components "+components+ ", stride "+strideB+"b "+strideL+"c"+ ", buffer "+buffer+ ", vboEnabled "+vboEnabled+ ", vboName "+vboName+ ", vboUsage 0x"+Integer.toHexString(vboUsage)+ ", vboTarget 0x"+Integer.toHexString(vboTarget)+ ", vboOffset "+vboOffset+ ", alive "+alive+ "]"; } public static final Class<?> getBufferClass(int dataType) { switch(dataType) { case GL.GL_BYTE: case GL.GL_UNSIGNED_BYTE: return ByteBuffer.class; case GL.GL_SHORT: case GL.GL_UNSIGNED_SHORT: return ShortBuffer.class; case GL2ES1.GL_FIXED: return IntBuffer.class; case GL.GL_FLOAT: return FloatBuffer.class; default: throw new GLException("Given OpenGL data type not supported: "+dataType); } } @Override public void setName(String newName) { location = -1; name = newName; } /** * Enable or disable use of VBO. * Only possible if a VBO buffer name is defined. * @see #setVBOName(int) */ public void setVBOEnabled(boolean vboEnabled) { this.vboEnabled=vboEnabled; } /** * Set the VBO buffer name, if valid (!= 0) enable use of VBO, * otherwise (==0) disable VBO usage. * * @see #setVBOEnabled(boolean) */ public void setVBOName(int vboName) { this.vboName=vboName; setVBOEnabled(0!=vboName); } /** * @param vboUsage {@link GL2ES2#GL_STREAM_DRAW}, {@link GL#GL_STATIC_DRAW} or {@link GL#GL_DYNAMIC_DRAW} */ public void setVBOUsage(int vboUsage) { this.vboUsage = vboUsage; } /** * @param vboTarget either {@link GL#GL_ARRAY_BUFFER} or {@link GL#GL_ELEMENT_ARRAY_BUFFER} */ public void setVBOTarget(int vboTarget) { this.vboTarget = vboTarget; } protected void init(String name, int index, int components, int componentType, boolean normalized, int stride, Buffer data, boolean isVertexAttribute, int vboName, long vboOffset, int vboUsage, int vboTarget) throws GLException { this.isVertexAttribute = isVertexAttribute; this.index = index; this.location = -1; // We can't have any dependence on the FixedFuncUtil class here for build bootstrapping reasons if( GL.GL_ELEMENT_ARRAY_BUFFER == vboTarget ) { - // ok .. - } else if( GL.GL_ARRAY_BUFFER == vboTarget ) { - // check name .. + // OK .. + } else if( ( 0 == vboUsage && 0 == vboTarget ) || GL.GL_ARRAY_BUFFER == vboTarget ) { + // Set/Check name .. - Required for GLSL case. Validation and debug-name for FFP. this.name = ( null == name ) ? GLPointerFuncUtil.getPredefinedArrayIndexName(index) : name ; if(null == this.name ) { throw new GLException("Not a valid array buffer index: "+index); } } else if( 0 < vboTarget ) { throw new GLException("Invalid GPUBuffer target: 0x"+Integer.toHexString(vboTarget)); } this.componentType = componentType; componentClazz = getBufferClass(componentType); if( GLBuffers.isGLTypeFixedPoint(componentType) ) { this.normalized = normalized; } else { this.normalized = false; } componentByteSize = GLBuffers.sizeOfGLType(componentType); if(0 > componentByteSize) { throw new GLException("Given componentType not supported: "+componentType+":\n\t"+this); } if(0 >= components) { throw new GLException("Invalid number of components: " + components); } this.components = components; if(0<stride && stride<components*componentByteSize) { throw new GLException("stride ("+stride+") lower than component bytes, "+components+" * "+componentByteSize); } if(0<stride && stride%componentByteSize!=0) { throw new GLException("stride ("+stride+") not a multiple of bpc "+componentByteSize); } this.buffer = data; this.strideB=(0==stride)?components*componentByteSize:stride; this.strideL=strideB/componentByteSize; this.vboName= vboName; this.vboEnabled= 0 != vboName ; this.vboOffset=vboOffset; switch(vboUsage) { case 0: // nop case GL.GL_STATIC_DRAW: case GL.GL_DYNAMIC_DRAW: case GL2ES2.GL_STREAM_DRAW: break; default: throw new GLException("invalid gpuBufferUsage: "+vboUsage+":\n\t"+this); } switch(vboTarget) { case 0: // nop case GL.GL_ARRAY_BUFFER: case GL.GL_ELEMENT_ARRAY_BUFFER: break; default: throw new GLException("invalid gpuBufferTarget: "+vboTarget+":\n\t"+this); } this.vboUsage=vboUsage; this.vboTarget=vboTarget; this.alive=true; } protected GLArrayDataWrapper() { } protected boolean alive; protected int index; protected int location; protected String name; protected int components; protected int componentType; protected Class<?> componentClazz; protected int componentByteSize; protected boolean normalized; protected int strideB; // stride in bytes protected int strideL; // stride in logical components protected Buffer buffer; protected boolean isVertexAttribute; protected long vboOffset; protected int vboName; protected boolean vboEnabled; protected int vboUsage; protected int vboTarget; }
true
true
protected void init(String name, int index, int components, int componentType, boolean normalized, int stride, Buffer data, boolean isVertexAttribute, int vboName, long vboOffset, int vboUsage, int vboTarget) throws GLException { this.isVertexAttribute = isVertexAttribute; this.index = index; this.location = -1; // We can't have any dependence on the FixedFuncUtil class here for build bootstrapping reasons if( GL.GL_ELEMENT_ARRAY_BUFFER == vboTarget ) { // ok .. } else if( GL.GL_ARRAY_BUFFER == vboTarget ) { // check name .. this.name = ( null == name ) ? GLPointerFuncUtil.getPredefinedArrayIndexName(index) : name ; if(null == this.name ) { throw new GLException("Not a valid array buffer index: "+index); } } else if( 0 < vboTarget ) { throw new GLException("Invalid GPUBuffer target: 0x"+Integer.toHexString(vboTarget)); } this.componentType = componentType; componentClazz = getBufferClass(componentType); if( GLBuffers.isGLTypeFixedPoint(componentType) ) { this.normalized = normalized; } else { this.normalized = false; } componentByteSize = GLBuffers.sizeOfGLType(componentType); if(0 > componentByteSize) { throw new GLException("Given componentType not supported: "+componentType+":\n\t"+this); } if(0 >= components) { throw new GLException("Invalid number of components: " + components); } this.components = components; if(0<stride && stride<components*componentByteSize) { throw new GLException("stride ("+stride+") lower than component bytes, "+components+" * "+componentByteSize); } if(0<stride && stride%componentByteSize!=0) { throw new GLException("stride ("+stride+") not a multiple of bpc "+componentByteSize); } this.buffer = data; this.strideB=(0==stride)?components*componentByteSize:stride; this.strideL=strideB/componentByteSize; this.vboName= vboName; this.vboEnabled= 0 != vboName ; this.vboOffset=vboOffset; switch(vboUsage) { case 0: // nop case GL.GL_STATIC_DRAW: case GL.GL_DYNAMIC_DRAW: case GL2ES2.GL_STREAM_DRAW: break; default: throw new GLException("invalid gpuBufferUsage: "+vboUsage+":\n\t"+this); } switch(vboTarget) { case 0: // nop case GL.GL_ARRAY_BUFFER: case GL.GL_ELEMENT_ARRAY_BUFFER: break; default: throw new GLException("invalid gpuBufferTarget: "+vboTarget+":\n\t"+this); } this.vboUsage=vboUsage; this.vboTarget=vboTarget; this.alive=true; }
protected void init(String name, int index, int components, int componentType, boolean normalized, int stride, Buffer data, boolean isVertexAttribute, int vboName, long vboOffset, int vboUsage, int vboTarget) throws GLException { this.isVertexAttribute = isVertexAttribute; this.index = index; this.location = -1; // We can't have any dependence on the FixedFuncUtil class here for build bootstrapping reasons if( GL.GL_ELEMENT_ARRAY_BUFFER == vboTarget ) { // OK .. } else if( ( 0 == vboUsage && 0 == vboTarget ) || GL.GL_ARRAY_BUFFER == vboTarget ) { // Set/Check name .. - Required for GLSL case. Validation and debug-name for FFP. this.name = ( null == name ) ? GLPointerFuncUtil.getPredefinedArrayIndexName(index) : name ; if(null == this.name ) { throw new GLException("Not a valid array buffer index: "+index); } } else if( 0 < vboTarget ) { throw new GLException("Invalid GPUBuffer target: 0x"+Integer.toHexString(vboTarget)); } this.componentType = componentType; componentClazz = getBufferClass(componentType); if( GLBuffers.isGLTypeFixedPoint(componentType) ) { this.normalized = normalized; } else { this.normalized = false; } componentByteSize = GLBuffers.sizeOfGLType(componentType); if(0 > componentByteSize) { throw new GLException("Given componentType not supported: "+componentType+":\n\t"+this); } if(0 >= components) { throw new GLException("Invalid number of components: " + components); } this.components = components; if(0<stride && stride<components*componentByteSize) { throw new GLException("stride ("+stride+") lower than component bytes, "+components+" * "+componentByteSize); } if(0<stride && stride%componentByteSize!=0) { throw new GLException("stride ("+stride+") not a multiple of bpc "+componentByteSize); } this.buffer = data; this.strideB=(0==stride)?components*componentByteSize:stride; this.strideL=strideB/componentByteSize; this.vboName= vboName; this.vboEnabled= 0 != vboName ; this.vboOffset=vboOffset; switch(vboUsage) { case 0: // nop case GL.GL_STATIC_DRAW: case GL.GL_DYNAMIC_DRAW: case GL2ES2.GL_STREAM_DRAW: break; default: throw new GLException("invalid gpuBufferUsage: "+vboUsage+":\n\t"+this); } switch(vboTarget) { case 0: // nop case GL.GL_ARRAY_BUFFER: case GL.GL_ELEMENT_ARRAY_BUFFER: break; default: throw new GLException("invalid gpuBufferTarget: "+vboTarget+":\n\t"+this); } this.vboUsage=vboUsage; this.vboTarget=vboTarget; this.alive=true; }
diff --git a/src/de/uni_hamburg/informatik/sep/zuul/server/befehle/BefehlFactory.java b/src/de/uni_hamburg/informatik/sep/zuul/server/befehle/BefehlFactory.java index 3ac81d9..e613052 100644 --- a/src/de/uni_hamburg/informatik/sep/zuul/server/befehle/BefehlFactory.java +++ b/src/de/uni_hamburg/informatik/sep/zuul/server/befehle/BefehlFactory.java @@ -1,118 +1,118 @@ package de.uni_hamburg.informatik.sep.zuul.server.befehle; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import de.uni_hamburg.informatik.sep.zuul.server.features.BeinStellen; public final class BefehlFactory { private static final Map<String, Befehl> _map; static { Befehl[] befehle = new Befehl[] { new BefehlGehe(), new BefehlHilfe(), new BefehlNehmen(), new BefehlEssenBoden(), new BefehlEssenTasche(), new BefehlEssenTascheGuterKruemel(), new BefehlEssenTascheSchlechterKruemel(), new BefehlEssenTascheUnbekannterKruemel(), new BefehlBeenden(), new BefehlUntersuche(), new BefehlInventarAnzeigen(), new BefehlFuettere(), new BefehlFuettereSchlechterKruemel(), new BefehlFuettereGuterKruemel(), new BefehlFuettereUnbekanntenKruemel(), new BefehlAblegen(), new BefehlAblegenKruemel(), new BefehlAblegenGuterKruemel(), new BefehlAblegenSchlechterKruemel(), new BefehlSchauen(), new BefehlGibMirMehrLeben(), new BeinStellen(), new BefehlDebug() }; _map = new HashMap<String, Befehl>(); for(Befehl befehl : befehle) { for(String alias : befehl.getBefehlsnamen()) { _map.put(alias, befehl); } } } public static Befehl gibBefehl(Class<?> befehlsKlasse) { for(Befehl befehl : _map.values()) { if(befehlsKlasse.isInstance(befehl)) return befehl; } return null; } /** * @param kontext * @param spieler * @param befehlszeile */ public static Befehl gibBefehl(Befehlszeile befehlszeile) { List<String> geparsteZeile = befehlszeile.getGeparsteZeile(); Collection<String> befehlsnamen = moeglicheBefehlsnamen(geparsteZeile); for(String befehlsname : befehlsnamen) { Befehl befehl = _map.get(befehlsname); if(befehl != null) { return befehl; } } return null; } /** * Gibt mögliche Befehle zurück. gib mir mehr leben => { gib mir mehr leben, * gib mir mehr, gib mir, gib } * * @param geparsteZeile * @return */ private static Collection<String> moeglicheBefehlsnamen( List<String> geparsteZeile) { ArrayList<String> befehlsnamen = new ArrayList<String>(); if(geparsteZeile.size() == 0) return befehlsnamen; for(int i = 0; i < geparsteZeile.size(); i++) befehlsnamen.add(""); for(int i = 0; i < geparsteZeile.size(); i++) { for(int j = i; j < geparsteZeile.size(); j++) { String previous = befehlsnamen.get(j); - if(previous != "") + if(!previous.isEmpty()) previous += " "; befehlsnamen.set(j, previous + geparsteZeile.get(i)); } } Collections.reverse(befehlsnamen); return befehlsnamen; } public static Befehl gibBefehl(String string) { return _map.get(string); } /** * @return the Map */ public static Map<String, Befehl> getMap() { return _map; } }
true
true
private static Collection<String> moeglicheBefehlsnamen( List<String> geparsteZeile) { ArrayList<String> befehlsnamen = new ArrayList<String>(); if(geparsteZeile.size() == 0) return befehlsnamen; for(int i = 0; i < geparsteZeile.size(); i++) befehlsnamen.add(""); for(int i = 0; i < geparsteZeile.size(); i++) { for(int j = i; j < geparsteZeile.size(); j++) { String previous = befehlsnamen.get(j); if(previous != "") previous += " "; befehlsnamen.set(j, previous + geparsteZeile.get(i)); } } Collections.reverse(befehlsnamen); return befehlsnamen; }
private static Collection<String> moeglicheBefehlsnamen( List<String> geparsteZeile) { ArrayList<String> befehlsnamen = new ArrayList<String>(); if(geparsteZeile.size() == 0) return befehlsnamen; for(int i = 0; i < geparsteZeile.size(); i++) befehlsnamen.add(""); for(int i = 0; i < geparsteZeile.size(); i++) { for(int j = i; j < geparsteZeile.size(); j++) { String previous = befehlsnamen.get(j); if(!previous.isEmpty()) previous += " "; befehlsnamen.set(j, previous + geparsteZeile.get(i)); } } Collections.reverse(befehlsnamen); return befehlsnamen; }
diff --git a/src/edu/sc/seis/sod/RunProperties.java b/src/edu/sc/seis/sod/RunProperties.java index 533feb5f2..bddf7e65f 100755 --- a/src/edu/sc/seis/sod/RunProperties.java +++ b/src/edu/sc/seis/sod/RunProperties.java @@ -1,117 +1,117 @@ /** * RunProperties.java * * @author Charles Groves */ package edu.sc.seis.sod; import org.w3c.dom.Element; import edu.iris.Fissures.model.TimeInterval; import edu.iris.Fissures.model.UnitImpl; public class RunProperties{ public RunProperties(Element el) throws ConfigurationException{ Element runNameChild = SodUtil.getElement(el, "runName"); if(runNameChild != null ){ runName = SodUtil.getText(runNameChild); CookieJar.getCommonContext().put("runName", runName); } Element statusBaseChild = SodUtil.getElement(el, "statusBase"); if(statusBaseChild != null){ statusDir = SodUtil.getText(statusBaseChild); } Element eventQueryChild = SodUtil.getElement(el, "eventQueryIncrement"); if(eventQueryChild != null){ eventQueryIncrement = SodUtil.loadTimeInterval(eventQueryChild); } Element eventLagChild = SodUtil.getElement(el, "eventLag"); if(eventLagChild != null){ eventLag = SodUtil.loadTimeInterval(eventLagChild); } Element eventRefreshChild = SodUtil.getElement(el, "eventRefreshInterval"); if(eventRefreshChild != null){ eventRefresh = SodUtil.loadTimeInterval(eventRefreshChild); } Element maxRetryChild = SodUtil.getElement(el, "maxRetryDelay"); if(maxRetryChild != null){ maxRetry = SodUtil.loadTimeInterval(maxRetryChild); } Element serverRetryChild = SodUtil.getElement(el, "serverRetryDelay"); - if(maxRetryChild != null){ - serverRetryDelay = SodUtil.loadTimeInterval(maxRetryChild); + if(serverRetryChild != null){ + serverRetryDelay = SodUtil.loadTimeInterval(serverRetryChild); } Element numWorkersChild = SodUtil.getElement(el, "waveformWorkerThreads"); if(numWorkersChild != null){ numWorkers = Integer.parseInt(SodUtil.getText(numWorkersChild)); } Element evChanPairProcChild = SodUtil.getElement(el, "eventChannelPairProcessing"); if(evChanPairProcChild != null){ evChanPairProc = SodUtil.getText(evChanPairProcChild); } if(SodUtil.isTrue(el, "reopenEvents")){ reopenEvents = true; } - if(SodUtil.isTrue(el, "reopenEvents")){ + if(SodUtil.isTrue(el, "removeDatabase")){ removeDatabase = true; } } public TimeInterval getMaxRetryDelay() { return maxRetry; } public TimeInterval getServerRetryDelay(){ return serverRetryDelay; } public TimeInterval getEventQueryIncrement() { return eventQueryIncrement; } public TimeInterval getEventLag() { return eventLag; } public TimeInterval getEventRefreshInterval() { return eventRefresh; } public String getRunName(){ return runName; } public String getStatusBaseDir(){ return statusDir; } public int getNumWaveformWorkerThreads(){ return numWorkers; } public boolean reopenEvents(){ return reopenEvents; } public boolean removeDatabase(){ return removeDatabase; } public String getEventChannelPairProcessing(){ return evChanPairProc; } public static final TimeInterval NO_TIME = new TimeInterval(0, UnitImpl.SECOND); public static final TimeInterval ONE_WEEK = new TimeInterval(7, UnitImpl.DAY); public static final TimeInterval TEN_MIN = new TimeInterval(10, UnitImpl.MINUTE); public static final TimeInterval DAYS_180 = new TimeInterval(180, UnitImpl.DAY); private TimeInterval eventQueryIncrement = ONE_WEEK; private TimeInterval eventLag = ONE_WEEK; private TimeInterval eventRefresh = TEN_MIN; private TimeInterval maxRetry = DAYS_180; private TimeInterval serverRetryDelay = NO_TIME; private String runName = "Your Sod"; private String statusDir = "status"; private int numWorkers = 1; private boolean reopenEvents = false; private boolean removeDatabase = false; public static final String AT_LEAST_ONCE = "atLeastOnce"; public static final String AT_MOST_ONCE = "atMostOnce"; private String evChanPairProc = AT_LEAST_ONCE; }
false
true
public RunProperties(Element el) throws ConfigurationException{ Element runNameChild = SodUtil.getElement(el, "runName"); if(runNameChild != null ){ runName = SodUtil.getText(runNameChild); CookieJar.getCommonContext().put("runName", runName); } Element statusBaseChild = SodUtil.getElement(el, "statusBase"); if(statusBaseChild != null){ statusDir = SodUtil.getText(statusBaseChild); } Element eventQueryChild = SodUtil.getElement(el, "eventQueryIncrement"); if(eventQueryChild != null){ eventQueryIncrement = SodUtil.loadTimeInterval(eventQueryChild); } Element eventLagChild = SodUtil.getElement(el, "eventLag"); if(eventLagChild != null){ eventLag = SodUtil.loadTimeInterval(eventLagChild); } Element eventRefreshChild = SodUtil.getElement(el, "eventRefreshInterval"); if(eventRefreshChild != null){ eventRefresh = SodUtil.loadTimeInterval(eventRefreshChild); } Element maxRetryChild = SodUtil.getElement(el, "maxRetryDelay"); if(maxRetryChild != null){ maxRetry = SodUtil.loadTimeInterval(maxRetryChild); } Element serverRetryChild = SodUtil.getElement(el, "serverRetryDelay"); if(maxRetryChild != null){ serverRetryDelay = SodUtil.loadTimeInterval(maxRetryChild); } Element numWorkersChild = SodUtil.getElement(el, "waveformWorkerThreads"); if(numWorkersChild != null){ numWorkers = Integer.parseInt(SodUtil.getText(numWorkersChild)); } Element evChanPairProcChild = SodUtil.getElement(el, "eventChannelPairProcessing"); if(evChanPairProcChild != null){ evChanPairProc = SodUtil.getText(evChanPairProcChild); } if(SodUtil.isTrue(el, "reopenEvents")){ reopenEvents = true; } if(SodUtil.isTrue(el, "reopenEvents")){ removeDatabase = true; } }
public RunProperties(Element el) throws ConfigurationException{ Element runNameChild = SodUtil.getElement(el, "runName"); if(runNameChild != null ){ runName = SodUtil.getText(runNameChild); CookieJar.getCommonContext().put("runName", runName); } Element statusBaseChild = SodUtil.getElement(el, "statusBase"); if(statusBaseChild != null){ statusDir = SodUtil.getText(statusBaseChild); } Element eventQueryChild = SodUtil.getElement(el, "eventQueryIncrement"); if(eventQueryChild != null){ eventQueryIncrement = SodUtil.loadTimeInterval(eventQueryChild); } Element eventLagChild = SodUtil.getElement(el, "eventLag"); if(eventLagChild != null){ eventLag = SodUtil.loadTimeInterval(eventLagChild); } Element eventRefreshChild = SodUtil.getElement(el, "eventRefreshInterval"); if(eventRefreshChild != null){ eventRefresh = SodUtil.loadTimeInterval(eventRefreshChild); } Element maxRetryChild = SodUtil.getElement(el, "maxRetryDelay"); if(maxRetryChild != null){ maxRetry = SodUtil.loadTimeInterval(maxRetryChild); } Element serverRetryChild = SodUtil.getElement(el, "serverRetryDelay"); if(serverRetryChild != null){ serverRetryDelay = SodUtil.loadTimeInterval(serverRetryChild); } Element numWorkersChild = SodUtil.getElement(el, "waveformWorkerThreads"); if(numWorkersChild != null){ numWorkers = Integer.parseInt(SodUtil.getText(numWorkersChild)); } Element evChanPairProcChild = SodUtil.getElement(el, "eventChannelPairProcessing"); if(evChanPairProcChild != null){ evChanPairProc = SodUtil.getText(evChanPairProcChild); } if(SodUtil.isTrue(el, "reopenEvents")){ reopenEvents = true; } if(SodUtil.isTrue(el, "removeDatabase")){ removeDatabase = true; } }
diff --git a/src/com/aragaer/reminder/ReminderCatcher.java b/src/com/aragaer/reminder/ReminderCatcher.java index eb9d343..9f8bae8 100644 --- a/src/com/aragaer/reminder/ReminderCatcher.java +++ b/src/com/aragaer/reminder/ReminderCatcher.java @@ -1,30 +1,31 @@ package com.aragaer.reminder; import android.app.Activity; import android.content.Intent; import android.os.Bundle; public class ReminderCatcher extends Activity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); int glyph_width = getResources().getDimensionPixelSize(R.dimen.notification_height); int position = (int) ReminderService.x / glyph_width; Intent i; - if (ReminderService.list == null || position > ReminderService.list.size()) + if (ReminderService.list == null + || position >= ReminderService.list.size()) i = new Intent(this, ReminderListActivity.class); else { final ReminderItem item = ReminderService.list.get(position); if (item._id == -1) i = new Intent(this, ReminderCreateActivity.class); else { i = new Intent(this, ReminderViewActivity.class); - i.putExtra("reminder_id", item._id); + i.putExtra("reminder_id", item._id); } } i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); startActivity(i); finish(); } }
false
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); int glyph_width = getResources().getDimensionPixelSize(R.dimen.notification_height); int position = (int) ReminderService.x / glyph_width; Intent i; if (ReminderService.list == null || position > ReminderService.list.size()) i = new Intent(this, ReminderListActivity.class); else { final ReminderItem item = ReminderService.list.get(position); if (item._id == -1) i = new Intent(this, ReminderCreateActivity.class); else { i = new Intent(this, ReminderViewActivity.class); i.putExtra("reminder_id", item._id); } } i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); startActivity(i); finish(); }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); int glyph_width = getResources().getDimensionPixelSize(R.dimen.notification_height); int position = (int) ReminderService.x / glyph_width; Intent i; if (ReminderService.list == null || position >= ReminderService.list.size()) i = new Intent(this, ReminderListActivity.class); else { final ReminderItem item = ReminderService.list.get(position); if (item._id == -1) i = new Intent(this, ReminderCreateActivity.class); else { i = new Intent(this, ReminderViewActivity.class); i.putExtra("reminder_id", item._id); } } i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); startActivity(i); finish(); }
diff --git a/src/FE_SRC_COMMON/com/ForgeEssentials/WorldBorder/WorldBorder.java b/src/FE_SRC_COMMON/com/ForgeEssentials/WorldBorder/WorldBorder.java index f339c4470..1ad98f7ed 100644 --- a/src/FE_SRC_COMMON/com/ForgeEssentials/WorldBorder/WorldBorder.java +++ b/src/FE_SRC_COMMON/com/ForgeEssentials/WorldBorder/WorldBorder.java @@ -1,156 +1,156 @@ package com.ForgeEssentials.WorldBorder; import net.minecraft.entity.player.EntityPlayerMP; import com.ForgeEssentials.api.data.DataStorageManager; import com.ForgeEssentials.api.data.IReconstructData; import com.ForgeEssentials.api.data.SaveableObject; import com.ForgeEssentials.api.data.SaveableObject.Reconstructor; import com.ForgeEssentials.api.data.SaveableObject.SaveableField; import com.ForgeEssentials.api.data.SaveableObject.UniqueLoadingKey; import com.ForgeEssentials.api.permissions.Zone; import com.ForgeEssentials.util.AreaSelector.Point; @SaveableObject public class WorldBorder { @UniqueLoadingKey @SaveableField public String zone; @SaveableField public Point center; @SaveableField public int rad; @SaveableField public byte shapeByte; // 1 = square, 2 = round. @SaveableField public boolean enabled; /** * For new borders * @param world */ public WorldBorder(Zone zone, Point center, int rad, byte shape) { if (zone.isGlobalZone() || zone.isWorldZone()) { this.zone = zone.getZoneName(); this.center = center; this.rad = rad; this.shapeByte = shape; this.enabled = true; } else { throw new RuntimeException(zone.getZoneName() + " is not the global zone or a worldzone"); } } public WorldBorder(Zone zone) { if (zone.isGlobalZone() || zone.isWorldZone()) { this.zone = zone.getZoneName(); this.center = new Point(0, 0, 0); this.rad = 0; this.shapeByte = 0; this.enabled = false; } else { throw new RuntimeException(zone.getZoneName() + " is not the global zone or a worldzone"); } } public WorldBorder(String zone, Object center, Object rad, Object shapeByte, Object enabled) { this.zone = zone; this.center = (Point) center; this.rad = (Integer) rad; this.shapeByte = (Byte) shapeByte; this.enabled = (Boolean) enabled; } @Reconstructor private static WorldBorder reconstruct(IReconstructData tag) { return new WorldBorder(tag.getUniqueKey(), tag.getFieldValue("center"), tag.getFieldValue("rad"), tag.getFieldValue("shapeByte"), tag.getFieldValue("enabled")); } public void check(EntityPlayerMP player) { // 1 = square if (shapeByte == 1) { - int dist = ModuleWorldBorder.getDistanceRound(center, player); - if (dist > rad) - { - ModuleWorldBorder.executeClosestEffects(this, dist, player); - } - } - // 2 = round - else if (shapeByte == 2) - { if (player.posX < (center.x - rad)) { ModuleWorldBorder.executeClosestEffects(this, player.posX - (center.x - rad), player); } if (player.posX > (center.x + rad)) { ModuleWorldBorder.executeClosestEffects(this, player.posX - (center.x + rad), player); } if (player.posZ < (center.z - rad)) { ModuleWorldBorder.executeClosestEffects(this, player.posZ - (center.z - rad), player); } if (player.posZ > (center.z + rad)) { ModuleWorldBorder.executeClosestEffects(this, player.posZ - (center.z + rad), player); } } + // 2 = round + else if (shapeByte == 2) + { + int dist = ModuleWorldBorder.getDistanceRound(center, player); + if (dist > rad) + { + ModuleWorldBorder.executeClosestEffects(this, dist, player); + } + } } public int getETA() { try { // 1 = square if (shapeByte == 1) { return (int) Math.pow((rad*2), 2); } // 2 = round else if (shapeByte == 2) { return (int) (Math.pow(rad, 2) * Math.PI); } } catch (Exception e) { e.printStackTrace(); } return 0; } public void save() { DataStorageManager.getReccomendedDriver().saveObject(ModuleWorldBorder.con, this); } public String getShape() { switch(shapeByte) { case 1: return "square"; case 2: return "round"; default: return "not set"; } } }
false
true
public void check(EntityPlayerMP player) { // 1 = square if (shapeByte == 1) { int dist = ModuleWorldBorder.getDistanceRound(center, player); if (dist > rad) { ModuleWorldBorder.executeClosestEffects(this, dist, player); } } // 2 = round else if (shapeByte == 2) { if (player.posX < (center.x - rad)) { ModuleWorldBorder.executeClosestEffects(this, player.posX - (center.x - rad), player); } if (player.posX > (center.x + rad)) { ModuleWorldBorder.executeClosestEffects(this, player.posX - (center.x + rad), player); } if (player.posZ < (center.z - rad)) { ModuleWorldBorder.executeClosestEffects(this, player.posZ - (center.z - rad), player); } if (player.posZ > (center.z + rad)) { ModuleWorldBorder.executeClosestEffects(this, player.posZ - (center.z + rad), player); } } }
public void check(EntityPlayerMP player) { // 1 = square if (shapeByte == 1) { if (player.posX < (center.x - rad)) { ModuleWorldBorder.executeClosestEffects(this, player.posX - (center.x - rad), player); } if (player.posX > (center.x + rad)) { ModuleWorldBorder.executeClosestEffects(this, player.posX - (center.x + rad), player); } if (player.posZ < (center.z - rad)) { ModuleWorldBorder.executeClosestEffects(this, player.posZ - (center.z - rad), player); } if (player.posZ > (center.z + rad)) { ModuleWorldBorder.executeClosestEffects(this, player.posZ - (center.z + rad), player); } } // 2 = round else if (shapeByte == 2) { int dist = ModuleWorldBorder.getDistanceRound(center, player); if (dist > rad) { ModuleWorldBorder.executeClosestEffects(this, dist, player); } } }
diff --git a/eclipse/plugins/net.sf.orcc.core/src/net/sf/orcc/network/Instance.java b/eclipse/plugins/net.sf.orcc.core/src/net/sf/orcc/network/Instance.java index 90e1afd50..ae2feffb9 100644 --- a/eclipse/plugins/net.sf.orcc.core/src/net/sf/orcc/network/Instance.java +++ b/eclipse/plugins/net.sf.orcc.core/src/net/sf/orcc/network/Instance.java @@ -1,464 +1,466 @@ /* * Copyright (c) 2009, IETR/INSA of Rennes * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the IETR/INSA of Rennes nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY * WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ package net.sf.orcc.network; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import net.sf.orcc.OrccException; import net.sf.orcc.ir.Actor; import net.sf.orcc.ir.Expression; import net.sf.orcc.ir.serialize.IRParser; import net.sf.orcc.moc.MoC; import net.sf.orcc.network.attributes.IAttribute; import net.sf.orcc.network.attributes.IAttributeContainer; /** * This class defines an instance. An instance has an id, a class, parameters * and attributes. The class of the instance points to an actor or a network. * * @author Matthieu Wipliez * */ public class Instance implements Comparable<Instance>, IAttributeContainer { /** * the actor referenced by this instance. May be <code>null</code> if this * instance references a network or a broadcast. */ private Actor actor; /** * attributes */ private Map<String, IAttribute> attributes; /** * the broadcast referenced by this instance. May be <code>null</code> if * this instance references an actor or a network. */ private Broadcast broadcast; /** * the class of this instance */ private String clasz; /** * the absolute path this instance is defined in */ private File file; /** * the path of classes from the top-level to this instance. */ private List<String> hierarchicalClass; /** * the path of identifiers from the top-level to this instance. */ private List<String> hierarchicalId; /** * the id of this instance */ private String id; /** * the network referenced by this instance. May be <code>null</code> if this * instance references an actor or a broadcast. */ private Network network; /** * the parameters of this instance */ private Map<String, Expression> parameters; private Instance parent; /** * the serializer/deserializer referenced by this instance. */ private SerDes serdes; /** * Creates a new instance with the given id and class. * * @param id * instance identifier * @param clasz * the class of the instance */ public Instance(String id, String clasz) { this.id = id; this.clasz = clasz; this.parameters = new HashMap<String, Expression>(); this.attributes = new HashMap<String, IAttribute>(); this.hierarchicalId = new ArrayList<String>(1); this.hierarchicalId.add(id); this.hierarchicalClass = new ArrayList<String>(1); this.hierarchicalClass.add(clasz); } @Override public int compareTo(Instance instance) { return id.compareTo(instance.id); } /** * Returns the actor referenced by this instance. * * @return the actor referenced by this instance, or <code>null</code> if * this instance does not reference an actor */ public Actor getActor() { return actor; } @Override public IAttribute getAttribute(String name) { return attributes.get(name); } @Override public Map<String, IAttribute> getAttributes() { return attributes; } /** * Returns the broadcast referenced by this instance. * * @return the broadcast referenced by this instance, or <code>null</code> * if this instance does not reference a broadcasst */ public Broadcast getBroadcast() { return broadcast; } /** * Returns the class of this instance. * * @return the class of this instance */ public String getClasz() { return clasz; } /** * Returns the classification class of the instance. * * @return the classification class of this instance */ public MoC getContentClass() { MoC clasz = null; if (isActor()) { clasz = actor.getMoC(); } else { clasz = network.getMoC(); } return clasz; } /** * Returns the file in which this instance is defined. This file is only * valid for instances that refer to actors and were instantiated. * * @return the file in which this instance is defined */ public File getFile() { return file; } /** * Returns the path of classes from the top-level to this instance. * * @return the path of classes from the top-level to this instance */ public List<String> getHierarchicalClass() { return hierarchicalClass; } /** * Returns the path of identifiers from the top-level to this instance. * * @return the path of identifiers from the top-level to this instance */ public List<String> getHierarchicalId() { return hierarchicalId; } /** * Returns the path of identifiers from the top-level to this instance as a * path of the form /top/network/.../instance. * * @return the path of identifiers from the top-level to this instance as a * path of the form /top/network/.../instance */ public String getHierarchicalPath() { StringBuilder builder = new StringBuilder(); for (String id : hierarchicalId) { builder.append('/'); builder.append(id); } return builder.toString(); } /** * Returns the identifier of this instance. * * @return the identifier of this instance */ public String getId() { return id; } /** * Returns the network referenced by this instance. * * @return the network referenced by this instance, or <code>null</code> if * this instance does not reference a network */ public Network getNetwork() { return network; } /** * Returns the parameters of this instance. This is a reference, not a copy. * * @return the parameters of this instance */ public Map<String, Expression> getParameters() { return parameters; } /** * Returns the instance that contains this instance, or <code>null</code>. * * @return the instance that contains this instance, or <code>null</code> */ public Instance getParent() { return parent; } /** * Returns the wrapper referenced by this instance. * * @return the wrapper referenced by this instance, or <code>null</code> if * this instance does not reference a wrapper */ public SerDes getWrapper() { return serdes; } @Override public int hashCode() { // the hash code of an instance is the hash code of its identifier return id.hashCode(); } /** * Tries to load this instance as an actor. * * @param path * the path where actors should be looked up * * @throws OrccException */ public void instantiate(List<String> vtlFolders) throws OrccException { String className = new File(clasz).getName(); for (String path : vtlFolders) { file = new File(path, className.replace('.', '/') + ".json"); if (file.exists()) { break; } else { file = null; } } if (file == null) { throw new OrccException("Actor \"" + className + "\" not found! Did you compile the VTL?"); } actor = Network.getActorFromPool(className); if (actor == null) { // try and load the actor try { InputStream in = new FileInputStream(file); actor = new IRParser().parseActor(in); Network.putActorInPool(className, actor); } catch (OrccException e) { throw new OrccException("Could not parse instance \"" + id + "\" because: " + e.getLocalizedMessage(), e); } catch (FileNotFoundException e) { throw new OrccException("Actor \"" + className - + "\" not found! Did you compile the VTL?", e); + + "\" not found!\nIf this actor has errors, please " + + "correct them and try again; otherwise, try to " + + "refresh/clean projects.", e); } } // replace path-based class by actor class clasz = className; // and update hierarchical class if (!hierarchicalClass.isEmpty()) { int last = hierarchicalClass.size() - 1; hierarchicalClass.remove(last); hierarchicalClass.add(clasz); } } /** * Returns true if this instance references an actor. * * @return true if this instance references an actor. */ public boolean isActor() { return (actor != null); } /** * Returns true if this instance is a broadcast. * * @return true if this instance is a broadcast */ public boolean isBroadcast() { return (broadcast != null); } /** * Returns true if this instance references a network. * * @return true if this instance references a network. */ public boolean isNetwork() { return (network != null); } /** * Returns true if this instance is a wrapper. * * @return true if this instance is a wrapper */ public boolean isSerdes() { return (serdes != null); } /** * Sets the contents of this instance to be that of an actor. Removes any * prior contents. * * @param actor * an actor */ public void setContents(Actor actor) { this.actor = actor; this.broadcast = null; this.network = null; this.serdes = null; } /** * Sets the contents of this instance to be that of a broadcast. Removes any * prior contents. * * @param broadcast * a broadcast */ public void setContents(Broadcast broadcast) { this.actor = null; this.broadcast = broadcast; this.network = null; this.serdes = null; } /** * Sets the contents of this instance to be that of a network. Removes any * prior contents. * * @param network * a network */ public void setContents(Network network) { this.actor = null; this.broadcast = null; this.network = network; this.serdes = null; } /** * Sets the contents of this instance to be that of a serdes. Removes any * prior contents. * * @param serdes * a serdes */ public void setContents(SerDes serdes) { this.actor = null; this.broadcast = null; this.network = null; this.serdes = serdes; } /** * Changes the identifier of this instance. * * @param id * a new identifier */ public void setId(String id) { this.id = id; } /** * Sets the parent of this instance. * * @param parent * the parent of this instance */ public void setParent(Instance parent) { this.parent = parent; } @Override public String toString() { return "\"" + id + "\" instance of \"" + clasz + "\""; } }
true
true
public void instantiate(List<String> vtlFolders) throws OrccException { String className = new File(clasz).getName(); for (String path : vtlFolders) { file = new File(path, className.replace('.', '/') + ".json"); if (file.exists()) { break; } else { file = null; } } if (file == null) { throw new OrccException("Actor \"" + className + "\" not found! Did you compile the VTL?"); } actor = Network.getActorFromPool(className); if (actor == null) { // try and load the actor try { InputStream in = new FileInputStream(file); actor = new IRParser().parseActor(in); Network.putActorInPool(className, actor); } catch (OrccException e) { throw new OrccException("Could not parse instance \"" + id + "\" because: " + e.getLocalizedMessage(), e); } catch (FileNotFoundException e) { throw new OrccException("Actor \"" + className + "\" not found! Did you compile the VTL?", e); } } // replace path-based class by actor class clasz = className; // and update hierarchical class if (!hierarchicalClass.isEmpty()) { int last = hierarchicalClass.size() - 1; hierarchicalClass.remove(last); hierarchicalClass.add(clasz); } }
public void instantiate(List<String> vtlFolders) throws OrccException { String className = new File(clasz).getName(); for (String path : vtlFolders) { file = new File(path, className.replace('.', '/') + ".json"); if (file.exists()) { break; } else { file = null; } } if (file == null) { throw new OrccException("Actor \"" + className + "\" not found! Did you compile the VTL?"); } actor = Network.getActorFromPool(className); if (actor == null) { // try and load the actor try { InputStream in = new FileInputStream(file); actor = new IRParser().parseActor(in); Network.putActorInPool(className, actor); } catch (OrccException e) { throw new OrccException("Could not parse instance \"" + id + "\" because: " + e.getLocalizedMessage(), e); } catch (FileNotFoundException e) { throw new OrccException("Actor \"" + className + "\" not found!\nIf this actor has errors, please " + "correct them and try again; otherwise, try to " + "refresh/clean projects.", e); } } // replace path-based class by actor class clasz = className; // and update hierarchical class if (!hierarchicalClass.isEmpty()) { int last = hierarchicalClass.size() - 1; hierarchicalClass.remove(last); hierarchicalClass.add(clasz); } }
diff --git a/src/main/java/me/xhawk87/CreateYourOwnMenus/commands/menu/MenuGrabCommand.java b/src/main/java/me/xhawk87/CreateYourOwnMenus/commands/menu/MenuGrabCommand.java index eedb5eb..8a7e4a2 100644 --- a/src/main/java/me/xhawk87/CreateYourOwnMenus/commands/menu/MenuGrabCommand.java +++ b/src/main/java/me/xhawk87/CreateYourOwnMenus/commands/menu/MenuGrabCommand.java @@ -1,97 +1,97 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package me.xhawk87.CreateYourOwnMenus.commands.menu; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import me.xhawk87.CreateYourOwnMenus.CreateYourOwnMenus; import me.xhawk87.CreateYourOwnMenus.Menu; import me.xhawk87.CreateYourOwnMenus.commands.IMenuCommand; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; /** * * @author XHawk87 */ public class MenuGrabCommand implements IMenuCommand { private CreateYourOwnMenus plugin; public MenuGrabCommand(CreateYourOwnMenus plugin) { this.plugin = plugin; } @Override public String getUsage() { return "/menu grab ([player]) [menu id]. Gives copies of all items in the given menu to the specified player (or the sender if no player is given). This will attempt to place items in the same location in the player's inventory as in the menu, starting with the top row as the hotbar."; } @Override public String getPermission() { return "cyom.commands.menu.grab"; } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (args.length < 1 || args.length > 2) { return false; } Player target; int index = 0; if (args.length == 1) { if (sender instanceof Player) { target = (Player) sender; } else { sender.sendMessage("Console must specify a player"); return true; } } else { String playerName = args[index++]; target = plugin.getServer().getPlayer(playerName); if (target == null) { sender.sendMessage("No player matching " + playerName); return true; } } String menuId = args[index++]; Menu menu = plugin.getMenu(menuId); if (menu == null) { sender.sendMessage("There is no menu matching " + menuId); return true; } PlayerInventory inv = target.getInventory(); List<ItemStack> toAdd = new ArrayList<>(); ItemStack[] contents = menu.getInventory().getContents(); for (int i = 0; i < contents.length; i++) { - ItemStack item = contents[i].clone(); + ItemStack item = contents[i]; if (item != null && item.getTypeId() != 0) { if (i < inv.getSize()) { ItemStack replaced = inv.getItem(i); if (replaced != null && replaced.getTypeId() != 0) { toAdd.add(replaced); } - inv.setItem(i, item); + inv.setItem(i, item.clone()); } else { - toAdd.add(item); + toAdd.add(item.clone()); } } } HashMap<Integer, ItemStack> toDrop = inv.addItem(toAdd.toArray(new ItemStack[toAdd.size()])); World world = target.getWorld(); Location location = target.getLocation(); for (ItemStack drop : toDrop.values()) { world.dropItem(location, drop); } sender.sendMessage(menu.getTitle() + " was grabbed for " + target.getDisplayName()); return true; } }
false
true
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (args.length < 1 || args.length > 2) { return false; } Player target; int index = 0; if (args.length == 1) { if (sender instanceof Player) { target = (Player) sender; } else { sender.sendMessage("Console must specify a player"); return true; } } else { String playerName = args[index++]; target = plugin.getServer().getPlayer(playerName); if (target == null) { sender.sendMessage("No player matching " + playerName); return true; } } String menuId = args[index++]; Menu menu = plugin.getMenu(menuId); if (menu == null) { sender.sendMessage("There is no menu matching " + menuId); return true; } PlayerInventory inv = target.getInventory(); List<ItemStack> toAdd = new ArrayList<>(); ItemStack[] contents = menu.getInventory().getContents(); for (int i = 0; i < contents.length; i++) { ItemStack item = contents[i].clone(); if (item != null && item.getTypeId() != 0) { if (i < inv.getSize()) { ItemStack replaced = inv.getItem(i); if (replaced != null && replaced.getTypeId() != 0) { toAdd.add(replaced); } inv.setItem(i, item); } else { toAdd.add(item); } } } HashMap<Integer, ItemStack> toDrop = inv.addItem(toAdd.toArray(new ItemStack[toAdd.size()])); World world = target.getWorld(); Location location = target.getLocation(); for (ItemStack drop : toDrop.values()) { world.dropItem(location, drop); } sender.sendMessage(menu.getTitle() + " was grabbed for " + target.getDisplayName()); return true; }
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (args.length < 1 || args.length > 2) { return false; } Player target; int index = 0; if (args.length == 1) { if (sender instanceof Player) { target = (Player) sender; } else { sender.sendMessage("Console must specify a player"); return true; } } else { String playerName = args[index++]; target = plugin.getServer().getPlayer(playerName); if (target == null) { sender.sendMessage("No player matching " + playerName); return true; } } String menuId = args[index++]; Menu menu = plugin.getMenu(menuId); if (menu == null) { sender.sendMessage("There is no menu matching " + menuId); return true; } PlayerInventory inv = target.getInventory(); List<ItemStack> toAdd = new ArrayList<>(); ItemStack[] contents = menu.getInventory().getContents(); for (int i = 0; i < contents.length; i++) { ItemStack item = contents[i]; if (item != null && item.getTypeId() != 0) { if (i < inv.getSize()) { ItemStack replaced = inv.getItem(i); if (replaced != null && replaced.getTypeId() != 0) { toAdd.add(replaced); } inv.setItem(i, item.clone()); } else { toAdd.add(item.clone()); } } } HashMap<Integer, ItemStack> toDrop = inv.addItem(toAdd.toArray(new ItemStack[toAdd.size()])); World world = target.getWorld(); Location location = target.getLocation(); for (ItemStack drop : toDrop.values()) { world.dropItem(location, drop); } sender.sendMessage(menu.getTitle() + " was grabbed for " + target.getDisplayName()); return true; }
diff --git a/src/test/org/apache/jcs/TestCacheElementRetrieval.java b/src/test/org/apache/jcs/TestCacheElementRetrieval.java index 5629cd26..2f6ac051 100644 --- a/src/test/org/apache/jcs/TestCacheElementRetrieval.java +++ b/src/test/org/apache/jcs/TestCacheElementRetrieval.java @@ -1,51 +1,51 @@ package org.apache.jcs; /* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.apache.jcs.engine.behavior.ICacheElement; import junit.framework.TestCase; /** * @author Aaron Smuts * */ public class TestCacheElementRetrieval extends TestCase { /** * * @throws Exception */ public void testSimpleElementRetrieval() throws Exception { JCS jcs = JCS.getInstance( "testCache1" ); jcs.put( "test_key", "test_data" ); long now = System.currentTimeMillis(); ICacheElement elem = jcs.getCacheElement( "test_key" ); assertEquals( "Name wasn't right", "testCache1", elem.getCacheName() ); - long diff = elem.getElementAttributes().getCreateTime() - now; + long diff = now - elem.getElementAttributes().getCreateTime(); assertTrue( "Create time should have been at or after the call", diff >= 0 ); } }
true
true
public void testSimpleElementRetrieval() throws Exception { JCS jcs = JCS.getInstance( "testCache1" ); jcs.put( "test_key", "test_data" ); long now = System.currentTimeMillis(); ICacheElement elem = jcs.getCacheElement( "test_key" ); assertEquals( "Name wasn't right", "testCache1", elem.getCacheName() ); long diff = elem.getElementAttributes().getCreateTime() - now; assertTrue( "Create time should have been at or after the call", diff >= 0 ); }
public void testSimpleElementRetrieval() throws Exception { JCS jcs = JCS.getInstance( "testCache1" ); jcs.put( "test_key", "test_data" ); long now = System.currentTimeMillis(); ICacheElement elem = jcs.getCacheElement( "test_key" ); assertEquals( "Name wasn't right", "testCache1", elem.getCacheName() ); long diff = now - elem.getElementAttributes().getCreateTime(); assertTrue( "Create time should have been at or after the call", diff >= 0 ); }
diff --git a/bunyan/src/common/bunyan/recipes/RecipesMisc.java b/bunyan/src/common/bunyan/recipes/RecipesMisc.java index 7cf3470..ce9de71 100644 --- a/bunyan/src/common/bunyan/recipes/RecipesMisc.java +++ b/bunyan/src/common/bunyan/recipes/RecipesMisc.java @@ -1,138 +1,138 @@ /** * Copyright (c) Scott Killen, 2012 * * This mod is distributed under the terms of the Minecraft Mod Public * License 1.0, or MMPL. Please check the contents of the license * located in /MMPL-1.0.txt */ package bunyan.recipes; import net.minecraft.src.Block; import net.minecraft.src.Item; import net.minecraft.src.ItemStack; import bunyan.Proxy; import bunyan.blocks.BunyanBlock; import bunyan.blocks.CustomLog; import bunyan.blocks.CustomWood; import bunyan.blocks.WideLog; public class RecipesMisc { public static void addRecipes() { // planks Proxy.addRecipe(new ItemStack(BunyanBlock.plank, 4, CustomWood.metaAcacia), new Object[] { "#", Character.valueOf('#'), new ItemStack(BunyanBlock.wood, 1, CustomLog.metaAcacia) }); Proxy.addRecipe(new ItemStack(BunyanBlock.plank, 4, CustomWood.metaFir), new Object[] { "#", Character.valueOf('#'), new ItemStack(BunyanBlock.wood, 1, CustomLog.metaFir) }); Proxy.addRecipe(new ItemStack(BunyanBlock.plank, 4, CustomWood.metaFir), new Object[] { "#", Character.valueOf('#'), new ItemStack(BunyanBlock.widewood, 1, WideLog.metaFir) }); Proxy.addRecipe(new ItemStack(BunyanBlock.plank, 4, CustomWood.metaRedwood), new Object[] { "#", Character.valueOf('#'), new ItemStack(BunyanBlock.widewood, 1, WideLog.metaRedwood) }); // sticks Proxy.addRecipe(new ItemStack(Item.stick, 4), new Object[] { "#", "#", Character.valueOf('#'), BunyanBlock.plank }); // pressure plate Proxy.addRecipe(new ItemStack(Block.pressurePlatePlanks), new Object[] { "##", Character.valueOf('#'), BunyanBlock.plank }); // bowl Proxy.addRecipe(new ItemStack(Item.bowlEmpty), new Object[] { "# #", " # ", Character.valueOf('#'), BunyanBlock.plank }); // slabs Proxy.addRecipe(new ItemStack(Block.stairSingle, 6, 2), new Object[] { "###", Character.valueOf('#'), BunyanBlock.plank }); // boat Proxy.addRecipe(new ItemStack(Item.boat), new Object[] { "X X", - "XXX", Character.valueOf('a'), BunyanBlock.plank }); + "XXX", Character.valueOf('X'), BunyanBlock.plank }); // door Proxy.addRecipe(new ItemStack(Item.doorWood), new Object[] { "##", "##", "##", Character.valueOf('#'), BunyanBlock.plank }); // trapdoor Proxy.addRecipe(new ItemStack(Block.trapdoor, 2), new Object[] { "aaa", "aaa", Character.valueOf('a'), BunyanBlock.plank }); // stairs Proxy.addRecipe( new ItemStack(Block.stairCompactPlanks), new Object[] { " a", " aa", "aaa", Character.valueOf('a'), BunyanBlock.plank }); // gate Proxy.addRecipe(new ItemStack(Block.fenceGate), new Object[] { "sas", "sas", Character.valueOf('a'), BunyanBlock.plank, Character.valueOf('s'), Item.stick }); // sign Proxy.addRecipe(new ItemStack(Item.sign), new Object[] { "aaa", "aaa", " s ", Character.valueOf('a'), BunyanBlock.plank, Character.valueOf('s'), Item.stick }); // bed Proxy.addRecipe(new ItemStack(Item.bed), new Object[] { "www", "aaa", Character.valueOf('a'), BunyanBlock.plank, Character.valueOf('w'), Block.cloth }); // noteblock Proxy.addRecipe(new ItemStack(Block.music), new Object[] { "aaa", "asa", "aaa", Character.valueOf('a'), BunyanBlock.plank, Character.valueOf('s'), Item.redstone }); // jukebox Proxy.addRecipe( new ItemStack(Block.jukebox), new Object[] { "aaa", "asa", "aaa", Character.valueOf('a'), BunyanBlock.plank, Character.valueOf('s'), Item.diamond }); // piston Proxy.addRecipe(new ItemStack(Block.pistonBase), new Object[] { "aaa", "cic", "crc", Character.valueOf('a'), BunyanBlock.plank, Character.valueOf('c'), Block.cobblestone, Character.valueOf('i'), Item.ingotIron, Character.valueOf('r'), Item.redstone }); // jukebox Proxy.addRecipe(new ItemStack(Block.bookShelf), new Object[] { "aaa", "sss", "aaa", Character.valueOf('a'), BunyanBlock.plank, Character.valueOf('s'), Item.book }); } }
true
true
public static void addRecipes() { // planks Proxy.addRecipe(new ItemStack(BunyanBlock.plank, 4, CustomWood.metaAcacia), new Object[] { "#", Character.valueOf('#'), new ItemStack(BunyanBlock.wood, 1, CustomLog.metaAcacia) }); Proxy.addRecipe(new ItemStack(BunyanBlock.plank, 4, CustomWood.metaFir), new Object[] { "#", Character.valueOf('#'), new ItemStack(BunyanBlock.wood, 1, CustomLog.metaFir) }); Proxy.addRecipe(new ItemStack(BunyanBlock.plank, 4, CustomWood.metaFir), new Object[] { "#", Character.valueOf('#'), new ItemStack(BunyanBlock.widewood, 1, WideLog.metaFir) }); Proxy.addRecipe(new ItemStack(BunyanBlock.plank, 4, CustomWood.metaRedwood), new Object[] { "#", Character.valueOf('#'), new ItemStack(BunyanBlock.widewood, 1, WideLog.metaRedwood) }); // sticks Proxy.addRecipe(new ItemStack(Item.stick, 4), new Object[] { "#", "#", Character.valueOf('#'), BunyanBlock.plank }); // pressure plate Proxy.addRecipe(new ItemStack(Block.pressurePlatePlanks), new Object[] { "##", Character.valueOf('#'), BunyanBlock.plank }); // bowl Proxy.addRecipe(new ItemStack(Item.bowlEmpty), new Object[] { "# #", " # ", Character.valueOf('#'), BunyanBlock.plank }); // slabs Proxy.addRecipe(new ItemStack(Block.stairSingle, 6, 2), new Object[] { "###", Character.valueOf('#'), BunyanBlock.plank }); // boat Proxy.addRecipe(new ItemStack(Item.boat), new Object[] { "X X", "XXX", Character.valueOf('a'), BunyanBlock.plank }); // door Proxy.addRecipe(new ItemStack(Item.doorWood), new Object[] { "##", "##", "##", Character.valueOf('#'), BunyanBlock.plank }); // trapdoor Proxy.addRecipe(new ItemStack(Block.trapdoor, 2), new Object[] { "aaa", "aaa", Character.valueOf('a'), BunyanBlock.plank }); // stairs Proxy.addRecipe( new ItemStack(Block.stairCompactPlanks), new Object[] { " a", " aa", "aaa", Character.valueOf('a'), BunyanBlock.plank }); // gate Proxy.addRecipe(new ItemStack(Block.fenceGate), new Object[] { "sas", "sas", Character.valueOf('a'), BunyanBlock.plank, Character.valueOf('s'), Item.stick }); // sign Proxy.addRecipe(new ItemStack(Item.sign), new Object[] { "aaa", "aaa", " s ", Character.valueOf('a'), BunyanBlock.plank, Character.valueOf('s'), Item.stick }); // bed Proxy.addRecipe(new ItemStack(Item.bed), new Object[] { "www", "aaa", Character.valueOf('a'), BunyanBlock.plank, Character.valueOf('w'), Block.cloth }); // noteblock Proxy.addRecipe(new ItemStack(Block.music), new Object[] { "aaa", "asa", "aaa", Character.valueOf('a'), BunyanBlock.plank, Character.valueOf('s'), Item.redstone }); // jukebox Proxy.addRecipe( new ItemStack(Block.jukebox), new Object[] { "aaa", "asa", "aaa", Character.valueOf('a'), BunyanBlock.plank, Character.valueOf('s'), Item.diamond }); // piston Proxy.addRecipe(new ItemStack(Block.pistonBase), new Object[] { "aaa", "cic", "crc", Character.valueOf('a'), BunyanBlock.plank, Character.valueOf('c'), Block.cobblestone, Character.valueOf('i'), Item.ingotIron, Character.valueOf('r'), Item.redstone }); // jukebox Proxy.addRecipe(new ItemStack(Block.bookShelf), new Object[] { "aaa", "sss", "aaa", Character.valueOf('a'), BunyanBlock.plank, Character.valueOf('s'), Item.book }); }
public static void addRecipes() { // planks Proxy.addRecipe(new ItemStack(BunyanBlock.plank, 4, CustomWood.metaAcacia), new Object[] { "#", Character.valueOf('#'), new ItemStack(BunyanBlock.wood, 1, CustomLog.metaAcacia) }); Proxy.addRecipe(new ItemStack(BunyanBlock.plank, 4, CustomWood.metaFir), new Object[] { "#", Character.valueOf('#'), new ItemStack(BunyanBlock.wood, 1, CustomLog.metaFir) }); Proxy.addRecipe(new ItemStack(BunyanBlock.plank, 4, CustomWood.metaFir), new Object[] { "#", Character.valueOf('#'), new ItemStack(BunyanBlock.widewood, 1, WideLog.metaFir) }); Proxy.addRecipe(new ItemStack(BunyanBlock.plank, 4, CustomWood.metaRedwood), new Object[] { "#", Character.valueOf('#'), new ItemStack(BunyanBlock.widewood, 1, WideLog.metaRedwood) }); // sticks Proxy.addRecipe(new ItemStack(Item.stick, 4), new Object[] { "#", "#", Character.valueOf('#'), BunyanBlock.plank }); // pressure plate Proxy.addRecipe(new ItemStack(Block.pressurePlatePlanks), new Object[] { "##", Character.valueOf('#'), BunyanBlock.plank }); // bowl Proxy.addRecipe(new ItemStack(Item.bowlEmpty), new Object[] { "# #", " # ", Character.valueOf('#'), BunyanBlock.plank }); // slabs Proxy.addRecipe(new ItemStack(Block.stairSingle, 6, 2), new Object[] { "###", Character.valueOf('#'), BunyanBlock.plank }); // boat Proxy.addRecipe(new ItemStack(Item.boat), new Object[] { "X X", "XXX", Character.valueOf('X'), BunyanBlock.plank }); // door Proxy.addRecipe(new ItemStack(Item.doorWood), new Object[] { "##", "##", "##", Character.valueOf('#'), BunyanBlock.plank }); // trapdoor Proxy.addRecipe(new ItemStack(Block.trapdoor, 2), new Object[] { "aaa", "aaa", Character.valueOf('a'), BunyanBlock.plank }); // stairs Proxy.addRecipe( new ItemStack(Block.stairCompactPlanks), new Object[] { " a", " aa", "aaa", Character.valueOf('a'), BunyanBlock.plank }); // gate Proxy.addRecipe(new ItemStack(Block.fenceGate), new Object[] { "sas", "sas", Character.valueOf('a'), BunyanBlock.plank, Character.valueOf('s'), Item.stick }); // sign Proxy.addRecipe(new ItemStack(Item.sign), new Object[] { "aaa", "aaa", " s ", Character.valueOf('a'), BunyanBlock.plank, Character.valueOf('s'), Item.stick }); // bed Proxy.addRecipe(new ItemStack(Item.bed), new Object[] { "www", "aaa", Character.valueOf('a'), BunyanBlock.plank, Character.valueOf('w'), Block.cloth }); // noteblock Proxy.addRecipe(new ItemStack(Block.music), new Object[] { "aaa", "asa", "aaa", Character.valueOf('a'), BunyanBlock.plank, Character.valueOf('s'), Item.redstone }); // jukebox Proxy.addRecipe( new ItemStack(Block.jukebox), new Object[] { "aaa", "asa", "aaa", Character.valueOf('a'), BunyanBlock.plank, Character.valueOf('s'), Item.diamond }); // piston Proxy.addRecipe(new ItemStack(Block.pistonBase), new Object[] { "aaa", "cic", "crc", Character.valueOf('a'), BunyanBlock.plank, Character.valueOf('c'), Block.cobblestone, Character.valueOf('i'), Item.ingotIron, Character.valueOf('r'), Item.redstone }); // jukebox Proxy.addRecipe(new ItemStack(Block.bookShelf), new Object[] { "aaa", "sss", "aaa", Character.valueOf('a'), BunyanBlock.plank, Character.valueOf('s'), Item.book }); }
diff --git a/main/tests/server/src/com/google/refine/tests/exporters/CsvExporterTests.java b/main/tests/server/src/com/google/refine/tests/exporters/CsvExporterTests.java index 7b878706..dc130ef7 100644 --- a/main/tests/server/src/com/google/refine/tests/exporters/CsvExporterTests.java +++ b/main/tests/server/src/com/google/refine/tests/exporters/CsvExporterTests.java @@ -1,244 +1,244 @@ /* Copyright 2010, Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Google Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.google.refine.tests.exporters; import java.io.IOException; import java.io.StringWriter; import java.util.Calendar; import java.util.Date; import java.util.Properties; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.times; import org.slf4j.LoggerFactory; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import com.google.refine.browsing.Engine; import com.google.refine.exporters.CsvExporter; import com.google.refine.model.Cell; import com.google.refine.model.Column; import com.google.refine.model.ModelException; import com.google.refine.model.Project; import com.google.refine.model.Row; import com.google.refine.tests.RefineTest; import com.google.refine.util.ParsingUtilities; public class CsvExporterTests extends RefineTest { @BeforeTest public void init() { logger = LoggerFactory.getLogger(this.getClass()); } //dependencies StringWriter writer; Project project; Engine engine; Properties options; //System Under Test CsvExporter SUT; @BeforeMethod public void SetUp(){ SUT = new CsvExporter(); writer = new StringWriter(); project = new Project(); engine = new Engine(project); options = mock(Properties.class); } @AfterMethod public void TearDown(){ SUT = null; writer = null; project = null; engine = null; options = null; } @Test public void exportSimpleCsv(){ CreateGrid(2, 2); try { SUT.export(project, options, engine, writer); } catch (IOException e) { Assert.fail(); } Assert.assertEquals(writer.toString(), "column0,column1\n" + "row0cell0,row0cell1\n" + "row1cell0,row1cell1\n"); } @Test public void exportSimpleCsvNoHeader(){ CreateGrid(2, 2); when(options.getProperty("printColumnHeader")).thenReturn("false"); try { SUT.export(project, options, engine, writer); } catch (IOException e) { Assert.fail(); } Assert.assertEquals(writer.toString(), "row0cell0,row0cell1\n" + "row1cell0,row1cell1\n"); verify(options,times(2)).getProperty("printColumnHeader"); } @Test public void exportCsvWithLineBreaks(){ CreateGrid(3,3); project.rows.get(1).cells.set(1, new Cell("line\n\n\nbreak", null)); try { SUT.export(project, options, engine, writer); } catch (IOException e) { Assert.fail(); } Assert.assertEquals(writer.toString(), "column0,column1,column2\n" + "row0cell0,row0cell1,row0cell2\n" + "row1cell0,\"line\n\n\nbreak\",row1cell2\n" + "row2cell0,row2cell1,row2cell2\n"); } @Test public void exportCsvWithComma(){ CreateGrid(3,3); project.rows.get(1).cells.set(1, new Cell("with, comma", null)); try { SUT.export(project, options, engine, writer); } catch (IOException e) { Assert.fail(); } Assert.assertEquals(writer.toString(), "column0,column1,column2\n" + "row0cell0,row0cell1,row0cell2\n" + "row1cell0,\"with, comma\",row1cell2\n" + "row2cell0,row2cell1,row2cell2\n"); } @Test public void exportCsvWithQuote(){ CreateGrid(3,3); project.rows.get(1).cells.set(1, new Cell("line has \"quote\"", null)); try { SUT.export(project, options, engine, writer); } catch (IOException e) { Assert.fail(); } Assert.assertEquals(writer.toString(), "column0,column1,column2\n" + "row0cell0,row0cell1,row0cell2\n" + "row1cell0,\"line has \"\"quote\"\"\",row1cell2\n" + "row2cell0,row2cell1,row2cell2\n"); } @Test public void exportCsvWithEmptyCells(){ CreateGrid(3,3); project.rows.get(1).cells.set(1, null); project.rows.get(2).cells.set(0, null); try { SUT.export(project, options, engine, writer); } catch (IOException e) { Assert.fail(); } Assert.assertEquals(writer.toString(), "column0,column1,column2\n" + "row0cell0,row0cell1,row0cell2\n" + "row1cell0,,row1cell2\n" + ",row2cell1,row2cell2\n"); } @Test public void exportDateColumns(){ - CreateGrid(1,1); + CreateGrid(1,2); Calendar calendar = Calendar.getInstance(); Date date = new Date(); when(options.getProperty("printColumnHeader")).thenReturn("false"); project.rows.get(0).cells.set(0, new Cell(calendar, null)); project.rows.get(0).cells.set(1, new Cell(date, null)); try { SUT.export(project, options, engine, writer); } catch (IOException e) { Assert.fail(); } String expectedOutput = ParsingUtilities.dateToString(calendar.getTime()) + "," + ParsingUtilities.dateToString(date) + "\n"; Assert.assertEquals(writer.toString(), expectedOutput); } //helper methods protected void CreateColumns(int noOfColumns){ for(int i = 0; i < noOfColumns; i++){ try { project.columnModel.addColumn(i, new Column(i, "column" + i), true); } catch (ModelException e1) { Assert.fail("Could not create column"); } } } protected void CreateGrid(int noOfRows, int noOfColumns){ CreateColumns(noOfColumns); for(int i = 0; i < noOfRows; i++){ Row row = new Row(noOfColumns); for(int j = 0; j < noOfColumns; j++){ row.cells.add(new Cell("row" + i + "cell" + j, null)); } project.rows.add(row); } } }
true
true
public void exportDateColumns(){ CreateGrid(1,1); Calendar calendar = Calendar.getInstance(); Date date = new Date(); when(options.getProperty("printColumnHeader")).thenReturn("false"); project.rows.get(0).cells.set(0, new Cell(calendar, null)); project.rows.get(0).cells.set(1, new Cell(date, null)); try { SUT.export(project, options, engine, writer); } catch (IOException e) { Assert.fail(); } String expectedOutput = ParsingUtilities.dateToString(calendar.getTime()) + "," + ParsingUtilities.dateToString(date) + "\n"; Assert.assertEquals(writer.toString(), expectedOutput); }
public void exportDateColumns(){ CreateGrid(1,2); Calendar calendar = Calendar.getInstance(); Date date = new Date(); when(options.getProperty("printColumnHeader")).thenReturn("false"); project.rows.get(0).cells.set(0, new Cell(calendar, null)); project.rows.get(0).cells.set(1, new Cell(date, null)); try { SUT.export(project, options, engine, writer); } catch (IOException e) { Assert.fail(); } String expectedOutput = ParsingUtilities.dateToString(calendar.getTime()) + "," + ParsingUtilities.dateToString(date) + "\n"; Assert.assertEquals(writer.toString(), expectedOutput); }
diff --git a/src/com/uiproject/meetingplanner/EditMeeting.java b/src/com/uiproject/meetingplanner/EditMeeting.java index ce2262c..78d0246 100644 --- a/src/com/uiproject/meetingplanner/EditMeeting.java +++ b/src/com/uiproject/meetingplanner/EditMeeting.java @@ -1,398 +1,401 @@ package com.uiproject.meetingplanner; import java.text.ParseException; import java.util.ArrayList; import android.app.Activity; import android.app.AlertDialog; import android.app.DatePickerDialog; import android.app.Dialog; import android.app.TimePickerDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.PorterDuff; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.DatePicker; import android.widget.EditText; import android.widget.Spinner; import android.widget.TextView; import android.widget.TimePicker; import android.widget.Toast; import com.uiproject.meetingplanner.database.MeetingPlannerDatabaseHelper; import com.uiproject.meetingplanner.database.MeetingPlannerDatabaseManager; public class EditMeeting extends Activity { public static final String PREFERENCE_FILENAME = "MeetAppPrefs"; private MeetingPlannerDatabaseManager db; private EditText mname, desc; private Button delete; private int mid, uid; //for date picker private Button mPickDate; private int mYear; private int mMonth; private int mDay; static final int DATE_DIALOG_ID = 0; //for time pickers private Button msPickTime; private int msHour; private int msMinute; static final int TIME_DIALOG_ID_START = 1; private Button mePickTime; private int meHour; private int meMinute; static final int TIME_DIALOG_ID_END = 2; static final int DESC_DIALOG = 3; private boolean ppl_changed = false; protected double trackTime; private Spinner spinner; TextView location, attendees; int lat, lon; String addr, title, description; String uids, names; ArrayList<Integer> uidList; // set listeners private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() { public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { mYear = year; mMonth = monthOfYear; mDay = dayOfMonth; updateDateDisplay(); } }; private TimePickerDialog.OnTimeSetListener msTimeSetListener = new TimePickerDialog.OnTimeSetListener() { public void onTimeSet(TimePicker view, int hourOfDay, int minute) { msHour = hourOfDay; msMinute = minute; updateTimeDisplay(true); } }; private TimePickerDialog.OnTimeSetListener meTimeSetListener = new TimePickerDialog.OnTimeSetListener() { public void onTimeSet(TimePicker view, int hourOfDay, int minute) { meHour = hourOfDay; meMinute = minute; updateTimeDisplay(false); } }; @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.editmeeting); mid = getIntent().getIntExtra("mid", -1); if (mid == -1){ Toast.makeText(getApplicationContext(), "Meeting not found", Toast.LENGTH_SHORT).show(); finish(); return; } SharedPreferences settings = getSharedPreferences(PREFERENCE_FILENAME, MODE_PRIVATE); uid = settings.getInt("uid", -1); mname = (EditText) findViewById(R.id.mname_field); desc = (EditText) findViewById(R.id.desc); mPickDate = (Button) findViewById(R.id.pickDate); msPickTime = (Button) findViewById(R.id.startPickTime); mePickTime = (Button) findViewById(R.id.endPickTime); spinner = (Spinner) findViewById(R.id.tracker_selector); location = (TextView) findViewById(R.id.location); attendees = (TextView) findViewById(R.id.attendees); delete = (Button) findViewById(R.id.delete); delete.getBackground().setColorFilter(0xFFFF0000, PorterDuff.Mode.MULTIPLY); db = new MeetingPlannerDatabaseManager(this, MeetingPlannerDatabaseHelper.DATABASE_VERSION); db.open(); MeetingInstance m = db.getMeeting(mid); db.close(); String date = m.getMeetingDate(); String stime = m.getMeetingStartTime(); String etime = m.getMeetingEndTime(); mYear = Integer.parseInt(date.substring(6)); mMonth = Integer.parseInt(date.substring(0, 2)) - 1; mDay = Integer.parseInt(date.substring(3, 5)); int colon = stime.indexOf(':'); msHour = Integer.parseInt(stime.substring(0, colon)); msMinute = Integer.parseInt(stime.substring(colon + 1, colon + 3)); meHour = Integer.parseInt(etime.substring(0, colon)); meMinute = Integer.parseInt(etime.substring(colon + 1, colon + 3)); int mtrack = m.getMeetingTrackTime(); //Toast.makeText(getApplicationContext(), "track: " + mtrack, Toast.LENGTH_SHORT).show(); //TODO look into tracking time trackTime = (double) m.getMeetingTrackTime() / 60.0; lat = m.getMeetingLat(); lon = m.getMeetingLon(); addr = m.getMeetingAddress(); title = m.getMeetingTitle(); description = m.getMeetingDescription(); db.open(); ArrayList<UserInstance> users =db.getMeetingUsersArray(mid); db.close(); names = ""; + uids = ""; boolean added = false; for (UserInstance u : users){ if (added){ names+= ", "; + uids+=","; } names = names + u.getUserFirstName() + " " + u.getUserLastName(); + uids += u.getUserID(); added = true; } mname.setText(title); desc.setText(description); location.setText(addr); attendees.setText(names); // update date and time displays updateDateDisplay(); updateTimeDisplay(true); updateTimeDisplay(false); // set tracking time ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource( this, R.array.tracker_array, R.layout.spinner_textview); adapter.setDropDownViewResource(R.layout.spinner_textview); spinner.setAdapter(adapter); spinner.setOnItemSelectedListener(new MyOnItemSelectedListener()); int spinnerPosition = adapter.getPosition(trackTime + ""); spinner.setSelection(spinnerPosition); } @Override // this is called when we come back from child activity public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch(requestCode) { case (R.string.editmeetloc) : { // location if (resultCode == Activity.RESULT_OK) { lat = data.getIntExtra("lat", 0); lon = data.getIntExtra("lon", 0); addr = data.getStringExtra("addr"); location.setText(addr); } break; }case (R.string.editmeetattendees): { // people if (resultCode == Activity.RESULT_OK) { uids = data.getStringExtra("uids"); names = data.getStringExtra("names"); attendees.setText(names); ppl_changed = true; } break; } } } public void changeDate(View button){ showDialog(DATE_DIALOG_ID); } public void changeStart(View button){ showDialog(TIME_DIALOG_ID_START); } public void changeEnd(View button){ showDialog(TIME_DIALOG_ID_END); } @Override protected Dialog onCreateDialog(int id) { switch (id) { case DATE_DIALOG_ID: return new DatePickerDialog(this, mDateSetListener, mYear, mMonth, mDay); case TIME_DIALOG_ID_START: return new TimePickerDialog(this, msTimeSetListener, msHour, msMinute, false); case TIME_DIALOG_ID_END: return new TimePickerDialog(this, meTimeSetListener, meHour, meMinute, false); } return null; } // updates the date in the TextView private void updateDateDisplay() { mPickDate.setText( new StringBuilder() // Month is 0 based so add 1 .append(mMonth + 1).append("/") .append(mDay).append("/") .append(mYear).append(" ")); } private void updateTimeDisplay(boolean start) { if(start){ msPickTime.setText( new StringBuilder() .append(pad(msHour)).append(":") .append(pad(msMinute))); }else{ mePickTime.setText( new StringBuilder() .append(pad(meHour)).append(":") .append(pad(meMinute))); } } private static String pad(int c) { if (c >= 10) return String.valueOf(c); else return "0" + String.valueOf(c); } public void saveMeeting(View button) throws ParseException{ Toast.makeText(EditMeeting.this, "meeting saved!", Toast.LENGTH_SHORT).show(); String mtitle = mname.getText().toString(); String mdesc = desc.getText().toString(); String mdate = (mMonth + 1) + "/" + mDay + "/" + mYear; String mstarttime = pad(msHour) + ":" + pad(msMinute); String mendtime = pad(meHour) + ":" + pad(meMinute); addr = "locationtest"; // TODO remove lat = 34; // TODO remove lon = -12; // TODO remove uids ="1"; Communicator.updateMeeting(mid, uid, mtitle, mdesc, lat, lon, addr, mdate, mstarttime, mendtime, (int) (trackTime * 60), uids); db.open(); db.updateMeeting(mid, mtitle, lat, lon, mdesc, addr, mdate, mstarttime, mendtime, (int)(trackTime * 60)); if (ppl_changed){ // need to update uses /* // db.deleteMeetingUsers(mid) int commaIndex; String tempids = uids; String n; uidList = new ArrayList<Integer>(); if (tempids.length() > 0){ while (tempids.length() > 0){ commaIndex = tempids.indexOf(','); if (commaIndex == -1){ int meetingId = Integer.parseInt(tempids); uidList.add(meetingId); break; }else{ n = tempids.substring(0, commaIndex); int meetingId = Integer.parseInt(n); uidList.add(meetingId); tempids = tempids.substring(commaIndex + 1); } } } for (Integer i : uidList){ // add all invited attendees db.createMeetingUser(mid, i, MeetingPlannerDatabaseHelper.ATTENDINGSTATUS_ATTENDING, "0"); } //add meeting creator db.createMeetingUser(mid, uid, MeetingPlannerDatabaseHelper.ATTENDINGSTATUS_ATTENDING, "0"); */ } db.close(); this.finish(); } public void invite(View button){ Intent intent = new Intent(EditMeeting.this, EditMeetingAttendees.class); intent.putExtra("uids", uids); EditMeeting.this.startActivityForResult(intent, R.string.editmeetattendees); } public void selectLocation(View button){ Intent intent = new Intent(EditMeeting.this, EditMeetingLocation.class); intent.putExtra("lat", lat); intent.putExtra("lon", lon); intent.putExtra("addr", addr); EditMeeting.this.startActivityForResult(intent, R.string.editmeetloc); } public void deleteMeeting(View button){ AlertDialog.Builder alt_bld = new AlertDialog.Builder(this); alt_bld.setMessage("Are you sure you want to delete this meeting? You cannot undo this action!"); alt_bld.setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { Toast.makeText(EditMeeting.this, "meeting deleted", Toast.LENGTH_SHORT).show(); //Communicator.removeMeeting(mid); } }); alt_bld.setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); alt_bld.show(); } // for the tracker spinner public class MyOnItemSelectedListener implements OnItemSelectedListener { public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { trackTime = Double.parseDouble(parent.getItemAtPosition(pos).toString()); } public void onNothingSelected(AdapterView parent) { // Do nothing. } } // menu @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.logoutonly, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.logout:{ Logout.logout(this); break; } } return true; } }
false
true
protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.editmeeting); mid = getIntent().getIntExtra("mid", -1); if (mid == -1){ Toast.makeText(getApplicationContext(), "Meeting not found", Toast.LENGTH_SHORT).show(); finish(); return; } SharedPreferences settings = getSharedPreferences(PREFERENCE_FILENAME, MODE_PRIVATE); uid = settings.getInt("uid", -1); mname = (EditText) findViewById(R.id.mname_field); desc = (EditText) findViewById(R.id.desc); mPickDate = (Button) findViewById(R.id.pickDate); msPickTime = (Button) findViewById(R.id.startPickTime); mePickTime = (Button) findViewById(R.id.endPickTime); spinner = (Spinner) findViewById(R.id.tracker_selector); location = (TextView) findViewById(R.id.location); attendees = (TextView) findViewById(R.id.attendees); delete = (Button) findViewById(R.id.delete); delete.getBackground().setColorFilter(0xFFFF0000, PorterDuff.Mode.MULTIPLY); db = new MeetingPlannerDatabaseManager(this, MeetingPlannerDatabaseHelper.DATABASE_VERSION); db.open(); MeetingInstance m = db.getMeeting(mid); db.close(); String date = m.getMeetingDate(); String stime = m.getMeetingStartTime(); String etime = m.getMeetingEndTime(); mYear = Integer.parseInt(date.substring(6)); mMonth = Integer.parseInt(date.substring(0, 2)) - 1; mDay = Integer.parseInt(date.substring(3, 5)); int colon = stime.indexOf(':'); msHour = Integer.parseInt(stime.substring(0, colon)); msMinute = Integer.parseInt(stime.substring(colon + 1, colon + 3)); meHour = Integer.parseInt(etime.substring(0, colon)); meMinute = Integer.parseInt(etime.substring(colon + 1, colon + 3)); int mtrack = m.getMeetingTrackTime(); //Toast.makeText(getApplicationContext(), "track: " + mtrack, Toast.LENGTH_SHORT).show(); //TODO look into tracking time trackTime = (double) m.getMeetingTrackTime() / 60.0; lat = m.getMeetingLat(); lon = m.getMeetingLon(); addr = m.getMeetingAddress(); title = m.getMeetingTitle(); description = m.getMeetingDescription(); db.open(); ArrayList<UserInstance> users =db.getMeetingUsersArray(mid); db.close(); names = ""; boolean added = false; for (UserInstance u : users){ if (added){ names+= ", "; } names = names + u.getUserFirstName() + " " + u.getUserLastName(); added = true; } mname.setText(title); desc.setText(description); location.setText(addr); attendees.setText(names); // update date and time displays updateDateDisplay(); updateTimeDisplay(true); updateTimeDisplay(false); // set tracking time ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource( this, R.array.tracker_array, R.layout.spinner_textview); adapter.setDropDownViewResource(R.layout.spinner_textview); spinner.setAdapter(adapter); spinner.setOnItemSelectedListener(new MyOnItemSelectedListener()); int spinnerPosition = adapter.getPosition(trackTime + ""); spinner.setSelection(spinnerPosition); }
protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.editmeeting); mid = getIntent().getIntExtra("mid", -1); if (mid == -1){ Toast.makeText(getApplicationContext(), "Meeting not found", Toast.LENGTH_SHORT).show(); finish(); return; } SharedPreferences settings = getSharedPreferences(PREFERENCE_FILENAME, MODE_PRIVATE); uid = settings.getInt("uid", -1); mname = (EditText) findViewById(R.id.mname_field); desc = (EditText) findViewById(R.id.desc); mPickDate = (Button) findViewById(R.id.pickDate); msPickTime = (Button) findViewById(R.id.startPickTime); mePickTime = (Button) findViewById(R.id.endPickTime); spinner = (Spinner) findViewById(R.id.tracker_selector); location = (TextView) findViewById(R.id.location); attendees = (TextView) findViewById(R.id.attendees); delete = (Button) findViewById(R.id.delete); delete.getBackground().setColorFilter(0xFFFF0000, PorterDuff.Mode.MULTIPLY); db = new MeetingPlannerDatabaseManager(this, MeetingPlannerDatabaseHelper.DATABASE_VERSION); db.open(); MeetingInstance m = db.getMeeting(mid); db.close(); String date = m.getMeetingDate(); String stime = m.getMeetingStartTime(); String etime = m.getMeetingEndTime(); mYear = Integer.parseInt(date.substring(6)); mMonth = Integer.parseInt(date.substring(0, 2)) - 1; mDay = Integer.parseInt(date.substring(3, 5)); int colon = stime.indexOf(':'); msHour = Integer.parseInt(stime.substring(0, colon)); msMinute = Integer.parseInt(stime.substring(colon + 1, colon + 3)); meHour = Integer.parseInt(etime.substring(0, colon)); meMinute = Integer.parseInt(etime.substring(colon + 1, colon + 3)); int mtrack = m.getMeetingTrackTime(); //Toast.makeText(getApplicationContext(), "track: " + mtrack, Toast.LENGTH_SHORT).show(); //TODO look into tracking time trackTime = (double) m.getMeetingTrackTime() / 60.0; lat = m.getMeetingLat(); lon = m.getMeetingLon(); addr = m.getMeetingAddress(); title = m.getMeetingTitle(); description = m.getMeetingDescription(); db.open(); ArrayList<UserInstance> users =db.getMeetingUsersArray(mid); db.close(); names = ""; uids = ""; boolean added = false; for (UserInstance u : users){ if (added){ names+= ", "; uids+=","; } names = names + u.getUserFirstName() + " " + u.getUserLastName(); uids += u.getUserID(); added = true; } mname.setText(title); desc.setText(description); location.setText(addr); attendees.setText(names); // update date and time displays updateDateDisplay(); updateTimeDisplay(true); updateTimeDisplay(false); // set tracking time ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource( this, R.array.tracker_array, R.layout.spinner_textview); adapter.setDropDownViewResource(R.layout.spinner_textview); spinner.setAdapter(adapter); spinner.setOnItemSelectedListener(new MyOnItemSelectedListener()); int spinnerPosition = adapter.getPosition(trackTime + ""); spinner.setSelection(spinnerPosition); }
diff --git a/src/volpes/ldk/Settings.java b/src/volpes/ldk/Settings.java index 34a7f70..08a80cc 100644 --- a/src/volpes/ldk/Settings.java +++ b/src/volpes/ldk/Settings.java @@ -1,194 +1,194 @@ /* * Copyright (C) 2012 Lasse Dissing Hansen * * 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 volpes.ldk; import java.io.*; import java.util.HashMap; import java.util.Map; /** * @author Lasse Dissing Hansen * @since 0.2 */ public class Settings { private Map<String,Object> data = new HashMap<String,Object>(); private boolean updated; /** * Creates a new settings object, given a file name * @param filename The name of the engine configurations file */ public Settings(String filename) { try { - BufferedReader reader = new BufferedReader(new FileReader(filename)); + BufferedReader reader = new BufferedReader(new InputStreamReader(getClass().getClassLoader().getResourceAsStream(filename))); try { String line; String parts[]; int index = 0; while((line = reader.readLine()) != null) { index++; if (line.contains(":")) { parts = line.split(":"); parts[0] = parts[0].trim(); parts[1] = parts[1].trim(); if (parts[1].matches("-?\\d+")) { data.put(parts[0],Integer.parseInt(parts[1])); } else if (parts[1].matches("-?\\d+(\\.\\d+)?")) { data.put(parts[0],Float.parseFloat(parts[1])); } else if (parts[1].equalsIgnoreCase("true") || parts[1].equalsIgnoreCase("false")) { data.put(parts[0],Boolean.parseBoolean(parts[1])); } else { data.put(parts[0],parts[1]); } } else { throw new LDKException("Line " + index + " expected a :"); } } } finally { reader.close(); } } catch (IOException e) { System.err.println("Unable to locate the engine configuration file \"" + filename + "\" at the games root directory"); System.exit(1); } } /** * Checks if such a key is to be found in the settings map * @param key The key to lookup * @return True if the map contains such a key */ public boolean has(String key) { return data.containsKey(key); } /** * Returns a boolean from the settings map * If there is no such key to be found or the value is not a boolean * the function will return an unspecified exception * Please use the ternary operator in combination with {@link #has(String)} * * boolean result = has(key) ? getBool(key) : default * * @param key The key to lookup in the map * @return The value of the setting */ public boolean getBool(String key) { return (boolean)data.get(key); } /** * Returns a integer from the settings map * If there is no such key to be found or the value is not a integer * the function will return an unspecified exception * Please use the ternary operator in combination with {@link #has(String)} * * boolean result = has(key) ? getInt(key) : default * * @param key The key to lookup in the map * @return The value of the setting */ public int getInt(String key) { return (int)data.get(key); } /** * Returns a float from the settings map * If there is no such key to be found or the value is not a float * the function will return an unspecified exception * Please use the ternary operator in combination with {@link #has(String)} * * boolean result = has(key) ? getFloat(key) : default * * @param key The key to lookup in the map * @return The value of the setting */ public float getFloat(String key) { return (float)data.get(key); } /** * Returns a String from the settings map * If there is no such key to be found or the value is not a String * the function will return an unspecified exception * Please use the ternary operator in combination with {@link #has(String)} * * boolean result = has(key) ? getString(key) : default * * @param key The key to lookup in the map * @return The value of the setting */ public String getString(String key) { return (String)data.get(key); } /** * Sets the entry with the specified key to the value * If no such entry exist a new one will be created * @param key The key of the entry * @param value The value of the entry */ public void setBool(String key, boolean value) { updated = true; data.put(key,value); } /** * Sets the entry with the specified key to the value * If no such entry exist a new one will be created * @param key The key of the entry * @param value The value of the entry */ public void setInt(String key, int value) { updated = true; data.put(key,value); } /** * Sets the entry with the specified key to the value * If no such entry exist a new one will be created * @param key The key of the entry * @param value The value of the entry */ public void setFloat(String key, float value) { updated = true; data.put(key,value); } /** * Sets the entry with the specified key to the value * If no such entry exist a new one will be created * @param key The key of the entry * @param value The value of the entry */ public void setString(String key, String value) { updated = true; data.put(key,value); } protected boolean isUpdated() { return updated; } }
true
true
public Settings(String filename) { try { BufferedReader reader = new BufferedReader(new FileReader(filename)); try { String line; String parts[]; int index = 0; while((line = reader.readLine()) != null) { index++; if (line.contains(":")) { parts = line.split(":"); parts[0] = parts[0].trim(); parts[1] = parts[1].trim(); if (parts[1].matches("-?\\d+")) { data.put(parts[0],Integer.parseInt(parts[1])); } else if (parts[1].matches("-?\\d+(\\.\\d+)?")) { data.put(parts[0],Float.parseFloat(parts[1])); } else if (parts[1].equalsIgnoreCase("true") || parts[1].equalsIgnoreCase("false")) { data.put(parts[0],Boolean.parseBoolean(parts[1])); } else { data.put(parts[0],parts[1]); } } else { throw new LDKException("Line " + index + " expected a :"); } } } finally { reader.close(); } } catch (IOException e) { System.err.println("Unable to locate the engine configuration file \"" + filename + "\" at the games root directory"); System.exit(1); } }
public Settings(String filename) { try { BufferedReader reader = new BufferedReader(new InputStreamReader(getClass().getClassLoader().getResourceAsStream(filename))); try { String line; String parts[]; int index = 0; while((line = reader.readLine()) != null) { index++; if (line.contains(":")) { parts = line.split(":"); parts[0] = parts[0].trim(); parts[1] = parts[1].trim(); if (parts[1].matches("-?\\d+")) { data.put(parts[0],Integer.parseInt(parts[1])); } else if (parts[1].matches("-?\\d+(\\.\\d+)?")) { data.put(parts[0],Float.parseFloat(parts[1])); } else if (parts[1].equalsIgnoreCase("true") || parts[1].equalsIgnoreCase("false")) { data.put(parts[0],Boolean.parseBoolean(parts[1])); } else { data.put(parts[0],parts[1]); } } else { throw new LDKException("Line " + index + " expected a :"); } } } finally { reader.close(); } } catch (IOException e) { System.err.println("Unable to locate the engine configuration file \"" + filename + "\" at the games root directory"); System.exit(1); } }
diff --git a/bundles/org.eclipse.e4.core.contexts/src/org/eclipse/e4/core/internal/contexts/ContextObjectSupplier.java b/bundles/org.eclipse.e4.core.contexts/src/org/eclipse/e4/core/internal/contexts/ContextObjectSupplier.java index c1ac2b96d..b2fe78990 100644 --- a/bundles/org.eclipse.e4.core.contexts/src/org/eclipse/e4/core/internal/contexts/ContextObjectSupplier.java +++ b/bundles/org.eclipse.e4.core.contexts/src/org/eclipse/e4/core/internal/contexts/ContextObjectSupplier.java @@ -1,186 +1,190 @@ /******************************************************************************* * Copyright (c) 2009, 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.e4.core.internal.contexts; import javax.inject.Named; import org.eclipse.e4.core.contexts.ContextChangeEvent; import org.eclipse.e4.core.contexts.IEclipseContext; import org.eclipse.e4.core.contexts.IRunAndTrack; import org.eclipse.e4.core.di.AbstractObjectSupplier; import org.eclipse.e4.core.di.IInjector; import org.eclipse.e4.core.di.IObjectDescriptor; import org.eclipse.e4.core.di.IRequestor; public class ContextObjectSupplier extends AbstractObjectSupplier { static private class ContextInjectionListener implements IRunAndTrackObject { final private Object[] result; final private String[] keys; final private IRequestor requestor; final private IEclipseContext context; public ContextInjectionListener(IEclipseContext context, Object[] result, String[] keys, IRequestor requestor) { this.result = result; this.keys = keys; this.requestor = requestor; this.context = context; } public boolean notify(ContextChangeEvent event) { if (event.getEventType() == ContextChangeEvent.INITIAL) { // needs to be done inside runnable to establish dependencies for (int i = 0; i < keys.length; i++) { if (keys[i] == null) continue; if (context.containsKey(keys[i])) result[i] = context.get(keys[i]); else result[i] = IInjector.NOT_A_VALUE; // TBD make sure this still creates // dependency on the key } return true; } IInjector injector = requestor.getInjector(); if (event.getEventType() == ContextChangeEvent.DISPOSE) { IEclipseContext originatingContext = event.getContext(); - ContextObjectSupplier originatingSupplier = getObjectSupplier(originatingContext, injector); - injector.disposed(originatingSupplier); - return false; + if (originatingContext == context) { + ContextObjectSupplier originatingSupplier = getObjectSupplier(originatingContext, injector); + injector.disposed(originatingSupplier); + return false; + } } else if (event.getEventType() == ContextChangeEvent.UNINJECTED) { IEclipseContext originatingContext = event.getContext(); - ContextObjectSupplier originatingSupplier = getObjectSupplier(originatingContext, injector); - injector.uninject(event.getArguments()[0], originatingSupplier); - return false; + if (originatingContext == context) { + ContextObjectSupplier originatingSupplier = getObjectSupplier(originatingContext, injector); + injector.uninject(event.getArguments()[0], originatingSupplier); + return false; + } } else { injector.update(new IRequestor[] { requestor }, requestor.getPrimarySupplier()); } return true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((context == null) ? 0 : context.hashCode()); result = prime * result + ((requestor == null) ? 0 : requestor.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ContextInjectionListener other = (ContextInjectionListener) obj; if (context == null) { if (other.context != null) return false; } else if (!context.equals(other.context)) return false; if (requestor == null) { if (other.requestor != null) return false; } else if (!requestor.equals(other.requestor)) return false; return true; } public Object getObject() { // XXX remove? // TODO Auto-generated method stub return null; } public boolean batchProcess() { return requestor.shouldGroupUpdates(); } } final static private String ECLIPSE_CONTEXT_NAME = IEclipseContext.class.getName(); final private IEclipseContext context; public ContextObjectSupplier(IEclipseContext context, IInjector injector) { this.context = context; } public IEclipseContext getContext() { return context; } @Override public Object get(IObjectDescriptor descriptor, IRequestor requestor) { // This method is rarely or never used on the primary supplier if (descriptor == null) return IInjector.NOT_A_VALUE; Object[] result = get(new IObjectDescriptor[] { descriptor }, requestor); if (result == null) return null; return result[0]; } @Override public Object[] get(IObjectDescriptor[] descriptors, final IRequestor requestor) { final Object[] result = new Object[descriptors.length]; final String[] keys = new String[descriptors.length]; for (int i = 0; i < descriptors.length; i++) { keys[i] = (descriptors[i] == null) ? null : getKey(descriptors[i]); if (ECLIPSE_CONTEXT_NAME.equals(keys[i])) { result[i] = context; keys[i] = null; } } if (requestor != null && requestor.shouldTrack()) { // only track if requested IRunAndTrack trackable = new ContextInjectionListener(context, result, keys, requestor); context.runAndTrack(trackable, null); } else { for (int i = 0; i < descriptors.length; i++) { if (keys[i] == null) continue; if (context.containsKey(keys[i])) result[i] = context.get(keys[i]); else result[i] = IInjector.NOT_A_VALUE; } } return result; } private String getKey(IObjectDescriptor descriptor) { if (descriptor.hasQualifier(Named.class)) { Object namedAnnotation = descriptor.getQualifier(Named.class); String key = ((Named) namedAnnotation).value(); return key; } Class<?> elementClass = descriptor.getElementClass(); if (elementClass != null) return elementClass.getName(); return null; } static public ContextObjectSupplier getObjectSupplier(IEclipseContext context, IInjector injector) { String key = ContextObjectSupplier.class.getName(); if (context.containsKey(key, true)) return (ContextObjectSupplier) context.get(key); ContextObjectSupplier objectSupplier = new ContextObjectSupplier(context, injector); context.set(key, objectSupplier); return objectSupplier; } }
false
true
public boolean notify(ContextChangeEvent event) { if (event.getEventType() == ContextChangeEvent.INITIAL) { // needs to be done inside runnable to establish dependencies for (int i = 0; i < keys.length; i++) { if (keys[i] == null) continue; if (context.containsKey(keys[i])) result[i] = context.get(keys[i]); else result[i] = IInjector.NOT_A_VALUE; // TBD make sure this still creates // dependency on the key } return true; } IInjector injector = requestor.getInjector(); if (event.getEventType() == ContextChangeEvent.DISPOSE) { IEclipseContext originatingContext = event.getContext(); ContextObjectSupplier originatingSupplier = getObjectSupplier(originatingContext, injector); injector.disposed(originatingSupplier); return false; } else if (event.getEventType() == ContextChangeEvent.UNINJECTED) { IEclipseContext originatingContext = event.getContext(); ContextObjectSupplier originatingSupplier = getObjectSupplier(originatingContext, injector); injector.uninject(event.getArguments()[0], originatingSupplier); return false; } else { injector.update(new IRequestor[] { requestor }, requestor.getPrimarySupplier()); } return true; }
public boolean notify(ContextChangeEvent event) { if (event.getEventType() == ContextChangeEvent.INITIAL) { // needs to be done inside runnable to establish dependencies for (int i = 0; i < keys.length; i++) { if (keys[i] == null) continue; if (context.containsKey(keys[i])) result[i] = context.get(keys[i]); else result[i] = IInjector.NOT_A_VALUE; // TBD make sure this still creates // dependency on the key } return true; } IInjector injector = requestor.getInjector(); if (event.getEventType() == ContextChangeEvent.DISPOSE) { IEclipseContext originatingContext = event.getContext(); if (originatingContext == context) { ContextObjectSupplier originatingSupplier = getObjectSupplier(originatingContext, injector); injector.disposed(originatingSupplier); return false; } } else if (event.getEventType() == ContextChangeEvent.UNINJECTED) { IEclipseContext originatingContext = event.getContext(); if (originatingContext == context) { ContextObjectSupplier originatingSupplier = getObjectSupplier(originatingContext, injector); injector.uninject(event.getArguments()[0], originatingSupplier); return false; } } else { injector.update(new IRequestor[] { requestor }, requestor.getPrimarySupplier()); } return true; }
diff --git a/sandbox/studio/org.nuxeo.ide.studio/src/org/nuxeo/ide/studio/editors/StudioEditor.java b/sandbox/studio/org.nuxeo.ide.studio/src/org/nuxeo/ide/studio/editors/StudioEditor.java index 134dc4a..bdf929d 100644 --- a/sandbox/studio/org.nuxeo.ide.studio/src/org/nuxeo/ide/studio/editors/StudioEditor.java +++ b/sandbox/studio/org.nuxeo.ide.studio/src/org/nuxeo/ide/studio/editors/StudioEditor.java @@ -1,125 +1,126 @@ package org.nuxeo.ide.studio.editors; import java.io.File; import java.net.URL; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.swt.SWT; import org.eclipse.swt.browser.Browser; import org.eclipse.swt.browser.TitleEvent; import org.eclipse.swt.browser.TitleListener; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorSite; import org.eclipse.ui.IViewPart; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.part.EditorPart; import org.nuxeo.ide.studio.StudioPlugin; import org.nuxeo.ide.studio.data.Node; import org.nuxeo.ide.studio.views.StudioBrowserView; public class StudioEditor extends EditorPart { public static final String ID = "org.nuxeo.ide.studio.editor"; protected Browser browser; public StudioEditor() { } @Override public void doSave(IProgressMonitor monitor) { } @Override public void doSaveAs() { } @Override public void init(IEditorSite site, IEditorInput input) throws PartInitException { setSite(site); setInput(input); } @Override public boolean isDirty() { return false; } @Override public boolean isSaveAsAllowed() { return false; } @Override public void createPartControl(Composite parent) { parent.setLayout(new FillLayout()); browser = new Browser(parent, SWT.NONE); Node node = (Node) getEditorInput().getAdapter(Node.class); URL url = StudioPlugin.getPreferences().getConnectLocation("ide", "dev", node.getKey()); StudioPlugin.logInfo("-> " + url); browser.setUrl(url.toExternalForm()); browser.addTitleListener(new TitleListener() { public void changed(TitleEvent event) { //id:type:saved! //id:type:created! if (event.title.endsWith(":saved!")) { StudioPlugin.logInfo("<- save done"); IWorkbenchWindow window=PlatformUI.getWorkbench().getActiveWorkbenchWindow(); IWorkbenchPage page = window.getActivePage(); IViewPart view = page.findView(StudioBrowserView.ID); if (view != null) { StudioBrowserView studioBrowserView = (StudioBrowserView)view; File file = StudioPlugin.getDefault().getProvider().getJar(studioBrowserView.getProjectName()); System.out.println(file); } } else if (event.title.endsWith(":created!")) { String id = null; String[] s = event.title.split(":"); if ( s.length > 0 ){ id = s[0]; } StudioPlugin.logInfo("<- create done"); IWorkbenchWindow window=PlatformUI.getWorkbench().getActiveWorkbenchWindow(); IWorkbenchPage page = window.getActivePage(); IViewPart view = page.findView(StudioBrowserView.ID); if (view != null) { StudioBrowserView studioBrowserView = (StudioBrowserView)view; studioBrowserView.refresh(); if ( id != null) { Node node = studioBrowserView.selectNode(id); if ( node != null ){ setInputWithNotify(new StudioEditorInput(node)); + setPartName("todo"); } } } } } }); } @Override public void setFocus() { } @Override public String getPartName() { return getEditorInput().getName(); } public Browser getBrowser() { return browser; } }
true
true
public void createPartControl(Composite parent) { parent.setLayout(new FillLayout()); browser = new Browser(parent, SWT.NONE); Node node = (Node) getEditorInput().getAdapter(Node.class); URL url = StudioPlugin.getPreferences().getConnectLocation("ide", "dev", node.getKey()); StudioPlugin.logInfo("-> " + url); browser.setUrl(url.toExternalForm()); browser.addTitleListener(new TitleListener() { public void changed(TitleEvent event) { //id:type:saved! //id:type:created! if (event.title.endsWith(":saved!")) { StudioPlugin.logInfo("<- save done"); IWorkbenchWindow window=PlatformUI.getWorkbench().getActiveWorkbenchWindow(); IWorkbenchPage page = window.getActivePage(); IViewPart view = page.findView(StudioBrowserView.ID); if (view != null) { StudioBrowserView studioBrowserView = (StudioBrowserView)view; File file = StudioPlugin.getDefault().getProvider().getJar(studioBrowserView.getProjectName()); System.out.println(file); } } else if (event.title.endsWith(":created!")) { String id = null; String[] s = event.title.split(":"); if ( s.length > 0 ){ id = s[0]; } StudioPlugin.logInfo("<- create done"); IWorkbenchWindow window=PlatformUI.getWorkbench().getActiveWorkbenchWindow(); IWorkbenchPage page = window.getActivePage(); IViewPart view = page.findView(StudioBrowserView.ID); if (view != null) { StudioBrowserView studioBrowserView = (StudioBrowserView)view; studioBrowserView.refresh(); if ( id != null) { Node node = studioBrowserView.selectNode(id); if ( node != null ){ setInputWithNotify(new StudioEditorInput(node)); } } } } } }); }
public void createPartControl(Composite parent) { parent.setLayout(new FillLayout()); browser = new Browser(parent, SWT.NONE); Node node = (Node) getEditorInput().getAdapter(Node.class); URL url = StudioPlugin.getPreferences().getConnectLocation("ide", "dev", node.getKey()); StudioPlugin.logInfo("-> " + url); browser.setUrl(url.toExternalForm()); browser.addTitleListener(new TitleListener() { public void changed(TitleEvent event) { //id:type:saved! //id:type:created! if (event.title.endsWith(":saved!")) { StudioPlugin.logInfo("<- save done"); IWorkbenchWindow window=PlatformUI.getWorkbench().getActiveWorkbenchWindow(); IWorkbenchPage page = window.getActivePage(); IViewPart view = page.findView(StudioBrowserView.ID); if (view != null) { StudioBrowserView studioBrowserView = (StudioBrowserView)view; File file = StudioPlugin.getDefault().getProvider().getJar(studioBrowserView.getProjectName()); System.out.println(file); } } else if (event.title.endsWith(":created!")) { String id = null; String[] s = event.title.split(":"); if ( s.length > 0 ){ id = s[0]; } StudioPlugin.logInfo("<- create done"); IWorkbenchWindow window=PlatformUI.getWorkbench().getActiveWorkbenchWindow(); IWorkbenchPage page = window.getActivePage(); IViewPart view = page.findView(StudioBrowserView.ID); if (view != null) { StudioBrowserView studioBrowserView = (StudioBrowserView)view; studioBrowserView.refresh(); if ( id != null) { Node node = studioBrowserView.selectNode(id); if ( node != null ){ setInputWithNotify(new StudioEditorInput(node)); setPartName("todo"); } } } } } }); }