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/biz/bokhorst/xprivacy/XPrivacyProvider.java b/src/biz/bokhorst/xprivacy/XPrivacyProvider.java index fa54f9b5..20ffa2c2 100644 --- a/src/biz/bokhorst/xprivacy/XPrivacyProvider.java +++ b/src/biz/bokhorst/xprivacy/XPrivacyProvider.java @@ -1,123 +1,123 @@ package biz.bokhorst.xprivacy; import java.util.Arrays; import java.util.Date; import android.content.ContentProvider; import android.content.ContentValues; import android.content.Context; import android.content.SharedPreferences; import android.content.UriMatcher; import android.database.Cursor; import android.database.MatrixCursor; import android.net.Uri; import android.os.Binder; public class XPrivacyProvider extends ContentProvider { public static final String AUTHORITY = "biz.bokhorst.xprivacy.provider"; public static final String PATH_PERMISSIONS = "permissions"; public static final String PATH_LASTUSE = "lastuse"; public static final Uri URI_PERMISSIONS = Uri.parse("content://" + AUTHORITY + "/" + PATH_PERMISSIONS); public static final Uri URI_LASTUSE = Uri.parse("content://" + AUTHORITY + "/" + PATH_LASTUSE); public static final String COL_NAME = "Name"; public static final String COL_PERMISSION = "Permission"; public static final String COL_UID = "Uid"; public static final String COL_LASTUSE = "LastUse"; private static final UriMatcher sUriMatcher; private static final int TYPE_PERMISSIONS = 1; private static final int TYPE_LASTUSE = 2; static { sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH); sUriMatcher.addURI(AUTHORITY, PATH_PERMISSIONS, TYPE_PERMISSIONS); sUriMatcher.addURI(AUTHORITY, PATH_LASTUSE, TYPE_LASTUSE); } @Override public boolean onCreate() { return true; } @Override public String getType(Uri uri) { if (sUriMatcher.match(uri) == TYPE_PERMISSIONS) return String.format("vnd.android.cursor.dir/%s.%s", AUTHORITY, PATH_PERMISSIONS); else if (sUriMatcher.match(uri) == TYPE_LASTUSE) return String.format("vnd.android.cursor.dir/%s.%s", AUTHORITY, PATH_LASTUSE); throw new IllegalArgumentException(); } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { if (selectionArgs != null) { // Get arguments String permissionName = selection; SharedPreferences prefs = getContext().getSharedPreferences(AUTHORITY, Context.MODE_PRIVATE); if (sUriMatcher.match(uri) == TYPE_PERMISSIONS && selectionArgs.length == 2) { int uid = Integer.parseInt(selectionArgs[0]); boolean usage = Boolean.parseBoolean(selectionArgs[1]); // Update usage count if (usage) { SharedPreferences.Editor editor = prefs.edit(); editor.putLong(getUsagePref(uid, permissionName), new Date().getTime()); editor.commit(); } // Return permission MatrixCursor mc = new MatrixCursor(new String[] { COL_NAME, COL_PERMISSION }); mc.addRow(new Object[] { permissionName, prefs.getString(getPermissionPref(permissionName), "*") }); return mc; } else if (sUriMatcher.match(uri) == TYPE_LASTUSE && selectionArgs.length == 1) { // Return usage - int uid = Integer.parseInt(selectionArgs[1]); + int uid = Integer.parseInt(selectionArgs[0]); MatrixCursor mc = new MatrixCursor(new String[] { COL_UID, COL_NAME, COL_LASTUSE }); mc.addRow(new Object[] { uid, permissionName, prefs.getLong(getUsagePref(uid, permissionName), 0) }); return mc; } } throw new IllegalArgumentException(); } @Override public Uri insert(Uri uri, ContentValues values) { throw new IllegalArgumentException(); } @Override public int update(Uri uri, ContentValues values, String where, String[] selectionArgs) { // TODO: register update time? if (sUriMatcher.match(uri) == TYPE_PERMISSIONS) { // Check update permission int uid = Binder.getCallingUid(); String[] packages = getContext().getPackageManager().getPackagesForUid(uid); if (Arrays.asList(packages).contains("com.android.settings")) { // Update permission SharedPreferences prefs = getContext().getSharedPreferences(AUTHORITY, Context.MODE_PRIVATE); SharedPreferences.Editor editor = prefs.edit(); editor.putString(getPermissionPref(values.getAsString(COL_NAME)), values.getAsString(COL_PERMISSION)); editor.commit(); } else throw new SecurityException(); return 1; } throw new IllegalArgumentException(); } private String getPermissionPref(String permissionName) { return COL_PERMISSION + "." + permissionName; } private String getUsagePref(int uid, String permissionName) { return COL_LASTUSE + "." + uid + "." + permissionName; } @Override public int delete(Uri url, String where, String[] selectionArgs) { throw new IllegalArgumentException(); } }
true
true
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { if (selectionArgs != null) { // Get arguments String permissionName = selection; SharedPreferences prefs = getContext().getSharedPreferences(AUTHORITY, Context.MODE_PRIVATE); if (sUriMatcher.match(uri) == TYPE_PERMISSIONS && selectionArgs.length == 2) { int uid = Integer.parseInt(selectionArgs[0]); boolean usage = Boolean.parseBoolean(selectionArgs[1]); // Update usage count if (usage) { SharedPreferences.Editor editor = prefs.edit(); editor.putLong(getUsagePref(uid, permissionName), new Date().getTime()); editor.commit(); } // Return permission MatrixCursor mc = new MatrixCursor(new String[] { COL_NAME, COL_PERMISSION }); mc.addRow(new Object[] { permissionName, prefs.getString(getPermissionPref(permissionName), "*") }); return mc; } else if (sUriMatcher.match(uri) == TYPE_LASTUSE && selectionArgs.length == 1) { // Return usage int uid = Integer.parseInt(selectionArgs[1]); MatrixCursor mc = new MatrixCursor(new String[] { COL_UID, COL_NAME, COL_LASTUSE }); mc.addRow(new Object[] { uid, permissionName, prefs.getLong(getUsagePref(uid, permissionName), 0) }); return mc; } } throw new IllegalArgumentException(); }
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { if (selectionArgs != null) { // Get arguments String permissionName = selection; SharedPreferences prefs = getContext().getSharedPreferences(AUTHORITY, Context.MODE_PRIVATE); if (sUriMatcher.match(uri) == TYPE_PERMISSIONS && selectionArgs.length == 2) { int uid = Integer.parseInt(selectionArgs[0]); boolean usage = Boolean.parseBoolean(selectionArgs[1]); // Update usage count if (usage) { SharedPreferences.Editor editor = prefs.edit(); editor.putLong(getUsagePref(uid, permissionName), new Date().getTime()); editor.commit(); } // Return permission MatrixCursor mc = new MatrixCursor(new String[] { COL_NAME, COL_PERMISSION }); mc.addRow(new Object[] { permissionName, prefs.getString(getPermissionPref(permissionName), "*") }); return mc; } else if (sUriMatcher.match(uri) == TYPE_LASTUSE && selectionArgs.length == 1) { // Return usage int uid = Integer.parseInt(selectionArgs[0]); MatrixCursor mc = new MatrixCursor(new String[] { COL_UID, COL_NAME, COL_LASTUSE }); mc.addRow(new Object[] { uid, permissionName, prefs.getLong(getUsagePref(uid, permissionName), 0) }); return mc; } } throw new IllegalArgumentException(); }
diff --git a/src/org/gridlab/gridsphere/portlet/jsrimpl/PersistencePreferenceAttribute.java b/src/org/gridlab/gridsphere/portlet/jsrimpl/PersistencePreferenceAttribute.java index 79837bfd4..8cad68daf 100644 --- a/src/org/gridlab/gridsphere/portlet/jsrimpl/PersistencePreferenceAttribute.java +++ b/src/org/gridlab/gridsphere/portlet/jsrimpl/PersistencePreferenceAttribute.java @@ -1,71 +1,73 @@ package org.gridlab.gridsphere.portlet.jsrimpl; import java.util.ArrayList; import java.util.List; /* * @author <a href="mailto:[email protected]">Oliver Wehrens</a> * @version $Id$ */ public class PersistencePreferenceAttribute { private String oid = null; protected boolean readonly = false; protected String name = ""; protected List values = new ArrayList(); public String getOid() { return oid; } public void setOid(String oid) { this.oid = oid; } public void setReadOnly(boolean readonly) { this.readonly = readonly; } public void setName(String name) { this.name = name; } public String getName() { return name; } public void setValues(List values) { this.values = values; } public List getValues() { return values; } public boolean isReadOnly() { return readonly; } public void setAValues(String[] values) { this.values = new ArrayList(); - for (int i = 0; i < values.length; i++) { - this.values.add(values[i]); + if (values != null) { + for (int i = 0; i < values.length; i++) { + this.values.add(values[i]); + } } } public String[] getAValues() { String[] array = new String[values.size()]; return (String[]) this.values.toArray(array); } public void setValue(String value) { setAValues(new String[]{value}); } public String getValue() { return (String) values.get(0); } }
true
true
public void setAValues(String[] values) { this.values = new ArrayList(); for (int i = 0; i < values.length; i++) { this.values.add(values[i]); } }
public void setAValues(String[] values) { this.values = new ArrayList(); if (values != null) { for (int i = 0; i < values.length; i++) { this.values.add(values[i]); } } }
diff --git a/src/org/jruby/ast/executable/YARVCompiledRunner.java b/src/org/jruby/ast/executable/YARVCompiledRunner.java index ae72f2fca..742bfb1f2 100644 --- a/src/org/jruby/ast/executable/YARVCompiledRunner.java +++ b/src/org/jruby/ast/executable/YARVCompiledRunner.java @@ -1,217 +1,217 @@ /***** 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) 2007 Ola Bini <[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.ast.executable; import java.io.Reader; import java.io.IOException; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.HashMap; import java.util.IdentityHashMap; import org.jruby.IRuby; import org.jruby.RubyFile; import org.jruby.RubyArray; import org.jruby.RubyNumeric; import org.jruby.RubyString; import org.jruby.RubySymbol; import org.jruby.parser.LocalStaticScope; import org.jruby.parser.StaticScope; import org.jruby.runtime.DynamicScope; import org.jruby.runtime.ThreadContext; import org.jruby.runtime.builtin.IRubyObject; /** * @author <a href="mailto:[email protected]">Ola Bini</a> */ public class YARVCompiledRunner { private IRuby runtime; private YARVMachine ym = YARVMachine.INSTANCE; private YARVMachine.InstructionSequence iseq; private Map jumps = new IdentityHashMap(); private Map labels = new HashMap(); public YARVCompiledRunner(IRuby runtime, Reader reader, String filename) { this.runtime = runtime; char[] first = new char[4]; try { reader.read(first); if(first[0] != 'R' || first[1] != 'B' || first[2] != 'C' || first[3] != 'M') { throw new RuntimeException("File is not a compiled YARV file"); } RubyFile f = new RubyFile(runtime,filename,reader); IRubyObject arr = runtime.getModule("Marshal").callMethod(runtime.getCurrentContext(),"load",f); iseq = transformIntoSequence(arr); } catch(IOException e) { throw new RuntimeException("Couldn't read from source",e); } } public YARVCompiledRunner(IRuby runtime, YARVMachine.InstructionSequence iseq) { this.runtime = runtime; this.iseq = iseq; } public IRubyObject run() { ThreadContext context = runtime.getCurrentContext(); StaticScope scope = new LocalStaticScope(null); scope.setVariables(iseq.locals); context.setPosition(new ISeqPosition(iseq)); return ym.exec(context, runtime.getObject(), new DynamicScope(scope,null), iseq.body); } private YARVMachine.InstructionSequence transformIntoSequence(IRubyObject arr) { if(!(arr instanceof RubyArray)) { throw new RuntimeException("Error when reading compiled YARV file"); } labels.clear(); jumps.clear(); - YARVMachine.InstructionSequence seq = new YARVMachine.InstructionSequence(runtime, "", "", ""); + YARVMachine.InstructionSequence seq = new YARVMachine.InstructionSequence(runtime,null,null,null); Iterator internal = (((RubyArray)arr).getList()).iterator(); seq.magic = internal.next().toString(); seq.major = RubyNumeric.fix2int((IRubyObject)internal.next()); seq.minor = RubyNumeric.fix2int((IRubyObject)internal.next()); seq.format_type = RubyNumeric.fix2int((IRubyObject)internal.next()); IRubyObject misc = (IRubyObject)internal.next(); if(misc.isNil()) { seq.misc = null; } else { seq.misc = misc; } seq.name = internal.next().toString(); seq.filename = internal.next().toString(); seq.line = new Object[0]; internal.next(); seq.type = internal.next().toString(); seq.locals = toStringArray((IRubyObject)internal.next()); IRubyObject argo = (IRubyObject)internal.next(); if(argo instanceof RubyArray) { List arglist = ((RubyArray)argo).getList(); seq.args_argc = RubyNumeric.fix2int((IRubyObject)arglist.get(0)); seq.args_arg_opts = RubyNumeric.fix2int((IRubyObject)arglist.get(1)); seq.args_opt_labels = toStringArray((IRubyObject)arglist.get(2)); seq.args_rest = RubyNumeric.fix2int((IRubyObject)arglist.get(3)); seq.args_block = RubyNumeric.fix2int((IRubyObject)arglist.get(4)); } else { seq.args_argc = RubyNumeric.fix2int(argo); } seq.exception = getExceptionInformation((IRubyObject)internal.next()); List bodyl = ((RubyArray)internal.next()).getList(); YARVMachine.Instruction[] body = new YARVMachine.Instruction[bodyl.size()]; int real=0; int i=0; for(Iterator iter = bodyl.iterator();iter.hasNext();i++) { IRubyObject is = (IRubyObject)iter.next(); if(is instanceof RubyArray) { body[real] = intoInstruction((RubyArray)is,real,seq); real++; } else if(is instanceof RubySymbol) { labels.put(is.toString(), new Integer(real+1)); } } YARVMachine.Instruction[] nbody = new YARVMachine.Instruction[real]; System.arraycopy(body,0,nbody,0,real); seq.body = nbody; for(Iterator iter = jumps.keySet().iterator();iter.hasNext();) { YARVMachine.Instruction k = (YARVMachine.Instruction)iter.next(); k.l_op0 = ((Integer)labels.get(jumps.get(k))).intValue() - 1; } return seq; } private String[] toStringArray(IRubyObject obj) { if(obj.isNil()) { return new String[0]; } else { List l = ((RubyArray)obj).getList(); String[] s = new String[l.size()]; int i=0; for(Iterator iter = l.iterator();iter.hasNext();i++) { s[i] = iter.next().toString(); } return s; } } private YARVMachine.Instruction intoInstruction(RubyArray obj, int n, YARVMachine.InstructionSequence iseq) { List internal = obj.getList(); String name = internal.get(0).toString(); int instruction = YARVMachine.instruction(name); YARVMachine.Instruction i = new YARVMachine.Instruction(instruction); if(internal.size() > 1) { IRubyObject first = (IRubyObject)internal.get(1); if(instruction == YARVInstructions.GETLOCAL || instruction == YARVInstructions.SETLOCAL) { i.l_op0 = (iseq.locals.length + 1) - RubyNumeric.fix2long(first); } else if(instruction == YARVInstructions.PUTOBJECT || instruction == YARVInstructions.OPT_REGEXPMATCH1 || instruction == YARVInstructions.GETINLINECACHE) { i.o_op0 = first; } else if(first instanceof RubyString || first instanceof RubySymbol ) { i.s_op0 = first.toString(); } else if(first instanceof RubyNumeric) { i.l_op0 = RubyNumeric.fix2long(first); } if(instruction == YARVInstructions.SEND) { i.i_op1 = RubyNumeric.fix2int((IRubyObject)internal.get(2)); i.i_op3 = RubyNumeric.fix2int((IRubyObject)internal.get(4)); } if(instruction == YARVInstructions.DEFINEMETHOD) { i.iseq_op = transformIntoSequence((IRubyObject)internal.get(2)); } if(isJump(instruction)) { i.index = n; jumps.put(i, internal.get(jumpIndex(instruction)).toString()); } } return i; } private boolean isJump(int i) { return i == YARVInstructions.JUMP || i == YARVInstructions.BRANCHIF || i == YARVInstructions.BRANCHUNLESS || i == YARVInstructions.GETINLINECACHE || i == YARVInstructions.SETINLINECACHE; } private int jumpIndex(int i) { if(i == YARVInstructions.GETINLINECACHE) { return 2; } else { return 1; } } private Object[] getExceptionInformation(IRubyObject obj) { // System.err.println(obj.callMethod(runtime.getCurrentContext(),"inspect")); return new Object[0]; } }// YARVCompiledRunner
true
true
private YARVMachine.InstructionSequence transformIntoSequence(IRubyObject arr) { if(!(arr instanceof RubyArray)) { throw new RuntimeException("Error when reading compiled YARV file"); } labels.clear(); jumps.clear(); YARVMachine.InstructionSequence seq = new YARVMachine.InstructionSequence(runtime, "", "", ""); Iterator internal = (((RubyArray)arr).getList()).iterator(); seq.magic = internal.next().toString(); seq.major = RubyNumeric.fix2int((IRubyObject)internal.next()); seq.minor = RubyNumeric.fix2int((IRubyObject)internal.next()); seq.format_type = RubyNumeric.fix2int((IRubyObject)internal.next()); IRubyObject misc = (IRubyObject)internal.next(); if(misc.isNil()) { seq.misc = null; } else { seq.misc = misc; } seq.name = internal.next().toString(); seq.filename = internal.next().toString(); seq.line = new Object[0]; internal.next(); seq.type = internal.next().toString(); seq.locals = toStringArray((IRubyObject)internal.next()); IRubyObject argo = (IRubyObject)internal.next(); if(argo instanceof RubyArray) { List arglist = ((RubyArray)argo).getList(); seq.args_argc = RubyNumeric.fix2int((IRubyObject)arglist.get(0)); seq.args_arg_opts = RubyNumeric.fix2int((IRubyObject)arglist.get(1)); seq.args_opt_labels = toStringArray((IRubyObject)arglist.get(2)); seq.args_rest = RubyNumeric.fix2int((IRubyObject)arglist.get(3)); seq.args_block = RubyNumeric.fix2int((IRubyObject)arglist.get(4)); } else { seq.args_argc = RubyNumeric.fix2int(argo); } seq.exception = getExceptionInformation((IRubyObject)internal.next()); List bodyl = ((RubyArray)internal.next()).getList(); YARVMachine.Instruction[] body = new YARVMachine.Instruction[bodyl.size()]; int real=0; int i=0; for(Iterator iter = bodyl.iterator();iter.hasNext();i++) { IRubyObject is = (IRubyObject)iter.next(); if(is instanceof RubyArray) { body[real] = intoInstruction((RubyArray)is,real,seq); real++; } else if(is instanceof RubySymbol) { labels.put(is.toString(), new Integer(real+1)); } } YARVMachine.Instruction[] nbody = new YARVMachine.Instruction[real]; System.arraycopy(body,0,nbody,0,real); seq.body = nbody; for(Iterator iter = jumps.keySet().iterator();iter.hasNext();) { YARVMachine.Instruction k = (YARVMachine.Instruction)iter.next(); k.l_op0 = ((Integer)labels.get(jumps.get(k))).intValue() - 1; } return seq; }
private YARVMachine.InstructionSequence transformIntoSequence(IRubyObject arr) { if(!(arr instanceof RubyArray)) { throw new RuntimeException("Error when reading compiled YARV file"); } labels.clear(); jumps.clear(); YARVMachine.InstructionSequence seq = new YARVMachine.InstructionSequence(runtime,null,null,null); Iterator internal = (((RubyArray)arr).getList()).iterator(); seq.magic = internal.next().toString(); seq.major = RubyNumeric.fix2int((IRubyObject)internal.next()); seq.minor = RubyNumeric.fix2int((IRubyObject)internal.next()); seq.format_type = RubyNumeric.fix2int((IRubyObject)internal.next()); IRubyObject misc = (IRubyObject)internal.next(); if(misc.isNil()) { seq.misc = null; } else { seq.misc = misc; } seq.name = internal.next().toString(); seq.filename = internal.next().toString(); seq.line = new Object[0]; internal.next(); seq.type = internal.next().toString(); seq.locals = toStringArray((IRubyObject)internal.next()); IRubyObject argo = (IRubyObject)internal.next(); if(argo instanceof RubyArray) { List arglist = ((RubyArray)argo).getList(); seq.args_argc = RubyNumeric.fix2int((IRubyObject)arglist.get(0)); seq.args_arg_opts = RubyNumeric.fix2int((IRubyObject)arglist.get(1)); seq.args_opt_labels = toStringArray((IRubyObject)arglist.get(2)); seq.args_rest = RubyNumeric.fix2int((IRubyObject)arglist.get(3)); seq.args_block = RubyNumeric.fix2int((IRubyObject)arglist.get(4)); } else { seq.args_argc = RubyNumeric.fix2int(argo); } seq.exception = getExceptionInformation((IRubyObject)internal.next()); List bodyl = ((RubyArray)internal.next()).getList(); YARVMachine.Instruction[] body = new YARVMachine.Instruction[bodyl.size()]; int real=0; int i=0; for(Iterator iter = bodyl.iterator();iter.hasNext();i++) { IRubyObject is = (IRubyObject)iter.next(); if(is instanceof RubyArray) { body[real] = intoInstruction((RubyArray)is,real,seq); real++; } else if(is instanceof RubySymbol) { labels.put(is.toString(), new Integer(real+1)); } } YARVMachine.Instruction[] nbody = new YARVMachine.Instruction[real]; System.arraycopy(body,0,nbody,0,real); seq.body = nbody; for(Iterator iter = jumps.keySet().iterator();iter.hasNext();) { YARVMachine.Instruction k = (YARVMachine.Instruction)iter.next(); k.l_op0 = ((Integer)labels.get(jumps.get(k))).intValue() - 1; } return seq; }
diff --git a/src/com/eteks/sweethome3d/io/HomeFileRecorder.java b/src/com/eteks/sweethome3d/io/HomeFileRecorder.java index 85a3612a..31b385dc 100644 --- a/src/com/eteks/sweethome3d/io/HomeFileRecorder.java +++ b/src/com/eteks/sweethome3d/io/HomeFileRecorder.java @@ -1,188 +1,189 @@ /* * HomeFileRecorder.java 30 aout 2006 * * Copyright (c) 2006 Emmanuel PUYBARET / eTeks <[email protected]>. All Rights Reserved. * * 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 com.eteks.sweethome3d.io; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InterruptedIOException; import java.io.OutputStream; import com.eteks.sweethome3d.model.Home; import com.eteks.sweethome3d.model.HomeRecorder; import com.eteks.sweethome3d.model.InterruptedRecorderException; import com.eteks.sweethome3d.model.RecorderException; /** * Recorder that stores homes in files with {@link DefaultHomeOutputStream} and * {@link DefaultHomeInputStream}. * @author Emmanuel Puybaret */ public class HomeFileRecorder implements HomeRecorder { private final int compressionLevel; private final boolean includeOnlyTemporaryContent; /** * Creates a home recorder able to write and read homes in uncompressed files. */ public HomeFileRecorder() { this(0); } /** * Creates a home recorder able to write and read homes in files compressed * at a level from 0 to 9. * @param compressionLevel 0 (uncompressed) to 9 (compressed). */ public HomeFileRecorder(int compressionLevel) { this(compressionLevel, false); } /** * Creates a home recorder able to write and read homes in files compressed * at a level from 0 to 9. * @param compressionLevel 0-9 * @param includeOnlyTemporaryContent if <code>true</code>, only content instances of * <code>TemporaryURLContent</code> class referenced by the saved home * will be written. If <code>false</code>, all the content instances * referenced by the saved home will be written in the zip stream. */ public HomeFileRecorder(int compressionLevel, boolean includeOnlyTemporaryContent) { this.compressionLevel = compressionLevel; this.includeOnlyTemporaryContent = includeOnlyTemporaryContent; } /** * Writes home data. * @throws RecorderException if a problem occurred while writing home. */ public void writeHome(Home home, String name) throws RecorderException { File homeFile = new File(name); if (homeFile.exists() && !homeFile.canWrite()) { throw new RecorderException("Can't write over file " + name); } DefaultHomeOutputStream homeOut = null; File tempFile = null; try { // Open a stream on a temporary file tempFile = File.createTempFile("save", ".sweethome3d"); + tempFile.deleteOnExit(); homeOut = new DefaultHomeOutputStream(new FileOutputStream(tempFile), this.compressionLevel, this.includeOnlyTemporaryContent); // Write home with HomeOuputStream homeOut.writeHome(home); } catch (InterruptedIOException ex) { throw new InterruptedRecorderException("Save " + name + " interrupted"); } catch (IOException ex) { throw new RecorderException("Can't save home " + name, ex); } finally { try { if (homeOut != null) { homeOut.close(); } } catch (IOException ex) { - throw new RecorderException("Can't close file " + name, ex); + throw new RecorderException("Can't close temporary file " + name, ex); } } // Open destination file OutputStream out; try { out = new FileOutputStream(homeFile); } catch (FileNotFoundException ex) { if (tempFile != null) { tempFile.delete(); } throw new RecorderException("Can't save file " + name, ex); } // Copy temporary file to home file // Overwriting home file will ensure that its rights are kept byte [] buffer = new byte [8192]; InputStream in = null; try { in = new FileInputStream(tempFile); int size; while ((size = in.read(buffer)) != -1) { out.write(buffer, 0, size); } } catch (IOException ex) { throw new RecorderException("Can't copy file " + tempFile + " to " + name); } finally { try { if (out != null) { out.close(); } } catch (IOException ex) { throw new RecorderException("Can't close file " + name, ex); } try { if (in != null) { in.close(); tempFile.delete(); } } catch (IOException ex) { // Forget exception } } } /** * Returns a home instance read from its file <code>name</code>. * @throws RecorderException if a problem occurred while reading home, * or if file <code>name</code> doesn't exist. */ public Home readHome(String name) throws RecorderException { DefaultHomeInputStream in = null; try { // Open a stream on file in = new DefaultHomeInputStream(new FileInputStream(name)); // Read home with HomeInputStream Home home = in.readHome(); return home; } catch (InterruptedIOException ex) { throw new InterruptedRecorderException("Read " + name + " interrupted"); } catch (IOException ex) { throw new RecorderException("Can't read home from " + name, ex); } catch (ClassNotFoundException ex) { throw new RecorderException("Missing classes to read home from " + name, ex); } finally { try { if (in != null) { in.close(); } } catch (IOException ex) { throw new RecorderException("Can't close file " + name, ex); } } } /** * Returns <code>true</code> if the file <code>name</code> exists. */ public boolean exists(String name) throws RecorderException { return new File(name).exists(); } }
false
true
public void writeHome(Home home, String name) throws RecorderException { File homeFile = new File(name); if (homeFile.exists() && !homeFile.canWrite()) { throw new RecorderException("Can't write over file " + name); } DefaultHomeOutputStream homeOut = null; File tempFile = null; try { // Open a stream on a temporary file tempFile = File.createTempFile("save", ".sweethome3d"); homeOut = new DefaultHomeOutputStream(new FileOutputStream(tempFile), this.compressionLevel, this.includeOnlyTemporaryContent); // Write home with HomeOuputStream homeOut.writeHome(home); } catch (InterruptedIOException ex) { throw new InterruptedRecorderException("Save " + name + " interrupted"); } catch (IOException ex) { throw new RecorderException("Can't save home " + name, ex); } finally { try { if (homeOut != null) { homeOut.close(); } } catch (IOException ex) { throw new RecorderException("Can't close file " + name, ex); } } // Open destination file OutputStream out; try { out = new FileOutputStream(homeFile); } catch (FileNotFoundException ex) { if (tempFile != null) { tempFile.delete(); } throw new RecorderException("Can't save file " + name, ex); } // Copy temporary file to home file // Overwriting home file will ensure that its rights are kept byte [] buffer = new byte [8192]; InputStream in = null; try { in = new FileInputStream(tempFile); int size; while ((size = in.read(buffer)) != -1) { out.write(buffer, 0, size); } } catch (IOException ex) { throw new RecorderException("Can't copy file " + tempFile + " to " + name); } finally { try { if (out != null) { out.close(); } } catch (IOException ex) { throw new RecorderException("Can't close file " + name, ex); } try { if (in != null) { in.close(); tempFile.delete(); } } catch (IOException ex) { // Forget exception } } }
public void writeHome(Home home, String name) throws RecorderException { File homeFile = new File(name); if (homeFile.exists() && !homeFile.canWrite()) { throw new RecorderException("Can't write over file " + name); } DefaultHomeOutputStream homeOut = null; File tempFile = null; try { // Open a stream on a temporary file tempFile = File.createTempFile("save", ".sweethome3d"); tempFile.deleteOnExit(); homeOut = new DefaultHomeOutputStream(new FileOutputStream(tempFile), this.compressionLevel, this.includeOnlyTemporaryContent); // Write home with HomeOuputStream homeOut.writeHome(home); } catch (InterruptedIOException ex) { throw new InterruptedRecorderException("Save " + name + " interrupted"); } catch (IOException ex) { throw new RecorderException("Can't save home " + name, ex); } finally { try { if (homeOut != null) { homeOut.close(); } } catch (IOException ex) { throw new RecorderException("Can't close temporary file " + name, ex); } } // Open destination file OutputStream out; try { out = new FileOutputStream(homeFile); } catch (FileNotFoundException ex) { if (tempFile != null) { tempFile.delete(); } throw new RecorderException("Can't save file " + name, ex); } // Copy temporary file to home file // Overwriting home file will ensure that its rights are kept byte [] buffer = new byte [8192]; InputStream in = null; try { in = new FileInputStream(tempFile); int size; while ((size = in.read(buffer)) != -1) { out.write(buffer, 0, size); } } catch (IOException ex) { throw new RecorderException("Can't copy file " + tempFile + " to " + name); } finally { try { if (out != null) { out.close(); } } catch (IOException ex) { throw new RecorderException("Can't close file " + name, ex); } try { if (in != null) { in.close(); tempFile.delete(); } } catch (IOException ex) { // Forget exception } } }
diff --git a/src/main/java/com/ushahidi/java/sdk/api/json/Comments.java b/src/main/java/com/ushahidi/java/sdk/api/json/Comments.java index b8fe884..3693747 100644 --- a/src/main/java/com/ushahidi/java/sdk/api/json/Comments.java +++ b/src/main/java/com/ushahidi/java/sdk/api/json/Comments.java @@ -1,63 +1,65 @@ /***************************************************************************** ** Copyright (c) 2010 - 2012 Ushahidi Inc ** All rights reserved ** Contact: [email protected] ** Website: http://www.ushahidi.com ** ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: http://www.gnu.org/licenses/lgpl.html. ** ** ** If you have questions regarding the use of this file, please contact ** Ushahidi developers at [email protected]. ** *****************************************************************************/ package com.ushahidi.java.sdk.api.json; import java.util.ArrayList; import java.util.List; import com.ushahidi.java.sdk.api.Comment; /** * @author eyedol * */ public class Comments extends Response { private static class Payload extends Response.Payload { private static class _Comment { private Comment comment; } private List<_Comment> comments; private Comment comment; } private Payload payload; public List<Comment> getComments() { List<Comment> comt = new ArrayList<Comment>(); if (payload != null) { // check if There are no results to show. - if ( !error.code.equals("007")) { - for (Payload._Comment item : payload.comments) { - Comment c = item.comment; - comt.add(c); + if (!error.code.equals("007")) { + if ((payload.comments != null) && (payload.comments.size() > 0)) { + for (Payload._Comment item : payload.comments) { + Comment c = item.comment; + comt.add(c); + } } } } return comt; } public Comment getComment() { return payload.comment; } }
true
true
public List<Comment> getComments() { List<Comment> comt = new ArrayList<Comment>(); if (payload != null) { // check if There are no results to show. if ( !error.code.equals("007")) { for (Payload._Comment item : payload.comments) { Comment c = item.comment; comt.add(c); } } } return comt; }
public List<Comment> getComments() { List<Comment> comt = new ArrayList<Comment>(); if (payload != null) { // check if There are no results to show. if (!error.code.equals("007")) { if ((payload.comments != null) && (payload.comments.size() > 0)) { for (Payload._Comment item : payload.comments) { Comment c = item.comment; comt.add(c); } } } } return comt; }
diff --git a/server/src/main/java/org/openqa/selenium/server/browserlaunchers/LauncherUtils.java b/server/src/main/java/org/openqa/selenium/server/browserlaunchers/LauncherUtils.java index 4a241cf8..2e7c10d4 100644 --- a/server/src/main/java/org/openqa/selenium/server/browserlaunchers/LauncherUtils.java +++ b/server/src/main/java/org/openqa/selenium/server/browserlaunchers/LauncherUtils.java @@ -1,295 +1,296 @@ package org.openqa.selenium.server.browserlaunchers; import net.sf.cotta.TDirectory; import net.sf.cotta.TFile; import net.sf.cotta.TIoException; import net.sf.cotta.utils.ClassPathLocator; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; import org.apache.tools.ant.taskdefs.Delete; import org.openqa.selenium.server.SeleniumServer; import java.io.*; import java.net.MalformedURLException; import java.net.URL; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Various static utility functions used to launch browsers */ public class LauncherUtils { /** * creates an empty temp directory for managing a browser profile */ protected static File createCustomProfileDir(String sessionId) { File tmpDir = new File(System.getProperty("java.io.tmpdir")); String customProfileDirParent = ((tmpDir.exists() && tmpDir.isDirectory()) ? tmpDir.getAbsolutePath() : "."); File customProfileDir = new File(customProfileDirParent + "/customProfileDir" + sessionId); if (customProfileDir.exists()) { LauncherUtils.recursivelyDeleteDir(customProfileDir); } customProfileDir.mkdir(); return customProfileDir; } /** * Delete a directory and all subdirectories */ protected static void recursivelyDeleteDir(File customProfileDir) { if (customProfileDir == null || !customProfileDir.exists()) { return; } Delete delete = new Delete(); delete.setProject(new Project()); delete.setDir(customProfileDir); delete.setFailOnError(true); delete.execute(); } /** * Try several times to recursively delete a directory */ protected static void deleteTryTryAgain(File dir, int tries) { try { recursivelyDeleteDir(dir); } catch (BuildException e) { if (tries > 0) { AsyncExecute.sleepTight(2000); deleteTryTryAgain(dir, tries - 1); } else { throw e; } } } /** * Generate a proxy.pac file, configuring a dynamic proxy for URLs * containing "/selenium-server/" */ protected static File makeProxyPAC(File parentDir, int port) throws FileNotFoundException { return makeProxyPAC(parentDir, port, true); } /** * Generate a proxy.pac file, configuring a dynamic proxy. <p/> If * proxySeleniumTrafficOnly is true, then the proxy applies only to URLs * containing "/selenium-server/". Otherwise the proxy applies to all URLs. */ protected static File makeProxyPAC(File parentDir, int port, boolean proxySeleniumTrafficOnly) throws FileNotFoundException { File proxyPAC = new File(parentDir, "proxy.pac"); PrintStream out = new PrintStream(new FileOutputStream(proxyPAC)); String defaultProxy = "DIRECT"; String configuredProxy = System.getProperty("http.proxyHost"); if (configuredProxy != null) { defaultProxy = "PROXY " + configuredProxy; String proxyPort = System.getProperty("http.proxyPort"); if (proxyPort != null) { defaultProxy += ":" + proxyPort; } } out.println("function FindProxyForURL(url, host) {"); if (proxySeleniumTrafficOnly) { out.println(" if(shExpMatch(url, '*/selenium-server/*')) {"); } out.println(" return 'PROXY localhost:" + Integer.toString(port) + "; " + defaultProxy + "';"); if (configuredProxy != null) { out.println(" } else {"); out.println(" return '" + defaultProxy + "';"); } if (proxySeleniumTrafficOnly) { out.println(" }"); } out.println("}"); out.close(); return proxyPAC; } /** * Strips the specified URL so it only includes a protocal, hostname and * port * * @throws MalformedURLException */ public static String stripStartURL(String url) { try { URL u = new URL(url); return u.getProtocol() + "://" + u.getAuthority(); } catch (MalformedURLException e) { throw new RuntimeException(e); } } protected static String getQueryString(String url) { try { URL u = new URL(url); String query = u.getQuery(); return query == null ? "" : query; } catch (MalformedURLException e) { throw new RuntimeException(e); } } protected static String getDefaultHTMLSuiteUrl(String browserURL, String suiteUrl, boolean multiWindow) { String url = LauncherUtils.stripStartURL(browserURL); return url + "/selenium-server/core/TestRunner.html?auto=true&" + "multiWindow=" + multiWindow + "&resultsUrl=../postResults&test=" + suiteUrl; } protected static String getDefaultRemoteSessionUrl(String startURL, String sessionId, boolean multiWindow) { String url = LauncherUtils.stripStartURL(startURL); return url + "/selenium-server/core/SeleneseRunner.html?" + "sessionId=" + sessionId + "&multiWindow=" + multiWindow + "&debugMode=" + SeleniumServer.isDebugMode(); } protected static File extractHTAFile(File dir, int port, String resourceFile, String outFile) { InputStream input = HTABrowserLauncher.class.getResourceAsStream(resourceFile); BufferedReader br = new BufferedReader(new InputStreamReader(input)); File hta = new File(dir, outFile); try { FileWriter fw = new FileWriter(hta); String line = br.readLine(); fw.write(line); fw.write('\n'); fw.write("<base href=\"http://localhost:" + port + "/selenium-server/core/\">"); while ((line = br.readLine()) != null) { fw.write(line); fw.write('\n'); } fw.flush(); fw.close(); } catch (IOException e) { throw new RuntimeException(e); } return hta; } protected static void assertNotScriptFile(File f) { try { FileReader r = new FileReader(f); char firstTwoChars[] = new char[2]; int charsRead = r.read(firstTwoChars); if (charsRead != 2) return; if (firstTwoChars[0] == '#' && firstTwoChars[1] == '!') { throw new RuntimeException("File was a script file, not a real executable: " + f.getAbsolutePath()); } } catch (IOException e) { throw new RuntimeException(e); } } protected static void copyDirectory(TDirectory sourceLocation, TDirectory targetLocation) throws IOException { targetLocation.ensureExists(); TDirectory[] subSourceDirs = sourceLocation.listDirs(); for (int i = 0; i < subSourceDirs.length; i++) { TDirectory subSourceLocation = subSourceDirs[i]; copyDirectory(subSourceLocation, targetLocation.dir(subSourceLocation.name())); } TFile[] files = sourceLocation.listFiles(); for (int i = 0; i < files.length; i++) { TFile file = files[i]; file.copyTo(targetLocation.file(file.name())); } } protected static void generatePacAndPrefJs(File customProfileDir, int port, boolean proxySeleniumTrafficOnly) throws FileNotFoundException { generatePacAndPrefJs(customProfileDir, port, proxySeleniumTrafficOnly, null); } protected static void generatePacAndPrefJs(File customProfileDir, int port, boolean proxySeleniumTrafficOnly, String homePage) throws FileNotFoundException { // TODO Do we want to make these preferences configurable somehow? // TODO: there is redundancy between these settings in the settings in // FirefoxChromeLauncher. // Those settings should be combined into a single location. File proxyPAC = LauncherUtils.makeProxyPAC(customProfileDir, port, proxySeleniumTrafficOnly); File prefsJS = new File(customProfileDir, "prefs.js"); PrintStream out = new PrintStream(new FileOutputStream(prefsJS)); // Don't ask if we want to switch default browsers out.println("user_pref('browser.shell.checkDefaultBrowser', false);"); // suppress authentication confirmations out.println("user_pref('network.http.phishy-userpass-length', 255);"); // Disable pop-up blocking out.println("user_pref('browser.allowpopups', true);"); out.println("user_pref('dom.disable_open_during_load', false);"); // Open links in new windows (Firefox 2.0) out.println("user_pref('browser.link.open_external', 2);"); out.println("user_pref('browser.link.open_newwindow', 2);"); // Configure us as the local proxy out.println("user_pref('network.proxy.type', 2);"); out.println("user_pref('network.proxy.autoconfig_url', '" + pathToBrowserURL(proxyPAC.getAbsolutePath()) + "');"); if (homePage != null) { out.println("user_pref('startup.homepage_override_url', '" + homePage + "');"); // for Firefox 2.0 out.println("user_pref('browser.startup.homepage', '" + homePage + "');"); + out.println("user_pref('startup.homepage_welcome_url', '');"); } // Disable security warnings out.println("user_pref('security.warn_submit_insecure', false);"); out.println("user_pref('security.warn_submit_insecure.show_once', false);"); out.println("user_pref('security.warn_entering_secure', false);"); out.println("user_pref('security.warn_entering_secure.show_once', false);"); out.println("user_pref('security.warn_entering_weak', false);"); out.println("user_pref('security.warn_entering_weak.show_once', false);"); out.println("user_pref('security.warn_leaving_secure', false);"); out.println("user_pref('security.warn_leaving_secure.show_once', false);"); out.println("user_pref('security.warn_viewing_mixed', false);"); out.println("user_pref('security.warn_viewing_mixed.show_once', false);"); // Disable cache out.println("user_pref('browser.cache.disk.enable', false);"); out.println("user_pref('browser.cache.memory.enable', false);"); // Disable "do you want to remember this password?" out.println("user_pref('signon.rememberSignons', false);"); out.close(); } static final Pattern JAVA_STYLE_UNC_URL = Pattern.compile("^file:////([^/]+/.*)$"); /** * Generates an URL suitable for use in browsers, unlike Java's URLs, which * choke on UNC paths. <p/> * <P> * Java's URLs work in IE, but break in Mozilla. Mozilla's team snobbily * demanded that <I>all</I> file paths must have the empty authority * (file:///), even for UNC file paths. On Mozilla \\socrates\build is * therefore represented as file://///socrates/build. * </P> * See Mozilla bug <a * href="https://bugzilla.mozilla.org/show_bug.cgi?id=66194">66194</A>. * * @param path - * the file path to convert to a browser URL * @return a nice Mozilla-compatible file URL */ private static String pathToBrowserURL(String path) { if (path == null) return null; String url = (new File(path)).toURI().toString(); Matcher m = JAVA_STYLE_UNC_URL.matcher(url); if (m.find()) { url = "file://///"; url += m.group(1); } return url; } static public void main(String[] args) throws TIoException { TDirectory dir = new ClassPathLocator(LauncherUtils.class).locate().asDirectory(); TFile[] files = dir.dir("customProfileDirCUSTFFCHROME").listFiles(); for (int i = 0; i < files.length; i++) { TFile file = files[i]; System.out.println("file = " + file); } } }
true
true
protected static void generatePacAndPrefJs(File customProfileDir, int port, boolean proxySeleniumTrafficOnly, String homePage) throws FileNotFoundException { // TODO Do we want to make these preferences configurable somehow? // TODO: there is redundancy between these settings in the settings in // FirefoxChromeLauncher. // Those settings should be combined into a single location. File proxyPAC = LauncherUtils.makeProxyPAC(customProfileDir, port, proxySeleniumTrafficOnly); File prefsJS = new File(customProfileDir, "prefs.js"); PrintStream out = new PrintStream(new FileOutputStream(prefsJS)); // Don't ask if we want to switch default browsers out.println("user_pref('browser.shell.checkDefaultBrowser', false);"); // suppress authentication confirmations out.println("user_pref('network.http.phishy-userpass-length', 255);"); // Disable pop-up blocking out.println("user_pref('browser.allowpopups', true);"); out.println("user_pref('dom.disable_open_during_load', false);"); // Open links in new windows (Firefox 2.0) out.println("user_pref('browser.link.open_external', 2);"); out.println("user_pref('browser.link.open_newwindow', 2);"); // Configure us as the local proxy out.println("user_pref('network.proxy.type', 2);"); out.println("user_pref('network.proxy.autoconfig_url', '" + pathToBrowserURL(proxyPAC.getAbsolutePath()) + "');"); if (homePage != null) { out.println("user_pref('startup.homepage_override_url', '" + homePage + "');"); // for Firefox 2.0 out.println("user_pref('browser.startup.homepage', '" + homePage + "');"); } // Disable security warnings out.println("user_pref('security.warn_submit_insecure', false);"); out.println("user_pref('security.warn_submit_insecure.show_once', false);"); out.println("user_pref('security.warn_entering_secure', false);"); out.println("user_pref('security.warn_entering_secure.show_once', false);"); out.println("user_pref('security.warn_entering_weak', false);"); out.println("user_pref('security.warn_entering_weak.show_once', false);"); out.println("user_pref('security.warn_leaving_secure', false);"); out.println("user_pref('security.warn_leaving_secure.show_once', false);"); out.println("user_pref('security.warn_viewing_mixed', false);"); out.println("user_pref('security.warn_viewing_mixed.show_once', false);"); // Disable cache out.println("user_pref('browser.cache.disk.enable', false);"); out.println("user_pref('browser.cache.memory.enable', false);"); // Disable "do you want to remember this password?" out.println("user_pref('signon.rememberSignons', false);"); out.close(); }
protected static void generatePacAndPrefJs(File customProfileDir, int port, boolean proxySeleniumTrafficOnly, String homePage) throws FileNotFoundException { // TODO Do we want to make these preferences configurable somehow? // TODO: there is redundancy between these settings in the settings in // FirefoxChromeLauncher. // Those settings should be combined into a single location. File proxyPAC = LauncherUtils.makeProxyPAC(customProfileDir, port, proxySeleniumTrafficOnly); File prefsJS = new File(customProfileDir, "prefs.js"); PrintStream out = new PrintStream(new FileOutputStream(prefsJS)); // Don't ask if we want to switch default browsers out.println("user_pref('browser.shell.checkDefaultBrowser', false);"); // suppress authentication confirmations out.println("user_pref('network.http.phishy-userpass-length', 255);"); // Disable pop-up blocking out.println("user_pref('browser.allowpopups', true);"); out.println("user_pref('dom.disable_open_during_load', false);"); // Open links in new windows (Firefox 2.0) out.println("user_pref('browser.link.open_external', 2);"); out.println("user_pref('browser.link.open_newwindow', 2);"); // Configure us as the local proxy out.println("user_pref('network.proxy.type', 2);"); out.println("user_pref('network.proxy.autoconfig_url', '" + pathToBrowserURL(proxyPAC.getAbsolutePath()) + "');"); if (homePage != null) { out.println("user_pref('startup.homepage_override_url', '" + homePage + "');"); // for Firefox 2.0 out.println("user_pref('browser.startup.homepage', '" + homePage + "');"); out.println("user_pref('startup.homepage_welcome_url', '');"); } // Disable security warnings out.println("user_pref('security.warn_submit_insecure', false);"); out.println("user_pref('security.warn_submit_insecure.show_once', false);"); out.println("user_pref('security.warn_entering_secure', false);"); out.println("user_pref('security.warn_entering_secure.show_once', false);"); out.println("user_pref('security.warn_entering_weak', false);"); out.println("user_pref('security.warn_entering_weak.show_once', false);"); out.println("user_pref('security.warn_leaving_secure', false);"); out.println("user_pref('security.warn_leaving_secure.show_once', false);"); out.println("user_pref('security.warn_viewing_mixed', false);"); out.println("user_pref('security.warn_viewing_mixed.show_once', false);"); // Disable cache out.println("user_pref('browser.cache.disk.enable', false);"); out.println("user_pref('browser.cache.memory.enable', false);"); // Disable "do you want to remember this password?" out.println("user_pref('signon.rememberSignons', false);"); out.close(); }
diff --git a/java/src/com/android/inputmethod/keyboard/PopupMiniKeyboardView.java b/java/src/com/android/inputmethod/keyboard/PopupMiniKeyboardView.java index fa2aa874..60d87f78 100644 --- a/java/src/com/android/inputmethod/keyboard/PopupMiniKeyboardView.java +++ b/java/src/com/android/inputmethod/keyboard/PopupMiniKeyboardView.java @@ -1,125 +1,127 @@ /* * Copyright (C) 2011 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.inputmethod.keyboard; import android.content.Context; import android.content.res.Resources; import android.os.SystemClock; import android.util.AttributeSet; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.widget.PopupWindow; import com.android.inputmethod.latin.R; /** * A view that renders a virtual {@link MiniKeyboard}. It handles rendering of keys and detecting * key presses and touch movements. */ public class PopupMiniKeyboardView extends KeyboardView implements PopupPanel { private final int[] mCoordinates = new int[2]; private final boolean mConfigShowMiniKeyboardAtTouchedPoint; private int mOriginX; private int mOriginY; private int mTrackerId; private long mDownTime; public PopupMiniKeyboardView(Context context, AttributeSet attrs) { this(context, attrs, R.attr.popupMiniKeyboardViewStyle); } public PopupMiniKeyboardView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); final Resources res = context.getResources(); mConfigShowMiniKeyboardAtTouchedPoint = res.getBoolean( R.bool.config_show_mini_keyboard_at_touched_point); // Override default ProximityKeyDetector. mKeyDetector = new MiniKeyboardKeyDetector(res.getDimension( R.dimen.mini_keyboard_slide_allowance)); // Remove gesture detector on mini-keyboard mGestureDetector = null; setKeyPreviewPopupEnabled(false, 0); } @Override public void setKeyPreviewPopupEnabled(boolean previewEnabled, int delay) { // Mini keyboard needs no pop-up key preview displayed, so we pass always false with a // delay of 0. The delay does not matter actually since the popup is not shown anyway. super.setKeyPreviewPopupEnabled(false, 0); } @Override public void showPanel(KeyboardView parentKeyboardView, Key parentKey, PointerTracker tracker, int keyPreviewY, PopupWindow window) { final View container = (View)getParent(); final MiniKeyboard miniKeyboard = (MiniKeyboard)getKeyboard(); final Keyboard parentKeyboard = parentKeyboardView.getKeyboard(); parentKeyboardView.getLocationInWindow(mCoordinates); final int pointX = (mConfigShowMiniKeyboardAtTouchedPoint) ? tracker.getLastX() : parentKey.mX + parentKey.mWidth / 2; final int pointY = parentKey.mY; - final int miniKeyboardX = pointX - miniKeyboard.getDefaultCoordX() - - container.getPaddingLeft() - + parentKeyboardView.getPaddingLeft() + mCoordinates[0]; + final int miniKeyboardLeft = pointX - miniKeyboard.getDefaultCoordX() + + parentKeyboardView.getPaddingLeft(); + final int miniKeyboardX = Math.max(0, Math.min(miniKeyboardLeft, + parentKeyboardView.getWidth() - miniKeyboard.getMinWidth())) + - container.getPaddingLeft() + mCoordinates[0]; final int miniKeyboardY = pointY - parentKeyboard.getVerticalGap() - (container.getMeasuredHeight() - container.getPaddingBottom()) + parentKeyboardView.getPaddingTop() + mCoordinates[1]; final int x = miniKeyboardX; final int y = parentKeyboardView.isKeyPreviewPopupEnabled() && miniKeyboard.isOneRowKeyboard() && keyPreviewY >= 0 ? keyPreviewY : miniKeyboardY; if (miniKeyboard.setShifted(parentKeyboard.isShiftedOrShiftLocked())) { invalidateAllKeys(); } window.setContentView(container); window.setWidth(container.getMeasuredWidth()); window.setHeight(container.getMeasuredHeight()); window.showAtLocation(parentKeyboardView, Gravity.NO_GRAVITY, x, y); mOriginX = x + container.getPaddingLeft() - mCoordinates[0]; mOriginY = y + container.getPaddingTop() - mCoordinates[1]; mTrackerId = tracker.mPointerId; mDownTime = SystemClock.uptimeMillis(); // Inject down event on the key to mini keyboard. final MotionEvent downEvent = translateMotionEvent(MotionEvent.ACTION_DOWN, pointX, pointY + parentKey.mHeight / 2, mDownTime); onTouchEvent(downEvent); downEvent.recycle(); } private MotionEvent translateMotionEvent(int action, float x, float y, long eventTime) { return MotionEvent.obtain(mDownTime, eventTime, action, x - mOriginX, y - mOriginY, 0); } @Override public boolean onTouchEvent(MotionEvent me) { final int index = me.getActionIndex(); final int id = me.getPointerId(index); if (id == mTrackerId) { final MotionEvent translated = translateMotionEvent(me.getAction(), me.getX(index), me.getY(index), me.getEventTime()); super.onTouchEvent(translated); translated.recycle(); } return true; } }
true
true
public void showPanel(KeyboardView parentKeyboardView, Key parentKey, PointerTracker tracker, int keyPreviewY, PopupWindow window) { final View container = (View)getParent(); final MiniKeyboard miniKeyboard = (MiniKeyboard)getKeyboard(); final Keyboard parentKeyboard = parentKeyboardView.getKeyboard(); parentKeyboardView.getLocationInWindow(mCoordinates); final int pointX = (mConfigShowMiniKeyboardAtTouchedPoint) ? tracker.getLastX() : parentKey.mX + parentKey.mWidth / 2; final int pointY = parentKey.mY; final int miniKeyboardX = pointX - miniKeyboard.getDefaultCoordX() - container.getPaddingLeft() + parentKeyboardView.getPaddingLeft() + mCoordinates[0]; final int miniKeyboardY = pointY - parentKeyboard.getVerticalGap() - (container.getMeasuredHeight() - container.getPaddingBottom()) + parentKeyboardView.getPaddingTop() + mCoordinates[1]; final int x = miniKeyboardX; final int y = parentKeyboardView.isKeyPreviewPopupEnabled() && miniKeyboard.isOneRowKeyboard() && keyPreviewY >= 0 ? keyPreviewY : miniKeyboardY; if (miniKeyboard.setShifted(parentKeyboard.isShiftedOrShiftLocked())) { invalidateAllKeys(); } window.setContentView(container); window.setWidth(container.getMeasuredWidth()); window.setHeight(container.getMeasuredHeight()); window.showAtLocation(parentKeyboardView, Gravity.NO_GRAVITY, x, y); mOriginX = x + container.getPaddingLeft() - mCoordinates[0]; mOriginY = y + container.getPaddingTop() - mCoordinates[1]; mTrackerId = tracker.mPointerId; mDownTime = SystemClock.uptimeMillis(); // Inject down event on the key to mini keyboard. final MotionEvent downEvent = translateMotionEvent(MotionEvent.ACTION_DOWN, pointX, pointY + parentKey.mHeight / 2, mDownTime); onTouchEvent(downEvent); downEvent.recycle(); }
public void showPanel(KeyboardView parentKeyboardView, Key parentKey, PointerTracker tracker, int keyPreviewY, PopupWindow window) { final View container = (View)getParent(); final MiniKeyboard miniKeyboard = (MiniKeyboard)getKeyboard(); final Keyboard parentKeyboard = parentKeyboardView.getKeyboard(); parentKeyboardView.getLocationInWindow(mCoordinates); final int pointX = (mConfigShowMiniKeyboardAtTouchedPoint) ? tracker.getLastX() : parentKey.mX + parentKey.mWidth / 2; final int pointY = parentKey.mY; final int miniKeyboardLeft = pointX - miniKeyboard.getDefaultCoordX() + parentKeyboardView.getPaddingLeft(); final int miniKeyboardX = Math.max(0, Math.min(miniKeyboardLeft, parentKeyboardView.getWidth() - miniKeyboard.getMinWidth())) - container.getPaddingLeft() + mCoordinates[0]; final int miniKeyboardY = pointY - parentKeyboard.getVerticalGap() - (container.getMeasuredHeight() - container.getPaddingBottom()) + parentKeyboardView.getPaddingTop() + mCoordinates[1]; final int x = miniKeyboardX; final int y = parentKeyboardView.isKeyPreviewPopupEnabled() && miniKeyboard.isOneRowKeyboard() && keyPreviewY >= 0 ? keyPreviewY : miniKeyboardY; if (miniKeyboard.setShifted(parentKeyboard.isShiftedOrShiftLocked())) { invalidateAllKeys(); } window.setContentView(container); window.setWidth(container.getMeasuredWidth()); window.setHeight(container.getMeasuredHeight()); window.showAtLocation(parentKeyboardView, Gravity.NO_GRAVITY, x, y); mOriginX = x + container.getPaddingLeft() - mCoordinates[0]; mOriginY = y + container.getPaddingTop() - mCoordinates[1]; mTrackerId = tracker.mPointerId; mDownTime = SystemClock.uptimeMillis(); // Inject down event on the key to mini keyboard. final MotionEvent downEvent = translateMotionEvent(MotionEvent.ACTION_DOWN, pointX, pointY + parentKey.mHeight / 2, mDownTime); onTouchEvent(downEvent); downEvent.recycle(); }
diff --git a/src/com/android/calendar/event/EventColorPickerDialog.java b/src/com/android/calendar/event/EventColorPickerDialog.java index 7eac6b0e..6826c796 100644 --- a/src/com/android/calendar/event/EventColorPickerDialog.java +++ b/src/com/android/calendar/event/EventColorPickerDialog.java @@ -1,67 +1,65 @@ /* * Copyright (C) 2013 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.calendar.event; import android.app.Activity; import android.content.DialogInterface; import android.os.Bundle; import com.android.calendar.R; import com.android.colorpicker.ColorPickerDialog; /** * A dialog which displays event colors, with an additional button for the calendar color. */ public class EventColorPickerDialog extends ColorPickerDialog { private static final int NUM_COLUMNS = 4; private int mCalendarColor; public EventColorPickerDialog() { // Empty constructor required for dialog fragment. } public EventColorPickerDialog(int[] colors, int selectedColor, int calendarColor, boolean isTablet) { super(R.string.event_color_picker_dialog_title, colors, selectedColor, NUM_COLUMNS, isTablet ? SIZE_LARGE : SIZE_SMALL); mCalendarColor = calendarColor; } public void setCalendarColor(int color) { mCalendarColor = color; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); final Activity activity = getActivity(); mAlertDialog.setButton(DialogInterface.BUTTON_NEUTRAL, activity.getString(R.string.event_color_set_to_default), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { - if (mListener != null) { - mListener.onColorSelected(mCalendarColor); - } + onColorSelected(mCalendarColor); } } ); } }
true
true
public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); final Activity activity = getActivity(); mAlertDialog.setButton(DialogInterface.BUTTON_NEUTRAL, activity.getString(R.string.event_color_set_to_default), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (mListener != null) { mListener.onColorSelected(mCalendarColor); } } } ); }
public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); final Activity activity = getActivity(); mAlertDialog.setButton(DialogInterface.BUTTON_NEUTRAL, activity.getString(R.string.event_color_set_to_default), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { onColorSelected(mCalendarColor); } } ); }
diff --git a/src/no/hials/muldvarp/v2/QuizActivity.java b/src/no/hials/muldvarp/v2/QuizActivity.java index 0e8295e..06f1f5f 100644 --- a/src/no/hials/muldvarp/v2/QuizActivity.java +++ b/src/no/hials/muldvarp/v2/QuizActivity.java @@ -1,198 +1,202 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package no.hials.muldvarp.v2; import android.app.AlertDialog; import android.app.FragmentTransaction; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.ListView; import java.util.ArrayList; import java.util.Collections; import no.hials.muldvarp.R; import no.hials.muldvarp.v2.domain.Domain; import no.hials.muldvarp.v2.domain.Question; import no.hials.muldvarp.v2.domain.Quiz; import no.hials.muldvarp.v2.fragments.QuizQuestionFragment; /** * This class defines an Activity used for Quiz-functionality. * * @author johan */ public class QuizActivity extends MuldvarpActivity{ //Global Variables View mainQuizView; View holderQuizView; ListView listView; Quiz quiz; int currentQuestionNumber; //Fragments ArrayList<QuizQuestionFragment> questionFragments; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //See if the Activity was started with an Intent that included a Domain object if(getIntent().hasExtra("Domain")) { domain = (Domain) getIntent().getExtras().get("Domain"); activityName = domain.getName(); quiz = (Quiz) domain; setupQuiz(); } } public void setupQuiz(){ //Change content view with animation LayoutInflater inflator = getLayoutInflater(); holderQuizView = inflator.inflate(R.layout.activity_quiz_question_holder, null, false); holderQuizView.startAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_in)); setContentView(holderQuizView); //Get fragments currentQuestionNumber = 0; if (!quiz.getQuestions().isEmpty()) { questionFragments = new ArrayList<QuizQuestionFragment>(); fillQuestionFragmentList(); FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.replace(R.id.QuizQuestionFragmentHolder, questionFragments.get(currentQuestionNumber)).commit(); } Button backToMainQuizButton = (Button) findViewById(R.id.backToMainQuizActivityButton); backToMainQuizButton.setText(R.string.quizBackToMainQuizButtonText); backToMainQuizButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { showReturnDialog(); } }); final Button prevQuestionButton = (Button) findViewById(R.id.quizPreviousButton); prevQuestionButton.setEnabled(false); prevQuestionButton.setText(R.string.quizPreviousButtonText); prevQuestionButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (currentQuestionNumber > 0) { Button nextQuestionButton = (Button) findViewById(R.id.quizNextButton); nextQuestionButton.setText(R.string.quizNextButtonText); onBackPressed(); if (currentQuestionNumber == 0){ prevQuestionButton.setEnabled(false); } } } }); final Button nextQuestionButton = (Button) findViewById(R.id.quizNextButton); - nextQuestionButton.setText(R.string.quizNextButtonText); + if (currentQuestionNumber >= quiz.getQuestions().size()-1){ + nextQuestionButton.setText(R.string.quizGoToResultsButtonText); + } else { + nextQuestionButton.setText(R.string.quizNextButtonText); + } nextQuestionButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (currentQuestionNumber < (quiz.getQuestions().size() -1)) { currentQuestionNumber++; prevQuestionButton.setEnabled(true); FragmentTransaction ft = getFragmentManager().beginTransaction(); // ft.setCustomAnimations(R.anim.fragment_slide_left_enter, // R.anim.fragment_slide_left_exit, // R.anim.fragment_slide_right_enter, // R.anim.fragment_slide_right_exit); ft.replace(R.id.QuizQuestionFragmentHolder, questionFragments.get(currentQuestionNumber)); ft.addToBackStack(null); ft.commit(); if (currentQuestionNumber >= quiz.getQuestions().size()-1){ nextQuestionButton.setText(R.string.quizGoToResultsButtonText); } } else if (currentQuestionNumber >= quiz.getQuestions().size()-1){ if(checkQuestionsForEmptyAnswers()){ showWarningDialog(); } else { Intent quizResultsIntent = new Intent(getApplicationContext(), QuizResultActivity.class); quizResultsIntent.putExtra("Quiz", quiz); startActivity(quizResultsIntent); finish(); //end the quizactivity } } } }); } /** * This method runs through all the questions in the quiz and returns true if there are * unanswered questions. * * It uses the checkForEmptyAnswers() method in the QuizQuestionFragment. * @return */ public boolean checkQuestionsForEmptyAnswers(){ for (int i = 0; i < quiz.getQuestions().size(); i++) { QuizQuestionFragment tempFrag = questionFragments.get(i); if(!tempFrag.checkForEmptyAnswers()){ return true; } } return false; } @Override public void onBackPressed() { currentQuestionNumber--; super.onBackPressed(); } private void fillQuestionFragmentList(){ //Only fill question fragment list if it hasn't been filled already if(questionFragments.isEmpty()){ questionFragments = new ArrayList<QuizQuestionFragment>(); if(quiz.isShuffleQuestions()){ Collections.shuffle(quiz.getQuestions()); } for (int i = 0; i < quiz.getQuestions().size(); i++) { Question tempQuestion = quiz.getQuestions().get(i); QuizQuestionFragment tempFrag = new QuizQuestionFragment(tempQuestion); tempFrag.setQuestionAmount(quiz.getQuestions().size()); tempFrag.setQuestionNo(i+1); questionFragments.add(tempFrag); } } } /** * Void method containing functionality to construct a dialog. */ public void showReturnDialog(){ AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.quizResultBackToQuizText).setTitle(R.string.quizResultBackToQuizPrompt); builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { //DO NOTHING } }); builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { finish(); //end the quizactivity } }); AlertDialog dialog = builder.create(); dialog.show(); } /** * Void method containing functionality to construct a dialog. */ public void showWarningDialog(){ AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.quizUnfilledAnswersWarningText).setTitle(R.string.warning); builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { } }); AlertDialog dialog = builder.create(); dialog.show(); } }
true
true
public void setupQuiz(){ //Change content view with animation LayoutInflater inflator = getLayoutInflater(); holderQuizView = inflator.inflate(R.layout.activity_quiz_question_holder, null, false); holderQuizView.startAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_in)); setContentView(holderQuizView); //Get fragments currentQuestionNumber = 0; if (!quiz.getQuestions().isEmpty()) { questionFragments = new ArrayList<QuizQuestionFragment>(); fillQuestionFragmentList(); FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.replace(R.id.QuizQuestionFragmentHolder, questionFragments.get(currentQuestionNumber)).commit(); } Button backToMainQuizButton = (Button) findViewById(R.id.backToMainQuizActivityButton); backToMainQuizButton.setText(R.string.quizBackToMainQuizButtonText); backToMainQuizButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { showReturnDialog(); } }); final Button prevQuestionButton = (Button) findViewById(R.id.quizPreviousButton); prevQuestionButton.setEnabled(false); prevQuestionButton.setText(R.string.quizPreviousButtonText); prevQuestionButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (currentQuestionNumber > 0) { Button nextQuestionButton = (Button) findViewById(R.id.quizNextButton); nextQuestionButton.setText(R.string.quizNextButtonText); onBackPressed(); if (currentQuestionNumber == 0){ prevQuestionButton.setEnabled(false); } } } }); final Button nextQuestionButton = (Button) findViewById(R.id.quizNextButton); nextQuestionButton.setText(R.string.quizNextButtonText); nextQuestionButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (currentQuestionNumber < (quiz.getQuestions().size() -1)) { currentQuestionNumber++; prevQuestionButton.setEnabled(true); FragmentTransaction ft = getFragmentManager().beginTransaction(); // ft.setCustomAnimations(R.anim.fragment_slide_left_enter, // R.anim.fragment_slide_left_exit, // R.anim.fragment_slide_right_enter, // R.anim.fragment_slide_right_exit); ft.replace(R.id.QuizQuestionFragmentHolder, questionFragments.get(currentQuestionNumber)); ft.addToBackStack(null); ft.commit(); if (currentQuestionNumber >= quiz.getQuestions().size()-1){ nextQuestionButton.setText(R.string.quizGoToResultsButtonText); } } else if (currentQuestionNumber >= quiz.getQuestions().size()-1){ if(checkQuestionsForEmptyAnswers()){ showWarningDialog(); } else { Intent quizResultsIntent = new Intent(getApplicationContext(), QuizResultActivity.class); quizResultsIntent.putExtra("Quiz", quiz); startActivity(quizResultsIntent); finish(); //end the quizactivity } } } }); }
public void setupQuiz(){ //Change content view with animation LayoutInflater inflator = getLayoutInflater(); holderQuizView = inflator.inflate(R.layout.activity_quiz_question_holder, null, false); holderQuizView.startAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_in)); setContentView(holderQuizView); //Get fragments currentQuestionNumber = 0; if (!quiz.getQuestions().isEmpty()) { questionFragments = new ArrayList<QuizQuestionFragment>(); fillQuestionFragmentList(); FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.replace(R.id.QuizQuestionFragmentHolder, questionFragments.get(currentQuestionNumber)).commit(); } Button backToMainQuizButton = (Button) findViewById(R.id.backToMainQuizActivityButton); backToMainQuizButton.setText(R.string.quizBackToMainQuizButtonText); backToMainQuizButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { showReturnDialog(); } }); final Button prevQuestionButton = (Button) findViewById(R.id.quizPreviousButton); prevQuestionButton.setEnabled(false); prevQuestionButton.setText(R.string.quizPreviousButtonText); prevQuestionButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (currentQuestionNumber > 0) { Button nextQuestionButton = (Button) findViewById(R.id.quizNextButton); nextQuestionButton.setText(R.string.quizNextButtonText); onBackPressed(); if (currentQuestionNumber == 0){ prevQuestionButton.setEnabled(false); } } } }); final Button nextQuestionButton = (Button) findViewById(R.id.quizNextButton); if (currentQuestionNumber >= quiz.getQuestions().size()-1){ nextQuestionButton.setText(R.string.quizGoToResultsButtonText); } else { nextQuestionButton.setText(R.string.quizNextButtonText); } nextQuestionButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (currentQuestionNumber < (quiz.getQuestions().size() -1)) { currentQuestionNumber++; prevQuestionButton.setEnabled(true); FragmentTransaction ft = getFragmentManager().beginTransaction(); // ft.setCustomAnimations(R.anim.fragment_slide_left_enter, // R.anim.fragment_slide_left_exit, // R.anim.fragment_slide_right_enter, // R.anim.fragment_slide_right_exit); ft.replace(R.id.QuizQuestionFragmentHolder, questionFragments.get(currentQuestionNumber)); ft.addToBackStack(null); ft.commit(); if (currentQuestionNumber >= quiz.getQuestions().size()-1){ nextQuestionButton.setText(R.string.quizGoToResultsButtonText); } } else if (currentQuestionNumber >= quiz.getQuestions().size()-1){ if(checkQuestionsForEmptyAnswers()){ showWarningDialog(); } else { Intent quizResultsIntent = new Intent(getApplicationContext(), QuizResultActivity.class); quizResultsIntent.putExtra("Quiz", quiz); startActivity(quizResultsIntent); finish(); //end the quizactivity } } } }); }
diff --git a/seide-core/src/main/java/net/sf/seide/stages/impl/StageStatisticsImpl.java b/seide-core/src/main/java/net/sf/seide/stages/impl/StageStatisticsImpl.java index 6fb4010..5b81a6b 100644 --- a/seide-core/src/main/java/net/sf/seide/stages/impl/StageStatisticsImpl.java +++ b/seide-core/src/main/java/net/sf/seide/stages/impl/StageStatisticsImpl.java @@ -1,100 +1,100 @@ package net.sf.seide.stages.impl; import java.util.concurrent.atomic.AtomicLong; import net.sf.seide.stages.StageStatistics; public class StageStatisticsImpl implements StageStatistics { private final String context; private final String id; private final AtomicLong pending = new AtomicLong(0); private final AtomicLong running = new AtomicLong(0); private final AtomicLong totalExecutions = new AtomicLong(0); private final AtomicLong totalExecutionTime = new AtomicLong(0); private final AtomicLong minExecutionTime = new AtomicLong(-1); private final AtomicLong maxExecutionTime = new AtomicLong(-1); public StageStatisticsImpl(String context, String id) { this.context = context; this.id = id; } public String getContext() { return this.context; } public String getId() { return this.id; } public long getPendingCount() { return this.pending.get(); } public long getRunningCount() { return this.running.get(); } public long getTotalExecutionCount() { return this.totalExecutions.get(); } public long getTotalExecutionTime() { return this.totalExecutionTime.get(); } public long getMinExecutionTime() { return this.minExecutionTime.get(); } public long getMaxExecutionTime() { return this.maxExecutionTime.get(); } public double getAvgExecutionTime() { long count = this.totalExecutions.get(); if (count > 0) { return this.totalExecutionTime.get() / count * 1.0; } else { return 0; } } public void addPending() { this.pending.incrementAndGet(); } public void removePending() { this.pending.decrementAndGet(); } public void addRunning() { this.running.incrementAndGet(); } public void removeRunning() { this.running.decrementAndGet(); } public void trackTimeAndExecution(long time) { this.totalExecutions.incrementAndGet(); this.totalExecutionTime.addAndGet(time); // FIXME: buggy... someone could change the value while I'm writting... if (!this.minExecutionTime.compareAndSet(-1, time)) { long safe = this.minExecutionTime.get(); - if (safe < time) { + if (time < safe) { this.minExecutionTime.compareAndSet(safe, time); } } if (!this.maxExecutionTime.compareAndSet(-1, time)) { long safe = this.maxExecutionTime.get(); - if (safe > time) { + if (time > safe) { this.maxExecutionTime.compareAndSet(safe, time); } } } }
false
true
public void trackTimeAndExecution(long time) { this.totalExecutions.incrementAndGet(); this.totalExecutionTime.addAndGet(time); // FIXME: buggy... someone could change the value while I'm writting... if (!this.minExecutionTime.compareAndSet(-1, time)) { long safe = this.minExecutionTime.get(); if (safe < time) { this.minExecutionTime.compareAndSet(safe, time); } } if (!this.maxExecutionTime.compareAndSet(-1, time)) { long safe = this.maxExecutionTime.get(); if (safe > time) { this.maxExecutionTime.compareAndSet(safe, time); } } }
public void trackTimeAndExecution(long time) { this.totalExecutions.incrementAndGet(); this.totalExecutionTime.addAndGet(time); // FIXME: buggy... someone could change the value while I'm writting... if (!this.minExecutionTime.compareAndSet(-1, time)) { long safe = this.minExecutionTime.get(); if (time < safe) { this.minExecutionTime.compareAndSet(safe, time); } } if (!this.maxExecutionTime.compareAndSet(-1, time)) { long safe = this.maxExecutionTime.get(); if (time > safe) { this.maxExecutionTime.compareAndSet(safe, time); } } }
diff --git a/amibe/src/org/jcae/mesh/amibe/algos2d/Insertion.java b/amibe/src/org/jcae/mesh/amibe/algos2d/Insertion.java index e5bdddb5..fa862712 100644 --- a/amibe/src/org/jcae/mesh/amibe/algos2d/Insertion.java +++ b/amibe/src/org/jcae/mesh/amibe/algos2d/Insertion.java @@ -1,472 +1,466 @@ /* jCAE stand for Java Computer Aided Engineering. Features are : Small CAD modeler, Finite element mesher, Plugin architecture. Copyright (C) 2003,2004,2005,2006, by EADS CRC Copyright (C) 2007,2008,2009, by EADS France This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.jcae.mesh.amibe.algos2d; import org.jcae.mesh.amibe.ds.TriangleVH; import org.jcae.mesh.amibe.ds.Triangle; import org.jcae.mesh.amibe.ds.AbstractHalfEdge; import org.jcae.mesh.amibe.ds.Vertex; import org.jcae.mesh.amibe.patch.Mesh2D; import org.jcae.mesh.amibe.patch.VirtualHalfEdge2D; import org.jcae.mesh.amibe.patch.Vertex2D; import org.jcae.mesh.amibe.metrics.KdTree; import org.jcae.mesh.amibe.metrics.Metric; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.HashSet; import gnu.trove.PrimeFinder; import java.util.logging.Level; import java.util.logging.Logger; /** * Insert nodes to produce a unit mesh. Process all edges; if an edge * is longer than sqrt(2), candidate vertices are added to a bucket * to virtually provide unit length subsegments. * The next step is to take vertices from the bucket in random order. * For each vertex <code>v</code>, the closest vertex <code>w</code> * already present in the mesh is returned by * {@link org.jcae.mesh.amibe.metrics.KdTree#getNearestVertex} * If the distance between <code>v</code> and <code>w</code> is lower * than 1/sqrt(2), <code>v</code> is dropped, otherwise it is inserted * into the mesh. Just after a vertex is inserted, incident edges are * swapped if they are not Delaunay. * The whole process is repeated until no new vertex is added. * * <p> * If all vertices of an edge were inserted at the same time, adjacent * edges may get in trouble because their candidate vertices could be * too near from these points. In order to avoid this problem, vertices * are processed in a random order so that all edges have a chance to be * splitted. As we want reproducible meshes, a pseudo-random order is * preferred. * </p> * * <p> * Triangle centroids are also inserted if they are not too near of * existing vertices. This was added to try to improve triangle * quality, but is a bad idea. Bad triangles should instead be sorted * (with {@link org.jcae.mesh.amibe.util.PAVLSortedTree}) and their * circumcenter added to the mesh if the overall quality is improved, * </p> * * <p> * The {@link AbstractHalfEdge#MARKED} flag has two purposes: half-edges * must be processed once, and when a small edge has been found, it will * never be processed, so there is no need to compute its length again * and again. By convention, if an half-edge and its symmetric half-edge * has both been tagged with <code>AbstractHalfEdge.MARKED</code>, this * means that this edge is small. If either an half-edge ot its symmetric * half-edge is tagged, this edge has already been processed. * </p> */ public class Insertion { private static final Logger LOGGER=Logger.getLogger(Insertion.class.getName()); private static final double ONE_PLUS_SQRT2 = 1.0 + Math.sqrt(2.0); private final Mesh2D mesh; private final KdTree<Vertex> kdTree; private final double minlen; private final double maxlen; // useful to see if addCandidatePoints() does its job private int nrInterpolations; private int nrFailedInterpolations; /** * Creates a <code>Insertion</code> instance. * * @param m the <code>Mesh2D</code> instance to refine. */ public Insertion(Mesh2D m, double minlen, double maxlen) { mesh = m; kdTree = mesh.getKdTree(); this.minlen = minlen; this.maxlen = maxlen; } /** * Iteratively insert inner nodes. */ public final void compute() { int nrIter = 0; LOGGER.config("Enter compute()"); LOGGER.fine(" Insert inner nodes"); ArrayList<Vertex2D> nodes = new ArrayList<Vertex2D>(); ArrayList<Vertex2D> triNodes = new ArrayList<Vertex2D>(); VirtualHalfEdge2D sym = new VirtualHalfEdge2D(); VirtualHalfEdge2D ot = new VirtualHalfEdge2D(); HashSet<Triangle> trianglesToCheck = new HashSet<Triangle>(mesh.getTriangles().size()); double curMinlen = minlen; // We use a LinkedHashSet instance below to keep triangle order LinkedHashSet<Triangle> oldTrianglesToCheck = new LinkedHashSet<Triangle>(mesh.getTriangles().size()); // We do not want to split boundary edges. for(Triangle gt : mesh.getTriangles()) { if (gt.hasAttributes(AbstractHalfEdge.OUTER)) continue; TriangleVH t = (TriangleVH) gt; ot.bind(t); oldTrianglesToCheck.add(t); for (int i = 0; i < 3; i++) { ot.next(); if (ot.hasAttributes(AbstractHalfEdge.BOUNDARY)) { ot.setAttributes(AbstractHalfEdge.MARKED); sym.bind((TriangleVH) ot.getTri(), ot.getLocalNumber()); sym.sym(); sym.setAttributes(AbstractHalfEdge.MARKED); } else ot.clearAttributes(AbstractHalfEdge.MARKED); } } // We try to insert new nodes by splitting large edges. As edge collapse // is costful, nodes are inserted only if it does not create small edges, // which means that nodes are not deleted. // We iterate over all edges, and put candidate nodes into triNodes. // If an edge has no candidates, either because it is small or because no // nodes can be inserted, it is tagged and will not have to be checked // during next iterations. // For triangle centroids, this is a little bit more difficult, we need to // keep track of triangles which have been modified at previous iteration. while (true) { nrIter++; // Maximal number of nodes which are inserted on an edge int maxNodes = 0; // Number of checked edges int checked = 0; // Number of nodes which are too near from existing vertices int tooNearNodes = 0; // Number of quadtree cells split int kdtreeSplit = 0; nodes.clear(); LOGGER.fine("Check all edges"); for(Triangle gt : mesh.getTriangles()) { if (gt.hasAttributes(AbstractHalfEdge.OUTER)) continue; TriangleVH t = (TriangleVH) gt; ot.bind(t); triNodes.clear(); // Maximal number of nodes which are inserted on edges of this triangle int nrTriNodes = 0; for (int i = 0; i < 3; i++) { ot.next(); if (ot.hasAttributes(AbstractHalfEdge.MARKED)) { // This edge has already been checked and cannot be split continue; } + // Tag symmetric edge so that edges are checked only once sym.bind((TriangleVH) ot.getTri(), ot.getLocalNumber()); sym.sym(); - if (sym.hasAttributes(AbstractHalfEdge.MARKED)) - { - // This edge has already been checked and cannot be split - continue; - } + sym.setAttributes(AbstractHalfEdge.MARKED); double l = mesh.interpolatedDistance((Vertex2D) ot.origin(), (Vertex2D) ot.destination()); if (l < maxlen) { // This edge is smaller than target size and is not split ot.setAttributes(AbstractHalfEdge.MARKED); - sym.setAttributes(AbstractHalfEdge.MARKED); continue; } - // Tag symmetric edge so that edges are checked only once - sym.setAttributes(AbstractHalfEdge.MARKED); int nrNodes = addCandidatePoints(ot, sym, l, triNodes); if (nrNodes > nrTriNodes) { nrTriNodes = nrNodes; } else if (nrNodes == 0) { ot.setAttributes(AbstractHalfEdge.MARKED); } checked++; } if (nrTriNodes > maxNodes) maxNodes = nrTriNodes; if (!triNodes.isEmpty()) { // Process in pseudo-random order int prime = PrimeFinder.nextPrime(nrTriNodes); int imax = triNodes.size(); while (imax % prime == 0) prime = PrimeFinder.nextPrime(prime+1); if (prime >= imax) prime = 1; int index = imax / 2; for (int i = 0; i < imax; i++) { Vertex2D v = triNodes.get(index); Metric metric = mesh.getMetric(v); double[] uv = v.getUV(); Vertex2D n = (Vertex2D) kdTree.getNearestVertex(metric, uv); assert checkNearestVertex(metric, uv, n); if (mesh.interpolatedDistance(v, n) > curMinlen) { kdTree.add(v); nodes.add(v); } else tooNearNodes++; index += prime; if (index >= imax) index -= imax; } } } // Try to insert triangle centroids after other points. // We scan triangles for which centroid have already // proven to be valid, and all triangles which have been // modified by vertex insertion. Vertex2D c = null; trianglesToCheck.clear(); LOGGER.fine("Check triangle centroids for "+oldTrianglesToCheck.size()+" triangles"); for (Triangle gt : oldTrianglesToCheck) { if (gt.hasAttributes(AbstractHalfEdge.OUTER)) continue; TriangleVH t = (TriangleVH) gt; // Check triangle centroid only if at least one edge is large boolean tooSmall = true; ot.bind(t); for (int j = 0; tooSmall && j < 3; j++) { ot.next(); if (ot.hasAttributes(AbstractHalfEdge.MARKED)) { sym.bind((TriangleVH) ot.getTri(), ot.getLocalNumber()); sym.sym(); if (!sym.hasAttributes(AbstractHalfEdge.MARKED)) tooSmall = false; } else tooSmall = false; } if (tooSmall) continue; if (c == null) c = (Vertex2D) mesh.createVertex(0.0, 0.0); mesh.moveVertexToCentroid(c, t); // Link to surrounding triangle to speed up // kdTree.getNearestVertex() and thus // v.getSurroundingOTriangle() below. c.setLink(t); Metric metric = mesh.getMetric(c); Vertex2D n = (Vertex2D) kdTree.getNearestVertex(metric, c.getUV()); assert checkNearestVertex(metric, c.getUV(), n); if (mesh.interpolatedDistance(c, n) > curMinlen) { kdTree.add(c); nodes.add(c); trianglesToCheck.add(t); c = null; } } if (nodes.isEmpty()) { if (checked > 0) { LOGGER.fine("No candidate found after checking "+checked+" edges"); if (tooNearNodes > 0) LOGGER.fine(tooNearNodes+" nodes are too near to be inserted"); if (curMinlen > 0.5*minlen && tooNearNodes > checked / 2) { curMinlen *= 0.9; LOGGER.fine("Lower minlen to "+curMinlen); continue; } } break; } // Reset curMinlen to minlen curMinlen = minlen; for (Vertex2D v : nodes) { // These vertices are not bound to any triangles, so // they must be removed, otherwise getSurroundingOTriangle // may return a null pointer. kdTree.remove(v); } LOGGER.fine("Try to insert "+nodes.size()+" nodes"); // Process in pseudo-random order. There is at most maxNodes nodes // on an edge, we choose an increment step greater than this value // to try to split all edges. int prime = PrimeFinder.nextPrime(maxNodes); int imax = nodes.size(); while (imax % prime == 0) prime = PrimeFinder.nextPrime(prime+1); if (prime >= imax) prime = 1; int index = imax / 2; int skippedNodes = 0; int totNrSwap = 0; for (int i = 0; i < imax; i++) { Vertex2D v = nodes.get(index); VirtualHalfEdge2D vt = v.getSurroundingOTriangle(mesh); int nrSwap = vt.split3(mesh, v, trianglesToCheck, false); if (0 == nrSwap) skippedNodes++; else totNrSwap += nrSwap; index += prime; if (index >= imax) index -= imax; } if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("Mesh now contains "+mesh.getTriangles().size()+" triangles"); if (checked > 0) LOGGER.fine(checked+" edges checked"); if (imax - skippedNodes > 0) LOGGER.fine((imax-skippedNodes)+" nodes added"); if (tooNearNodes > 0) LOGGER.fine(tooNearNodes+" nodes are too near from existing vertices and cannot be inserted"); if (skippedNodes > 0) LOGGER.fine(skippedNodes+" nodes cannot be inserted"); if (totNrSwap > 0) LOGGER.fine(totNrSwap+" edges have been swapped during processing"); if (kdtreeSplit > 0) LOGGER.fine(kdtreeSplit+" quadtree cells split"); } if (skippedNodes == nodes.size()) break; // Copy trianglesToCheck into oldTrianglesToCheck and keep original // order from mesh.getTriangles(). This is to make sure that this // use of trianglesToCheck does not modify result. oldTrianglesToCheck.clear(); for(Triangle t : mesh.getTriangles()) { if (trianglesToCheck.contains(t)) oldTrianglesToCheck.add(t); } } LOGGER.fine("Number of iterations to insert all nodes: "+nrIter); LOGGER.fine("Number of lengths computed: "+nrInterpolations); if (nrFailedInterpolations > 0) LOGGER.info("Number of failed interpolations: "+nrFailedInterpolations); LOGGER.config("Leave compute()"); } private int addCandidatePoints(VirtualHalfEdge2D ot, VirtualHalfEdge2D sym, double edgeLength, ArrayList<Vertex2D> triNodes) { int nrNodes = 0; Vertex2D start = (Vertex2D) ot.origin(); Vertex2D end = (Vertex2D) ot.destination(); double [] lower = new double[2]; double [] upper = new double[2]; int nr; double delta, target; if (edgeLength < ONE_PLUS_SQRT2) { // Add middle point; otherwise point would be too near from end point nr = 1; target = 0.5*edgeLength; delta = Math.min(0.02, 0.9*Math.abs(target - 0.5*Math.sqrt(2))); } else if (edgeLength > 4.0) { // Long edges are discretized, but do not create more than 4 subsegments nr = 3; target = edgeLength / 4.0; delta = 0.1; } else { nr = (int) edgeLength; target = 1.0; delta = 0.05; } // One could take nrDichotomy = 1-log(delta)/log(2), but this // value may not work when surface parameters have a large // gradient, so take a larger value to be safe. int nrDichotomy = 20; int r = nr; Vertex2D last = start; while (r > 0) { System.arraycopy(last.getUV(), 0, lower, 0, 2); System.arraycopy(end.getUV(), 0, upper, 0, 2); Vertex2D np = (Vertex2D) mesh.createVertex(0.5*(lower[0]+upper[0]), 0.5*(lower[1]+upper[1])); int cnt = nrDichotomy; while(cnt >= 0) { cnt--; nrInterpolations++; double l = mesh.interpolatedDistance(last, np); if (Math.abs(l - target) < delta) { last = np; Metric metric = mesh.getMetric(last); // Link to surrounding triangle to speed up // kdTree.getNearestVertex() if (!sym.hasAttributes(AbstractHalfEdge.OUTER) && metric.distance2(last.getUV(), sym.apex().getUV()) < metric.distance2(last.getUV(), ot.apex().getUV())) last.setLink(sym.getTri()); else last.setLink(ot.getTri()); triNodes.add(last); nrNodes++; r--; break; } else if (l > target) { double [] current = np.getUV(); System.arraycopy(current, 0, upper, 0, 2); np.moveTo(0.5*(lower[0] + current[0]), 0.5*(lower[1] + current[1])); } else { double [] current = np.getUV(); System.arraycopy(current, 0, lower, 0, 2); np.moveTo(0.5*(upper[0] + current[0]), 0.5*(upper[1] + current[1])); } } if (cnt < 0) nrFailedInterpolations++; return nrNodes; } return nrNodes; } private boolean checkNearestVertex(Metric metric, double[] uv, Vertex n) { double d1 = metric.distance2(uv, n.getUV()); Vertex debug = kdTree.getNearestVertexDebug(metric, uv); double d2 = metric.distance2(uv, debug.getUV()); assert d1 == d2 : ""+n+" is at a distance "+d1+" but nearest point is "+debug+" at distance "+d2; return true; } }
false
true
public final void compute() { int nrIter = 0; LOGGER.config("Enter compute()"); LOGGER.fine(" Insert inner nodes"); ArrayList<Vertex2D> nodes = new ArrayList<Vertex2D>(); ArrayList<Vertex2D> triNodes = new ArrayList<Vertex2D>(); VirtualHalfEdge2D sym = new VirtualHalfEdge2D(); VirtualHalfEdge2D ot = new VirtualHalfEdge2D(); HashSet<Triangle> trianglesToCheck = new HashSet<Triangle>(mesh.getTriangles().size()); double curMinlen = minlen; // We use a LinkedHashSet instance below to keep triangle order LinkedHashSet<Triangle> oldTrianglesToCheck = new LinkedHashSet<Triangle>(mesh.getTriangles().size()); // We do not want to split boundary edges. for(Triangle gt : mesh.getTriangles()) { if (gt.hasAttributes(AbstractHalfEdge.OUTER)) continue; TriangleVH t = (TriangleVH) gt; ot.bind(t); oldTrianglesToCheck.add(t); for (int i = 0; i < 3; i++) { ot.next(); if (ot.hasAttributes(AbstractHalfEdge.BOUNDARY)) { ot.setAttributes(AbstractHalfEdge.MARKED); sym.bind((TriangleVH) ot.getTri(), ot.getLocalNumber()); sym.sym(); sym.setAttributes(AbstractHalfEdge.MARKED); } else ot.clearAttributes(AbstractHalfEdge.MARKED); } } // We try to insert new nodes by splitting large edges. As edge collapse // is costful, nodes are inserted only if it does not create small edges, // which means that nodes are not deleted. // We iterate over all edges, and put candidate nodes into triNodes. // If an edge has no candidates, either because it is small or because no // nodes can be inserted, it is tagged and will not have to be checked // during next iterations. // For triangle centroids, this is a little bit more difficult, we need to // keep track of triangles which have been modified at previous iteration. while (true) { nrIter++; // Maximal number of nodes which are inserted on an edge int maxNodes = 0; // Number of checked edges int checked = 0; // Number of nodes which are too near from existing vertices int tooNearNodes = 0; // Number of quadtree cells split int kdtreeSplit = 0; nodes.clear(); LOGGER.fine("Check all edges"); for(Triangle gt : mesh.getTriangles()) { if (gt.hasAttributes(AbstractHalfEdge.OUTER)) continue; TriangleVH t = (TriangleVH) gt; ot.bind(t); triNodes.clear(); // Maximal number of nodes which are inserted on edges of this triangle int nrTriNodes = 0; for (int i = 0; i < 3; i++) { ot.next(); if (ot.hasAttributes(AbstractHalfEdge.MARKED)) { // This edge has already been checked and cannot be split continue; } sym.bind((TriangleVH) ot.getTri(), ot.getLocalNumber()); sym.sym(); if (sym.hasAttributes(AbstractHalfEdge.MARKED)) { // This edge has already been checked and cannot be split continue; } double l = mesh.interpolatedDistance((Vertex2D) ot.origin(), (Vertex2D) ot.destination()); if (l < maxlen) { // This edge is smaller than target size and is not split ot.setAttributes(AbstractHalfEdge.MARKED); sym.setAttributes(AbstractHalfEdge.MARKED); continue; } // Tag symmetric edge so that edges are checked only once sym.setAttributes(AbstractHalfEdge.MARKED); int nrNodes = addCandidatePoints(ot, sym, l, triNodes); if (nrNodes > nrTriNodes) { nrTriNodes = nrNodes; } else if (nrNodes == 0) { ot.setAttributes(AbstractHalfEdge.MARKED); } checked++; } if (nrTriNodes > maxNodes) maxNodes = nrTriNodes; if (!triNodes.isEmpty()) { // Process in pseudo-random order int prime = PrimeFinder.nextPrime(nrTriNodes); int imax = triNodes.size(); while (imax % prime == 0) prime = PrimeFinder.nextPrime(prime+1); if (prime >= imax) prime = 1; int index = imax / 2; for (int i = 0; i < imax; i++) { Vertex2D v = triNodes.get(index); Metric metric = mesh.getMetric(v); double[] uv = v.getUV(); Vertex2D n = (Vertex2D) kdTree.getNearestVertex(metric, uv); assert checkNearestVertex(metric, uv, n); if (mesh.interpolatedDistance(v, n) > curMinlen) { kdTree.add(v); nodes.add(v); } else tooNearNodes++; index += prime; if (index >= imax) index -= imax; } } } // Try to insert triangle centroids after other points. // We scan triangles for which centroid have already // proven to be valid, and all triangles which have been // modified by vertex insertion. Vertex2D c = null; trianglesToCheck.clear(); LOGGER.fine("Check triangle centroids for "+oldTrianglesToCheck.size()+" triangles"); for (Triangle gt : oldTrianglesToCheck) { if (gt.hasAttributes(AbstractHalfEdge.OUTER)) continue; TriangleVH t = (TriangleVH) gt; // Check triangle centroid only if at least one edge is large boolean tooSmall = true; ot.bind(t); for (int j = 0; tooSmall && j < 3; j++) { ot.next(); if (ot.hasAttributes(AbstractHalfEdge.MARKED)) { sym.bind((TriangleVH) ot.getTri(), ot.getLocalNumber()); sym.sym(); if (!sym.hasAttributes(AbstractHalfEdge.MARKED)) tooSmall = false; } else tooSmall = false; } if (tooSmall) continue; if (c == null) c = (Vertex2D) mesh.createVertex(0.0, 0.0); mesh.moveVertexToCentroid(c, t); // Link to surrounding triangle to speed up // kdTree.getNearestVertex() and thus // v.getSurroundingOTriangle() below. c.setLink(t); Metric metric = mesh.getMetric(c); Vertex2D n = (Vertex2D) kdTree.getNearestVertex(metric, c.getUV()); assert checkNearestVertex(metric, c.getUV(), n); if (mesh.interpolatedDistance(c, n) > curMinlen) { kdTree.add(c); nodes.add(c); trianglesToCheck.add(t); c = null; } } if (nodes.isEmpty()) { if (checked > 0) { LOGGER.fine("No candidate found after checking "+checked+" edges"); if (tooNearNodes > 0) LOGGER.fine(tooNearNodes+" nodes are too near to be inserted"); if (curMinlen > 0.5*minlen && tooNearNodes > checked / 2) { curMinlen *= 0.9; LOGGER.fine("Lower minlen to "+curMinlen); continue; } } break; } // Reset curMinlen to minlen curMinlen = minlen; for (Vertex2D v : nodes) { // These vertices are not bound to any triangles, so // they must be removed, otherwise getSurroundingOTriangle // may return a null pointer. kdTree.remove(v); } LOGGER.fine("Try to insert "+nodes.size()+" nodes"); // Process in pseudo-random order. There is at most maxNodes nodes // on an edge, we choose an increment step greater than this value // to try to split all edges. int prime = PrimeFinder.nextPrime(maxNodes); int imax = nodes.size(); while (imax % prime == 0) prime = PrimeFinder.nextPrime(prime+1); if (prime >= imax) prime = 1; int index = imax / 2; int skippedNodes = 0; int totNrSwap = 0; for (int i = 0; i < imax; i++) { Vertex2D v = nodes.get(index); VirtualHalfEdge2D vt = v.getSurroundingOTriangle(mesh); int nrSwap = vt.split3(mesh, v, trianglesToCheck, false); if (0 == nrSwap) skippedNodes++; else totNrSwap += nrSwap; index += prime; if (index >= imax) index -= imax; } if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("Mesh now contains "+mesh.getTriangles().size()+" triangles"); if (checked > 0) LOGGER.fine(checked+" edges checked"); if (imax - skippedNodes > 0) LOGGER.fine((imax-skippedNodes)+" nodes added"); if (tooNearNodes > 0) LOGGER.fine(tooNearNodes+" nodes are too near from existing vertices and cannot be inserted"); if (skippedNodes > 0) LOGGER.fine(skippedNodes+" nodes cannot be inserted"); if (totNrSwap > 0) LOGGER.fine(totNrSwap+" edges have been swapped during processing"); if (kdtreeSplit > 0) LOGGER.fine(kdtreeSplit+" quadtree cells split"); } if (skippedNodes == nodes.size()) break; // Copy trianglesToCheck into oldTrianglesToCheck and keep original // order from mesh.getTriangles(). This is to make sure that this // use of trianglesToCheck does not modify result. oldTrianglesToCheck.clear(); for(Triangle t : mesh.getTriangles()) { if (trianglesToCheck.contains(t)) oldTrianglesToCheck.add(t); } } LOGGER.fine("Number of iterations to insert all nodes: "+nrIter); LOGGER.fine("Number of lengths computed: "+nrInterpolations); if (nrFailedInterpolations > 0) LOGGER.info("Number of failed interpolations: "+nrFailedInterpolations); LOGGER.config("Leave compute()"); }
public final void compute() { int nrIter = 0; LOGGER.config("Enter compute()"); LOGGER.fine(" Insert inner nodes"); ArrayList<Vertex2D> nodes = new ArrayList<Vertex2D>(); ArrayList<Vertex2D> triNodes = new ArrayList<Vertex2D>(); VirtualHalfEdge2D sym = new VirtualHalfEdge2D(); VirtualHalfEdge2D ot = new VirtualHalfEdge2D(); HashSet<Triangle> trianglesToCheck = new HashSet<Triangle>(mesh.getTriangles().size()); double curMinlen = minlen; // We use a LinkedHashSet instance below to keep triangle order LinkedHashSet<Triangle> oldTrianglesToCheck = new LinkedHashSet<Triangle>(mesh.getTriangles().size()); // We do not want to split boundary edges. for(Triangle gt : mesh.getTriangles()) { if (gt.hasAttributes(AbstractHalfEdge.OUTER)) continue; TriangleVH t = (TriangleVH) gt; ot.bind(t); oldTrianglesToCheck.add(t); for (int i = 0; i < 3; i++) { ot.next(); if (ot.hasAttributes(AbstractHalfEdge.BOUNDARY)) { ot.setAttributes(AbstractHalfEdge.MARKED); sym.bind((TriangleVH) ot.getTri(), ot.getLocalNumber()); sym.sym(); sym.setAttributes(AbstractHalfEdge.MARKED); } else ot.clearAttributes(AbstractHalfEdge.MARKED); } } // We try to insert new nodes by splitting large edges. As edge collapse // is costful, nodes are inserted only if it does not create small edges, // which means that nodes are not deleted. // We iterate over all edges, and put candidate nodes into triNodes. // If an edge has no candidates, either because it is small or because no // nodes can be inserted, it is tagged and will not have to be checked // during next iterations. // For triangle centroids, this is a little bit more difficult, we need to // keep track of triangles which have been modified at previous iteration. while (true) { nrIter++; // Maximal number of nodes which are inserted on an edge int maxNodes = 0; // Number of checked edges int checked = 0; // Number of nodes which are too near from existing vertices int tooNearNodes = 0; // Number of quadtree cells split int kdtreeSplit = 0; nodes.clear(); LOGGER.fine("Check all edges"); for(Triangle gt : mesh.getTriangles()) { if (gt.hasAttributes(AbstractHalfEdge.OUTER)) continue; TriangleVH t = (TriangleVH) gt; ot.bind(t); triNodes.clear(); // Maximal number of nodes which are inserted on edges of this triangle int nrTriNodes = 0; for (int i = 0; i < 3; i++) { ot.next(); if (ot.hasAttributes(AbstractHalfEdge.MARKED)) { // This edge has already been checked and cannot be split continue; } // Tag symmetric edge so that edges are checked only once sym.bind((TriangleVH) ot.getTri(), ot.getLocalNumber()); sym.sym(); sym.setAttributes(AbstractHalfEdge.MARKED); double l = mesh.interpolatedDistance((Vertex2D) ot.origin(), (Vertex2D) ot.destination()); if (l < maxlen) { // This edge is smaller than target size and is not split ot.setAttributes(AbstractHalfEdge.MARKED); continue; } int nrNodes = addCandidatePoints(ot, sym, l, triNodes); if (nrNodes > nrTriNodes) { nrTriNodes = nrNodes; } else if (nrNodes == 0) { ot.setAttributes(AbstractHalfEdge.MARKED); } checked++; } if (nrTriNodes > maxNodes) maxNodes = nrTriNodes; if (!triNodes.isEmpty()) { // Process in pseudo-random order int prime = PrimeFinder.nextPrime(nrTriNodes); int imax = triNodes.size(); while (imax % prime == 0) prime = PrimeFinder.nextPrime(prime+1); if (prime >= imax) prime = 1; int index = imax / 2; for (int i = 0; i < imax; i++) { Vertex2D v = triNodes.get(index); Metric metric = mesh.getMetric(v); double[] uv = v.getUV(); Vertex2D n = (Vertex2D) kdTree.getNearestVertex(metric, uv); assert checkNearestVertex(metric, uv, n); if (mesh.interpolatedDistance(v, n) > curMinlen) { kdTree.add(v); nodes.add(v); } else tooNearNodes++; index += prime; if (index >= imax) index -= imax; } } } // Try to insert triangle centroids after other points. // We scan triangles for which centroid have already // proven to be valid, and all triangles which have been // modified by vertex insertion. Vertex2D c = null; trianglesToCheck.clear(); LOGGER.fine("Check triangle centroids for "+oldTrianglesToCheck.size()+" triangles"); for (Triangle gt : oldTrianglesToCheck) { if (gt.hasAttributes(AbstractHalfEdge.OUTER)) continue; TriangleVH t = (TriangleVH) gt; // Check triangle centroid only if at least one edge is large boolean tooSmall = true; ot.bind(t); for (int j = 0; tooSmall && j < 3; j++) { ot.next(); if (ot.hasAttributes(AbstractHalfEdge.MARKED)) { sym.bind((TriangleVH) ot.getTri(), ot.getLocalNumber()); sym.sym(); if (!sym.hasAttributes(AbstractHalfEdge.MARKED)) tooSmall = false; } else tooSmall = false; } if (tooSmall) continue; if (c == null) c = (Vertex2D) mesh.createVertex(0.0, 0.0); mesh.moveVertexToCentroid(c, t); // Link to surrounding triangle to speed up // kdTree.getNearestVertex() and thus // v.getSurroundingOTriangle() below. c.setLink(t); Metric metric = mesh.getMetric(c); Vertex2D n = (Vertex2D) kdTree.getNearestVertex(metric, c.getUV()); assert checkNearestVertex(metric, c.getUV(), n); if (mesh.interpolatedDistance(c, n) > curMinlen) { kdTree.add(c); nodes.add(c); trianglesToCheck.add(t); c = null; } } if (nodes.isEmpty()) { if (checked > 0) { LOGGER.fine("No candidate found after checking "+checked+" edges"); if (tooNearNodes > 0) LOGGER.fine(tooNearNodes+" nodes are too near to be inserted"); if (curMinlen > 0.5*minlen && tooNearNodes > checked / 2) { curMinlen *= 0.9; LOGGER.fine("Lower minlen to "+curMinlen); continue; } } break; } // Reset curMinlen to minlen curMinlen = minlen; for (Vertex2D v : nodes) { // These vertices are not bound to any triangles, so // they must be removed, otherwise getSurroundingOTriangle // may return a null pointer. kdTree.remove(v); } LOGGER.fine("Try to insert "+nodes.size()+" nodes"); // Process in pseudo-random order. There is at most maxNodes nodes // on an edge, we choose an increment step greater than this value // to try to split all edges. int prime = PrimeFinder.nextPrime(maxNodes); int imax = nodes.size(); while (imax % prime == 0) prime = PrimeFinder.nextPrime(prime+1); if (prime >= imax) prime = 1; int index = imax / 2; int skippedNodes = 0; int totNrSwap = 0; for (int i = 0; i < imax; i++) { Vertex2D v = nodes.get(index); VirtualHalfEdge2D vt = v.getSurroundingOTriangle(mesh); int nrSwap = vt.split3(mesh, v, trianglesToCheck, false); if (0 == nrSwap) skippedNodes++; else totNrSwap += nrSwap; index += prime; if (index >= imax) index -= imax; } if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("Mesh now contains "+mesh.getTriangles().size()+" triangles"); if (checked > 0) LOGGER.fine(checked+" edges checked"); if (imax - skippedNodes > 0) LOGGER.fine((imax-skippedNodes)+" nodes added"); if (tooNearNodes > 0) LOGGER.fine(tooNearNodes+" nodes are too near from existing vertices and cannot be inserted"); if (skippedNodes > 0) LOGGER.fine(skippedNodes+" nodes cannot be inserted"); if (totNrSwap > 0) LOGGER.fine(totNrSwap+" edges have been swapped during processing"); if (kdtreeSplit > 0) LOGGER.fine(kdtreeSplit+" quadtree cells split"); } if (skippedNodes == nodes.size()) break; // Copy trianglesToCheck into oldTrianglesToCheck and keep original // order from mesh.getTriangles(). This is to make sure that this // use of trianglesToCheck does not modify result. oldTrianglesToCheck.clear(); for(Triangle t : mesh.getTriangles()) { if (trianglesToCheck.contains(t)) oldTrianglesToCheck.add(t); } } LOGGER.fine("Number of iterations to insert all nodes: "+nrIter); LOGGER.fine("Number of lengths computed: "+nrInterpolations); if (nrFailedInterpolations > 0) LOGGER.info("Number of failed interpolations: "+nrFailedInterpolations); LOGGER.config("Leave compute()"); }
diff --git a/src/tesseract/forces/AirDrag.java b/src/tesseract/forces/AirDrag.java index b6f0dbd..2f652be 100644 --- a/src/tesseract/forces/AirDrag.java +++ b/src/tesseract/forces/AirDrag.java @@ -1,200 +1,200 @@ package tesseract.forces; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import javax.media.j3d.Transform3D; import javax.vecmath.Quat4f; import javax.vecmath.Vector2f; import javax.vecmath.Vector3f; import tesseract.objects.PhysicalObject; public class AirDrag extends Force { private static final float COEFFICIENT = 20f; @Override protected Vector3f calculateForce(PhysicalObject obj) { if (obj.isNodeNull() || obj.getVelocity().length() == 0) { return new Vector3f(); } Vector3f v = new Vector3f(obj.getVelocity()); Vector3f p = new Vector3f(obj.getPosition()); p.negate(); Vector3f c = new Vector3f(); c.sub(new Vector3f(0, 1, 0), v); Quat4f r = new Quat4f(c.x, c.y, c.z, 0); r.normalize(); Vector3f com = new Vector3f(-obj.getCenterOfMass().x, -obj.getCenterOfMass().y, -obj.getCenterOfMass().z); com.negate(); Transform3D tmp = new Transform3D(); tmp.setTranslation(com); Transform3D tmp2 = new Transform3D(); tmp2.setRotation(r); com.negate(); com.add(p); tmp2.setTranslation(com); tmp2.mul(tmp); ArrayList<Vector3f> vertices = obj.getVertices(); ArrayList<Vector2f> points = new ArrayList<Vector2f>(); for (Vector3f point : vertices) { tmp2.transform(point); Vector2f newPoint = new Vector2f(point.x, point.z); // Place min y at front of arraylist if it's the minimum if (points.size() == 0) { points.add(newPoint); } else if (newPoint.y < points.get(0).y || (newPoint.y == points.get(0).y && newPoint.x < points.get(0).x)) { Vector2f oldPoint = points.get(0); points.set(0, newPoint); points.add(oldPoint); } else { points.add(newPoint); } } List<Vector2f> hull = convexHull(points); float surfaceArea = areaOfHull(hull); float force = 0.5f * v.lengthSquared() * COEFFICIENT * surfaceArea; v.normalize(); v.scale(-force); - return new Vector3f(); + return v; } /** * * @param hull vector list. * @return area */ private float areaOfHull(final List<Vector2f> hull) { float area = 0; Vector2f p = hull.get(0); for (int i = 2; i < hull.size(); i++) { // Area of triangle p0 - p(i-1) - p(i) Vector2f ab = new Vector2f(); Vector2f ac = new Vector2f(); ab.sub(hull.get(i - 1), p); ac.sub(hull.get(i), p); area += 0.5f * (ab.x * ac.y - ac.x * ab.y); } return area; } /** * Graham's convex hull algorithm from pseudocode on wikipedia. * @param points point list. * @return point list. */ private List<Vector2f> convexHull(final ArrayList<Vector2f> points) { Collections.sort(points, new Vector2fAngleCompare(points.get(0))); points.set(0, points.get(points.size() - 1)); int m = 2; for (int i = m + 1; i < points.size(); i++) { try { while (i < points.size() - 1 && ccw(points.get(m - 1), points.get(m), points.get(i)) <= 0) { if (m == 2) { final Vector2f vec = points.get(m); points.set(m, points.get(i)); points.set(i, vec); i++; } else { m--; } } } catch (Exception e) { System.out.println(e); } m++; final Vector2f vec = points.get(m); points.set(m, points.get(i)); points.set(i, vec); } return points.subList(0, m + 1); } /** * * @param v1 vector. * @param v2 vector. * @param v3 vector. * @return result */ private float ccw(final Vector2f v1, final Vector2f v2, final Vector2f v3) { return (v2.x - v1.x) * (v3.y - v1.y) - (v2.y - v1.y) * (v3.x - v1.x); } /** * * * */ private class Vector2fAngleCompare implements Comparator<Vector2f> { /** * Base vector. */ Vector2f base; /** * constructor. * @param theBase the base. */ public Vector2fAngleCompare(final Vector2f theBase) { base = theBase; } /** * @param o1 vector to compare * @param o2 vector2 to compare * @return comparison */ public int compare(final Vector2f o1, final Vector2f o2) { return (int) Math.signum(vecAngle(o1) - vecAngle(o2)); } /** * * @param vector to look at. * @return result */ private float vecAngle(final Vector2f vector) { final Vector2f v = new Vector2f(); v.sub(vector, base); return v.y / (v.x * v.x + v.y * v.y); } } }
true
true
protected Vector3f calculateForce(PhysicalObject obj) { if (obj.isNodeNull() || obj.getVelocity().length() == 0) { return new Vector3f(); } Vector3f v = new Vector3f(obj.getVelocity()); Vector3f p = new Vector3f(obj.getPosition()); p.negate(); Vector3f c = new Vector3f(); c.sub(new Vector3f(0, 1, 0), v); Quat4f r = new Quat4f(c.x, c.y, c.z, 0); r.normalize(); Vector3f com = new Vector3f(-obj.getCenterOfMass().x, -obj.getCenterOfMass().y, -obj.getCenterOfMass().z); com.negate(); Transform3D tmp = new Transform3D(); tmp.setTranslation(com); Transform3D tmp2 = new Transform3D(); tmp2.setRotation(r); com.negate(); com.add(p); tmp2.setTranslation(com); tmp2.mul(tmp); ArrayList<Vector3f> vertices = obj.getVertices(); ArrayList<Vector2f> points = new ArrayList<Vector2f>(); for (Vector3f point : vertices) { tmp2.transform(point); Vector2f newPoint = new Vector2f(point.x, point.z); // Place min y at front of arraylist if it's the minimum if (points.size() == 0) { points.add(newPoint); } else if (newPoint.y < points.get(0).y || (newPoint.y == points.get(0).y && newPoint.x < points.get(0).x)) { Vector2f oldPoint = points.get(0); points.set(0, newPoint); points.add(oldPoint); } else { points.add(newPoint); } } List<Vector2f> hull = convexHull(points); float surfaceArea = areaOfHull(hull); float force = 0.5f * v.lengthSquared() * COEFFICIENT * surfaceArea; v.normalize(); v.scale(-force); return new Vector3f(); }
protected Vector3f calculateForce(PhysicalObject obj) { if (obj.isNodeNull() || obj.getVelocity().length() == 0) { return new Vector3f(); } Vector3f v = new Vector3f(obj.getVelocity()); Vector3f p = new Vector3f(obj.getPosition()); p.negate(); Vector3f c = new Vector3f(); c.sub(new Vector3f(0, 1, 0), v); Quat4f r = new Quat4f(c.x, c.y, c.z, 0); r.normalize(); Vector3f com = new Vector3f(-obj.getCenterOfMass().x, -obj.getCenterOfMass().y, -obj.getCenterOfMass().z); com.negate(); Transform3D tmp = new Transform3D(); tmp.setTranslation(com); Transform3D tmp2 = new Transform3D(); tmp2.setRotation(r); com.negate(); com.add(p); tmp2.setTranslation(com); tmp2.mul(tmp); ArrayList<Vector3f> vertices = obj.getVertices(); ArrayList<Vector2f> points = new ArrayList<Vector2f>(); for (Vector3f point : vertices) { tmp2.transform(point); Vector2f newPoint = new Vector2f(point.x, point.z); // Place min y at front of arraylist if it's the minimum if (points.size() == 0) { points.add(newPoint); } else if (newPoint.y < points.get(0).y || (newPoint.y == points.get(0).y && newPoint.x < points.get(0).x)) { Vector2f oldPoint = points.get(0); points.set(0, newPoint); points.add(oldPoint); } else { points.add(newPoint); } } List<Vector2f> hull = convexHull(points); float surfaceArea = areaOfHull(hull); float force = 0.5f * v.lengthSquared() * COEFFICIENT * surfaceArea; v.normalize(); v.scale(-force); return v; }
diff --git a/src/Window.java b/src/Window.java index 9a2668b..bfb2141 100644 --- a/src/Window.java +++ b/src/Window.java @@ -1,84 +1,80 @@ import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextField; import java.util.prefs.Preferences; /** * Main class * @author bencall * */ // public class Window implements ActionListener{ private boolean on = false; private JButton bouton; private JTextField nameField; private LaunchThread t; private Preferences prefs; /** * @param args */ public static void main(String[] args) { new Rplay(); } public Window(){ prefs = Preferences.userRoot().node(this.getClass().getName()); JFrame window = new JFrame(); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // window.setSize(380, 100); window.setTitle("RPlay"); java.awt.Container contenu = window.getContentPane(); contenu.setLayout(new FlowLayout()); String apname = prefs.get("apname", ""); // Get the default AP name nameField = new JTextField(apname,15); bouton = new JButton("Start Airport Express"); bouton.addActionListener(this); contenu.add(new JLabel("AP Name: ")); contenu.add(nameField); contenu.add(bouton); window.pack(); window.setVisible(true); - // If was previously Started, start it now - if (prefs.getBoolean("launched", false)) { - // TODO: Refactor so no duplication of code below - on = true; - t = new LaunchThread(nameField.getText()); - t.start(); - bouton.setText("Stop Airport Express"); + // If was previously started, start it now + if (prefs.getBoolean("launched", true)) { + bouton.doClick(); } } @Override public void actionPerformed(ActionEvent arg0) { if(!on){ on = true; t = new LaunchThread(nameField.getText()); t.start(); bouton.setText("Stop Airport Express"); prefs.put("apname", nameField.getText()); prefs.putBoolean("launched", true); // Used on next launch } else { on = false; t.stopThread(); bouton.setText("Start Airport Express"); prefs.putBoolean("launched", false); // Used on next launch } } }
true
true
public Window(){ prefs = Preferences.userRoot().node(this.getClass().getName()); JFrame window = new JFrame(); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // window.setSize(380, 100); window.setTitle("RPlay"); java.awt.Container contenu = window.getContentPane(); contenu.setLayout(new FlowLayout()); String apname = prefs.get("apname", ""); // Get the default AP name nameField = new JTextField(apname,15); bouton = new JButton("Start Airport Express"); bouton.addActionListener(this); contenu.add(new JLabel("AP Name: ")); contenu.add(nameField); contenu.add(bouton); window.pack(); window.setVisible(true); // If was previously Started, start it now if (prefs.getBoolean("launched", false)) { // TODO: Refactor so no duplication of code below on = true; t = new LaunchThread(nameField.getText()); t.start(); bouton.setText("Stop Airport Express"); } }
public Window(){ prefs = Preferences.userRoot().node(this.getClass().getName()); JFrame window = new JFrame(); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // window.setSize(380, 100); window.setTitle("RPlay"); java.awt.Container contenu = window.getContentPane(); contenu.setLayout(new FlowLayout()); String apname = prefs.get("apname", ""); // Get the default AP name nameField = new JTextField(apname,15); bouton = new JButton("Start Airport Express"); bouton.addActionListener(this); contenu.add(new JLabel("AP Name: ")); contenu.add(nameField); contenu.add(bouton); window.pack(); window.setVisible(true); // If was previously started, start it now if (prefs.getBoolean("launched", true)) { bouton.doClick(); } }
diff --git a/src/main/java/net/floodlightcontroller/core/internal/Controller.java b/src/main/java/net/floodlightcontroller/core/internal/Controller.java index e5d7ad2..3890de0 100644 --- a/src/main/java/net/floodlightcontroller/core/internal/Controller.java +++ b/src/main/java/net/floodlightcontroller/core/internal/Controller.java @@ -1,2053 +1,2053 @@ /** * Copyright 2011, Big Switch Networks, Inc. * Originally created by David Erickson, Stanford University * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. **/ package net.floodlightcontroller.core.internal; import java.io.FileInputStream; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.util.ArrayList; import java.nio.channels.ClosedChannelException; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; import java.util.Stack; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import net.floodlightcontroller.core.FloodlightContext; import net.floodlightcontroller.core.IFloodlightProviderService; import net.floodlightcontroller.core.IHAListener; import net.floodlightcontroller.core.IInfoProvider; import net.floodlightcontroller.core.IOFMessageListener; import net.floodlightcontroller.core.IListener.Command; import net.floodlightcontroller.core.IOFSwitch; import net.floodlightcontroller.core.IOFSwitchFilter; import net.floodlightcontroller.core.IOFSwitchListener; import net.floodlightcontroller.core.internal.OFChannelState.HandshakeState; import net.floodlightcontroller.core.util.ListenerDispatcher; import net.floodlightcontroller.core.web.CoreWebRoutable; import net.floodlightcontroller.counter.ICounterStoreService; import net.floodlightcontroller.packet.Ethernet; import net.floodlightcontroller.perfmon.IPktInProcessingTimeService; import net.floodlightcontroller.restserver.IRestApiService; import net.floodlightcontroller.storage.IResultSet; import net.floodlightcontroller.storage.IStorageSourceListener; import net.floodlightcontroller.storage.IStorageSourceService; import net.floodlightcontroller.storage.OperatorPredicate; import net.floodlightcontroller.storage.StorageException; import net.floodlightcontroller.threadpool.IThreadPoolService; import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.ChannelUpstreamHandler; import org.jboss.netty.channel.Channels; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.group.ChannelGroup; import org.jboss.netty.channel.group.DefaultChannelGroup; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; import org.jboss.netty.handler.timeout.IdleStateAwareChannelUpstreamHandler; import org.jboss.netty.handler.timeout.IdleStateEvent; import org.jboss.netty.handler.timeout.ReadTimeoutException; import org.openflow.protocol.OFEchoReply; import org.openflow.protocol.OFError; import org.openflow.protocol.OFError.OFBadActionCode; import org.openflow.protocol.OFError.OFBadRequestCode; import org.openflow.protocol.OFError.OFErrorType; import org.openflow.protocol.OFError.OFFlowModFailedCode; import org.openflow.protocol.OFError.OFHelloFailedCode; import org.openflow.protocol.OFError.OFPortModFailedCode; import org.openflow.protocol.OFError.OFQueueOpFailedCode; import org.openflow.protocol.OFFeaturesReply; import org.openflow.protocol.OFGetConfigReply; import org.openflow.protocol.OFMessage; import org.openflow.protocol.OFPacketIn; import org.openflow.protocol.OFPhysicalPort; import org.openflow.protocol.OFPortStatus; import org.openflow.protocol.OFPortStatus.OFPortReason; import org.openflow.protocol.OFSetConfig; import org.openflow.protocol.OFStatisticsRequest; import org.openflow.protocol.OFSwitchConfig; import org.openflow.protocol.OFType; import org.openflow.protocol.OFVendor; import org.openflow.protocol.factory.BasicFactory; import org.openflow.protocol.factory.MessageParseException; import org.openflow.protocol.statistics.OFDescriptionStatistics; import org.openflow.protocol.statistics.OFStatistics; import org.openflow.protocol.statistics.OFStatisticsType; import org.openflow.protocol.vendor.OFBasicVendorDataType; import org.openflow.protocol.vendor.OFBasicVendorId; import org.openflow.protocol.vendor.OFVendorId; import org.openflow.util.HexString; import org.openflow.util.U16; import org.openflow.util.U32; import org.openflow.vendor.nicira.OFNiciraVendorData; import org.openflow.vendor.nicira.OFRoleReplyVendorData; import org.openflow.vendor.nicira.OFRoleRequestVendorData; import org.openflow.vendor.nicira.OFRoleVendorData; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The main controller class. Handles all setup and network listeners */ public class Controller implements IFloodlightProviderService, IStorageSourceListener { protected static Logger log = LoggerFactory.getLogger(Controller.class); protected BasicFactory factory; protected ConcurrentMap<OFType, ListenerDispatcher<OFType,IOFMessageListener>> messageListeners; // The activeSwitches map contains only those switches that are actively // being controlled by us -- it doesn't contain switches that are // in the slave role protected ConcurrentHashMap<Long, IOFSwitch> activeSwitches; // connectedSwitches contains all connected switches, including ones where // we're a slave controller. We need to keep track of them so that we can // send role request messages to switches when our role changes to master // We add a switch to this set after it successfully completes the // handshake. Access to this Set needs to be synchronized with roleChanger protected HashSet<OFSwitchImpl> connectedSwitches; // The controllerNodeIPsCache maps Controller IDs to their IP address. // It's only used by handleControllerNodeIPsChanged protected HashMap<String, String> controllerNodeIPsCache; protected Set<IOFSwitchListener> switchListeners; protected Set<IHAListener> haListeners; protected Map<String, List<IInfoProvider>> providerMap; protected BlockingQueue<IUpdate> updates; // Module dependencies protected IRestApiService restApi; protected ICounterStoreService counterStore = null; protected IStorageSourceService storageSource; protected IPktInProcessingTimeService pktinProcTime; protected IThreadPoolService threadPool; // Configuration options protected int openFlowPort = 6633; protected int workerThreads = 0; // The id for this controller node. Should be unique for each controller // node in a controller cluster. protected String controllerId = "localhost"; // The current role of the controller. // If the controller isn't configured to support roles, then this is null. protected Role role; // A helper that handles sending and timeout handling for role requests protected RoleChanger roleChanger; // Start time of the controller protected long systemStartTime; // Storage table names protected static final String CONTROLLER_TABLE_NAME = "controller_controller"; protected static final String CONTROLLER_ID = "id"; protected static final String SWITCH_TABLE_NAME = "controller_switch"; protected static final String SWITCH_DATAPATH_ID = "dpid"; protected static final String SWITCH_SOCKET_ADDRESS = "socket_address"; protected static final String SWITCH_IP = "ip"; protected static final String SWITCH_CONTROLLER_ID = "controller_id"; protected static final String SWITCH_ACTIVE = "active"; protected static final String SWITCH_CONNECTED_SINCE = "connected_since"; protected static final String SWITCH_CAPABILITIES = "capabilities"; protected static final String SWITCH_BUFFERS = "buffers"; protected static final String SWITCH_TABLES = "tables"; protected static final String SWITCH_ACTIONS = "actions"; protected static final String SWITCH_CONFIG_TABLE_NAME = "controller_switchconfig"; protected static final String SWITCH_CONFIG_CORE_SWITCH = "core_switch"; protected static final String PORT_TABLE_NAME = "controller_port"; protected static final String PORT_ID = "id"; protected static final String PORT_SWITCH = "switch_id"; protected static final String PORT_NUMBER = "number"; protected static final String PORT_HARDWARE_ADDRESS = "hardware_address"; protected static final String PORT_NAME = "name"; protected static final String PORT_CONFIG = "config"; protected static final String PORT_STATE = "state"; protected static final String PORT_CURRENT_FEATURES = "current_features"; protected static final String PORT_ADVERTISED_FEATURES = "advertised_features"; protected static final String PORT_SUPPORTED_FEATURES = "supported_features"; protected static final String PORT_PEER_FEATURES = "peer_features"; protected static final String CONTROLLER_INTERFACE_TABLE_NAME = "controller_controllerinterface"; protected static final String CONTROLLER_INTERFACE_ID = "id"; protected static final String CONTROLLER_INTERFACE_CONTROLLER_ID = "controller_id"; protected static final String CONTROLLER_INTERFACE_TYPE = "type"; protected static final String CONTROLLER_INTERFACE_NUMBER = "number"; protected static final String CONTROLLER_INTERFACE_DISCOVERED_IP = "discovered_ip"; // Perf. related configuration protected static final int SEND_BUFFER_SIZE = 4 * 1024 * 1024; protected static final int BATCH_MAX_SIZE = 100; protected static final boolean ALWAYS_DECODE_ETH = true; /** * Updates handled by the main loop */ protected interface IUpdate { /** * Calls the appropriate listeners */ public void dispatch(); } /** * Update message indicating a switch was added or removed */ protected class SwitchUpdate implements IUpdate { public IOFSwitch sw; public boolean added; public SwitchUpdate(IOFSwitch sw, boolean added) { this.sw = sw; this.added = added; } public void dispatch() { if (log.isTraceEnabled()) { log.trace("Dispatching switch update {} {}", sw, added); } if (switchListeners != null) { for (IOFSwitchListener listener : switchListeners) { if (added) listener.addedSwitch(sw); else listener.removedSwitch(sw); } } } } /** * Update message indicating controller's role has changed */ protected class HARoleUpdate implements IUpdate { public Role oldRole; public Role newRole; public HARoleUpdate(Role newRole, Role oldRole) { this.oldRole = oldRole; this.newRole = newRole; } public void dispatch() { // Make sure that old and new roles are different. if (oldRole == newRole) { if (log.isTraceEnabled()) { log.trace("HA role update ignored as the old and " + "new roles are the same. newRole = {}" + "oldRole = {}", newRole, oldRole); } return; } if (log.isTraceEnabled()) { log.trace("Dispatching HA Role update newRole = {}, oldRole = {}", newRole, oldRole); } if (haListeners != null) { for (IHAListener listener : haListeners) { listener.roleChanged(oldRole, newRole); } } } } /** * Update message indicating * IPs of controllers in controller cluster have changed. */ protected class HAControllerNodeIPUpdate implements IUpdate { public Map<String,String> curControllerNodeIPs; public Map<String,String> addedControllerNodeIPs; public Map<String,String> removedControllerNodeIPs; public HAControllerNodeIPUpdate( HashMap<String,String> curControllerNodeIPs, HashMap<String,String> addedControllerNodeIPs, HashMap<String,String> removedControllerNodeIPs) { this.curControllerNodeIPs = curControllerNodeIPs; this.addedControllerNodeIPs = addedControllerNodeIPs; this.removedControllerNodeIPs = removedControllerNodeIPs; } public void dispatch() { if (log.isTraceEnabled()) { log.trace("Dispatching HA Controller Node IP update " + "curIPs = {}, addedIPs = {}, removedIPs = {}", new Object[] { curControllerNodeIPs, addedControllerNodeIPs, removedControllerNodeIPs } ); } if (haListeners != null) { for (IHAListener listener: haListeners) { listener.controllerNodeIPsChanged(curControllerNodeIPs, addedControllerNodeIPs, removedControllerNodeIPs); } } } } // *************** // Getters/Setters // *************** public void setStorageSourceService(IStorageSourceService storageSource) { this.storageSource = storageSource; } public void setCounterStore(ICounterStoreService counterStore) { this.counterStore = counterStore; } public void setPktInProcessingService(IPktInProcessingTimeService pits) { this.pktinProcTime = pits; } public void setRestApiService(IRestApiService restApi) { this.restApi = restApi; } public void setThreadPoolService(IThreadPoolService tp) { this.threadPool = tp; } @Override public Role getRole() { synchronized(roleChanger) { return role; } } @Override public void setRole(Role role) { if (role == null) throw new NullPointerException("Role can not be null."); if (role == Role.MASTER && this.role == Role.SLAVE) { // Reset db state to Inactive for all switches. updateAllInactiveSwitchInfo(); } // Need to synchronize to ensure a reliable ordering on role request // messages send and to ensure the list of connected switches is stable // RoleChanger will handle the actual sending of the message and // timeout handling // @see RoleChanger synchronized(roleChanger) { if (role.equals(this.role)) { log.debug("Ignoring role change: role is already {}", role); return; } Role oldRole = this.role; this.role = role; log.debug("Submitting role change request to role {}", role); roleChanger.submitRequest(connectedSwitches, role); // Enqueue an update for our listeners. try { this.updates.put(new HARoleUpdate(role, oldRole)); } catch (InterruptedException e) { log.error("Failure adding update to queue", e); } } } // ********************** // ChannelUpstreamHandler // ********************** /** * Return a new channel handler for processing a switch connections * @param state The channel state object for the connection * @return the new channel handler */ protected ChannelUpstreamHandler getChannelHandler(OFChannelState state) { return new OFChannelHandler(state); } /** * Channel handler deals with the switch connection and dispatches * switch messages to the appropriate locations. * @author readams */ protected class OFChannelHandler extends IdleStateAwareChannelUpstreamHandler { protected OFSwitchImpl sw; protected OFChannelState state; public OFChannelHandler(OFChannelState state) { this.state = state; } @Override public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { log.info("New switch connection from {}", e.getChannel().getRemoteAddress()); sw = new OFSwitchImpl(); sw.setChannel(e.getChannel()); sw.setFloodlightProvider(Controller.this); sw.setThreadPoolService(threadPool); List<OFMessage> msglist = new ArrayList<OFMessage>(1); msglist.add(factory.getMessage(OFType.HELLO)); e.getChannel().write(msglist); } @Override public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { if (sw != null && state.hsState == HandshakeState.READY) { if (activeSwitches.containsKey(sw.getId())) { // It's safe to call removeSwitch even though the map might // not contain this particular switch but another with the // same DPID removeSwitch(sw); } synchronized(roleChanger) { connectedSwitches.remove(sw); } sw.setConnected(false); } log.info("Disconnected switch {}", sw); } @Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { if (e.getCause() instanceof ReadTimeoutException) { // switch timeout log.error("Disconnecting switch {} due to read timeout", sw); ctx.getChannel().close(); } else if (e.getCause() instanceof HandshakeTimeoutException) { log.error("Disconnecting switch {}: failed to complete handshake", sw); ctx.getChannel().close(); } else if (e.getCause() instanceof ClosedChannelException) { //log.warn("Channel for sw {} already closed", sw); } else if (e.getCause() instanceof IOException) { log.error("Disconnecting switch {} due to IO Error: {}", sw, e.getCause().getMessage()); ctx.getChannel().close(); } else if (e.getCause() instanceof SwitchStateException) { log.error("Disconnecting switch {} due to switch state error: {}", sw, e.getCause().getMessage()); ctx.getChannel().close(); } else if (e.getCause() instanceof MessageParseException) { log.error("Disconnecting switch " + sw + " due to message parse failure", e.getCause()); ctx.getChannel().close(); } else if (e.getCause() instanceof StorageException) { log.error("Terminating controller due to storage exception", e.getCause()); terminate(); } else if (e.getCause() instanceof RejectedExecutionException) { log.warn("Could not process message: queue full"); } else { log.error("Error while processing message from switch " + sw, e.getCause()); ctx.getChannel().close(); } } @Override public void channelIdle(ChannelHandlerContext ctx, IdleStateEvent e) throws Exception { List<OFMessage> msglist = new ArrayList<OFMessage>(1); msglist.add(factory.getMessage(OFType.ECHO_REQUEST)); e.getChannel().write(msglist); } @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { if (e.getMessage() instanceof List) { @SuppressWarnings("unchecked") List<OFMessage> msglist = (List<OFMessage>)e.getMessage(); for (OFMessage ofm : msglist) { try { processOFMessage(ofm); } catch (Exception ex) { // We are the last handler in the stream, so run the // exception through the channel again by passing in // ctx.getChannel(). Channels.fireExceptionCaught(ctx.getChannel(), ex); } } // Flush all flow-mods/packet-out generated from this "train" OFSwitchImpl.flush_all(); } } /** * Process the request for the switch description */ void processSwitchDescReply() { try { // Read description, if it has been updated @SuppressWarnings("unchecked") Future<List<OFStatistics>> desc_future = (Future<List<OFStatistics>>)sw. getAttribute(IOFSwitch.SWITCH_DESCRIPTION_FUTURE); List<OFStatistics> values = desc_future.get(0, TimeUnit.MILLISECONDS); if (values != null) { OFDescriptionStatistics description = new OFDescriptionStatistics(); ChannelBuffer data = ChannelBuffers.buffer(description.getLength()); for (OFStatistics f : values) { f.writeTo(data); description.readFrom(data); break; // SHOULD be a list of length 1 } sw.setAttribute(IOFSwitch.SWITCH_DESCRIPTION_DATA, description); sw.setSwitchProperties(description); data = null; // At this time, also set other switch properties from storage boolean is_core_switch = false; IResultSet resultSet = null; try { String swid = sw.getStringId(); resultSet = storageSource.getRow(SWITCH_CONFIG_TABLE_NAME, swid); for (Iterator<IResultSet> it = resultSet.iterator(); it.hasNext();) { // In case of multiple rows, use the status // in last row? Map<String, Object> row = it.next().getRow(); if (row.containsKey(SWITCH_CONFIG_CORE_SWITCH)) { if (log.isDebugEnabled()) { log.debug("Reading SWITCH_IS_CORE_SWITCH " + "config for switch={}, is-core={}", sw, row.get(SWITCH_CONFIG_CORE_SWITCH)); } String ics = (String)row.get(SWITCH_CONFIG_CORE_SWITCH); is_core_switch = ics.equals("true"); } } } finally { if (resultSet != null) resultSet.close(); } if (is_core_switch) { sw.setAttribute(IOFSwitch.SWITCH_IS_CORE_SWITCH, new Boolean(true)); } } sw.removeAttribute(IOFSwitch.SWITCH_DESCRIPTION_FUTURE); state.hasDescription = true; checkSwitchReady(); } catch (InterruptedException ex) { // Ignore } catch (TimeoutException ex) { // Ignore } catch (Exception ex) { log.error("Exception in reading description " + " during handshake - {}", ex); } } /** * Send initial switch setup information that we need before adding * the switch * @throws IOException */ void sendHelloConfiguration() throws IOException { // Send initial Features Request sw.write(factory.getMessage(OFType.FEATURES_REQUEST), null); } /** * Send the configuration requests we can only do after we have * the features reply * @throws IOException */ void sendFeatureReplyConfiguration() throws IOException { // Ensure we receive the full packet via PacketIn OFSetConfig config = (OFSetConfig) factory .getMessage(OFType.SET_CONFIG); config.setMissSendLength((short) 0xffff) .setLengthU(OFSwitchConfig.MINIMUM_LENGTH); sw.write(config, null); sw.write(factory.getMessage(OFType.GET_CONFIG_REQUEST), null); // Get Description to set switch-specific flags OFStatisticsRequest req = new OFStatisticsRequest(); req.setStatisticType(OFStatisticsType.DESC); req.setLengthU(req.getLengthU()); Future<List<OFStatistics>> dfuture = sw.getStatistics(req); sw.setAttribute(IOFSwitch.SWITCH_DESCRIPTION_FUTURE, dfuture); } protected void checkSwitchReady() { if (state.hsState == HandshakeState.FEATURES_REPLY && state.hasDescription && state.hasGetConfigReply) { state.hsState = HandshakeState.READY; synchronized(roleChanger) { // We need to keep track of all of the switches that are connected // to the controller, in any role, so that we can later send the // role request messages when the controller role changes. // We need to be synchronized while doing this: we must not // send a another role request to the connectedSwitches until // we were able to add this new switch to connectedSwitches // *and* send the current role to the new switch. connectedSwitches.add(sw); if (role != null) { // Send a role request if role support is enabled for the controller // This is a probe that we'll use to determine if the switch // actually supports the role request message. If it does we'll // get back a role reply message. If it doesn't we'll get back an // OFError message. // If role is MASTER we will promote switch to active // list when we receive the switch's role reply messages log.debug("This controller's role is {}, " + "sending initial role request msg to {}", role, sw); Collection<OFSwitchImpl> swList = new ArrayList<OFSwitchImpl>(1); swList.add(sw); roleChanger.submitRequest(swList, role); } else { // Role supported not enabled on controller (for now) // automatically promote switch to active state. log.debug("This controller's role is null, " + "not sending role request msg to {}", role, sw); // Need to clear FlowMods before we add the switch // and dispatch updates otherwise we have a race condition. sw.clearAllFlowMods(); addSwitch(sw); state.firstRoleReplyReceived = true; } } } } /* Handle a role reply message we received from the switch. Since * netty serializes message dispatch we don't need to synchronize * against other receive operations from the same switch, so no need * to synchronize addSwitch(), removeSwitch() operations from the same * connection. * FIXME: However, when a switch with the same DPID connects we do * need some synchronization. However, handling switches with same * DPID needs to be revisited anyways (get rid of r/w-lock and synchronous * removedSwitch notification):1 * */ protected void handleRoleReplyMessage(OFVendor vendorMessage, OFRoleReplyVendorData roleReplyVendorData) { // Map from the role code in the message to our role enum int nxRole = roleReplyVendorData.getRole(); Role role = null; switch (nxRole) { case OFRoleVendorData.NX_ROLE_OTHER: role = Role.EQUAL; break; case OFRoleVendorData.NX_ROLE_MASTER: role = Role.MASTER; break; case OFRoleVendorData.NX_ROLE_SLAVE: role = Role.SLAVE; break; default: log.error("Invalid role value in role reply message"); sw.getChannel().close(); return; } log.debug("Handling role reply for role {} from {}. " + "Controller's role is {} ", new Object[] { role, sw, Controller.this.role} ); sw.deliverRoleReply(vendorMessage.getXid(), role); boolean isActive = activeSwitches.containsKey(sw.getId()); if (!isActive && sw.isActive()) { // Transition from SLAVE to MASTER. // Some switches don't seem to update us with port // status messages while in slave role. readSwitchPortStateFromStorage(sw); // Only add the switch to the active switch list if // we're not in the slave role. Note that if the role // attribute is null, then that means that the switch // doesn't support the role request messages, so in that // case we're effectively in the EQUAL role and the // switch should be included in the active switch list. addSwitch(sw); log.debug("Added master switch {} to active switch list", HexString.toHexString(sw.getId())); if (!state.firstRoleReplyReceived) { // This is the first role-reply message we receive from // this switch or roles were disabled when the switch // connected: // Delete all pre-existing flows for new connections to // the master // // FIXME: Need to think more about what the test should // be for when we flush the flow-table? For example, // if all the controllers are temporarily in the backup // role (e.g. right after a failure of the master // controller) at the point the switch connects, then // all of the controllers will initially connect as // backup controllers and not flush the flow-table. // Then when one of them is promoted to master following // the master controller election the flow-table // will still not be flushed because that's treated as // a failover event where we don't want to flush the // flow-table. The end result would be that the flow // table for a newly connected switch is never // flushed. Not sure how to handle that case though... sw.clearAllFlowMods(); log.debug("First role reply from master switch {}, " + "clear FlowTable to active switch list", HexString.toHexString(sw.getId())); } } else if (isActive && !sw.isActive()) { // Transition from MASTER to SLAVE: remove switch // from active switch list. log.debug("Removed slave switch {} from active switch" + " list", HexString.toHexString(sw.getId())); removeSwitch(sw); } // Indicate that we have received a role reply message. state.firstRoleReplyReceived = true; } protected boolean handleVendorMessage(OFVendor vendorMessage) { boolean shouldHandleMessage = false; int vendor = vendorMessage.getVendor(); switch (vendor) { case OFNiciraVendorData.NX_VENDOR_ID: OFNiciraVendorData niciraVendorData = (OFNiciraVendorData)vendorMessage.getVendorData(); int dataType = niciraVendorData.getDataType(); switch (dataType) { case OFRoleReplyVendorData.NXT_ROLE_REPLY: OFRoleReplyVendorData roleReplyVendorData = (OFRoleReplyVendorData) niciraVendorData; handleRoleReplyMessage(vendorMessage, roleReplyVendorData); break; default: log.warn("Unhandled Nicira VENDOR message; " + "data type = {}", dataType); break; } break; default: log.warn("Unhandled VENDOR message; vendor id = {}", vendor); break; } return shouldHandleMessage; } /** * Dispatch an Openflow message from a switch to the appropriate * handler. * @param m The message to process * @throws IOException * @throws SwitchStateException */ protected void processOFMessage(OFMessage m) throws IOException, SwitchStateException { boolean shouldHandleMessage = false; switch (m.getType()) { case HELLO: if (log.isTraceEnabled()) log.trace("HELLO from {}", sw); if (state.hsState.equals(HandshakeState.START)) { state.hsState = HandshakeState.HELLO; sendHelloConfiguration(); } else { throw new SwitchStateException("Unexpected HELLO from " + sw); } break; case ECHO_REQUEST: OFEchoReply reply = (OFEchoReply) factory.getMessage(OFType.ECHO_REPLY); reply.setXid(m.getXid()); sw.write(reply, null); break; case ECHO_REPLY: break; case FEATURES_REPLY: if (log.isTraceEnabled()) log.trace("Features Reply from {}", sw); if (state.hsState.equals(HandshakeState.HELLO)) { sw.setFeaturesReply((OFFeaturesReply) m); sendFeatureReplyConfiguration(); state.hsState = HandshakeState.FEATURES_REPLY; // uncomment to enable "dumb" switches like cbench // state.hsState = HandshakeState.READY; // addSwitch(sw); } else { String em = "Unexpected FEATURES_REPLY from " + sw; throw new SwitchStateException(em); } break; case GET_CONFIG_REPLY: if (log.isTraceEnabled()) log.trace("Get config reply from {}", sw); if (!state.hsState.equals(HandshakeState.FEATURES_REPLY)) { String em = "Unexpected GET_CONFIG_REPLY from " + sw; throw new SwitchStateException(em); } OFGetConfigReply cr = (OFGetConfigReply) m; if (cr.getMissSendLength() == (short)0xffff) { log.trace("Config Reply from {} confirms " + "miss length set to 0xffff", sw); } else { log.warn("Config Reply from {} has " + "miss length set to {}", sw, cr.getMissSendLength()); } state.hasGetConfigReply = true; checkSwitchReady(); break; case VENDOR: shouldHandleMessage = handleVendorMessage((OFVendor)m); break; case ERROR: // TODO: we need better error handling. Especially for // request/reply style message (stats, roles) we should have // a unified way to lookup the xid in the error message. // This will probable involve rewriting the way we handle // request/reply style messages. OFError error = (OFError) m; boolean shouldLogError = true; // TODO: should we check that firstRoleReplyReceived is false, // i.e., check only whether the first request fails? if (sw.checkFirstPendingRoleRequestXid(error.getXid())) { boolean isBadVendorError = (error.getErrorType() == OFError.OFErrorType. OFPET_BAD_REQUEST.getValue()) && (error.getErrorCode() == OFError. OFBadRequestCode. OFPBRC_BAD_VENDOR.ordinal()); // We expect to receive a bad vendor error when // we're connected to a switch that doesn't support // the Nicira vendor extensions (i.e. not OVS or // derived from OVS). So that's not a real error // case and we don't want to log those spurious errors. shouldLogError = !isBadVendorError; if (isBadVendorError) { - if (!state.firstRoleReplyReceived) { + if (state.firstRoleReplyReceived) { log.warn("Received ERROR from sw {} that " +"indicates roles are not supported " +"but we have received a valid " +"role reply earlier", sw); + state.firstRoleReplyReceived = false; } - state.firstRoleReplyReceived = true; sw.deliverRoleRequestNotSupported(error.getXid()); synchronized(roleChanger) { if (sw.role == null && Controller.this.role==Role.SLAVE) { // the switch doesn't understand role request // messages and the current controller role is // slave. We need to disconnect the switch. // @see RoleChanger for rationale sw.getChannel().close(); } else if (sw.role == null) { // Controller's role is master: add to // active // TODO: check if clearing flow table is // right choice here. // Need to clear FlowMods before we add the switch // and dispatch updates otherwise we have a race condition. // TODO: switch update is async. Won't we still have a potential // race condition? sw.clearAllFlowMods(); addSwitch(sw); } } } else { // TODO: Is this the right thing to do if we receive // some other error besides a bad vendor error? // Presumably that means the switch did actually // understand the role request message, but there // was some other error from processing the message. // OF 1.2 specifies a OFPET_ROLE_REQUEST_FAILED // error code, but it doesn't look like the Nicira // role request has that. Should check OVS source // code to see if it's possible for any other errors // to be returned. // If we received an error the switch is not // in the correct role, so we need to disconnect it. // We could also resend the request but then we need to // check if there are other pending request in which // case we shouldn't resend. If we do resend we need // to make sure that the switch eventually accepts one // of our requests or disconnect the switch. This feels // cumbersome. sw.getChannel().close(); } } // Once we support OF 1.2, we'd add code to handle it here. //if (error.getXid() == state.ofRoleRequestXid) { //} if (shouldLogError) logError(sw, error); break; case STATS_REPLY: if (state.hsState.ordinal() < HandshakeState.FEATURES_REPLY.ordinal()) { String em = "Unexpected STATS_REPLY from " + sw; throw new SwitchStateException(em); } sw.deliverStatisticsReply(m); if (sw.hasAttribute(IOFSwitch.SWITCH_DESCRIPTION_FUTURE)) { processSwitchDescReply(); } break; case PORT_STATUS: // We want to update our port state info even if we're in // the slave role, but we only want to update storage if // we're the master (or equal). boolean updateStorage = state.hsState. equals(HandshakeState.READY) && (sw.getRole() != Role.SLAVE); handlePortStatusMessage(sw, (OFPortStatus)m, updateStorage); shouldHandleMessage = true; break; default: shouldHandleMessage = true; break; } if (shouldHandleMessage) { sw.getListenerReadLock().lock(); try { if (sw.isConnected()) { if (!state.hsState.equals(HandshakeState.READY)) { log.debug("Ignoring message type {} received " + "from switch {} before switch is " + "fully configured.", m.getType(), sw); } // Check if the controller is in the slave role for the // switch. If it is, then don't dispatch the message to // the listeners. // TODO: Should we dispatch messages that we expect to // receive when we're in the slave role, e.g. port // status messages? Since we're "hiding" switches from // the listeners when we're in the slave role, then it // seems a little weird to dispatch port status messages // to them. On the other hand there might be special // modules that care about all of the connected switches // and would like to receive port status notifications. else if (sw.getRole() == Role.SLAVE) { // Don't log message if it's a port status message // since we expect to receive those from the switch // and don't want to emit spurious messages. if (m.getType() != OFType.PORT_STATUS) { log.debug("Ignoring message type {} received " + "from switch {} while in the slave role.", m.getType(), sw); } } else { handleMessage(sw, m, null); } } } finally { sw.getListenerReadLock().unlock(); } } } } // **************** // Message handlers // **************** protected void handlePortStatusMessage(IOFSwitch sw, OFPortStatus m, boolean updateStorage) { short portNumber = m.getDesc().getPortNumber(); OFPhysicalPort port = m.getDesc(); if (m.getReason() == (byte)OFPortReason.OFPPR_MODIFY.ordinal()) { sw.setPort(port); if (updateStorage) updatePortInfo(sw, port); log.debug("Port #{} modified for {}", portNumber, sw); } else if (m.getReason() == (byte)OFPortReason.OFPPR_ADD.ordinal()) { sw.setPort(port); if (updateStorage) updatePortInfo(sw, port); log.debug("Port #{} added for {}", portNumber, sw); } else if (m.getReason() == (byte)OFPortReason.OFPPR_DELETE.ordinal()) { sw.deletePort(portNumber); if (updateStorage) removePortInfo(sw, portNumber); log.debug("Port #{} deleted for {}", portNumber, sw); } } /** * flcontext_cache - Keep a thread local stack of contexts */ protected static final ThreadLocal<Stack<FloodlightContext>> flcontext_cache = new ThreadLocal <Stack<FloodlightContext>> () { @Override protected Stack<FloodlightContext> initialValue() { return new Stack<FloodlightContext>(); } }; /** * flcontext_alloc - pop a context off the stack, if required create a new one * @return FloodlightContext */ protected static FloodlightContext flcontext_alloc() { FloodlightContext flcontext = null; if (flcontext_cache.get().empty()) { flcontext = new FloodlightContext(); } else { flcontext = flcontext_cache.get().pop(); } return flcontext; } /** * flcontext_free - Free the context to the current thread * @param flcontext */ protected void flcontext_free(FloodlightContext flcontext) { flcontext.getStorage().clear(); flcontext_cache.get().push(flcontext); } /** * Handle replies to certain OFMessages, and pass others off to listeners * @param sw The switch for the message * @param m The message * @param bContext The floodlight context. If null then floodlight context would * be allocated in this function * @throws IOException */ protected void handleMessage(IOFSwitch sw, OFMessage m, FloodlightContext bContext) throws IOException { Ethernet eth = null; switch (m.getType()) { case PACKET_IN: OFPacketIn pi = (OFPacketIn)m; if (pi.getPacketData().length <= 0) { log.error("Ignoring PacketIn (Xid = " + pi.getXid() + ") because the data field is empty."); return; } if (Controller.ALWAYS_DECODE_ETH) { eth = new Ethernet(); eth.deserialize(pi.getPacketData(), 0, pi.getPacketData().length); counterStore.updatePacketInCounters(sw, m, eth); } // fall through to default case... default: List<IOFMessageListener> listeners = null; if (messageListeners.containsKey(m.getType())) { listeners = messageListeners.get(m.getType()). getOrderedListeners(); } FloodlightContext bc = null; if (listeners != null) { // Check if floodlight context is passed from the calling // function, if so use that floodlight context, otherwise // allocate one if (bContext == null) { bc = flcontext_alloc(); } else { bc = bContext; } if (eth != null) { IFloodlightProviderService.bcStore.put(bc, IFloodlightProviderService.CONTEXT_PI_PAYLOAD, eth); } // Get the starting time (overall and per-component) of // the processing chain for this packet if performance // monitoring is turned on pktinProcTime.bootstrap(listeners); pktinProcTime.recordStartTimePktIn(); Command cmd; for (IOFMessageListener listener : listeners) { if (listener instanceof IOFSwitchFilter) { if (!((IOFSwitchFilter)listener).isInterested(sw)) { continue; } } pktinProcTime.recordStartTimeComp(listener); cmd = listener.receive(sw, m, bc); pktinProcTime.recordEndTimeComp(listener); if (Command.STOP.equals(cmd)) { break; } } pktinProcTime.recordEndTimePktIn(sw, m, bc); } else { log.error("Unhandled OF Message: {} from {}", m, sw); } if ((bContext == null) && (bc != null)) flcontext_free(bc); } } /** * Log an OpenFlow error message from a switch * @param sw The switch that sent the error * @param error The error message */ protected void logError(IOFSwitch sw, OFError error) { int etint = 0xffff & error.getErrorType(); if (etint < 0 || etint >= OFErrorType.values().length) { log.error("Unknown error code {} from sw {}", etint, sw); } OFErrorType et = OFErrorType.values()[etint]; switch (et) { case OFPET_HELLO_FAILED: OFHelloFailedCode hfc = OFHelloFailedCode.values()[0xffff & error.getErrorCode()]; log.error("Error {} {} from {}", new Object[] {et, hfc, sw}); break; case OFPET_BAD_REQUEST: OFBadRequestCode brc = OFBadRequestCode.values()[0xffff & error.getErrorCode()]; log.error("Error {} {} from {}", new Object[] {et, brc, sw}); break; case OFPET_BAD_ACTION: OFBadActionCode bac = OFBadActionCode.values()[0xffff & error.getErrorCode()]; log.error("Error {} {} from {}", new Object[] {et, bac, sw}); break; case OFPET_FLOW_MOD_FAILED: OFFlowModFailedCode fmfc = OFFlowModFailedCode.values()[0xffff & error.getErrorCode()]; log.error("Error {} {} from {}", new Object[] {et, fmfc, sw}); break; case OFPET_PORT_MOD_FAILED: OFPortModFailedCode pmfc = OFPortModFailedCode.values()[0xffff & error.getErrorCode()]; log.error("Error {} {} from {}", new Object[] {et, pmfc, sw}); break; case OFPET_QUEUE_OP_FAILED: OFQueueOpFailedCode qofc = OFQueueOpFailedCode.values()[0xffff & error.getErrorCode()]; log.error("Error {} {} from {}", new Object[] {et, qofc, sw}); break; default: break; } } /** * Add a switch to the active switch list and call the switch listeners. * This happens either when a switch first connects (and the controller is * not in the slave role) or when the role of the controller changes from * slave to master. * @param sw the switch that has been added */ // TODO: need to rethink locking and the synchronous switch update. // We can / should also handle duplicate DPIDs in connectedSwitches protected void addSwitch(IOFSwitch sw) { // TODO: is it safe to modify the HashMap without holding // the old switch's lock? OFSwitchImpl oldSw = (OFSwitchImpl) this.activeSwitches.put(sw.getId(), sw); if (sw == oldSw) { // Note == for object equality, not .equals for value log.info("New add switch for pre-existing switch {}", sw); return; } if (oldSw != null) { oldSw.getListenerWriteLock().lock(); try { log.error("New switch added {} for already-added switch {}", sw, oldSw); // Set the connected flag to false to suppress calling // the listeners for this switch in processOFMessage oldSw.setConnected(false); oldSw.cancelAllStatisticsReplies(); updateInactiveSwitchInfo(oldSw); // we need to clean out old switch state definitively // before adding the new switch // FIXME: It seems not completely kosher to call the // switch listeners here. I thought one of the points of // having the asynchronous switch update mechanism was so // the addedSwitch and removedSwitch were always called // from a single thread to simplify concurrency issues // for the listener. if (switchListeners != null) { for (IOFSwitchListener listener : switchListeners) { listener.removedSwitch(oldSw); } } // will eventually trigger a removeSwitch(), which will cause // a "Not removing Switch ... already removed debug message. // TODO: Figure out a way to handle this that avoids the // spurious debug message. oldSw.getChannel().close(); } finally { oldSw.getListenerWriteLock().unlock(); } } updateActiveSwitchInfo(sw); SwitchUpdate update = new SwitchUpdate(sw, true); try { this.updates.put(update); } catch (InterruptedException e) { log.error("Failure adding update to queue", e); } } /** * Remove a switch from the active switch list and call the switch listeners. * This happens either when the switch is disconnected or when the * controller's role for the switch changes from master to slave. * @param sw the switch that has been removed */ protected void removeSwitch(IOFSwitch sw) { // No need to acquire the listener lock, since // this method is only called after netty has processed all // pending messages log.debug("removeSwitch: {}", sw); if (!this.activeSwitches.remove(sw.getId(), sw) || !sw.isConnected()) { log.debug("Not removing switch {}; already removed", sw); return; } // We cancel all outstanding statistics replies if the switch transition // from active. In the future we might allow statistics requests // from slave controllers. Then we need to move this cancelation // to switch disconnect sw.cancelAllStatisticsReplies(); // FIXME: I think there's a race condition if we call updateInactiveSwitchInfo // here if role support is enabled. In that case if the switch is being // removed because we've been switched to being in the slave role, then I think // it's possible that the new master may have already been promoted to master // and written out the active switch state to storage. If we now execute // updateInactiveSwitchInfo we may wipe out all of the state that was // written out by the new master. Maybe need to revisit how we handle all // of the switch state that's written to storage. updateInactiveSwitchInfo(sw); SwitchUpdate update = new SwitchUpdate(sw, false); try { this.updates.put(update); } catch (InterruptedException e) { log.error("Failure adding update to queue", e); } } // *************** // IFloodlightProvider // *************** @Override public synchronized void addOFMessageListener(OFType type, IOFMessageListener listener) { ListenerDispatcher<OFType, IOFMessageListener> ldd = messageListeners.get(type); if (ldd == null) { ldd = new ListenerDispatcher<OFType, IOFMessageListener>(); messageListeners.put(type, ldd); } ldd.addListener(type, listener); } @Override public synchronized void removeOFMessageListener(OFType type, IOFMessageListener listener) { ListenerDispatcher<OFType, IOFMessageListener> ldd = messageListeners.get(type); if (ldd != null) { ldd.removeListener(listener); } } private void logListeners() { for (Map.Entry<OFType, ListenerDispatcher<OFType, IOFMessageListener>> entry : messageListeners.entrySet()) { OFType type = entry.getKey(); ListenerDispatcher<OFType, IOFMessageListener> ldd = entry.getValue(); StringBuffer sb = new StringBuffer(); sb.append("OFListeners for "); sb.append(type); sb.append(": "); for (IOFMessageListener l : ldd.getOrderedListeners()) { sb.append(l.getName()); sb.append(","); } log.debug(sb.toString()); } } public void removeOFMessageListeners(OFType type) { messageListeners.remove(type); } @Override public Map<Long, IOFSwitch> getSwitches() { return Collections.unmodifiableMap(this.activeSwitches); } @Override public void addOFSwitchListener(IOFSwitchListener listener) { this.switchListeners.add(listener); } @Override public void removeOFSwitchListener(IOFSwitchListener listener) { this.switchListeners.remove(listener); } @Override public Map<OFType, List<IOFMessageListener>> getListeners() { Map<OFType, List<IOFMessageListener>> lers = new HashMap<OFType, List<IOFMessageListener>>(); for(Entry<OFType, ListenerDispatcher<OFType, IOFMessageListener>> e : messageListeners.entrySet()) { lers.put(e.getKey(), e.getValue().getOrderedListeners()); } return Collections.unmodifiableMap(lers); } @Override public boolean injectOfMessage(IOFSwitch sw, OFMessage msg, FloodlightContext bc) { if (sw == null) { log.info("Failed to inject OFMessage {} onto a null switch", msg); return false; } // FIXME: Do we need to be able to inject messages to switches // where we're the slave controller (i.e. they're connected but // not active)? // FIXME: Don't we need synchronization logic here so we're holding // the listener read lock when we call handleMessage? After some // discussions it sounds like the right thing to do here would be to // inject the message as a netty upstream channel event so it goes // through the normal netty event processing, including being // handled if (!activeSwitches.containsKey(sw.getId())) return false; try { // Pass Floodlight context to the handleMessages() handleMessage(sw, msg, bc); } catch (IOException e) { log.error("Error reinjecting OFMessage on switch {}", HexString.toHexString(sw.getId())); return false; } return true; } @Override public synchronized void terminate() { log.info("Calling System.exit"); System.exit(1); } @Override public boolean injectOfMessage(IOFSwitch sw, OFMessage msg) { // call the overloaded version with floodlight context set to null return injectOfMessage(sw, msg, null); } @Override public void handleOutgoingMessage(IOFSwitch sw, OFMessage m, FloodlightContext bc) { if (log.isTraceEnabled()) { String str = OFMessage.getDataAsString(sw, m, bc); log.trace("{}", str); } List<IOFMessageListener> listeners = null; if (messageListeners.containsKey(m.getType())) { listeners = messageListeners.get(m.getType()).getOrderedListeners(); } if (listeners != null) { for (IOFMessageListener listener : listeners) { if (listener instanceof IOFSwitchFilter) { if (!((IOFSwitchFilter)listener).isInterested(sw)) { continue; } } if (Command.STOP.equals(listener.receive(sw, m, bc))) { break; } } } } @Override public BasicFactory getOFMessageFactory() { return factory; } @Override public String getControllerId() { return controllerId; } // ************** // Initialization // ************** protected void updateAllInactiveSwitchInfo() { if (role == Role.SLAVE) { return; } String controllerId = getControllerId(); String[] switchColumns = { SWITCH_DATAPATH_ID, SWITCH_CONTROLLER_ID, SWITCH_ACTIVE }; String[] portColumns = { PORT_ID, PORT_SWITCH }; IResultSet switchResultSet = null; try { OperatorPredicate op = new OperatorPredicate(SWITCH_CONTROLLER_ID, OperatorPredicate.Operator.EQ, controllerId); switchResultSet = storageSource.executeQuery(SWITCH_TABLE_NAME, switchColumns, op, null); while (switchResultSet.next()) { IResultSet portResultSet = null; try { String datapathId = switchResultSet.getString(SWITCH_DATAPATH_ID); switchResultSet.setBoolean(SWITCH_ACTIVE, Boolean.FALSE); op = new OperatorPredicate(PORT_SWITCH, OperatorPredicate.Operator.EQ, datapathId); portResultSet = storageSource.executeQuery(PORT_TABLE_NAME, portColumns, op, null); while (portResultSet.next()) { portResultSet.deleteRow(); } portResultSet.save(); } finally { if (portResultSet != null) portResultSet.close(); } } switchResultSet.save(); } finally { if (switchResultSet != null) switchResultSet.close(); } } protected void updateControllerInfo() { updateAllInactiveSwitchInfo(); // Write out the controller info to the storage source Map<String, Object> controllerInfo = new HashMap<String, Object>(); String id = getControllerId(); controllerInfo.put(CONTROLLER_ID, id); storageSource.updateRow(CONTROLLER_TABLE_NAME, controllerInfo); } protected void updateActiveSwitchInfo(IOFSwitch sw) { if (role == Role.SLAVE) { return; } // Obtain the row info for the switch Map<String, Object> switchInfo = new HashMap<String, Object>(); String datapathIdString = sw.getStringId(); switchInfo.put(SWITCH_DATAPATH_ID, datapathIdString); String controllerId = getControllerId(); switchInfo.put(SWITCH_CONTROLLER_ID, controllerId); Date connectedSince = sw.getConnectedSince(); switchInfo.put(SWITCH_CONNECTED_SINCE, connectedSince); Channel channel = sw.getChannel(); SocketAddress socketAddress = channel.getRemoteAddress(); if (socketAddress != null) { String socketAddressString = socketAddress.toString(); switchInfo.put(SWITCH_SOCKET_ADDRESS, socketAddressString); if (socketAddress instanceof InetSocketAddress) { InetSocketAddress inetSocketAddress = (InetSocketAddress)socketAddress; InetAddress inetAddress = inetSocketAddress.getAddress(); String ip = inetAddress.getHostAddress(); switchInfo.put(SWITCH_IP, ip); } } // Write out the switch features info OFFeaturesReply featuresReply = sw.getFeaturesReply(); long capabilities = U32.f(featuresReply.getCapabilities()); switchInfo.put(SWITCH_CAPABILITIES, capabilities); long buffers = U32.f(featuresReply.getBuffers()); switchInfo.put(SWITCH_BUFFERS, buffers); long tables = U32.f(featuresReply.getTables()); switchInfo.put(SWITCH_TABLES, tables); long actions = U32.f(featuresReply.getActions()); switchInfo.put(SWITCH_ACTIONS, actions); switchInfo.put(SWITCH_ACTIVE, Boolean.TRUE); // Update the switch storageSource.updateRowAsync(SWITCH_TABLE_NAME, switchInfo); // Update the ports for (OFPhysicalPort port: sw.getPorts().values()) { updatePortInfo(sw, port); } } protected void updateInactiveSwitchInfo(IOFSwitch sw) { if (role == Role.SLAVE) { return; } log.debug("Update DB with inactiveSW {}", sw); // Update the controller info in the storage source to be inactive Map<String, Object> switchInfo = new HashMap<String, Object>(); String datapathIdString = sw.getStringId(); switchInfo.put(SWITCH_DATAPATH_ID, datapathIdString); //switchInfo.put(SWITCH_CONNECTED_SINCE, null); switchInfo.put(SWITCH_ACTIVE, Boolean.FALSE); storageSource.updateRowAsync(SWITCH_TABLE_NAME, switchInfo); } protected void updatePortInfo(IOFSwitch sw, OFPhysicalPort port) { if (role == Role.SLAVE) { return; } String datapathIdString = sw.getStringId(); Map<String, Object> portInfo = new HashMap<String, Object>(); int portNumber = U16.f(port.getPortNumber()); String id = datapathIdString + "|" + portNumber; portInfo.put(PORT_ID, id); portInfo.put(PORT_SWITCH, datapathIdString); portInfo.put(PORT_NUMBER, portNumber); byte[] hardwareAddress = port.getHardwareAddress(); String hardwareAddressString = HexString.toHexString(hardwareAddress); portInfo.put(PORT_HARDWARE_ADDRESS, hardwareAddressString); String name = port.getName(); portInfo.put(PORT_NAME, name); long config = U32.f(port.getConfig()); portInfo.put(PORT_CONFIG, config); long state = U32.f(port.getState()); portInfo.put(PORT_STATE, state); long currentFeatures = U32.f(port.getCurrentFeatures()); portInfo.put(PORT_CURRENT_FEATURES, currentFeatures); long advertisedFeatures = U32.f(port.getAdvertisedFeatures()); portInfo.put(PORT_ADVERTISED_FEATURES, advertisedFeatures); long supportedFeatures = U32.f(port.getSupportedFeatures()); portInfo.put(PORT_SUPPORTED_FEATURES, supportedFeatures); long peerFeatures = U32.f(port.getPeerFeatures()); portInfo.put(PORT_PEER_FEATURES, peerFeatures); storageSource.updateRowAsync(PORT_TABLE_NAME, portInfo); } /** * Read switch port data from storage and write it into a switch object * @param sw the switch to update */ protected void readSwitchPortStateFromStorage(OFSwitchImpl sw) { OperatorPredicate op = new OperatorPredicate(PORT_SWITCH, OperatorPredicate.Operator.EQ, sw.getStringId()); IResultSet portResultSet = storageSource.executeQuery(PORT_TABLE_NAME, null, op, null); //Map<Short, OFPhysicalPort> oldports = // new HashMap<Short, OFPhysicalPort>(); //oldports.putAll(sw.getPorts()); while (portResultSet.next()) { try { OFPhysicalPort p = new OFPhysicalPort(); p.setPortNumber((short)portResultSet.getInt(PORT_NUMBER)); p.setName(portResultSet.getString(PORT_NAME)); p.setConfig((int)portResultSet.getLong(PORT_CONFIG)); p.setState((int)portResultSet.getLong(PORT_STATE)); String portMac = portResultSet.getString(PORT_HARDWARE_ADDRESS); p.setHardwareAddress(HexString.fromHexString(portMac)); p.setCurrentFeatures((int)portResultSet. getLong(PORT_CURRENT_FEATURES)); p.setAdvertisedFeatures((int)portResultSet. getLong(PORT_ADVERTISED_FEATURES)); p.setSupportedFeatures((int)portResultSet. getLong(PORT_SUPPORTED_FEATURES)); p.setPeerFeatures((int)portResultSet. getLong(PORT_PEER_FEATURES)); //oldports.remove(Short.valueOf(p.getPortNumber())); sw.setPort(p); } catch (NullPointerException e) { // ignore } } //for (Short portNum : oldports.keySet()) { // sw.deletePort(portNum); //} } protected void removePortInfo(IOFSwitch sw, short portNumber) { if (role == Role.SLAVE) { return; } String datapathIdString = sw.getStringId(); String id = datapathIdString + "|" + portNumber; storageSource.deleteRowAsync(PORT_TABLE_NAME, id); } /** * Sets the initial role based on properties in the config params. * It looks for two different properties. * If the "role" property is specified then the value should be * either "EQUAL", "MASTER", or "SLAVE" and the role of the * controller is set to the specified value. If the "role" property * is not specified then it looks next for the "role.path" property. * In this case the value should be the path to a property file in * the file system that contains a property called "floodlight.role" * which can be one of the values listed above for the "role" property. * The idea behind the "role.path" mechanism is that you have some * separate heartbeat and master controller election algorithm that * determines the role of the controller. When a role transition happens, * it updates the current role in the file specified by the "role.path" * file. Then if floodlight restarts for some reason it can get the * correct current role of the controller from the file. * @param configParams The config params for the FloodlightProvider service * @return A valid role if role information is specified in the * config params, otherwise null */ protected Role getInitialRole(Map<String, String> configParams) { Role role = null; String roleString = configParams.get("role"); if (roleString == null) { String rolePath = configParams.get("rolepath"); if (rolePath != null) { Properties properties = new Properties(); try { properties.load(new FileInputStream(rolePath)); roleString = properties.getProperty("floodlight.role"); } catch (IOException exc) { // Don't treat it as an error if the file specified by the // rolepath property doesn't exist. This lets us enable the // HA mechanism by just creating/setting the floodlight.role // property in that file without having to modify the // floodlight properties. } } } if (roleString != null) { // Canonicalize the string to the form used for the enum constants roleString = roleString.trim().toUpperCase(); try { role = Role.valueOf(roleString); } catch (IllegalArgumentException exc) { log.error("Invalid current role value: {}", roleString); } } log.info("Controller roles set to {}", role); return role; } /** * Tell controller that we're ready to accept switches loop * @throws IOException */ public void run() { if (log.isDebugEnabled()) { logListeners(); } try { final ServerBootstrap bootstrap = createServerBootStrap(); bootstrap.setOption("reuseAddr", true); bootstrap.setOption("child.keepAlive", true); bootstrap.setOption("child.tcpNoDelay", true); bootstrap.setOption("child.sendBufferSize", Controller.SEND_BUFFER_SIZE); ChannelPipelineFactory pfact = new OpenflowPipelineFactory(this, null); bootstrap.setPipelineFactory(pfact); InetSocketAddress sa = new InetSocketAddress(openFlowPort); final ChannelGroup cg = new DefaultChannelGroup(); cg.add(bootstrap.bind(sa)); log.info("Listening for switch connections on {}", sa); } catch (Exception e) { throw new RuntimeException(e); } // main loop while (true) { try { IUpdate update = updates.take(); update.dispatch(); } catch (InterruptedException e) { return; } catch (StorageException e) { log.error("Storage exception in controller " + "updates loop; terminating process", e); return; } catch (Exception e) { log.error("Exception in controller updates loop", e); } } } private ServerBootstrap createServerBootStrap() { if (workerThreads == 0) { return new ServerBootstrap( new NioServerSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool())); } else { return new ServerBootstrap( new NioServerSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool(), workerThreads)); } } public void setConfigParams(Map<String, String> configParams) { String ofPort = configParams.get("openflowport"); if (ofPort != null) { this.openFlowPort = Integer.parseInt(ofPort); } log.debug("OpenFlow port set to {}", this.openFlowPort); String threads = configParams.get("workerthreads"); if (threads != null) { this.workerThreads = Integer.parseInt(threads); } log.debug("Number of worker threads set to {}", this.workerThreads); String controllerId = configParams.get("controllerid"); if (controllerId != null) { this.controllerId = controllerId; } log.debug("ControllerId set to {}", this.controllerId); } private void initVendorMessages() { // Configure openflowj to be able to parse the role request/reply // vendor messages. OFBasicVendorId niciraVendorId = new OFBasicVendorId( OFNiciraVendorData.NX_VENDOR_ID, 4); OFVendorId.registerVendorId(niciraVendorId); OFBasicVendorDataType roleRequestVendorData = new OFBasicVendorDataType( OFRoleRequestVendorData.NXT_ROLE_REQUEST, OFRoleRequestVendorData.getInstantiable()); niciraVendorId.registerVendorDataType(roleRequestVendorData); OFBasicVendorDataType roleReplyVendorData = new OFBasicVendorDataType( OFRoleReplyVendorData.NXT_ROLE_REPLY, OFRoleReplyVendorData.getInstantiable()); niciraVendorId.registerVendorDataType(roleReplyVendorData); } /** * Initialize internal data structures */ public void init(Map<String, String> configParams) { // These data structures are initialized here because other // module's startUp() might be called before ours this.messageListeners = new ConcurrentHashMap<OFType, ListenerDispatcher<OFType, IOFMessageListener>>(); this.switchListeners = new CopyOnWriteArraySet<IOFSwitchListener>(); this.haListeners = new CopyOnWriteArraySet<IHAListener>(); this.activeSwitches = new ConcurrentHashMap<Long, IOFSwitch>(); this.connectedSwitches = new HashSet<OFSwitchImpl>(); this.controllerNodeIPsCache = new HashMap<String, String>(); this.updates = new LinkedBlockingQueue<IUpdate>(); this.factory = new BasicFactory(); this.providerMap = new HashMap<String, List<IInfoProvider>>(); setConfigParams(configParams); this.role = getInitialRole(configParams); this.roleChanger = new RoleChanger(); initVendorMessages(); this.systemStartTime = System.currentTimeMillis(); } /** * Startup all of the controller's components */ public void startupComponents() { // Create the table names we use storageSource.createTable(CONTROLLER_TABLE_NAME, null); storageSource.createTable(SWITCH_TABLE_NAME, null); storageSource.createTable(PORT_TABLE_NAME, null); storageSource.createTable(CONTROLLER_INTERFACE_TABLE_NAME, null); storageSource.createTable(SWITCH_CONFIG_TABLE_NAME, null); storageSource.setTablePrimaryKeyName(CONTROLLER_TABLE_NAME, CONTROLLER_ID); storageSource.setTablePrimaryKeyName(SWITCH_TABLE_NAME, SWITCH_DATAPATH_ID); storageSource.setTablePrimaryKeyName(PORT_TABLE_NAME, PORT_ID); storageSource.setTablePrimaryKeyName(CONTROLLER_INTERFACE_TABLE_NAME, CONTROLLER_INTERFACE_ID); storageSource.addListener(CONTROLLER_INTERFACE_TABLE_NAME, this); while (true) { try { updateControllerInfo(); break; } catch (StorageException e) { log.info("Waiting for storage source"); try { Thread.sleep(1000); } catch (InterruptedException e1) { } } } // Add our REST API restApi.addRestletRoutable(new CoreWebRoutable()); } @Override public void addInfoProvider(String type, IInfoProvider provider) { if (!providerMap.containsKey(type)) { providerMap.put(type, new ArrayList<IInfoProvider>()); } providerMap.get(type).add(provider); } @Override public void removeInfoProvider(String type, IInfoProvider provider) { if (!providerMap.containsKey(type)) { log.debug("Provider type {} doesn't exist.", type); return; } providerMap.get(type).remove(provider); } public Map<String, Object> getControllerInfo(String type) { if (!providerMap.containsKey(type)) return null; Map<String, Object> result = new LinkedHashMap<String, Object>(); for (IInfoProvider provider : providerMap.get(type)) { result.putAll(provider.getInfo(type)); } return result; } @Override public void addHAListener(IHAListener listener) { this.haListeners.add(listener); } @Override public void removeHAListener(IHAListener listener) { this.haListeners.remove(listener); } /** * Handle changes to the controller nodes IPs and dispatch update. */ @SuppressWarnings("unchecked") protected void handleControllerNodeIPChanges() { HashMap<String,String> curControllerNodeIPs = new HashMap<String,String>(); HashMap<String,String> addedControllerNodeIPs = new HashMap<String,String>(); HashMap<String,String> removedControllerNodeIPs =new HashMap<String,String>(); String[] colNames = { CONTROLLER_INTERFACE_CONTROLLER_ID, CONTROLLER_INTERFACE_TYPE, CONTROLLER_INTERFACE_NUMBER, CONTROLLER_INTERFACE_DISCOVERED_IP }; synchronized(controllerNodeIPsCache) { // We currently assume that interface Ethernet0 is the relevant // controller interface. Might change. // We could (should?) implement this using // predicates, but creating the individual and compound predicate // seems more overhead then just checking every row. Particularly, // since the number of rows is small and changes infrequent IResultSet res = storageSource.executeQuery(CONTROLLER_INTERFACE_TABLE_NAME, colNames,null, null); while (res.next()) { if (res.getString(CONTROLLER_INTERFACE_TYPE).equals("Ethernet") && res.getInt(CONTROLLER_INTERFACE_NUMBER) == 0) { String controllerID = res.getString(CONTROLLER_INTERFACE_CONTROLLER_ID); String discoveredIP = res.getString(CONTROLLER_INTERFACE_DISCOVERED_IP); String curIP = controllerNodeIPsCache.get(controllerID); curControllerNodeIPs.put(controllerID, discoveredIP); if (curIP == null) { // new controller node IP addedControllerNodeIPs.put(controllerID, discoveredIP); } else if (curIP != discoveredIP) { // IP changed removedControllerNodeIPs.put(controllerID, curIP); addedControllerNodeIPs.put(controllerID, discoveredIP); } } } // Now figure out if rows have been deleted. We can't use the // rowKeys from rowsDeleted directly, since the tables primary // key is a compound that we can't disassemble Set<String> curEntries = curControllerNodeIPs.keySet(); Set<String> removedEntries = controllerNodeIPsCache.keySet(); removedEntries.removeAll(curEntries); for (String removedControllerID : removedEntries) removedControllerNodeIPs.put(removedControllerID, controllerNodeIPsCache.get(removedControllerID)); controllerNodeIPsCache = (HashMap<String, String>) curControllerNodeIPs.clone(); HAControllerNodeIPUpdate update = new HAControllerNodeIPUpdate( curControllerNodeIPs, addedControllerNodeIPs, removedControllerNodeIPs); if (!removedControllerNodeIPs.isEmpty() || !addedControllerNodeIPs.isEmpty()) { try { this.updates.put(update); } catch (InterruptedException e) { log.error("Failure adding update to queue", e); } } } } @Override public Map<String, String> getControllerNodeIPs() { // We return a copy of the mapping so we can guarantee that // the mapping return is the same as one that will be (or was) // dispatched to IHAListeners HashMap<String,String> retval = new HashMap<String,String>(); synchronized(controllerNodeIPsCache) { retval.putAll(controllerNodeIPsCache); } return retval; } @Override public void rowsModified(String tableName, Set<Object> rowKeys) { if (tableName.equals(CONTROLLER_INTERFACE_TABLE_NAME)) { handleControllerNodeIPChanges(); } } @Override public void rowsDeleted(String tableName, Set<Object> rowKeys) { if (tableName.equals(CONTROLLER_INTERFACE_TABLE_NAME)) { handleControllerNodeIPChanges(); } } @Override public long getSystemStartTime() { return (this.systemStartTime); } }
false
true
protected void processOFMessage(OFMessage m) throws IOException, SwitchStateException { boolean shouldHandleMessage = false; switch (m.getType()) { case HELLO: if (log.isTraceEnabled()) log.trace("HELLO from {}", sw); if (state.hsState.equals(HandshakeState.START)) { state.hsState = HandshakeState.HELLO; sendHelloConfiguration(); } else { throw new SwitchStateException("Unexpected HELLO from " + sw); } break; case ECHO_REQUEST: OFEchoReply reply = (OFEchoReply) factory.getMessage(OFType.ECHO_REPLY); reply.setXid(m.getXid()); sw.write(reply, null); break; case ECHO_REPLY: break; case FEATURES_REPLY: if (log.isTraceEnabled()) log.trace("Features Reply from {}", sw); if (state.hsState.equals(HandshakeState.HELLO)) { sw.setFeaturesReply((OFFeaturesReply) m); sendFeatureReplyConfiguration(); state.hsState = HandshakeState.FEATURES_REPLY; // uncomment to enable "dumb" switches like cbench // state.hsState = HandshakeState.READY; // addSwitch(sw); } else { String em = "Unexpected FEATURES_REPLY from " + sw; throw new SwitchStateException(em); } break; case GET_CONFIG_REPLY: if (log.isTraceEnabled()) log.trace("Get config reply from {}", sw); if (!state.hsState.equals(HandshakeState.FEATURES_REPLY)) { String em = "Unexpected GET_CONFIG_REPLY from " + sw; throw new SwitchStateException(em); } OFGetConfigReply cr = (OFGetConfigReply) m; if (cr.getMissSendLength() == (short)0xffff) { log.trace("Config Reply from {} confirms " + "miss length set to 0xffff", sw); } else { log.warn("Config Reply from {} has " + "miss length set to {}", sw, cr.getMissSendLength()); } state.hasGetConfigReply = true; checkSwitchReady(); break; case VENDOR: shouldHandleMessage = handleVendorMessage((OFVendor)m); break; case ERROR: // TODO: we need better error handling. Especially for // request/reply style message (stats, roles) we should have // a unified way to lookup the xid in the error message. // This will probable involve rewriting the way we handle // request/reply style messages. OFError error = (OFError) m; boolean shouldLogError = true; // TODO: should we check that firstRoleReplyReceived is false, // i.e., check only whether the first request fails? if (sw.checkFirstPendingRoleRequestXid(error.getXid())) { boolean isBadVendorError = (error.getErrorType() == OFError.OFErrorType. OFPET_BAD_REQUEST.getValue()) && (error.getErrorCode() == OFError. OFBadRequestCode. OFPBRC_BAD_VENDOR.ordinal()); // We expect to receive a bad vendor error when // we're connected to a switch that doesn't support // the Nicira vendor extensions (i.e. not OVS or // derived from OVS). So that's not a real error // case and we don't want to log those spurious errors. shouldLogError = !isBadVendorError; if (isBadVendorError) { if (!state.firstRoleReplyReceived) { log.warn("Received ERROR from sw {} that " +"indicates roles are not supported " +"but we have received a valid " +"role reply earlier", sw); } state.firstRoleReplyReceived = true; sw.deliverRoleRequestNotSupported(error.getXid()); synchronized(roleChanger) { if (sw.role == null && Controller.this.role==Role.SLAVE) { // the switch doesn't understand role request // messages and the current controller role is // slave. We need to disconnect the switch. // @see RoleChanger for rationale sw.getChannel().close(); } else if (sw.role == null) { // Controller's role is master: add to // active // TODO: check if clearing flow table is // right choice here. // Need to clear FlowMods before we add the switch // and dispatch updates otherwise we have a race condition. // TODO: switch update is async. Won't we still have a potential // race condition? sw.clearAllFlowMods(); addSwitch(sw); } } } else { // TODO: Is this the right thing to do if we receive // some other error besides a bad vendor error? // Presumably that means the switch did actually // understand the role request message, but there // was some other error from processing the message. // OF 1.2 specifies a OFPET_ROLE_REQUEST_FAILED // error code, but it doesn't look like the Nicira // role request has that. Should check OVS source // code to see if it's possible for any other errors // to be returned. // If we received an error the switch is not // in the correct role, so we need to disconnect it. // We could also resend the request but then we need to // check if there are other pending request in which // case we shouldn't resend. If we do resend we need // to make sure that the switch eventually accepts one // of our requests or disconnect the switch. This feels // cumbersome. sw.getChannel().close(); } } // Once we support OF 1.2, we'd add code to handle it here. //if (error.getXid() == state.ofRoleRequestXid) { //} if (shouldLogError) logError(sw, error); break; case STATS_REPLY: if (state.hsState.ordinal() < HandshakeState.FEATURES_REPLY.ordinal()) { String em = "Unexpected STATS_REPLY from " + sw; throw new SwitchStateException(em); } sw.deliverStatisticsReply(m); if (sw.hasAttribute(IOFSwitch.SWITCH_DESCRIPTION_FUTURE)) { processSwitchDescReply(); } break; case PORT_STATUS: // We want to update our port state info even if we're in // the slave role, but we only want to update storage if // we're the master (or equal). boolean updateStorage = state.hsState. equals(HandshakeState.READY) && (sw.getRole() != Role.SLAVE); handlePortStatusMessage(sw, (OFPortStatus)m, updateStorage); shouldHandleMessage = true; break; default: shouldHandleMessage = true; break; } if (shouldHandleMessage) { sw.getListenerReadLock().lock(); try { if (sw.isConnected()) { if (!state.hsState.equals(HandshakeState.READY)) { log.debug("Ignoring message type {} received " + "from switch {} before switch is " + "fully configured.", m.getType(), sw); } // Check if the controller is in the slave role for the // switch. If it is, then don't dispatch the message to // the listeners. // TODO: Should we dispatch messages that we expect to // receive when we're in the slave role, e.g. port // status messages? Since we're "hiding" switches from // the listeners when we're in the slave role, then it // seems a little weird to dispatch port status messages // to them. On the other hand there might be special // modules that care about all of the connected switches // and would like to receive port status notifications. else if (sw.getRole() == Role.SLAVE) { // Don't log message if it's a port status message // since we expect to receive those from the switch // and don't want to emit spurious messages. if (m.getType() != OFType.PORT_STATUS) { log.debug("Ignoring message type {} received " + "from switch {} while in the slave role.", m.getType(), sw); } } else { handleMessage(sw, m, null); } } } finally { sw.getListenerReadLock().unlock(); } } }
protected void processOFMessage(OFMessage m) throws IOException, SwitchStateException { boolean shouldHandleMessage = false; switch (m.getType()) { case HELLO: if (log.isTraceEnabled()) log.trace("HELLO from {}", sw); if (state.hsState.equals(HandshakeState.START)) { state.hsState = HandshakeState.HELLO; sendHelloConfiguration(); } else { throw new SwitchStateException("Unexpected HELLO from " + sw); } break; case ECHO_REQUEST: OFEchoReply reply = (OFEchoReply) factory.getMessage(OFType.ECHO_REPLY); reply.setXid(m.getXid()); sw.write(reply, null); break; case ECHO_REPLY: break; case FEATURES_REPLY: if (log.isTraceEnabled()) log.trace("Features Reply from {}", sw); if (state.hsState.equals(HandshakeState.HELLO)) { sw.setFeaturesReply((OFFeaturesReply) m); sendFeatureReplyConfiguration(); state.hsState = HandshakeState.FEATURES_REPLY; // uncomment to enable "dumb" switches like cbench // state.hsState = HandshakeState.READY; // addSwitch(sw); } else { String em = "Unexpected FEATURES_REPLY from " + sw; throw new SwitchStateException(em); } break; case GET_CONFIG_REPLY: if (log.isTraceEnabled()) log.trace("Get config reply from {}", sw); if (!state.hsState.equals(HandshakeState.FEATURES_REPLY)) { String em = "Unexpected GET_CONFIG_REPLY from " + sw; throw new SwitchStateException(em); } OFGetConfigReply cr = (OFGetConfigReply) m; if (cr.getMissSendLength() == (short)0xffff) { log.trace("Config Reply from {} confirms " + "miss length set to 0xffff", sw); } else { log.warn("Config Reply from {} has " + "miss length set to {}", sw, cr.getMissSendLength()); } state.hasGetConfigReply = true; checkSwitchReady(); break; case VENDOR: shouldHandleMessage = handleVendorMessage((OFVendor)m); break; case ERROR: // TODO: we need better error handling. Especially for // request/reply style message (stats, roles) we should have // a unified way to lookup the xid in the error message. // This will probable involve rewriting the way we handle // request/reply style messages. OFError error = (OFError) m; boolean shouldLogError = true; // TODO: should we check that firstRoleReplyReceived is false, // i.e., check only whether the first request fails? if (sw.checkFirstPendingRoleRequestXid(error.getXid())) { boolean isBadVendorError = (error.getErrorType() == OFError.OFErrorType. OFPET_BAD_REQUEST.getValue()) && (error.getErrorCode() == OFError. OFBadRequestCode. OFPBRC_BAD_VENDOR.ordinal()); // We expect to receive a bad vendor error when // we're connected to a switch that doesn't support // the Nicira vendor extensions (i.e. not OVS or // derived from OVS). So that's not a real error // case and we don't want to log those spurious errors. shouldLogError = !isBadVendorError; if (isBadVendorError) { if (state.firstRoleReplyReceived) { log.warn("Received ERROR from sw {} that " +"indicates roles are not supported " +"but we have received a valid " +"role reply earlier", sw); state.firstRoleReplyReceived = false; } sw.deliverRoleRequestNotSupported(error.getXid()); synchronized(roleChanger) { if (sw.role == null && Controller.this.role==Role.SLAVE) { // the switch doesn't understand role request // messages and the current controller role is // slave. We need to disconnect the switch. // @see RoleChanger for rationale sw.getChannel().close(); } else if (sw.role == null) { // Controller's role is master: add to // active // TODO: check if clearing flow table is // right choice here. // Need to clear FlowMods before we add the switch // and dispatch updates otherwise we have a race condition. // TODO: switch update is async. Won't we still have a potential // race condition? sw.clearAllFlowMods(); addSwitch(sw); } } } else { // TODO: Is this the right thing to do if we receive // some other error besides a bad vendor error? // Presumably that means the switch did actually // understand the role request message, but there // was some other error from processing the message. // OF 1.2 specifies a OFPET_ROLE_REQUEST_FAILED // error code, but it doesn't look like the Nicira // role request has that. Should check OVS source // code to see if it's possible for any other errors // to be returned. // If we received an error the switch is not // in the correct role, so we need to disconnect it. // We could also resend the request but then we need to // check if there are other pending request in which // case we shouldn't resend. If we do resend we need // to make sure that the switch eventually accepts one // of our requests or disconnect the switch. This feels // cumbersome. sw.getChannel().close(); } } // Once we support OF 1.2, we'd add code to handle it here. //if (error.getXid() == state.ofRoleRequestXid) { //} if (shouldLogError) logError(sw, error); break; case STATS_REPLY: if (state.hsState.ordinal() < HandshakeState.FEATURES_REPLY.ordinal()) { String em = "Unexpected STATS_REPLY from " + sw; throw new SwitchStateException(em); } sw.deliverStatisticsReply(m); if (sw.hasAttribute(IOFSwitch.SWITCH_DESCRIPTION_FUTURE)) { processSwitchDescReply(); } break; case PORT_STATUS: // We want to update our port state info even if we're in // the slave role, but we only want to update storage if // we're the master (or equal). boolean updateStorage = state.hsState. equals(HandshakeState.READY) && (sw.getRole() != Role.SLAVE); handlePortStatusMessage(sw, (OFPortStatus)m, updateStorage); shouldHandleMessage = true; break; default: shouldHandleMessage = true; break; } if (shouldHandleMessage) { sw.getListenerReadLock().lock(); try { if (sw.isConnected()) { if (!state.hsState.equals(HandshakeState.READY)) { log.debug("Ignoring message type {} received " + "from switch {} before switch is " + "fully configured.", m.getType(), sw); } // Check if the controller is in the slave role for the // switch. If it is, then don't dispatch the message to // the listeners. // TODO: Should we dispatch messages that we expect to // receive when we're in the slave role, e.g. port // status messages? Since we're "hiding" switches from // the listeners when we're in the slave role, then it // seems a little weird to dispatch port status messages // to them. On the other hand there might be special // modules that care about all of the connected switches // and would like to receive port status notifications. else if (sw.getRole() == Role.SLAVE) { // Don't log message if it's a port status message // since we expect to receive those from the switch // and don't want to emit spurious messages. if (m.getType() != OFType.PORT_STATUS) { log.debug("Ignoring message type {} received " + "from switch {} while in the slave role.", m.getType(), sw); } } else { handleMessage(sw, m, null); } } } finally { sw.getListenerReadLock().unlock(); } } }
diff --git a/src/java/org/apache/commons/logging/LogFactory.java b/src/java/org/apache/commons/logging/LogFactory.java index 9fb1a3c..81c1338 100644 --- a/src/java/org/apache/commons/logging/LogFactory.java +++ b/src/java/org/apache/commons/logging/LogFactory.java @@ -1,1432 +1,1432 @@ /* * Copyright 2001-2006 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. */ package org.apache.commons.logging; import java.io.BufferedReader; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URL; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.Enumeration; import java.util.Hashtable; import java.util.Properties; /** * <p>Factory for creating {@link Log} instances, with discovery and * configuration features similar to that employed by standard Java APIs * such as JAXP.</p> * * <p><strong>IMPLEMENTATION NOTE</strong> - This implementation is heavily * based on the SAXParserFactory and DocumentBuilderFactory implementations * (corresponding to the JAXP pluggability APIs) found in Apache Xerces.</p> * * @author Craig R. McClanahan * @author Costin Manolache * @author Richard A. Sitze * @version $Revision$ $Date$ */ public abstract class LogFactory { // ----------------------------------------------------- Manifest Constants /** * The name of the key in the config file used to specify the priority of * that particular config file. The associated value is a floating-point * number; higher values take priority over lower values. */ public static final String PRIORITY_KEY = "priority"; /** * The name of the key in the config file used to specify whether logging * classes should be loaded via the thread context class loader (TCCL), * or not. By default, the TCCL is used. */ public static final String TCCL_KEY = "use_tccl"; /** * The name of the property used to identify the LogFactory implementation * class name. This can be used as a system property, or as an entry in a * configuration properties file. */ public static final String FACTORY_PROPERTY = "org.apache.commons.logging.LogFactory"; /** * The fully qualified class name of the fallback <code>LogFactory</code> * implementation class to use, if no other can be found. */ public static final String FACTORY_DEFAULT = "org.apache.commons.logging.impl.LogFactoryImpl"; /** * The name of the properties file to search for. */ public static final String FACTORY_PROPERTIES = "commons-logging.properties"; /** * JDK1.3+ <a href="http://java.sun.com/j2se/1.3/docs/guide/jar/jar.html#Service%20Provider"> * 'Service Provider' specification</a>. * */ protected static final String SERVICE_ID = "META-INF/services/org.apache.commons.logging.LogFactory"; /** * The name of the property used to enable internal commons-logging * diagnostic output, in order to get information on what logging * implementations are being discovered, what classloaders they * are loaded through, etc. * <p> * If a system property of this name is set then the value is * assumed to be the name of a file. The special strings * STDOUT or STDERR (case-sensitive) indicate output to * System.out and System.err respectively. */ public static final String DIAGNOSTICS_DEST_PROPERTY = "org.apache.commons.logging.diagnostics.dest"; /** * When null (the usual case), no diagnostic output will be * generated by LogFactory or LogFactoryImpl. When non-null, * interesting events will be written to the specified object. */ private static PrintStream diagnosticsStream = null; /** * A string that gets prefixed to every message output by the * logDiagnostic method, so that users can clearly see which * LogFactory class is generating the output. */ private static String diagnosticPrefix; /** * <p>Setting this system property value allows the <code>Hashtable</code> used to store * classloaders to be substituted by an alternative implementation. * </p> * <p> * <strong>Note:</strong> <code>LogFactory</code> will print: * <code><pre> * [ERROR] LogFactory: Load of custom hashtable failed</em> * </code></pre> * to system error and then continue using a standard Hashtable. * </p> * <p> * <strong>Usage:</strong> Set this property when Java is invoked * and <code>LogFactory</code> will attempt to load a new instance * of the given implementation class. * For example, running the following ant scriplet: * <code><pre> * &lt;java classname="${test.runner}" fork="yes" failonerror="${test.failonerror}"&gt; * ... * &lt;sysproperty * key="org.apache.commons.logging.LogFactory.HashtableImpl" * value="org.apache.commons.logging.AltHashtable"/&gt; * &lt;/java&gt; * </pre></code> * will mean that <code>LogFactory</code> will load an instance of * <code>org.apache.commons.logging.AltHashtable</code>. * </p> * <p> * A typical use case is to allow a custom * Hashtable implementation using weak references to be substituted. * This will allow classloaders to be garbage collected without * the need to release them (on 1.3+ JVMs only, of course ;) * </p> */ public static final String HASHTABLE_IMPLEMENTATION_PROPERTY = "org.apache.commons.logging.LogFactory.HashtableImpl"; /** Name used to load the weak hashtable implementation by names */ private static final String WEAK_HASHTABLE_CLASSNAME = "org.apache.commons.logging.impl.WeakHashtable"; /** * A reference to the classloader that loaded this class. This is the * same as LogFactory.class.getClassLoader(). However computing this * value isn't quite as simple as that, as we potentially need to use * AccessControllers etc. It's more efficient to compute it once and * cache it here. */ private static ClassLoader thisClassLoader; // ----------------------------------------------------------- Constructors /** * Protected constructor that is not available for public use. */ protected LogFactory() { } // --------------------------------------------------------- Public Methods /** * Return the configuration attribute with the specified name (if any), * or <code>null</code> if there is no such attribute. * * @param name Name of the attribute to return */ public abstract Object getAttribute(String name); /** * Return an array containing the names of all currently defined * configuration attributes. If there are no such attributes, a zero * length array is returned. */ public abstract String[] getAttributeNames(); /** * Convenience method to derive a name from the specified class and * call <code>getInstance(String)</code> with it. * * @param clazz Class for which a suitable Log name will be derived * * @exception LogConfigurationException if a suitable <code>Log</code> * instance cannot be returned */ public abstract Log getInstance(Class clazz) throws LogConfigurationException; /** * <p>Construct (if necessary) and return a <code>Log</code> instance, * using the factory's current set of configuration attributes.</p> * * <p><strong>NOTE</strong> - Depending upon the implementation of * the <code>LogFactory</code> you are using, the <code>Log</code> * instance you are returned may or may not be local to the current * application, and may or may not be returned again on a subsequent * call with the same name argument.</p> * * @param name Logical name of the <code>Log</code> instance to be * returned (the meaning of this name is only known to the underlying * logging implementation that is being wrapped) * * @exception LogConfigurationException if a suitable <code>Log</code> * instance cannot be returned */ public abstract Log getInstance(String name) throws LogConfigurationException; /** * Release any internal references to previously created {@link Log} * instances returned by this factory. This is useful in environments * like servlet containers, which implement application reloading by * throwing away a ClassLoader. Dangling references to objects in that * class loader would prevent garbage collection. */ public abstract void release(); /** * Remove any configuration attribute associated with the specified name. * If there is no such attribute, no action is taken. * * @param name Name of the attribute to remove */ public abstract void removeAttribute(String name); /** * Set the configuration attribute with the specified name. Calling * this with a <code>null</code> value is equivalent to calling * <code>removeAttribute(name)</code>. * * @param name Name of the attribute to set * @param value Value of the attribute to set, or <code>null</code> * to remove any setting for this attribute */ public abstract void setAttribute(String name, Object value); // ------------------------------------------------------- Static Variables /** * The previously constructed <code>LogFactory</code> instances, keyed by * the <code>ClassLoader</code> with which it was created. */ protected static Hashtable factories = null; /** * Prevously constructed <code>LogFactory</code> instance as in the * <code>factories</code> map. but for the case where * <code>getClassLoader</code> returns <code>null</code>. * This can happen when: * <ul> * <li>using JDK1.1 and the calling code is loaded via the system * classloader (very common)</li> * <li>using JDK1.2+ and the calling code is loaded via the boot * classloader (only likely for embedded systems work).</li> * </ul> * Note that <code>factories</code> is a <i>Hashtable</i> (not a HashMap), * and hashtables don't allow null as a key. */ protected static LogFactory nullClassLoaderFactory = null; /** * Create the hashtable which will be used to store a map of * (context-classloader -> logfactory-object). Version 1.2+ of Java * supports "weak references", allowing a custom Hashtable class * to be used which uses only weak references to its keys. Using weak * references can fix memory leaks on webapp unload in some cases (though * not all). Version 1.1 of Java does not support weak references, so we * must dynamically determine which we are using. And just for fun, this * code also supports the ability for a system property to specify an * arbitrary Hashtable implementation name. * <p> * Note that the correct way to ensure no memory leaks occur is to ensure * that LogFactory.release(contextClassLoader) is called whenever a * webapp is undeployed. */ private static final Hashtable createFactoryStore() { Hashtable result = null; String storeImplementationClass = System.getProperty(HASHTABLE_IMPLEMENTATION_PROPERTY); if (storeImplementationClass == null) { storeImplementationClass = WEAK_HASHTABLE_CLASSNAME; } try { Class implementationClass = Class.forName(storeImplementationClass); result = (Hashtable) implementationClass.newInstance(); } catch (Throwable t) { // ignore if (!WEAK_HASHTABLE_CLASSNAME.equals(storeImplementationClass)) { // if the user's trying to set up a custom implementation, give a clue if (isDiagnosticsEnabled()) { // use internal logging to issue the warning logDiagnostic("[ERROR] LogFactory: Load of custom hashtable failed"); } else { // we *really* want this output, even if diagnostics weren't // explicitly enabled by the user. System.err.println("[ERROR] LogFactory: Load of custom hashtable failed"); } } } if (result == null) { result = new Hashtable(); } return result; } // --------------------------------------------------------- Static Methods /** * <p>Construct (if necessary) and return a <code>LogFactory</code> * instance, using the following ordered lookup procedure to determine * the name of the implementation class to be loaded.</p> * <ul> * <li>The <code>org.apache.commons.logging.LogFactory</code> system * property.</li> * <li>The JDK 1.3 Service Discovery mechanism</li> * <li>Use the properties file <code>commons-logging.properties</code> * file, if found in the class path of this class. The configuration * file is in standard <code>java.util.Properties</code> format and * contains the fully qualified name of the implementation class * with the key being the system property defined above.</li> * <li>Fall back to a default implementation class * (<code>org.apache.commons.logging.impl.LogFactoryImpl</code>).</li> * </ul> * * <p><em>NOTE</em> - If the properties file method of identifying the * <code>LogFactory</code> implementation class is utilized, all of the * properties defined in this file will be set as configuration attributes * on the corresponding <code>LogFactory</code> instance.</p> * * <p><em>NOTE</em> - In a multithreaded environment it is possible * that two different instances will be returned for the same * classloader environment. * </p> * * @exception LogConfigurationException if the implementation class is not * available or cannot be instantiated. */ public static LogFactory getFactory() throws LogConfigurationException { // Identify the class loader we will be using ClassLoader contextClassLoader = getContextClassLoader(); if (contextClassLoader == null) { // This is an odd enough situation to report about. This // output will be a nuisance on JDK1.1, as the system // classloader is null in that environment. logDiagnostic("Context classloader is null."); } // Return any previously registered factory for this class loader LogFactory factory = getCachedFactory(contextClassLoader); if (factory != null) { return factory; } logDiagnostic( "LogFactory requested for the first time for context classloader " + objectId(contextClassLoader)); // Load properties file. // // If the properties file exists, then its contents are used as // "attributes" on the LogFactory implementation class. One particular // property may also control which LogFactory concrete subclass is // used, but only if other discovery mechanisms fail.. // // As the properties file (if it exists) will be used one way or // another in the end we may as well look for it first. Properties props = getConfigurationFile(contextClassLoader, FACTORY_PROPERTIES); // Determine whether we will be using the thread context class loader to // load logging classes or not by checking the loaded properties file (if any). ClassLoader baseClassLoader = contextClassLoader; if (props != null) { String useTCCLStr = props.getProperty(TCCL_KEY); if (useTCCLStr != null) { - if (Boolean.valueOf(useTCCLStr) == Boolean.FALSE) { + if (Boolean.valueOf(useTCCLStr).booleanValue() == false) { // Don't use current context classloader when locating any // LogFactory or Log classes, just use the class that loaded // this abstract class. When this class is deployed in a shared // classpath of a container, it means webapps cannot deploy their // own logging implementations. It also means that it is up to the // implementation whether to load library-specific config files // from the TCCL or not. baseClassLoader = thisClassLoader; } } } // Determine which concrete LogFactory subclass to use. // First, try a global system property logDiagnostic( "Looking for system property [" + FACTORY_PROPERTY + "] to define the LogFactory subclass to use.."); try { String factoryClass = System.getProperty(FACTORY_PROPERTY); if (factoryClass != null) { logDiagnostic( "Creating an instance of LogFactory class " + factoryClass + " as specified by system property " + FACTORY_PROPERTY); factory = newFactory(factoryClass, baseClassLoader, contextClassLoader); } } catch (SecurityException e) { logDiagnostic( "A security exception occurred while trying to create an" + " instance of the custom factory class" + ": [" + e.getMessage().trim() + "]. Trying alternative implementations.."); ; // ignore } // Second, try to find a service by using the JDK1.3 class // discovery mechanism, which involves putting a file with the name // of an interface class in the META-INF/services directory, where the // contents of the file is a single line specifying a concrete class // that implements the desired interface. if (factory == null) { logDiagnostic( "Looking for a resource file of name [" + SERVICE_ID + "] to define the LogFactory subclass to use.."); try { InputStream is = getResourceAsStream(contextClassLoader, SERVICE_ID); if( is != null ) { // This code is needed by EBCDIC and other strange systems. // It's a fix for bugs reported in xerces BufferedReader rd; try { rd = new BufferedReader(new InputStreamReader(is, "UTF-8")); } catch (java.io.UnsupportedEncodingException e) { rd = new BufferedReader(new InputStreamReader(is)); } String factoryClassName = rd.readLine(); rd.close(); if (factoryClassName != null && ! "".equals(factoryClassName)) { logDiagnostic( "Creating an instance of LogFactory class " + factoryClassName + " as specified by file " + SERVICE_ID + " which was present in the path of the context" + " classloader."); factory = newFactory(factoryClassName, baseClassLoader, contextClassLoader ); } } } catch( Exception ex ) { logDiagnostic( "A security exception occurred while trying to create an" + " instance of the custom factory class" + ": [" + ex.getMessage().trim() + "]. Trying alternative implementations.."); ; // ignore } } // Third try a properties file. // If the properties file exists, it'll be read and the properties // used. IMHO ( costin ) System property and JDK1.3 jar service // should be enough for detecting the class name. The properties // should be used to set the attributes ( which may be specific to // the webapp, even if a default logger is set at JVM level by a // system property ) if (factory == null) { logDiagnostic( "Looking for a properties file of name " + FACTORY_PROPERTIES + " to define the LogFactory subclass to use.."); if (props != null) { logDiagnostic( "Properties file found. Looking for property " + FACTORY_PROPERTY + " to define the LogFactory subclass to use.."); String factoryClass = props.getProperty(FACTORY_PROPERTY); if (factoryClass != null) { factory = newFactory(factoryClass, baseClassLoader, contextClassLoader); // what about handling an exception from newFactory?? } } } // Fourth, try the fallback implementation class if (factory == null) { logDiagnostic( "Loading the default LogFactory implementation " + FACTORY_DEFAULT + " via the same classloader that loaded this LogFactory" + " class (ie not looking in the context classloader)."); // Note: unlike the above code which can try to load custom LogFactory // implementations via the TCCL, we don't try to load the default LogFactory // implementation via the context classloader because: // * that can cause problems (see comments in newFactory method) // * no-one should be customising the code of the default class // Yes, we do give up the ability for the child to ship a newer // version of the LogFactoryImpl class and have it used dynamically // by an old LogFactory class in the parent, but that isn't // necessarily a good idea anyway. factory = newFactory(FACTORY_DEFAULT, thisClassLoader, contextClassLoader); } if (factory != null) { /** * Always cache using context class loader. */ cacheFactory(contextClassLoader, factory); if( props!=null ) { Enumeration names = props.propertyNames(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); String value = props.getProperty(name); factory.setAttribute(name, value); } } } return factory; } /** * Convenience method to return a named logger, without the application * having to care about factories. * * @param clazz Class from which a log name will be derived * * @exception LogConfigurationException if a suitable <code>Log</code> * instance cannot be returned */ public static Log getLog(Class clazz) throws LogConfigurationException { return (getFactory().getInstance(clazz)); } /** * Convenience method to return a named logger, without the application * having to care about factories. * * @param name Logical name of the <code>Log</code> instance to be * returned (the meaning of this name is only known to the underlying * logging implementation that is being wrapped) * * @exception LogConfigurationException if a suitable <code>Log</code> * instance cannot be returned */ public static Log getLog(String name) throws LogConfigurationException { return (getFactory().getInstance(name)); } /** * Release any internal references to previously created {@link LogFactory} * instances that have been associated with the specified class loader * (if any), after calling the instance method <code>release()</code> on * each of them. * * @param classLoader ClassLoader for which to release the LogFactory */ public static void release(ClassLoader classLoader) { logDiagnostic("Releasing factory for classloader " + objectId(classLoader)); synchronized (factories) { if (classLoader == null) { if (nullClassLoaderFactory != null) { nullClassLoaderFactory.release(); nullClassLoaderFactory = null; } } else { LogFactory factory = (LogFactory) factories.get(classLoader); if (factory != null) { factory.release(); factories.remove(classLoader); } } } } /** * Release any internal references to previously created {@link LogFactory} * instances, after calling the instance method <code>release()</code> on * each of them. This is useful in environments like servlet containers, * which implement application reloading by throwing away a ClassLoader. * Dangling references to objects in that class loader would prevent * garbage collection. */ public static void releaseAll() { logDiagnostic("Releasing factory for all classloaders."); synchronized (factories) { Enumeration elements = factories.elements(); while (elements.hasMoreElements()) { LogFactory element = (LogFactory) elements.nextElement(); element.release(); } factories.clear(); if (nullClassLoaderFactory != null) { nullClassLoaderFactory.release(); nullClassLoaderFactory = null; } } } // ------------------------------------------------------ Protected Methods /** * Safely get access to the classloader for the specified class. * <p> * Theoretically, calling getClassLoader can throw a security exception, * and so should be done under an AccessController in order to provide * maximum flexibility. However in practice people don't appear to use * security policies that forbid getClassLoader calls. So for the moment * all code is written to call this method rather than Class.getClassLoader, * so that we could put AccessController stuff in this method without any * disruption later if we need to. * <p> * Even when using an AccessController, however, this method can still * throw SecurityException. Commons-logging basically relies on the * ability to access classloaders, ie a policy that forbids all * classloader access will also prevent commons-logging from working: * currently this method will throw an exception preventing the entire app * from starting up. Maybe it would be good to detect this situation and * just disable all commons-logging? Not high priority though - as stated * above, security policies that prevent classloader access aren't common. * */ protected static ClassLoader getClassLoader(Class clazz) { try { return clazz.getClassLoader(); } catch(SecurityException ex) { logDiagnostic( "Unable to get classloader for class " + clazz + " due to security restrictions."); throw ex; } } /** * Calls LogFactory.directGetContextClassLoader under the control of an * AccessController class. This means that java code running under a * security manager that forbids access to ClassLoaders will still work * if this class is given appropriate privileges, even when the caller * doesn't have such privileges. Without using an AccessController, the * the entire call stack must have the privilege before the call is * allowed. * * @return the context classloader associated with the current thread, * or null if security doesn't allow it. * * @throws LogConfigurationException if there was some weird error while * attempting to get the context classloader. * * @throws SecurityException if the current java security policy doesn't * allow this class to access the context classloader. */ protected static ClassLoader getContextClassLoader() throws LogConfigurationException { return (ClassLoader)AccessController.doPrivileged( new PrivilegedAction() { public Object run() { return directGetContextClassLoader(); } }); } /** * Return the thread context class loader if available; otherwise return * null. * <p> * Most/all code should call getContextClassLoader rather than calling * this method directly. * <p> * The thread context class loader is available for JDK 1.2 * or later, if certain security conditions are met. * <p> * Note that no internal logging is done within this method because * this method is called every time LogFactory.getLogger() is called, * and we don't want too much output generated here. * * @exception LogConfigurationException if a suitable class loader * cannot be identified. * * @exception SecurityException if the java security policy forbids * access to the context classloader from one of the classes in the * current call stack. */ protected static ClassLoader directGetContextClassLoader() throws LogConfigurationException { ClassLoader classLoader = null; try { // Are we running on a JDK 1.2 or later system? Method method = Thread.class.getMethod("getContextClassLoader", (Class[]) null); // Get the thread context class loader (if there is one) try { classLoader = (ClassLoader)method.invoke(Thread.currentThread(), (Object[]) null); } catch (IllegalAccessException e) { throw new LogConfigurationException ("Unexpected IllegalAccessException", e); } catch (InvocationTargetException e) { /** * InvocationTargetException is thrown by 'invoke' when * the method being invoked (getContextClassLoader) throws * an exception. * * getContextClassLoader() throws SecurityException when * the context class loader isn't an ancestor of the * calling class's class loader, or if security * permissions are restricted. * * In the first case (not related), we want to ignore and * keep going. We cannot help but also ignore the second * with the logic below, but other calls elsewhere (to * obtain a class loader) will trigger this exception where * we can make a distinction. */ if (e.getTargetException() instanceof SecurityException) { ; // ignore } else { // Capture 'e.getTargetException()' exception for details // alternate: log 'e.getTargetException()', and pass back 'e'. throw new LogConfigurationException ("Unexpected InvocationTargetException", e.getTargetException()); } } } catch (NoSuchMethodException e) { // Assume we are running on JDK 1.1 classLoader = getClassLoader(LogFactory.class); // We deliberately don't log a message here to outputStream; // this message would be output for every call to LogFactory.getLog() // when running on JDK1.1 // // if (outputStream != null) { // outputStream.println( // "Method Thread.getContextClassLoader does not exist;" // + " assuming this is JDK 1.1, and that the context" // + " classloader is the same as the class that loaded" // + " the concrete LogFactory class."); // } } // Return the selected class loader return classLoader; } /** * Check cached factories (keyed by contextClassLoader) * * @param contextClassLoader is the context classloader associated * with the current thread. This allows separate LogFactory objects * per component within a container, provided each component has * a distinct context classloader set. This parameter may be null * in JDK1.1, and in embedded systems where jcl-using code is * placed in the bootclasspath. * * @return the factory associated with the specified classloader if * one has previously been created, or null if this is the first time * we have seen this particular classloader. */ private static LogFactory getCachedFactory(ClassLoader contextClassLoader) { LogFactory factory = null; if (contextClassLoader == null) { // We have to handle this specially, as factories is a Hashtable // and those don't accept null as a key value. // // nb: nullClassLoaderFactory might be null. That's ok. factory = nullClassLoaderFactory; } else { factory = (LogFactory) factories.get(contextClassLoader); } return factory; } /** * Remember this factory, so later calls to LogFactory.getCachedFactory * can return the previously created object (together with all its * cached Log objects). * * @param classLoader should be the current context classloader. Note that * this can be null under some circumstances; this is ok. * * @param factory should be the factory to cache. This should never be null. */ private static void cacheFactory(ClassLoader classLoader, LogFactory factory) { // Ideally we would assert(factory != null) here. However reporting // errors from within a logging implementation is a little tricky! if (factory != null) { if (classLoader == null) { nullClassLoaderFactory = factory; } else { factories.put(classLoader, factory); } } } /** * Return a new instance of the specified <code>LogFactory</code> * implementation class, loaded by the specified class loader. * If that fails, try the class loader used to load this * (abstract) LogFactory. * <p> * <h2>ClassLoader conflicts</h2> * Note that there can be problems if the specified ClassLoader is not the * same as the classloader that loaded this class, ie when loading a * concrete LogFactory subclass via a context classloader. * <p> * The problem is the same one that can occur when loading a concrete Log * subclass via a context classloader. * <p> * The problem occurs when code running in the context classloader calls * class X which was loaded via a parent classloader, and class X then calls * LogFactory.getFactory (either directly or via LogFactory.getLog). Because * class X was loaded via the parent, it binds to LogFactory loaded via * the parent. When the code in this method finds some LogFactoryYYYY * class in the child (context) classloader, and there also happens to be a * LogFactory class defined in the child classloader, then LogFactoryYYYY * will be bound to LogFactory@childloader. It cannot be cast to * LogFactory@parentloader, ie this method cannot return the object as * the desired type. Note that it doesn't matter if the LogFactory class * in the child classloader is identical to the LogFactory class in the * parent classloader, they are not compatible. * <p> * The solution taken here is to simply print out an error message when * this occurs then throw an exception. The deployer of the application * must ensure they remove all occurrences of the LogFactory class from * the child classloader in order to resolve the issue. Note that they * do not have to move the custom LogFactory subclass; that is ok as * long as the only LogFactory class it can find to bind to is in the * parent classloader. * <p> * @param factoryClass Fully qualified name of the <code>LogFactory</code> * implementation class * @param classLoader ClassLoader from which to load this class * @param contextClassLoader is the context that this new factory will * manage logging for. * * @exception LogConfigurationException if a suitable instance * cannot be created */ protected static LogFactory newFactory(final String factoryClass, final ClassLoader classLoader, final ClassLoader contextClassLoader) throws LogConfigurationException { Object result = AccessController.doPrivileged( new PrivilegedAction() { public Object run() { return createFactory(factoryClass, classLoader); } }); if (result instanceof LogConfigurationException) { LogConfigurationException ex = (LogConfigurationException) result; logDiagnostic( "An error occurred while loading the factory class:" + ex.getMessage()); throw ex; } logDiagnostic( "Created object " + objectId(result) + " to manage classloader " + objectId(contextClassLoader)); return (LogFactory)result; } /** * Method provided for backwards compatibility; see newFactory version that * takes 3 parameters. * <p> * This method would only ever be called in some rather odd situation. * Note that this method is static, so overriding in a subclass doesn't * have any effect unless this method is called from a method in that * subclass. However this method only makes sense to use from the * getFactory method, and as that is almost always invoked via * LogFactory.getFactory, any custom definition in a subclass would be * pointless. Only a class with a custom getFactory method, then invoked * directly via CustomFactoryImpl.getFactory or similar would ever call * this. Anyway, it's here just in case, though the "managed class loader" * value output to the diagnostics will not report the correct value. */ protected static LogFactory newFactory(final String factoryClass, final ClassLoader classLoader) { return newFactory(factoryClass, classLoader, null); } /** * Implements the operations described in the javadoc for newFactory. * * @param factoryClass * @param classLoader * * @return either a LogFactory object or a LogConfigurationException object. */ protected static Object createFactory(String factoryClass, ClassLoader classLoader) { // This will be used to diagnose bad configurations // and allow a useful message to be sent to the user Class logFactoryClass = null; try { if (classLoader != null) { try { // First the given class loader param (thread class loader) // Warning: must typecast here & allow exception // to be generated/caught & recast properly. logFactoryClass = classLoader.loadClass(factoryClass); if (LogFactory.class.isAssignableFrom(logFactoryClass)) { logDiagnostic( "loaded class " + logFactoryClass.getName() + " from classloader " + objectId(classLoader)); } else { logDiagnostic( "Factory class " + logFactoryClass.getName() + " loaded from classloader " + objectId(classLoader) + " does not extend " + LogFactory.class.getName() + " as loaded by this classloader."); } return (LogFactory) logFactoryClass.newInstance(); } catch (ClassNotFoundException ex) { if (classLoader == thisClassLoader) { // Nothing more to try, onwards. logDiagnostic( "Unable to locate any class called " + factoryClass + " via classloader " + objectId(classLoader)); throw ex; } // ignore exception, continue } catch (NoClassDefFoundError e) { if (classLoader == thisClassLoader) { // Nothing more to try, onwards. logDiagnostic( "Class " + factoryClass + " cannot be loaded" + " via classloader " + objectId(classLoader) + ": it depends on some other class that cannot" + " be found."); throw e; } // ignore exception, continue } catch(ClassCastException e) { if (classLoader == thisClassLoader) { // This cast exception is not due to classloader issues; // the specified class *really* doesn't extend the // required LogFactory base class. logDiagnostic( "Class " + factoryClass + " really does not extend " + LogFactory.class.getName()); throw e; } // Ignore exception, continue } } /* At this point, either classLoader == null, OR * classLoader was unable to load factoryClass. * * In either case, we call Class.forName, which is equivalent * to LogFactory.class.getClassLoader.load(name), ie we ignore * the classloader parameter the caller passed, and fall back * to trying the classloader associated with this class. See the * javadoc for the newFactory method for more info on the * consequences of this. * * Notes: * * LogFactory.class.getClassLoader() may return 'null' * if LogFactory is loaded by the bootstrap classloader. */ // Warning: must typecast here & allow exception // to be generated/caught & recast properly. logDiagnostic( "Unable to load factory class via classloader " + objectId(classLoader) + ": trying the classloader associated with this LogFactory."); logFactoryClass = Class.forName(factoryClass); return (LogFactory) logFactoryClass.newInstance(); } catch (Exception e) { // Check to see if we've got a bad configuration logDiagnostic("Unable to create logfactory instance."); if (logFactoryClass != null && !LogFactory.class.isAssignableFrom(logFactoryClass)) { return new LogConfigurationException( "The chosen LogFactory implementation does not extend LogFactory." + " Please check your configuration.", e); } return new LogConfigurationException(e); } } /** * Applets may run in an environment where accessing resources of a loader is * a secure operation, but where the commons-logging library has explicitly * been granted permission for that operation. In this case, we need to * run the operation using an AccessController. */ private static InputStream getResourceAsStream(final ClassLoader loader, final String name) { return (InputStream)AccessController.doPrivileged( new PrivilegedAction() { public Object run() { if (loader != null) { return loader.getResourceAsStream(name); } else { return ClassLoader.getSystemResourceAsStream(name); } } }); } /** * Given a filename, return an enumeration of URLs pointing to * all the occurrences of that filename in the classpath. * <p> * This is just like ClassLoader.getResources except that the * operation is done under an AccessController so that this method will * succeed when this jarfile is privileged but the caller is not. * This method must therefore remain private to avoid security issues. * <p> * If no instances are found, an Enumeration is returned whose * hasMoreElements method returns false (ie an "empty" enumeration). * If resources could not be listed for some reason, null is returned. */ private static Enumeration getResources(final ClassLoader loader, final String name) { PrivilegedAction action = new PrivilegedAction() { public Object run() { try { if (loader != null) { return loader.getResources(name); } else { return ClassLoader.getSystemResources(name); } } catch(IOException e) { logDiagnostic( "Exception while trying to find configuration file " + name + ":" + e.getMessage()); return null; } } }; Object result = AccessController.doPrivileged(action); return (Enumeration) result; } /** * Given a URL that refers to a .properties file, load that file. * This is done under an AccessController so that this method will * succeed when this jarfile is privileged but the caller is not. * This method must therefore remain private to avoid security issues. * <p> * Null is returned if the URL cannot be opened. */ private static Properties getProperties(final URL url) { PrivilegedAction action = new PrivilegedAction() { public Object run() { try { InputStream stream = url.openStream(); if (stream != null) { Properties props = new Properties(); props.load(stream); stream.close(); return props; } } catch(IOException e) { logDiagnostic("Unable to read URL " + url); } return null; } }; return (Properties) AccessController.doPrivileged(action); } /** * Locate a user-provided configuration file. * <p> * The classpath of the specified classLoader (usually the context classloader) * is searched for properties files of the specified name. If none is found, * null is returned. If more than one is found, then the file with the greatest * value for its PRIORITY property is returned. If multiple files have the * same PRIORITY value then the first in the classpath is returned. * <p> * This differs from the 1.0.x releases; those always use the first one found. * However as the priority is a new field, this change is backwards compatible. * <p> * The purpose of the priority field is to allow a webserver administrator to * override logging settings in all webapps by placing a commons-logging.properties * file in a shared classpath location with a priority > 0; this overrides any * commons-logging.properties files without priorities which are in the * webapps. Webapps can also use explicit priorities to override a configuration * file in the shared classpath if needed. */ private static final Properties getConfigurationFile( ClassLoader classLoader, String fileName) { Properties props = null; double priority = 0.0; try { Enumeration urls = getResources(classLoader, fileName); if (urls == null) { return null; } while (urls.hasMoreElements()) { URL url = (URL) urls.nextElement(); Properties newProps = getProperties(url); if (newProps != null) { if (props == null) { props = newProps; } else { String newPriorityStr = newProps.getProperty(PRIORITY_KEY); if (newPriorityStr != null) { double newPriority = Double.valueOf(newPriorityStr).doubleValue(); if (newPriority > priority) { props = newProps; priority = newPriority; } } } } } } catch (SecurityException e) { logDiagnostic("SecurityException thrown"); } return props; } /** * Determines whether the user wants internal diagnostic output. If so, * returns an appropriate writer object. Users can enable diagnostic * output by setting the system property named OUTPUT_PROPERTY to * a filename, or the special values STDOUT or STDERR. */ private static void initDiagnostics() { String dest; try { dest = System.getProperty(DIAGNOSTICS_DEST_PROPERTY); if (dest == null) { return; } } catch(SecurityException ex) { // We must be running in some very secure environment. // We just have to assume output is not wanted.. return; } if (dest.equals("STDOUT")) { diagnosticsStream = System.out; } else if (dest.equals("STDERR")) { diagnosticsStream = System.err; } else { try { // open the file in append mode FileOutputStream fos = new FileOutputStream(dest, true); diagnosticsStream = new PrintStream(fos); } catch(IOException ex) { // We should report this to the user - but how? return; } } // In order to avoid confusion where multiple instances of JCL are // being used via different classloaders within the same app, we // ensure each logged message has a prefix of form // LogFactory@12345: Class clazz = LogFactory.class; String classLoaderName; try { ClassLoader classLoader = thisClassLoader; if (thisClassLoader == null) { classLoaderName = "BOOTLOADER"; } else { classLoaderName = String.valueOf(System.identityHashCode(classLoader)); } } catch(SecurityException e) { classLoaderName = "UNKNOWN"; } diagnosticPrefix = clazz.getName() + "@" + classLoaderName + ": "; } /** * Indicates true if the user has enabled internal logging. * <p> * By the way, sorry for the incorrect grammar, but calling this method * areDiagnosticsEnabled just isn't java beans style. * * @return true if calls to logDiagnostic will have any effect. */ protected static boolean isDiagnosticsEnabled() { return diagnosticsStream != null; } /** * Write the specified message to the internal logging destination. * <p> * Note that this method is private; concrete subclasses of this class * should not call it because the diagnosticPrefix string this * method puts in front of all its messages is LogFactory@...., * while subclasses should put SomeSubClass@... * <p> * Subclasses should instead compute their own prefix, then call * logRawDiagnostic. Note that calling isDiagnosticsEnabled is * fine for subclasses. * <p> * Note that it is safe to call this method before initDiagnostics * is called; any output will just be ignored (as isDiagnosticsEnabled * will return false). * * @param msg is the diagnostic message to be output. */ private static final void logDiagnostic(String msg) { if (diagnosticsStream != null) { diagnosticsStream.print(diagnosticPrefix); diagnosticsStream.println(msg); diagnosticsStream.flush(); } } /** * Write the specified message to the internal logging destination. * * @param msg is the diagnostic message to be output. */ protected static final void logRawDiagnostic(String msg) { if (diagnosticsStream != null) { diagnosticsStream.println(msg); diagnosticsStream.flush(); } } /** * Generate useful diagnostics regarding the classloader tree for * the specified class. * <p> * As an example, if the specified class was loaded via a webapp's * classloader, then you may get the following output: * <pre> * Class com.acme.Foo was loaded via classloader 11111 * ClassLoader tree: 11111 -> 22222 (SYSTEM) -> 33333 -> BOOT * </pre> * <p> * This method returns immediately if isDiagnosticsEnabled() * returns false. * * @param clazz is the class whose classloader + tree are to be * output. */ private static void logClassLoaderTree(Class clazz) { if (!isDiagnosticsEnabled()) { return; } String className = clazz.getName(); ClassLoader classLoader; ClassLoader systemClassLoader; try { classLoader = getClassLoader(clazz); } catch(SecurityException ex) { // not much useful diagnostics we can print here! logDiagnostic( "Security forbids determining the classloader for " + className); return; } logDiagnostic( "Class " + className + " was loaded via classloader " + objectId(classLoader)); try { systemClassLoader = ClassLoader.getSystemClassLoader(); } catch(SecurityException ex) { logDiagnostic( "Security forbids determining the system classloader."); return; } if (classLoader != null) { StringBuffer buf = new StringBuffer("ClassLoader tree:"); for(;;) { buf.append(objectId(classLoader)); if (classLoader == systemClassLoader) { buf.append(" (SYSTEM) "); } try { classLoader = classLoader.getParent(); } catch(SecurityException ex) { buf.append(" --> SECRET"); break; } buf.append(" --> "); if (classLoader == null) { buf.append("BOOT"); break; } } logDiagnostic(buf.toString()); } } /** * Returns a string that uniquely identifies the specified object, including * its class. * <p> * The returned string is of form "classname@hashcode", ie is the same as * the return value of the Object.toString() method, but works even when * the specified object's class has overidden the toString method. * * @param o may be null. * @return a string of form classname@hashcode, or "null" if param o is null. */ public static String objectId(Object o) { if (o == null) { return "null"; } else { return o.getClass().getName() + "@" + System.identityHashCode(o); } } // ---------------------------------------------------------------------- // Static initialiser block to perform initialisation at class load time. // // We can't do this in the class constructor, as there are many // static methods on this class that can be called before any // LogFactory instances are created, and they depend upon this // stuff having been set up. // // Note that this block must come after any variable declarations used // by any methods called from this block, as we want any static initialiser // associated with the variable to run first. If static initialisers for // variables run after this code, then (a) their value might be needed // by methods called from here, and (b) they might *override* any value // computed here! // // So the wisest thing to do is just to place this code at the very end // of the class file. // ---------------------------------------------------------------------- static { // note: it's safe to call methods before initDiagnostics. thisClassLoader = getClassLoader(LogFactory.class); initDiagnostics(); logClassLoaderTree(LogFactory.class); factories = createFactoryStore(); } }
true
true
public static LogFactory getFactory() throws LogConfigurationException { // Identify the class loader we will be using ClassLoader contextClassLoader = getContextClassLoader(); if (contextClassLoader == null) { // This is an odd enough situation to report about. This // output will be a nuisance on JDK1.1, as the system // classloader is null in that environment. logDiagnostic("Context classloader is null."); } // Return any previously registered factory for this class loader LogFactory factory = getCachedFactory(contextClassLoader); if (factory != null) { return factory; } logDiagnostic( "LogFactory requested for the first time for context classloader " + objectId(contextClassLoader)); // Load properties file. // // If the properties file exists, then its contents are used as // "attributes" on the LogFactory implementation class. One particular // property may also control which LogFactory concrete subclass is // used, but only if other discovery mechanisms fail.. // // As the properties file (if it exists) will be used one way or // another in the end we may as well look for it first. Properties props = getConfigurationFile(contextClassLoader, FACTORY_PROPERTIES); // Determine whether we will be using the thread context class loader to // load logging classes or not by checking the loaded properties file (if any). ClassLoader baseClassLoader = contextClassLoader; if (props != null) { String useTCCLStr = props.getProperty(TCCL_KEY); if (useTCCLStr != null) { if (Boolean.valueOf(useTCCLStr) == Boolean.FALSE) { // Don't use current context classloader when locating any // LogFactory or Log classes, just use the class that loaded // this abstract class. When this class is deployed in a shared // classpath of a container, it means webapps cannot deploy their // own logging implementations. It also means that it is up to the // implementation whether to load library-specific config files // from the TCCL or not. baseClassLoader = thisClassLoader; } } } // Determine which concrete LogFactory subclass to use. // First, try a global system property logDiagnostic( "Looking for system property [" + FACTORY_PROPERTY + "] to define the LogFactory subclass to use.."); try { String factoryClass = System.getProperty(FACTORY_PROPERTY); if (factoryClass != null) { logDiagnostic( "Creating an instance of LogFactory class " + factoryClass + " as specified by system property " + FACTORY_PROPERTY); factory = newFactory(factoryClass, baseClassLoader, contextClassLoader); } } catch (SecurityException e) { logDiagnostic( "A security exception occurred while trying to create an" + " instance of the custom factory class" + ": [" + e.getMessage().trim() + "]. Trying alternative implementations.."); ; // ignore } // Second, try to find a service by using the JDK1.3 class // discovery mechanism, which involves putting a file with the name // of an interface class in the META-INF/services directory, where the // contents of the file is a single line specifying a concrete class // that implements the desired interface. if (factory == null) { logDiagnostic( "Looking for a resource file of name [" + SERVICE_ID + "] to define the LogFactory subclass to use.."); try { InputStream is = getResourceAsStream(contextClassLoader, SERVICE_ID); if( is != null ) { // This code is needed by EBCDIC and other strange systems. // It's a fix for bugs reported in xerces BufferedReader rd; try { rd = new BufferedReader(new InputStreamReader(is, "UTF-8")); } catch (java.io.UnsupportedEncodingException e) { rd = new BufferedReader(new InputStreamReader(is)); } String factoryClassName = rd.readLine(); rd.close(); if (factoryClassName != null && ! "".equals(factoryClassName)) { logDiagnostic( "Creating an instance of LogFactory class " + factoryClassName + " as specified by file " + SERVICE_ID + " which was present in the path of the context" + " classloader."); factory = newFactory(factoryClassName, baseClassLoader, contextClassLoader ); } } } catch( Exception ex ) { logDiagnostic( "A security exception occurred while trying to create an" + " instance of the custom factory class" + ": [" + ex.getMessage().trim() + "]. Trying alternative implementations.."); ; // ignore } } // Third try a properties file. // If the properties file exists, it'll be read and the properties // used. IMHO ( costin ) System property and JDK1.3 jar service // should be enough for detecting the class name. The properties // should be used to set the attributes ( which may be specific to // the webapp, even if a default logger is set at JVM level by a // system property ) if (factory == null) { logDiagnostic( "Looking for a properties file of name " + FACTORY_PROPERTIES + " to define the LogFactory subclass to use.."); if (props != null) { logDiagnostic( "Properties file found. Looking for property " + FACTORY_PROPERTY + " to define the LogFactory subclass to use.."); String factoryClass = props.getProperty(FACTORY_PROPERTY); if (factoryClass != null) { factory = newFactory(factoryClass, baseClassLoader, contextClassLoader); // what about handling an exception from newFactory?? } } } // Fourth, try the fallback implementation class if (factory == null) { logDiagnostic( "Loading the default LogFactory implementation " + FACTORY_DEFAULT + " via the same classloader that loaded this LogFactory" + " class (ie not looking in the context classloader)."); // Note: unlike the above code which can try to load custom LogFactory // implementations via the TCCL, we don't try to load the default LogFactory // implementation via the context classloader because: // * that can cause problems (see comments in newFactory method) // * no-one should be customising the code of the default class // Yes, we do give up the ability for the child to ship a newer // version of the LogFactoryImpl class and have it used dynamically // by an old LogFactory class in the parent, but that isn't // necessarily a good idea anyway. factory = newFactory(FACTORY_DEFAULT, thisClassLoader, contextClassLoader); } if (factory != null) { /** * Always cache using context class loader. */ cacheFactory(contextClassLoader, factory); if( props!=null ) { Enumeration names = props.propertyNames(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); String value = props.getProperty(name); factory.setAttribute(name, value); } } } return factory; }
public static LogFactory getFactory() throws LogConfigurationException { // Identify the class loader we will be using ClassLoader contextClassLoader = getContextClassLoader(); if (contextClassLoader == null) { // This is an odd enough situation to report about. This // output will be a nuisance on JDK1.1, as the system // classloader is null in that environment. logDiagnostic("Context classloader is null."); } // Return any previously registered factory for this class loader LogFactory factory = getCachedFactory(contextClassLoader); if (factory != null) { return factory; } logDiagnostic( "LogFactory requested for the first time for context classloader " + objectId(contextClassLoader)); // Load properties file. // // If the properties file exists, then its contents are used as // "attributes" on the LogFactory implementation class. One particular // property may also control which LogFactory concrete subclass is // used, but only if other discovery mechanisms fail.. // // As the properties file (if it exists) will be used one way or // another in the end we may as well look for it first. Properties props = getConfigurationFile(contextClassLoader, FACTORY_PROPERTIES); // Determine whether we will be using the thread context class loader to // load logging classes or not by checking the loaded properties file (if any). ClassLoader baseClassLoader = contextClassLoader; if (props != null) { String useTCCLStr = props.getProperty(TCCL_KEY); if (useTCCLStr != null) { if (Boolean.valueOf(useTCCLStr).booleanValue() == false) { // Don't use current context classloader when locating any // LogFactory or Log classes, just use the class that loaded // this abstract class. When this class is deployed in a shared // classpath of a container, it means webapps cannot deploy their // own logging implementations. It also means that it is up to the // implementation whether to load library-specific config files // from the TCCL or not. baseClassLoader = thisClassLoader; } } } // Determine which concrete LogFactory subclass to use. // First, try a global system property logDiagnostic( "Looking for system property [" + FACTORY_PROPERTY + "] to define the LogFactory subclass to use.."); try { String factoryClass = System.getProperty(FACTORY_PROPERTY); if (factoryClass != null) { logDiagnostic( "Creating an instance of LogFactory class " + factoryClass + " as specified by system property " + FACTORY_PROPERTY); factory = newFactory(factoryClass, baseClassLoader, contextClassLoader); } } catch (SecurityException e) { logDiagnostic( "A security exception occurred while trying to create an" + " instance of the custom factory class" + ": [" + e.getMessage().trim() + "]. Trying alternative implementations.."); ; // ignore } // Second, try to find a service by using the JDK1.3 class // discovery mechanism, which involves putting a file with the name // of an interface class in the META-INF/services directory, where the // contents of the file is a single line specifying a concrete class // that implements the desired interface. if (factory == null) { logDiagnostic( "Looking for a resource file of name [" + SERVICE_ID + "] to define the LogFactory subclass to use.."); try { InputStream is = getResourceAsStream(contextClassLoader, SERVICE_ID); if( is != null ) { // This code is needed by EBCDIC and other strange systems. // It's a fix for bugs reported in xerces BufferedReader rd; try { rd = new BufferedReader(new InputStreamReader(is, "UTF-8")); } catch (java.io.UnsupportedEncodingException e) { rd = new BufferedReader(new InputStreamReader(is)); } String factoryClassName = rd.readLine(); rd.close(); if (factoryClassName != null && ! "".equals(factoryClassName)) { logDiagnostic( "Creating an instance of LogFactory class " + factoryClassName + " as specified by file " + SERVICE_ID + " which was present in the path of the context" + " classloader."); factory = newFactory(factoryClassName, baseClassLoader, contextClassLoader ); } } } catch( Exception ex ) { logDiagnostic( "A security exception occurred while trying to create an" + " instance of the custom factory class" + ": [" + ex.getMessage().trim() + "]. Trying alternative implementations.."); ; // ignore } } // Third try a properties file. // If the properties file exists, it'll be read and the properties // used. IMHO ( costin ) System property and JDK1.3 jar service // should be enough for detecting the class name. The properties // should be used to set the attributes ( which may be specific to // the webapp, even if a default logger is set at JVM level by a // system property ) if (factory == null) { logDiagnostic( "Looking for a properties file of name " + FACTORY_PROPERTIES + " to define the LogFactory subclass to use.."); if (props != null) { logDiagnostic( "Properties file found. Looking for property " + FACTORY_PROPERTY + " to define the LogFactory subclass to use.."); String factoryClass = props.getProperty(FACTORY_PROPERTY); if (factoryClass != null) { factory = newFactory(factoryClass, baseClassLoader, contextClassLoader); // what about handling an exception from newFactory?? } } } // Fourth, try the fallback implementation class if (factory == null) { logDiagnostic( "Loading the default LogFactory implementation " + FACTORY_DEFAULT + " via the same classloader that loaded this LogFactory" + " class (ie not looking in the context classloader)."); // Note: unlike the above code which can try to load custom LogFactory // implementations via the TCCL, we don't try to load the default LogFactory // implementation via the context classloader because: // * that can cause problems (see comments in newFactory method) // * no-one should be customising the code of the default class // Yes, we do give up the ability for the child to ship a newer // version of the LogFactoryImpl class and have it used dynamically // by an old LogFactory class in the parent, but that isn't // necessarily a good idea anyway. factory = newFactory(FACTORY_DEFAULT, thisClassLoader, contextClassLoader); } if (factory != null) { /** * Always cache using context class loader. */ cacheFactory(contextClassLoader, factory); if( props!=null ) { Enumeration names = props.propertyNames(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); String value = props.getProperty(name); factory.setAttribute(name, value); } } } return factory; }
diff --git a/src/no/runsafe/framework/server/player/RunsafeAmbiguousPlayer.java b/src/no/runsafe/framework/server/player/RunsafeAmbiguousPlayer.java index 21583c2c..14597e07 100644 --- a/src/no/runsafe/framework/server/player/RunsafeAmbiguousPlayer.java +++ b/src/no/runsafe/framework/server/player/RunsafeAmbiguousPlayer.java @@ -1,20 +1,21 @@ package no.runsafe.framework.server.player; import org.bukkit.OfflinePlayer; import java.util.List; public class RunsafeAmbiguousPlayer extends RunsafePlayer { public RunsafeAmbiguousPlayer(OfflinePlayer toWrap, List<String> ambiguous) { super(toWrap); + ambiguity = ambiguous; } public List<String> getAmbiguity() { return ambiguity; } private List<String> ambiguity; }
true
true
public RunsafeAmbiguousPlayer(OfflinePlayer toWrap, List<String> ambiguous) { super(toWrap); }
public RunsafeAmbiguousPlayer(OfflinePlayer toWrap, List<String> ambiguous) { super(toWrap); ambiguity = ambiguous; }
diff --git a/src/ca/eandb/util/args/ArgumentProcessor.java b/src/ca/eandb/util/args/ArgumentProcessor.java index 0f1ba1e..abb01a1 100644 --- a/src/ca/eandb/util/args/ArgumentProcessor.java +++ b/src/ca/eandb/util/args/ArgumentProcessor.java @@ -1,545 +1,548 @@ /* * Copyright (c) 2008 Bradley W. Kimmel * * 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 ca.eandb.util.args; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Queue; import ca.eandb.util.ArrayQueue; import ca.eandb.util.UnexpectedException; /** * An object that processes command line arguments. * @author Brad Kimmel */ public final class ArgumentProcessor<T> implements Command<T> { /** * A <code>Map</code> for looking up option <code>Command</code> options, * keyed by the option name. A command line argument of the form * <code>--&lt;option_name&gt;</code> is used to trigger a given option * handler. * * The difference between an option and a command (stored in * {@link #commands} is that multiple options may be specified. Only a * single command may be specified. When a command is encountered, control * is tranferred to that command and no further options or commands are * processed by this <code>ArgumentProcessor</code>. */ private final Map<String, Command<? super T>> options = new HashMap<String, Command<? super T>>(); /** * A <code>Map</code> for looking up the full option name associated with * a given single character shortcut (e.g., <code>V</code> may be a * shortcut for <code>verbose</code>). */ private final Map<Character, String> shortcuts = new HashMap<Character, String>(); /** * A <code>Map</code> for looking up <code>Command</code> options, keyed * by the command name. A command line option of the form * <code>&lt;command_name&gt;</code> is used to trigger a given command * handler. * * The difference between an option (stored in {@link #options} and a * command (stored in {@link #commands} is that multiple options may be * specified. Only a single command may be specified. When a command is * encountered, control is tranferred to that command and no further * options or commands are processed by this * <code>ArgumentProcessor</code>. */ private final Map<String, Command<? super T>> commands = new HashMap<String, Command<? super T>>(); /** * The <code>Command</code> to execute if the end of the command line * options is reached without a <code>Command</code> being executed, or if * an unrecognized command is encountered. */ private Command<? super T> defaultCommand = null; /** * The <code>Command</code> to execute to enter shell mode. */ private Command<? super T> shellCommand = null; /** * Creates a new <code>ArgumentProcessor</code>. * @param shell A value indicating whether a shell should be started if no * commands are provided on the command line. */ public ArgumentProcessor(boolean shell) { addCommand("help", new HelpCommand()); if (shell) { shellCommand = new ShellCommand(); } } /** * Creates a new <code>ArgumentProcessor</code>. */ public ArgumentProcessor() { this(false); } /** * A <code>Command</code> that prints a list of options and commands * registered with this <code>ArgumentProcessor</code> to the console. * @author Brad Kimmel */ private class HelpCommand implements Command<Object> { /* (non-Javadoc) * @see ca.eandb.util.args.Command#process(java.util.Queue, java.lang.Object) */ public void process(Queue<String> argq, Object state) { System.out.println("Usage: <java_cmd> [ <options> ] <command> <args>"); System.out.println(); System.out.println("Options:"); for (Map.Entry<Character, String> entry : shortcuts.entrySet()) { System.out.printf("-%c, --%s", entry.getKey(), entry.getValue()); System.out.println(); } System.out.println(); System.out.println("Commands:"); for (String cmd : commands.keySet()) { System.out.println(cmd); } } } /** * A <code>Command</code> for starting a shell. * @author Brad */ private class ShellCommand implements Command<T> { /** A flag indicating whether the shell should exit. */ private boolean exit = false; /** A flag indicating whether the shell is currently running. */ private boolean running = false; /* (non-Javadoc) * @see ca.eandb.util.args.Command#process(java.util.Queue, java.lang.Object) */ public void process(Queue<String> argq, T state) { if (running) { return; } running = true; addCommand("exit", new Command<Object>() { public void process(Queue<String> argq, Object state) { exit = true; } }); BufferedReader shell = new BufferedReader(new InputStreamReader(System.in)); do { System.out.print(">> "); String cmd = null; try { cmd = shell.readLine(); } catch (IOException e) { e.printStackTrace(); } if (cmd == null) { break; } String[] args = cmd.trim().split("\\s+"); try { ArgumentProcessor.this.process(args, state); } catch (Exception e) { e.printStackTrace(); } } while (!exit); running = false; } } /** * Creates an option for the specified field and type. * @param fieldName The name of the field to create the option handler for. * @param type The type of the field to create the option handler for. * @return The <code>Command</code> to process the option. */ private Command<? super T> createOption(String fieldName, Class<?> type) { if (type == Integer.class || type == int.class) { return new IntegerFieldOption<T>(fieldName); } else if (type == Boolean.class || type == boolean.class) { return new BooleanFieldOption<T>(fieldName); } else if (type == String.class) { return new StringFieldOption<T>(fieldName); } else if (type == Double.class || type == double.class) { return new DoubleFieldOption<T>(fieldName); } else if (type == File.class) { return new FileFieldOption<T>(fieldName); } throw new IllegalArgumentException("Cannot create option for parameter of type `" + type.getName() + "'"); } /** * Adds an option for the specified field having the given * {@link OptionArgument} annotation. * @param field The <code>Field</code> to add the option for. * @param annotation The <code>OptionArgument</code> annotation on the * field. */ private void processField(Field field, OptionArgument annotation) { String name = field.getName(); Class<?> type = field.getType(); String key = annotation.value(); if (key.isEmpty()) { key = name; } char shortKey = annotation.shortKey(); if (shortKey == '\0') { shortKey = key.charAt(0); } Command<? super T> option = createOption(name, type); addOption(key, shortKey, option); } /** * Adds a command that passes control to the specified field. * @param field The <code>Field</code> to pass control to. * @param annotation The <code>CommandArgument</code> annotation on the * field. */ private void processField(final Field field, CommandArgument annotation) { String name = field.getName(); Class<?> type = field.getType(); String key = annotation.value(); if (key.isEmpty()) { key = name; } final ArgumentProcessor<Object> argProcessor = new ArgumentProcessor<Object>(); argProcessor.processAnnotations(type); addCommand(key, new Command<T>() { public void process(Queue<String> argq, T state) { try { Object value = field.get(state); argProcessor.process(argq, value); } catch (IllegalArgumentException e) { throw new UnexpectedException(e); } catch (IllegalAccessException e) { throw new UnexpectedException(e); } } }); } /** * Processes the relevant annotations on the given field and adds the * required options or commands. * @param field The <code>Field</code> to process. */ private void processField(Field field) { OptionArgument optAnnotation = field.getAnnotation(OptionArgument.class); if (optAnnotation != null) { processField(field, optAnnotation); } else { CommandArgument cmdAnnotation = field.getAnnotation(CommandArgument.class); if (cmdAnnotation != null) { processField(field, cmdAnnotation); } } } /** * Processes the relevant annotations on the given method and adds the * required command. * @param method The <code>Method</code> to process. */ private void processMethod(final Method method) { CommandArgument annotation = method.getAnnotation(CommandArgument.class); if (annotation != null) { final String name = method.getName(); final Class<?>[] paramTypes = method.getParameterTypes(); final Annotation[][] paramAnnotations = method.getParameterAnnotations(); final ArgumentProcessor<Object[]> argProcessor = new ArgumentProcessor<Object[]>(); final Object[] defaultParams = new Object[paramTypes.length]; final List<Integer> positionalParams = new ArrayList<Integer>(); String key = annotation.value(); if (key.isEmpty()) { key = name; } for (int i = 0; i < paramAnnotations.length; i++) { Class<?> paramType = paramTypes[i]; if (paramType == Integer.class || paramType == int.class) { defaultParams[i] = 0; } else if (paramType == Double.class || paramType == double.class) { defaultParams[i] = 0.0; } else if (paramType == String.class) { defaultParams[i] = ""; } else if (paramType == File.class) { defaultParams[i] = null; } else if (paramType == Boolean.class || paramType == boolean.class) { defaultParams[i] = false; } else { throw new IllegalArgumentException("Invalid type (" + paramType.getCanonicalName() + ") for option parameter: method=" + method.getDeclaringClass().getCanonicalName() + "." + name); } - for (int j = 0; j < paramAnnotations[i].length; j++) { + int j; + for (j = 0; j < paramAnnotations[i].length; j++) { if (paramAnnotations[i][j] instanceof OptionArgument) { OptionArgument optAnnotation = (OptionArgument) paramAnnotations[i][j]; String optKey = optAnnotation.value(); if (optKey.isEmpty()) { throw new IllegalArgumentException("OptionArgument on parameter requires key (method=`" + method.getDeclaringClass().getCanonicalName() + "." + name + "')."); } char optShortKey = optAnnotation.shortKey(); if (optShortKey == '\0') { optShortKey = optKey.charAt(0); } final int index = i; if (paramType == Integer.class || paramType == int.class) { argProcessor.addOption(optKey, optShortKey, new Command<Object[]>() { public void process(Queue<String> argq, Object[] state) { state[index] = Integer.parseInt(argq.remove()); } }); } else if (paramType == Boolean.class || paramType == boolean.class) { argProcessor.addOption(optKey, optShortKey, new Command<Object[]>() { public void process(Queue<String> argq, Object[] state) { state[index] = true; } }); } else if (paramType == String.class) { argProcessor.addOption(optKey, optShortKey, new Command<Object[]>() { public void process(Queue<String> argq, Object[] state) { state[index] = argq.remove(); } }); } else if (paramType == Double.class || paramType == double.class) { argProcessor.addOption(optKey, optShortKey, new Command<Object[]>() { public void process(Queue<String> argq, Object[] state) { state[index] = Double.parseDouble(argq.remove()); } }); } else if (paramType == File.class) { argProcessor.addOption(optKey, optShortKey, new Command<Object[]>() { public void process(Queue<String> argq, Object[] state) { state[index] = new File(argq.remove()); } }); } break; } } - // There is no OptionArgument annotation, so treat it as a + // If there is no OptionArgument annotation, treat it as a // positional parameter. - positionalParams.add(i); + if (j >= paramAnnotations[i].length) { + positionalParams.add(i); + } } // The default command will parse out all the positional parameters // from what's left over after all the options have been processed. argProcessor.setDefaultCommand(new Command<Object[]>() { public void process(Queue<String> argq, Object[] state) { for (int index : positionalParams) { Class<?> paramType = paramTypes[index]; if (paramType == Integer.class || paramType == int.class) { state[index] = Integer.parseInt(argq.remove()); } else if (paramType == Double.class || paramType == double.class) { state[index] = Double.parseDouble(argq.remove()); } else if (paramType == String.class) { state[index] = argq.remove(); } else if (paramType == File.class) { state[index] = new File(argq.remove()); } else if (paramType == Boolean.class || paramType == boolean.class) { state[index] = Boolean.parseBoolean(argq.remove()); } else { throw new UnexpectedException(); } } } }); // Add the command that processes its arguments and invokes the // method. addCommand(key, new Command<T>(){ public void process(Queue<String> argq, T state) { Object[] params = defaultParams.clone(); argProcessor.process(argq, params); try { method.invoke(state, params); } catch (IllegalArgumentException e) { throw new UnexpectedException(e); } catch (IllegalAccessException e) { throw new UnexpectedException(e); } catch (InvocationTargetException e) { throw new UnexpectedException(e); } } }); } } /** * Processes <code>CommandArgument</code> and <code>OptionArgument</code> * annotations and creates adds the corresponding commands or options to * this <code>ArgumentProcessor</code> for setting fields or calling * methods. * @param cl The <code>Class</code> whose fields and methods are to be * processed. */ public void processAnnotations(Class<?> cl) { for (Field field : cl.getFields()) { processField(field); } for (Method method : cl.getMethods()) { processMethod(method); } } /** * Add a command line option handler. * @param key The <code>String</code> that identifies this option. The * option may be triggered by specifying <code>--&lt;key&gt;</code> * on the command line. * @param shortKey The <code>char</code> that serves as a shortcut to the * option. The option may be triggered by specifying * <code>-&lt;shortKey&gt;</code> on the command line. * @param handler The <code>Command</code> that is used to process the * option. */ public void addOption(String key, char shortKey, Command<? super T> handler) { options.put(key, handler); shortcuts.put(shortKey, key); } /** * Adds a new command handler. * @param key The <code>String</code> that identifies this command. The * command may be triggered by a command line argument with this * value. * @param handler The <code>Command</code> that is used to process the * command. */ public void addCommand(String key, Command<? super T> handler) { commands.put(key, handler); } /** * Sets the command handler that is used to process unrecognized commands * or that is executed when the end of the command line arguments is * reached without a command being executed. * @param command The <code>Command</code> to use (may be null). */ public void setDefaultCommand(Command<? super T> command) { defaultCommand = command; } /** * Processes command line arguments. * @param args The command line arguments to process. * @param state The application state object. */ public void process(String[] args, T state) { process(new ArrayQueue<String>(args), state); } /** * Processes command line arguments. * @param argq A <code>Queue</code> containing the command line arguments * to be processed. * @param state The application state object. */ public void process(Queue<String> argq, T state) { while (!argq.isEmpty()) { String nextArg = argq.peek(); if (nextArg.startsWith("--")) { argq.remove(); String key = nextArg.substring(2); Command<? super T> option = options.get(key); if (option != null) { option.process(argq, state); } } else if (nextArg.startsWith("-")) { argq.remove(); for (int i = 1; i < nextArg.length(); i++) { char key = nextArg.charAt(i); Command<? super T> option = options.get(shortcuts.get(key)); if (option != null) { option.process(argq, state); } } } else { Command<? super T> command = commands.get(nextArg); if (command != null) { argq.remove(); command.process(argq, state); return; } break; } } if (defaultCommand != null) { defaultCommand.process(argq, state); } if (shellCommand != null) { shellCommand.process(argq, state); } } }
false
true
private void processMethod(final Method method) { CommandArgument annotation = method.getAnnotation(CommandArgument.class); if (annotation != null) { final String name = method.getName(); final Class<?>[] paramTypes = method.getParameterTypes(); final Annotation[][] paramAnnotations = method.getParameterAnnotations(); final ArgumentProcessor<Object[]> argProcessor = new ArgumentProcessor<Object[]>(); final Object[] defaultParams = new Object[paramTypes.length]; final List<Integer> positionalParams = new ArrayList<Integer>(); String key = annotation.value(); if (key.isEmpty()) { key = name; } for (int i = 0; i < paramAnnotations.length; i++) { Class<?> paramType = paramTypes[i]; if (paramType == Integer.class || paramType == int.class) { defaultParams[i] = 0; } else if (paramType == Double.class || paramType == double.class) { defaultParams[i] = 0.0; } else if (paramType == String.class) { defaultParams[i] = ""; } else if (paramType == File.class) { defaultParams[i] = null; } else if (paramType == Boolean.class || paramType == boolean.class) { defaultParams[i] = false; } else { throw new IllegalArgumentException("Invalid type (" + paramType.getCanonicalName() + ") for option parameter: method=" + method.getDeclaringClass().getCanonicalName() + "." + name); } for (int j = 0; j < paramAnnotations[i].length; j++) { if (paramAnnotations[i][j] instanceof OptionArgument) { OptionArgument optAnnotation = (OptionArgument) paramAnnotations[i][j]; String optKey = optAnnotation.value(); if (optKey.isEmpty()) { throw new IllegalArgumentException("OptionArgument on parameter requires key (method=`" + method.getDeclaringClass().getCanonicalName() + "." + name + "')."); } char optShortKey = optAnnotation.shortKey(); if (optShortKey == '\0') { optShortKey = optKey.charAt(0); } final int index = i; if (paramType == Integer.class || paramType == int.class) { argProcessor.addOption(optKey, optShortKey, new Command<Object[]>() { public void process(Queue<String> argq, Object[] state) { state[index] = Integer.parseInt(argq.remove()); } }); } else if (paramType == Boolean.class || paramType == boolean.class) { argProcessor.addOption(optKey, optShortKey, new Command<Object[]>() { public void process(Queue<String> argq, Object[] state) { state[index] = true; } }); } else if (paramType == String.class) { argProcessor.addOption(optKey, optShortKey, new Command<Object[]>() { public void process(Queue<String> argq, Object[] state) { state[index] = argq.remove(); } }); } else if (paramType == Double.class || paramType == double.class) { argProcessor.addOption(optKey, optShortKey, new Command<Object[]>() { public void process(Queue<String> argq, Object[] state) { state[index] = Double.parseDouble(argq.remove()); } }); } else if (paramType == File.class) { argProcessor.addOption(optKey, optShortKey, new Command<Object[]>() { public void process(Queue<String> argq, Object[] state) { state[index] = new File(argq.remove()); } }); } break; } } // There is no OptionArgument annotation, so treat it as a // positional parameter. positionalParams.add(i); } // The default command will parse out all the positional parameters // from what's left over after all the options have been processed. argProcessor.setDefaultCommand(new Command<Object[]>() { public void process(Queue<String> argq, Object[] state) { for (int index : positionalParams) { Class<?> paramType = paramTypes[index]; if (paramType == Integer.class || paramType == int.class) { state[index] = Integer.parseInt(argq.remove()); } else if (paramType == Double.class || paramType == double.class) { state[index] = Double.parseDouble(argq.remove()); } else if (paramType == String.class) { state[index] = argq.remove(); } else if (paramType == File.class) { state[index] = new File(argq.remove()); } else if (paramType == Boolean.class || paramType == boolean.class) { state[index] = Boolean.parseBoolean(argq.remove()); } else { throw new UnexpectedException(); } } } }); // Add the command that processes its arguments and invokes the // method. addCommand(key, new Command<T>(){ public void process(Queue<String> argq, T state) { Object[] params = defaultParams.clone(); argProcessor.process(argq, params); try { method.invoke(state, params); } catch (IllegalArgumentException e) { throw new UnexpectedException(e); } catch (IllegalAccessException e) { throw new UnexpectedException(e); } catch (InvocationTargetException e) { throw new UnexpectedException(e); } } }); } }
private void processMethod(final Method method) { CommandArgument annotation = method.getAnnotation(CommandArgument.class); if (annotation != null) { final String name = method.getName(); final Class<?>[] paramTypes = method.getParameterTypes(); final Annotation[][] paramAnnotations = method.getParameterAnnotations(); final ArgumentProcessor<Object[]> argProcessor = new ArgumentProcessor<Object[]>(); final Object[] defaultParams = new Object[paramTypes.length]; final List<Integer> positionalParams = new ArrayList<Integer>(); String key = annotation.value(); if (key.isEmpty()) { key = name; } for (int i = 0; i < paramAnnotations.length; i++) { Class<?> paramType = paramTypes[i]; if (paramType == Integer.class || paramType == int.class) { defaultParams[i] = 0; } else if (paramType == Double.class || paramType == double.class) { defaultParams[i] = 0.0; } else if (paramType == String.class) { defaultParams[i] = ""; } else if (paramType == File.class) { defaultParams[i] = null; } else if (paramType == Boolean.class || paramType == boolean.class) { defaultParams[i] = false; } else { throw new IllegalArgumentException("Invalid type (" + paramType.getCanonicalName() + ") for option parameter: method=" + method.getDeclaringClass().getCanonicalName() + "." + name); } int j; for (j = 0; j < paramAnnotations[i].length; j++) { if (paramAnnotations[i][j] instanceof OptionArgument) { OptionArgument optAnnotation = (OptionArgument) paramAnnotations[i][j]; String optKey = optAnnotation.value(); if (optKey.isEmpty()) { throw new IllegalArgumentException("OptionArgument on parameter requires key (method=`" + method.getDeclaringClass().getCanonicalName() + "." + name + "')."); } char optShortKey = optAnnotation.shortKey(); if (optShortKey == '\0') { optShortKey = optKey.charAt(0); } final int index = i; if (paramType == Integer.class || paramType == int.class) { argProcessor.addOption(optKey, optShortKey, new Command<Object[]>() { public void process(Queue<String> argq, Object[] state) { state[index] = Integer.parseInt(argq.remove()); } }); } else if (paramType == Boolean.class || paramType == boolean.class) { argProcessor.addOption(optKey, optShortKey, new Command<Object[]>() { public void process(Queue<String> argq, Object[] state) { state[index] = true; } }); } else if (paramType == String.class) { argProcessor.addOption(optKey, optShortKey, new Command<Object[]>() { public void process(Queue<String> argq, Object[] state) { state[index] = argq.remove(); } }); } else if (paramType == Double.class || paramType == double.class) { argProcessor.addOption(optKey, optShortKey, new Command<Object[]>() { public void process(Queue<String> argq, Object[] state) { state[index] = Double.parseDouble(argq.remove()); } }); } else if (paramType == File.class) { argProcessor.addOption(optKey, optShortKey, new Command<Object[]>() { public void process(Queue<String> argq, Object[] state) { state[index] = new File(argq.remove()); } }); } break; } } // If there is no OptionArgument annotation, treat it as a // positional parameter. if (j >= paramAnnotations[i].length) { positionalParams.add(i); } } // The default command will parse out all the positional parameters // from what's left over after all the options have been processed. argProcessor.setDefaultCommand(new Command<Object[]>() { public void process(Queue<String> argq, Object[] state) { for (int index : positionalParams) { Class<?> paramType = paramTypes[index]; if (paramType == Integer.class || paramType == int.class) { state[index] = Integer.parseInt(argq.remove()); } else if (paramType == Double.class || paramType == double.class) { state[index] = Double.parseDouble(argq.remove()); } else if (paramType == String.class) { state[index] = argq.remove(); } else if (paramType == File.class) { state[index] = new File(argq.remove()); } else if (paramType == Boolean.class || paramType == boolean.class) { state[index] = Boolean.parseBoolean(argq.remove()); } else { throw new UnexpectedException(); } } } }); // Add the command that processes its arguments and invokes the // method. addCommand(key, new Command<T>(){ public void process(Queue<String> argq, T state) { Object[] params = defaultParams.clone(); argProcessor.process(argq, params); try { method.invoke(state, params); } catch (IllegalArgumentException e) { throw new UnexpectedException(e); } catch (IllegalAccessException e) { throw new UnexpectedException(e); } catch (InvocationTargetException e) { throw new UnexpectedException(e); } } }); } }
diff --git a/expenditure-tracking/src/pt/ist/expenditureTrackingSystem/domain/dto/AfterTheFactAcquisitionsImportBean.java b/expenditure-tracking/src/pt/ist/expenditureTrackingSystem/domain/dto/AfterTheFactAcquisitionsImportBean.java index c7e8678c..97bfaa15 100644 --- a/expenditure-tracking/src/pt/ist/expenditureTrackingSystem/domain/dto/AfterTheFactAcquisitionsImportBean.java +++ b/expenditure-tracking/src/pt/ist/expenditureTrackingSystem/domain/dto/AfterTheFactAcquisitionsImportBean.java @@ -1,201 +1,204 @@ package pt.ist.expenditureTrackingSystem.domain.dto; import java.io.Serializable; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import pt.ist.expenditureTrackingSystem.domain.DomainException; import pt.ist.expenditureTrackingSystem.domain.acquisitions.afterthefact.AfterTheFactAcquisitionProcess; import pt.ist.expenditureTrackingSystem.domain.acquisitions.afterthefact.AfterTheFactAcquisitionType; import pt.ist.expenditureTrackingSystem.domain.acquisitions.afterthefact.ImportFile; import pt.ist.expenditureTrackingSystem.domain.dto.Issue.IssueType; import pt.ist.expenditureTrackingSystem.domain.dto.Issue.IssueTypeLevel; import pt.ist.expenditureTrackingSystem.domain.organization.Supplier; import pt.ist.expenditureTrackingSystem.domain.util.Money; import pt.ist.expenditureTrackingSystem.presentationTier.util.FileUploadBean; import pt.ist.fenixWebFramework.services.Service; import pt.utl.ist.fenix.tools.util.StringNormalizer; public class AfterTheFactAcquisitionsImportBean extends FileUploadBean implements Serializable { private AfterTheFactAcquisitionType afterTheFactAcquisitionType; private String contents; private List<Issue> issues = new ArrayList<Issue>(); private int importedLines = 0; private int errorCount = 0; private int warningCount = 0; private boolean createData; public AfterTheFactAcquisitionsImportBean() { } public AfterTheFactAcquisitionType getAfterTheFactAcquisitionType() { return afterTheFactAcquisitionType; } public void setAfterTheFactAcquisitionType(AfterTheFactAcquisitionType afterTheFactAcquisitionType) { this.afterTheFactAcquisitionType = afterTheFactAcquisitionType; } public void setFileContents(final byte[] contents) { this.contents = new String(contents); } public String getContents() { return contents; } public List<Issue> getIssues() { return issues; } public void registerIssue(final IssueType issueType, final int lineNumber, final String... messageArgs) { if (issueType.getIssueTypeLevel() == IssueTypeLevel.ERROR) { errorCount++; } else if (issueType.getIssueTypeLevel() == IssueTypeLevel.WARNING) { warningCount++; } issues.add(new Issue(issueType, lineNumber + 1, messageArgs)); } public void reset() { importedLines = errorCount = warningCount = 0; issues.clear(); } @Service public void importAcquisitions() { final String[] lines = getContents().split("\n"); final ImportFile file = new ImportFile(getContents().getBytes()); for (int i = 0; i < lines.length; i++) { final String line = lines[i]; if (line.isEmpty()) { registerIssue(IssueType.EMPTY_LINE, i); } else { final String[] parts = line.split("\t"); if (parts.length == 5 || parts.length == 4) { final String supplierNif = cleanupNIF(parts[0]); final String supplierName = StringNormalizer.normalizePreservingCapitalizedLetters(cleanup(parts[1])); Supplier supplier = findSupplier(supplierNif, supplierName); if (supplier == null) { if (!createData) { registerIssue(IssueType.SUPPLIER_DOES_NOT_EXIST, i, supplierNif, supplierName); } else { supplier = createSupplier(supplierName, supplierNif); } } final String description = cleanup(parts[2]); final String valueString = cleanup(parts[3]); Money value; try { - value = new Money(valueString.replace(",", "")); + value = new Money(valueString.replace('.', 'X').replace("X", "").replace(',', '.')); } catch (DomainException ex) { value = null; registerIssue(IssueType.BAD_MONEY_VALUE_FORMAT, i, valueString); } catch (NumberFormatException ex) { value = null; registerIssue(IssueType.BAD_MONEY_VALUE_FORMAT, i, valueString); } final String vatValueString = parts.length == 5 ? cleanup(parts[4]) : "0"; BigDecimal vatValue; try { - vatValue = new BigDecimal(vatValueString.replace(",", "")); + vatValue = new BigDecimal(vatValueString.replace('.', 'X').replace("X", "").replace(',', '.')); } catch (NumberFormatException ex) { vatValue = null; registerIssue(IssueType.BAD_VAT_VALUE_FORMAT, i, vatValueString); } if (supplier != null && value != null && vatValue != null) { if (supplier.isFundAllocationAllowed(value)) { if (createData) { try { importAcquisition(supplier, description, value, vatValue, file); } catch (DomainException e) { registerIssue(IssueType.CANNOT_ALLOCATE_MONEY_TO_SUPPLIER, i, supplierNif, supplierName, valueString); } } importedLines++; } else { + System.out.println(supplier.getName()); + System.out.println(" total allocated:" + supplier.getTotalAllocated().getValue()); + System.out.println(" trying to allocate value: " + value.getValue()); registerIssue(IssueType.CANNOT_ALLOCATE_MONEY_TO_SUPPLIER, i, supplierNif, supplierName, valueString); } } } else { registerIssue(IssueType.WRONG_NUMBER_LINE_COLUMNS, i); } } } if (issues.size() > 0 && createData) { throw new ImportError(); } } private Supplier createSupplier(String supplierName, String supplierNif) { Supplier supplier = new Supplier(supplierNif); supplier.setName(supplierName); return supplier; } public static class ImportError extends Error { } public void importAcquisition(final Supplier supplier, final String description, final Money value, final BigDecimal vatValue, ImportFile file) { final AfterTheFactAcquisitionProcessBean afterTheFactAcquisitionProcessBean = new AfterTheFactAcquisitionProcessBean(); afterTheFactAcquisitionProcessBean.setAfterTheFactAcquisitionType(getAfterTheFactAcquisitionType()); afterTheFactAcquisitionProcessBean.setDescription(description); afterTheFactAcquisitionProcessBean.setSupplier(supplier); afterTheFactAcquisitionProcessBean.setValue(value); afterTheFactAcquisitionProcessBean.setVatValue(vatValue); file.addAfterTheFactAcquisitionProcesses(AfterTheFactAcquisitionProcess .createNewAfterTheFactAcquisitionProcess(afterTheFactAcquisitionProcessBean)); } private Supplier findSupplier(final String supplierNif, final String supplierName) { final Supplier supplier = Supplier.readSupplierByFiscalIdentificationCode(supplierNif); return supplier == null ? Supplier.readSupplierByName(supplierName) : supplier; } public int getErrorCount() { return errorCount; } public int getWarningCount() { return warningCount; } public boolean hasError() { return getErrorCount() > 0; } public int getImportedLines() { return importedLines; } private String cleanupNIF(final String string) { return cleanup(string).replace(" ", ""); } private String cleanup(final String string) { String result = string; if (result.length() >= 2 && result.charAt(0) == '"' && result.charAt(result.length() - 1) == '"') { result = result.substring(1, result.length() - 1); } result = result.replace('€', ' '); result = result.trim(); return result; } public boolean isCreateData() { return createData; } public void setCreateData(boolean createData) { this.createData = createData; } }
false
true
public void importAcquisitions() { final String[] lines = getContents().split("\n"); final ImportFile file = new ImportFile(getContents().getBytes()); for (int i = 0; i < lines.length; i++) { final String line = lines[i]; if (line.isEmpty()) { registerIssue(IssueType.EMPTY_LINE, i); } else { final String[] parts = line.split("\t"); if (parts.length == 5 || parts.length == 4) { final String supplierNif = cleanupNIF(parts[0]); final String supplierName = StringNormalizer.normalizePreservingCapitalizedLetters(cleanup(parts[1])); Supplier supplier = findSupplier(supplierNif, supplierName); if (supplier == null) { if (!createData) { registerIssue(IssueType.SUPPLIER_DOES_NOT_EXIST, i, supplierNif, supplierName); } else { supplier = createSupplier(supplierName, supplierNif); } } final String description = cleanup(parts[2]); final String valueString = cleanup(parts[3]); Money value; try { value = new Money(valueString.replace(",", "")); } catch (DomainException ex) { value = null; registerIssue(IssueType.BAD_MONEY_VALUE_FORMAT, i, valueString); } catch (NumberFormatException ex) { value = null; registerIssue(IssueType.BAD_MONEY_VALUE_FORMAT, i, valueString); } final String vatValueString = parts.length == 5 ? cleanup(parts[4]) : "0"; BigDecimal vatValue; try { vatValue = new BigDecimal(vatValueString.replace(",", "")); } catch (NumberFormatException ex) { vatValue = null; registerIssue(IssueType.BAD_VAT_VALUE_FORMAT, i, vatValueString); } if (supplier != null && value != null && vatValue != null) { if (supplier.isFundAllocationAllowed(value)) { if (createData) { try { importAcquisition(supplier, description, value, vatValue, file); } catch (DomainException e) { registerIssue(IssueType.CANNOT_ALLOCATE_MONEY_TO_SUPPLIER, i, supplierNif, supplierName, valueString); } } importedLines++; } else { registerIssue(IssueType.CANNOT_ALLOCATE_MONEY_TO_SUPPLIER, i, supplierNif, supplierName, valueString); } } } else { registerIssue(IssueType.WRONG_NUMBER_LINE_COLUMNS, i); } } } if (issues.size() > 0 && createData) { throw new ImportError(); } }
public void importAcquisitions() { final String[] lines = getContents().split("\n"); final ImportFile file = new ImportFile(getContents().getBytes()); for (int i = 0; i < lines.length; i++) { final String line = lines[i]; if (line.isEmpty()) { registerIssue(IssueType.EMPTY_LINE, i); } else { final String[] parts = line.split("\t"); if (parts.length == 5 || parts.length == 4) { final String supplierNif = cleanupNIF(parts[0]); final String supplierName = StringNormalizer.normalizePreservingCapitalizedLetters(cleanup(parts[1])); Supplier supplier = findSupplier(supplierNif, supplierName); if (supplier == null) { if (!createData) { registerIssue(IssueType.SUPPLIER_DOES_NOT_EXIST, i, supplierNif, supplierName); } else { supplier = createSupplier(supplierName, supplierNif); } } final String description = cleanup(parts[2]); final String valueString = cleanup(parts[3]); Money value; try { value = new Money(valueString.replace('.', 'X').replace("X", "").replace(',', '.')); } catch (DomainException ex) { value = null; registerIssue(IssueType.BAD_MONEY_VALUE_FORMAT, i, valueString); } catch (NumberFormatException ex) { value = null; registerIssue(IssueType.BAD_MONEY_VALUE_FORMAT, i, valueString); } final String vatValueString = parts.length == 5 ? cleanup(parts[4]) : "0"; BigDecimal vatValue; try { vatValue = new BigDecimal(vatValueString.replace('.', 'X').replace("X", "").replace(',', '.')); } catch (NumberFormatException ex) { vatValue = null; registerIssue(IssueType.BAD_VAT_VALUE_FORMAT, i, vatValueString); } if (supplier != null && value != null && vatValue != null) { if (supplier.isFundAllocationAllowed(value)) { if (createData) { try { importAcquisition(supplier, description, value, vatValue, file); } catch (DomainException e) { registerIssue(IssueType.CANNOT_ALLOCATE_MONEY_TO_SUPPLIER, i, supplierNif, supplierName, valueString); } } importedLines++; } else { System.out.println(supplier.getName()); System.out.println(" total allocated:" + supplier.getTotalAllocated().getValue()); System.out.println(" trying to allocate value: " + value.getValue()); registerIssue(IssueType.CANNOT_ALLOCATE_MONEY_TO_SUPPLIER, i, supplierNif, supplierName, valueString); } } } else { registerIssue(IssueType.WRONG_NUMBER_LINE_COLUMNS, i); } } } if (issues.size() > 0 && createData) { throw new ImportError(); } }
diff --git a/src/main/java/org/bukkit/inventory/ItemStack.java b/src/main/java/org/bukkit/inventory/ItemStack.java index c730db62..df51a20e 100644 --- a/src/main/java/org/bukkit/inventory/ItemStack.java +++ b/src/main/java/org/bukkit/inventory/ItemStack.java @@ -1,391 +1,391 @@ package org.bukkit.inventory; import com.google.common.collect.ImmutableMap; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import org.bukkit.Material; import org.bukkit.configuration.serialization.ConfigurationSerializable; import org.bukkit.enchantments.Enchantment; import org.bukkit.material.MaterialData; /** * Represents a stack of items */ public class ItemStack implements ConfigurationSerializable { private int type; private int amount = 0; private MaterialData data = null; private short durability = 0; private Map<Enchantment, Integer> enchantments = new HashMap<Enchantment, Integer>(); public ItemStack(final int type) { this(type, 0); } public ItemStack(final Material type) { this(type, 0); } public ItemStack(final int type, final int amount) { this(type, amount, (short) 0); } public ItemStack(final Material type, final int amount) { this(type.getId(), amount); } public ItemStack(final int type, final int amount, final short damage) { this(type, amount, damage, null); } public ItemStack(final Material type, final int amount, final short damage) { this(type.getId(), amount, damage); } public ItemStack(final int type, final int amount, final short damage, final Byte data) { this.type = type; this.amount = amount; this.durability = damage; if (data != null) { createData(data); this.durability = data; } } public ItemStack(final Material type, final int amount, final short damage, final Byte data) { this(type.getId(), amount, damage, data); } /** * Gets the type of this item * * @return Type of the items in this stack */ public Material getType() { return Material.getMaterial(type); } /** * Sets the type of this item<br /> * <br /> * Note that in doing so you will reset the MaterialData for this stack * * @param type New type to set the items in this stack to */ public void setType(Material type) { setTypeId(type.getId()); } /** * Gets the type id of this item * * @return Type Id of the items in this stack */ public int getTypeId() { return type; } /** * Sets the type id of this item<br /> * <br /> * Note that in doing so you will reset the MaterialData for this stack * * @param type New type id to set the items in this stack to */ public void setTypeId(int type) { this.type = type; createData((byte) 0); } /** * Gets the amount of items in this stack * * @return Amount of items in this stick */ public int getAmount() { return amount; } /** * Sets the amount of items in this stack * * @param amount New amount of items in this stack */ public void setAmount(int amount) { this.amount = amount; } /** * Gets the MaterialData for this stack of items * * @return MaterialData for this item */ public MaterialData getData() { Material mat = Material.getMaterial(getTypeId()); if (mat != null && mat.getData() != null) { data = mat.getNewData((byte) this.durability); } return data; } /** * Sets the MaterialData for this stack of items * * @param data New MaterialData for this item */ public void setData(MaterialData data) { Material mat = getType(); if ((mat == null) || (mat.getData() == null)) { this.data = data; } else { if ((data.getClass() == mat.getData()) || (data.getClass() == MaterialData.class)) { this.data = data; } else { throw new IllegalArgumentException("Provided data is not of type " + mat.getData().getName() + ", found " + data.getClass().getName()); } } } /** * Sets the durability of this item * * @param durability Durability of this item */ public void setDurability(final short durability) { this.durability = durability; } /** * Gets the durability of this item * * @return Durability of this item */ public short getDurability() { return durability; } /** * Get the maximum stacksize for the material hold in this ItemStack * Returns -1 if it has no idea. * * @return The maximum you can stack this material to. */ public int getMaxStackSize() { Material material = getType(); if (material != null) { return material.getMaxStackSize(); } return -1; } private void createData(final byte data) { Material mat = Material.getMaterial(type); if (mat == null) { this.data = new MaterialData(type, data); } else { this.data = mat.getNewData(data); } } @Override public String toString() { return "ItemStack{" + getType().name() + " x " + getAmount() + "}"; } @Override public boolean equals(Object obj) { if (!(obj instanceof ItemStack)) { return false; } ItemStack item = (ItemStack) obj; return item.getAmount() == getAmount() && item.getTypeId() == getTypeId() && getDurability() == item.getDurability() && getEnchantments().equals(item.getEnchantments()); } @Override public ItemStack clone() { ItemStack result = new ItemStack(type, amount, durability); result.addUnsafeEnchantments(getEnchantments()); return result; } @Override public int hashCode() { int hash = 11; hash = hash * 19 + 7 * getTypeId(); // Overriding hashCode since equals is overridden, it's just hash = hash * 7 + 23 * getAmount(); // too bad these are mutable values... Q_Q return hash; } /** * Checks if this ItemStack contains the given {@link Enchantment} * * @param ench Enchantment to test * @return True if this has the given enchantment */ public boolean containsEnchantment(Enchantment ench) { return enchantments.containsKey(ench); } /** * Gets the level of the specified enchantment on this item stack * * @param ench Enchantment to check * @return Level of the enchantment, or 0 */ public int getEnchantmentLevel(Enchantment ench) { return enchantments.get(ench); } /** * Gets a map containing all enchantments and their levels on this item. * * @return Map of enchantments. */ public Map<Enchantment, Integer> getEnchantments() { return ImmutableMap.copyOf(enchantments); } /** * Adds the specified enchantments to this item stack. * <p> * This method is the same as calling {@link #addEnchantment(org.bukkit.enchantments.Enchantment, int)} * for each element of the map. * * @param enchantments Enchantments to add */ public void addEnchantments(Map<Enchantment, Integer> enchantments) { for (Map.Entry<Enchantment, Integer> entry : enchantments.entrySet()) { addEnchantment(entry.getKey(), entry.getValue()); } } /** * Adds the specified {@link Enchantment} to this item stack. * <p> * If this item stack already contained the given enchantment (at any level), it will be replaced. * * @param ench Enchantment to add * @param level Level of the enchantment */ public void addEnchantment(Enchantment ench, int level) { if ((level < ench.getStartLevel()) || (level > ench.getMaxLevel())) { throw new IllegalArgumentException("Enchantment level is either too low or too high (given " + level + ", bounds are " + ench.getStartLevel() + " to " + ench.getMaxLevel()); } else if (!ench.canEnchantItem(this)) { throw new IllegalArgumentException("Specified enchantment cannot be applied to this itemstack"); } addUnsafeEnchantment(ench, level); } /** * Adds the specified enchantments to this item stack in an unsafe manner. * <p> * This method is the same as calling {@link #addUnsafeEnchantment(org.bukkit.enchantments.Enchantment, int)} * for each element of the map. * * @param enchantments Enchantments to add */ public void addUnsafeEnchantments(Map<Enchantment, Integer> enchantments) { for (Map.Entry<Enchantment, Integer> entry : enchantments.entrySet()) { addUnsafeEnchantment(entry.getKey(), entry.getValue()); } } /** * Adds the specified {@link Enchantment} to this item stack. * <p> * If this item stack already contained the given enchantment (at any level), it will be replaced. * <p> * This method is unsafe and will ignore level restrictions or item type. Use at your own * discretion. * * @param ench Enchantment to add * @param level Level of the enchantment */ public void addUnsafeEnchantment(Enchantment ench, int level) { enchantments.put(ench, level); } /** * Removes the specified {@link Enchantment} if it exists on this item stack * * @param ench Enchantment to remove * @return Previous level, or 0 */ public int removeEnchantment(Enchantment ench) { Integer previous = enchantments.remove(ench); return (previous == null) ? 0 : previous; } public Map<String, Object> serialize() { Map<String, Object> result = new LinkedHashMap<String, Object>(); result.put("type", getType().name()); if (durability != 0) { result.put("damage", durability); } if (amount != 1) { result.put("amount", amount); } Map<Enchantment, Integer> enchants = getEnchantments(); if (enchants.size() > 0) { Map<String, Integer> safeEnchants = new HashMap<String, Integer>(); for (Map.Entry<Enchantment, Integer> entry : enchants.entrySet()) { safeEnchants.put(entry.getKey().getName(), entry.getValue()); } result.put("enchantments", safeEnchants); } return result; } public static ItemStack deserialize(Map<String, Object> args) { Material type = Material.getMaterial((String) args.get("type")); short damage = 0; int amount = 1; if (args.containsKey("damage")) { - damage = (Short) args.get("damage"); + damage = ((Number) args.get("damage")).shortValue(); } if (args.containsKey("amount")) { amount = (Integer) args.get("amount"); } ItemStack result = new ItemStack(type, amount, damage); if (args.containsKey("enchantments")) { Object raw = args.get("enchantments"); if (raw instanceof Map) { @SuppressWarnings("unchecked") Map<Object, Object> map = (Map<Object, Object>) raw; for (Map.Entry<Object, Object> entry : map.entrySet()) { Enchantment enchantment = Enchantment.getByName(entry.getKey().toString()); if ((enchantment != null) && (entry.getValue() instanceof Integer)) { result.addEnchantment(enchantment, (Integer) entry.getValue()); } } } } return result; } }
true
true
public static ItemStack deserialize(Map<String, Object> args) { Material type = Material.getMaterial((String) args.get("type")); short damage = 0; int amount = 1; if (args.containsKey("damage")) { damage = (Short) args.get("damage"); } if (args.containsKey("amount")) { amount = (Integer) args.get("amount"); } ItemStack result = new ItemStack(type, amount, damage); if (args.containsKey("enchantments")) { Object raw = args.get("enchantments"); if (raw instanceof Map) { @SuppressWarnings("unchecked") Map<Object, Object> map = (Map<Object, Object>) raw; for (Map.Entry<Object, Object> entry : map.entrySet()) { Enchantment enchantment = Enchantment.getByName(entry.getKey().toString()); if ((enchantment != null) && (entry.getValue() instanceof Integer)) { result.addEnchantment(enchantment, (Integer) entry.getValue()); } } } } return result; }
public static ItemStack deserialize(Map<String, Object> args) { Material type = Material.getMaterial((String) args.get("type")); short damage = 0; int amount = 1; if (args.containsKey("damage")) { damage = ((Number) args.get("damage")).shortValue(); } if (args.containsKey("amount")) { amount = (Integer) args.get("amount"); } ItemStack result = new ItemStack(type, amount, damage); if (args.containsKey("enchantments")) { Object raw = args.get("enchantments"); if (raw instanceof Map) { @SuppressWarnings("unchecked") Map<Object, Object> map = (Map<Object, Object>) raw; for (Map.Entry<Object, Object> entry : map.entrySet()) { Enchantment enchantment = Enchantment.getByName(entry.getKey().toString()); if ((enchantment != null) && (entry.getValue() instanceof Integer)) { result.addEnchantment(enchantment, (Integer) entry.getValue()); } } } } return result; }
diff --git a/src/uk/co/oliwali/MultiHome/MultiHome.java b/src/uk/co/oliwali/MultiHome/MultiHome.java index c79b2c7..6e76ab6 100644 --- a/src/uk/co/oliwali/MultiHome/MultiHome.java +++ b/src/uk/co/oliwali/MultiHome/MultiHome.java @@ -1,132 +1,132 @@ package uk.co.oliwali.MultiHome; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; import javax.persistence.PersistenceException; import org.bukkit.ChatColor; import org.bukkit.World; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.plugin.java.JavaPlugin; public class MultiHome extends JavaPlugin { public String name; public String version; public static final Logger log = Logger.getLogger("Minecraft"); private Permission permissions; public void onDisable() { sendMessage("info", "Version " + version + " disabled!"); } public void onEnable() { name = this.getDescription().getName(); version = this.getDescription().getVersion(); permissions = new Permission(this); setupDatabase(); sendMessage("info", "Version " + version + " enabled!"); } private void setupDatabase() { try { getDatabase().find(Home.class).findRowCount(); } catch (PersistenceException ex) { System.out.println("Installing database for " + getDescription().getName() + " due to first time usage"); installDDL(); } } @Override public List<Class<?>> getDatabaseClasses() { List<Class<?>> list = new ArrayList<Class<?>>(); list.add(Home.class); return list; } public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String args[]) { String prefix = cmd.getName(); Player player = (Player) sender; World world = player.getWorld(); if (prefix.equalsIgnoreCase("home") && permissions.home(player)) { if (args.length > 0) { String command = args[0]; //Setting home if (command.equalsIgnoreCase("set")) { Home home = getDatabase().find(Home.class).where().ieq("world", world.getName()).ieq("player", player.getName()).findUnique(); - if (home != null) { + if (home == null) { home = new Home(); home.setPlayer(player.getName()); } - home.setLocation(player.getLocation()); + home.setLocation(player.getLocation()); getDatabase().save(home); sendMessage(player, "`aYour home has been set in world `f" + world.getName()); } //Get help else if (command.equalsIgnoreCase("help")) { sendMessage(player, "`a--------------------`f MultiHome `a--------------------"); sendMessage(player, "`a/home`f - Go to your home in the world you are in"); sendMessage(player, "`a/home set`f - Set your home in the world you are in"); } } //Go home else { Home home = (Home) getDatabase().find(Home.class).where().ieq("world", world.getName()).ieq("player", player.getName()).findUnique(); if (home == null) { sendMessage(player, "`cYou do not have a home set in world `f" + world.getName()); sendMessage(player, "`fUse `c/home set`f to set a home"); } else { player.teleport(home.getLocation()); sendMessage(player, "`aWelcome to your home in `f" + world.getName()); } } return true; } return false; } public void sendMessage(Player player, String msg) { player.sendMessage(replaceColors(msg)); } public void sendMessage(String level, String msg) { msg = "[" + name + "] " + msg; if (level == "info") log.info(msg); else log.severe(msg); } public String replaceColors(String str) { str = str.replace("`c", ChatColor.RED.toString()); str = str.replace("`4", ChatColor.DARK_RED.toString()); str = str.replace("`e", ChatColor.YELLOW.toString()); str = str.replace("`6", ChatColor.GOLD.toString()); str = str.replace("`a", ChatColor.GREEN.toString()); str = str.replace("`2", ChatColor.DARK_GREEN.toString()); str = str.replace("`b", ChatColor.AQUA.toString()); str = str.replace("`8", ChatColor.DARK_AQUA.toString()); str = str.replace("`9", ChatColor.BLUE.toString()); str = str.replace("`1", ChatColor.DARK_BLUE.toString()); str = str.replace("`d", ChatColor.LIGHT_PURPLE.toString()); str = str.replace("`5", ChatColor.DARK_PURPLE.toString()); str = str.replace("`0", ChatColor.BLACK.toString()); str = str.replace("`8", ChatColor.DARK_GRAY.toString()); str = str.replace("`7", ChatColor.GRAY.toString()); str = str.replace("`f", ChatColor.WHITE.toString()); return str; } }
false
true
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String args[]) { String prefix = cmd.getName(); Player player = (Player) sender; World world = player.getWorld(); if (prefix.equalsIgnoreCase("home") && permissions.home(player)) { if (args.length > 0) { String command = args[0]; //Setting home if (command.equalsIgnoreCase("set")) { Home home = getDatabase().find(Home.class).where().ieq("world", world.getName()).ieq("player", player.getName()).findUnique(); if (home != null) { home = new Home(); home.setPlayer(player.getName()); } home.setLocation(player.getLocation()); getDatabase().save(home); sendMessage(player, "`aYour home has been set in world `f" + world.getName()); } //Get help else if (command.equalsIgnoreCase("help")) { sendMessage(player, "`a--------------------`f MultiHome `a--------------------"); sendMessage(player, "`a/home`f - Go to your home in the world you are in"); sendMessage(player, "`a/home set`f - Set your home in the world you are in"); } } //Go home else { Home home = (Home) getDatabase().find(Home.class).where().ieq("world", world.getName()).ieq("player", player.getName()).findUnique(); if (home == null) { sendMessage(player, "`cYou do not have a home set in world `f" + world.getName()); sendMessage(player, "`fUse `c/home set`f to set a home"); } else { player.teleport(home.getLocation()); sendMessage(player, "`aWelcome to your home in `f" + world.getName()); } } return true; } return false; }
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String args[]) { String prefix = cmd.getName(); Player player = (Player) sender; World world = player.getWorld(); if (prefix.equalsIgnoreCase("home") && permissions.home(player)) { if (args.length > 0) { String command = args[0]; //Setting home if (command.equalsIgnoreCase("set")) { Home home = getDatabase().find(Home.class).where().ieq("world", world.getName()).ieq("player", player.getName()).findUnique(); if (home == null) { home = new Home(); home.setPlayer(player.getName()); } home.setLocation(player.getLocation()); getDatabase().save(home); sendMessage(player, "`aYour home has been set in world `f" + world.getName()); } //Get help else if (command.equalsIgnoreCase("help")) { sendMessage(player, "`a--------------------`f MultiHome `a--------------------"); sendMessage(player, "`a/home`f - Go to your home in the world you are in"); sendMessage(player, "`a/home set`f - Set your home in the world you are in"); } } //Go home else { Home home = (Home) getDatabase().find(Home.class).where().ieq("world", world.getName()).ieq("player", player.getName()).findUnique(); if (home == null) { sendMessage(player, "`cYou do not have a home set in world `f" + world.getName()); sendMessage(player, "`fUse `c/home set`f to set a home"); } else { player.teleport(home.getLocation()); sendMessage(player, "`aWelcome to your home in `f" + world.getName()); } } return true; } return false; }
diff --git a/src/main/java/net/stormdev/ucars/shops/CarShop.java b/src/main/java/net/stormdev/ucars/shops/CarShop.java index ba462ed..513dc77 100644 --- a/src/main/java/net/stormdev/ucars/shops/CarShop.java +++ b/src/main/java/net/stormdev/ucars/shops/CarShop.java @@ -1,113 +1,115 @@ package net.stormdev.ucars.shops; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.stormdev.ucars.trade.Lang; import net.stormdev.ucars.trade.main; import net.stormdev.ucars.utils.Car; import net.stormdev.ucars.utils.CarGenerator; import net.stormdev.ucars.utils.IconMenu; import net.stormdev.ucars.utils.IconMenu.OptionClickEvent; import net.stormdev.ucars.utils.IconMenu.OptionClickEventHandler; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; public class CarShop { private double value; private IconMenu menu = null; private main plugin; public CarShop(main plugin){ this.plugin = plugin; value = main.config.getDouble("general.carTrading.averageCarValue")*1.25; int v = (int)value*100; value = (double) v/100; setupMenu(plugin); } public void destroy(){ menu.destroy(); } public IconMenu getShopWindow(){ if(menu == null){ setupMenu(plugin); } return menu; } public void onClick(OptionClickEvent event){ event.setWillClose(false); event.setWillDestroy(false); int slot = event.getPosition(); if(slot == 4){ //Buy a car event.setWillClose(true); buyCar(event.getPlayer()); } return; } public void open(Player player){ getShopWindow().open(player); return; } public void buyCar(Player player){ if(main.economy == null){ main.plugin.setupEconomy(); if(main.economy == null){ player.sendMessage(main.colors.getError()+"No economy plugin found! Error!"); return; } } double bal = main.economy.getBalance(player.getName()); double cost = value; if(cost < 1){ return; } double rem = bal-cost; if(rem<0){ - player.sendMessage(main.colors.getError()+Lang.get("general.buy.notEnoughMoney")); + String msg = Lang.get("general.buy.notEnoughMoney"); + msg = msg.replaceAll(Pattern.quote("%balance%"), Matcher.quoteReplacement(bal+"")); + player.sendMessage(main.colors.getError()+msg); return; } main.economy.withdrawPlayer(player.getName(), cost); String currency = main.config.getString("general.carTrading.currencySign"); String msg = Lang.get("general.buy.success"); msg = msg.replaceAll(Pattern.quote("%item%"), "a car"); msg = msg.replaceAll(Pattern.quote("%price%"), Matcher.quoteReplacement(currency+cost)); msg = msg.replaceAll(Pattern.quote("%balance%"), Matcher.quoteReplacement(currency+rem)); player.sendMessage(main.colors.getSuccess()+msg); //Give them the car Car c = CarGenerator.gen(); ItemStack i = c.getItem(); player.getInventory().addItem(i); plugin.carSaver.setCar(c.id, c); return; } public void setupMenu(main plugin){ String currency = main.config.getString("general.carTrading.currencySign"); this.menu = new IconMenu("Car Shop", 9, new OptionClickEventHandler(){ public void onOptionClick(OptionClickEvent event) { onClick(event); return; }}, plugin); List<String> info = new ArrayList<String>(); info.add(main.colors.getTitle()+"[Price:] "+main.colors.getInfo()+currency+value); this.menu.setOption(4, new ItemStack(Material.MINECART), main.colors.getTitle()+"Buy Random Car", info); } }
true
true
public void buyCar(Player player){ if(main.economy == null){ main.plugin.setupEconomy(); if(main.economy == null){ player.sendMessage(main.colors.getError()+"No economy plugin found! Error!"); return; } } double bal = main.economy.getBalance(player.getName()); double cost = value; if(cost < 1){ return; } double rem = bal-cost; if(rem<0){ player.sendMessage(main.colors.getError()+Lang.get("general.buy.notEnoughMoney")); return; } main.economy.withdrawPlayer(player.getName(), cost); String currency = main.config.getString("general.carTrading.currencySign"); String msg = Lang.get("general.buy.success"); msg = msg.replaceAll(Pattern.quote("%item%"), "a car"); msg = msg.replaceAll(Pattern.quote("%price%"), Matcher.quoteReplacement(currency+cost)); msg = msg.replaceAll(Pattern.quote("%balance%"), Matcher.quoteReplacement(currency+rem)); player.sendMessage(main.colors.getSuccess()+msg); //Give them the car Car c = CarGenerator.gen(); ItemStack i = c.getItem(); player.getInventory().addItem(i); plugin.carSaver.setCar(c.id, c); return; }
public void buyCar(Player player){ if(main.economy == null){ main.plugin.setupEconomy(); if(main.economy == null){ player.sendMessage(main.colors.getError()+"No economy plugin found! Error!"); return; } } double bal = main.economy.getBalance(player.getName()); double cost = value; if(cost < 1){ return; } double rem = bal-cost; if(rem<0){ String msg = Lang.get("general.buy.notEnoughMoney"); msg = msg.replaceAll(Pattern.quote("%balance%"), Matcher.quoteReplacement(bal+"")); player.sendMessage(main.colors.getError()+msg); return; } main.economy.withdrawPlayer(player.getName(), cost); String currency = main.config.getString("general.carTrading.currencySign"); String msg = Lang.get("general.buy.success"); msg = msg.replaceAll(Pattern.quote("%item%"), "a car"); msg = msg.replaceAll(Pattern.quote("%price%"), Matcher.quoteReplacement(currency+cost)); msg = msg.replaceAll(Pattern.quote("%balance%"), Matcher.quoteReplacement(currency+rem)); player.sendMessage(main.colors.getSuccess()+msg); //Give them the car Car c = CarGenerator.gen(); ItemStack i = c.getItem(); player.getInventory().addItem(i); plugin.carSaver.setCar(c.id, c); return; }
diff --git a/src/java/org/apache/cassandra/net/IncomingTcpConnection.java b/src/java/org/apache/cassandra/net/IncomingTcpConnection.java index dcc0f0e2..07f38bd0 100644 --- a/src/java/org/apache/cassandra/net/IncomingTcpConnection.java +++ b/src/java/org/apache/cassandra/net/IncomingTcpConnection.java @@ -1,71 +1,71 @@ package org.apache.cassandra.net; import java.io.*; import java.net.Socket; import java.nio.ByteBuffer; import org.apache.log4j.Logger; import org.apache.cassandra.net.io.IncomingStreamReader; import org.apache.cassandra.utils.FBUtilities; public class IncomingTcpConnection extends Thread { private static Logger logger = Logger.getLogger(IncomingTcpConnection.class); private final DataInputStream input; private Socket socket; public IncomingTcpConnection(Socket socket) { this.socket = socket; try { input = new DataInputStream(socket.getInputStream()); } catch (IOException e) { throw new IOError(e); } } @Override public void run() { while (true) { try { MessagingService.validateMagic(input.readInt()); int header = input.readInt(); int type = MessagingService.getBits(header, 1, 2); boolean isStream = MessagingService.getBits(header, 3, 1) == 1; int version = MessagingService.getBits(header, 15, 8); if (isStream) { new IncomingStreamReader(socket.getChannel()).read(); } else { int size = input.readInt(); byte[] contentBytes = new byte[size]; input.readFully(contentBytes); MessagingService.getDeserializationExecutor().submit(new MessageDeserializationTask(new ByteArrayInputStream(contentBytes))); } } catch (EOFException e) { if (logger.isTraceEnabled()) - logger.trace("error reading from socket; closing", e); + logger.trace("eof reading from socket; closing", e); break; } catch (IOException e) { if (logger.isDebugEnabled()) logger.debug("error reading from socket; closing", e); break; } } } }
true
true
public void run() { while (true) { try { MessagingService.validateMagic(input.readInt()); int header = input.readInt(); int type = MessagingService.getBits(header, 1, 2); boolean isStream = MessagingService.getBits(header, 3, 1) == 1; int version = MessagingService.getBits(header, 15, 8); if (isStream) { new IncomingStreamReader(socket.getChannel()).read(); } else { int size = input.readInt(); byte[] contentBytes = new byte[size]; input.readFully(contentBytes); MessagingService.getDeserializationExecutor().submit(new MessageDeserializationTask(new ByteArrayInputStream(contentBytes))); } } catch (EOFException e) { if (logger.isTraceEnabled()) logger.trace("error reading from socket; closing", e); break; } catch (IOException e) { if (logger.isDebugEnabled()) logger.debug("error reading from socket; closing", e); break; } } }
public void run() { while (true) { try { MessagingService.validateMagic(input.readInt()); int header = input.readInt(); int type = MessagingService.getBits(header, 1, 2); boolean isStream = MessagingService.getBits(header, 3, 1) == 1; int version = MessagingService.getBits(header, 15, 8); if (isStream) { new IncomingStreamReader(socket.getChannel()).read(); } else { int size = input.readInt(); byte[] contentBytes = new byte[size]; input.readFully(contentBytes); MessagingService.getDeserializationExecutor().submit(new MessageDeserializationTask(new ByteArrayInputStream(contentBytes))); } } catch (EOFException e) { if (logger.isTraceEnabled()) logger.trace("eof reading from socket; closing", e); break; } catch (IOException e) { if (logger.isDebugEnabled()) logger.debug("error reading from socket; closing", e); break; } } }
diff --git a/java/src/ch/dritz/zhaw/ci/evolutionstrategy/Individual.java b/java/src/ch/dritz/zhaw/ci/evolutionstrategy/Individual.java index a4f9316..93cbbbd 100644 --- a/java/src/ch/dritz/zhaw/ci/evolutionstrategy/Individual.java +++ b/java/src/ch/dritz/zhaw/ci/evolutionstrategy/Individual.java @@ -1,139 +1,139 @@ package ch.dritz.zhaw.ci.evolutionstrategy; import java.util.Arrays; import java.util.Random; /** * An individual for the evolution strategy * @author D.Ritz */ public class Individual implements Cloneable { public static final double UNIT = 1D; public static final double MIN_G = 300D; public static final int IDX_PARAM_D = 0; public static final int IDX_PARAM_H = 1; public static Random rand = new Random(); // object parameters int[] param = { 0, 0}; // fitness double fitness = 0D; double g = 0D; boolean fitnessOk = false; // strategy related params int age = 1; double sigma = 0.01D; double sigmaSigma = 0.01D; // other int index = 0; public Individual(int index, int d, int h) { this.index = index; this.param[IDX_PARAM_D] = d; this.param[IDX_PARAM_H] = h; } public Individual(int index, int[] param) { this.index = index; this.param = Arrays.copyOf(param, 2); } public int numParams() { return 2; } public int getParam(int idx) { return param[idx]; } public void setParam(int idx, int value) { param[idx] = value; } /** * calculates the fitness * @return true if g() >= minG */ public boolean fitness() { double d = UNIT * param[IDX_PARAM_D]; double h = UNIT * param[IDX_PARAM_H]; fitness = Math.PI * d * d / 2 + Math.PI * d * h; g = Math.PI * d * d * h / 4; - fitnessOk = g >= MIN_G; + fitnessOk = (g >= MIN_G) && (d > 0D) && (h > 0D); return fitnessOk; } /** * Mutates the strategic param (sigma) non-isotropic. * Since it's only one param, this is extremely easy: * tau_0 and tau_1 are the same since 'u' is 1 */ public void mutateStrategicParam() { sigma += sigmaSigma * rand.nextGaussian(); double tau = 1D / Math.sqrt(2D); sigmaSigma = Math.exp(tau * rand.nextGaussian()) * sigmaSigma * Math.exp(tau * rand.nextGaussian()); } /** * Mutates the object params using isotropic mutation */ public void mutateObjectParams() { for (int i = 0; i < param.length; i++) param[i] += sigma * rand.nextGaussian(); double tau = 1D / Math.sqrt(2D); sigma = sigma * Math.exp(tau * rand.nextGaussian()); } @Override protected Individual clone() { try { return (Individual) super.clone(); } catch (CloneNotSupportedException e) { return null; } } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Individual at ").append(String.format("%02d", index)); sb.append(", d: ").append(String.format("%02d", param[IDX_PARAM_D])); sb.append(", h: ").append(String.format("%02d", param[IDX_PARAM_H])); sb.append(", fit: ").append(String.format("%04.3f", fitness)); sb.append(", g: ").append(String.format("%04.3f", g)); sb.append(", ok: ").append(fitnessOk); return sb.toString(); } //-------------------------------------------------------------------------- public static Individual randomIndividual(int index) { return new Individual(index, (int) ((double) rand.nextInt(30) / UNIT), (int) ((double) rand.nextInt(30) / UNIT)); } }
true
true
public boolean fitness() { double d = UNIT * param[IDX_PARAM_D]; double h = UNIT * param[IDX_PARAM_H]; fitness = Math.PI * d * d / 2 + Math.PI * d * h; g = Math.PI * d * d * h / 4; fitnessOk = g >= MIN_G; return fitnessOk; }
public boolean fitness() { double d = UNIT * param[IDX_PARAM_D]; double h = UNIT * param[IDX_PARAM_H]; fitness = Math.PI * d * d / 2 + Math.PI * d * h; g = Math.PI * d * d * h / 4; fitnessOk = (g >= MIN_G) && (d > 0D) && (h > 0D); return fitnessOk; }
diff --git a/org.eclipse.gmf.runtime/plugins/org.eclipse.gmf.runtime.common.ui.services/src/org/eclipse/gmf/runtime/common/ui/services/parser/GetParserOperation.java b/org.eclipse.gmf.runtime/plugins/org.eclipse.gmf.runtime.common.ui.services/src/org/eclipse/gmf/runtime/common/ui/services/parser/GetParserOperation.java index ca57c534..445eb346 100644 --- a/org.eclipse.gmf.runtime/plugins/org.eclipse.gmf.runtime.common.ui.services/src/org/eclipse/gmf/runtime/common/ui/services/parser/GetParserOperation.java +++ b/org.eclipse.gmf.runtime/plugins/org.eclipse.gmf.runtime.common.ui.services/src/org/eclipse/gmf/runtime/common/ui/services/parser/GetParserOperation.java @@ -1,55 +1,55 @@ /****************************************************************************** * Copyright (c) 2002, 2004 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.gmf.runtime.common.ui.services.parser; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.gmf.runtime.common.core.service.IOperation; import org.eclipse.gmf.runtime.common.core.service.IProvider; /** * Operation to get a parser using an IAdaptable hint for the parser to be used */ public class GetParserOperation implements IOperation { /** * Hint for the parser to be used */ private final IAdaptable hint; /** * Method GetParserOperation. * * @param hint IAdaptable hint for the parser to be used */ protected GetParserOperation(IAdaptable hint) { - assert null!=hint : "GetParserOperation constoructor received NULL as argument"; //$NON-NLS-1$ + assert null!=hint : "GetParserOperation constructor received NULL as argument"; //$NON-NLS-1$ this.hint = hint; } /** * @see org.eclipse.gmf.runtime.common.core.service.IOperation#execute(org.eclipse.gmf.runtime.common.core.service.IProvider) */ public Object execute(IProvider provider) { return ((IParserProvider) provider).getParser(getHint()); } /** * Method getHint. * @return IAdaptable */ public final IAdaptable getHint() { return hint; } }
true
true
protected GetParserOperation(IAdaptable hint) { assert null!=hint : "GetParserOperation constoructor received NULL as argument"; //$NON-NLS-1$ this.hint = hint; }
protected GetParserOperation(IAdaptable hint) { assert null!=hint : "GetParserOperation constructor received NULL as argument"; //$NON-NLS-1$ this.hint = hint; }
diff --git a/illacommon/src/illarion/common/data/BookPage.java b/illacommon/src/illarion/common/data/BookPage.java index 97b9a785..a026c1d6 100644 --- a/illacommon/src/illarion/common/data/BookPage.java +++ b/illacommon/src/illarion/common/data/BookPage.java @@ -1,88 +1,88 @@ /* * This file is part of the Illarion Common Library. * * Copyright © 2012 - Illarion e.V. * * The Illarion Common Library 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. * * The Illarion Common 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with the Illarion Common Library. If not, see <http://www.gnu.org/licenses/>. */ package illarion.common.data; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * This class represents one page of a book. * * @author Martin Karing &lt;[email protected]&gt; */ public final class BookPage implements Iterable<BookPageEntry> { /** * The list of entries on this page. */ private final List<BookPageEntry> entries; /** * Create a new blank page. */ private BookPage() { entries = new ArrayList<BookPageEntry>(); } /** * Create a book page that receives its data from a XML node. * * @param source the XML node that supplies the data */ public BookPage(final Node source) { this(); final NodeList children = source.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { final Node child = children.item(i); if ("headline".equals(child.getNodeName())) { - entries.add(new BookPageEntry(true, child.getFirstChild().getNodeValue())); + entries.add(new BookPageEntry(true, child.getNodeValue())); } else if ("paragraph".equals(child.getNodeName())) { - entries.add(new BookPageEntry(false, child.getFirstChild().getNodeValue())); + entries.add(new BookPageEntry(false, child.getNodeValue())); } } } @Override public Iterator<BookPageEntry> iterator() { return entries.iterator(); } /** * Get the amount of book page entries on this book page. * * @return the amount of book page entries */ public int getEntryCount() { return entries.size(); } /** * Get a book page entry with a specified index. * * @param index the index of the book page entry requested * @return the book page entry assigned to the index * @throws IndexOutOfBoundsException if the index is out of range ({@code index &lt; 0 || index &gt;= size()}) */ public BookPageEntry getEntry(final int index) { return entries.get(index); } }
false
true
public BookPage(final Node source) { this(); final NodeList children = source.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { final Node child = children.item(i); if ("headline".equals(child.getNodeName())) { entries.add(new BookPageEntry(true, child.getFirstChild().getNodeValue())); } else if ("paragraph".equals(child.getNodeName())) { entries.add(new BookPageEntry(false, child.getFirstChild().getNodeValue())); } } }
public BookPage(final Node source) { this(); final NodeList children = source.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { final Node child = children.item(i); if ("headline".equals(child.getNodeName())) { entries.add(new BookPageEntry(true, child.getNodeValue())); } else if ("paragraph".equals(child.getNodeName())) { entries.add(new BookPageEntry(false, child.getNodeValue())); } } }
diff --git a/projects/connector-manager/source/java/com/google/enterprise/connector/servlet/ServletUtil.java b/projects/connector-manager/source/java/com/google/enterprise/connector/servlet/ServletUtil.java index 5026d07a..45cd0b94 100644 --- a/projects/connector-manager/source/java/com/google/enterprise/connector/servlet/ServletUtil.java +++ b/projects/connector-manager/source/java/com/google/enterprise/connector/servlet/ServletUtil.java @@ -1,916 +1,917 @@ // Copyright (C) 2006-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.enterprise.connector.servlet; import com.google.enterprise.connector.common.JarUtils; import com.google.enterprise.connector.common.SecurityUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.net.InetAddress; import java.net.URL; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; /** * Servlet constant and utility class. * * Non-instantiable class that holds constants and XML tag constants, * utilities for reading/writing XML string, etc. * */ public class ServletUtil { private static Logger LOGGER = Logger.getLogger(ServletUtil.class.getName()); private ServletUtil() { } public static final String MANAGER_NAME = "Google Enterprise Connector Manager"; public static final String MIMETYPE_XML = "text/xml"; public static final String MIMETYPE_HTML = "text/html"; public static final String MIMETYPE_TEXT_PLAIN = "text/plain"; public static final String MIMETYPE_ZIP = "application/zip"; public static final String PROTOCOL = "googleconnector://"; public static final String DOCID = "/doc?docid="; public static final String QUERY_PARAM_LANG = "Lang"; public static final String DEFAULT_LANGUAGE = "en"; public static final String XMLTAG_RESPONSE_ROOT = "CmResponse"; public static final String XMLTAG_STATUSID = "StatusId"; public static final String XMLTAG_STATUS_MESSAGE = "StatusMsg"; public static final String XMLTAG_STATUS_PARAMS = "CMParams"; public static final String XMLTAG_STATUS_PARAM_ORDER = "Order"; public static final String XMLTAG_STATUS_PARAM = "CMParam"; public static final String XMLTAG_CONNECTOR_LOGS = "ConnectorLogs"; public static final String XMLTAG_FEED_LOGS = "FeedLogs"; public static final String XMLTAG_TEED_FEED = "TeedFeedFile"; public static final String XMLTAG_LOG = "Log"; public static final String XMLTAG_NAME = "Name"; public static final String XMLTAG_SIZE = "Size"; public static final String XMLTAG_LAST_MODIFIED = "LastModified"; public static final String XMLTAG_VERSION = "Version"; public static final String XMLTAG_INFO = "Info"; public static final String XMLTAG_CONNECTOR_INSTANCES = "ConnectorInstances"; public static final String XMLTAG_CONNECTOR_INSTANCE = "ConnectorInstance"; public static final String XMLTAG_CONNECTOR_TYPES = "ConnectorTypes"; public static final String XMLTAG_CONNECTOR_TYPE = "ConnectorType"; public static final String XMLTAG_CONNECTOR_STATUS = "ConnectorStatus"; public static final String XMLTAG_CONNECTOR_NAME = "ConnectorName"; public static final String XMLTAG_STATUS = "Status"; public static final String XMLTAG_CONFIG_FORM = "ConfigForm"; public static final String XMLTAG_CONFIGURE_RESPONSE = "ConfigureResponse"; public static final String XMLTAG_MESSAGE = "message"; public static final String XMLTAG_FORM_SNIPPET = "FormSnippet"; public static final String XMLTAG_MANAGER_CONFIG = "ManagerConfig"; public static final String XMLTAG_FEEDERGATE = "FeederGate"; public static final String XMLTAG_FEEDERGATE_HOST = "host"; public static final String XMLTAG_FEEDERGATE_PORT = "port"; public static final String XMLTAG_CONNECTOR_CONFIG = "ConnectorConfig"; public static final String XMLTAG_UPDATE_CONNECTOR = "Update"; public static final String XMLTAG_PARAMETERS = "Param"; public static final String XMLTAG_AUTHN_REQUEST = "AuthnRequest"; public static final String XMLTAG_AUTHN_CREDENTIAL = "Credentials"; public static final String XMLTAG_AUTHN_USERNAME = "Username"; public static final String XMLTAG_AUTHN_PASSWORD = "Password"; public static final String XMLTAG_AUTHN_DOMAIN = "Domain"; public static final String XMLTAG_AUTHN_RESPONSE = "AuthnResponse"; public static final String XMLTAG_SUCCESS = "Success"; public static final String XMLTAG_FAILURE = "Failure"; public static final String XMLTAG_AUTHZ_QUERY = "AuthorizationQuery"; public static final String XMLTAG_CONNECTOR_QUERY = "ConnectorQuery"; public static final String XMLTAG_IDENTITY = "Identity"; public static final String XMLTAG_RESOURCE = "Resource"; public static final String XMLTAG_AUTHZ_RESPONSE = "AuthorizationResponse"; public static final String XMLTAG_ANSWER = "Answer"; public static final String XMLTAG_DECISION = "Decision"; public static final String XMLTAG_CONNECTOR_SCHEDULES = "ConnectorSchedules"; public static final String XMLTAG_CONNECTOR_SCHEDULE = "ConnectorSchedule"; public static final String XMLTAG_DISABLED = "disabled"; public static final String XMLTAG_LOAD = "load"; public static final String XMLTAG_DELAY = "RetryDelayMillis"; public static final String XMLTAG_TIME_INTERVALS = "TimeIntervals"; public static final String LOG_RESPONSE_EMPTY_REQUEST = "Empty request"; public static final String LOG_RESPONSE_EMPTY_NODE = "Empty node"; public static final String LOG_RESPONSE_NULL_CONNECTOR = "Null connector name"; public static final String LOG_RESPONSE_NULL_CONNECTOR_TYPE = "Null connector type name"; public static final String LOG_RESPONSE_NULL_SCHEDULE = "Null connector schedule"; public static final String LOG_EXCEPTION_CONNECTOR_TYPE_NOT_FOUND = "Exception: the connector type is not found"; public static final String LOG_EXCEPTION_CONNECTOR_NOT_FOUND = "Exception: the connector is not found"; public static final String LOG_EXCEPTION_CONNECTOR_EXISTS = "Exception: the connector exists"; public static final String LOG_EXCEPTION_INSTANTIATOR = "Exception: instantiator"; public static final String LOG_EXCEPTION_PERSISTENT_STORE = "Exception: persistent store"; public static final String LOG_EXCEPTION_THROWABLE = "Exception: throwable"; public static final String LOG_EXCEPTION_CONNECTOR_MANAGER = "Exception: general"; public static final String XML_SIMPLE_RESPONSE = "<CmResponse>\n" + " <StatusId>0</StatusId>\n" + "</CmResponse>\n"; public static final String DEFAULT_FORM = "<tr><td>Username</td><td>\n" + "<input type=\"text\" name=\"Username\" /></td></tr>\n" + "<tr><td>Password</td><td>\n" + "<input type=\"password\" name=\"Password\" /></td></tr>\n" + "<tr><td>Repository</td><td>\n" + "<input type=\"text\" name=\"Repository\" /></td></tr>\n"; public static final String ATTRIBUTE_NAME = "name=\""; public static final String ATTRIBUTE_VALUE = " value=\""; public static final String ATTRIBUTE_VERSION = "version=\""; public static final char QUOTE = '"'; private static final String[] XMLIndent = { "", " ", " ", " ", " ", " ", " ", " "}; private static DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); /** * Parse an XML String to a Document. * * @param fileContent the XML string * @param errorHandler The error handle for SAX parser * @param entityResolver The entity resolver to use * @return A result Document object, null on error */ public static Document parse(String fileContent, SAXParseErrorHandler errorHandler, EntityResolver entityResolver) { InputStream in = stringToInputStream(fileContent); return (in == null) ? null : parse(in, errorHandler, entityResolver); } /** * Get a root element from the XML request body. * * @param xmlBody String the XML request body * @param rootTagName String the root element tag name * @return a result Element object if successful, null on error */ public static Element parseAndGetRootElement(String xmlBody, String rootTagName) { InputStream in = stringToInputStream(xmlBody); return (in == null) ? null : parseAndGetRootElement(in, rootTagName); } private static InputStream stringToInputStream(String fileContent) { try { return new ByteArrayInputStream(fileContent.getBytes("UTF-8")); } catch (java.io.UnsupportedEncodingException uee) { LOGGER.log(Level.SEVERE, "Really Unexpected", uee); return null; } } /** * Parse an input stream to a Document. * * @param in the input stream * @param errorHandler The error handle for SAX parser * @param entityResolver The entity resolver to use * @return A result Document object, null on error */ public static Document parse(InputStream in, SAXParseErrorHandler errorHandler, EntityResolver entityResolver) { try { DocumentBuilder builder = factory.newDocumentBuilder(); builder.setErrorHandler(errorHandler); builder.setEntityResolver(entityResolver); Document document = builder.parse(in); return document; } catch (ParserConfigurationException pce) { LOGGER.log(Level.SEVERE, "Parse exception", pce); } catch (SAXException se) { LOGGER.log(Level.SEVERE, "SAX Exception", se); } catch (IOException ioe) { LOGGER.log(Level.SEVERE, "IO Exception", ioe); } return null; } /** * Get a root element from an XML input stream. * * @param in the input stream * @param rootTagName String the root element tag name * @return a result Element object if successful, null on error */ public static Element parseAndGetRootElement(InputStream in, String rootTagName) { SAXParseErrorHandler errorHandler = new SAXParseErrorHandler(); Document document = ServletUtil.parse(in, errorHandler, null); if (document == null) { LOGGER.log(Level.WARNING, "XML parsing exception!"); return null; } NodeList nodeList = document.getElementsByTagName(rootTagName); if (nodeList == null || nodeList.getLength() == 0) { LOGGER.log(Level.WARNING, "Empty node: " + rootTagName); return null; } return (Element) nodeList.item(0); } /** * Get the attribute value of a given attribute name for * the first XML element of given name * * @param elem Element The parent XML element * @param name String name of the child text element * @param attrName String Attribute name * @return String attribute value of named child element */ public static String getFirstAttribute(Element elem, String name, String attrName) { NodeList nodeList = elem.getElementsByTagName(name); if (nodeList.getLength() == 0) { return null; } return (((Element)nodeList.item(0)).getAttribute(attrName)); } /** * Get the attribute values of a given name/value pair for * the first XML element of given name * * @param elem Element The parent XML element * @param name String name of the child text element * @return attribute name and value map of named child element * */ public static Map getAllAttributes(Element elem, String name) { Map attributes = new TreeMap(); NodeList nodeList = elem.getElementsByTagName(name); int length = nodeList.getLength(); for (int n = 0; n < length; ++n) { attributes.put(((Element)nodeList.item(n)).getAttribute("name"), ((Element)nodeList.item(n)).getAttribute("value")); } return attributes; } /** * Get text data of first XML element of given name * * @param elem Element The parent XML element * @param name String name of the child text element * @return text data of named child element */ public static String getFirstElementByTagName(Element elem, String name) { NodeList nodeList = elem.getElementsByTagName(name); if (nodeList.getLength() == 0) { return null; } NodeList children = nodeList.item(0).getChildNodes(); if (children.getLength() == 0 || children.item(0).getNodeType() != Node.TEXT_NODE) { return null; } return children.item(0).getNodeValue(); } /** * Get a list of all child text element of given name directly * under a given element * * @param elem the parent element * @param name the given name of searched child elements * @return a list of values of those child text elements */ public static List getAllElementsByTagName(Element elem, String name) { NodeList nodeList = elem.getElementsByTagName(name); List result = new ArrayList(); for (int i = 0; i < nodeList.getLength(); ++i) { NodeList children = nodeList.item(i).getChildNodes(); if (children.getLength() == 0 || children.item(0).getNodeType() != Node.TEXT_NODE) { continue; } result.add(children.item(0).getNodeValue()); } return result; } /** * Write an XML response with only StatusId (int) to a PrintWriter. * * @param out where PrintWriter to be written to * @param statusId int * */ public static void writeResponse(PrintWriter out, int statusId) { writeRootTag(out, false); writeStatusId(out, statusId); writeRootTag(out, true); } /** * Write an XML response with full status to a PrintWriter. * * @param out where PrintWriter to be written to * @param status ConnectorMessageCode * */ public static void writeResponse(PrintWriter out, ConnectorMessageCode status) { writeRootTag(out, false); writeMessageCode(out, status); writeRootTag(out, true); } /** * Write the root XML tag <CMResponse> to a PrintWriter. * * @param out where PrintWriter to be written to * @param endingTag boolean true if it is the ending tag * */ public static void writeRootTag(PrintWriter out, boolean endingTag) { writeXMLTag(out, 0, ServletUtil.XMLTAG_RESPONSE_ROOT, endingTag); } /** * Write Connector Manager, OS, JVM version information. * * @param out where PrintWriter to be written to */ public static void writeManagerSplash(PrintWriter out) { writeXMLElement(out, 1, ServletUtil.XMLTAG_INFO, getManagerSplash()); } /** * Get Connector Manager, OS, JVM version information. */ public static String getManagerSplash() { return ServletUtil.MANAGER_NAME + " " + JarUtils.getJarVersion(ServletUtil.class) + "; " + System.getProperty("java.vendor") + " " + System.getProperty("java.vm.name") + " " + System.getProperty("java.version") + "; " + System.getProperty("os.name") + " " + System.getProperty("os.version") + " (" + System.getProperty("os.arch") + ")"; } /** * Write a statusId response to a PrintWriter. * * @param out where PrintWriter to be written to * @param statusId int * */ public static void writeStatusId(PrintWriter out, int statusId) { writeXMLElement(out, 1, ServletUtil.XMLTAG_STATUSID, Integer.toString(statusId)); } /** * Write a partial XML status response to a PrintWriter. * * @param out where PrintWriter to be written to * @param status ConnectorMessageCode * */ public static void writeMessageCode(PrintWriter out, ConnectorMessageCode status) { writeStatusId(out, status.getMessageId()); if (status.getMessage() != null && status.getMessage().length() > 1) { writeXMLElement( out, 1, ServletUtil.XMLTAG_STATUS_MESSAGE, status.getMessage()); } if (status.getParams() == null) { return; } for (int i = 0; i < status.getParams().length; ++i) { String param = status.getParams()[i].toString(); if (param == null || param.length() < 1) { continue; } out.println(indentStr(1) + "<" + XMLTAG_STATUS_PARAMS + " " + XMLTAG_STATUS_PARAM_ORDER + "=\"" + Integer.toString(i) + "\"" + " " + XMLTAG_STATUS_PARAM + "=\"" + param + "\"/>"); } } /** * Write a name value pair as an XML element to a PrintWriter. * * @param out where PrintWriter to be written to * @param indentLevel the depth of indentation. * @param elemName element name * @param elemValue element value */ public static void writeXMLElement(PrintWriter out, int indentLevel, String elemName, String elemValue) { out.println(indentStr(indentLevel) + "<" + elemName + ">" + elemValue + "</" + elemName + ">"); } /** * Write a name value pair as an XML element to a StringBuffer. * * @param out where StringBuffer to be written to * @param indentLevel the depth of indentation. * @param elemName element name * @param elemValue element value */ public static void writeXMLElement(StringBuffer out, int indentLevel, String elemName, String elemValue) { out.append(indentStr(indentLevel)).append("<").append(elemName).append(">"); out.append(elemValue).append("</").append(elemName).append(">"); } /** * Write a name as an empty XML element to a PrintWriter. * * @param out where PrintWriter to be written to * @param indentLevel the depth of indentation. * @param elemName element name */ public static void writeEmptyXMLElement(PrintWriter out, int indentLevel, String elemName) { out.println(indentStr(indentLevel) + "<" + elemName + "></" + elemName + ">"); } /** * Write an XML tag with attributes out to a PrintWriter. * * @param out where PrintWriter to be written to * @param indentLevel the depth of indentation. * @param elemName element name * @param attributes attributes * @param closeTag if true, close the tag with '/>' */ public static void writeXMLTagWithAttrs(PrintWriter out, int indentLevel, String elemName, String attributes, boolean closeTag) { out.println(indentStr(indentLevel) + "<" + elemName + " " + attributes + ((closeTag)? "/>" : ">")); } /** * Write an XML tag with attributes out to a StringBuffer. * * @param out where StringBuffer to be written to * @param indentLevel the depth of indentation. * @param elemName element name * @param attributes attributes * @param closeTag if true, close the tag with '/>' */ public static void writeXMLTagWithAttrs(StringBuffer out, int indentLevel, String elemName, String attributes, boolean closeTag) { out.append(indentStr(indentLevel)).append("<").append(elemName); out.append(" ").append(attributes).append((closeTag)? "/>" : ">"); } /** Write an XML tag to a PrintWriter * * @param out where PrintWriter to be written to * @param indentLevel the depth of indentation * @param tagName String name of the XML tag to be added * @param endingTag String write a beginning tag if true or * an ending tag if false */ public static void writeXMLTag(PrintWriter out, int indentLevel, String tagName, boolean endingTag) { out.println(indentStr(indentLevel) + (endingTag ? "</" : "<") + (tagName) + ">"); } /** Write an XML tag to a StringBuffer * * @param out where StringBuffer to be written to * @param indentLevel the depth of indentation * @param tagName String name of the XML tag to be added * @param endingTag String write a beginning tag if true or * an ending tag if false */ public static void writeXMLTag(StringBuffer out, int indentLevel, String tagName, boolean endingTag) { out.append(indentStr(indentLevel)).append(endingTag ? "</" : "<"); out.append(tagName).append(">"); } // A helper method to ident output string. private static String indentStr(int level) { if (level < XMLIndent.length) { return XMLIndent[level]; } else { return XMLIndent[XMLIndent.length - 1] + indentStr(level + 1 - XMLIndent.length); } } private static final Pattern PREPEND_CM_PATTERN = Pattern.compile("\\bname\\b\\s*=\\s*[\"']"); private static final Pattern STRIP_CM_PATTERN = Pattern.compile("(\\bname\\b\\s*=\\s*[\"'])CM_"); /** * Given a String such as: * <Param name="CM_Color" value="a"/> <Param name="CM_Password" value="a"/> * * Return a String such as: * <Param name="Color" value="a"/> <Param name="Password" value="a"/> * * @param str String an XML string with PREFIX_CM as above * @return a result XML string without PREFIX_CM as above */ public static String stripCmPrefix(String str) { Matcher matcher = STRIP_CM_PATTERN.matcher(str); String result = matcher.replaceAll("$1"); return result; } /** * Inverse operation for stripCmPrefix. * * @param str String an XML string without PREFIX_CM as above * @return a result XML string with PREFIX_CM as above */ public static String prependCmPrefix(String str) { Matcher matcher = PREPEND_CM_PATTERN.matcher(str); String result = matcher.replaceAll("$0CM_"); return result; } private static final Pattern CDATA_BEGIN_PATTERN = Pattern.compile("/*\\Q<![CDATA[\\E"); private static final Pattern CDATA_END_PATTERN = Pattern.compile("/*\\Q]]>\\E"); /** * Removes any markers form the given snippet that are not allowed to be * nested. * * @param formSnippet snippet of a form that may have markers in it that are * not allowed to be nested. * @return the given formSnippet with all markers that are not allowed to be * nested removed. */ public static String removeNestedMarkers(String formSnippet) { Matcher matcher = CDATA_BEGIN_PATTERN.matcher(formSnippet); String result = matcher.replaceAll(""); matcher = CDATA_END_PATTERN.matcher(result); result = matcher.replaceAll(""); return result; } /** * For Debugging: Write out the HttpServletRequest information. * This writes an XML stream to the response output that describes * most of the data received in the request structure. It returns * true, so that you may call it from doGet() like: * if (dumpServletRequest(req, res)) return; * without javac complaining about unreachable code with a straight * return. * * @param req An HttpServletRequest * @param res An HttpServletResponse * @returns true */ public static boolean dumpServletRequest(HttpServletRequest req, HttpServletResponse res) throws IOException { res.setContentType(ServletUtil.MIMETYPE_XML); PrintWriter out = res.getWriter(); ServletUtil.writeRootTag(out, false); ServletUtil.writeXMLTag(out, 2, "HttpServletRequest", false); ServletUtil.writeXMLElement(out, 3, "Method", req.getMethod()); ServletUtil.writeXMLElement(out, 3, "AuthType", req.getAuthType()); ServletUtil.writeXMLElement(out, 3, "ContextPath", req.getContextPath()); ServletUtil.writeXMLElement(out, 3, "PathInfo", req.getPathInfo()); ServletUtil.writeXMLElement(out, 3, "PathTranslated", req.getPathTranslated()); ServletUtil.writeXMLElement(out, 3, "QueryString", req.getQueryString()); ServletUtil.writeXMLElement(out, 3, "RemoteUser", req.getRemoteUser()); ServletUtil.writeXMLElement(out, 3, "RequestURI", req.getRequestURI()); ServletUtil.writeXMLElement(out, 3, "RequestURL", req.getRequestURL().toString()); ServletUtil.writeXMLElement(out, 3, "ServletPath", req.getServletPath()); ServletUtil.writeXMLTag(out, 3, "Headers", false); for (Enumeration names = req.getHeaderNames(); names.hasMoreElements(); ) { String name = (String)(names.nextElement()); for (Enumeration e = req.getHeaders(name); e.hasMoreElements(); ) ServletUtil.writeXMLElement(out, 4, name, (String)(e.nextElement())); } ServletUtil.writeXMLTag(out, 3, "Headers", true); ServletUtil.writeXMLTag(out, 2, "HttpServletRequest", true); ServletUtil.writeXMLTag(out, 2, "ServletRequest", false); ServletUtil.writeXMLElement(out, 3, "Protocol", req.getProtocol()); ServletUtil.writeXMLElement(out, 3, "Scheme", req.getScheme()); ServletUtil.writeXMLElement(out, 3, "ServerName", req.getServerName()); ServletUtil.writeXMLElement(out, 3, "ServerPort", String.valueOf(req.getServerPort())); ServletUtil.writeXMLElement(out, 3, "RemoteAddr", req.getRemoteAddr()); ServletUtil.writeXMLElement(out, 3, "RemoteHost", req.getRemoteHost()); Enumeration names; ServletUtil.writeXMLTag(out, 3, "Attributes", false); for (names = req.getAttributeNames(); names.hasMoreElements(); ) { String name = (String)(names.nextElement()); ServletUtil.writeXMLElement(out, 4, name, req.getAttribute(name).toString()); } ServletUtil.writeXMLTag(out, 3, "Attributes", true); ServletUtil.writeXMLTag(out, 3, "Parameters", false); for (names = req.getParameterNames(); names.hasMoreElements(); ) { String name = (String)(names.nextElement()); String[] params = req.getParameterValues(name); for (int i = 0; i < params.length; i++) ServletUtil.writeXMLElement(out, 4, name, params[i]); } ServletUtil.writeXMLTag(out, 3, "Parameters", true); ServletUtil.writeXMLTag(out, 2, "ServletRequest", true); ServletUtil.writeRootTag(out, true); out.close(); return true; } /** * Verify the request originated from either the GSA or * localhost. Since the logs and the feed file may contain * proprietary customer information, we don't want to serve * them up to just anybody. * * @param gsaHost the GSA feed host * @param remoteAddr the IP address of the caller * @returns true if request came from an acceptable IP address. */ public static boolean allowedRemoteAddr(String gsaHost, String remoteAddr) { try { InetAddress caller = InetAddress.getByName(remoteAddr); if (caller.isLoopbackAddress() || caller.equals(InetAddress.getLocalHost())) { return true; // localhost is allowed access } InetAddress[] gsaAddrs = InetAddress.getAllByName(gsaHost); for (int i = 0; i < gsaAddrs.length; i++) { if (caller.equals(gsaAddrs[i])) { return true; // GSA is allowed access } } } catch (UnknownHostException uhe) { // Unknown host - fall through to fail. } return false; } private static final String DOCTYPE = "<!DOCTYPE html PUBLIC " + "\"-//W3C//DTD XHTML 1.0 Transitional//EN\" " + "\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">"; private static final String TEMP_ROOT_BEGIN_ELEMENT = "<filtered_root>"; private static final String TEMP_ROOT_END_ELEMENT = "</filtered_root>"; private static final String XHTML_DTD_URL = "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"; private static final String XHTML_DTD_FILE = "/xhtml1-transitional.dtd"; private static final String HTML_LAT1_URL = "http://www.w3.org/TR/xhtml1/DTD/xhtml-lat1.ent"; private static final String HTML_LAT1_FILE = "/xhtml-lat1.ent"; private static final String HTML_SYMBOL_URL = "http://www.w3.org/TR/xhtml1/DTD/xhtml-symbol.ent"; private static final String HTML_SYMBOL_FILE = "/xhtml-symbol.ent"; private static final String HTML_SPECIAL_URL = "http://www.w3.org/TR/xhtml1/DTD/xhtml-special.ent"; private static final String HTML_SPECIAL_FILE = "/xhtml-special.ent"; private static class LocalEntityResolver implements EntityResolver { public InputSource resolveEntity(String publicId, String systemId) { URL url; if (XHTML_DTD_URL.equals(systemId)) { LOGGER.fine("publicId=" + publicId + "; systemId=" + systemId); url = getClass().getResource(XHTML_DTD_FILE); if (url != null) { // Go with local resource. LOGGER.fine("Resolving " + XHTML_DTD_URL + " to local entity"); return new InputSource(url.toString()); } else { // Go with the HTTP URL. LOGGER.fine("Unable to resolve " + XHTML_DTD_URL + " to local entity"); return null; } } else if (HTML_LAT1_URL.equals(systemId)) { url = getClass().getResource(HTML_LAT1_FILE); if (url != null) { return new InputSource(url.toString()); } else { return null; } } else if (HTML_SYMBOL_URL.equals(systemId)) { url = getClass().getResource(HTML_SYMBOL_FILE); if (url != null) { return new InputSource(url.toString()); } else { return null; } } else if (HTML_SPECIAL_URL.equals(systemId)) { url = getClass().getResource(HTML_SPECIAL_FILE); if (url != null) { return new InputSource(url.toString()); } else { return null; } } else { return null; } } } /** * Utility function to scan the form snippet for any sensitive values and * replace them with obfuscated values. * * @param formSnippet the form snippet to scan. Expected to be a collection * of table rows (&lt;TR&gt;) containing input elements used within an * HTML FORM. Should not contain the actual HTML FORM element. * @return given formSnippet will all the sensitive values obfuscated. * Returns null on error. Therefore caller should check result before * using. */ public static String filterSensitiveData(String formSnippet) { boolean valueObfuscated = false; // Wrap the given form in a temporary root. String rootSnippet = DOCTYPE + TEMP_ROOT_BEGIN_ELEMENT + formSnippet + TEMP_ROOT_END_ELEMENT; // Convert to DOM tree and obfuscated values if needed. Document document = ServletUtil.parse(rootSnippet, new SAXParseErrorHandler(), new LocalEntityResolver()); if (document == null) { LOGGER.log(Level.WARNING, "XML parsing exception!"); return null; } NodeList nodeList = document.getElementsByTagName("input"); int length = nodeList.getLength(); for (int n = 0; n < length; ++n) { // Find any names that are sensitive and obfuscate their values. Element element = (Element) nodeList.item(n); if (SecurityUtils.isKeySensitive(element.getAttribute("name")) && element.hasAttribute("value") && element.getAttribute("type").equalsIgnoreCase("password")) { element.setAttribute("value", obfuscateValue(element.getAttribute("value"))); valueObfuscated = true; } } if (!valueObfuscated) { // Form snippet was not touched - just return it. return formSnippet; } else { // Part of form snippet was obfuscated. Transform the DOM tree back into // a string. String filteredSnippet; try { TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.METHOD, "html"); transformer.setOutputProperty(OutputKeys.VERSION, "4.0"); + transformer.setOutputProperty(OutputKeys.INDENT, "no"); DOMSource source = new DOMSource(document); StreamResult result = new StreamResult(new StringWriter()); transformer.transform(source, result); filteredSnippet = result.getWriter().toString(); } catch (TransformerException unexpected) { LOGGER.log(Level.WARNING, "XML transformation error!", unexpected); return null; } // Remove the temporary root element. filteredSnippet = filteredSnippet.substring( TEMP_ROOT_BEGIN_ELEMENT.length(), filteredSnippet.length() - TEMP_ROOT_END_ELEMENT.length()); return filteredSnippet; } } /** * Utility function to replace any sensitive values in the given config data * that are obfuscated with open values from the previous configuration. * * @param configData the updated config properties that may still include some * obfuscated values. * @param previousConfigData the current or previous set of properties that * have all the values in the clear. */ public static void replaceSensitiveData(Map configData, Map previousConfigData) { for (Iterator iter = configData.keySet().iterator(); iter.hasNext(); ) { String key = (String) iter.next(); // Revert if the key is sensitive and the string is still obfuscated and // hasn't changed in length. if (SecurityUtils.isKeySensitive(key) && isObfuscated((String) configData.get(key)) && ((String) configData.get(key)).length() == ((String) previousConfigData.get(key)).length()) { configData.put(key, previousConfigData.get(key)); } } } protected static String obfuscateValue(String value) { return value.replaceAll(".", "*"); } // Entire string of one or more '*' characters. private static final Pattern OBFUSCATED_PATTERN = Pattern.compile("^\\*+$"); /** * @param value the value to be checked. * @return true if the given value is obfuscated. */ protected static boolean isObfuscated(String value) { Matcher matcher = OBFUSCATED_PATTERN.matcher(value); return matcher.matches(); } }
true
true
public static String filterSensitiveData(String formSnippet) { boolean valueObfuscated = false; // Wrap the given form in a temporary root. String rootSnippet = DOCTYPE + TEMP_ROOT_BEGIN_ELEMENT + formSnippet + TEMP_ROOT_END_ELEMENT; // Convert to DOM tree and obfuscated values if needed. Document document = ServletUtil.parse(rootSnippet, new SAXParseErrorHandler(), new LocalEntityResolver()); if (document == null) { LOGGER.log(Level.WARNING, "XML parsing exception!"); return null; } NodeList nodeList = document.getElementsByTagName("input"); int length = nodeList.getLength(); for (int n = 0; n < length; ++n) { // Find any names that are sensitive and obfuscate their values. Element element = (Element) nodeList.item(n); if (SecurityUtils.isKeySensitive(element.getAttribute("name")) && element.hasAttribute("value") && element.getAttribute("type").equalsIgnoreCase("password")) { element.setAttribute("value", obfuscateValue(element.getAttribute("value"))); valueObfuscated = true; } } if (!valueObfuscated) { // Form snippet was not touched - just return it. return formSnippet; } else { // Part of form snippet was obfuscated. Transform the DOM tree back into // a string. String filteredSnippet; try { TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.METHOD, "html"); transformer.setOutputProperty(OutputKeys.VERSION, "4.0"); DOMSource source = new DOMSource(document); StreamResult result = new StreamResult(new StringWriter()); transformer.transform(source, result); filteredSnippet = result.getWriter().toString(); } catch (TransformerException unexpected) { LOGGER.log(Level.WARNING, "XML transformation error!", unexpected); return null; } // Remove the temporary root element. filteredSnippet = filteredSnippet.substring( TEMP_ROOT_BEGIN_ELEMENT.length(), filteredSnippet.length() - TEMP_ROOT_END_ELEMENT.length()); return filteredSnippet; } }
public static String filterSensitiveData(String formSnippet) { boolean valueObfuscated = false; // Wrap the given form in a temporary root. String rootSnippet = DOCTYPE + TEMP_ROOT_BEGIN_ELEMENT + formSnippet + TEMP_ROOT_END_ELEMENT; // Convert to DOM tree and obfuscated values if needed. Document document = ServletUtil.parse(rootSnippet, new SAXParseErrorHandler(), new LocalEntityResolver()); if (document == null) { LOGGER.log(Level.WARNING, "XML parsing exception!"); return null; } NodeList nodeList = document.getElementsByTagName("input"); int length = nodeList.getLength(); for (int n = 0; n < length; ++n) { // Find any names that are sensitive and obfuscate their values. Element element = (Element) nodeList.item(n); if (SecurityUtils.isKeySensitive(element.getAttribute("name")) && element.hasAttribute("value") && element.getAttribute("type").equalsIgnoreCase("password")) { element.setAttribute("value", obfuscateValue(element.getAttribute("value"))); valueObfuscated = true; } } if (!valueObfuscated) { // Form snippet was not touched - just return it. return formSnippet; } else { // Part of form snippet was obfuscated. Transform the DOM tree back into // a string. String filteredSnippet; try { TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.METHOD, "html"); transformer.setOutputProperty(OutputKeys.VERSION, "4.0"); transformer.setOutputProperty(OutputKeys.INDENT, "no"); DOMSource source = new DOMSource(document); StreamResult result = new StreamResult(new StringWriter()); transformer.transform(source, result); filteredSnippet = result.getWriter().toString(); } catch (TransformerException unexpected) { LOGGER.log(Level.WARNING, "XML transformation error!", unexpected); return null; } // Remove the temporary root element. filteredSnippet = filteredSnippet.substring( TEMP_ROOT_BEGIN_ELEMENT.length(), filteredSnippet.length() - TEMP_ROOT_END_ELEMENT.length()); return filteredSnippet; } }
diff --git a/src/org/servalproject/LogActivity.java b/src/org/servalproject/LogActivity.java index 325ec976..111b11d8 100644 --- a/src/org/servalproject/LogActivity.java +++ b/src/org/servalproject/LogActivity.java @@ -1,187 +1,187 @@ /** * Copyright (C) 2011 The Serval Project * * This file is part of Serval Software (http://www.servalproject.org) * * Serval Software 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 source code is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this source code; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /** * 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. * You should have received a copy of the GNU General Public License along with * this program; if not, see <http://www.gnu.org/licenses/>. * Use this application at your own risk. * * Copyright (c) 2009 by Harald Mueller and Seth Lemons. */ package org.servalproject; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.List; import org.servalproject.system.ChipsetDetection; import android.app.Activity; import android.os.Bundle; import android.webkit.WebSettings; import android.webkit.WebView; public class LogActivity extends Activity { public static final String MSG_TAG = "ADHOC -> AccessControlActivity"; private static final String HEADER = "<html><head><title>background-color</title> "+ "<style type=\"text/css\"> "+ "body { background-color:#181818; font-family:Arial; font-size:100%; color: #ffffff } "+ ".date { font-family:Arial; font-size:80%; font-weight:bold} "+ ".done { font-family:Arial; font-size:80%; color: #2ff425} "+ ".failed { font-family:Arial; font-size:80%; color: #ff3636} "+ ".heading { font-family:Arial; text-decoration: underline; font-size:100%; font-weight: bold; color: #ffffff} " + ".skipped { font-family:Arial; font-size:80%; color: #6268e5} "+ "</style> "+ "</head><body>"; private static final String FOOTER = "</body></html>"; private WebView webView = null; private ServalBatPhoneApplication application; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.logview); // Init Application this.application = (ServalBatPhoneApplication)this.getApplication(); this.webView = (WebView) findViewById(R.id.webviewLog); this.webView.getSettings().setJavaScriptEnabled(false); this.webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE); this.webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(false); this.webView.getSettings().setPluginsEnabled(false); this.webView.getSettings().setSupportMultipleWindows(false); this.webView.getSettings().setSupportZoom(false); this.setWebViewContent(); } private void setWebViewContent() { this.webView.loadDataWithBaseURL("fake://fakeme",HEADER+this.readLogfile()+FOOTER , "text/html", "UTF-8", "fake://fakeme"); } private String readLogfile(){ FileInputStream fis = null; InputStreamReader isr = null; String data = ""; List<String> logfiles = ChipsetDetection .getList("/data/data/org.servalproject/conf/logfiles.list"); for (String l : logfiles) { if (l.indexOf(":") == -1) continue; - String logfile = l.substring(1, l.indexOf(":") - 1); + String logfile = l.substring(0, l.indexOf(":")); String description = l.substring(l.indexOf(":") + 1, l.length()); data = data + "<div class=\"heading\">"+description+"</div>\n"; try { File file = new File("/data/data/org.servalproject/var/" + logfile + ".log"); fis = new FileInputStream(file); isr = new InputStreamReader(fis, "utf-8"); char[] buff = new char[(int) file.length()]; isr.read(buff); data = data + new String(buff); } catch (Exception e) { // We don't need to display anything, just put a message in the // log data = data + "<div class=\"failed\">No messages</div>"; // this.application.displayToastMessage("Unable to open log-File!"); } finally { try { if (isr != null) isr.close(); if (fis != null) fis.close(); } catch (Exception e) { // nothing } } } return data; } public static void logMessage(String logname, String message, boolean failedP) { BufferedWriter writer = null; try { writer = new BufferedWriter(new FileWriter( "/data/data/org.servalproject/var/" + logname + ".log", true), 256); Calendar currentDate = Calendar.getInstance(); SimpleDateFormat formatter = new SimpleDateFormat( "yyyy/MMM/dd HH:mm:ss"); String dateNow = formatter.format(currentDate.getTime()); writer.write("<div class=\"date\">" + dateNow + "</div>\n"); writer.write("<div class=\"action\">" + message + "</div>\n"); writer.write("<div class=\""); if (failedP) writer.write("failed\">failed"); else writer.write("done\">done"); writer.write("</div>\n"); writer.close(); } catch (IOException e) { // Should we do something here? try { if (writer != null) writer.close(); } catch (IOException e2) { } } return; } public static void logErase(String logname) { BufferedWriter writer = null; try { writer = new BufferedWriter(new FileWriter( "/data/data/org.servalproject/var/" + logname + ".log", true), 256); writer.close(); } catch (IOException e) { // Should we do something here? try { if (writer != null) writer.close(); } catch (IOException e2) { } } return; } }
true
true
private String readLogfile(){ FileInputStream fis = null; InputStreamReader isr = null; String data = ""; List<String> logfiles = ChipsetDetection .getList("/data/data/org.servalproject/conf/logfiles.list"); for (String l : logfiles) { if (l.indexOf(":") == -1) continue; String logfile = l.substring(1, l.indexOf(":") - 1); String description = l.substring(l.indexOf(":") + 1, l.length()); data = data + "<div class=\"heading\">"+description+"</div>\n"; try { File file = new File("/data/data/org.servalproject/var/" + logfile + ".log"); fis = new FileInputStream(file); isr = new InputStreamReader(fis, "utf-8"); char[] buff = new char[(int) file.length()]; isr.read(buff); data = data + new String(buff); } catch (Exception e) { // We don't need to display anything, just put a message in the // log data = data + "<div class=\"failed\">No messages</div>"; // this.application.displayToastMessage("Unable to open log-File!"); } finally { try { if (isr != null) isr.close(); if (fis != null) fis.close(); } catch (Exception e) { // nothing } } } return data; }
private String readLogfile(){ FileInputStream fis = null; InputStreamReader isr = null; String data = ""; List<String> logfiles = ChipsetDetection .getList("/data/data/org.servalproject/conf/logfiles.list"); for (String l : logfiles) { if (l.indexOf(":") == -1) continue; String logfile = l.substring(0, l.indexOf(":")); String description = l.substring(l.indexOf(":") + 1, l.length()); data = data + "<div class=\"heading\">"+description+"</div>\n"; try { File file = new File("/data/data/org.servalproject/var/" + logfile + ".log"); fis = new FileInputStream(file); isr = new InputStreamReader(fis, "utf-8"); char[] buff = new char[(int) file.length()]; isr.read(buff); data = data + new String(buff); } catch (Exception e) { // We don't need to display anything, just put a message in the // log data = data + "<div class=\"failed\">No messages</div>"; // this.application.displayToastMessage("Unable to open log-File!"); } finally { try { if (isr != null) isr.close(); if (fis != null) fis.close(); } catch (Exception e) { // nothing } } } return data; }
diff --git a/src/main/java/pl/psnc/dl/wf4ever/dlibra/UserProfile.java b/src/main/java/pl/psnc/dl/wf4ever/dlibra/UserProfile.java index b642603..0e9da42 100644 --- a/src/main/java/pl/psnc/dl/wf4ever/dlibra/UserProfile.java +++ b/src/main/java/pl/psnc/dl/wf4ever/dlibra/UserProfile.java @@ -1,141 +1,143 @@ /** * */ package pl.psnc.dl.wf4ever.dlibra; import java.net.URI; import java.net.URISyntaxException; import org.apache.log4j.Logger; /** * @author piotrhol * */ public class UserProfile { public enum Role { ADMIN, AUTHENTICATED, PUBLIC } private final static Logger logger = Logger.getLogger(UserProfile.class); private final String login; private final String password; private final String name; private final Role role; private final URI uri; private URI homePage; /** * @param login * @param name */ public UserProfile(String login, String password, String name, Role role, URI uri) { super(); this.login = login; this.password = password; this.name = name; this.role = role; this.uri = generateAbsoluteURI(uri, login); } public static URI generateAbsoluteURI(URI uri, String login) { if (uri == null) { - uri = URI.create(login); - if (uri == null) { + try { + uri = new URI(login); + } + catch (URISyntaxException e2) { try { uri = new URI(null, login, null); } catch (URISyntaxException e) { try { uri = new URI(null, login.replaceAll("\\W", ""), null); } catch (URISyntaxException e1) { //impossible logger.error(e1); } } } } if (!uri.isAbsolute()) uri = URI.create("http://sandbox.wf4ever.project.com/users/").resolve(uri); return uri; } /** * @param login * @param name */ public UserProfile(String login, String password, String name, Role role) { this(login, password, name, role, null); } /** * @param uri * the uri to set */ public void setHomePage(URI uri) { this.homePage = uri; } /** * @return the uri */ public URI getHomePage() { return homePage; } public String getLogin() { return login; } /** * @return the password */ public String getPassword() { return password; } public String getName() { return name; } public Role getRole() { return role; } /** * @return the uri */ public URI getUri() { return uri; } }
true
true
public static URI generateAbsoluteURI(URI uri, String login) { if (uri == null) { uri = URI.create(login); if (uri == null) { try { uri = new URI(null, login, null); } catch (URISyntaxException e) { try { uri = new URI(null, login.replaceAll("\\W", ""), null); } catch (URISyntaxException e1) { //impossible logger.error(e1); } } } } if (!uri.isAbsolute()) uri = URI.create("http://sandbox.wf4ever.project.com/users/").resolve(uri); return uri; }
public static URI generateAbsoluteURI(URI uri, String login) { if (uri == null) { try { uri = new URI(login); } catch (URISyntaxException e2) { try { uri = new URI(null, login, null); } catch (URISyntaxException e) { try { uri = new URI(null, login.replaceAll("\\W", ""), null); } catch (URISyntaxException e1) { //impossible logger.error(e1); } } } } if (!uri.isAbsolute()) uri = URI.create("http://sandbox.wf4ever.project.com/users/").resolve(uri); return uri; }
diff --git a/src/main/java/servlet/UploadServlet.java b/src/main/java/servlet/UploadServlet.java index c77531a..0a5708d 100644 --- a/src/main/java/servlet/UploadServlet.java +++ b/src/main/java/servlet/UploadServlet.java @@ -1,82 +1,82 @@ package servlet; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileItemFactory; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.io.IOUtils; public class UploadServlet extends HttpServlet { private static final long serialVersionUID = -8279791785237277465L; private static final String TASKS_DIRECTORY = "/vol/project/2012/362/g1236218/TaskFiles/"; @SuppressWarnings("unchecked") protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); //add to db - check task in db, add to subtasks, //adds to filesystem List<FileItem> items = null; FileItem file = null; String taskDir = ""; String filename = ""; try { items = (List<FileItem>) new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); } catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); return; } for( FileItem item : items ) { if(item.isFormField()) { String field = item.getFieldName(); if (field.equals("task")) { - String task = file.getString(); + String task = item.getString(); if (task == null) { //output need task name } else { //task is task name - add task to db if not yet inputted taskDir = TASKS_DIRECTORY + task + "/"; } } } else { file = item; filename = file.getName(); } } InputStream fileIn = file.getInputStream(); OutputStream fileOut = new FileOutputStream(taskDir + filename); IOUtils.copy(fileIn, fileOut); fileOut.close(); out.println("<html>"); out.println("<body>"); out.println("uploaded \""+filename + "\" to task " + taskDir + "<br>"); out.println("click <a href=index.jsp>here</a> to return to the homepage"); out.println("</body>"); out.println("</html>"); } }
true
true
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); //add to db - check task in db, add to subtasks, //adds to filesystem List<FileItem> items = null; FileItem file = null; String taskDir = ""; String filename = ""; try { items = (List<FileItem>) new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); } catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); return; } for( FileItem item : items ) { if(item.isFormField()) { String field = item.getFieldName(); if (field.equals("task")) { String task = file.getString(); if (task == null) { //output need task name } else { //task is task name - add task to db if not yet inputted taskDir = TASKS_DIRECTORY + task + "/"; } } } else { file = item; filename = file.getName(); } } InputStream fileIn = file.getInputStream(); OutputStream fileOut = new FileOutputStream(taskDir + filename); IOUtils.copy(fileIn, fileOut); fileOut.close(); out.println("<html>"); out.println("<body>"); out.println("uploaded \""+filename + "\" to task " + taskDir + "<br>"); out.println("click <a href=index.jsp>here</a> to return to the homepage"); out.println("</body>"); out.println("</html>"); }
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); //add to db - check task in db, add to subtasks, //adds to filesystem List<FileItem> items = null; FileItem file = null; String taskDir = ""; String filename = ""; try { items = (List<FileItem>) new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); } catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); return; } for( FileItem item : items ) { if(item.isFormField()) { String field = item.getFieldName(); if (field.equals("task")) { String task = item.getString(); if (task == null) { //output need task name } else { //task is task name - add task to db if not yet inputted taskDir = TASKS_DIRECTORY + task + "/"; } } } else { file = item; filename = file.getName(); } } InputStream fileIn = file.getInputStream(); OutputStream fileOut = new FileOutputStream(taskDir + filename); IOUtils.copy(fileIn, fileOut); fileOut.close(); out.println("<html>"); out.println("<body>"); out.println("uploaded \""+filename + "\" to task " + taskDir + "<br>"); out.println("click <a href=index.jsp>here</a> to return to the homepage"); out.println("</body>"); out.println("</html>"); }
diff --git a/src/api/org/openmrs/util/OpenmrsConstants.java b/src/api/org/openmrs/util/OpenmrsConstants.java index 5e982526..38da0e1d 100644 --- a/src/api/org/openmrs/util/OpenmrsConstants.java +++ b/src/api/org/openmrs/util/OpenmrsConstants.java @@ -1,1207 +1,1204 @@ /** * The contents of this file are subject to the OpenMRS 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://license.openmrs.org * * 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) OpenMRS, LLC. All Rights Reserved. */ package org.openmrs.util; import java.util.Collection; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Vector; import org.openmrs.GlobalProperty; import org.openmrs.Privilege; import org.openmrs.api.ConceptService; import org.openmrs.module.ModuleConstants; import org.openmrs.module.ModuleFactory; import org.openmrs.patient.impl.LuhnIdentifierValidator; import org.openmrs.scheduler.SchedulerConstants; /** * Constants used in OpenMRS. Contents built from build properties (version, version_short, and * expected_database). Some are set at runtime (database, database version). This file should * contain all privilege names and global property names. Those strings added to the static CORE_* * methods will be written to the database at startup if they don't exist yet. */ public final class OpenmrsConstants { //private static Log log = LogFactory.getLog(OpenmrsConstants.class); /** * This is the hard coded primary key of the order type for DRUG. This has to be done because * some logic in the API acts on this order type */ public static final int ORDERTYPE_DRUG = 2; /** * This is the hard coded primary key of the concept class for DRUG. This has to be done because * some logic in the API acts on this concept class */ public static final int CONCEPT_CLASS_DRUG = 3; /** * hack alert: During an ant build, the openmrs api jar manifest file is loaded with these * values. When constructing the OpenmrsConstants class file, the api jar is read and the values * are copied in as constants */ private static final Package THIS_PACKAGE = OpenmrsConstants.class.getPackage(); public static final String OPENMRS_VERSION = THIS_PACKAGE.getSpecificationVendor(); public static final String OPENMRS_VERSION_SHORT = THIS_PACKAGE.getSpecificationVersion(); /** * See {@link DatabaseUpdater#updatesRequired()} to see what changesets in the * liquibase-update-to-latest.xml file in the openmrs api jar file need to be run to bring the * db up to date with what the api requires. * * @deprecated the database doesn't have just one main version now that we are using liquibase. */ public static final String DATABASE_VERSION_EXPECTED = THIS_PACKAGE.getImplementationVersion(); public static String DATABASE_NAME = "openmrs"; public static String DATABASE_BUSINESS_NAME = "openmrs"; /** * See {@link DatabaseUpdater#updatesRequired()} to see what changesets in the * liquibase-update-to-latest.xml file in the openmrs api jar file need to be run to bring the * db up to date with what the api requires. * * @deprecated the database doesn't have just one main version now that we are using liquibase. */ public static String DATABASE_VERSION = null; /** * Set true from runtime configuration to obscure patients for system demonstrations */ public static boolean OBSCURE_PATIENTS = false; public static String OBSCURE_PATIENTS_GIVEN_NAME = "Demo"; public static String OBSCURE_PATIENTS_MIDDLE_NAME = null; public static String OBSCURE_PATIENTS_FAMILY_NAME = "Person"; public static final String REGEX_LARGE = "[!\"#\\$%&'\\(\\)\\*,+-\\./:;<=>\\?@\\[\\\\\\\\\\]^_`{\\|}~]"; public static final String REGEX_SMALL = "[!\"#\\$%&'\\(\\)\\*,\\./:;<=>\\?@\\[\\\\\\\\\\]^_`{\\|}~]"; public static final Integer CIVIL_STATUS_CONCEPT_ID = 1054; /** * The directory that will store filesystem data about openmrs like module omods, generated data * exports, etc. This shouldn't be accessed directory, the * OpenmrsUtil.getApplicationDataDirectory() should be used. This should be null here. This * constant will hold the value of the user's runtime property for the * application_data_directory and is set programmatically at startup. This value is set in the * openmrs startup method If this is null, the getApplicationDataDirectory() uses some OS * heuristics to determine where to put an app data dir. * * @see #APPLICATION_DATA_DIRECTORY_RUNTIME_PROPERTY * @see OpenmrsUtil#getApplicationDataDirectory() * @see OpenmrsUtil#startup(java.util.Properties) */ public static String APPLICATION_DATA_DIRECTORY = null; /** * The name of the runtime property that a user can set that will specify where openmrs's * application directory is * * @see #APPLICATION_DATA_DIRECTORY */ public static String APPLICATION_DATA_DIRECTORY_RUNTIME_PROPERTY = "application_data_directory"; /** * The name of the runtime property that a user can set that will specify whether the database * is automatically updated on startup */ public static String AUTO_UPDATE_DATABASE_RUNTIME_PROPERTY = "auto_update_database"; /** * These words are ignored in concept and patient searches * * @return Collection<String> of words that are ignored */ public static final Collection<String> STOP_WORDS() { List<String> stopWords = new Vector<String>(); stopWords.add("A"); stopWords.add("AND"); stopWords.add("AT"); stopWords.add("BUT"); stopWords.add("BY"); stopWords.add("FOR"); stopWords.add("HAS"); stopWords.add("OF"); stopWords.add("THE"); stopWords.add("TO"); return stopWords; } /** * A gender character to gender name map<br/> * TODO issues with localization. How should this be handled? * * @return Map<String, String> of gender character to gender name */ public static final Map<String, String> GENDER() { Map<String, String> genders = new LinkedHashMap<String, String>(); genders.put("M", "Male"); genders.put("F", "Female"); return genders; } // Baked in Privileges: public static final String PRIV_VIEW_CONCEPTS = "View Concepts"; public static final String PRIV_MANAGE_CONCEPTS = "Manage Concepts"; public static final String PRIV_PURGE_CONCEPTS = "Purge Concepts"; public static final String PRIV_VIEW_CONCEPT_PROPOSALS = "View Concept Proposals"; public static final String PRIV_ADD_CONCEPT_PROPOSALS = "Add Concept Proposals"; public static final String PRIV_EDIT_CONCEPT_PROPOSALS = "Edit Concept Proposals"; public static final String PRIV_DELETE_CONCEPT_PROPOSALS = "Delete Concept Proposals"; public static final String PRIV_PURGE_CONCEPT_PROPOSALS = "Purge Concept Proposals"; public static final String PRIV_VIEW_USERS = "View Users"; public static final String PRIV_ADD_USERS = "Add Users"; public static final String PRIV_EDIT_USERS = "Edit Users"; public static final String PRIV_DELETE_USERS = "Delete Users"; public static final String PRIV_PURGE_USERS = "Purge Users"; public static final String PRIV_EDIT_USER_PASSWORDS = "Edit User Passwords"; public static final String PRIV_VIEW_ENCOUNTERS = "View Encounters"; public static final String PRIV_ADD_ENCOUNTERS = "Add Encounters"; public static final String PRIV_EDIT_ENCOUNTERS = "Edit Encounters"; public static final String PRIV_DELETE_ENCOUNTERS = "Delete Encounters"; public static final String PRIV_PURGE_ENCOUNTERS = "Purge Encounters"; public static final String PRIV_VIEW_ENCOUNTER_TYPES = "View Encounter Types"; public static final String PRIV_MANAGE_ENCOUNTER_TYPES = "Manage Encounter Types"; public static final String PRIV_PURGE_ENCOUNTER_TYPES = "Purge Encounter Types"; public static final String PRIV_VIEW_LOCATIONS = "View Locations"; public static final String PRIV_MANAGE_LOCATIONS = "Manage Locations"; public static final String PRIV_PURGE_LOCATIONS = "Purge Locations"; public static final String PRIV_MANAGE_LOCATION_TAGS = "Manage Location Tags"; public static final String PRIV_PURGE_LOCATION_TAGS = "Purge Location Tags"; public static final String PRIV_VIEW_OBS = "View Observations"; public static final String PRIV_ADD_OBS = "Add Observations"; public static final String PRIV_EDIT_OBS = "Edit Observations"; public static final String PRIV_DELETE_OBS = "Delete Observations"; public static final String PRIV_PURGE_OBS = "Purge Observations"; @Deprecated public static final String PRIV_VIEW_MIME_TYPES = "View Mime Types"; @Deprecated public static final String PRIV_PURGE_MIME_TYPES = "Purge Mime Types"; public static final String PRIV_VIEW_PATIENTS = "View Patients"; public static final String PRIV_ADD_PATIENTS = "Add Patients"; public static final String PRIV_EDIT_PATIENTS = "Edit Patients"; public static final String PRIV_DELETE_PATIENTS = "Delete Patients"; public static final String PRIV_PURGE_PATIENTS = "Purge Patients"; public static final String PRIV_VIEW_PATIENT_IDENTIFIERS = "View Patient Identifiers"; public static final String PRIV_ADD_PATIENT_IDENTIFIERS = "Add Patient Identifiers"; public static final String PRIV_EDIT_PATIENT_IDENTIFIERS = "Edit Patient Identifiers"; public static final String PRIV_DELETE_PATIENT_IDENTIFIERS = "Delete Patient Identifiers"; public static final String PRIV_PURGE_PATIENT_IDENTIFIERS = "Purge Patient Identifiers"; public static final String PRIV_VIEW_PATIENT_COHORTS = "View Patient Cohorts"; public static final String PRIV_ADD_COHORTS = "Add Cohorts"; public static final String PRIV_EDIT_COHORTS = "Edit Cohorts"; public static final String PRIV_DELETE_COHORTS = "Delete Cohorts"; public static final String PRIV_PURGE_COHORTS = "Purge Cohorts"; public static final String PRIV_VIEW_ORDERS = "View Orders"; public static final String PRIV_ADD_ORDERS = "Add Orders"; public static final String PRIV_EDIT_ORDERS = "Edit Orders"; public static final String PRIV_DELETE_ORDERS = "Delete Orders"; public static final String PRIV_PURGE_ORDERS = "Purge Orders"; public static final String PRIV_VIEW_FORMS = "View Forms"; public static final String PRIV_MANAGE_FORMS = "Manage Forms"; public static final String PRIV_PURGE_FORMS = "Purge Forms"; @Deprecated public static final String PRIV_VIEW_REPORTS = "View Reports"; @Deprecated public static final String PRIV_ADD_REPORTS = "Add Reports"; @Deprecated public static final String PRIV_EDIT_REPORTS = "Edit Reports"; @Deprecated public static final String PRIV_DELETE_REPORTS = "Delete Reports"; @Deprecated public static final String PRIV_RUN_REPORTS = "Run Reports"; @Deprecated public static final String PRIV_VIEW_REPORT_OBJECTS = "View Report Objects"; @Deprecated public static final String PRIV_ADD_REPORT_OBJECTS = "Add Report Objects"; @Deprecated public static final String PRIV_EDIT_REPORT_OBJECTS = "Edit Report Objects"; @Deprecated public static final String PRIV_DELETE_REPORT_OBJECTS = "Delete Report Objects"; public static final String PRIV_MANAGE_IDENTIFIER_TYPES = "Manage Identifier Types"; public static final String PRIV_VIEW_IDENTIFIER_TYPES = "View Identifier Types"; public static final String PRIV_PURGE_IDENTIFIER_TYPES = "Purge Identifier Types"; @Deprecated public static final String PRIV_MANAGE_MIME_TYPES = "Manage Mime Types"; public static final String PRIV_VIEW_CONCEPT_CLASSES = "View Concept Classes"; public static final String PRIV_MANAGE_CONCEPT_CLASSES = "Manage Concept Classes"; public static final String PRIV_PURGE_CONCEPT_CLASSES = "Purge Concept Classes"; public static final String PRIV_VIEW_CONCEPT_DATATYPES = "View Concept Datatypes"; public static final String PRIV_MANAGE_CONCEPT_DATATYPES = "Manage Concept Datatypes"; public static final String PRIV_PURGE_CONCEPT_DATATYPES = "Purge Concept Datatypes"; public static final String PRIV_VIEW_PRIVILEGES = "View Privileges"; public static final String PRIV_MANAGE_PRIVILEGES = "Manage Privileges"; public static final String PRIV_PURGE_PRIVILEGES = "Purge Privileges"; public static final String PRIV_VIEW_ROLES = "View Roles"; public static final String PRIV_MANAGE_ROLES = "Manage Roles"; public static final String PRIV_PURGE_ROLES = "Purge Roles"; public static final String PRIV_VIEW_FIELD_TYPES = "View Field Types"; public static final String PRIV_MANAGE_FIELD_TYPES = "Manage Field Types"; public static final String PRIV_PURGE_FIELD_TYPES = "Purge Field Types"; public static final String PRIV_VIEW_ORDER_TYPES = "View Order Types"; public static final String PRIV_MANAGE_ORDER_TYPES = "Manage Order Types"; public static final String PRIV_PURGE_ORDER_TYPES = "Purge Order Types"; public static final String PRIV_VIEW_RELATIONSHIP_TYPES = "View Relationship Types"; public static final String PRIV_MANAGE_RELATIONSHIP_TYPES = "Manage Relationship Types"; public static final String PRIV_PURGE_RELATIONSHIP_TYPES = "Purge Relationship Types"; public static final String PRIV_MANAGE_ALERTS = "Manage Alerts"; public static final String PRIV_MANAGE_CONCEPT_SOURCES = "Manage Concept Sources"; public static final String PRIV_VIEW_CONCEPT_SOURCES = "View Concept Sources"; public static final String PRIV_PURGE_CONCEPT_SOURCES = "Purge Concept Sources"; public static final String PRIV_VIEW_NAVIGATION_MENU = "View Navigation Menu"; public static final String PRIV_VIEW_ADMIN_FUNCTIONS = "View Administration Functions"; public static final String PRIV_VIEW_UNPUBLISHED_FORMS = "View Unpublished Forms"; public static final String PRIV_VIEW_PROGRAMS = "View Programs"; public static final String PRIV_MANAGE_PROGRAMS = "Manage Programs"; public static final String PRIV_VIEW_PATIENT_PROGRAMS = "View Patient Programs"; public static final String PRIV_ADD_PATIENT_PROGRAMS = "Add Patient Programs"; public static final String PRIV_EDIT_PATIENT_PROGRAMS = "Edit Patient Programs"; public static final String PRIV_DELETE_PATIENT_PROGRAMS = "Delete Patient Programs"; public static final String PRIV_PURGE_PATIENT_PROGRAMS = "Add Patient Programs"; public static final String PRIV_DASHBOARD_OVERVIEW = "Patient Dashboard - View Overview Section"; public static final String PRIV_DASHBOARD_REGIMEN = "Patient Dashboard - View Regimen Section"; public static final String PRIV_DASHBOARD_ENCOUNTERS = "Patient Dashboard - View Encounters Section"; public static final String PRIV_DASHBOARD_DEMOGRAPHICS = "Patient Dashboard - View Demographics Section"; public static final String PRIV_DASHBOARD_GRAPHS = "Patient Dashboard - View Graphs Section"; public static final String PRIV_DASHBOARD_FORMS = "Patient Dashboard - View Forms Section"; public static final String PRIV_DASHBOARD_SUMMARY = "Patient Dashboard - View Patient Summary"; public static final String PRIV_VIEW_GLOBAL_PROPERTIES = "View Global Properties"; public static final String PRIV_MANAGE_GLOBAL_PROPERTIES = "Manage Global Properties"; public static final String PRIV_PURGE_GLOBAL_PROPERTIES = "Purge Global Properties"; public static final String PRIV_MANAGE_MODULES = "Manage Modules"; public static final String PRIV_MANAGE_SCHEDULER = "Manage Scheduler"; public static final String PRIV_VIEW_PERSON_ATTRIBUTE_TYPES = "View Person Attribute Types"; public static final String PRIV_MANAGE_PERSON_ATTRIBUTE_TYPES = "Manage Person Attribute Types"; public static final String PRIV_PURGE_PERSON_ATTRIBUTE_TYPES = "Purge Person Attribute Types"; public static final String PRIV_VIEW_PERSONS = "View People"; public static final String PRIV_ADD_PERSONS = "Add People"; public static final String PRIV_EDIT_PERSONS = "Edit People"; public static final String PRIV_DELETE_PERSONS = "Delete People"; public static final String PRIV_PURGE_PERSONS = "Purge People"; /** * @deprecated replacing with ADD/EDIT/DELETE privileges */ public static final String PRIV_MANAGE_RELATIONSHIPS = "Manage Relationships"; public static final String PRIV_VIEW_RELATIONSHIPS = "View Relationships"; public static final String PRIV_ADD_RELATIONSHIPS = "Add Relationships"; public static final String PRIV_EDIT_RELATIONSHIPS = "Edit Relationships"; public static final String PRIV_DELETE_RELATIONSHIPS = "Delete Relationships"; public static final String PRIV_PURGE_RELATIONSHIPS = "Purge Relationships"; public static final String PRIV_VIEW_DATABASE_CHANGES = "View Database Changes"; public static final String PRIV_MANAGE_IMPLEMENTATION_ID = "Manage Implementation Id"; public static final String PRIV_SQL_LEVEL_ACCESS = "SQL Level Access"; /** * Cached list of core privileges */ private static Map<String, String> CORE_PRIVILEGES = null; /** * These are the privileges that are required by OpenMRS. Upon startup, if any of these * privileges do not exist in the database, they are inserted. These privileges are not allowed * to be deleted. They are marked as 'locked' in the administration screens. * * @return privileges core to the system */ public static final Map<String, String> CORE_PRIVILEGES() { // if we don't have a cache, create one if (CORE_PRIVILEGES == null) { CORE_PRIVILEGES = new HashMap<String, String>(); CORE_PRIVILEGES.put(PRIV_VIEW_PROGRAMS, "Able to view patient programs"); CORE_PRIVILEGES.put(PRIV_MANAGE_PROGRAMS, "Able to add/view/delete patient programs"); CORE_PRIVILEGES.put(PRIV_VIEW_PATIENT_PROGRAMS, "Able to see which programs that patients are in"); CORE_PRIVILEGES.put(PRIV_ADD_PATIENT_PROGRAMS, "Able to add patients to programs"); CORE_PRIVILEGES.put(PRIV_EDIT_PATIENT_PROGRAMS, "Able to edit patients in programs"); CORE_PRIVILEGES.put(PRIV_DELETE_PATIENT_PROGRAMS, "Able to delete patients from programs"); CORE_PRIVILEGES.put(PRIV_VIEW_UNPUBLISHED_FORMS, "Able to view and fill out unpublished forms"); CORE_PRIVILEGES.put(PRIV_VIEW_CONCEPTS, "Able to view concept entries"); CORE_PRIVILEGES.put(PRIV_MANAGE_CONCEPTS, "Able to add/edit/delete concept entries"); CORE_PRIVILEGES.put(PRIV_VIEW_CONCEPT_PROPOSALS, "Able to view concept proposals to the system"); CORE_PRIVILEGES.put(PRIV_ADD_CONCEPT_PROPOSALS, "Able to add concept proposals to the system"); CORE_PRIVILEGES.put(PRIV_EDIT_CONCEPT_PROPOSALS, "Able to edit concept proposals in the system"); CORE_PRIVILEGES.put(PRIV_DELETE_CONCEPT_PROPOSALS, "Able to delete concept proposals from the system"); CORE_PRIVILEGES.put(PRIV_VIEW_USERS, "Able to view users in OpenMRS"); CORE_PRIVILEGES.put(PRIV_ADD_USERS, "Able to add users to OpenMRS"); CORE_PRIVILEGES.put(PRIV_EDIT_USERS, "Able to edit users in OpenMRS"); CORE_PRIVILEGES.put(PRIV_DELETE_USERS, "Able to delete users in OpenMRS"); CORE_PRIVILEGES.put(PRIV_EDIT_USER_PASSWORDS, "Able to change the passwords of users in OpenMRS"); CORE_PRIVILEGES.put(PRIV_VIEW_ENCOUNTERS, "Able to view patient encounters"); CORE_PRIVILEGES.put(PRIV_ADD_ENCOUNTERS, "Able to add patient encounters"); CORE_PRIVILEGES.put(PRIV_EDIT_ENCOUNTERS, "Able to edit patient encounters"); CORE_PRIVILEGES.put(PRIV_DELETE_ENCOUNTERS, "Able to delete patient encounters"); CORE_PRIVILEGES.put(PRIV_VIEW_OBS, "Able to view patient observations"); CORE_PRIVILEGES.put(PRIV_ADD_OBS, "Able to add patient observations"); CORE_PRIVILEGES.put(PRIV_EDIT_OBS, "Able to edit patient observations"); CORE_PRIVILEGES.put(PRIV_DELETE_OBS, "Able to delete patient observations"); CORE_PRIVILEGES.put(PRIV_VIEW_PATIENTS, "Able to view patients"); CORE_PRIVILEGES.put(PRIV_ADD_PATIENTS, "Able to add patients"); CORE_PRIVILEGES.put(PRIV_EDIT_PATIENTS, "Able to edit patients"); CORE_PRIVILEGES.put(PRIV_DELETE_PATIENTS, "Able to delete patients"); CORE_PRIVILEGES.put(PRIV_VIEW_PATIENT_IDENTIFIERS, "Able to view patient identifiers"); CORE_PRIVILEGES.put(PRIV_ADD_PATIENT_IDENTIFIERS, "Able to add patient identifiers"); CORE_PRIVILEGES.put(PRIV_EDIT_PATIENT_IDENTIFIERS, "Able to edit patient identifiers"); CORE_PRIVILEGES.put(PRIV_DELETE_PATIENT_IDENTIFIERS, "Able to delete patient identifiers"); CORE_PRIVILEGES.put(PRIV_VIEW_PATIENT_COHORTS, "Able to view patient cohorts"); CORE_PRIVILEGES.put(PRIV_ADD_COHORTS, "Able to add a cohort to the system"); CORE_PRIVILEGES.put(PRIV_EDIT_COHORTS, "Able to add a cohort to the system"); CORE_PRIVILEGES.put(PRIV_DELETE_COHORTS, "Able to add a cohort to the system"); CORE_PRIVILEGES.put(PRIV_VIEW_ORDERS, "Able to view orders"); CORE_PRIVILEGES.put(PRIV_ADD_ORDERS, "Able to add orders"); CORE_PRIVILEGES.put(PRIV_EDIT_ORDERS, "Able to edit orders"); CORE_PRIVILEGES.put(PRIV_DELETE_ORDERS, "Able to delete orders"); CORE_PRIVILEGES.put(PRIV_VIEW_FORMS, "Able to view forms"); CORE_PRIVILEGES.put(PRIV_MANAGE_FORMS, "Able to add/edit/delete forms"); CORE_PRIVILEGES.put(PRIV_VIEW_REPORTS, "Able to view reports"); CORE_PRIVILEGES.put(PRIV_ADD_REPORTS, "Able to add reports"); CORE_PRIVILEGES.put(PRIV_EDIT_REPORTS, "Able to edit reports"); CORE_PRIVILEGES.put(PRIV_DELETE_REPORTS, "Able to delete reports"); CORE_PRIVILEGES.put(PRIV_RUN_REPORTS, "Able to run reports"); CORE_PRIVILEGES.put(PRIV_VIEW_REPORT_OBJECTS, "Able to view report objects"); CORE_PRIVILEGES.put(PRIV_ADD_REPORT_OBJECTS, "Able to add report objects"); CORE_PRIVILEGES.put(PRIV_EDIT_REPORT_OBJECTS, "Able to edit report objects"); CORE_PRIVILEGES.put(PRIV_DELETE_REPORT_OBJECTS, "Able to delete report objects"); CORE_PRIVILEGES.put(PRIV_VIEW_IDENTIFIER_TYPES, "Able to view patient identifier types"); CORE_PRIVILEGES.put(PRIV_MANAGE_RELATIONSHIPS, "Able to add/edit/delete relationships"); CORE_PRIVILEGES.put(PRIV_MANAGE_IDENTIFIER_TYPES, "Able to add/edit/delete patient identifier types"); CORE_PRIVILEGES.put(PRIV_VIEW_LOCATIONS, "Able to view locations"); CORE_PRIVILEGES.put(PRIV_MANAGE_LOCATIONS, "Able to add/edit/delete locations"); CORE_PRIVILEGES.put(PRIV_MANAGE_LOCATION_TAGS, "Able to add/edit/delete location tags"); CORE_PRIVILEGES.put(PRIV_VIEW_CONCEPT_CLASSES, "Able to view concept classes"); CORE_PRIVILEGES.put(PRIV_MANAGE_CONCEPT_CLASSES, "Able to add/edit/retire concept classes"); CORE_PRIVILEGES.put(PRIV_VIEW_CONCEPT_DATATYPES, "Able to view concept datatypes"); CORE_PRIVILEGES.put(PRIV_MANAGE_CONCEPT_DATATYPES, "Able to add/edit/retire concept datatypes"); CORE_PRIVILEGES.put(PRIV_VIEW_ENCOUNTER_TYPES, "Able to view encounter types"); CORE_PRIVILEGES.put(PRIV_MANAGE_ENCOUNTER_TYPES, "Able to add/edit/delete encounter types"); CORE_PRIVILEGES.put(PRIV_VIEW_PRIVILEGES, "Able to view user privileges"); CORE_PRIVILEGES.put(PRIV_MANAGE_PRIVILEGES, "Able to add/edit/delete privileges"); CORE_PRIVILEGES.put(PRIV_VIEW_FIELD_TYPES, "Able to view field types"); CORE_PRIVILEGES.put(PRIV_MANAGE_FIELD_TYPES, "Able to add/edit/retire field types"); CORE_PRIVILEGES.put(PRIV_PURGE_FIELD_TYPES, "Able to purge field types"); CORE_PRIVILEGES.put(PRIV_MANAGE_ORDER_TYPES, "Able to add/edit/retire order types"); CORE_PRIVILEGES.put(PRIV_VIEW_ORDER_TYPES, "Able to view order types"); CORE_PRIVILEGES.put(PRIV_VIEW_RELATIONSHIP_TYPES, "Able to view relationship types"); CORE_PRIVILEGES.put(PRIV_MANAGE_RELATIONSHIP_TYPES, "Able to add/edit/retire relationship types"); CORE_PRIVILEGES.put(PRIV_MANAGE_ALERTS, "Able to add/edit/delete user alerts"); CORE_PRIVILEGES.put(PRIV_MANAGE_CONCEPT_SOURCES, "Able to add/edit/delete concept sources"); CORE_PRIVILEGES.put(PRIV_VIEW_CONCEPT_SOURCES, "Able to view concept sources"); CORE_PRIVILEGES.put(PRIV_VIEW_ROLES, "Able to view user roles"); CORE_PRIVILEGES.put(PRIV_MANAGE_ROLES, "Able to add/edit/delete user roles"); CORE_PRIVILEGES.put(PRIV_VIEW_NAVIGATION_MENU, "Able to view the navigation menu (Home, View Patients, Dictionary, Administration, My Profile)"); CORE_PRIVILEGES.put(PRIV_VIEW_ADMIN_FUNCTIONS, "Able to view the 'Administration' link in the navigation bar"); CORE_PRIVILEGES.put(PRIV_DASHBOARD_OVERVIEW, "Able to view the 'Overview' tab on the patient dashboard"); CORE_PRIVILEGES.put(PRIV_DASHBOARD_REGIMEN, "Able to view the 'Regimen' tab on the patient dashboard"); CORE_PRIVILEGES.put(PRIV_DASHBOARD_ENCOUNTERS, "Able to view the 'Encounters' tab on the patient dashboard"); CORE_PRIVILEGES.put(PRIV_DASHBOARD_DEMOGRAPHICS, "Able to view the 'Demographics' tab on the patient dashboard"); CORE_PRIVILEGES.put(PRIV_DASHBOARD_GRAPHS, "Able to view the 'Graphs' tab on the patient dashboard"); CORE_PRIVILEGES.put(PRIV_DASHBOARD_FORMS, "Able to view the 'Forms' tab on the patient dashboard"); CORE_PRIVILEGES.put(PRIV_DASHBOARD_SUMMARY, "Able to view the 'Summary' tab on the patient dashboard"); CORE_PRIVILEGES.put(PRIV_VIEW_GLOBAL_PROPERTIES, "Able to view global properties on the administration screen"); CORE_PRIVILEGES.put(PRIV_MANAGE_GLOBAL_PROPERTIES, "Able to add/edit global properties"); CORE_PRIVILEGES.put(PRIV_MANAGE_MODULES, "Able to add/remove modules to the system"); CORE_PRIVILEGES.put(PRIV_MANAGE_SCHEDULER, "Able to add/edit/remove scheduled tasks"); CORE_PRIVILEGES.put(PRIV_VIEW_PERSON_ATTRIBUTE_TYPES, "Able to view person attribute types"); CORE_PRIVILEGES.put(PRIV_MANAGE_PERSON_ATTRIBUTE_TYPES, "Able to add/edit/delete person attribute types"); CORE_PRIVILEGES.put(PRIV_VIEW_PERSONS, "Able to view person objects"); CORE_PRIVILEGES.put(PRIV_ADD_PERSONS, "Able to add person objects"); CORE_PRIVILEGES.put(PRIV_EDIT_PERSONS, "Able to edit person objects"); CORE_PRIVILEGES.put(PRIV_DELETE_PERSONS, "Able to delete objects"); CORE_PRIVILEGES.put(PRIV_VIEW_RELATIONSHIPS, "Able to view relationships"); CORE_PRIVILEGES.put(PRIV_ADD_RELATIONSHIPS, "Able to add relationships"); CORE_PRIVILEGES.put(PRIV_EDIT_RELATIONSHIPS, "Able to edit relationships"); CORE_PRIVILEGES.put(PRIV_DELETE_RELATIONSHIPS, "Able to delete relationships"); CORE_PRIVILEGES.put(PRIV_VIEW_DATABASE_CHANGES, "Able to view database changes from the admin screen"); CORE_PRIVILEGES.put(PRIV_MANAGE_IMPLEMENTATION_ID, "Able to view/add/edit the implementation id for the system"); } // always add the module core privileges back on for (Privilege privilege : ModuleFactory.getPrivileges()) { CORE_PRIVILEGES.put(privilege.getPrivilege(), privilege.getDescription()); } return CORE_PRIVILEGES; } // Baked in Roles: public static final String SUPERUSER_ROLE = "System Developer"; public static final String ANONYMOUS_ROLE = "Anonymous"; public static final String AUTHENTICATED_ROLE = "Authenticated"; public static final String PROVIDER_ROLE = "Provider"; /** * All roles returned by this method are inserted into the database if they do not exist * already. These roles are also forbidden to be deleted from the administration screens. * * @return roles that are core to the system */ public static final Map<String, String> CORE_ROLES() { Map<String, String> roles = new HashMap<String, String>(); roles .put(SUPERUSER_ROLE, "Assigned to developers of OpenMRS. Gives additional access to change fundamental structure of the database model."); roles.put(ANONYMOUS_ROLE, "Privileges for non-authenticated users."); roles.put(AUTHENTICATED_ROLE, "Privileges gained once authentication has been established."); roles.put(PROVIDER_ROLE, "All users with the 'Provider' role will appear as options in the default Infopath "); return roles; } /** * These roles are given to a user automatically and cannot be assigned * * @return <code>Collection<String></code> of the auto-assigned roles */ public static final Collection<String> AUTO_ROLES() { List<String> roles = new Vector<String>(); roles.add(ANONYMOUS_ROLE); roles.add(AUTHENTICATED_ROLE); return roles; } public static final String GLOBAL_PROPERTY_CONCEPTS_LOCKED = "concepts.locked"; public static final String GLOBAL_PROPERTY_PATIENT_LISTING_ATTRIBUTES = "patient.listingAttributeTypes"; public static final String GLOBAL_PROPERTY_PATIENT_VIEWING_ATTRIBUTES = "patient.viewingAttributeTypes"; public static final String GLOBAL_PROPERTY_PATIENT_HEADER_ATTRIBUTES = "patient.headerAttributeTypes"; public static final String GLOBAL_PROPERTY_USER_LISTING_ATTRIBUTES = "user.listingAttributeTypes"; public static final String GLOBAL_PROPERTY_USER_VIEWING_ATTRIBUTES = "user.viewingAttributeTypes"; public static final String GLOBAL_PROPERTY_USER_HEADER_ATTRIBUTES = "user.headerAttributeTypes"; public static final String GLOBAL_PROPERTY_PATIENT_IDENTIFIER_REGEX = "patient.identifierRegex"; public static final String GLOBAL_PROPERTY_PATIENT_IDENTIFIER_PREFIX = "patient.identifierPrefix"; public static final String GLOBAL_PROPERTY_PATIENT_IDENTIFIER_SUFFIX = "patient.identifierSuffix"; public static final String GLOBAL_PROPERTY_PATIENT_SEARCH_MAX_RESULTS = "patient.searchMaxResults"; public static final String GLOBAL_PROPERTY_GZIP_ENABLED = "gzip.enabled"; public static final String GLOBAL_PROPERTY_MEDICAL_RECORD_OBSERVATIONS = "concept.medicalRecordObservations"; public static final String GLOBAL_PROPERTY_PROBLEM_LIST = "concept.problemList"; @Deprecated public static final String GLOBAL_PROPERTY_REPORT_XML_MACROS = "report.xmlMacros"; public static final String GLOBAL_PROPERTY_STANDARD_DRUG_REGIMENS = "dashboard.regimen.standardRegimens"; public static final String GLOBAL_PROPERTY_DEFAULT_PATIENT_IDENTIFIER_VALIDATOR = "patient.defaultPatientIdentifierValidator"; public static final String GLOBAL_PROPERTY_PATIENT_IDENTIFIER_IMPORTANT_TYPES = "patient_identifier.importantTypes"; public static final String GLOBAL_PROPERTY_ENCOUNTER_FORM_OBS_SORT_ORDER = "encounterForm.obsSortOrder"; public static final String GLOBAL_PROPERTY_LOCALE_ALLOWED_LIST = "locale.allowed.list"; public static final String GLOBAL_PROPERTY_IMPLEMENTATION_ID = "implementation_id"; public static final String GLOBAL_PROPERTY_NEWPATIENTFORM_RELATIONSHIPS = "newPatientForm.relationships"; public static final String GLOBAL_PROPERTY_COMPLEX_OBS_DIR = "obs.complex_obs_dir"; public static final String GLOBAL_PROPERTY_MIN_SEARCH_CHARACTERS = "minSearchCharacters"; public static final String GLOBAL_PROPERTY_DEFAULT_LOCALE = "default_locale"; public static final String GLOBAL_PROPERTY_DEFAULT_LOCALE_DEFAULT_VALUE = "en_GB"; public static final String GLOBAL_PROPERTY_PATIENT_SEARCH_MATCH_MODE = "patientSearch.matchMode"; public static final String GLOBAL_PROPERTY_PATIENT_SEARCH_MATCH_ANYWHERE = "ANYWHERE"; public static final String GLOBAL_PROPERTY_DEFAULT_SERIALIZER = "serialization.defaultSerializer"; /** * At OpenMRS startup these global properties/default values/descriptions are inserted into the * database if they do not exist yet. * * @return List<GlobalProperty> of the core global properties */ public static final List<GlobalProperty> CORE_GLOBAL_PROPERTIES() { List<GlobalProperty> props = new Vector<GlobalProperty>(); props.add(new GlobalProperty("use_patient_attribute.healthCenter", "false", "Indicates whether or not the 'health center' attribute is shown when viewing/searching for patients")); props.add(new GlobalProperty("use_patient_attribute.mothersName", "false", "Indicates whether or not mother's name is able to be added/viewed for a patient")); props.add(new GlobalProperty("new_patient_form.showRelationships", "false", "true/false whether or not to show the relationship editor on the addPatient.htm screen")); props.add(new GlobalProperty("dashboard.overview.showConcepts", "", "Comma delimited list of concepts ids to show on the patient dashboard overview tab")); - props - .add(new GlobalProperty("dashboard.encounters.viewWhere", "newWindow", - "Defines how the 'View Encounter' link should act. Known values: 'sameWindow', 'newWindow', 'oneNewWindow'")); props.add(new GlobalProperty("dashboard.encounters.showEmptyFields", "true", "true/false whether or not to show empty fields on the 'View Encounter' window")); props .add(new GlobalProperty( "dashboard.encounters.usePages", "smart", "true/false/smart on how to show the pages on the 'View Encounter' window. 'smart' means that if > 50% of the fields have page numbers defined, show data in pages")); props.add(new GlobalProperty("dashboard.encounters.showViewLink", "true", "true/false whether or not to show the 'View Encounter' link on the patient dashboard")); props.add(new GlobalProperty("dashboard.encounters.showEditLink", "true", "true/false whether or not to show the 'Edit Encounter' link on the patient dashboard")); props .add(new GlobalProperty( "dashboard.header.programs_to_show", "", "List of programs to show Enrollment details of in the patient header. (Should be an ordered comma-separated list of program_ids or names.)")); props .add(new GlobalProperty( "dashboard.header.workflows_to_show", "", "List of programs to show Enrollment details of in the patient header. List of workflows to show current status of in the patient header. These will only be displayed if they belong to a program listed above. (Should be a comma-separated list of program_workflow_ids.)")); props.add(new GlobalProperty("dashboard.relationships.show_types", "", "Types of relationships separated by commas. Doctor/Patient,Parent/Child")); props.add(new GlobalProperty("FormEntry.enableDashboardTab", "true", "true/false whether or not to show a Form Entry tab on the patient dashboard")); props.add(new GlobalProperty("FormEntry.enableOnEncounterTab", "false", "true/false whether or not to show a Enter Form button on the encounters tab of the patient dashboard")); props .add(new GlobalProperty( "dashboard.regimen.displayDrugSetIds", "ANTIRETROVIRAL DRUGS,TUBERCULOSIS TREATMENT DRUGS", "Drug sets that appear on the Patient Dashboard Regimen tab. Comma separated list of name of concepts that are defined as drug sets.")); String standardRegimens = "<list>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion>" + " <drugId>2</drugId>" + " <dose>1</dose>" + " <units>tab(s)</units>" + " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " </drugComponents>" + " <displayName>3TC + d4T(30) + NVP (Triomune-30)</displayName>" + " <codeName>standardTri30</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>" + " </regimenSuggestion>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion>" + " <drugId>3</drugId>" + " <dose>1</dose>" + " <units>tab(s)</units>" + " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " </drugComponents>" + " <displayName>3TC + d4T(40) + NVP (Triomune-40)</displayName>" + " <codeName>standardTri40</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>" + " </regimenSuggestion>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion>" + " <drugId>39</drugId>" + " <dose>1</dose>" + " <units>tab(s)</units>" + " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " <drugSuggestion>" + " <drugId>22</drugId>" + " <dose>200</dose>" + " <units>mg</units>" + " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " </drugComponents>" + " <displayName>AZT + 3TC + NVP</displayName>" + " <codeName>standardAztNvp</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>" + " </regimenSuggestion>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion reference=\"../../../regimenSuggestion[3]/drugComponents/drugSuggestion\"/>" + " <drugSuggestion>" + " <drugId>11</drugId>" + " <dose>600</dose>" + " <units>mg</units>" + " <frequency>1/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " </drugComponents>" + " <displayName>AZT + 3TC + EFV(600)</displayName>" + " <codeName>standardAztEfv</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>" + " </regimenSuggestion>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion>" + " <drugId>5</drugId>" + " <dose>30</dose>" + " <units>mg</units>" + " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " <drugSuggestion>" + " <drugId>42</drugId>" + " <dose>150</dose>" + " <units>mg</units>" + " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " <drugSuggestion reference=\"../../../regimenSuggestion[4]/drugComponents/drugSuggestion[2]\"/>" + " </drugComponents>" + " <displayName>d4T(30) + 3TC + EFV(600)</displayName>" + " <codeName>standardD4t30Efv</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>" + " </regimenSuggestion>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion>" + " <drugId>6</drugId>" + " <dose>40</dose>" + " <units>mg</units>" + " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " <drugSuggestion reference=\"../../../regimenSuggestion[5]/drugComponents/drugSuggestion[2]\"/>" + " <drugSuggestion reference=\"../../../regimenSuggestion[4]/drugComponents/drugSuggestion[2]\"/>" + " </drugComponents>" + " <displayName>d4T(40) + 3TC + EFV(600)</displayName>" + " <codeName>standardD4t40Efv</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>" + " </regimenSuggestion>" + "</list>"; props.add(new GlobalProperty(GLOBAL_PROPERTY_STANDARD_DRUG_REGIMENS, standardRegimens, "XML description of standard drug regimens, to be shown as shortcuts on the dashboard regimen entry tab")); props.add(new GlobalProperty("concept.weight", "5089", "Concept id of the concept defining the WEIGHT concept")); props.add(new GlobalProperty("concept.height", "5090", "Concept id of the concept defining the HEIGHT concept")); props .add(new GlobalProperty("concept.cd4_count", "5497", "Concept id of the concept defining the CD4 count concept")); props.add(new GlobalProperty("concept.causeOfDeath", "5002", "Concept id of the concept defining the CAUSE OF DEATH concept")); props.add(new GlobalProperty("concept.none", "1107", "Concept id of the concept defining the NONE concept")); props.add(new GlobalProperty("concept.otherNonCoded", "5622", "Concept id of the concept defining the OTHER NON-CODED concept")); props.add(new GlobalProperty("concept.patientDied", "1742", "Concept id of the concept defining the PATIENT DIED concept")); props.add(new GlobalProperty("concept.reasonExitedCare", "1811", "Concept id of the concept defining the REASON EXITED CARE concept")); props.add(new GlobalProperty("concept.reasonOrderStopped", "1812", "Concept id of the concept defining the REASON ORDER STOPPED concept")); props.add(new GlobalProperty("mail.transport_protocol", "smtp", "Transport protocol for the messaging engine. Valid values: smtp")); props.add(new GlobalProperty("mail.smtp_host", "localhost", "SMTP host name")); props.add(new GlobalProperty("mail.smtp_port", "25", "SMTP port")); props.add(new GlobalProperty("mail.from", "[email protected]", "Email address to use as the default from address")); props.add(new GlobalProperty("mail.debug", "false", "true/false whether to print debugging information during mailing")); props.add(new GlobalProperty("mail.smtp_auth", "false", "true/false whether the smtp host requires authentication")); props.add(new GlobalProperty("mail.user", "test", "Username of the SMTP user (if smtp_auth is enabled)")); props.add(new GlobalProperty("mail.password", "test", "Password for the SMTP user (if smtp_auth is enabled)")); props.add(new GlobalProperty("mail.default_content_type", "text/plain", "Content type to append to the mail messages")); props.add(new GlobalProperty(ModuleConstants.REPOSITORY_FOLDER_PROPERTY, ModuleConstants.REPOSITORY_FOLDER_PROPERTY_DEFAULT, "Name of the folder in which to store the modules")); props .add(new GlobalProperty("layout.address.format", "general", "Format in which to display the person addresses. Valid values are general, kenya, rwanda, usa, and lesotho")); props.add(new GlobalProperty("layout.name.format", "short", "Format in which to display the person names. Valid values are short, long")); // TODO should be changed to text defaults and constants should be removed props.add(new GlobalProperty("scheduler.username", SchedulerConstants.SCHEDULER_DEFAULT_USERNAME, "Username for the OpenMRS user that will perform the scheduler activities")); props.add(new GlobalProperty("scheduler.password", SchedulerConstants.SCHEDULER_DEFAULT_PASSWORD, "Password for the OpenMRS user that will perform the scheduler activities")); props.add(new GlobalProperty(GLOBAL_PROPERTY_CONCEPTS_LOCKED, "false", "true/false whether or not concepts can be edited in this database.")); props.add(new GlobalProperty(GLOBAL_PROPERTY_PATIENT_LISTING_ATTRIBUTES, "", "A comma delimited list of PersonAttributeType names that should be displayed for patients in _lists_")); props .add(new GlobalProperty(GLOBAL_PROPERTY_PATIENT_VIEWING_ATTRIBUTES, "", "A comma delimited list of PersonAttributeType names that should be displayed for patients when _viewing individually_")); props.add(new GlobalProperty(GLOBAL_PROPERTY_PATIENT_HEADER_ATTRIBUTES, "", "A comma delimited list of PersonAttributeType names that will be shown on the patient dashboard")); props.add(new GlobalProperty(GLOBAL_PROPERTY_USER_LISTING_ATTRIBUTES, "", "A comma delimited list of PersonAttributeType names that should be displayed for users in _lists_")); props .add(new GlobalProperty(GLOBAL_PROPERTY_USER_VIEWING_ATTRIBUTES, "", "A comma delimited list of PersonAttributeType names that should be displayed for users when _viewing individually_")); props .add(new GlobalProperty(GLOBAL_PROPERTY_USER_HEADER_ATTRIBUTES, "", "A comma delimited list of PersonAttributeType names that will be shown on the user dashboard. (not used in v1.5)")); props .add(new GlobalProperty( GLOBAL_PROPERTY_PATIENT_IDENTIFIER_REGEX, "^0*@SEARCH@([A-Z]+-[0-9])?$", "A MySQL regular expression for the patient identifier search strings. The @SEARCH@ string is replaced at runtime with the user's search string. An empty regex will cause a simply 'like' sql search to be used")); props .add(new GlobalProperty( GLOBAL_PROPERTY_PATIENT_IDENTIFIER_PREFIX, "", "This property is only used if " + GLOBAL_PROPERTY_PATIENT_IDENTIFIER_REGEX + " is empty. The string here is prepended to the sql indentifier search string. The sql becomes \"... where identifier like '<PREFIX><QUERY STRING><SUFFIX>';\". Typically this value is either a percent sign (%) or empty.")); props .add(new GlobalProperty( GLOBAL_PROPERTY_PATIENT_IDENTIFIER_SUFFIX, "%", "This property is only used if " + GLOBAL_PROPERTY_PATIENT_IDENTIFIER_REGEX + " is empty. The string here is prepended to the sql indentifier search string. The sql becomes \"... where identifier like '<PREFIX><QUERY STRING><SUFFIX>';\". Typically this value is either a percent sign (%) or empty.")); props.add(new GlobalProperty(GLOBAL_PROPERTY_PATIENT_SEARCH_MAX_RESULTS, "1000", "The maximum number of results returned by patient searches")); props .add(new GlobalProperty( GLOBAL_PROPERTY_GZIP_ENABLED, "false", "Set to 'true' to turn on OpenMRS's gzip filter, and have the webapp compress data before sending it to any client that supports it. Generally use this if you are running Tomcat standalone. If you are running Tomcat behind Apache, then you'd want to use Apache to do gzip compression.")); props .add(new GlobalProperty(GLOBAL_PROPERTY_REPORT_XML_MACROS, "", "Macros that will be applied to Report Schema XMLs when they are interpreted. This should be java.util.properties format.")); props .add(new GlobalProperty( GLOBAL_PROPERTY_MEDICAL_RECORD_OBSERVATIONS, "1238", "The concept id of the MEDICAL_RECORD_OBSERVATIONS concept. This concept_id is presumed to be the generic grouping (obr) concept in hl7 messages. An obs_group row is not created for this concept.")); props .add(new GlobalProperty( GLOBAL_PROPERTY_PROBLEM_LIST, "1284", "The concept id of the PROBLEM LIST concept. This concept_id is presumed to be the generic grouping (obr) concept in hl7 messages. An obs_group row is not created for this concept.")); props .add(new GlobalProperty( GLOBAL_PROPERTY_LOG_LEVEL, LOG_LEVEL_INFO, "log level used by the logger 'org.openmrs'. This value will override the log4j.xml value. Valid values are trace, debug, info, warn, error or fatal")); props .add(new GlobalProperty( GLOBAL_PROPERTY_DEFAULT_PATIENT_IDENTIFIER_VALIDATOR, LUHN_IDENTIFIER_VALIDATOR, "This property sets the default patient identifier validator. The default validator is only used in a handful of (mostly legacy) instances. For example, it's used to generate the isValidCheckDigit calculated column and to append the string \"(default)\" to the name of the default validator on the editPatientIdentifierType form.")); props .add(new GlobalProperty( GLOBAL_PROPERTY_PATIENT_IDENTIFIER_IMPORTANT_TYPES, "", "A comma delimited list of PatientIdentifier names : PatientIdentifier locations that will be displayed on the patient dashboard. E.g.: TRACnet ID:Rwanda,ELDID:Kenya")); props.add(new GlobalProperty(GLOBAL_PROPERTY_COMPLEX_OBS_DIR, "complex_obs", "Default directory for storing complex obs.")); props .add(new GlobalProperty( GLOBAL_PROPERTY_ENCOUNTER_FORM_OBS_SORT_ORDER, "number", "The sort order for the obs listed on the encounter edit form. 'number' sorts on the associated numbering from the form schema. 'weight' sorts on the order displayed in the form schema.")); props.add(new GlobalProperty(GLOBAL_PROPERTY_LOCALE_ALLOWED_LIST, "en, es, fr, it, pt", "Comma delimited list of locales allowed for use on system")); props .add(new GlobalProperty( GLOBAL_PROPERTY_NEWPATIENTFORM_RELATIONSHIPS, "", "Comma separated list of the RelationshipTypes to show on the new/short patient form. The list is defined like '3a, 4b, 7a'. The number is the RelationshipTypeId and the 'a' vs 'b' part is which side of the relationship is filled in by the user.")); props.add(new GlobalProperty(GLOBAL_PROPERTY_MIN_SEARCH_CHARACTERS, "3", "Number of characters user must input before searching is started.")); props .add(new GlobalProperty( OpenmrsConstants.GLOBAL_PROPERTY_DEFAULT_LOCALE, OpenmrsConstants.GLOBAL_PROPERTY_DEFAULT_LOCALE_DEFAULT_VALUE, "Specifies the default locale. You can specify both the language code(ISO-639) and the country code(ISO-3166), e.g. 'en_GB' or just country: e.g. 'en'")); for (GlobalProperty gp : ModuleFactory.getGlobalProperties()) { props.add(gp); } return props; } // ConceptProposal proposed concept identifier keyword public static final String PROPOSED_CONCEPT_IDENTIFIER = "PROPOSED"; // ConceptProposal states public static final String CONCEPT_PROPOSAL_UNMAPPED = "UNMAPPED"; public static final String CONCEPT_PROPOSAL_CONCEPT = "CONCEPT"; public static final String CONCEPT_PROPOSAL_SYNONYM = "SYNONYM"; public static final String CONCEPT_PROPOSAL_REJECT = "REJECT"; public static final Collection<String> CONCEPT_PROPOSAL_STATES() { Collection<String> states = new Vector<String>(); states.add(CONCEPT_PROPOSAL_UNMAPPED); states.add(CONCEPT_PROPOSAL_CONCEPT); states.add(CONCEPT_PROPOSAL_SYNONYM); states.add(CONCEPT_PROPOSAL_REJECT); return states; } public static Locale SPANISH_LANGUAGE = new Locale("es"); public static Locale PORTUGUESE_LANGUAGE = new Locale("pt"); public static Locale ITALIAN_LANGUAGE = new Locale("it"); /** * @return Collection of locales available to openmrs * @deprecated */ public static final Collection<Locale> OPENMRS_LOCALES() { List<Locale> languages = new Vector<Locale>(); languages.add(Locale.US); languages.add(Locale.UK); languages.add(Locale.FRENCH); languages.add(SPANISH_LANGUAGE); languages.add(PORTUGUESE_LANGUAGE); languages.add(ITALIAN_LANGUAGE); return languages; } /** * @deprecated use {@link LocaleUtility#getDefaultLocale()} */ public static final Locale GLOBAL_DEFAULT_LOCALE = LocaleUtility.DEFAULT_LOCALE; /** * @return Collection of locales that the concept dictionary should be aware of * @see ConceptService#getLocalesOfConceptNames() * @deprecated */ public static final Collection<Locale> OPENMRS_CONCEPT_LOCALES() { List<Locale> languages = new Vector<Locale>(); languages.add(Locale.ENGLISH); languages.add(Locale.FRENCH); languages.add(SPANISH_LANGUAGE); languages.add(PORTUGUESE_LANGUAGE); languages.add(ITALIAN_LANGUAGE); return languages; } @Deprecated private static Map<String, String> OPENMRS_LOCALE_DATE_PATTERNS = null; /** * @return Mapping of Locales to locale specific date pattern * @deprecated use the {@link org.openmrs.api.context.Context#getDateFormat()} */ public static final Map<String, String> OPENMRS_LOCALE_DATE_PATTERNS() { if (OPENMRS_LOCALE_DATE_PATTERNS == null) { Map<String, String> patterns = new HashMap<String, String>(); patterns.put(Locale.US.toString().toLowerCase(), "MM/dd/yyyy"); patterns.put(Locale.UK.toString().toLowerCase(), "dd/MM/yyyy"); patterns.put(Locale.FRENCH.toString().toLowerCase(), "dd/MM/yyyy"); patterns.put(Locale.GERMAN.toString().toLowerCase(), "MM.dd.yyyy"); patterns.put(SPANISH_LANGUAGE.toString().toLowerCase(), "dd/MM/yyyy"); patterns.put(PORTUGUESE_LANGUAGE.toString().toLowerCase(), "dd/MM/yyyy"); patterns.put(ITALIAN_LANGUAGE.toString().toLowerCase(), "dd/MM/yyyy"); OPENMRS_LOCALE_DATE_PATTERNS = patterns; } return OPENMRS_LOCALE_DATE_PATTERNS; } /* * User property names */ public static final String USER_PROPERTY_CHANGE_PASSWORD = "forcePassword"; public static final String USER_PROPERTY_DEFAULT_LOCALE = "defaultLocale"; public static final String USER_PROPERTY_DEFAULT_LOCATION = "defaultLocation"; public static final String USER_PROPERTY_SHOW_RETIRED = "showRetired"; public static final String USER_PROPERTY_SHOW_VERBOSE = "showVerbose"; public static final String USER_PROPERTY_NOTIFICATION = "notification"; public static final String USER_PROPERTY_NOTIFICATION_ADDRESS = "notificationAddress"; public static final String USER_PROPERTY_NOTIFICATION_FORMAT = "notificationFormat"; // text/plain, text/html /** * Name of the user_property that stores the number of unsuccessful login attempts this user has * made */ public static final String USER_PROPERTY_LOGIN_ATTEMPTS = "loginAttempts"; /** * Name of the user_property that stores the time the user was locked out due to too many login * attempts */ public static final String USER_PROPERTY_LOCKOUT_TIMESTAMP = "lockoutTimestamp"; /** * A user property name. The value should be a comma-separated ordered list of fully qualified * locales within which the user is a proficient speaker. The list should be ordered from the * most to the least proficiency. Example: * <code>proficientLocales = en_US, en_GB, en, fr_RW</code> */ public static final String USER_PROPERTY_PROFICIENT_LOCALES = "proficientLocales"; /** * Report object properties */ @Deprecated public static final String REPORT_OBJECT_TYPE_PATIENTFILTER = "Patient Filter"; @Deprecated public static final String REPORT_OBJECT_TYPE_PATIENTSEARCH = "Patient Search"; @Deprecated public static final String REPORT_OBJECT_TYPE_PATIENTDATAPRODUCER = "Patient Data Producer"; // Used for differences between windows/linux upload capabilities) // Used for determining where to find runtime properties public static final String OPERATING_SYSTEM_KEY = "os.name"; public static final String OPERATING_SYSTEM = System.getProperty(OPERATING_SYSTEM_KEY); public static final String OPERATING_SYSTEM_WINDOWS_XP = "Windows XP"; public static final String OPERATING_SYSTEM_WINDOWS_VISTA = "Windows Vista"; public static final String OPERATING_SYSTEM_LINUX = "Linux"; public static final String OPERATING_SYSTEM_SUNOS = "SunOS"; public static final String OPERATING_SYSTEM_FREEBSD = "FreeBSD"; public static final String OPERATING_SYSTEM_OSX = "Mac OS X"; /** * URL to the concept source id verification server */ public static final String IMPLEMENTATION_ID_REMOTE_CONNECTION_URL = "http://resources.openmrs.org/tools/implementationid"; /** * Shortcut booleans used to make some OS specific checks more generic; note the *nix flavored * check is missing some less obvious choices */ public static final boolean UNIX_BASED_OPERATING_SYSTEM = (OPERATING_SYSTEM.indexOf(OPERATING_SYSTEM_LINUX) > -1 || OPERATING_SYSTEM.indexOf(OPERATING_SYSTEM_SUNOS) > -1 || OPERATING_SYSTEM.indexOf(OPERATING_SYSTEM_FREEBSD) > -1 || OPERATING_SYSTEM.indexOf(OPERATING_SYSTEM_OSX) > -1); public static final boolean WINDOWS_BASED_OPERATING_SYSTEM = OPERATING_SYSTEM.indexOf("Windows") > -1; public static final boolean WINDOWS_VISTA_OPERATING_SYSTEM = OPERATING_SYSTEM.equals(OPERATING_SYSTEM_WINDOWS_VISTA); /** * Marker put into the serialization session map to tell @Replace methods whether or not to do * just the very basic serialization */ public static final String SHORT_SERIALIZATION = "isShortSerialization"; // Global property key for global logger level public static final String GLOBAL_PROPERTY_LOG_LEVEL = "log.level.openmrs"; // Global logger category public static final String LOG_CLASS_DEFAULT = "org.openmrs"; // Log levels public static final String LOG_LEVEL_TRACE = "trace"; public static final String LOG_LEVEL_DEBUG = "debug"; public static final String LOG_LEVEL_INFO = "info"; public static final String LOG_LEVEL_WARN = "warn"; public static final String LOG_LEVEL_ERROR = "error"; public static final String LOG_LEVEL_FATAL = "fatal"; /** * These enumerations should be used in ObsService and PersonService getters to help determine * which type of object to restrict on * * @see org.openmrs.api.ObsService * @see org.openmrs.api.PersonService */ public static enum PERSON_TYPE { PERSON, PATIENT, USER } //Patient Identifier Validators public static final String LUHN_IDENTIFIER_VALIDATOR = LuhnIdentifierValidator.class.getName(); // ComplexObsHandler views public static final String RAW_VIEW = "RAW_VIEW"; public static final String TEXT_VIEW = "TEXT_VIEW"; }
true
true
public static final List<GlobalProperty> CORE_GLOBAL_PROPERTIES() { List<GlobalProperty> props = new Vector<GlobalProperty>(); props.add(new GlobalProperty("use_patient_attribute.healthCenter", "false", "Indicates whether or not the 'health center' attribute is shown when viewing/searching for patients")); props.add(new GlobalProperty("use_patient_attribute.mothersName", "false", "Indicates whether or not mother's name is able to be added/viewed for a patient")); props.add(new GlobalProperty("new_patient_form.showRelationships", "false", "true/false whether or not to show the relationship editor on the addPatient.htm screen")); props.add(new GlobalProperty("dashboard.overview.showConcepts", "", "Comma delimited list of concepts ids to show on the patient dashboard overview tab")); props .add(new GlobalProperty("dashboard.encounters.viewWhere", "newWindow", "Defines how the 'View Encounter' link should act. Known values: 'sameWindow', 'newWindow', 'oneNewWindow'")); props.add(new GlobalProperty("dashboard.encounters.showEmptyFields", "true", "true/false whether or not to show empty fields on the 'View Encounter' window")); props .add(new GlobalProperty( "dashboard.encounters.usePages", "smart", "true/false/smart on how to show the pages on the 'View Encounter' window. 'smart' means that if > 50% of the fields have page numbers defined, show data in pages")); props.add(new GlobalProperty("dashboard.encounters.showViewLink", "true", "true/false whether or not to show the 'View Encounter' link on the patient dashboard")); props.add(new GlobalProperty("dashboard.encounters.showEditLink", "true", "true/false whether or not to show the 'Edit Encounter' link on the patient dashboard")); props .add(new GlobalProperty( "dashboard.header.programs_to_show", "", "List of programs to show Enrollment details of in the patient header. (Should be an ordered comma-separated list of program_ids or names.)")); props .add(new GlobalProperty( "dashboard.header.workflows_to_show", "", "List of programs to show Enrollment details of in the patient header. List of workflows to show current status of in the patient header. These will only be displayed if they belong to a program listed above. (Should be a comma-separated list of program_workflow_ids.)")); props.add(new GlobalProperty("dashboard.relationships.show_types", "", "Types of relationships separated by commas. Doctor/Patient,Parent/Child")); props.add(new GlobalProperty("FormEntry.enableDashboardTab", "true", "true/false whether or not to show a Form Entry tab on the patient dashboard")); props.add(new GlobalProperty("FormEntry.enableOnEncounterTab", "false", "true/false whether or not to show a Enter Form button on the encounters tab of the patient dashboard")); props .add(new GlobalProperty( "dashboard.regimen.displayDrugSetIds", "ANTIRETROVIRAL DRUGS,TUBERCULOSIS TREATMENT DRUGS", "Drug sets that appear on the Patient Dashboard Regimen tab. Comma separated list of name of concepts that are defined as drug sets.")); String standardRegimens = "<list>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion>" + " <drugId>2</drugId>" + " <dose>1</dose>" + " <units>tab(s)</units>" + " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " </drugComponents>" + " <displayName>3TC + d4T(30) + NVP (Triomune-30)</displayName>" + " <codeName>standardTri30</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>" + " </regimenSuggestion>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion>" + " <drugId>3</drugId>" + " <dose>1</dose>" + " <units>tab(s)</units>" + " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " </drugComponents>" + " <displayName>3TC + d4T(40) + NVP (Triomune-40)</displayName>" + " <codeName>standardTri40</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>" + " </regimenSuggestion>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion>" + " <drugId>39</drugId>" + " <dose>1</dose>" + " <units>tab(s)</units>" + " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " <drugSuggestion>" + " <drugId>22</drugId>" + " <dose>200</dose>" + " <units>mg</units>" + " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " </drugComponents>" + " <displayName>AZT + 3TC + NVP</displayName>" + " <codeName>standardAztNvp</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>" + " </regimenSuggestion>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion reference=\"../../../regimenSuggestion[3]/drugComponents/drugSuggestion\"/>" + " <drugSuggestion>" + " <drugId>11</drugId>" + " <dose>600</dose>" + " <units>mg</units>" + " <frequency>1/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " </drugComponents>" + " <displayName>AZT + 3TC + EFV(600)</displayName>" + " <codeName>standardAztEfv</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>" + " </regimenSuggestion>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion>" + " <drugId>5</drugId>" + " <dose>30</dose>" + " <units>mg</units>" + " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " <drugSuggestion>" + " <drugId>42</drugId>" + " <dose>150</dose>" + " <units>mg</units>" + " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " <drugSuggestion reference=\"../../../regimenSuggestion[4]/drugComponents/drugSuggestion[2]\"/>" + " </drugComponents>" + " <displayName>d4T(30) + 3TC + EFV(600)</displayName>" + " <codeName>standardD4t30Efv</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>" + " </regimenSuggestion>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion>" + " <drugId>6</drugId>" + " <dose>40</dose>" + " <units>mg</units>" + " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " <drugSuggestion reference=\"../../../regimenSuggestion[5]/drugComponents/drugSuggestion[2]\"/>" + " <drugSuggestion reference=\"../../../regimenSuggestion[4]/drugComponents/drugSuggestion[2]\"/>" + " </drugComponents>" + " <displayName>d4T(40) + 3TC + EFV(600)</displayName>" + " <codeName>standardD4t40Efv</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>" + " </regimenSuggestion>" + "</list>"; props.add(new GlobalProperty(GLOBAL_PROPERTY_STANDARD_DRUG_REGIMENS, standardRegimens, "XML description of standard drug regimens, to be shown as shortcuts on the dashboard regimen entry tab")); props.add(new GlobalProperty("concept.weight", "5089", "Concept id of the concept defining the WEIGHT concept")); props.add(new GlobalProperty("concept.height", "5090", "Concept id of the concept defining the HEIGHT concept")); props .add(new GlobalProperty("concept.cd4_count", "5497", "Concept id of the concept defining the CD4 count concept")); props.add(new GlobalProperty("concept.causeOfDeath", "5002", "Concept id of the concept defining the CAUSE OF DEATH concept")); props.add(new GlobalProperty("concept.none", "1107", "Concept id of the concept defining the NONE concept")); props.add(new GlobalProperty("concept.otherNonCoded", "5622", "Concept id of the concept defining the OTHER NON-CODED concept")); props.add(new GlobalProperty("concept.patientDied", "1742", "Concept id of the concept defining the PATIENT DIED concept")); props.add(new GlobalProperty("concept.reasonExitedCare", "1811", "Concept id of the concept defining the REASON EXITED CARE concept")); props.add(new GlobalProperty("concept.reasonOrderStopped", "1812", "Concept id of the concept defining the REASON ORDER STOPPED concept")); props.add(new GlobalProperty("mail.transport_protocol", "smtp", "Transport protocol for the messaging engine. Valid values: smtp")); props.add(new GlobalProperty("mail.smtp_host", "localhost", "SMTP host name")); props.add(new GlobalProperty("mail.smtp_port", "25", "SMTP port")); props.add(new GlobalProperty("mail.from", "[email protected]", "Email address to use as the default from address")); props.add(new GlobalProperty("mail.debug", "false", "true/false whether to print debugging information during mailing")); props.add(new GlobalProperty("mail.smtp_auth", "false", "true/false whether the smtp host requires authentication")); props.add(new GlobalProperty("mail.user", "test", "Username of the SMTP user (if smtp_auth is enabled)")); props.add(new GlobalProperty("mail.password", "test", "Password for the SMTP user (if smtp_auth is enabled)")); props.add(new GlobalProperty("mail.default_content_type", "text/plain", "Content type to append to the mail messages")); props.add(new GlobalProperty(ModuleConstants.REPOSITORY_FOLDER_PROPERTY, ModuleConstants.REPOSITORY_FOLDER_PROPERTY_DEFAULT, "Name of the folder in which to store the modules")); props .add(new GlobalProperty("layout.address.format", "general", "Format in which to display the person addresses. Valid values are general, kenya, rwanda, usa, and lesotho")); props.add(new GlobalProperty("layout.name.format", "short", "Format in which to display the person names. Valid values are short, long")); // TODO should be changed to text defaults and constants should be removed props.add(new GlobalProperty("scheduler.username", SchedulerConstants.SCHEDULER_DEFAULT_USERNAME, "Username for the OpenMRS user that will perform the scheduler activities")); props.add(new GlobalProperty("scheduler.password", SchedulerConstants.SCHEDULER_DEFAULT_PASSWORD, "Password for the OpenMRS user that will perform the scheduler activities")); props.add(new GlobalProperty(GLOBAL_PROPERTY_CONCEPTS_LOCKED, "false", "true/false whether or not concepts can be edited in this database.")); props.add(new GlobalProperty(GLOBAL_PROPERTY_PATIENT_LISTING_ATTRIBUTES, "", "A comma delimited list of PersonAttributeType names that should be displayed for patients in _lists_")); props .add(new GlobalProperty(GLOBAL_PROPERTY_PATIENT_VIEWING_ATTRIBUTES, "", "A comma delimited list of PersonAttributeType names that should be displayed for patients when _viewing individually_")); props.add(new GlobalProperty(GLOBAL_PROPERTY_PATIENT_HEADER_ATTRIBUTES, "", "A comma delimited list of PersonAttributeType names that will be shown on the patient dashboard")); props.add(new GlobalProperty(GLOBAL_PROPERTY_USER_LISTING_ATTRIBUTES, "", "A comma delimited list of PersonAttributeType names that should be displayed for users in _lists_")); props .add(new GlobalProperty(GLOBAL_PROPERTY_USER_VIEWING_ATTRIBUTES, "", "A comma delimited list of PersonAttributeType names that should be displayed for users when _viewing individually_")); props .add(new GlobalProperty(GLOBAL_PROPERTY_USER_HEADER_ATTRIBUTES, "", "A comma delimited list of PersonAttributeType names that will be shown on the user dashboard. (not used in v1.5)")); props .add(new GlobalProperty( GLOBAL_PROPERTY_PATIENT_IDENTIFIER_REGEX, "^0*@SEARCH@([A-Z]+-[0-9])?$", "A MySQL regular expression for the patient identifier search strings. The @SEARCH@ string is replaced at runtime with the user's search string. An empty regex will cause a simply 'like' sql search to be used")); props .add(new GlobalProperty( GLOBAL_PROPERTY_PATIENT_IDENTIFIER_PREFIX, "", "This property is only used if " + GLOBAL_PROPERTY_PATIENT_IDENTIFIER_REGEX + " is empty. The string here is prepended to the sql indentifier search string. The sql becomes \"... where identifier like '<PREFIX><QUERY STRING><SUFFIX>';\". Typically this value is either a percent sign (%) or empty.")); props .add(new GlobalProperty( GLOBAL_PROPERTY_PATIENT_IDENTIFIER_SUFFIX, "%", "This property is only used if " + GLOBAL_PROPERTY_PATIENT_IDENTIFIER_REGEX + " is empty. The string here is prepended to the sql indentifier search string. The sql becomes \"... where identifier like '<PREFIX><QUERY STRING><SUFFIX>';\". Typically this value is either a percent sign (%) or empty.")); props.add(new GlobalProperty(GLOBAL_PROPERTY_PATIENT_SEARCH_MAX_RESULTS, "1000", "The maximum number of results returned by patient searches")); props .add(new GlobalProperty( GLOBAL_PROPERTY_GZIP_ENABLED, "false", "Set to 'true' to turn on OpenMRS's gzip filter, and have the webapp compress data before sending it to any client that supports it. Generally use this if you are running Tomcat standalone. If you are running Tomcat behind Apache, then you'd want to use Apache to do gzip compression.")); props .add(new GlobalProperty(GLOBAL_PROPERTY_REPORT_XML_MACROS, "", "Macros that will be applied to Report Schema XMLs when they are interpreted. This should be java.util.properties format.")); props .add(new GlobalProperty( GLOBAL_PROPERTY_MEDICAL_RECORD_OBSERVATIONS, "1238", "The concept id of the MEDICAL_RECORD_OBSERVATIONS concept. This concept_id is presumed to be the generic grouping (obr) concept in hl7 messages. An obs_group row is not created for this concept.")); props .add(new GlobalProperty( GLOBAL_PROPERTY_PROBLEM_LIST, "1284", "The concept id of the PROBLEM LIST concept. This concept_id is presumed to be the generic grouping (obr) concept in hl7 messages. An obs_group row is not created for this concept.")); props .add(new GlobalProperty( GLOBAL_PROPERTY_LOG_LEVEL, LOG_LEVEL_INFO, "log level used by the logger 'org.openmrs'. This value will override the log4j.xml value. Valid values are trace, debug, info, warn, error or fatal")); props .add(new GlobalProperty( GLOBAL_PROPERTY_DEFAULT_PATIENT_IDENTIFIER_VALIDATOR, LUHN_IDENTIFIER_VALIDATOR, "This property sets the default patient identifier validator. The default validator is only used in a handful of (mostly legacy) instances. For example, it's used to generate the isValidCheckDigit calculated column and to append the string \"(default)\" to the name of the default validator on the editPatientIdentifierType form.")); props .add(new GlobalProperty( GLOBAL_PROPERTY_PATIENT_IDENTIFIER_IMPORTANT_TYPES, "", "A comma delimited list of PatientIdentifier names : PatientIdentifier locations that will be displayed on the patient dashboard. E.g.: TRACnet ID:Rwanda,ELDID:Kenya")); props.add(new GlobalProperty(GLOBAL_PROPERTY_COMPLEX_OBS_DIR, "complex_obs", "Default directory for storing complex obs.")); props .add(new GlobalProperty( GLOBAL_PROPERTY_ENCOUNTER_FORM_OBS_SORT_ORDER, "number", "The sort order for the obs listed on the encounter edit form. 'number' sorts on the associated numbering from the form schema. 'weight' sorts on the order displayed in the form schema.")); props.add(new GlobalProperty(GLOBAL_PROPERTY_LOCALE_ALLOWED_LIST, "en, es, fr, it, pt", "Comma delimited list of locales allowed for use on system")); props .add(new GlobalProperty( GLOBAL_PROPERTY_NEWPATIENTFORM_RELATIONSHIPS, "", "Comma separated list of the RelationshipTypes to show on the new/short patient form. The list is defined like '3a, 4b, 7a'. The number is the RelationshipTypeId and the 'a' vs 'b' part is which side of the relationship is filled in by the user.")); props.add(new GlobalProperty(GLOBAL_PROPERTY_MIN_SEARCH_CHARACTERS, "3", "Number of characters user must input before searching is started.")); props .add(new GlobalProperty( OpenmrsConstants.GLOBAL_PROPERTY_DEFAULT_LOCALE, OpenmrsConstants.GLOBAL_PROPERTY_DEFAULT_LOCALE_DEFAULT_VALUE, "Specifies the default locale. You can specify both the language code(ISO-639) and the country code(ISO-3166), e.g. 'en_GB' or just country: e.g. 'en'")); for (GlobalProperty gp : ModuleFactory.getGlobalProperties()) { props.add(gp); } return props; }
public static final List<GlobalProperty> CORE_GLOBAL_PROPERTIES() { List<GlobalProperty> props = new Vector<GlobalProperty>(); props.add(new GlobalProperty("use_patient_attribute.healthCenter", "false", "Indicates whether or not the 'health center' attribute is shown when viewing/searching for patients")); props.add(new GlobalProperty("use_patient_attribute.mothersName", "false", "Indicates whether or not mother's name is able to be added/viewed for a patient")); props.add(new GlobalProperty("new_patient_form.showRelationships", "false", "true/false whether or not to show the relationship editor on the addPatient.htm screen")); props.add(new GlobalProperty("dashboard.overview.showConcepts", "", "Comma delimited list of concepts ids to show on the patient dashboard overview tab")); props.add(new GlobalProperty("dashboard.encounters.showEmptyFields", "true", "true/false whether or not to show empty fields on the 'View Encounter' window")); props .add(new GlobalProperty( "dashboard.encounters.usePages", "smart", "true/false/smart on how to show the pages on the 'View Encounter' window. 'smart' means that if > 50% of the fields have page numbers defined, show data in pages")); props.add(new GlobalProperty("dashboard.encounters.showViewLink", "true", "true/false whether or not to show the 'View Encounter' link on the patient dashboard")); props.add(new GlobalProperty("dashboard.encounters.showEditLink", "true", "true/false whether or not to show the 'Edit Encounter' link on the patient dashboard")); props .add(new GlobalProperty( "dashboard.header.programs_to_show", "", "List of programs to show Enrollment details of in the patient header. (Should be an ordered comma-separated list of program_ids or names.)")); props .add(new GlobalProperty( "dashboard.header.workflows_to_show", "", "List of programs to show Enrollment details of in the patient header. List of workflows to show current status of in the patient header. These will only be displayed if they belong to a program listed above. (Should be a comma-separated list of program_workflow_ids.)")); props.add(new GlobalProperty("dashboard.relationships.show_types", "", "Types of relationships separated by commas. Doctor/Patient,Parent/Child")); props.add(new GlobalProperty("FormEntry.enableDashboardTab", "true", "true/false whether or not to show a Form Entry tab on the patient dashboard")); props.add(new GlobalProperty("FormEntry.enableOnEncounterTab", "false", "true/false whether or not to show a Enter Form button on the encounters tab of the patient dashboard")); props .add(new GlobalProperty( "dashboard.regimen.displayDrugSetIds", "ANTIRETROVIRAL DRUGS,TUBERCULOSIS TREATMENT DRUGS", "Drug sets that appear on the Patient Dashboard Regimen tab. Comma separated list of name of concepts that are defined as drug sets.")); String standardRegimens = "<list>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion>" + " <drugId>2</drugId>" + " <dose>1</dose>" + " <units>tab(s)</units>" + " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " </drugComponents>" + " <displayName>3TC + d4T(30) + NVP (Triomune-30)</displayName>" + " <codeName>standardTri30</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>" + " </regimenSuggestion>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion>" + " <drugId>3</drugId>" + " <dose>1</dose>" + " <units>tab(s)</units>" + " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " </drugComponents>" + " <displayName>3TC + d4T(40) + NVP (Triomune-40)</displayName>" + " <codeName>standardTri40</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>" + " </regimenSuggestion>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion>" + " <drugId>39</drugId>" + " <dose>1</dose>" + " <units>tab(s)</units>" + " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " <drugSuggestion>" + " <drugId>22</drugId>" + " <dose>200</dose>" + " <units>mg</units>" + " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " </drugComponents>" + " <displayName>AZT + 3TC + NVP</displayName>" + " <codeName>standardAztNvp</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>" + " </regimenSuggestion>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion reference=\"../../../regimenSuggestion[3]/drugComponents/drugSuggestion\"/>" + " <drugSuggestion>" + " <drugId>11</drugId>" + " <dose>600</dose>" + " <units>mg</units>" + " <frequency>1/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " </drugComponents>" + " <displayName>AZT + 3TC + EFV(600)</displayName>" + " <codeName>standardAztEfv</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>" + " </regimenSuggestion>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion>" + " <drugId>5</drugId>" + " <dose>30</dose>" + " <units>mg</units>" + " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " <drugSuggestion>" + " <drugId>42</drugId>" + " <dose>150</dose>" + " <units>mg</units>" + " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " <drugSuggestion reference=\"../../../regimenSuggestion[4]/drugComponents/drugSuggestion[2]\"/>" + " </drugComponents>" + " <displayName>d4T(30) + 3TC + EFV(600)</displayName>" + " <codeName>standardD4t30Efv</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>" + " </regimenSuggestion>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion>" + " <drugId>6</drugId>" + " <dose>40</dose>" + " <units>mg</units>" + " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " <drugSuggestion reference=\"../../../regimenSuggestion[5]/drugComponents/drugSuggestion[2]\"/>" + " <drugSuggestion reference=\"../../../regimenSuggestion[4]/drugComponents/drugSuggestion[2]\"/>" + " </drugComponents>" + " <displayName>d4T(40) + 3TC + EFV(600)</displayName>" + " <codeName>standardD4t40Efv</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>" + " </regimenSuggestion>" + "</list>"; props.add(new GlobalProperty(GLOBAL_PROPERTY_STANDARD_DRUG_REGIMENS, standardRegimens, "XML description of standard drug regimens, to be shown as shortcuts on the dashboard regimen entry tab")); props.add(new GlobalProperty("concept.weight", "5089", "Concept id of the concept defining the WEIGHT concept")); props.add(new GlobalProperty("concept.height", "5090", "Concept id of the concept defining the HEIGHT concept")); props .add(new GlobalProperty("concept.cd4_count", "5497", "Concept id of the concept defining the CD4 count concept")); props.add(new GlobalProperty("concept.causeOfDeath", "5002", "Concept id of the concept defining the CAUSE OF DEATH concept")); props.add(new GlobalProperty("concept.none", "1107", "Concept id of the concept defining the NONE concept")); props.add(new GlobalProperty("concept.otherNonCoded", "5622", "Concept id of the concept defining the OTHER NON-CODED concept")); props.add(new GlobalProperty("concept.patientDied", "1742", "Concept id of the concept defining the PATIENT DIED concept")); props.add(new GlobalProperty("concept.reasonExitedCare", "1811", "Concept id of the concept defining the REASON EXITED CARE concept")); props.add(new GlobalProperty("concept.reasonOrderStopped", "1812", "Concept id of the concept defining the REASON ORDER STOPPED concept")); props.add(new GlobalProperty("mail.transport_protocol", "smtp", "Transport protocol for the messaging engine. Valid values: smtp")); props.add(new GlobalProperty("mail.smtp_host", "localhost", "SMTP host name")); props.add(new GlobalProperty("mail.smtp_port", "25", "SMTP port")); props.add(new GlobalProperty("mail.from", "[email protected]", "Email address to use as the default from address")); props.add(new GlobalProperty("mail.debug", "false", "true/false whether to print debugging information during mailing")); props.add(new GlobalProperty("mail.smtp_auth", "false", "true/false whether the smtp host requires authentication")); props.add(new GlobalProperty("mail.user", "test", "Username of the SMTP user (if smtp_auth is enabled)")); props.add(new GlobalProperty("mail.password", "test", "Password for the SMTP user (if smtp_auth is enabled)")); props.add(new GlobalProperty("mail.default_content_type", "text/plain", "Content type to append to the mail messages")); props.add(new GlobalProperty(ModuleConstants.REPOSITORY_FOLDER_PROPERTY, ModuleConstants.REPOSITORY_FOLDER_PROPERTY_DEFAULT, "Name of the folder in which to store the modules")); props .add(new GlobalProperty("layout.address.format", "general", "Format in which to display the person addresses. Valid values are general, kenya, rwanda, usa, and lesotho")); props.add(new GlobalProperty("layout.name.format", "short", "Format in which to display the person names. Valid values are short, long")); // TODO should be changed to text defaults and constants should be removed props.add(new GlobalProperty("scheduler.username", SchedulerConstants.SCHEDULER_DEFAULT_USERNAME, "Username for the OpenMRS user that will perform the scheduler activities")); props.add(new GlobalProperty("scheduler.password", SchedulerConstants.SCHEDULER_DEFAULT_PASSWORD, "Password for the OpenMRS user that will perform the scheduler activities")); props.add(new GlobalProperty(GLOBAL_PROPERTY_CONCEPTS_LOCKED, "false", "true/false whether or not concepts can be edited in this database.")); props.add(new GlobalProperty(GLOBAL_PROPERTY_PATIENT_LISTING_ATTRIBUTES, "", "A comma delimited list of PersonAttributeType names that should be displayed for patients in _lists_")); props .add(new GlobalProperty(GLOBAL_PROPERTY_PATIENT_VIEWING_ATTRIBUTES, "", "A comma delimited list of PersonAttributeType names that should be displayed for patients when _viewing individually_")); props.add(new GlobalProperty(GLOBAL_PROPERTY_PATIENT_HEADER_ATTRIBUTES, "", "A comma delimited list of PersonAttributeType names that will be shown on the patient dashboard")); props.add(new GlobalProperty(GLOBAL_PROPERTY_USER_LISTING_ATTRIBUTES, "", "A comma delimited list of PersonAttributeType names that should be displayed for users in _lists_")); props .add(new GlobalProperty(GLOBAL_PROPERTY_USER_VIEWING_ATTRIBUTES, "", "A comma delimited list of PersonAttributeType names that should be displayed for users when _viewing individually_")); props .add(new GlobalProperty(GLOBAL_PROPERTY_USER_HEADER_ATTRIBUTES, "", "A comma delimited list of PersonAttributeType names that will be shown on the user dashboard. (not used in v1.5)")); props .add(new GlobalProperty( GLOBAL_PROPERTY_PATIENT_IDENTIFIER_REGEX, "^0*@SEARCH@([A-Z]+-[0-9])?$", "A MySQL regular expression for the patient identifier search strings. The @SEARCH@ string is replaced at runtime with the user's search string. An empty regex will cause a simply 'like' sql search to be used")); props .add(new GlobalProperty( GLOBAL_PROPERTY_PATIENT_IDENTIFIER_PREFIX, "", "This property is only used if " + GLOBAL_PROPERTY_PATIENT_IDENTIFIER_REGEX + " is empty. The string here is prepended to the sql indentifier search string. The sql becomes \"... where identifier like '<PREFIX><QUERY STRING><SUFFIX>';\". Typically this value is either a percent sign (%) or empty.")); props .add(new GlobalProperty( GLOBAL_PROPERTY_PATIENT_IDENTIFIER_SUFFIX, "%", "This property is only used if " + GLOBAL_PROPERTY_PATIENT_IDENTIFIER_REGEX + " is empty. The string here is prepended to the sql indentifier search string. The sql becomes \"... where identifier like '<PREFIX><QUERY STRING><SUFFIX>';\". Typically this value is either a percent sign (%) or empty.")); props.add(new GlobalProperty(GLOBAL_PROPERTY_PATIENT_SEARCH_MAX_RESULTS, "1000", "The maximum number of results returned by patient searches")); props .add(new GlobalProperty( GLOBAL_PROPERTY_GZIP_ENABLED, "false", "Set to 'true' to turn on OpenMRS's gzip filter, and have the webapp compress data before sending it to any client that supports it. Generally use this if you are running Tomcat standalone. If you are running Tomcat behind Apache, then you'd want to use Apache to do gzip compression.")); props .add(new GlobalProperty(GLOBAL_PROPERTY_REPORT_XML_MACROS, "", "Macros that will be applied to Report Schema XMLs when they are interpreted. This should be java.util.properties format.")); props .add(new GlobalProperty( GLOBAL_PROPERTY_MEDICAL_RECORD_OBSERVATIONS, "1238", "The concept id of the MEDICAL_RECORD_OBSERVATIONS concept. This concept_id is presumed to be the generic grouping (obr) concept in hl7 messages. An obs_group row is not created for this concept.")); props .add(new GlobalProperty( GLOBAL_PROPERTY_PROBLEM_LIST, "1284", "The concept id of the PROBLEM LIST concept. This concept_id is presumed to be the generic grouping (obr) concept in hl7 messages. An obs_group row is not created for this concept.")); props .add(new GlobalProperty( GLOBAL_PROPERTY_LOG_LEVEL, LOG_LEVEL_INFO, "log level used by the logger 'org.openmrs'. This value will override the log4j.xml value. Valid values are trace, debug, info, warn, error or fatal")); props .add(new GlobalProperty( GLOBAL_PROPERTY_DEFAULT_PATIENT_IDENTIFIER_VALIDATOR, LUHN_IDENTIFIER_VALIDATOR, "This property sets the default patient identifier validator. The default validator is only used in a handful of (mostly legacy) instances. For example, it's used to generate the isValidCheckDigit calculated column and to append the string \"(default)\" to the name of the default validator on the editPatientIdentifierType form.")); props .add(new GlobalProperty( GLOBAL_PROPERTY_PATIENT_IDENTIFIER_IMPORTANT_TYPES, "", "A comma delimited list of PatientIdentifier names : PatientIdentifier locations that will be displayed on the patient dashboard. E.g.: TRACnet ID:Rwanda,ELDID:Kenya")); props.add(new GlobalProperty(GLOBAL_PROPERTY_COMPLEX_OBS_DIR, "complex_obs", "Default directory for storing complex obs.")); props .add(new GlobalProperty( GLOBAL_PROPERTY_ENCOUNTER_FORM_OBS_SORT_ORDER, "number", "The sort order for the obs listed on the encounter edit form. 'number' sorts on the associated numbering from the form schema. 'weight' sorts on the order displayed in the form schema.")); props.add(new GlobalProperty(GLOBAL_PROPERTY_LOCALE_ALLOWED_LIST, "en, es, fr, it, pt", "Comma delimited list of locales allowed for use on system")); props .add(new GlobalProperty( GLOBAL_PROPERTY_NEWPATIENTFORM_RELATIONSHIPS, "", "Comma separated list of the RelationshipTypes to show on the new/short patient form. The list is defined like '3a, 4b, 7a'. The number is the RelationshipTypeId and the 'a' vs 'b' part is which side of the relationship is filled in by the user.")); props.add(new GlobalProperty(GLOBAL_PROPERTY_MIN_SEARCH_CHARACTERS, "3", "Number of characters user must input before searching is started.")); props .add(new GlobalProperty( OpenmrsConstants.GLOBAL_PROPERTY_DEFAULT_LOCALE, OpenmrsConstants.GLOBAL_PROPERTY_DEFAULT_LOCALE_DEFAULT_VALUE, "Specifies the default locale. You can specify both the language code(ISO-639) and the country code(ISO-3166), e.g. 'en_GB' or just country: e.g. 'en'")); for (GlobalProperty gp : ModuleFactory.getGlobalProperties()) { props.add(gp); } return props; }
diff --git a/xml/src/main/java/org/openstreetmap/osmosis/xml/v0_6/impl/BoundWriter.java b/xml/src/main/java/org/openstreetmap/osmosis/xml/v0_6/impl/BoundWriter.java index c8b04ca8..4bce565d 100644 --- a/xml/src/main/java/org/openstreetmap/osmosis/xml/v0_6/impl/BoundWriter.java +++ b/xml/src/main/java/org/openstreetmap/osmosis/xml/v0_6/impl/BoundWriter.java @@ -1,92 +1,92 @@ // This software is released into the Public Domain. See copying.txt for details. package org.openstreetmap.osmosis.xml.v0_6.impl; import java.util.Locale; import org.openstreetmap.osmosis.core.domain.v0_6.Bound; import org.openstreetmap.osmosis.xml.common.ElementWriter; /** * @author KNewman * @author Igor Podolskiy * */ public class BoundWriter extends ElementWriter { private boolean legacyBound; /** * Creates a new instance. * * @param elementName * The name of the element to be written. * @param indentLevel * The indent level of the element. * @param legacyBound * If true, write the legacy <bound> element instead of the * correct <bounds> one. */ public BoundWriter(String elementName, int indentLevel, boolean legacyBound) { super(elementName, indentLevel); this.legacyBound = legacyBound; } /** * Writes the bound. * * @param bound * The bound to be processed. */ public void process(Bound bound) { if (legacyBound) { processLegacy(bound); } else { processRegular(bound); } } private void processRegular(Bound bound) { String format = "%.5f"; beginOpenElement(); addAttribute(XmlConstants.ATTRIBUTE_NAME_MINLON, - String.format(format, Locale.US, bound.getLeft())); + String.format(Locale.US, format, bound.getLeft())); addAttribute(XmlConstants.ATTRIBUTE_NAME_MINLAT, - String.format(format, Locale.US, bound.getBottom())); + String.format(Locale.US, format, bound.getBottom())); addAttribute(XmlConstants.ATTRIBUTE_NAME_MAXLON, - String.format(format, Locale.US, bound.getRight())); + String.format(Locale.US, format, bound.getRight())); addAttribute(XmlConstants.ATTRIBUTE_NAME_MAXLAT, - String.format(format, Locale.US, bound.getTop())); + String.format(Locale.US, format, bound.getTop())); if (bound.getOrigin() != null) { addAttribute("origin", bound.getOrigin()); } endOpenElement(true); } private void processLegacy(Bound bound) { // Only add the Bound if the origin string isn't empty if (!"".equals(bound.getOrigin())) { beginOpenElement(); // Write with the US locale (to force . instead of , as the decimal // separator) // Use only 5 decimal places (~1.2 meter resolution should be // sufficient for Bound) addAttribute("box", String.format( Locale.US, "%.5f,%.5f,%.5f,%.5f", bound.getBottom(), bound.getLeft(), bound.getTop(), bound.getRight())); addAttribute("origin", bound.getOrigin()); endOpenElement(true); } } }
false
true
private void processRegular(Bound bound) { String format = "%.5f"; beginOpenElement(); addAttribute(XmlConstants.ATTRIBUTE_NAME_MINLON, String.format(format, Locale.US, bound.getLeft())); addAttribute(XmlConstants.ATTRIBUTE_NAME_MINLAT, String.format(format, Locale.US, bound.getBottom())); addAttribute(XmlConstants.ATTRIBUTE_NAME_MAXLON, String.format(format, Locale.US, bound.getRight())); addAttribute(XmlConstants.ATTRIBUTE_NAME_MAXLAT, String.format(format, Locale.US, bound.getTop())); if (bound.getOrigin() != null) { addAttribute("origin", bound.getOrigin()); } endOpenElement(true); }
private void processRegular(Bound bound) { String format = "%.5f"; beginOpenElement(); addAttribute(XmlConstants.ATTRIBUTE_NAME_MINLON, String.format(Locale.US, format, bound.getLeft())); addAttribute(XmlConstants.ATTRIBUTE_NAME_MINLAT, String.format(Locale.US, format, bound.getBottom())); addAttribute(XmlConstants.ATTRIBUTE_NAME_MAXLON, String.format(Locale.US, format, bound.getRight())); addAttribute(XmlConstants.ATTRIBUTE_NAME_MAXLAT, String.format(Locale.US, format, bound.getTop())); if (bound.getOrigin() != null) { addAttribute("origin", bound.getOrigin()); } endOpenElement(true); }
diff --git a/chapter7/file/src/main/java/camelinaction/FileSaverWithFileName.java b/chapter7/file/src/main/java/camelinaction/FileSaverWithFileName.java index a03dcab..436770a 100644 --- a/chapter7/file/src/main/java/camelinaction/FileSaverWithFileName.java +++ b/chapter7/file/src/main/java/camelinaction/FileSaverWithFileName.java @@ -1,45 +1,45 @@ /** * 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 camelinaction; import org.apache.camel.CamelContext; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.impl.DefaultCamelContext; public class FileSaverWithFileName { public static void main(String args[]) throws Exception { // create CamelContext CamelContext context = new DefaultCamelContext(); // add our route to the CamelContext context.addRoutes(new RouteBuilder() { public void configure() { from("stream:in?promptMessage=Enter something:") - .to("file:target/data/outbox?fileName=${date:now:yyyyMMdd-hh:mm:ss}.txt"); + .to("file:target/data/outbox?fileName=${date:now:yyyyMMdd-hhmmss}.txt"); } }); // start the route and let it do its work context.start(); Thread.sleep(10000); // stop the CamelContext context.stop(); } }
true
true
public static void main(String args[]) throws Exception { // create CamelContext CamelContext context = new DefaultCamelContext(); // add our route to the CamelContext context.addRoutes(new RouteBuilder() { public void configure() { from("stream:in?promptMessage=Enter something:") .to("file:target/data/outbox?fileName=${date:now:yyyyMMdd-hh:mm:ss}.txt"); } }); // start the route and let it do its work context.start(); Thread.sleep(10000); // stop the CamelContext context.stop(); }
public static void main(String args[]) throws Exception { // create CamelContext CamelContext context = new DefaultCamelContext(); // add our route to the CamelContext context.addRoutes(new RouteBuilder() { public void configure() { from("stream:in?promptMessage=Enter something:") .to("file:target/data/outbox?fileName=${date:now:yyyyMMdd-hhmmss}.txt"); } }); // start the route and let it do its work context.start(); Thread.sleep(10000); // stop the CamelContext context.stop(); }
diff --git a/src/to/joe/j2mc/info/command/PlayerListCommand.java b/src/to/joe/j2mc/info/command/PlayerListCommand.java index e937f7f..ef70f8f 100644 --- a/src/to/joe/j2mc/info/command/PlayerListCommand.java +++ b/src/to/joe/j2mc/info/command/PlayerListCommand.java @@ -1,97 +1,97 @@ package to.joe.j2mc.info.command; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import to.joe.j2mc.core.J2MC_Manager; import to.joe.j2mc.core.command.MasterCommand; import to.joe.j2mc.info.J2MC_Info; public class PlayerListCommand extends MasterCommand { J2MC_Info plugin; public PlayerListCommand(J2MC_Info Info) { super(Info); this.plugin = Info; } @Override public void exec(CommandSender sender, String commandName, String[] args, Player player, boolean isPlayer) { if (!sender.hasPermission("j2mc.core.admin")) { int total = 0; for(Player derp : plugin.getServer().getOnlinePlayers()){ if(!J2MC_Manager.getVisibility().isVanished(derp)){ total++; } } sender.sendMessage(ChatColor.AQUA + "Players (" + total + "/" + plugin.getServer().getMaxPlayers() + "):"); if (total == 0) { sender.sendMessage(ChatColor.RED + "No one is online :("); return; } StringBuilder builder = new StringBuilder(); for (Player pl : plugin.getServer().getOnlinePlayers()) { if (!J2MC_Manager.getVisibility().isVanished(pl)) { String toAdd; toAdd = pl.getDisplayName(); if(J2MC_Manager.getPermissions().hasFlag(pl.getName(), 'd')){ toAdd = ChatColor.GOLD + pl.getName(); } builder.append(toAdd + ChatColor.WHITE + ", "); if (builder.length() > 75) { builder.setLength(builder.length() - (toAdd + ChatColor.WHITE + ", ").length()); sender.sendMessage(builder.toString()); builder = new StringBuilder(); builder.append(toAdd + ChatColor.WHITE + ", "); } } } builder.setLength(builder.length() - 2); sender.sendMessage(builder.toString()); } else { sender.sendMessage(ChatColor.AQUA + "Players (" + plugin.getServer().getOnlinePlayers().length + "/" + plugin.getServer().getMaxPlayers() + "):"); if (plugin.getServer().getOnlinePlayers().length == 0) { sender.sendMessage(ChatColor.RED + "No one is online :("); return; } StringBuilder builder = new StringBuilder(); for (Player pl : plugin.getServer().getOnlinePlayers()) { String toAdd = ""; toAdd = ChatColor.GREEN + pl.getName(); if(J2MC_Manager.getPermissions().hasFlag(pl.getName(), 't')){ toAdd = ChatColor.DARK_GREEN + pl.getName(); } if(J2MC_Manager.getPermissions().hasFlag(pl.getName(), 'd')){ toAdd = ChatColor.GOLD + pl.getName(); } - if(pl.hasPermission("j2mc-chat.mute")){ + if(pl.hasPermission("j2mc.chat.mute")){ toAdd = ChatColor.YELLOW + pl.getName(); } if(pl.hasPermission("j2mc.core.admin")){ toAdd = ChatColor.RED + pl.getName(); } if(J2MC_Manager.getVisibility().isVanished(pl)){ toAdd = ChatColor.AQUA + pl.getName(); } if(J2MC_Manager.getPermissions().hasFlag(pl.getName(), 'N')){ - toAdd += ChatColor.DARK_AQUA + "��"; + toAdd += ChatColor.DARK_AQUA + "\u00ab\u00bb"; } if(J2MC_Manager.getPermissions().hasFlag(pl.getName(), 'k')){ toAdd += ChatColor.RED + "&"; } builder.append(toAdd + ChatColor.WHITE + ", "); if (builder.length() > 75) { builder.setLength(builder.length() - (toAdd + ChatColor.WHITE + ", ").length()); sender.sendMessage(builder.toString()); builder = new StringBuilder(); builder.append(toAdd + ChatColor.WHITE + ", "); } } builder.setLength(builder.length() - 2); sender.sendMessage(builder.toString()); } } }
false
true
public void exec(CommandSender sender, String commandName, String[] args, Player player, boolean isPlayer) { if (!sender.hasPermission("j2mc.core.admin")) { int total = 0; for(Player derp : plugin.getServer().getOnlinePlayers()){ if(!J2MC_Manager.getVisibility().isVanished(derp)){ total++; } } sender.sendMessage(ChatColor.AQUA + "Players (" + total + "/" + plugin.getServer().getMaxPlayers() + "):"); if (total == 0) { sender.sendMessage(ChatColor.RED + "No one is online :("); return; } StringBuilder builder = new StringBuilder(); for (Player pl : plugin.getServer().getOnlinePlayers()) { if (!J2MC_Manager.getVisibility().isVanished(pl)) { String toAdd; toAdd = pl.getDisplayName(); if(J2MC_Manager.getPermissions().hasFlag(pl.getName(), 'd')){ toAdd = ChatColor.GOLD + pl.getName(); } builder.append(toAdd + ChatColor.WHITE + ", "); if (builder.length() > 75) { builder.setLength(builder.length() - (toAdd + ChatColor.WHITE + ", ").length()); sender.sendMessage(builder.toString()); builder = new StringBuilder(); builder.append(toAdd + ChatColor.WHITE + ", "); } } } builder.setLength(builder.length() - 2); sender.sendMessage(builder.toString()); } else { sender.sendMessage(ChatColor.AQUA + "Players (" + plugin.getServer().getOnlinePlayers().length + "/" + plugin.getServer().getMaxPlayers() + "):"); if (plugin.getServer().getOnlinePlayers().length == 0) { sender.sendMessage(ChatColor.RED + "No one is online :("); return; } StringBuilder builder = new StringBuilder(); for (Player pl : plugin.getServer().getOnlinePlayers()) { String toAdd = ""; toAdd = ChatColor.GREEN + pl.getName(); if(J2MC_Manager.getPermissions().hasFlag(pl.getName(), 't')){ toAdd = ChatColor.DARK_GREEN + pl.getName(); } if(J2MC_Manager.getPermissions().hasFlag(pl.getName(), 'd')){ toAdd = ChatColor.GOLD + pl.getName(); } if(pl.hasPermission("j2mc-chat.mute")){ toAdd = ChatColor.YELLOW + pl.getName(); } if(pl.hasPermission("j2mc.core.admin")){ toAdd = ChatColor.RED + pl.getName(); } if(J2MC_Manager.getVisibility().isVanished(pl)){ toAdd = ChatColor.AQUA + pl.getName(); } if(J2MC_Manager.getPermissions().hasFlag(pl.getName(), 'N')){ toAdd += ChatColor.DARK_AQUA + "��"; } if(J2MC_Manager.getPermissions().hasFlag(pl.getName(), 'k')){ toAdd += ChatColor.RED + "&"; } builder.append(toAdd + ChatColor.WHITE + ", "); if (builder.length() > 75) { builder.setLength(builder.length() - (toAdd + ChatColor.WHITE + ", ").length()); sender.sendMessage(builder.toString()); builder = new StringBuilder(); builder.append(toAdd + ChatColor.WHITE + ", "); } } builder.setLength(builder.length() - 2); sender.sendMessage(builder.toString()); } }
public void exec(CommandSender sender, String commandName, String[] args, Player player, boolean isPlayer) { if (!sender.hasPermission("j2mc.core.admin")) { int total = 0; for(Player derp : plugin.getServer().getOnlinePlayers()){ if(!J2MC_Manager.getVisibility().isVanished(derp)){ total++; } } sender.sendMessage(ChatColor.AQUA + "Players (" + total + "/" + plugin.getServer().getMaxPlayers() + "):"); if (total == 0) { sender.sendMessage(ChatColor.RED + "No one is online :("); return; } StringBuilder builder = new StringBuilder(); for (Player pl : plugin.getServer().getOnlinePlayers()) { if (!J2MC_Manager.getVisibility().isVanished(pl)) { String toAdd; toAdd = pl.getDisplayName(); if(J2MC_Manager.getPermissions().hasFlag(pl.getName(), 'd')){ toAdd = ChatColor.GOLD + pl.getName(); } builder.append(toAdd + ChatColor.WHITE + ", "); if (builder.length() > 75) { builder.setLength(builder.length() - (toAdd + ChatColor.WHITE + ", ").length()); sender.sendMessage(builder.toString()); builder = new StringBuilder(); builder.append(toAdd + ChatColor.WHITE + ", "); } } } builder.setLength(builder.length() - 2); sender.sendMessage(builder.toString()); } else { sender.sendMessage(ChatColor.AQUA + "Players (" + plugin.getServer().getOnlinePlayers().length + "/" + plugin.getServer().getMaxPlayers() + "):"); if (plugin.getServer().getOnlinePlayers().length == 0) { sender.sendMessage(ChatColor.RED + "No one is online :("); return; } StringBuilder builder = new StringBuilder(); for (Player pl : plugin.getServer().getOnlinePlayers()) { String toAdd = ""; toAdd = ChatColor.GREEN + pl.getName(); if(J2MC_Manager.getPermissions().hasFlag(pl.getName(), 't')){ toAdd = ChatColor.DARK_GREEN + pl.getName(); } if(J2MC_Manager.getPermissions().hasFlag(pl.getName(), 'd')){ toAdd = ChatColor.GOLD + pl.getName(); } if(pl.hasPermission("j2mc.chat.mute")){ toAdd = ChatColor.YELLOW + pl.getName(); } if(pl.hasPermission("j2mc.core.admin")){ toAdd = ChatColor.RED + pl.getName(); } if(J2MC_Manager.getVisibility().isVanished(pl)){ toAdd = ChatColor.AQUA + pl.getName(); } if(J2MC_Manager.getPermissions().hasFlag(pl.getName(), 'N')){ toAdd += ChatColor.DARK_AQUA + "\u00ab\u00bb"; } if(J2MC_Manager.getPermissions().hasFlag(pl.getName(), 'k')){ toAdd += ChatColor.RED + "&"; } builder.append(toAdd + ChatColor.WHITE + ", "); if (builder.length() > 75) { builder.setLength(builder.length() - (toAdd + ChatColor.WHITE + ", ").length()); sender.sendMessage(builder.toString()); builder = new StringBuilder(); builder.append(toAdd + ChatColor.WHITE + ", "); } } builder.setLength(builder.length() - 2); sender.sendMessage(builder.toString()); } }
diff --git a/src/main/edu/iastate/music/marching/attendance/servlets/FormsServlet.java b/src/main/edu/iastate/music/marching/attendance/servlets/FormsServlet.java index b7888e3b..a7842d06 100644 --- a/src/main/edu/iastate/music/marching/attendance/servlets/FormsServlet.java +++ b/src/main/edu/iastate/music/marching/attendance/servlets/FormsServlet.java @@ -1,732 +1,732 @@ package edu.iastate.music.marching.attendance.servlets; import java.io.IOException; import java.net.URLEncoder; import java.util.Calendar; import java.util.Date; import java.util.LinkedList; import java.util.List; import java.util.TimeZone; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import edu.iastate.music.marching.attendance.App; import edu.iastate.music.marching.attendance.controllers.DataTrain; import edu.iastate.music.marching.attendance.controllers.FormController; import edu.iastate.music.marching.attendance.model.Absence; import edu.iastate.music.marching.attendance.model.Form; import edu.iastate.music.marching.attendance.model.User; import edu.iastate.music.marching.attendance.util.PageBuilder; import edu.iastate.music.marching.attendance.util.Util; import edu.iastate.music.marching.attendance.util.ValidationUtil; public class FormsServlet extends AbstractBaseServlet { /** * */ private static final long serialVersionUID = -4738485557840953303L; private enum Page { forma, formb, formc, formd, index, view, remove, messages; } private static final String SERVLET_PATH = "form"; private static final String SUCCESS_FORMA = "Submitted new Form A"; private static final String SUCCESS_FORMB = "Submitted new Form B"; private static final String SUCCESS_FORMC = "Submitted new Form C"; private static final String SUCCESS_FORMD = "Submitted new Form D"; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (!isLoggedIn(req, resp)) { resp.sendRedirect(AuthServlet.getLoginUrl(req)); return; } else if (!isLoggedIn(req, resp, getServletUserTypes())) { resp.sendRedirect(ErrorServlet.getLoginFailedUrl(req)); return; } Page page = parsePathInfo(req.getPathInfo(), Page.class); if (page == null) { show404(req, resp); return; } switch (page) { case forma: postFormA(req, resp); break; case formb: handleFormB(req, resp); break; case formc: handleFormC(req, resp); break; case formd: handleFormD(req, resp); break; case index: showIndex(req, resp); break; case view: viewForm(req, resp, new LinkedList<String>(), ""); break; // case remove: // removeForm(req, resp); // break; case messages: break; default: ErrorServlet.showError(req, resp, 404); } } private void viewForm(HttpServletRequest req, HttpServletResponse resp, List<String> errors, String success_message) throws ServletException, IOException { DataTrain train = DataTrain.getAndStartTrain(); User currentUser = train.getAuthController().getCurrentUser( req.getSession()); Form form = null; try { long id = Long.parseLong(req.getParameter("id")); form = train.getFormsController().get(id); PageBuilder page = new PageBuilder(Page.view, SERVLET_PATH); page.setPageTitle("Form " + form.getType()); page.setAttribute("form", form); page.setAttribute("day", form.getDayAsString()); page.setAttribute("isDirector", currentUser.getType().isDirector()); page.setAttribute("error_messages", errors); page.setAttribute("success_message", success_message); page.passOffToJsp(req, resp); } catch (NumberFormatException nfe) { ErrorServlet.showError(req, resp, 500); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (!isLoggedIn(req, resp)) { resp.sendRedirect(AuthServlet.getLoginUrl()); return; } else if (!isLoggedIn(req, resp, getServletUserTypes())) { resp.sendRedirect(ErrorServlet.getLoginFailedUrl(req)); return; } Page page = parsePathInfo(req.getPathInfo(), Page.class); if (page == null) ErrorServlet.showError(req, resp, 404); else switch (page) { case index: showIndex(req, resp); break; case forma: postFormA(req, resp); break; case formb: handleFormB(req, resp); break; case formc: handleFormC(req, resp); break; case formd: handleFormD(req, resp); break; case messages: break; case view: updateStatus(req, resp); break; default: ErrorServlet.showError(req, resp, 404); } } private void updateStatus(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { DataTrain train = DataTrain.getAndStartTrain(); FormController fc = train.getFormsController(); List<String> errors = new LinkedList<String>(); String success_message = ""; boolean validForm = true; Form f = null; Form.Status status = null; long id = 0; if (!ValidationUtil.isPost(req)) { validForm = false; } if (validForm) { try { id = Long.parseLong(req.getParameter("id")); f = fc.get(id); String strStat = req.getParameter("status"); if (strStat.equalsIgnoreCase("Approved")) status = Form.Status.Approved; else if (strStat.equalsIgnoreCase("Pending")) status = Form.Status.Pending; else if (strStat.equalsIgnoreCase("Denied")) status = Form.Status.Denied; else { validForm = false; errors.add("Invalid form status."); } } catch (NumberFormatException e) { errors.add("Unable to find form."); validForm = false; } catch (NullPointerException e) { errors.add("Unable to find form."); validForm = false; } } if (validForm) { // Send them back to their Form page f.setStatus(status); fc.update(f); success_message = "Successfully updated form."; } viewForm(req, resp, errors, success_message); } private void postFormA(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String reason = null; Date date = null; DataTrain train = DataTrain.getAndStartTrain(); // Parse out all data from form and validate boolean validForm = true; List<String> errors = new LinkedList<String>(); if (!ValidationUtil.isPost(req)) { // This is not a post request to create a new form, no need to // validate validForm = false; } else { // Extract all basic parameters reason = req.getParameter("Reason"); try { date = Util.parseDate(req.getParameter("StartMonth"), req.getParameter("StartDay"), req.getParameter("StartYear"), "0", "AM", "0", train .getAppDataController().get().getTimeZone()); } catch (IllegalArgumentException e) { validForm = false; errors.add("Invalid Input: The input date is invalid."); } } if (validForm) { // Store our new form to the data store User student = train.getAuthController().getCurrentUser( req.getSession()); Form form = null; try { form = train.getFormsController().createFormA(student, date, reason); } catch (IllegalArgumentException e) { validForm = false; errors.add(e.getMessage()); } if (form == null) { validForm = false; errors.add("Internal Error: Failed to create form and store in database"); } } if (validForm) { String url = getIndexURL() + "?success_message=" + URLEncoder.encode(SUCCESS_FORMA, "UTF-8"); // url = resp.encodeRedirectURL(url); resp.sendRedirect(url); } else { // Show form PageBuilder page = new PageBuilder(Page.forma, SERVLET_PATH); page.setPageTitle("Form A"); page.setAttribute("error_messages", errors); page.setAttribute("cutoff", train.getAppDataController().get() .getFormSubmissionCutoff()); page.setAttribute("Reason", reason); setStartDate(date, page, train.getAppDataController().get() .getTimeZone()); page.passOffToJsp(req, resp); } } private void handleFormB(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String department = null; String course = null; String section = null; String building = null; Date startDate = null; Date endDate = null; Date fromTime = null; Date toTime = null; int day = -1; int minutesToOrFrom = 0; String comments = null; Absence.Type absenceType = null; DataTrain train = DataTrain.getAndStartTrain(); // Parse out all data from form and validate boolean validForm = true; List<String> errors = new LinkedList<String>(); if (!ValidationUtil.isPost(req)) { // This is not a post request to create a new form, no need to // validate validForm = false; } else { // Extract all basic parameters department = req.getParameter("Department"); course = req.getParameter("Course"); section = req.getParameter("Section"); building = req.getParameter("Building"); comments = req.getParameter("Comments"); - String minutestmp = req.getParameter("MinutestoOrFrom"); + String minutestmp = req.getParameter("MinutesToOrFrom"); try { minutesToOrFrom = Integer.parseInt(minutestmp); } catch (NumberFormatException nfe) { errors.add("Minutes to or from must be a whole number."); } String stype = req.getParameter("Type"); if (stype != null && !stype.equals("")) { if (stype.equals(Absence.Type.Absence.getValue())) { absenceType = Absence.Type.Absence; } else if (stype.equals(Absence.Type.Tardy.getValue())) { absenceType = Absence.Type.Tardy; } else if (stype.equals(Absence.Type.EarlyCheckOut.getValue())) { absenceType = Absence.Type.EarlyCheckOut; } } else { errors.add("Invalid type."); } // this is one-based! Starting on Sunday. try { day = Integer.parseInt(req.getParameter("DayOfWeek")); } catch (NumberFormatException nfe) { errors.add("Weekday was invalid."); } if (day < 1 || day > 7) { errors.add("Value of " + day + " for day was not valid."); } try { startDate = Util.parseDate(req.getParameter("StartMonth"), req.getParameter("StartDay"), req.getParameter("StartYear"), "0", "AM", "0", train .getAppDataController().get().getTimeZone()); } catch (IllegalArgumentException e) { validForm = false; errors.add("The start date is invalid."); } try { endDate = Util.parseDate(req.getParameter("EndMonth"), req.getParameter("EndDay"), req.getParameter("EndYear"), "0", "AM", "0", train .getAppDataController().get().getTimeZone()); } catch (IllegalArgumentException e) { validForm = false; errors.add("The end date is invalid."); } try { fromTime = Util.parseDate("1", "1", "1000", req.getParameter("FromHour"), req.getParameter("FromAMPM"), req.getParameter("FromMinute"), train .getAppDataController().get().getTimeZone()); } catch (IllegalArgumentException e) { validForm = false; errors.add("The start time is invalid."); } try { toTime = Util.parseDate("1", "1", "1000", req.getParameter("ToHour"), req.getParameter("ToAMPM"), req.getParameter("ToMinute"), train .getAppDataController().get().getTimeZone()); } catch (IllegalArgumentException e) { validForm = false; errors.add("The end time is invalid."); } } if (validForm) { // Store our new form to the datastore User student = train.getAuthController().getCurrentUser( req.getSession()); Form form = null; try { form = train.getFormsController().createFormB(student, department, course, section, building, startDate, endDate, day, fromTime, toTime, comments, minutesToOrFrom, absenceType); } catch (IllegalArgumentException e) { validForm = false; errors.add(e.getMessage()); } if (form == null) { validForm = false; errors.add("Internal Error: Failed to create form and store in database. Please submit a bug report through the form at the bottom of this page."); } } if (validForm) { String url = getIndexURL() + "?success_message=" + URLEncoder.encode(SUCCESS_FORMB, "UTF-8"); url = resp.encodeRedirectURL(url); resp.sendRedirect(url); } else { // Show form PageBuilder page = new PageBuilder(Page.formb, SERVLET_PATH); page.setPageTitle("Form B"); page.setAttribute("daysOfWeek", App.getDaysOfTheWeek()); page.setAttribute("error_messages", errors); page.setAttribute("Department", department); page.setAttribute("Course", course); page.setAttribute("Section", section); page.setAttribute("Building", building); setStartDate(startDate, page, train.getAppDataController().get() .getTimeZone()); setEndDate(endDate, page, train.getAppDataController().get() .getTimeZone()); page.setAttribute("Type", Form.Type.B); page.setAttribute("Comments", comments); page.setAttribute("MinutesToOrFrom", minutesToOrFrom); page.setAttribute("Type", absenceType); page.setAttribute("types", Absence.Type.values()); page.passOffToJsp(req, resp); } } private void handleFormC(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Date date = null; String reason = null; Absence.Type type = null; DataTrain train = DataTrain.getAndStartTrain(); // Parse out all data from form and validate boolean validForm = true; List<String> errors = new LinkedList<String>(); if (!ValidationUtil.isPost(req)) { // This is not a post request to create a new form, no need to // validate validForm = false; } else { // Extract all basic parameters reason = req.getParameter("Reason"); String stype = req.getParameter("Type"); if (stype != null && !stype.equals("")) { if (stype.equals(Absence.Type.Absence.getValue())) { type = Absence.Type.Absence; } else if (stype.equals(Absence.Type.Tardy.getValue())) { type = Absence.Type.Tardy; } else if (stype.equals(Absence.Type.EarlyCheckOut.getValue())) { type = Absence.Type.EarlyCheckOut; } } else { errors.add("Invalid type."); } try { if (type == Absence.Type.Absence) { date = Util.parseDate(req.getParameter("Month"), req.getParameter("Day"), req.getParameter("Year"), "0", "AM", "0", train.getAppDataController().get() .getTimeZone()); } else { date = Util .parseDate(req.getParameter("Month"), req.getParameter("Day"), req.getParameter("Year"), req.getParameter("Hour"), req.getParameter("AMPM"), req.getParameter("Minute"), train .getAppDataController().get() .getTimeZone()); } } catch (IllegalArgumentException e) { validForm = false; errors.add("The date is invalid."); } } if (validForm) { // Store our new form to the data store User student = train.getAuthController().getCurrentUser( req.getSession()); Form form = null; try { form = train.getFormsController().createFormC(student, date, type, reason); } catch (IllegalArgumentException e) { validForm = false; errors.add(e.getMessage()); } if (form == null) { validForm = false; errors.add("Internal Error: Failed to create form and store in database"); } } if (validForm) { String url = getIndexURL() + "?success_message=" + URLEncoder.encode(SUCCESS_FORMC, "UTF-8"); url = resp.encodeRedirectURL(url); resp.sendRedirect(url); } else { // Show form PageBuilder page = new PageBuilder(Page.formc, SERVLET_PATH); page.setPageTitle("Form C"); page.setAttribute("error_messages", errors); page.setAttribute("types", Absence.Type.values()); setStartDate(date, page, train.getAppDataController().get() .getTimeZone()); page.setAttribute("Reason", reason); page.passOffToJsp(req, resp); } } private void handleFormD(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String email = null; int minutes = 0; Date date = null; String details = null; DataTrain train = DataTrain.getAndStartTrain(); // Parse out all data from form and validate boolean validForm = true; List<String> errors = new LinkedList<String>(); if (!ValidationUtil.isPost(req)) { // This is not a post request to create a new form, no need to // validate validForm = false; } else { // Extract all basic parameters email = req.getParameter("Email"); details = req.getParameter("Details"); try { minutes = Integer.parseInt(req.getParameter("AmountWorked")); } catch (NumberFormatException e) { validForm = false; errors.add("Invalid amount of time worked: " + e.getMessage()); } try { date = Util.parseDate(req.getParameter("StartMonth"), req.getParameter("StartDay"), req.getParameter("StartYear"), "0", "AM", "0", train .getAppDataController().get().getTimeZone()); } catch (IllegalArgumentException e) { validForm = false; errors.add("Invalid Input: The input date is invalid."); } } User student = train.getAuthController().getCurrentUser( req.getSession()); if (validForm) { // Store our new form to the data store Form form = null; try { // hash the id for use in the accepting and declining forms form = train.getFormsController().createFormD(student, email, date, minutes, details); } catch (IllegalArgumentException e) { validForm = false; errors.add(e.getMessage()); } if (form == null) { validForm = false; errors.add("Internal Error: Failed to create form and store in database"); } } if (validForm) { String url = getIndexURL() + "?success_message=" + URLEncoder.encode(SUCCESS_FORMD, "UTF-8"); url = resp.encodeRedirectURL(url); resp.sendRedirect(url); } else { // Show form PageBuilder page = new PageBuilder(Page.formd, SERVLET_PATH); page.setPageTitle("Form D"); page.setAttribute("error_messages", errors); page.setAttribute("verifiers", train.getAppDataController().get() .getTimeWorkedEmails()); page.setAttribute("Email", email); page.setAttribute("AmountWorked", minutes); setStartDate(date, page, train.getAppDataController().get() .getTimeZone()); page.setAttribute("Details", details); page.passOffToJsp(req, resp); } } private void setEndDate(Date date, PageBuilder page, TimeZone timezone) { if (date == null) return; Calendar c = Calendar.getInstance(timezone); c.setTime(date); page.setAttribute("EndYear", c.get(Calendar.YEAR)); page.setAttribute("EndMonth", c.get(Calendar.MONTH)); page.setAttribute("EndDay", c.get(Calendar.DATE)); } private void setStartDate(Date date, PageBuilder page, TimeZone timezone) { if (date == null) return; Calendar c = Calendar.getInstance(timezone); c.setTime(date); page.setAttribute("StartYear", c.get(Calendar.YEAR)); page.setAttribute("StartMonth", c.get(Calendar.MONTH)); page.setAttribute("StartDay", c.get(Calendar.DATE)); page.setAttribute("StartHour", c.get(Calendar.HOUR)); page.setAttribute("StartMinute", c.get(Calendar.MINUTE)); page.setAttribute("StartPeriod", c.get(Calendar.AM_PM)); } private void showIndex(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { DataTrain train = DataTrain.getAndStartTrain(); FormController fc = train.getFormsController(); PageBuilder page = new PageBuilder(Page.index, SERVLET_PATH); // Pass through any success message in the url parameters sent from a // new form being created or deleted page.setAttribute("success_message", req.getParameter("success_message")); User currentUser = train.getAuthController().getCurrentUser( req.getSession()); String removeid = req.getParameter("removeid"); if (removeid != null && removeid != "") { try { long id = Long.parseLong(removeid); if (currentUser.getType() == User.Type.Student && fc.get(id).getStatus() != Form.Status.Pending) { page.setAttribute("error_messages", "Students cannot delete any non-pending form."); } else { if (fc.removeForm(id)) { page.setAttribute("success_message", "Form successfully deleted"); } else { page.setAttribute("error_messages", "Form not deleted. If the form was already approved then you can't delete it."); } } } catch (NullPointerException e) { page.setAttribute("error_messages", "The form does not exist."); } } // Handle students and director differently List<Form> forms = null; if (getServletUserType() == User.Type.Student) forms = fc.get(currentUser); else if (getServletUserType() == User.Type.Director) forms = fc.getAll(); page.setAttribute("forms", forms); page.passOffToJsp(req, resp); } /** * This servlet can be used for multiple user types, this grabs the type of * user this specific servlet instance is for * * @return */ private User.Type getServletUserType() { String value = getInitParameter("userType"); return User.Type.valueOf(value); } /** * This servlet can be used for multiple user types, this grabs the type of * user this specific servlet instance can be accessed by * * @return */ private User.Type[] getServletUserTypes() { User.Type userType = getServletUserType(); // Since a TA is also a student, we also allow them access to their // student forms if (userType == User.Type.Student) return new User.Type[] { User.Type.Student, User.Type.TA }; else return new User.Type[] { userType }; } /** * Have to use a method since this servlet can be mapped from different * paths */ private String getIndexURL() { return pageToUrl(Page.index, getInitParameter("path")); } }
true
true
private void handleFormB(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String department = null; String course = null; String section = null; String building = null; Date startDate = null; Date endDate = null; Date fromTime = null; Date toTime = null; int day = -1; int minutesToOrFrom = 0; String comments = null; Absence.Type absenceType = null; DataTrain train = DataTrain.getAndStartTrain(); // Parse out all data from form and validate boolean validForm = true; List<String> errors = new LinkedList<String>(); if (!ValidationUtil.isPost(req)) { // This is not a post request to create a new form, no need to // validate validForm = false; } else { // Extract all basic parameters department = req.getParameter("Department"); course = req.getParameter("Course"); section = req.getParameter("Section"); building = req.getParameter("Building"); comments = req.getParameter("Comments"); String minutestmp = req.getParameter("MinutestoOrFrom"); try { minutesToOrFrom = Integer.parseInt(minutestmp); } catch (NumberFormatException nfe) { errors.add("Minutes to or from must be a whole number."); } String stype = req.getParameter("Type"); if (stype != null && !stype.equals("")) { if (stype.equals(Absence.Type.Absence.getValue())) { absenceType = Absence.Type.Absence; } else if (stype.equals(Absence.Type.Tardy.getValue())) { absenceType = Absence.Type.Tardy; } else if (stype.equals(Absence.Type.EarlyCheckOut.getValue())) { absenceType = Absence.Type.EarlyCheckOut; } } else { errors.add("Invalid type."); } // this is one-based! Starting on Sunday. try { day = Integer.parseInt(req.getParameter("DayOfWeek")); } catch (NumberFormatException nfe) { errors.add("Weekday was invalid."); } if (day < 1 || day > 7) { errors.add("Value of " + day + " for day was not valid."); } try { startDate = Util.parseDate(req.getParameter("StartMonth"), req.getParameter("StartDay"), req.getParameter("StartYear"), "0", "AM", "0", train .getAppDataController().get().getTimeZone()); } catch (IllegalArgumentException e) { validForm = false; errors.add("The start date is invalid."); } try { endDate = Util.parseDate(req.getParameter("EndMonth"), req.getParameter("EndDay"), req.getParameter("EndYear"), "0", "AM", "0", train .getAppDataController().get().getTimeZone()); } catch (IllegalArgumentException e) { validForm = false; errors.add("The end date is invalid."); } try { fromTime = Util.parseDate("1", "1", "1000", req.getParameter("FromHour"), req.getParameter("FromAMPM"), req.getParameter("FromMinute"), train .getAppDataController().get().getTimeZone()); } catch (IllegalArgumentException e) { validForm = false; errors.add("The start time is invalid."); } try { toTime = Util.parseDate("1", "1", "1000", req.getParameter("ToHour"), req.getParameter("ToAMPM"), req.getParameter("ToMinute"), train .getAppDataController().get().getTimeZone()); } catch (IllegalArgumentException e) { validForm = false; errors.add("The end time is invalid."); } } if (validForm) { // Store our new form to the datastore User student = train.getAuthController().getCurrentUser( req.getSession()); Form form = null; try { form = train.getFormsController().createFormB(student, department, course, section, building, startDate, endDate, day, fromTime, toTime, comments, minutesToOrFrom, absenceType); } catch (IllegalArgumentException e) { validForm = false; errors.add(e.getMessage()); } if (form == null) { validForm = false; errors.add("Internal Error: Failed to create form and store in database. Please submit a bug report through the form at the bottom of this page."); } } if (validForm) { String url = getIndexURL() + "?success_message=" + URLEncoder.encode(SUCCESS_FORMB, "UTF-8"); url = resp.encodeRedirectURL(url); resp.sendRedirect(url); } else { // Show form PageBuilder page = new PageBuilder(Page.formb, SERVLET_PATH); page.setPageTitle("Form B"); page.setAttribute("daysOfWeek", App.getDaysOfTheWeek()); page.setAttribute("error_messages", errors); page.setAttribute("Department", department); page.setAttribute("Course", course); page.setAttribute("Section", section); page.setAttribute("Building", building); setStartDate(startDate, page, train.getAppDataController().get() .getTimeZone()); setEndDate(endDate, page, train.getAppDataController().get() .getTimeZone()); page.setAttribute("Type", Form.Type.B); page.setAttribute("Comments", comments); page.setAttribute("MinutesToOrFrom", minutesToOrFrom); page.setAttribute("Type", absenceType); page.setAttribute("types", Absence.Type.values()); page.passOffToJsp(req, resp); } }
private void handleFormB(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String department = null; String course = null; String section = null; String building = null; Date startDate = null; Date endDate = null; Date fromTime = null; Date toTime = null; int day = -1; int minutesToOrFrom = 0; String comments = null; Absence.Type absenceType = null; DataTrain train = DataTrain.getAndStartTrain(); // Parse out all data from form and validate boolean validForm = true; List<String> errors = new LinkedList<String>(); if (!ValidationUtil.isPost(req)) { // This is not a post request to create a new form, no need to // validate validForm = false; } else { // Extract all basic parameters department = req.getParameter("Department"); course = req.getParameter("Course"); section = req.getParameter("Section"); building = req.getParameter("Building"); comments = req.getParameter("Comments"); String minutestmp = req.getParameter("MinutesToOrFrom"); try { minutesToOrFrom = Integer.parseInt(minutestmp); } catch (NumberFormatException nfe) { errors.add("Minutes to or from must be a whole number."); } String stype = req.getParameter("Type"); if (stype != null && !stype.equals("")) { if (stype.equals(Absence.Type.Absence.getValue())) { absenceType = Absence.Type.Absence; } else if (stype.equals(Absence.Type.Tardy.getValue())) { absenceType = Absence.Type.Tardy; } else if (stype.equals(Absence.Type.EarlyCheckOut.getValue())) { absenceType = Absence.Type.EarlyCheckOut; } } else { errors.add("Invalid type."); } // this is one-based! Starting on Sunday. try { day = Integer.parseInt(req.getParameter("DayOfWeek")); } catch (NumberFormatException nfe) { errors.add("Weekday was invalid."); } if (day < 1 || day > 7) { errors.add("Value of " + day + " for day was not valid."); } try { startDate = Util.parseDate(req.getParameter("StartMonth"), req.getParameter("StartDay"), req.getParameter("StartYear"), "0", "AM", "0", train .getAppDataController().get().getTimeZone()); } catch (IllegalArgumentException e) { validForm = false; errors.add("The start date is invalid."); } try { endDate = Util.parseDate(req.getParameter("EndMonth"), req.getParameter("EndDay"), req.getParameter("EndYear"), "0", "AM", "0", train .getAppDataController().get().getTimeZone()); } catch (IllegalArgumentException e) { validForm = false; errors.add("The end date is invalid."); } try { fromTime = Util.parseDate("1", "1", "1000", req.getParameter("FromHour"), req.getParameter("FromAMPM"), req.getParameter("FromMinute"), train .getAppDataController().get().getTimeZone()); } catch (IllegalArgumentException e) { validForm = false; errors.add("The start time is invalid."); } try { toTime = Util.parseDate("1", "1", "1000", req.getParameter("ToHour"), req.getParameter("ToAMPM"), req.getParameter("ToMinute"), train .getAppDataController().get().getTimeZone()); } catch (IllegalArgumentException e) { validForm = false; errors.add("The end time is invalid."); } } if (validForm) { // Store our new form to the datastore User student = train.getAuthController().getCurrentUser( req.getSession()); Form form = null; try { form = train.getFormsController().createFormB(student, department, course, section, building, startDate, endDate, day, fromTime, toTime, comments, minutesToOrFrom, absenceType); } catch (IllegalArgumentException e) { validForm = false; errors.add(e.getMessage()); } if (form == null) { validForm = false; errors.add("Internal Error: Failed to create form and store in database. Please submit a bug report through the form at the bottom of this page."); } } if (validForm) { String url = getIndexURL() + "?success_message=" + URLEncoder.encode(SUCCESS_FORMB, "UTF-8"); url = resp.encodeRedirectURL(url); resp.sendRedirect(url); } else { // Show form PageBuilder page = new PageBuilder(Page.formb, SERVLET_PATH); page.setPageTitle("Form B"); page.setAttribute("daysOfWeek", App.getDaysOfTheWeek()); page.setAttribute("error_messages", errors); page.setAttribute("Department", department); page.setAttribute("Course", course); page.setAttribute("Section", section); page.setAttribute("Building", building); setStartDate(startDate, page, train.getAppDataController().get() .getTimeZone()); setEndDate(endDate, page, train.getAppDataController().get() .getTimeZone()); page.setAttribute("Type", Form.Type.B); page.setAttribute("Comments", comments); page.setAttribute("MinutesToOrFrom", minutesToOrFrom); page.setAttribute("Type", absenceType); page.setAttribute("types", Absence.Type.values()); page.passOffToJsp(req, resp); } }
diff --git a/src/main/java/de/cismet/cids/custom/objectrenderer/wunda_blau/Alkis_buchungsblattRenderer.java b/src/main/java/de/cismet/cids/custom/objectrenderer/wunda_blau/Alkis_buchungsblattRenderer.java index 10448fa8..924f3d4f 100644 --- a/src/main/java/de/cismet/cids/custom/objectrenderer/wunda_blau/Alkis_buchungsblattRenderer.java +++ b/src/main/java/de/cismet/cids/custom/objectrenderer/wunda_blau/Alkis_buchungsblattRenderer.java @@ -1,318 +1,318 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * Alkis_pointRenderer.java * * Created on 10.09.2009, 15:52:16 */ package de.cismet.cids.custom.objectrenderer.wunda_blau; import de.aedsicad.aaaweb.service.alkis.info.ALKISInfoServices; import de.aedsicad.aaaweb.service.util.Buchungsblatt; import de.cismet.cids.custom.objectrenderer.utils.alkis.SOAPAccessProvider; import de.cismet.cids.dynamics.CidsBean; import de.cismet.cids.tools.metaobjectrenderer.CidsBeanRenderer; import de.cismet.tools.CismetThreadPool; import de.cismet.tools.collections.TypeSafeCollections; import de.cismet.tools.gui.FooterComponentProvider; import de.cismet.tools.gui.StaticSwingTools; import de.cismet.tools.gui.TitleComponentProvider; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.List; import java.util.logging.Level; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.SwingWorker; import javax.swing.Timer; import org.jdesktop.swingx.error.ErrorInfo; /** * * @author srichter */ public class Alkis_buchungsblattRenderer extends javax.swing.JPanel implements CidsBeanRenderer, TitleComponentProvider, FooterComponentProvider { private static final org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(Alkis_buchungsblattRenderer.class); private final List<JLabel> retrieveableLabels; private SOAPAccessProvider soapProvider; // private ALKISSearchServices searchService; private ALKISInfoServices infoService; private Buchungsblatt buchungsblatt; private CidsBean cidsBean; private String title; /** Creates new form Alkis_pointRenderer */ public Alkis_buchungsblattRenderer() { retrieveableLabels = TypeSafeCollections.newArrayList(); try { soapProvider = new SOAPAccessProvider(); // searchService = soapProvider.getAlkisSearchService(); infoService = soapProvider.getAlkisInfoService(); } catch (Exception ex) { log.fatal(ex, ex); } initComponents(); retrieveableLabels.add(lblTxtEigentuemerNachname); retrieveableLabels.add(lblTxtFlurstueckcode); // retrieveableLabels.add(lblTxtAbmarkung); // retrieveableLabels.add(lblTxtModellart); // retrieveableLabels.add(lblTxtDienststelle); // retrieveableLabels.add(lblTxtLand); // retrieveableLabels.add(lblTxtDienststelle); // retrieveableLabels.add(lblTxtAnlass); // retrieveableLabels.add(lblTxtBemerkungAbmarkung); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; bindingGroup = new org.jdesktop.beansbinding.BindingGroup(); panTitle = new javax.swing.JPanel(); panFooter = new javax.swing.JPanel(); lblTxtBuchungsblattcode = new javax.swing.JLabel(); btnRetrieve = new javax.swing.JButton(); lblBuchungsblattcode = new javax.swing.JLabel(); lblTxtEigentuemerNachname = new javax.swing.JLabel(); lblTxtFlurstueckcode = new javax.swing.JLabel(); lblEigentuemernachname = new javax.swing.JLabel(); lblFlurstueckcode = new javax.swing.JLabel(); panTitle.setOpaque(false); javax.swing.GroupLayout panTitleLayout = new javax.swing.GroupLayout(panTitle); panTitle.setLayout(panTitleLayout); panTitleLayout.setHorizontalGroup( panTitleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 100, Short.MAX_VALUE) ); panTitleLayout.setVerticalGroup( panTitleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 100, Short.MAX_VALUE) ); panFooter.setOpaque(false); javax.swing.GroupLayout panFooterLayout = new javax.swing.GroupLayout(panFooter); panFooter.setLayout(panFooterLayout); panFooterLayout.setHorizontalGroup( panFooterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 100, Short.MAX_VALUE) ); panFooterLayout.setVerticalGroup( panFooterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 100, Short.MAX_VALUE) ); setLayout(new java.awt.GridBagLayout()); - org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.pointcode}"), lblTxtBuchungsblattcode, org.jdesktop.beansbinding.BeanProperty.create("text")); + org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.buchungsblattcode}"), lblTxtBuchungsblattcode, org.jdesktop.beansbinding.BeanProperty.create("text")); binding.setSourceNullValue("-"); binding.setSourceUnreadableValue("<Error>"); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); add(lblTxtBuchungsblattcode, gridBagConstraints); btnRetrieve.setText(org.openide.util.NbBundle.getMessage(Alkis_buchungsblattRenderer.class, "Alkis_buchungsblattRenderer.btnRetrieve.text")); // NOI18N btnRetrieve.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnRetrieveActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.gridwidth = 2; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); add(btnRetrieve, gridBagConstraints); lblBuchungsblattcode.setText(org.openide.util.NbBundle.getMessage(Alkis_buchungsblattRenderer.class, "Alkis_buchungsblattRenderer.lblBuchungsblattcode.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); add(lblBuchungsblattcode, gridBagConstraints); lblTxtEigentuemerNachname.setText(org.openide.util.NbBundle.getMessage(Alkis_buchungsblattRenderer.class, "Alkis_buchungsblattRenderer.lblTxtEigentuemerNachname.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); add(lblTxtEigentuemerNachname, gridBagConstraints); lblTxtFlurstueckcode.setText(org.openide.util.NbBundle.getMessage(Alkis_buchungsblattRenderer.class, "Alkis_buchungsblattRenderer.lblTxtFlurstueckcode.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); add(lblTxtFlurstueckcode, gridBagConstraints); lblEigentuemernachname.setText(org.openide.util.NbBundle.getMessage(Alkis_buchungsblattRenderer.class, "Alkis_buchungsblattRenderer.lblEigentuemernachname.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); add(lblEigentuemernachname, gridBagConstraints); lblFlurstueckcode.setText(org.openide.util.NbBundle.getMessage(Alkis_buchungsblattRenderer.class, "Alkis_buchungsblattRenderer.lblFlurstueckcode.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); add(lblFlurstueckcode, gridBagConstraints); bindingGroup.bind(); }// </editor-fold>//GEN-END:initComponents private void btnRetrieveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRetrieveActionPerformed final CidsBean bean = cidsBean; if (bean != null) { final String buchungsblattCode = String.valueOf(bean.getProperty("buchungsblattcode")); if (buchungsblattCode != null) { CismetThreadPool.execute(new RetrieveWorker(buchungsblattCode)); } } }//GEN-LAST:event_btnRetrieveActionPerformed @Override public CidsBean getCidsBean() { return cidsBean; } @Override public void setCidsBean(CidsBean cb) { if (cb != null) { this.cidsBean = cb; bindingGroup.unbind(); bindingGroup.bind(); } } @Override public String getTitle() { return title; } @Override public void setTitle(String title) { this.title = title; } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnRetrieve; private javax.swing.JLabel lblBuchungsblattcode; private javax.swing.JLabel lblEigentuemernachname; private javax.swing.JLabel lblFlurstueckcode; private javax.swing.JLabel lblTxtBuchungsblattcode; private javax.swing.JLabel lblTxtEigentuemerNachname; private javax.swing.JLabel lblTxtFlurstueckcode; private javax.swing.JPanel panFooter; private javax.swing.JPanel panTitle; private org.jdesktop.beansbinding.BindingGroup bindingGroup; // End of variables declaration//GEN-END:variables @Override public JComponent getTitleComponent() { return panTitle; } @Override public JComponent getFooterComponent() { return panFooter; } final class RetrieveWorker extends SwingWorker<Buchungsblatt, Void> { public RetrieveWorker(String pointCode) { this.buchungsBlattCode = pointCode; timer = new Timer(250, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (waitStat.length() < 11) { waitStat += "."; } else { waitStat = "."; } for (final JLabel label : retrieveableLabels) { label.setText(waitStat); } } }); btnRetrieve.setVisible(false); timer.start(); } private final String buchungsBlattCode; private String waitStat = ""; private final Timer timer; @Override protected Buchungsblatt doInBackground() throws Exception { return infoService.getBuchungsblatt(soapProvider.getIdentityCard(), soapProvider.getService(), buchungsBlattCode); } private final void restoreOnException() { btnRetrieve.setVisible(true); for (JLabel label : retrieveableLabels) { label.setText("..."); } } @Override protected void done() { timer.stop(); try { final Buchungsblatt buchungsblatt = get(); if (buchungsblatt != null) { Alkis_buchungsblattRenderer.this.buchungsblatt = buchungsblatt; // Alkis_buchungsblattRenderer.this.bindingGroup.unbind(); // Alkis_buchungsblattRenderer.this.bindingGroup.bind(); //TODO this is quick and dirty for tesing only! lblTxtEigentuemerNachname.setText(buchungsblatt.getOwners()[0].getSurName()); // lblTxtModellart.setText(point.getModellArt()); // lblTxtDienststelle.setText(point.getZustaendigeStelleStelle()); // lblTxtLand.setText(point.getZustaendigeStelleLand()); // lblTxtBeginn.setText(point.getLebenszeitIntervallBeginnt()); // lblTxtEnde.setText(point.getLebenszeitIntervallEndet()); // lblTxtAnlass.setText(point.getAnlass()); // lblTxtBemerkungAbmarkung.setText(point.getBemerkungZurAbmarkungName()); } } catch (InterruptedException ex) { restoreOnException(); log.warn(ex, ex); } catch (Exception ex) { //TODO show error message to user? restoreOnException(); org.jdesktop.swingx.error.ErrorInfo ei = new ErrorInfo("Fehler beim Retrieve", ex.getMessage(), null, null, ex, Level.ALL, null); org.jdesktop.swingx.JXErrorPane.showDialog(StaticSwingTools.getParentFrame(Alkis_buchungsblattRenderer.this), ei); log.error(ex, ex); } } } }
true
true
private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; bindingGroup = new org.jdesktop.beansbinding.BindingGroup(); panTitle = new javax.swing.JPanel(); panFooter = new javax.swing.JPanel(); lblTxtBuchungsblattcode = new javax.swing.JLabel(); btnRetrieve = new javax.swing.JButton(); lblBuchungsblattcode = new javax.swing.JLabel(); lblTxtEigentuemerNachname = new javax.swing.JLabel(); lblTxtFlurstueckcode = new javax.swing.JLabel(); lblEigentuemernachname = new javax.swing.JLabel(); lblFlurstueckcode = new javax.swing.JLabel(); panTitle.setOpaque(false); javax.swing.GroupLayout panTitleLayout = new javax.swing.GroupLayout(panTitle); panTitle.setLayout(panTitleLayout); panTitleLayout.setHorizontalGroup( panTitleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 100, Short.MAX_VALUE) ); panTitleLayout.setVerticalGroup( panTitleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 100, Short.MAX_VALUE) ); panFooter.setOpaque(false); javax.swing.GroupLayout panFooterLayout = new javax.swing.GroupLayout(panFooter); panFooter.setLayout(panFooterLayout); panFooterLayout.setHorizontalGroup( panFooterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 100, Short.MAX_VALUE) ); panFooterLayout.setVerticalGroup( panFooterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 100, Short.MAX_VALUE) ); setLayout(new java.awt.GridBagLayout()); org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.pointcode}"), lblTxtBuchungsblattcode, org.jdesktop.beansbinding.BeanProperty.create("text")); binding.setSourceNullValue("-"); binding.setSourceUnreadableValue("<Error>"); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); add(lblTxtBuchungsblattcode, gridBagConstraints); btnRetrieve.setText(org.openide.util.NbBundle.getMessage(Alkis_buchungsblattRenderer.class, "Alkis_buchungsblattRenderer.btnRetrieve.text")); // NOI18N btnRetrieve.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnRetrieveActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.gridwidth = 2; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); add(btnRetrieve, gridBagConstraints); lblBuchungsblattcode.setText(org.openide.util.NbBundle.getMessage(Alkis_buchungsblattRenderer.class, "Alkis_buchungsblattRenderer.lblBuchungsblattcode.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); add(lblBuchungsblattcode, gridBagConstraints); lblTxtEigentuemerNachname.setText(org.openide.util.NbBundle.getMessage(Alkis_buchungsblattRenderer.class, "Alkis_buchungsblattRenderer.lblTxtEigentuemerNachname.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); add(lblTxtEigentuemerNachname, gridBagConstraints); lblTxtFlurstueckcode.setText(org.openide.util.NbBundle.getMessage(Alkis_buchungsblattRenderer.class, "Alkis_buchungsblattRenderer.lblTxtFlurstueckcode.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); add(lblTxtFlurstueckcode, gridBagConstraints); lblEigentuemernachname.setText(org.openide.util.NbBundle.getMessage(Alkis_buchungsblattRenderer.class, "Alkis_buchungsblattRenderer.lblEigentuemernachname.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); add(lblEigentuemernachname, gridBagConstraints); lblFlurstueckcode.setText(org.openide.util.NbBundle.getMessage(Alkis_buchungsblattRenderer.class, "Alkis_buchungsblattRenderer.lblFlurstueckcode.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); add(lblFlurstueckcode, gridBagConstraints); bindingGroup.bind(); }// </editor-fold>//GEN-END:initComponents
private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; bindingGroup = new org.jdesktop.beansbinding.BindingGroup(); panTitle = new javax.swing.JPanel(); panFooter = new javax.swing.JPanel(); lblTxtBuchungsblattcode = new javax.swing.JLabel(); btnRetrieve = new javax.swing.JButton(); lblBuchungsblattcode = new javax.swing.JLabel(); lblTxtEigentuemerNachname = new javax.swing.JLabel(); lblTxtFlurstueckcode = new javax.swing.JLabel(); lblEigentuemernachname = new javax.swing.JLabel(); lblFlurstueckcode = new javax.swing.JLabel(); panTitle.setOpaque(false); javax.swing.GroupLayout panTitleLayout = new javax.swing.GroupLayout(panTitle); panTitle.setLayout(panTitleLayout); panTitleLayout.setHorizontalGroup( panTitleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 100, Short.MAX_VALUE) ); panTitleLayout.setVerticalGroup( panTitleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 100, Short.MAX_VALUE) ); panFooter.setOpaque(false); javax.swing.GroupLayout panFooterLayout = new javax.swing.GroupLayout(panFooter); panFooter.setLayout(panFooterLayout); panFooterLayout.setHorizontalGroup( panFooterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 100, Short.MAX_VALUE) ); panFooterLayout.setVerticalGroup( panFooterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 100, Short.MAX_VALUE) ); setLayout(new java.awt.GridBagLayout()); org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.buchungsblattcode}"), lblTxtBuchungsblattcode, org.jdesktop.beansbinding.BeanProperty.create("text")); binding.setSourceNullValue("-"); binding.setSourceUnreadableValue("<Error>"); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); add(lblTxtBuchungsblattcode, gridBagConstraints); btnRetrieve.setText(org.openide.util.NbBundle.getMessage(Alkis_buchungsblattRenderer.class, "Alkis_buchungsblattRenderer.btnRetrieve.text")); // NOI18N btnRetrieve.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnRetrieveActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.gridwidth = 2; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); add(btnRetrieve, gridBagConstraints); lblBuchungsblattcode.setText(org.openide.util.NbBundle.getMessage(Alkis_buchungsblattRenderer.class, "Alkis_buchungsblattRenderer.lblBuchungsblattcode.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); add(lblBuchungsblattcode, gridBagConstraints); lblTxtEigentuemerNachname.setText(org.openide.util.NbBundle.getMessage(Alkis_buchungsblattRenderer.class, "Alkis_buchungsblattRenderer.lblTxtEigentuemerNachname.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); add(lblTxtEigentuemerNachname, gridBagConstraints); lblTxtFlurstueckcode.setText(org.openide.util.NbBundle.getMessage(Alkis_buchungsblattRenderer.class, "Alkis_buchungsblattRenderer.lblTxtFlurstueckcode.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); add(lblTxtFlurstueckcode, gridBagConstraints); lblEigentuemernachname.setText(org.openide.util.NbBundle.getMessage(Alkis_buchungsblattRenderer.class, "Alkis_buchungsblattRenderer.lblEigentuemernachname.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); add(lblEigentuemernachname, gridBagConstraints); lblFlurstueckcode.setText(org.openide.util.NbBundle.getMessage(Alkis_buchungsblattRenderer.class, "Alkis_buchungsblattRenderer.lblFlurstueckcode.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); add(lblFlurstueckcode, gridBagConstraints); bindingGroup.bind(); }// </editor-fold>//GEN-END:initComponents
diff --git a/android/src/net/noraisin/android_aurena/AndroidAurena.java b/android/src/net/noraisin/android_aurena/AndroidAurena.java index 2da86a2..aa80527 100644 --- a/android/src/net/noraisin/android_aurena/AndroidAurena.java +++ b/android/src/net/noraisin/android_aurena/AndroidAurena.java @@ -1,238 +1,238 @@ package net.noraisin.android_aurena; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; import com.gstreamer.GStreamer; import android.app.Activity; import android.content.Context; import android.util.Log; import android.os.Bundle; import android.os.Environment; import android.os.PowerManager; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageButton; import android.widget.TextView; import android.widget.Toast; import android.net.nsd.NsdServiceInfo; import android.net.nsd.NsdManager; public class AndroidAurena extends Activity implements SurfaceHolder.Callback { private static native boolean classInit(); private native void nativeInit(); private native void nativeFinalize(); private native void nativePlay(String server); private native void nativePause(); private native void nativeSurfaceInit(Object surface); private native void nativeSurfaceFinalize(); private long native_custom_data; private int position; private int duration; private PowerManager.WakeLock wake_lock; /* mDNS members */ NsdManager mNsdManager; NsdManager.ResolveListener mResolveListener; NsdManager.DiscoveryListener mDiscoveryListener; NsdServiceInfo mService; private static final String SERVICE_TYPE = "_aurena._tcp."; private static final String TAG = "GStreamer"; /* Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mNsdManager = (NsdManager) getSystemService(Context.NSD_SERVICE); initializeDiscoveryListener(); initializeResolveListener(); try { GStreamer.init(this); } catch (Exception e) { Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show(); finish(); return; } setContentView(R.layout.main); PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); wake_lock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "Android Aurena"); wake_lock.setReferenceCounted(false); SurfaceView sv = (SurfaceView) this.findViewById(R.id.surface_video); SurfaceHolder sh = sv.getHolder(); sh.addCallback(this); nativeInit(); wake_lock.acquire(); } protected void onDestroy() { nativeFinalize(); if (wake_lock.isHeld()) wake_lock.release(); super.onDestroy(); } /* Called from native code */ private void setMessage(final String message) { final TextView tv = (TextView) this.findViewById(R.id.textview_message); runOnUiThread (new Runnable() { public void run() { /* Disable until we have got rid of non-fatal errors */ /*tv.setText(message);*/ } }); } /* Called from native code */ private void onGStreamerInitialized () { mNsdManager.discoverServices( SERVICE_TYPE, NsdManager.PROTOCOL_DNS_SD, mDiscoveryListener); } /* The text widget acts as an slave for the seek bar, so it reflects what the seek bar shows, whether * it is an actual pipeline position or the position the user is currently dragging to. */ private void updateTimeWidget () { final TextView tv = (TextView) this.findViewById(R.id.textview_time); SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss"); df.setTimeZone(TimeZone.getTimeZone("UTC")); final String message = df.format(new Date (position)) + " / " + df.format(new Date (duration)); tv.setText(message); } /* Called from native code */ private void setCurrentPosition(final int position, final int duration) { this.position = position; this.duration = duration; runOnUiThread (new Runnable() { public void run() { updateTimeWidget(); } }); } /* Called from native code */ private void setCurrentState (int state) { Log.d (TAG, "State has changed to " + state); switch (state) { case 1: setMessage ("NULL"); break; case 2: setMessage ("READY"); break; case 3: setMessage ("PAUSED"); break; case 4: setMessage ("PLAYING"); break; } } static { System.loadLibrary("gstreamer_android"); System.loadLibrary("android-aurena"); classInit(); } public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { Log.d(TAG, "Surface changed to format " + format + " width " + width + " height " + height); nativeSurfaceInit (holder.getSurface()); } public void surfaceCreated(SurfaceHolder holder) { Log.d(TAG, "Surface created: " + holder.getSurface()); } public void surfaceDestroyed(SurfaceHolder holder) { Log.d(TAG, "Surface destroyed"); nativeSurfaceFinalize (); } // mDNS Discovery public void initializeDiscoveryListener() { mDiscoveryListener = new NsdManager.DiscoveryListener() { @Override public void onDiscoveryStarted(String regType) { Log.d(TAG, "Service discovery started"); } @Override public void onServiceFound(NsdServiceInfo service) { Log.d(TAG, "Service discovery success" + service); if (!service.getServiceType().equals(SERVICE_TYPE)) { Log.d(TAG, "Unknown Service Type: " + service.getServiceType()); } else { mNsdManager.resolveService(service, mResolveListener); } } @Override public void onServiceLost(NsdServiceInfo service) { Log.e(TAG, "service lost" + service); if (mService == service) { mService = null; } } @Override public void onDiscoveryStopped(String serviceType) { Log.i(TAG, "Discovery stopped: " + serviceType); } @Override public void onStartDiscoveryFailed(String serviceType, int errorCode) { Log.e(TAG, "Discovery failed: Error code:" + errorCode); - mNsdManager.stopServiceDiscovery(this); + // mNsdManager.stopServiceDiscovery(this); } @Override public void onStopDiscoveryFailed(String serviceType, int errorCode) { Log.e(TAG, "Discovery failed: Error code:" + errorCode); mNsdManager.stopServiceDiscovery(this); } }; } public void initializeResolveListener() { mResolveListener = new NsdManager.ResolveListener() { @Override public void onResolveFailed(NsdServiceInfo serviceInfo, int errorCode) { Log.e(TAG, "Resolve failed" + errorCode); } @Override public void onServiceResolved(NsdServiceInfo serviceInfo) { Log.e(TAG, "Resolve Succeeded. " + serviceInfo); mService = serviceInfo; String server = mService.getHost().getHostAddress() + ":" + mService.getPort(); Log.d(TAG, "Connecting to server: " + server); nativePause (); nativePlay (server); } }; } }
true
true
public void initializeDiscoveryListener() { mDiscoveryListener = new NsdManager.DiscoveryListener() { @Override public void onDiscoveryStarted(String regType) { Log.d(TAG, "Service discovery started"); } @Override public void onServiceFound(NsdServiceInfo service) { Log.d(TAG, "Service discovery success" + service); if (!service.getServiceType().equals(SERVICE_TYPE)) { Log.d(TAG, "Unknown Service Type: " + service.getServiceType()); } else { mNsdManager.resolveService(service, mResolveListener); } } @Override public void onServiceLost(NsdServiceInfo service) { Log.e(TAG, "service lost" + service); if (mService == service) { mService = null; } } @Override public void onDiscoveryStopped(String serviceType) { Log.i(TAG, "Discovery stopped: " + serviceType); } @Override public void onStartDiscoveryFailed(String serviceType, int errorCode) { Log.e(TAG, "Discovery failed: Error code:" + errorCode); mNsdManager.stopServiceDiscovery(this); } @Override public void onStopDiscoveryFailed(String serviceType, int errorCode) { Log.e(TAG, "Discovery failed: Error code:" + errorCode); mNsdManager.stopServiceDiscovery(this); } }; }
public void initializeDiscoveryListener() { mDiscoveryListener = new NsdManager.DiscoveryListener() { @Override public void onDiscoveryStarted(String regType) { Log.d(TAG, "Service discovery started"); } @Override public void onServiceFound(NsdServiceInfo service) { Log.d(TAG, "Service discovery success" + service); if (!service.getServiceType().equals(SERVICE_TYPE)) { Log.d(TAG, "Unknown Service Type: " + service.getServiceType()); } else { mNsdManager.resolveService(service, mResolveListener); } } @Override public void onServiceLost(NsdServiceInfo service) { Log.e(TAG, "service lost" + service); if (mService == service) { mService = null; } } @Override public void onDiscoveryStopped(String serviceType) { Log.i(TAG, "Discovery stopped: " + serviceType); } @Override public void onStartDiscoveryFailed(String serviceType, int errorCode) { Log.e(TAG, "Discovery failed: Error code:" + errorCode); // mNsdManager.stopServiceDiscovery(this); } @Override public void onStopDiscoveryFailed(String serviceType, int errorCode) { Log.e(TAG, "Discovery failed: Error code:" + errorCode); mNsdManager.stopServiceDiscovery(this); } }; }
diff --git a/src/com/ichi2/anki/Statistics.java b/src/com/ichi2/anki/Statistics.java index b8416674..43b71d0f 100644 --- a/src/com/ichi2/anki/Statistics.java +++ b/src/com/ichi2/anki/Statistics.java @@ -1,248 +1,248 @@ /***************************************************************************************** * Copyright (c) 2011 Norbert Nagold <norbert.nagold@gmail. * * * * This program is free software; you can redistribute it and/or modify it under * * the terms of the GNU General Public License as published by the Free Software * * Foundation; either version 3 of the License, or (at your option) any later * * version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along with * * this program. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************************/ package com.ichi2.anki; import android.content.Context; import android.content.res.Resources; public class Statistics { public static String[] axisLabels = { "", "" }; public static String sTitle; public static String[] Titles; public static double[] xAxisData; public static double[][] sSeriesList; private static Deck sDeck; public static int sType; /** * Types */ public static final int TYPE_DUE = 0; public static final int TYPE_CUMULATIVE_DUE = 1; public static final int TYPE_INTERVALS = 2; public static final int TYPE_REVIEWS = 3; public static final int TYPE_REVIEWING_TIME = 4; public static void initVariables(Context context, int type, int period, String title) { Resources res = context.getResources(); sType = type; sTitle = title; axisLabels[0] = res.getString(R.string.statistics_period_x_axis); axisLabels[1] = res.getString(R.string.statistics_period_y_axis); if (type <= TYPE_CUMULATIVE_DUE) { Titles = new String[3]; Titles[0] = res.getString(R.string.statistics_young_cards); Titles[1] = res.getString(R.string.statistics_mature_cards); Titles[2] = res.getString(R.string.statistics_failed_cards); sSeriesList = new double[3][period]; xAxisData = xAxisData(period, false); } else if (type == TYPE_REVIEWS) { Titles = new String[3]; Titles[0] = res.getString(R.string.statistics_new_cards); Titles[1] = res.getString(R.string.statistics_young_cards); Titles[2] = res.getString(R.string.statistics_mature_cards); sSeriesList = new double[3][period]; xAxisData = xAxisData(period, true); } else { Titles = new String[1]; sSeriesList = new double[1][period]; switch (type) { case TYPE_INTERVALS: xAxisData = xAxisData(period, false); break; case TYPE_REVIEWING_TIME: xAxisData = xAxisData(period, true); axisLabels[1] = context.getResources().getString(R.string.statistics_period_x_axis_minutes); break; } } } public static boolean refreshDeckStatistics(Context context, Deck deck, int type, int period, String title) { initVariables(context, type, period, title); sDeck = deck; sSeriesList = getSeriesList(context, type, period); if (sSeriesList != null) { return true; } else { return false; } } public static boolean refreshAllDeckStatistics(Context context, String[] deckPaths, int type, int period, String title) { initVariables(context, type, period, title); for (String dp : deckPaths) { double[][] seriesList; sDeck = Deck.openDeck(dp); seriesList = getSeriesList(context, type, period); sDeck.closeDeck(false); for (int i = 0; i < sSeriesList.length; i++) { for (int j = 0; j < period; j++) { sSeriesList[i][j] += seriesList[i][j]; } } } if (sSeriesList != null) { return true; } else { return false; } } public static double[][] getSeriesList(Context context, int type, int period) { double[][] seriesList; AnkiDb ankiDB = AnkiDatabaseManager.getDatabase(sDeck.getDeckPath()); ankiDB.getDatabase().beginTransaction(); try { switch (type) { case TYPE_DUE: seriesList = new double[3][period]; seriesList[0] = getCardsByDue(period, false); seriesList[1] = getMatureCardsByDue(period, false); seriesList[2] = getFailedCardsByDue(period, false); - seriesList[0][0] += seriesList[2][0]; seriesList[0][1] += seriesList[2][1]; seriesList[1][0] += seriesList[2][0]; seriesList[1][1] += seriesList[2][1]; break; case TYPE_CUMULATIVE_DUE: seriesList = new double[3][period]; seriesList[0] = getCardsByDue(period, true); seriesList[1] = getMatureCardsByDue(period, true); seriesList[2] = getFailedCardsByDue(period, true); - for (int i = 0; i < period; i++) { + seriesList[1][0] += seriesList[2][0]; + for (int i = 1; i < period; i++) { seriesList[0][i] += seriesList[2][i]; seriesList[1][i] += seriesList[2][i]; } break; case TYPE_INTERVALS: seriesList = new double[1][period]; seriesList[0] = getCardsByInterval(period); break; case TYPE_REVIEWS: seriesList = getReviews(period); break; case TYPE_REVIEWING_TIME: seriesList = new double[1][period]; seriesList[0] = getReviewTime(period); break; default: seriesList = null; } ankiDB.getDatabase().setTransactionSuccessful(); } finally { ankiDB.getDatabase().endTransaction(); } return seriesList; } public static double[] xAxisData(int length, boolean backwards) { double series[] = new double[length]; if (backwards) { for (int i = 0; i < length; i++) { series[i] = i - length + 1; } } else { for (int i = 0; i < length; i++) { series[i] = i; } } return series; } public static double[] getCardsByDue(int length, boolean cumulative) { double series[] = new double[length]; series[0] = sDeck.getDueCount(); for (int i = 1; i < length; i++) { int count = 0; count = sDeck.getNextDueCards(i); if (cumulative) { series[i] = count + series[i - 1]; } else { series[i] = count; } } return series; } public static double[] getMatureCardsByDue(int length, boolean cumulative) { double series[] = new double[length]; for (int i = 0; i < length; i++) { int count = 0; count = sDeck.getNextDueMatureCards(i); if (cumulative && i > 0) { series[i] = count + series[i - 1]; } else { series[i] = count; } } return series; } public static double[] getFailedCardsByDue(int length, boolean cumulative) { double series[] = new double[length]; series[0] = sDeck.getFailedSoonCount(); series[1] = sDeck.getFailedDelayedCount(); if (cumulative) { series[1] += series[0]; for (int i = 2; i < length; i++) { series[i] = series[1]; } } return series; } public static double[][] getReviews(int length) { double series[][] = new double[3][length]; for (int i = 0; i < length; i++) { int result[] = sDeck.getDaysReviewed(i - length + 1); series[0][i] = result[0]; series[1][i] = result[1]; series[2][i] = result[2]; } return series; } public static double[] getReviewTime(int length) { double series[] = new double[length]; for (int i = 0; i < length; i++) { series[i] = sDeck.getReviewTime(i - length + 1) / 60; } return series; } public static double[] getCardsByInterval(int length) { double series[] = new double[length]; for (int i = 0; i < length; i++) { series[i] = sDeck.getCardsByInterval(i); } return series; } }
false
true
public static double[][] getSeriesList(Context context, int type, int period) { double[][] seriesList; AnkiDb ankiDB = AnkiDatabaseManager.getDatabase(sDeck.getDeckPath()); ankiDB.getDatabase().beginTransaction(); try { switch (type) { case TYPE_DUE: seriesList = new double[3][period]; seriesList[0] = getCardsByDue(period, false); seriesList[1] = getMatureCardsByDue(period, false); seriesList[2] = getFailedCardsByDue(period, false); seriesList[0][0] += seriesList[2][0]; seriesList[0][1] += seriesList[2][1]; seriesList[1][0] += seriesList[2][0]; seriesList[1][1] += seriesList[2][1]; break; case TYPE_CUMULATIVE_DUE: seriesList = new double[3][period]; seriesList[0] = getCardsByDue(period, true); seriesList[1] = getMatureCardsByDue(period, true); seriesList[2] = getFailedCardsByDue(period, true); for (int i = 0; i < period; i++) { seriesList[0][i] += seriesList[2][i]; seriesList[1][i] += seriesList[2][i]; } break; case TYPE_INTERVALS: seriesList = new double[1][period]; seriesList[0] = getCardsByInterval(period); break; case TYPE_REVIEWS: seriesList = getReviews(period); break; case TYPE_REVIEWING_TIME: seriesList = new double[1][period]; seriesList[0] = getReviewTime(period); break; default: seriesList = null; } ankiDB.getDatabase().setTransactionSuccessful(); } finally { ankiDB.getDatabase().endTransaction(); } return seriesList; }
public static double[][] getSeriesList(Context context, int type, int period) { double[][] seriesList; AnkiDb ankiDB = AnkiDatabaseManager.getDatabase(sDeck.getDeckPath()); ankiDB.getDatabase().beginTransaction(); try { switch (type) { case TYPE_DUE: seriesList = new double[3][period]; seriesList[0] = getCardsByDue(period, false); seriesList[1] = getMatureCardsByDue(period, false); seriesList[2] = getFailedCardsByDue(period, false); seriesList[0][1] += seriesList[2][1]; seriesList[1][0] += seriesList[2][0]; seriesList[1][1] += seriesList[2][1]; break; case TYPE_CUMULATIVE_DUE: seriesList = new double[3][period]; seriesList[0] = getCardsByDue(period, true); seriesList[1] = getMatureCardsByDue(period, true); seriesList[2] = getFailedCardsByDue(period, true); seriesList[1][0] += seriesList[2][0]; for (int i = 1; i < period; i++) { seriesList[0][i] += seriesList[2][i]; seriesList[1][i] += seriesList[2][i]; } break; case TYPE_INTERVALS: seriesList = new double[1][period]; seriesList[0] = getCardsByInterval(period); break; case TYPE_REVIEWS: seriesList = getReviews(period); break; case TYPE_REVIEWING_TIME: seriesList = new double[1][period]; seriesList[0] = getReviewTime(period); break; default: seriesList = null; } ankiDB.getDatabase().setTransactionSuccessful(); } finally { ankiDB.getDatabase().endTransaction(); } return seriesList; }
diff --git a/flexodesktop/model/flexoutils/src/main/java/org/openflexo/toolbox/ResourceLocator.java b/flexodesktop/model/flexoutils/src/main/java/org/openflexo/toolbox/ResourceLocator.java index 60e46c1b7..d8ebbff22 100644 --- a/flexodesktop/model/flexoutils/src/main/java/org/openflexo/toolbox/ResourceLocator.java +++ b/flexodesktop/model/flexoutils/src/main/java/org/openflexo/toolbox/ResourceLocator.java @@ -1,228 +1,228 @@ /* * (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.toolbox; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.util.Enumeration; import java.util.List; import java.util.Vector; import java.util.logging.Level; import java.util.logging.Logger; /** * @author bmangez * * <B>Class Description</B> */ public class ResourceLocator { private static final Logger logger = Logger.getLogger(ResourceLocator.class.getPackage().getName()); static File locateFile(String relativePathName) { File locateFile = locateFile(relativePathName, false); if (locateFile != null && locateFile.exists()) { return locateFile; } return locateFile(relativePathName, true); } static File locateFile(String relativePathName, boolean lenient) { // logger.info("locateFile: "+relativePathName); for (Enumeration<File> e = getDirectoriesSearchOrder().elements(); e.hasMoreElements();) { File nextTry = new File(e.nextElement(), relativePathName); if (nextTry.exists()) { if (logger.isLoggable(Level.FINER)) { logger.finer("Found " + nextTry.getAbsolutePath()); } try { if (nextTry.getCanonicalFile().getName().equals(nextTry.getName()) || lenient) { return nextTry; } } catch (IOException e1) { } } else { if (logger.isLoggable(Level.FINER)) { logger.finer("Searched for a " + nextTry.getAbsolutePath()); } } } if (logger.isLoggable(Level.WARNING)) { logger.warning("Could not locate resource " + relativePathName); } return new File(userDirectory, relativePathName); } static String retrieveRelativePath(FileResource fileResource) { for (Enumeration<File> e = getDirectoriesSearchOrder().elements(); e.hasMoreElements();) { File f = e.nextElement(); if (fileResource.getAbsolutePath().startsWith(f.getAbsolutePath())) { return fileResource.getAbsolutePath().substring(f.getAbsolutePath().length() + 1).replace('\\', '/'); } } if (fileResource.getAbsolutePath().startsWith(userDirectory.getAbsolutePath())) { return fileResource.getAbsolutePath().substring(userDirectory.getAbsolutePath().length() + 1).replace('\\', '/'); } if (logger.isLoggable(Level.SEVERE)) { logger.severe("File resource cannot be found: " + fileResource.getAbsolutePath()); } return null; } public static String cleanPath(String relativePathName) { try { return locateFile(relativePathName).getCanonicalPath(); } catch (IOException e) { return locateFile(relativePathName).getAbsolutePath(); } // return cleanAbsolutePath(dirtyPath); } private static Vector<File> directoriesSearchOrder = null; private static File preferredResourcePath; private static File userDirectory = null; private static File userHomeDirectory = null; public static File getPreferredResourcePath() { return preferredResourcePath; } public static void resetFlexoResourceLocation(File newLocation) { preferredResourcePath = newLocation; directoriesSearchOrder = null; } public static void printDirectoriesSearchOrder(PrintStream out) { out.println("Directories search order is:"); for (File file : getDirectoriesSearchOrder()) { out.println(file.getAbsolutePath()); } } public static void init() { getDirectoriesSearchOrder(); } public static void addProjectDirectory(File projectDirectory) { init(); if (projectDirectory.exists()) { addProjectResourceDirs(directoriesSearchOrder, projectDirectory); } } private static Vector<File> getDirectoriesSearchOrder() { if (directoriesSearchOrder == null) { synchronized (ResourceLocator.class) { if (directoriesSearchOrder == null) { if (logger.isLoggable(Level.INFO)) { logger.info("Initializing directories search order"); } directoriesSearchOrder = new Vector<File>(); if (preferredResourcePath != null) { if (logger.isLoggable(Level.INFO)) { logger.info("Adding directory " + preferredResourcePath.getAbsolutePath()); } directoriesSearchOrder.add(preferredResourcePath); } File workingDirectory = new File(System.getProperty("user.dir")); File flexoDesktopDirectory = findProjectDirectoryWithName(workingDirectory, "flexodesktop"); if (flexoDesktopDirectory != null) { findAllFlexoProjects(flexoDesktopDirectory, directoriesSearchOrder); - } - File technologyadaptersintegrationDirectory = new File(flexoDesktopDirectory.getParentFile(), - "packaging/technologyadaptersintegration"); - if (technologyadaptersintegrationDirectory != null) { - findAllFlexoProjects(technologyadaptersintegrationDirectory, directoriesSearchOrder); + File technologyadaptersintegrationDirectory = new File(flexoDesktopDirectory.getParentFile(), + "packaging/technologyadaptersintegration"); + if (technologyadaptersintegrationDirectory != null) { + findAllFlexoProjects(technologyadaptersintegrationDirectory, directoriesSearchOrder); + } } directoriesSearchOrder.add(workingDirectory); } } } return directoriesSearchOrder; } public static File findProjectDirectoryWithName(File currentDir, String projectName) { if (currentDir != null) { File attempt = new File(currentDir, projectName); if (attempt.exists()) { return attempt; } else { return findProjectDirectoryWithName(currentDir.getParentFile(), projectName); } } return null; } public static void findAllFlexoProjects(File dir, List<File> files) { if (new File(dir, "pom.xml").exists()) { files.add(dir); for (File f : dir.listFiles()) { if (f.getName().startsWith("flexo") || f.getName().equals("technologyadaptersintegration")) { addProjectResourceDirs(files, f); } else if (f.isDirectory()) { findAllFlexoProjects(f, files); } } } } public static void addProjectResourceDirs(List<File> files, File f) { File file1 = new File(f.getAbsolutePath() + "/src/main/resources"); File file2 = new File(f.getAbsolutePath() + "/src/test/resources"); File file3 = new File(f.getAbsolutePath() + "/src/dev/resources"); // File file4 = new File(f.getAbsolutePath()); if (logger.isLoggable(Level.FINE)) { logger.info("Adding directory " + file1.getAbsolutePath()); } if (logger.isLoggable(Level.FINE)) { logger.fine("Adding directory " + file2.getAbsolutePath()); } if (logger.isLoggable(Level.FINE)) { logger.fine("Adding directory " + file3.getAbsolutePath()); } /*if (logger.isLoggable(Level.FINE)) { logger.fine("Adding directory " + file4.getAbsolutePath()); }*/ if (file1.exists()) { files.add(file1); } if (file2.exists()) { files.add(file2); } if (file3.exists()) { files.add(file3); } /*if (file4.exists()) { files.add(file4); }*/ } public static File getUserDirectory() { return userDirectory; } public static File getUserHomeDirectory() { return userHomeDirectory; } }
true
true
private static Vector<File> getDirectoriesSearchOrder() { if (directoriesSearchOrder == null) { synchronized (ResourceLocator.class) { if (directoriesSearchOrder == null) { if (logger.isLoggable(Level.INFO)) { logger.info("Initializing directories search order"); } directoriesSearchOrder = new Vector<File>(); if (preferredResourcePath != null) { if (logger.isLoggable(Level.INFO)) { logger.info("Adding directory " + preferredResourcePath.getAbsolutePath()); } directoriesSearchOrder.add(preferredResourcePath); } File workingDirectory = new File(System.getProperty("user.dir")); File flexoDesktopDirectory = findProjectDirectoryWithName(workingDirectory, "flexodesktop"); if (flexoDesktopDirectory != null) { findAllFlexoProjects(flexoDesktopDirectory, directoriesSearchOrder); } File technologyadaptersintegrationDirectory = new File(flexoDesktopDirectory.getParentFile(), "packaging/technologyadaptersintegration"); if (technologyadaptersintegrationDirectory != null) { findAllFlexoProjects(technologyadaptersintegrationDirectory, directoriesSearchOrder); } directoriesSearchOrder.add(workingDirectory); } } } return directoriesSearchOrder; }
private static Vector<File> getDirectoriesSearchOrder() { if (directoriesSearchOrder == null) { synchronized (ResourceLocator.class) { if (directoriesSearchOrder == null) { if (logger.isLoggable(Level.INFO)) { logger.info("Initializing directories search order"); } directoriesSearchOrder = new Vector<File>(); if (preferredResourcePath != null) { if (logger.isLoggable(Level.INFO)) { logger.info("Adding directory " + preferredResourcePath.getAbsolutePath()); } directoriesSearchOrder.add(preferredResourcePath); } File workingDirectory = new File(System.getProperty("user.dir")); File flexoDesktopDirectory = findProjectDirectoryWithName(workingDirectory, "flexodesktop"); if (flexoDesktopDirectory != null) { findAllFlexoProjects(flexoDesktopDirectory, directoriesSearchOrder); File technologyadaptersintegrationDirectory = new File(flexoDesktopDirectory.getParentFile(), "packaging/technologyadaptersintegration"); if (technologyadaptersintegrationDirectory != null) { findAllFlexoProjects(technologyadaptersintegrationDirectory, directoriesSearchOrder); } } directoriesSearchOrder.add(workingDirectory); } } } return directoriesSearchOrder; }
diff --git a/projects/framework/test-contract/src/org/identityconnectors/contract/data/macro/Expression.java b/projects/framework/test-contract/src/org/identityconnectors/contract/data/macro/Expression.java index 15aeaf2e..32e281bf 100644 --- a/projects/framework/test-contract/src/org/identityconnectors/contract/data/macro/Expression.java +++ b/projects/framework/test-contract/src/org/identityconnectors/contract/data/macro/Expression.java @@ -1,347 +1,346 @@ /* * Copyright 2008 Sun Microsystems, Inc. All rights reserved. * * U.S. Government Rights - Commercial software. Government users * are subject to the Sun Microsystems, Inc. standard license agreement * and applicable provisions of the FAR and its supplements. * * Use is subject to license terms. * * This distribution may include materials developed by third parties. * Sun, Sun Microsystems, the Sun logo, Java and Project Identity * Connectors are trademarks or registered trademarks of Sun * Microsystems, Inc. or its subsidiaries in the U.S. and other * countries. * * UNIX is a registered trademark in the U.S. and other countries, * exclusively licensed through X/Open Company, Ltd. * * ----------- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 2008 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of the Common Development * and Distribution License(CDDL) (the License). You may not use this file * except in compliance with the License. * * You can obtain a copy of the License at * http://identityconnectors.dev.java.net/CDDLv1.0.html * See the License for the specific language governing permissions and * limitations under the License. * * When distributing the Covered Code, include this CDDL Header Notice in each * file and include the License file at identityconnectors/legal/license.txt. * If applicable, add the following below this CDDL Header, with the fields * enclosed by brackets [] replaced by your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * ----------- */ package org.identityconnectors.contract.data.macro; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.ConcurrentMap; import org.identityconnectors.common.logging.Log; import junit.framework.Assert; /** * Expression is made of of: * <ol> * <li>a macro</li> * <li>a string</li> * <li>a combination of strings and macros that return strings (MUST return string though). * this is really just a special case of a string</li> * </ol> * <p>Example of Expression: * <ul><li>${RANDOM, A}</li> * <li>${INTEGER, ${RANDOM, ##}}</li> * <li>${FLOAT, ${RANDOM, #####}${LITERAL, .}${RANDOM, ##}}</li> </ul></p> * * @author Dan Vernon */ public class Expression { private static final Log LOG = Log.getLog(Expression.class); /** * Encapsulates a position counter used for parsing * expressions. */ class ExpressionContext { private int _currentPosition; ExpressionContext (int currentPosition) { setCurrentPosition(currentPosition); } public void setCurrentPosition(int currentPosition) { _currentPosition = currentPosition; } public int getCurrentPosition() { return _currentPosition; } } String _expressionString = null; private ConcurrentMap<String, Macro> _macroRegistry = null; /** * constructor * * @param macroRegistry * @param expressionString */ public Expression(ConcurrentMap<String, Macro> macroRegistry, String expressionString) { _macroRegistry = macroRegistry; _expressionString = expressionString; } /** * Expression {@link String} which came as a constructor parameter * @return */ public String getExpressionString() { return _expressionString; } /** * Resolve the Expression to value using {@link Macro}s * * @return {@link Object} value */ public Object resolveExpression() { // expression is made of of: // 1. a macro // 2. a string // 3. a combination of strings and macros that return strings (MUST return string though). // this is really just a special case of a string ExpressionContext context = new ExpressionContext(0); Object expressionReturn = null; // handle empty strings if (_expressionString.length()==0) { expressionReturn = _expressionString; } for(int i=context.getCurrentPosition();i<_expressionString.length();i++) { char ch = _expressionString.charAt(i); if (ch == '$' && i + 1 < _expressionString.length() && _expressionString.charAt(i + 1) == '{') { int macroStart = i; i++; int closingBrace = findClosingBrace(_expressionString, i); Assert.assertFalse("Improperly formatted expression: No closing brace found for expression", (i == -1)); // get the macro String macroString = _expressionString.substring(macroStart, closingBrace + 1); context.setCurrentPosition(macroStart); Object obj = processMacro(context, macroString); if (expressionReturn == null) { expressionReturn = obj; } else { expressionReturn = concatenate(expressionReturn, obj); } i += context.getCurrentPosition(); } else { String processedString = processString(context, _expressionString.substring(i)); if(expressionReturn == null) { expressionReturn = processedString; } else { // fixes the case that you have expression "${MACRO, args} ", where // MACRO is macro that doesn't return String // this could typically happen at the end of line if (expressionReturn instanceof String || processedString.trim().length()>0) { expressionReturn = concatenate(expressionReturn, processedString); } } i += context.getCurrentPosition(); } } return expressionReturn; } /** * Concat two String objects * * @param string1 * @param string2 * @return */ private String concatenate(Object string1, Object string2) { String concatenatedStrings = null; // we can only append them if they are both strings Assert.assertTrue("Cannot concatenate " + string1 + " and " + string2, ( (string1 instanceof String) && (string2 instanceof String) ) ); concatenatedStrings = (String)string1 + (String)string2; return concatenatedStrings; } /** * Helper function for finding closing brace * * @param expressionText * @param i * @return */ private int findClosingBrace(String expressionText, int i) { int braceLevel = 0; for(int index=i;index<expressionText.length();index++) { char ch = expressionText.charAt(index); switch(ch) { case '{': braceLevel++; break; case '}': braceLevel--; if(braceLevel == 0) { return index; } break; } } return -1; } /** * Processes the Expression string. Some escaping could be done here, but currently is not. * * @param context * @param patternSubstring * @return */ private String processString(ExpressionContext context, String patternSubstring) { int index = 0; StringBuffer foundString = new StringBuffer(); for(index=0;index<patternSubstring.length();index++) { char ch = patternSubstring.charAt(index); foundString.append(ch); } context.setCurrentPosition(index); return foundString.toString(); } /** * Processes the text using Macro * * @param context * @param macroText * @return */ private Object processMacro(ExpressionContext context, String macroText) { int index = 0; int embeddedMacroLevel = 0; List<String> parametersStrings = new ArrayList<String>(); // make sure it's a valid macro Assert.assertTrue("Macro text not properly formated ${<macro} for " + macroText, (macroText.startsWith("${")) && (macroText.endsWith("}")) ); // TODO Could this be cleaner? // strip off ${ and } macroText = macroText.substring(2, macroText.length() - 1); // handle special case - LITERAL macro if (macroText.startsWith(LiteralMacro.MACRO_NAME)) { context.setCurrentPosition(macroText.length() + 1); return macroText.substring(macroText.indexOf(',') + 1).trim(); } StringBuffer foundParameter = new StringBuffer(); // find the parameters by splitting on ',' // treat everything between '${' and '}' as // a single entity. for(index=0;index<macroText.length();index++) { char ch = macroText.charAt(index); switch(ch) { case '$': foundParameter.append(ch); // next character must be either a '$' // or a '{' or it's an error index++; Assert.assertTrue(index < macroText.length()); ch = macroText.charAt(index); foundParameter.append(ch); if(ch == '{') { embeddedMacroLevel++; } break; case '}': if(embeddedMacroLevel > 0) { embeddedMacroLevel--; } foundParameter.append(ch); break; case ',': if(embeddedMacroLevel == 0) { parametersStrings.add(foundParameter.toString().trim()); foundParameter = new StringBuffer(); } else { foundParameter.append(ch); } break; default: foundParameter.append(ch); break; } } // add the last one in ... there may not be one in certain // cases, so check length first String lastParameter = foundParameter.toString().trim(); if(lastParameter.length() > 0) { parametersStrings.add(lastParameter); } List<Object> resolvedParameters = new ArrayList<Object>(); for(String parameterString : parametersStrings) { Expression expression = new Expression(_macroRegistry, parameterString); resolvedParameters.add(expression.resolveExpression()); } // the resolved first parameter MUST be a string that represents // the macro name. String macroName = (String)resolvedParameters.get(0); Assert.assertNotNull("Macro name not found", macroName); // check if exist alias for macro Object[] alias = MacroAliases.ALIASES.get(macroName); if (alias != null) { Assert.assertTrue("Wrong macro alias definition - it must contain at least alias name.", alias.length > 0); // update macro name macroName = (String) alias[0]; // also remove macro name from parameters and add there new one + // alias parameters resolvedParameters.remove(0); resolvedParameters.addAll(0, Arrays.asList(alias)); - LOG.info("Macro alias ''{0}'' replaced by macro ''{1}'', added parameters ''{2}''.", - macroName, (String) alias[0], Arrays.copyOfRange(alias, 1, alias.length - 1)); + LOG.info("Macro alias ''{0}'' replaced by ''{1}''.", macroName, Arrays.asList(alias)); } Macro macro = _macroRegistry.get(macroName); Assert.assertNotNull("No macro defined for " + macroName, macro); // add in one for the trailing } that was removed earlier context.setCurrentPosition(index + 1); return macro.resolve(resolvedParameters.toArray()); } }
true
true
private Object processMacro(ExpressionContext context, String macroText) { int index = 0; int embeddedMacroLevel = 0; List<String> parametersStrings = new ArrayList<String>(); // make sure it's a valid macro Assert.assertTrue("Macro text not properly formated ${<macro} for " + macroText, (macroText.startsWith("${")) && (macroText.endsWith("}")) ); // TODO Could this be cleaner? // strip off ${ and } macroText = macroText.substring(2, macroText.length() - 1); // handle special case - LITERAL macro if (macroText.startsWith(LiteralMacro.MACRO_NAME)) { context.setCurrentPosition(macroText.length() + 1); return macroText.substring(macroText.indexOf(',') + 1).trim(); } StringBuffer foundParameter = new StringBuffer(); // find the parameters by splitting on ',' // treat everything between '${' and '}' as // a single entity. for(index=0;index<macroText.length();index++) { char ch = macroText.charAt(index); switch(ch) { case '$': foundParameter.append(ch); // next character must be either a '$' // or a '{' or it's an error index++; Assert.assertTrue(index < macroText.length()); ch = macroText.charAt(index); foundParameter.append(ch); if(ch == '{') { embeddedMacroLevel++; } break; case '}': if(embeddedMacroLevel > 0) { embeddedMacroLevel--; } foundParameter.append(ch); break; case ',': if(embeddedMacroLevel == 0) { parametersStrings.add(foundParameter.toString().trim()); foundParameter = new StringBuffer(); } else { foundParameter.append(ch); } break; default: foundParameter.append(ch); break; } } // add the last one in ... there may not be one in certain // cases, so check length first String lastParameter = foundParameter.toString().trim(); if(lastParameter.length() > 0) { parametersStrings.add(lastParameter); } List<Object> resolvedParameters = new ArrayList<Object>(); for(String parameterString : parametersStrings) { Expression expression = new Expression(_macroRegistry, parameterString); resolvedParameters.add(expression.resolveExpression()); } // the resolved first parameter MUST be a string that represents // the macro name. String macroName = (String)resolvedParameters.get(0); Assert.assertNotNull("Macro name not found", macroName); // check if exist alias for macro Object[] alias = MacroAliases.ALIASES.get(macroName); if (alias != null) { Assert.assertTrue("Wrong macro alias definition - it must contain at least alias name.", alias.length > 0); // update macro name macroName = (String) alias[0]; // also remove macro name from parameters and add there new one + // alias parameters resolvedParameters.remove(0); resolvedParameters.addAll(0, Arrays.asList(alias)); LOG.info("Macro alias ''{0}'' replaced by macro ''{1}'', added parameters ''{2}''.", macroName, (String) alias[0], Arrays.copyOfRange(alias, 1, alias.length - 1)); } Macro macro = _macroRegistry.get(macroName); Assert.assertNotNull("No macro defined for " + macroName, macro); // add in one for the trailing } that was removed earlier context.setCurrentPosition(index + 1); return macro.resolve(resolvedParameters.toArray()); }
private Object processMacro(ExpressionContext context, String macroText) { int index = 0; int embeddedMacroLevel = 0; List<String> parametersStrings = new ArrayList<String>(); // make sure it's a valid macro Assert.assertTrue("Macro text not properly formated ${<macro} for " + macroText, (macroText.startsWith("${")) && (macroText.endsWith("}")) ); // TODO Could this be cleaner? // strip off ${ and } macroText = macroText.substring(2, macroText.length() - 1); // handle special case - LITERAL macro if (macroText.startsWith(LiteralMacro.MACRO_NAME)) { context.setCurrentPosition(macroText.length() + 1); return macroText.substring(macroText.indexOf(',') + 1).trim(); } StringBuffer foundParameter = new StringBuffer(); // find the parameters by splitting on ',' // treat everything between '${' and '}' as // a single entity. for(index=0;index<macroText.length();index++) { char ch = macroText.charAt(index); switch(ch) { case '$': foundParameter.append(ch); // next character must be either a '$' // or a '{' or it's an error index++; Assert.assertTrue(index < macroText.length()); ch = macroText.charAt(index); foundParameter.append(ch); if(ch == '{') { embeddedMacroLevel++; } break; case '}': if(embeddedMacroLevel > 0) { embeddedMacroLevel--; } foundParameter.append(ch); break; case ',': if(embeddedMacroLevel == 0) { parametersStrings.add(foundParameter.toString().trim()); foundParameter = new StringBuffer(); } else { foundParameter.append(ch); } break; default: foundParameter.append(ch); break; } } // add the last one in ... there may not be one in certain // cases, so check length first String lastParameter = foundParameter.toString().trim(); if(lastParameter.length() > 0) { parametersStrings.add(lastParameter); } List<Object> resolvedParameters = new ArrayList<Object>(); for(String parameterString : parametersStrings) { Expression expression = new Expression(_macroRegistry, parameterString); resolvedParameters.add(expression.resolveExpression()); } // the resolved first parameter MUST be a string that represents // the macro name. String macroName = (String)resolvedParameters.get(0); Assert.assertNotNull("Macro name not found", macroName); // check if exist alias for macro Object[] alias = MacroAliases.ALIASES.get(macroName); if (alias != null) { Assert.assertTrue("Wrong macro alias definition - it must contain at least alias name.", alias.length > 0); // update macro name macroName = (String) alias[0]; // also remove macro name from parameters and add there new one + // alias parameters resolvedParameters.remove(0); resolvedParameters.addAll(0, Arrays.asList(alias)); LOG.info("Macro alias ''{0}'' replaced by ''{1}''.", macroName, Arrays.asList(alias)); } Macro macro = _macroRegistry.get(macroName); Assert.assertNotNull("No macro defined for " + macroName, macro); // add in one for the trailing } that was removed earlier context.setCurrentPosition(index + 1); return macro.resolve(resolvedParameters.toArray()); }
diff --git a/test/web/org/appfuse/webapp/action/LoginServletTest.java b/test/web/org/appfuse/webapp/action/LoginServletTest.java index aa2079a8..073dce28 100644 --- a/test/web/org/appfuse/webapp/action/LoginServletTest.java +++ b/test/web/org/appfuse/webapp/action/LoginServletTest.java @@ -1,116 +1,116 @@ package org.appfuse.webapp.action; import java.util.HashMap; import java.util.Map; import java.util.ResourceBundle; import org.apache.cactus.ServletTestCase; import org.apache.cactus.WebRequest; import org.apache.cactus.WebResponse; import org.apache.cactus.client.authentication.FormAuthentication; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.appfuse.Constants; public class LoginServletTest extends ServletTestCase { //~ Static fields/initializers ============================================= private static ResourceBundle rb = null; //~ Instance fields ======================================================== private Log log = LogFactory.getLog(LoginServletTest.class); private LoginServlet servlet = null; //~ Constructors =========================================================== public LoginServletTest(String name) { super(name); rb = ResourceBundle.getBundle(this.getClass().getName()); } //~ Methods ================================================================ public LoginServlet createInstance() throws Exception { return new LoginServlet(); } protected void setUp() throws Exception { super.setUp(); servlet = new LoginServlet(); // set initialization parameters config.setInitParameter(Constants.AUTH_URL, rb.getString("authURL")); config.setInitParameter(Constants.HTTP_PORT, rb.getString("httpPort")); config.setInitParameter(Constants.HTTPS_PORT, rb.getString("httpsPort")); config.setInitParameter("isSecure", rb.getString("isSecure")); config.setInitParameter(Constants.ENC_ALGORITHM, rb.getString("algorithm")); servlet.init(config); } protected void tearDown() throws Exception { servlet = null; super.tearDown(); } /** * Test that initialization parameters were set * * @throws Exception */ public void testInit() throws Exception { // check all parameters from web.xml String authURL = config.getInitParameter(Constants.AUTH_URL); log.debug("authURL: " + authURL); assertTrue((authURL != null) && authURL.equals(rb.getString("authURL"))); Map config = (HashMap) servlet.getServletContext().getAttribute(Constants.CONFIG); - assertEquals((String) config.get(Constants.HTTP_PORT), + assertEquals(config.get(Constants.HTTP_PORT), rb.getString("httpPort")); - assertEquals((String) config.get(Constants.HTTPS_PORT), + assertEquals(config.get(Constants.HTTPS_PORT), rb.getString("httpsPort")); - assertEquals((Boolean) config.get(Constants.SECURE_LOGIN), + assertEquals(config.get(Constants.SECURE_LOGIN), Boolean.valueOf(rb.getString("isSecure"))); - assertEquals((String) config.get(Constants.ENC_ALGORITHM), + assertEquals(config.get(Constants.ENC_ALGORITHM), rb.getString("algorithm")); } public void beginFormAuthentication(WebRequest theRequest) { theRequest.setRedirectorName("ServletRedirectorSecure"); theRequest.setAuthentication(new FormAuthentication(rb.getString("username"), rb.getString("encryptedPassword"))); } /** * Test logging in as user a user */ public void testFormAuthentication() { assertEquals(rb.getString("username"), request.getUserPrincipal().getName()); assertEquals(rb.getString("username"), request.getRemoteUser()); assertTrue("User not in '" + rb.getString("role") + "' role", request.isUserInRole(rb.getString("role"))); } public void beginExecute(WebRequest wRequest) { wRequest.addParameter("j_username", rb.getString("username")); wRequest.addParameter("j_password", rb.getString("password")); } public void testExecute() throws Exception { servlet.execute(request, response); } public void endExecute(WebResponse response) { // TODO: get header value, verify Http Status 302 } public static void main(String[] args) { junit.textui.TestRunner.run(LoginServletTest.class); } }
false
true
public void testInit() throws Exception { // check all parameters from web.xml String authURL = config.getInitParameter(Constants.AUTH_URL); log.debug("authURL: " + authURL); assertTrue((authURL != null) && authURL.equals(rb.getString("authURL"))); Map config = (HashMap) servlet.getServletContext().getAttribute(Constants.CONFIG); assertEquals((String) config.get(Constants.HTTP_PORT), rb.getString("httpPort")); assertEquals((String) config.get(Constants.HTTPS_PORT), rb.getString("httpsPort")); assertEquals((Boolean) config.get(Constants.SECURE_LOGIN), Boolean.valueOf(rb.getString("isSecure"))); assertEquals((String) config.get(Constants.ENC_ALGORITHM), rb.getString("algorithm")); }
public void testInit() throws Exception { // check all parameters from web.xml String authURL = config.getInitParameter(Constants.AUTH_URL); log.debug("authURL: " + authURL); assertTrue((authURL != null) && authURL.equals(rb.getString("authURL"))); Map config = (HashMap) servlet.getServletContext().getAttribute(Constants.CONFIG); assertEquals(config.get(Constants.HTTP_PORT), rb.getString("httpPort")); assertEquals(config.get(Constants.HTTPS_PORT), rb.getString("httpsPort")); assertEquals(config.get(Constants.SECURE_LOGIN), Boolean.valueOf(rb.getString("isSecure"))); assertEquals(config.get(Constants.ENC_ALGORITHM), rb.getString("algorithm")); }
diff --git a/src/com/novell/android/yastroid/YastroidOpenHelper.java b/src/com/novell/android/yastroid/YastroidOpenHelper.java index 3e4c036..3445583 100644 --- a/src/com/novell/android/yastroid/YastroidOpenHelper.java +++ b/src/com/novell/android/yastroid/YastroidOpenHelper.java @@ -1,83 +1,83 @@ package com.novell.android.yastroid; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; //import android.widget.Toast; public class YastroidOpenHelper extends SQLiteOpenHelper { private static final String TAG = "YaSTroidDatabase"; private static final String DATABASE_NAME = "yastroid"; private static final int DATABASE_VERSION = 4; static final String SERVERS_TABLE_NAME = "servers"; static final String SERVERS_NAME = "name"; static final String SERVERS_SCHEME = "scheme"; static final String SERVERS_HOST = "hostname"; static final String SERVERS_PORT = "port"; static final String SERVERS_USER = "user"; static final String SERVERS_PASS = "pass"; static final String SERVERS_GROUP = "grp"; static final String GROUP_TABLE_NAME = "groups"; static final String GROUP_NAME = "name"; static final String GROUP_DESCRIPTION = "description"; static final String GROUP_ICON = "icon"; static final int GROUP_DEFAULT_ALL = 1; private static final String CREATE_SERVER_TABLE = "CREATE TABLE " + SERVERS_TABLE_NAME + " (" + "_id INTEGER PRIMARY KEY AUTOINCREMENT, " + SERVERS_NAME + " TEXT, " + SERVERS_SCHEME + " TEXT, " + SERVERS_HOST + " TEXT, " + SERVERS_PORT + " INTEGER, " + SERVERS_USER + " TEXT, " + SERVERS_PASS + " TEXT, " + SERVERS_GROUP + " INTEGER);"; private static final String CREATE_GROUP_TABLE = "CREATE TABLE " + GROUP_TABLE_NAME + " (" + "_id INTEGER PRIMARY KEY AUTOINCREMENT, " + GROUP_NAME + " TEXT, " + GROUP_DESCRIPTION + " TEXT, " + GROUP_ICON + " INTEGER);"; private static final String DEFAULT_GROUP = "INSERT INTO " + GROUP_TABLE_NAME + "(name,description,icon) VALUES ('All', 'All servers', '0');"; private static final String ADD_SERVER = "INSERT INTO " + SERVERS_TABLE_NAME + "(name,scheme,hostname,port,user,pass,grp) VALUES ('webyast1', 'http', '137.65.132.194', '4984','root','sandy','" + GROUP_DEFAULT_ALL +"');"; public YastroidOpenHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_SERVER_TABLE); db.execSQL(CREATE_GROUP_TABLE); db.execSQL(DEFAULT_GROUP); // Demo data db.execSQL(ADD_SERVER); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(TAG, "Upgrading database from version " + oldVersion + "to " + newVersion); // Any changes to the database structure should occur here. // This is called if the DATABASE_VERSION installed is older // than the new version. // ie. db.execSQL("alter table " + TASKS_TABLE + " add column " + // TASK_ADDRESS + " text"); db.execSQL("ALTER TABLE servers ADD COLUMN grp INTEGER;"); db.execSQL(CREATE_GROUP_TABLE); db.execSQL(DEFAULT_GROUP); - db.execSQL("UPDATE " + SERVERS_TABLE_NAME + " SET " + SERVERS_GROUP + "'0';"); + db.execSQL("UPDATE " + SERVERS_TABLE_NAME + " SET " + SERVERS_GROUP + "='" + GROUP_DEFAULT_ALL + "';"); } }
true
true
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(TAG, "Upgrading database from version " + oldVersion + "to " + newVersion); // Any changes to the database structure should occur here. // This is called if the DATABASE_VERSION installed is older // than the new version. // ie. db.execSQL("alter table " + TASKS_TABLE + " add column " + // TASK_ADDRESS + " text"); db.execSQL("ALTER TABLE servers ADD COLUMN grp INTEGER;"); db.execSQL(CREATE_GROUP_TABLE); db.execSQL(DEFAULT_GROUP); db.execSQL("UPDATE " + SERVERS_TABLE_NAME + " SET " + SERVERS_GROUP + "'0';"); }
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(TAG, "Upgrading database from version " + oldVersion + "to " + newVersion); // Any changes to the database structure should occur here. // This is called if the DATABASE_VERSION installed is older // than the new version. // ie. db.execSQL("alter table " + TASKS_TABLE + " add column " + // TASK_ADDRESS + " text"); db.execSQL("ALTER TABLE servers ADD COLUMN grp INTEGER;"); db.execSQL(CREATE_GROUP_TABLE); db.execSQL(DEFAULT_GROUP); db.execSQL("UPDATE " + SERVERS_TABLE_NAME + " SET " + SERVERS_GROUP + "='" + GROUP_DEFAULT_ALL + "';"); }
diff --git a/src/fitnesse/responders/editing/SymbolicLinkResponder.java b/src/fitnesse/responders/editing/SymbolicLinkResponder.java index 9e4af9e..5d3fd94 100644 --- a/src/fitnesse/responders/editing/SymbolicLinkResponder.java +++ b/src/fitnesse/responders/editing/SymbolicLinkResponder.java @@ -1,126 +1,126 @@ // Copyright (C) 2003,2004,2005 by Object Mentor, Inc. All rights reserved. // Released under the terms of the GNU General Public License version 2 or later. package fitnesse.responders.editing; import fitnesse.*; import fitnesse.http.*; import fitnesse.responders.*; import fitnesse.wiki.*; import java.io.File; public class SymbolicLinkResponder implements Responder { private Response response; private String resource; private PageCrawler crawler; private FitNesseContext context; public Response makeResponse(FitNesseContext context, Request request) throws Exception { resource = request.getResource(); this.context = context; crawler = context.root.getPageCrawler(); WikiPage page = crawler.getPage(context.root, PathParser.parse(resource)); if(page == null) return new NotFoundResponder().makeResponse(context, request); response = new SimpleResponse(); if(request.hasInput("removal")) removeSymbolicLink(request, page); else addSymbolicLink(request, page); return response; } private void setRedirect(String resource) { response.redirect(resource + "?properties"); } private void removeSymbolicLink(Request request, WikiPage page) throws Exception { String linkToRemove = (String) request.getInput("removal"); PageData data = page.getData(); WikiPageProperties properties = data.getProperties(); WikiPageProperty symLinks = getSymLinkProperty(properties); symLinks.remove(linkToRemove); if(symLinks.keySet().size() == 0) properties.remove(SymbolicPage.PROPERTY_NAME); page.commit(data); setRedirect(resource); } private void addSymbolicLink(Request request, WikiPage page) throws Exception { String linkName = (String) request.getInput("linkName"); String linkPath = (String) request.getInput("linkPath"); if(isFilePath(linkPath) && !isValidDirectoryPath(linkPath)) { String message = "Cannot create link to the file system path, <b>" + linkPath + "</b>." + "<br> The canonical file system path used was <b>" + createFileFromPath(linkPath).getCanonicalPath() + ".</b>" + "<br>Either it doesn't exist or it's not a directory."; response = new ErrorResponder(message).makeResponse(context, null); response.setStatus(404); } else if(!isFilePath(linkPath) && isInternalPageThatDoesntExist(linkPath)) { - response = new ErrorResponder("The page to which you are attemting to link, " + linkPath + ", doesn't exist.").makeResponse(context, null); + response = new ErrorResponder("The page to which you are attempting to link, " + linkPath + ", doesn't exist.").makeResponse(context, null); response.setStatus(404); } else if(page.hasChildPage(linkName)) { response = new ErrorResponder(resource + " already has a child named " + linkName + ".").makeResponse(context, null); response.setStatus(412); } else { PageData data = page.getData(); WikiPageProperties properties = data.getProperties(); WikiPageProperty symLinks = getSymLinkProperty(properties); symLinks.set(linkName, linkPath); page.commit(data); setRedirect(resource); } } private boolean isValidDirectoryPath(String linkPath) throws Exception { File file = createFileFromPath(linkPath); if(file.exists()) return file.isDirectory(); else { File parentDir = file.getParentFile(); return parentDir.exists() && parentDir.isDirectory(); } } private File createFileFromPath(String linkPath) { String pathToFile = linkPath.substring(7); return new File(pathToFile); } private boolean isFilePath(String linkPath) { return linkPath.startsWith("file://"); } private boolean isInternalPageThatDoesntExist(String linkPath) throws Exception { return !crawler.pageExists(context.root, PathParser.parse(linkPath)); } private WikiPageProperty getSymLinkProperty(WikiPageProperties properties) { WikiPageProperty symLinks = properties.getProperty(SymbolicPage.PROPERTY_NAME); if(symLinks == null) symLinks = properties.set(SymbolicPage.PROPERTY_NAME); return symLinks; } }
true
true
private void addSymbolicLink(Request request, WikiPage page) throws Exception { String linkName = (String) request.getInput("linkName"); String linkPath = (String) request.getInput("linkPath"); if(isFilePath(linkPath) && !isValidDirectoryPath(linkPath)) { String message = "Cannot create link to the file system path, <b>" + linkPath + "</b>." + "<br> The canonical file system path used was <b>" + createFileFromPath(linkPath).getCanonicalPath() + ".</b>" + "<br>Either it doesn't exist or it's not a directory."; response = new ErrorResponder(message).makeResponse(context, null); response.setStatus(404); } else if(!isFilePath(linkPath) && isInternalPageThatDoesntExist(linkPath)) { response = new ErrorResponder("The page to which you are attemting to link, " + linkPath + ", doesn't exist.").makeResponse(context, null); response.setStatus(404); } else if(page.hasChildPage(linkName)) { response = new ErrorResponder(resource + " already has a child named " + linkName + ".").makeResponse(context, null); response.setStatus(412); } else { PageData data = page.getData(); WikiPageProperties properties = data.getProperties(); WikiPageProperty symLinks = getSymLinkProperty(properties); symLinks.set(linkName, linkPath); page.commit(data); setRedirect(resource); } }
private void addSymbolicLink(Request request, WikiPage page) throws Exception { String linkName = (String) request.getInput("linkName"); String linkPath = (String) request.getInput("linkPath"); if(isFilePath(linkPath) && !isValidDirectoryPath(linkPath)) { String message = "Cannot create link to the file system path, <b>" + linkPath + "</b>." + "<br> The canonical file system path used was <b>" + createFileFromPath(linkPath).getCanonicalPath() + ".</b>" + "<br>Either it doesn't exist or it's not a directory."; response = new ErrorResponder(message).makeResponse(context, null); response.setStatus(404); } else if(!isFilePath(linkPath) && isInternalPageThatDoesntExist(linkPath)) { response = new ErrorResponder("The page to which you are attempting to link, " + linkPath + ", doesn't exist.").makeResponse(context, null); response.setStatus(404); } else if(page.hasChildPage(linkName)) { response = new ErrorResponder(resource + " already has a child named " + linkName + ".").makeResponse(context, null); response.setStatus(412); } else { PageData data = page.getData(); WikiPageProperties properties = data.getProperties(); WikiPageProperty symLinks = getSymLinkProperty(properties); symLinks.set(linkName, linkPath); page.commit(data); setRedirect(resource); } }
diff --git a/src/java/com/eviware/soapui/support/jdbc/JdbcUtils.java b/src/java/com/eviware/soapui/support/jdbc/JdbcUtils.java index 56166e5d3..c6a57637d 100644 --- a/src/java/com/eviware/soapui/support/jdbc/JdbcUtils.java +++ b/src/java/com/eviware/soapui/support/jdbc/JdbcUtils.java @@ -1,79 +1,79 @@ /* * soapUI, copyright (C) 2004-2010 eviware.com * * soapUI is free software; you can redistribute it and/or modify it under the * terms of version 2.1 of the GNU Lesser General Public License as published by * the Free Software Foundation. * * soapUI 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 at gnu.org. */ package com.eviware.soapui.support.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import com.eviware.soapui.SoapUI; import com.eviware.soapui.model.propertyexpansion.PropertyExpander; import com.eviware.soapui.model.propertyexpansion.PropertyExpansionContext; import com.eviware.soapui.support.SoapUIException; import com.eviware.soapui.support.StringUtils; public class JdbcUtils { public static final String PASS_TEMPLATE = "PASS_VALUE"; public static Connection initConnection( PropertyExpansionContext context, String driver, String connectionString, String password ) throws SQLException, SoapUIException { if( JdbcUtils.missingConnSettings( driver, connectionString, password ) ) { throw new SoapUIException( "Some connections settings are missing" ); - } + } String drvr = PropertyExpander.expandProperties( context, driver ).trim(); String connStr = PropertyExpander.expandProperties( context, connectionString ).trim(); String pass = StringUtils.hasContent( password ) ? PropertyExpander.expandProperties( context, password ).trim() : ""; String masskedPass = connStr.replace( PASS_TEMPLATE, "#####" ); if( connStr.contains( PASS_TEMPLATE ) ) { connStr = connStr.replaceFirst( PASS_TEMPLATE, pass ); } try { DriverManager.getDriver( connStr ); } catch( SQLException e ) { - SoapUI.logError( e ); + // SoapUI.logError( e ); try { Class.forName( drvr ).newInstance(); } catch( Exception e1 ) { SoapUI.logError( e ); throw new SoapUIException( "Failed to init connection for drvr [" + drvr + "], connectionString [" + masskedPass + "]" ); } } return DriverManager.getConnection( connStr ); } public static boolean hasMasskedPass( String connStr ) { return !StringUtils.isNullOrEmpty( connStr ) ? connStr.contains( PASS_TEMPLATE ) : false; } public static boolean missingConnSettings( String driver, String connectionString, String password ) { return StringUtils.isNullOrEmpty( driver ) || StringUtils.isNullOrEmpty( connectionString ) || ( connectionString.contains( PASS_TEMPLATE ) && StringUtils.isNullOrEmpty( password ) ); } }
false
true
public static Connection initConnection( PropertyExpansionContext context, String driver, String connectionString, String password ) throws SQLException, SoapUIException { if( JdbcUtils.missingConnSettings( driver, connectionString, password ) ) { throw new SoapUIException( "Some connections settings are missing" ); } String drvr = PropertyExpander.expandProperties( context, driver ).trim(); String connStr = PropertyExpander.expandProperties( context, connectionString ).trim(); String pass = StringUtils.hasContent( password ) ? PropertyExpander.expandProperties( context, password ).trim() : ""; String masskedPass = connStr.replace( PASS_TEMPLATE, "#####" ); if( connStr.contains( PASS_TEMPLATE ) ) { connStr = connStr.replaceFirst( PASS_TEMPLATE, pass ); } try { DriverManager.getDriver( connStr ); } catch( SQLException e ) { SoapUI.logError( e ); try { Class.forName( drvr ).newInstance(); } catch( Exception e1 ) { SoapUI.logError( e ); throw new SoapUIException( "Failed to init connection for drvr [" + drvr + "], connectionString [" + masskedPass + "]" ); } } return DriverManager.getConnection( connStr ); }
public static Connection initConnection( PropertyExpansionContext context, String driver, String connectionString, String password ) throws SQLException, SoapUIException { if( JdbcUtils.missingConnSettings( driver, connectionString, password ) ) { throw new SoapUIException( "Some connections settings are missing" ); } String drvr = PropertyExpander.expandProperties( context, driver ).trim(); String connStr = PropertyExpander.expandProperties( context, connectionString ).trim(); String pass = StringUtils.hasContent( password ) ? PropertyExpander.expandProperties( context, password ).trim() : ""; String masskedPass = connStr.replace( PASS_TEMPLATE, "#####" ); if( connStr.contains( PASS_TEMPLATE ) ) { connStr = connStr.replaceFirst( PASS_TEMPLATE, pass ); } try { DriverManager.getDriver( connStr ); } catch( SQLException e ) { // SoapUI.logError( e ); try { Class.forName( drvr ).newInstance(); } catch( Exception e1 ) { SoapUI.logError( e ); throw new SoapUIException( "Failed to init connection for drvr [" + drvr + "], connectionString [" + masskedPass + "]" ); } } return DriverManager.getConnection( connStr ); }
diff --git a/org.strategoxt.imp.testing/editor/java/org/strategoxt/imp/testing/SpoofaxTestingJSGLRI.java b/org.strategoxt.imp.testing/editor/java/org/strategoxt/imp/testing/SpoofaxTestingJSGLRI.java index 5f3293f..9cc768c 100644 --- a/org.strategoxt.imp.testing/editor/java/org/strategoxt/imp/testing/SpoofaxTestingJSGLRI.java +++ b/org.strategoxt.imp.testing/editor/java/org/strategoxt/imp/testing/SpoofaxTestingJSGLRI.java @@ -1,152 +1,152 @@ package org.strategoxt.imp.testing; import static org.spoofax.interpreter.core.Tools.asJavaString; import static org.spoofax.interpreter.core.Tools.isTermAppl; import static org.spoofax.jsglr.client.imploder.ImploderAttachment.getLeftToken; import static org.spoofax.jsglr.client.imploder.ImploderAttachment.getRightToken; import static org.spoofax.jsglr.client.imploder.ImploderAttachment.getTokenizer; import static org.spoofax.terms.Term.termAt; import static org.spoofax.terms.Term.tryGetConstructor; import java.io.IOException; import java.util.Iterator; import org.eclipse.imp.language.Language; import org.eclipse.imp.language.LanguageRegistry; import org.spoofax.interpreter.terms.IStrategoAppl; import org.spoofax.interpreter.terms.IStrategoConstructor; import org.spoofax.interpreter.terms.IStrategoList; import org.spoofax.interpreter.terms.IStrategoString; import org.spoofax.interpreter.terms.IStrategoTerm; import org.spoofax.interpreter.terms.ITermFactory; import org.spoofax.jsglr.client.imploder.ImploderAttachment; import org.spoofax.jsglr.client.imploder.Tokenizer; import org.spoofax.jsglr.shared.BadTokenException; import org.spoofax.jsglr.shared.SGLRException; import org.spoofax.jsglr.shared.TokenExpectedException; import org.spoofax.terms.StrategoListIterator; import org.spoofax.terms.TermTransformer; import org.spoofax.terms.TermVisitor; import org.spoofax.terms.attachments.ParentAttachment; import org.spoofax.terms.attachments.ParentTermFactory; import org.strategoxt.imp.runtime.Debug; import org.strategoxt.imp.runtime.Environment; import org.strategoxt.imp.runtime.dynamicloading.Descriptor; import org.strategoxt.imp.runtime.parser.JSGLRI; public class SpoofaxTestingJSGLRI extends JSGLRI { private static final int PARSE_TIMEOUT = 20 * 1000; private static final IStrategoConstructor INPUT_4 = Environment.getTermFactory().makeConstructor("Input", 4); private static final IStrategoConstructor OUTPUT_4 = Environment.getTermFactory().makeConstructor("Output", 4); private static final IStrategoConstructor ERROR_1 = Environment.getTermFactory().makeConstructor("Error", 1); private static final IStrategoConstructor LANGUAGE_1 = Environment.getTermFactory().makeConstructor("Language", 1); private final FragmentParser fragmentParser = new FragmentParser(); private final SelectionFetcher selections = new SelectionFetcher(); public SpoofaxTestingJSGLRI(JSGLRI template) { super(template.getParseTable(), template.getStartSymbol(), template.getController()); setTimeout(PARSE_TIMEOUT); setUseRecovery(true); } @Override protected IStrategoTerm doParse(String input, String filename) throws TokenExpectedException, BadTokenException, SGLRException, IOException { IStrategoTerm ast = super.doParse(input, filename); return parseTestedFragments(ast); } private IStrategoTerm parseTestedFragments(final IStrategoTerm root) { final Tokenizer oldTokenizer = (Tokenizer) getTokenizer(root); final Retokenizer retokenizer = new Retokenizer(oldTokenizer); final ITermFactory nonParentFactory = Environment.getTermFactory(); final ITermFactory factory = new ParentTermFactory(nonParentFactory); final FragmentParser testedParser = getFragmentParser(root); assert !(nonParentFactory instanceof ParentTermFactory); if (testedParser == null || !testedParser.isInitialized()) return root; IStrategoTerm result = new TermTransformer(factory, true) { @Override public IStrategoTerm preTransform(IStrategoTerm term) { IStrategoConstructor cons = tryGetConstructor(term); if (cons == INPUT_4 || cons == OUTPUT_4) { IStrategoTerm fragmentHead = termAt(term, 1); IStrategoTerm fragmentTail = termAt(term, 2); retokenizer.copyTokensUpToIndex(getLeftToken(fragmentHead).getIndex() - 1); try { IStrategoTerm parsed = testedParser.parse(oldTokenizer, term, cons == OUTPUT_4); int oldFragmentEndIndex = getRightToken(fragmentTail).getIndex(); retokenizer.copyTokensFromFragment(fragmentHead, fragmentTail, parsed, getLeftToken(fragmentHead).getStartOffset(), getRightToken(fragmentTail).getEndOffset()); if (!testedParser.isLastSyntaxCorrect()) - parsed = factory.makeAppl(ERROR_1, parsed); + parsed = nonParentFactory.makeAppl(ERROR_1, parsed); ImploderAttachment implodement = ImploderAttachment.get(term); IStrategoList selected = selections.fetch(parsed); term = factory.annotateTerm(term, nonParentFactory.makeListCons(parsed, selected)); term.putAttachment(implodement.clone()); retokenizer.skipTokensUpToIndex(oldFragmentEndIndex); } catch (IOException e) { Debug.log("Could not parse tested code fragment", e); } catch (SGLRException e) { Debug.log("Could not parse tested code fragment", e); } catch (CloneNotSupportedException e) { Environment.logException("Could not parse tested code fragment", e); } catch (RuntimeException e) { Environment.logException("Could not parse tested code fragment", e); } } return term; } @Override public IStrategoTerm postTransform(IStrategoTerm term) { Iterator<IStrategoTerm> iterator = TermVisitor.tryGetListIterator(term); for (int i = 0, max = term.getSubtermCount(); i < max; i++) { IStrategoTerm kid = iterator == null ? term.getSubterm(i) : iterator.next(); ParentAttachment.putParent(kid, term, null); } return term; } }.transform(root); retokenizer.copyTokensAfterFragments(); retokenizer.getTokenizer().setAst(result); retokenizer.getTokenizer().initAstNodeBinding(); return result; } private FragmentParser getFragmentParser(IStrategoTerm root) { Language language = getLanguage(root); if (language == null) return null; Descriptor descriptor = Environment.getDescriptor(language); fragmentParser.configure(descriptor, getController().getRelativePath(), getController().getProject(), root); return fragmentParser; } private Language getLanguage(IStrategoTerm root) { if (isTermAppl(root) && "EmptyFile".equals(((IStrategoAppl) root).getName())) return null; IStrategoList headers = termAt(root, 0); for (IStrategoTerm header : StrategoListIterator.iterable(headers)) { if (tryGetConstructor(header) == LANGUAGE_1) { IStrategoString name = termAt(header, 0); return LanguageRegistry.findLanguage(asJavaString(name)); } } return null; } }
true
true
private IStrategoTerm parseTestedFragments(final IStrategoTerm root) { final Tokenizer oldTokenizer = (Tokenizer) getTokenizer(root); final Retokenizer retokenizer = new Retokenizer(oldTokenizer); final ITermFactory nonParentFactory = Environment.getTermFactory(); final ITermFactory factory = new ParentTermFactory(nonParentFactory); final FragmentParser testedParser = getFragmentParser(root); assert !(nonParentFactory instanceof ParentTermFactory); if (testedParser == null || !testedParser.isInitialized()) return root; IStrategoTerm result = new TermTransformer(factory, true) { @Override public IStrategoTerm preTransform(IStrategoTerm term) { IStrategoConstructor cons = tryGetConstructor(term); if (cons == INPUT_4 || cons == OUTPUT_4) { IStrategoTerm fragmentHead = termAt(term, 1); IStrategoTerm fragmentTail = termAt(term, 2); retokenizer.copyTokensUpToIndex(getLeftToken(fragmentHead).getIndex() - 1); try { IStrategoTerm parsed = testedParser.parse(oldTokenizer, term, cons == OUTPUT_4); int oldFragmentEndIndex = getRightToken(fragmentTail).getIndex(); retokenizer.copyTokensFromFragment(fragmentHead, fragmentTail, parsed, getLeftToken(fragmentHead).getStartOffset(), getRightToken(fragmentTail).getEndOffset()); if (!testedParser.isLastSyntaxCorrect()) parsed = factory.makeAppl(ERROR_1, parsed); ImploderAttachment implodement = ImploderAttachment.get(term); IStrategoList selected = selections.fetch(parsed); term = factory.annotateTerm(term, nonParentFactory.makeListCons(parsed, selected)); term.putAttachment(implodement.clone()); retokenizer.skipTokensUpToIndex(oldFragmentEndIndex); } catch (IOException e) { Debug.log("Could not parse tested code fragment", e); } catch (SGLRException e) { Debug.log("Could not parse tested code fragment", e); } catch (CloneNotSupportedException e) { Environment.logException("Could not parse tested code fragment", e); } catch (RuntimeException e) { Environment.logException("Could not parse tested code fragment", e); } } return term; } @Override public IStrategoTerm postTransform(IStrategoTerm term) { Iterator<IStrategoTerm> iterator = TermVisitor.tryGetListIterator(term); for (int i = 0, max = term.getSubtermCount(); i < max; i++) { IStrategoTerm kid = iterator == null ? term.getSubterm(i) : iterator.next(); ParentAttachment.putParent(kid, term, null); } return term; } }.transform(root); retokenizer.copyTokensAfterFragments(); retokenizer.getTokenizer().setAst(result); retokenizer.getTokenizer().initAstNodeBinding(); return result; }
private IStrategoTerm parseTestedFragments(final IStrategoTerm root) { final Tokenizer oldTokenizer = (Tokenizer) getTokenizer(root); final Retokenizer retokenizer = new Retokenizer(oldTokenizer); final ITermFactory nonParentFactory = Environment.getTermFactory(); final ITermFactory factory = new ParentTermFactory(nonParentFactory); final FragmentParser testedParser = getFragmentParser(root); assert !(nonParentFactory instanceof ParentTermFactory); if (testedParser == null || !testedParser.isInitialized()) return root; IStrategoTerm result = new TermTransformer(factory, true) { @Override public IStrategoTerm preTransform(IStrategoTerm term) { IStrategoConstructor cons = tryGetConstructor(term); if (cons == INPUT_4 || cons == OUTPUT_4) { IStrategoTerm fragmentHead = termAt(term, 1); IStrategoTerm fragmentTail = termAt(term, 2); retokenizer.copyTokensUpToIndex(getLeftToken(fragmentHead).getIndex() - 1); try { IStrategoTerm parsed = testedParser.parse(oldTokenizer, term, cons == OUTPUT_4); int oldFragmentEndIndex = getRightToken(fragmentTail).getIndex(); retokenizer.copyTokensFromFragment(fragmentHead, fragmentTail, parsed, getLeftToken(fragmentHead).getStartOffset(), getRightToken(fragmentTail).getEndOffset()); if (!testedParser.isLastSyntaxCorrect()) parsed = nonParentFactory.makeAppl(ERROR_1, parsed); ImploderAttachment implodement = ImploderAttachment.get(term); IStrategoList selected = selections.fetch(parsed); term = factory.annotateTerm(term, nonParentFactory.makeListCons(parsed, selected)); term.putAttachment(implodement.clone()); retokenizer.skipTokensUpToIndex(oldFragmentEndIndex); } catch (IOException e) { Debug.log("Could not parse tested code fragment", e); } catch (SGLRException e) { Debug.log("Could not parse tested code fragment", e); } catch (CloneNotSupportedException e) { Environment.logException("Could not parse tested code fragment", e); } catch (RuntimeException e) { Environment.logException("Could not parse tested code fragment", e); } } return term; } @Override public IStrategoTerm postTransform(IStrategoTerm term) { Iterator<IStrategoTerm> iterator = TermVisitor.tryGetListIterator(term); for (int i = 0, max = term.getSubtermCount(); i < max; i++) { IStrategoTerm kid = iterator == null ? term.getSubterm(i) : iterator.next(); ParentAttachment.putParent(kid, term, null); } return term; } }.transform(root); retokenizer.copyTokensAfterFragments(); retokenizer.getTokenizer().setAst(result); retokenizer.getTokenizer().initAstNodeBinding(); return result; }
diff --git a/code/mobile/smartFridge/src/edu/rit/smartFridge/ListRemoveActivity.java b/code/mobile/smartFridge/src/edu/rit/smartFridge/ListRemoveActivity.java index 2ce6a56..4493ac0 100644 --- a/code/mobile/smartFridge/src/edu/rit/smartFridge/ListRemoveActivity.java +++ b/code/mobile/smartFridge/src/edu/rit/smartFridge/ListRemoveActivity.java @@ -1,71 +1,71 @@ package edu.rit.smartFridge; import android.app.ListActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.ListView; import edu.rit.smartFridge.model.InventoryItem; import edu.rit.smartFridge.model.ShoppingList; import edu.rit.smartFridge.util.Connector; import edu.rit.smartFridge.util.DataConnect; public class ListRemoveActivity extends ListActivity { /** Called when the activity is first created. */ public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // get the extras and the connector Bundle extras = getIntent().getExtras(); final DataConnect connector = Connector.getInstance(); ShoppingList list; final String itemName; final int UPC; // get item name and UPC if (extras != null) { itemName = extras.getString(getString(R.string.current_item)); UPC = extras.getInt(getString(R.string.current_upc)); int listId = extras.getInt(getString(R.string.current_list)); list = connector.getList(listId); } else { itemName = ""; UPC = -1; list = null; } // copy the list somewhere final so the listener can use it final ShoppingList finalList = connector.populateItems(list); String[] yesNo = {"Yes", "No"}; setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, yesNo)); ListView lv = getListView(); lv.setTextFilterEnabled(true); // make a listener lv.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (position == 0) { finalList.removeItem(new InventoryItem(itemName, UPC)); } Intent i = new Intent().setClass(parent.getContext(), ItemListActivity.class) - .putExtra(getString(R.string.current_list), finalList); + .putExtra(getString(R.string.current_list), finalList.getID()); parent.getContext().startActivity(i); } }); } }
true
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // get the extras and the connector Bundle extras = getIntent().getExtras(); final DataConnect connector = Connector.getInstance(); ShoppingList list; final String itemName; final int UPC; // get item name and UPC if (extras != null) { itemName = extras.getString(getString(R.string.current_item)); UPC = extras.getInt(getString(R.string.current_upc)); int listId = extras.getInt(getString(R.string.current_list)); list = connector.getList(listId); } else { itemName = ""; UPC = -1; list = null; } // copy the list somewhere final so the listener can use it final ShoppingList finalList = connector.populateItems(list); String[] yesNo = {"Yes", "No"}; setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, yesNo)); ListView lv = getListView(); lv.setTextFilterEnabled(true); // make a listener lv.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (position == 0) { finalList.removeItem(new InventoryItem(itemName, UPC)); } Intent i = new Intent().setClass(parent.getContext(), ItemListActivity.class) .putExtra(getString(R.string.current_list), finalList); parent.getContext().startActivity(i); } }); }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // get the extras and the connector Bundle extras = getIntent().getExtras(); final DataConnect connector = Connector.getInstance(); ShoppingList list; final String itemName; final int UPC; // get item name and UPC if (extras != null) { itemName = extras.getString(getString(R.string.current_item)); UPC = extras.getInt(getString(R.string.current_upc)); int listId = extras.getInt(getString(R.string.current_list)); list = connector.getList(listId); } else { itemName = ""; UPC = -1; list = null; } // copy the list somewhere final so the listener can use it final ShoppingList finalList = connector.populateItems(list); String[] yesNo = {"Yes", "No"}; setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, yesNo)); ListView lv = getListView(); lv.setTextFilterEnabled(true); // make a listener lv.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (position == 0) { finalList.removeItem(new InventoryItem(itemName, UPC)); } Intent i = new Intent().setClass(parent.getContext(), ItemListActivity.class) .putExtra(getString(R.string.current_list), finalList.getID()); parent.getContext().startActivity(i); } }); }
diff --git a/src/net/reichholf/dreamdroid/fragment/dialogs/ActionDialog.java b/src/net/reichholf/dreamdroid/fragment/dialogs/ActionDialog.java index 0038c093..643b7016 100644 --- a/src/net/reichholf/dreamdroid/fragment/dialogs/ActionDialog.java +++ b/src/net/reichholf/dreamdroid/fragment/dialogs/ActionDialog.java @@ -1,22 +1,24 @@ /* © 2010 Stephan Reichholf <stephan at reichholf dot net> * * Licensed under the Create-Commons Attribution-Noncommercial-Share Alike 3.0 Unported * http://creativecommons.org/licenses/by-nc-sa/3.0/ */ package net.reichholf.dreamdroid.fragment.dialogs; /** * @author sre * */ public abstract class ActionDialog extends AbstractDialog { protected void finishDialog(int action, Object details) { - ((DialogActionListener) getActivity()).onDialogAction(action, details, getTag()); + DialogActionListener listener = (DialogActionListener) getActivity(); + if(listener != null) + listener.onDialogAction(action, details, getTag()); dismiss(); } public interface DialogActionListener { public void onDialogAction(int action, Object details, String dialogTag); } }
true
true
protected void finishDialog(int action, Object details) { ((DialogActionListener) getActivity()).onDialogAction(action, details, getTag()); dismiss(); }
protected void finishDialog(int action, Object details) { DialogActionListener listener = (DialogActionListener) getActivity(); if(listener != null) listener.onDialogAction(action, details, getTag()); dismiss(); }
diff --git a/forumlistener/XenForo.java b/forumlistener/XenForo.java index 8f7e14f..4595a0d 100644 --- a/forumlistener/XenForo.java +++ b/forumlistener/XenForo.java @@ -1,107 +1,105 @@ import java.security.NoSuchAlgorithmException; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import com.greatmancode.extras.Tools; import com.greatmancode.okb3.OKBSync; import com.greatmancode.okb3.OKBWebsiteDB; import com.greatmancode.okb3.OKConfig; public class XenForo implements OKBSync { String fieldName = "user_group_id"; public XenForo() { if (OKConfig.useSecondaryGroups) { fieldName = "secondary_group_ids"; } } @Override public boolean accountExist(String username, String password) { - String encpass = "nope"; boolean exist = false; try { ResultSet rs = OKBWebsiteDB.dbm.prepare("SELECT data FROM " + (String) OKConfig.tablePrefix + "xf_user_authenticate," + (String) OKConfig.tablePrefix + "xf_user WHERE " + OKConfig.tablePrefix + "xf_user.username = '" + username + "' AND " + OKConfig.tablePrefix + "xf_user.user_id = " + OKConfig.tablePrefix + "xf_user_authenticate.user_id").executeQuery(); if (rs.next()) { do { - encpass = Tools.SHA256(Tools.SHA256(password) + Tools.regmatch("\"salt\";.:..:\"(.*)\";.:.:\"hashFunc\"", rs.getString("data"))); + if (Tools.SHA256(Tools.SHA256(password) + Tools.regmatch("\"salt\";.:..:\"(.*)\";.:.:\"hashFunc\"", rs.getString("data"))).equals(Tools.regmatch("\"hash\";.:..:\"(.*)\";.:.:\"salt\"", rs.getString("data")))) + { + exist = true; + } } while (rs.next()); } rs.close(); } catch (SQLException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } - if (!encpass.equals("nope")) - { - exist = true; - } return exist; } @Override public void changeRank(String username, int forumGroupId) { try { OKBWebsiteDB.dbm.prepare("UPDATE " + OKConfig.tablePrefix + "xf_user," + OKConfig.tablePrefix+ "xf_user_authenticate SET user_group_id='" + forumGroupId + "' WHERE " + OKConfig.tablePrefix + "xf_user.username='" + username + "' AND " + OKConfig.tablePrefix + "xf_user.user_id=xf_user_authenticate.user_id").executeUpdate(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public void ban(String username, int forumGroupId) { changeRank(username,forumGroupId); } @Override public void unban(String username, int forumGroupId) { changeRank(username,forumGroupId); } @Override public List<Integer> getGroup(String username) { List<Integer> group = new ArrayList<Integer>(); String query1 = "SELECT " + fieldName + ",data FROM " + OKConfig.tablePrefix + "xf_user," + OKConfig.tablePrefix + "xf_user_authenticate WHERE " + OKConfig.tablePrefix + "xf_user.username = '" + username + "' AND " + OKConfig.tablePrefix + "xf_user.user_id = " + OKConfig.tablePrefix + "xf_user_authenticate.user_id"; try { ResultSet rs = OKBWebsiteDB.dbm.prepare(query1).executeQuery(); if (rs.next()) { group.add(rs.getInt(fieldName)); } rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return group; } }
false
true
public boolean accountExist(String username, String password) { String encpass = "nope"; boolean exist = false; try { ResultSet rs = OKBWebsiteDB.dbm.prepare("SELECT data FROM " + (String) OKConfig.tablePrefix + "xf_user_authenticate," + (String) OKConfig.tablePrefix + "xf_user WHERE " + OKConfig.tablePrefix + "xf_user.username = '" + username + "' AND " + OKConfig.tablePrefix + "xf_user.user_id = " + OKConfig.tablePrefix + "xf_user_authenticate.user_id").executeQuery(); if (rs.next()) { do { encpass = Tools.SHA256(Tools.SHA256(password) + Tools.regmatch("\"salt\";.:..:\"(.*)\";.:.:\"hashFunc\"", rs.getString("data"))); } while (rs.next()); } rs.close(); } catch (SQLException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } if (!encpass.equals("nope")) { exist = true; } return exist; }
public boolean accountExist(String username, String password) { boolean exist = false; try { ResultSet rs = OKBWebsiteDB.dbm.prepare("SELECT data FROM " + (String) OKConfig.tablePrefix + "xf_user_authenticate," + (String) OKConfig.tablePrefix + "xf_user WHERE " + OKConfig.tablePrefix + "xf_user.username = '" + username + "' AND " + OKConfig.tablePrefix + "xf_user.user_id = " + OKConfig.tablePrefix + "xf_user_authenticate.user_id").executeQuery(); if (rs.next()) { do { if (Tools.SHA256(Tools.SHA256(password) + Tools.regmatch("\"salt\";.:..:\"(.*)\";.:.:\"hashFunc\"", rs.getString("data"))).equals(Tools.regmatch("\"hash\";.:..:\"(.*)\";.:.:\"salt\"", rs.getString("data")))) { exist = true; } } while (rs.next()); } rs.close(); } catch (SQLException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return exist; }
diff --git a/src/org/broad/igv/ui/action/FitDataToWindowMenuAction.java b/src/org/broad/igv/ui/action/FitDataToWindowMenuAction.java index 7399282c2..1ced49afa 100644 --- a/src/org/broad/igv/ui/action/FitDataToWindowMenuAction.java +++ b/src/org/broad/igv/ui/action/FitDataToWindowMenuAction.java @@ -1,125 +1,125 @@ /* * Copyright (c) 2007-2011 by The Broad Institute of MIT and Harvard. All Rights Reserved. * * This software is licensed under the terms of the GNU Lesser General Public License (LGPL), * Version 2.1 which is available at http://www.opensource.org/licenses/lgpl-2.1.php. * * THE SOFTWARE IS PROVIDED "AS IS." THE BROAD AND MIT MAKE NO REPRESENTATIONS OR * WARRANTES OF ANY KIND CONCERNING THE SOFTWARE, EXPRESS OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, WHETHER * OR NOT DISCOVERABLE. IN NO EVENT SHALL THE BROAD OR MIT, OR THEIR RESPECTIVE * TRUSTEES, DIRECTORS, OFFICERS, EMPLOYEES, AND AFFILIATES BE LIABLE FOR ANY DAMAGES * OF ANY KIND, INCLUDING, WITHOUT LIMITATION, INCIDENTAL OR CONSEQUENTIAL DAMAGES, * ECONOMIC DAMAGES OR INJURY TO PROPERTY AND LOST PROFITS, REGARDLESS OF WHETHER * THE BROAD OR MIT SHALL BE ADVISED, SHALL HAVE OTHER REASON TO KNOW, OR IN FACT * SHALL KNOW OF THE POSSIBILITY OF THE FOREGOING. */ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.broad.igv.ui.action; import org.apache.log4j.Logger; import org.broad.igv.track.Track; import org.broad.igv.track.TrackGroup; import org.broad.igv.ui.IGV; import org.broad.igv.ui.UIConstants; import org.broad.igv.ui.panel.DataPanelContainer; import org.broad.igv.ui.panel.TrackPanel; import org.broad.igv.ui.panel.TrackPanelScrollPane; import java.awt.event.ActionEvent; import java.util.Collection; import java.util.List; /** * @author jrobinso */ public class FitDataToWindowMenuAction extends MenuAction { static Logger log = Logger.getLogger(FitDataToWindowMenuAction.class); IGV mainFrame; public FitDataToWindowMenuAction(String label, int mnemonic, IGV mainFrame) { super(label, null, mnemonic); this.mainFrame = mainFrame; } @Override /** * The action method. A swing worker is used, so "invoke later" and explicit * threads are not neccessary. * */ public void actionPerformed(ActionEvent e) { for (TrackPanel tp : IGV.getInstance().getTrackPanels()) { fitTracksToPanel(tp.getScrollPane().getDataPanel()); } mainFrame.doRefresh(); } /** * Adjust the height of tracks so that all tracks fit in the available * height of the panel. This is not possible in all cases as the * minimum height for tracks is respected. * * @param dataPanel * @return */ private boolean fitTracksToPanel(DataPanelContainer dataPanel) { boolean success = true; int availableHeight = dataPanel.getVisibleHeight(); int visibleTrackCount = 0; // Process data tracks first Collection<TrackGroup> groups = dataPanel.getTrackGroups(); // Count visible tracks. for (TrackGroup group : groups) { List<Track> tracks = group.getTracks(); for (Track track : tracks) { if (track.isVisible()) { ++visibleTrackCount; } } } // Auto resize the height of the visible tracks if (visibleTrackCount > 0) { int groupGapHeight = (groups.size() + 1) * UIConstants.groupGap; double adjustedAvailableHeight = Math.max(1, availableHeight - groupGapHeight); double delta = adjustedAvailableHeight / visibleTrackCount; // Minimum track height is 1 if (delta < 1) { delta = 1; } int iTotal = 0; double target = 0; for (TrackGroup group : groups) { List<Track> tracks = group.getTracks(); for (Track track : tracks) { target += delta; int height = (int) (target - iTotal); - track.setHeight(height); + track.setHeight(height, true); iTotal += height; } } } return success; } }
true
true
private boolean fitTracksToPanel(DataPanelContainer dataPanel) { boolean success = true; int availableHeight = dataPanel.getVisibleHeight(); int visibleTrackCount = 0; // Process data tracks first Collection<TrackGroup> groups = dataPanel.getTrackGroups(); // Count visible tracks. for (TrackGroup group : groups) { List<Track> tracks = group.getTracks(); for (Track track : tracks) { if (track.isVisible()) { ++visibleTrackCount; } } } // Auto resize the height of the visible tracks if (visibleTrackCount > 0) { int groupGapHeight = (groups.size() + 1) * UIConstants.groupGap; double adjustedAvailableHeight = Math.max(1, availableHeight - groupGapHeight); double delta = adjustedAvailableHeight / visibleTrackCount; // Minimum track height is 1 if (delta < 1) { delta = 1; } int iTotal = 0; double target = 0; for (TrackGroup group : groups) { List<Track> tracks = group.getTracks(); for (Track track : tracks) { target += delta; int height = (int) (target - iTotal); track.setHeight(height); iTotal += height; } } } return success; }
private boolean fitTracksToPanel(DataPanelContainer dataPanel) { boolean success = true; int availableHeight = dataPanel.getVisibleHeight(); int visibleTrackCount = 0; // Process data tracks first Collection<TrackGroup> groups = dataPanel.getTrackGroups(); // Count visible tracks. for (TrackGroup group : groups) { List<Track> tracks = group.getTracks(); for (Track track : tracks) { if (track.isVisible()) { ++visibleTrackCount; } } } // Auto resize the height of the visible tracks if (visibleTrackCount > 0) { int groupGapHeight = (groups.size() + 1) * UIConstants.groupGap; double adjustedAvailableHeight = Math.max(1, availableHeight - groupGapHeight); double delta = adjustedAvailableHeight / visibleTrackCount; // Minimum track height is 1 if (delta < 1) { delta = 1; } int iTotal = 0; double target = 0; for (TrackGroup group : groups) { List<Track> tracks = group.getTracks(); for (Track track : tracks) { target += delta; int height = (int) (target - iTotal); track.setHeight(height, true); iTotal += height; } } } return success; }
diff --git a/src/main/java/fi/csc/microarray/client/visualisation/methods/gbrowser/track/SeqBlockTrack.java b/src/main/java/fi/csc/microarray/client/visualisation/methods/gbrowser/track/SeqBlockTrack.java index b5640b684..5d2cef61c 100644 --- a/src/main/java/fi/csc/microarray/client/visualisation/methods/gbrowser/track/SeqBlockTrack.java +++ b/src/main/java/fi/csc/microarray/client/visualisation/methods/gbrowser/track/SeqBlockTrack.java @@ -1,338 +1,338 @@ package fi.csc.microarray.client.visualisation.methods.gbrowser.track; import java.awt.Color; import java.awt.Rectangle; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import fi.csc.microarray.client.visualisation.methods.gbrowser.DataSource; import fi.csc.microarray.client.visualisation.methods.gbrowser.GenomeBrowserConstants; import fi.csc.microarray.client.visualisation.methods.gbrowser.View; import fi.csc.microarray.client.visualisation.methods.gbrowser.dataFetcher.AreaRequestHandler; import fi.csc.microarray.client.visualisation.methods.gbrowser.drawable.Drawable; import fi.csc.microarray.client.visualisation.methods.gbrowser.drawable.RectDrawable; import fi.csc.microarray.client.visualisation.methods.gbrowser.fileFormat.ColumnType; import fi.csc.microarray.client.visualisation.methods.gbrowser.fileFormat.Strand; import fi.csc.microarray.client.visualisation.methods.gbrowser.message.AreaResult; import fi.csc.microarray.client.visualisation.methods.gbrowser.message.BpCoord; import fi.csc.microarray.client.visualisation.methods.gbrowser.message.Cigar; import fi.csc.microarray.client.visualisation.methods.gbrowser.message.ReadPart; import fi.csc.microarray.client.visualisation.methods.gbrowser.message.RegionContent; import fi.csc.microarray.client.visualisation.methods.gbrowser.utils.Sequence; /** * Track that shows actual content of reads using color coding. * */ public class SeqBlockTrack extends Track { public static final Color[] charColors = new Color[] { new Color(64, 192, 64, 128), // A new Color(64, 64, 192, 128), // C new Color(128, 128, 128, 128), // G new Color(192, 64, 64, 128) // T }; private Collection<RegionContent> reads = new TreeSet<RegionContent>(); private List<Integer> occupiedSpace = new ArrayList<Integer>(); private long maxBpLength; private long minBpLength; private DataSource refData; private Collection<RegionContent> refReads = new TreeSet<RegionContent>(); private boolean highlightSNP = false; public SeqBlockTrack(View view, DataSource file, Class<? extends AreaRequestHandler> handler, Color fontColor, long minBpLength, long maxBpLength) { super(view, file, handler); this.minBpLength = minBpLength; this.maxBpLength = maxBpLength; } @Override public Collection<Drawable> getDrawables() { Collection<Drawable> drawables = getEmptyDrawCollection(); occupiedSpace.clear(); // If SNP highlight mode is on, we need reference sequence data char[] refSeq = highlightSNP ? getReferenceArray(refReads, view, strand) : null; // Main loop: Iterate over RegionContent objects (one object corresponds to one read) Iterator<RegionContent> iter = reads.iterator(); while (iter.hasNext()) { RegionContent read = iter.next(); // Remove reads that are not in this view if (!read.region.intercepts(getView().getBpRegion())) { iter.remove(); continue; } // Collect relevant data for this read BpCoord startBp = read.region.start; // Split read into continuous blocks (elements) by using the cigar List<ReadPart> visibleRegions = Cigar.splitVisibleElements(read); for (ReadPart visibleRegion : visibleRegions) { // Skip elements that are not in this view if (!visibleRegion.intercepts(getView().getBpRegion())) { continue; } // Width in basepairs long widthInBps = visibleRegion.getLength(); // Create rectangle covering the correct screen area (x-axis) Rectangle rect = new Rectangle(); rect.x = getView().bpToTrack(visibleRegion.start); rect.width = (int) Math.round(getView().bpWidth() * widthInBps); // Do not draw invisible rectangles if (rect.width < 2) { rect.width = 2; } // Read parts are drawn in order and placed in layers int layer = 0; while (occupiedSpace.size() > layer && occupiedSpace.get(layer) > rect.x + 1) { layer++; } // Read part reserves the space of the layer from end to left corner of the screen int end = rect.x + rect.width; if (occupiedSpace.size() > layer) { occupiedSpace.set(layer, end); } else { occupiedSpace.add(end); } // Now we can decide the y coordinate rect.y = getYCoord(layer, GenomeBrowserConstants.READ_HEIGHT); rect.height = GenomeBrowserConstants.READ_HEIGHT; // Check if we are about to go over the edge of the drawing area boolean lastBeforeMaxStackingDepthCut = getYCoord(layer + 1, GenomeBrowserConstants.READ_HEIGHT) < 0; // Check if we are over the edge of the drawing area if (rect.y < 0) { continue; } // Check if we have enough space for the actual sequence (at least pixel per nucleotide) String seq = visibleRegion.getSequencePart(); if (rect.width < seq.length()) { // Too little space - only show one rectangle for each read part Color color = Color.gray; // Mark last line that will be drawn if (lastBeforeMaxStackingDepthCut) { color = color.brighter(); } drawables.add(new RectDrawable(rect, color, null)); } else { // Enough space - show color coding for each nucleotide // Complement the read if on reverse strand if ((Strand) read.values.get(ColumnType.STRAND) == Strand.REVERSED) { StringBuffer buf = new StringBuffer(seq.toUpperCase()); // Complement seq = buf.toString().replace('A', 'x'). // switch A and T replace('T', 'A').replace('x', 'T'). replace('C', 'x'). // switch C and G replace('G', 'C').replace('x', 'G'); } // Prepare to draw single nucleotides float increment = getView().bpWidth(); float startX = getView().bpToTrackFloat(startBp); // Draw each nucleotide for (int j = 0; j < seq.length(); j++) { char letter = seq.charAt(j); long refIndex = j; // Choose a color depending on viewing mode Color bg = Color.white; long posInRef = startBp.bp.intValue() + refIndex - getView().getBpRegion().start.bp.intValue(); if (highlightSNP && posInRef >= 0 && posInRef < refSeq.length && Character.toLowerCase(refSeq[(int)posInRef]) == Character.toLowerCase(letter)) { bg = Color.gray; } else { switch (letter) { case 'A': bg = charColors[0]; break; case 'C': bg = charColors[1]; break; case 'G': bg = charColors[2]; break; case 'T': bg = charColors[3]; break; } } // Tell that we have reached max. stacking depth if (lastBeforeMaxStackingDepthCut) { bg = bg.brighter(); } // Draw rectangle - int x = Math.round(startX + refIndex * increment); + int x = Math.round(startX + Math.round(((float)refIndex) * increment)); int width = increment >= 1.0f ? Math.round(increment) : 1; drawables.add(new RectDrawable(x, rect.y, width, GenomeBrowserConstants.READ_HEIGHT, bg, null)); } } } } return drawables; } private int getYCoord(int layer, int height) { return (int) (getView().getTrackHeight() - ((layer + 1) * (height + GenomeBrowserConstants.SPACE_BETWEEN_READS))); } public void processAreaResult(AreaResult<RegionContent> areaResult) { // Check that areaResult has same concised status (currently always false) and correct strand if (areaResult.status.file == file && areaResult.status.concise == isConcised() && areaResult.content.values.get(ColumnType.STRAND) == getStrand()) { // Add this to queue of RegionContents to be processed this.reads.add(areaResult.content); getView().redraw(); } // "Spy" on reference sequence data, if available if (areaResult.status.file == refData) { this.refReads.add(areaResult.content); } } @Override public Integer getHeight() { if (isVisible()) { return super.getHeight(); } else { return 0; } } @Override public boolean isStretchable() { return isVisible(); // Stretchable unless hidden } @Override public boolean isVisible() { // visible region is not suitable return (super.isVisible() && getView().getBpRegion().getLength() > minBpLength && getView().getBpRegion().getLength() <= maxBpLength); } @Override public Map<DataSource, Set<ColumnType>> requestedData() { HashMap<DataSource, Set<ColumnType>> datas = new HashMap<DataSource, Set<ColumnType>>(); datas.put(file, new HashSet<ColumnType>(Arrays.asList(new ColumnType[] { ColumnType.SEQUENCE, ColumnType.STRAND, ColumnType.CIGAR }))); // We might also need reference sequence data if (highlightSNP) { datas.put(refData, new HashSet<ColumnType>(Arrays.asList(new ColumnType[] { ColumnType.SEQUENCE }))); } return datas; } @Override public boolean isConcised() { return false; } /** * Enable SNP highlighting and set reference data. * * @param highlightSNP * @see SeqBlockTrack.setReferenceSeq */ public void enableSNPHighlight(DataSource file, Class<? extends AreaRequestHandler> handler) { // turn on highlighting mode highlightSNP = true; // set reference data refData = file; view.getQueueManager().createQueue(file, handler); view.getQueueManager().addResultListener(file, this); } /** * Disable SNP highlighting. * * @param file */ public void disableSNPHiglight(DataSource file) { // turn off highlighting mode highlightSNP = false; } /** * Convert reference sequence reads to a char array. */ public static char[] getReferenceArray(Collection<RegionContent> refReads, View view, Strand strand) { char[] refSeq = new char[0]; Iterator<RegionContent> iter = refReads.iterator(); refSeq = new char[view.getBpRegion().getLength().intValue() + 1]; int startBp = view.getBpRegion().start.bp.intValue(); int endBp = view.getBpRegion().end.bp.intValue(); RegionContent read; while (iter.hasNext()) { read = iter.next(); if (!read.region.intercepts(view.getBpRegion())) { iter.remove(); continue; } // we might need to reverse reference sequence char[] readBases; if (strand == Strand.REVERSED) { readBases = Sequence.complement((String) read.values.get(ColumnType.SEQUENCE)).toCharArray(); } else { readBases = ((String) read.values.get(ColumnType.SEQUENCE)).toCharArray(); } int readStart = read.region.start.bp.intValue(); int readNum = 0; int nextPos = 0; for (char c : readBases) { nextPos = readStart + readNum++; if (nextPos >= startBp && nextPos <= endBp) { refSeq[nextPos - startBp] = c; } } } return refSeq; } @Override public String getName() { return "Reads"; } }
true
true
public Collection<Drawable> getDrawables() { Collection<Drawable> drawables = getEmptyDrawCollection(); occupiedSpace.clear(); // If SNP highlight mode is on, we need reference sequence data char[] refSeq = highlightSNP ? getReferenceArray(refReads, view, strand) : null; // Main loop: Iterate over RegionContent objects (one object corresponds to one read) Iterator<RegionContent> iter = reads.iterator(); while (iter.hasNext()) { RegionContent read = iter.next(); // Remove reads that are not in this view if (!read.region.intercepts(getView().getBpRegion())) { iter.remove(); continue; } // Collect relevant data for this read BpCoord startBp = read.region.start; // Split read into continuous blocks (elements) by using the cigar List<ReadPart> visibleRegions = Cigar.splitVisibleElements(read); for (ReadPart visibleRegion : visibleRegions) { // Skip elements that are not in this view if (!visibleRegion.intercepts(getView().getBpRegion())) { continue; } // Width in basepairs long widthInBps = visibleRegion.getLength(); // Create rectangle covering the correct screen area (x-axis) Rectangle rect = new Rectangle(); rect.x = getView().bpToTrack(visibleRegion.start); rect.width = (int) Math.round(getView().bpWidth() * widthInBps); // Do not draw invisible rectangles if (rect.width < 2) { rect.width = 2; } // Read parts are drawn in order and placed in layers int layer = 0; while (occupiedSpace.size() > layer && occupiedSpace.get(layer) > rect.x + 1) { layer++; } // Read part reserves the space of the layer from end to left corner of the screen int end = rect.x + rect.width; if (occupiedSpace.size() > layer) { occupiedSpace.set(layer, end); } else { occupiedSpace.add(end); } // Now we can decide the y coordinate rect.y = getYCoord(layer, GenomeBrowserConstants.READ_HEIGHT); rect.height = GenomeBrowserConstants.READ_HEIGHT; // Check if we are about to go over the edge of the drawing area boolean lastBeforeMaxStackingDepthCut = getYCoord(layer + 1, GenomeBrowserConstants.READ_HEIGHT) < 0; // Check if we are over the edge of the drawing area if (rect.y < 0) { continue; } // Check if we have enough space for the actual sequence (at least pixel per nucleotide) String seq = visibleRegion.getSequencePart(); if (rect.width < seq.length()) { // Too little space - only show one rectangle for each read part Color color = Color.gray; // Mark last line that will be drawn if (lastBeforeMaxStackingDepthCut) { color = color.brighter(); } drawables.add(new RectDrawable(rect, color, null)); } else { // Enough space - show color coding for each nucleotide // Complement the read if on reverse strand if ((Strand) read.values.get(ColumnType.STRAND) == Strand.REVERSED) { StringBuffer buf = new StringBuffer(seq.toUpperCase()); // Complement seq = buf.toString().replace('A', 'x'). // switch A and T replace('T', 'A').replace('x', 'T'). replace('C', 'x'). // switch C and G replace('G', 'C').replace('x', 'G'); } // Prepare to draw single nucleotides float increment = getView().bpWidth(); float startX = getView().bpToTrackFloat(startBp); // Draw each nucleotide for (int j = 0; j < seq.length(); j++) { char letter = seq.charAt(j); long refIndex = j; // Choose a color depending on viewing mode Color bg = Color.white; long posInRef = startBp.bp.intValue() + refIndex - getView().getBpRegion().start.bp.intValue(); if (highlightSNP && posInRef >= 0 && posInRef < refSeq.length && Character.toLowerCase(refSeq[(int)posInRef]) == Character.toLowerCase(letter)) { bg = Color.gray; } else { switch (letter) { case 'A': bg = charColors[0]; break; case 'C': bg = charColors[1]; break; case 'G': bg = charColors[2]; break; case 'T': bg = charColors[3]; break; } } // Tell that we have reached max. stacking depth if (lastBeforeMaxStackingDepthCut) { bg = bg.brighter(); } // Draw rectangle int x = Math.round(startX + refIndex * increment); int width = increment >= 1.0f ? Math.round(increment) : 1; drawables.add(new RectDrawable(x, rect.y, width, GenomeBrowserConstants.READ_HEIGHT, bg, null)); } } } } return drawables; }
public Collection<Drawable> getDrawables() { Collection<Drawable> drawables = getEmptyDrawCollection(); occupiedSpace.clear(); // If SNP highlight mode is on, we need reference sequence data char[] refSeq = highlightSNP ? getReferenceArray(refReads, view, strand) : null; // Main loop: Iterate over RegionContent objects (one object corresponds to one read) Iterator<RegionContent> iter = reads.iterator(); while (iter.hasNext()) { RegionContent read = iter.next(); // Remove reads that are not in this view if (!read.region.intercepts(getView().getBpRegion())) { iter.remove(); continue; } // Collect relevant data for this read BpCoord startBp = read.region.start; // Split read into continuous blocks (elements) by using the cigar List<ReadPart> visibleRegions = Cigar.splitVisibleElements(read); for (ReadPart visibleRegion : visibleRegions) { // Skip elements that are not in this view if (!visibleRegion.intercepts(getView().getBpRegion())) { continue; } // Width in basepairs long widthInBps = visibleRegion.getLength(); // Create rectangle covering the correct screen area (x-axis) Rectangle rect = new Rectangle(); rect.x = getView().bpToTrack(visibleRegion.start); rect.width = (int) Math.round(getView().bpWidth() * widthInBps); // Do not draw invisible rectangles if (rect.width < 2) { rect.width = 2; } // Read parts are drawn in order and placed in layers int layer = 0; while (occupiedSpace.size() > layer && occupiedSpace.get(layer) > rect.x + 1) { layer++; } // Read part reserves the space of the layer from end to left corner of the screen int end = rect.x + rect.width; if (occupiedSpace.size() > layer) { occupiedSpace.set(layer, end); } else { occupiedSpace.add(end); } // Now we can decide the y coordinate rect.y = getYCoord(layer, GenomeBrowserConstants.READ_HEIGHT); rect.height = GenomeBrowserConstants.READ_HEIGHT; // Check if we are about to go over the edge of the drawing area boolean lastBeforeMaxStackingDepthCut = getYCoord(layer + 1, GenomeBrowserConstants.READ_HEIGHT) < 0; // Check if we are over the edge of the drawing area if (rect.y < 0) { continue; } // Check if we have enough space for the actual sequence (at least pixel per nucleotide) String seq = visibleRegion.getSequencePart(); if (rect.width < seq.length()) { // Too little space - only show one rectangle for each read part Color color = Color.gray; // Mark last line that will be drawn if (lastBeforeMaxStackingDepthCut) { color = color.brighter(); } drawables.add(new RectDrawable(rect, color, null)); } else { // Enough space - show color coding for each nucleotide // Complement the read if on reverse strand if ((Strand) read.values.get(ColumnType.STRAND) == Strand.REVERSED) { StringBuffer buf = new StringBuffer(seq.toUpperCase()); // Complement seq = buf.toString().replace('A', 'x'). // switch A and T replace('T', 'A').replace('x', 'T'). replace('C', 'x'). // switch C and G replace('G', 'C').replace('x', 'G'); } // Prepare to draw single nucleotides float increment = getView().bpWidth(); float startX = getView().bpToTrackFloat(startBp); // Draw each nucleotide for (int j = 0; j < seq.length(); j++) { char letter = seq.charAt(j); long refIndex = j; // Choose a color depending on viewing mode Color bg = Color.white; long posInRef = startBp.bp.intValue() + refIndex - getView().getBpRegion().start.bp.intValue(); if (highlightSNP && posInRef >= 0 && posInRef < refSeq.length && Character.toLowerCase(refSeq[(int)posInRef]) == Character.toLowerCase(letter)) { bg = Color.gray; } else { switch (letter) { case 'A': bg = charColors[0]; break; case 'C': bg = charColors[1]; break; case 'G': bg = charColors[2]; break; case 'T': bg = charColors[3]; break; } } // Tell that we have reached max. stacking depth if (lastBeforeMaxStackingDepthCut) { bg = bg.brighter(); } // Draw rectangle int x = Math.round(startX + Math.round(((float)refIndex) * increment)); int width = increment >= 1.0f ? Math.round(increment) : 1; drawables.add(new RectDrawable(x, rect.y, width, GenomeBrowserConstants.READ_HEIGHT, bg, null)); } } } } return drawables; }
diff --git a/src/main/java/net/aufdemrand/denizen/scripts/helpers/ArgumentHelper.java b/src/main/java/net/aufdemrand/denizen/scripts/helpers/ArgumentHelper.java index eb937a0d2..ad2820a1d 100644 --- a/src/main/java/net/aufdemrand/denizen/scripts/helpers/ArgumentHelper.java +++ b/src/main/java/net/aufdemrand/denizen/scripts/helpers/ArgumentHelper.java @@ -1,310 +1,310 @@ package net.aufdemrand.denizen.scripts.helpers; import java.util.Arrays; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import net.aufdemrand.denizen.Denizen; import net.aufdemrand.denizen.scripts.ScriptEngine.QueueType; import net.aufdemrand.denizen.utilities.debugging.Debugger; /** * The dScript Argument Helper will aide you in parsing and formatting arguments from a ScriptEntry. The Argument Helper (aH) * object reference is included with AbstractCommand, AbstractRequirement, AbstractActivity and AbstractTrigger. * * @author Jeremy Schroeder * */ public class ArgumentHelper { Debugger dB; Denizen denizen; public enum ArgumentType { String, Word, Integer, Double, Float, Boolean, Custom } public ArgumentHelper(Denizen denizen) { this.denizen = denizen; dB = denizen.getDebugger(); } /** * dScript Argument JAVA Parse Method JAVA Get Method Returns Pattern Matcher (Case_Insensitive) * +------------------------+----------------------+---------------------+-------------+---------------------------------------------- * NPCID:# parsed in executer done in executer DenizenNPC (matched against current NPCs) * PLAYER:player_name parsed in executer done in executer Player (matched against online/offline Players) * TOGGLE:true|false matchesToggle(arg) getBooleanFrom(arg) boolean trigger:(true|false) * DURATION:# matchesDuration(arg) getIntegerFrom(arg) int duration:\d+ * SCRIPT:script_name matchesScript(arg) getStringFrom(arg) String script:.+ matched against loaded Scripts * LOCATION:x#,y#,z#,world matchesLocation(arg) getLocationFrom(arg) Location location:\d+,\d+,\d+,\w+ * QUEUE:Queue_Type matchesQueueType(arg) getQueueFrom(arg) QueueType queue:(?:player|task|denizen) * QTY:# matchesQuantity(arg) getQuantityFrom(arg) int qty:\d+ * ITEM:Material_Type(:#) matchesItem(arg) getItemFrom(arg) ItemStack item:\.+:(\d+) matched against Material_Type * ITEM:#(:#) matchesItem(arg) getItemFrom(arg) ItemStack item:\d+|(\d+:\d+) * # (Integer) matchesInteger(arg) getIntegerFrom(arg) int \d+ * #.# (Double) matchesDouble(arg) getDoubleFrom(arg) double \d+\.\d+ * #.## (Float) matchesFloat(arg) getFloatFrom(arg) float ^[-+]?[0-9]+[.]?[0-9]*([eE][-+]?[0-9]+) * 'NPCs rule!' (String) matchesString(arg) getStringFrom(arg) String \.+ * single_word (Word) matchesWord(arg) getStringFrom(arg) String \w+ * string|string2 (List) matchesString(arg) getListFrom(arg) List<String> String.split("|") */ final Pattern durationPattern = Pattern.compile("duration:(\\d+)", Pattern.CASE_INSENSITIVE); final Pattern scriptPattern = Pattern.compile("script:.+", Pattern.CASE_INSENSITIVE); final Pattern locationPattern = Pattern.compile("location:(?:-|)\\d+,(?:-|)\\d+,(?:-|)\\d+,\\w+", Pattern.CASE_INSENSITIVE); final Pattern queuetypePattern = Pattern.compile("(?:queue|queuetype):(?:player|player_task|npc)", Pattern.CASE_INSENSITIVE); final Pattern quantityPattern = Pattern.compile("qty:(?:-|)\\d+", Pattern.CASE_INSENSITIVE); final Pattern togglePattern = Pattern.compile("toggle:(true|false)", Pattern.CASE_INSENSITIVE); final Pattern materialPattern = Pattern.compile("[a-zA-Z\\x5F]+", Pattern.CASE_INSENSITIVE); final Pattern materialDataPattern = Pattern.compile("[a-zA-Z]+?:\\d+", Pattern.CASE_INSENSITIVE); final Pattern itemIdPattern = Pattern.compile("(?:(item:)|)\\d+"); final Pattern itemIdDataPattern = Pattern.compile("(?:(item:)|)(\\d+)(:)(\\d+)"); final Pattern integerPattern = Pattern.compile("(?:-|)\\d+"); final Pattern doublePattern = Pattern.compile("(?:-|)\\d+(\\.\\d+|)"); final Pattern floatPattern = Pattern.compile("^[-+]?[0-9]+[.]?[0-9]*([eE][-+]?[0-9]+)?$"); final Pattern stringPattern = Pattern.compile("\\.+", Pattern.CASE_INSENSITIVE); final Pattern wordPattern = Pattern.compile("\\w+", Pattern.CASE_INSENSITIVE); /* * Argument Matchers */ /** * In practice, the remaining standard arguments should be used whenever possible to keep things consistant across the entire * Denizen experience. Should you need to use custom arguments, however, there is support for that as well. After all, while using * standard arguments is nice, you should never reach. Arguments should make as much sense to the user as possible. * * Small code examples: * 0 if (aH.matchesArg("HARD", arg)) * 1 hardness = Hardness.HARD; * * 0 if (aH.matchesValueArg("HARDNESS", arg, ArgumentType.Word)) * 1 try { hardness = Hardness.valueOf(aH.getStringFrom(arg));} * 2 catch (Exception e) { dB.echoError("Invalid HARDNESS!")} * * * Methods for dealing with Custom Denizen Arguments * * DenizenScript Argument JAVA Parse Method JAVA Get Method Returns * +------------------------+-------------------------------------------------+---------------------+--------------------------------- * CUSTOM_ARGUMENT matchesArg("CUSTOM_ARGUMENT", arg) None. No value boolean * CSTM_ARG:value MatchesValueArg("CSTM_ARG", arg, ArgumentType) get____From(arg) depends on get method * * * Note: ArgumentType will filter the type of value to match to. If anything should be excepted as the value, or you plan * on parsing the value yourself, use ArgumentType.Custom. * * Valid ArgumentTypes: ArgumentType.String, ArgumentType.Word, ArgumentType.Integer, ArgumentType.Double, ArgumentType.Float, * and ArgumentType.Custom * */ Matcher m; public boolean matchesValueArg(String argumentName, String argument, ArgumentType type) { if (argument == null) return false; if (argument.split(":").length == 1) return false; - if (!argument.toUpperCase().contains(argumentName.toUpperCase() + ":")) return false; + if (!argument.split(":")[0].equalsIgnoreCase(argumentName)) return false; argument = argument.split(":", 2)[1]; switch (type) { case Word: m = wordPattern.matcher(argument); return m.matches(); case Integer: m = integerPattern.matcher(argument); return m.matches(); case Double: m = doublePattern.matcher(argument); return m.matches(); case Float: m = floatPattern.matcher(argument); return m.matches(); case Boolean: if (argument.equalsIgnoreCase("true")) return true; else return false; default: return true; } } public boolean matchesArg(String name, String argument) { if (argument.toUpperCase().equals(name.toUpperCase())) return true; return false; } public boolean matchesInteger(String argument) { m = integerPattern.matcher(argument); return m.matches(); } public boolean matchesDouble(String argument) { m = doublePattern.matcher(argument); return m.matches(); } public boolean matchesLocation(String argument) { m = locationPattern.matcher(argument); return m.matches(); } public boolean matchesItem(String argument) { m = itemIdPattern.matcher(argument); if (m.matches()) return true; m = itemIdDataPattern.matcher(argument); if (m.matches()) return true; // Strip ITEM: to check against a valid Material if (argument.toUpperCase().startsWith("ITEM:")) argument = argument.substring(5); m = materialPattern.matcher(argument); if (m.matches()) { // Check against Materials for (Material mat : Material.values()) if (mat.name().equalsIgnoreCase(argument)) return true; } m = materialDataPattern.matcher(argument); if (m.matches()) { if (argument.split(":").length == 2) argument = argument.split(":")[0]; for (Material mat : Material.values()) if (mat.name().equalsIgnoreCase(argument)) return true; } // No match! return false; } public boolean matchesDuration(String regex) { m = durationPattern.matcher(regex); return m.matches(); } public boolean matchesToggle(String regex) { m = togglePattern.matcher(regex); return m.matches(); } public boolean matchesQueueType(String regex) { m = queuetypePattern.matcher(regex); return m.matches(); } public boolean matchesScript(String regex) { m = scriptPattern.matcher(regex); // Check if script exists by looking for Script Name: // Type: ... if (m.matches() && denizen.getScripts().contains(regex.toUpperCase() + ".TYPE")) return true; return false; } public boolean matchesQuantity(String regex) { m = quantityPattern.matcher(regex); return m.matches(); } /* * Argument Extractors */ public boolean getBooleanFrom(String argument) { if (argument.split(":").length >= 2) return Boolean.valueOf(argument.split(":")[1]).booleanValue(); else return false; } public String getStringFrom(String argument) { if (argument.split(":").length >= 2) return argument.split(":")[1]; else return argument; } public Player getPlayerFrom(String argument) { if (argument.split(":").length >= 2) return denizen.getServer().getPlayer(argument.split(":")[1]); else return denizen.getServer().getPlayer(argument); } public Location getLocationFrom(String argument) { argument = argument.split(":", 2)[1]; String[] num = argument.split(","); Location location = null; try { location = new Location(Bukkit.getWorld(num[3]), Double.valueOf(num[0]), Double.valueOf(num[1]), Double.valueOf(num[2])); } catch (Exception e) { dB.echoError("Invalid Location!"); return null; } return location; } public List<String> getListFrom(String argument) { return Arrays.asList(argument.split("\\|")); } public QueueType getQueueFrom(String argument) { try { if (argument.split(":").length >= 2) return QueueType.valueOf(argument.split(":")[1].toUpperCase()); else return QueueType.valueOf(argument.toUpperCase()); } catch (Exception e) { dB.echoError("Invalid Queuetype!"); } return null; } public Integer getIntegerFrom(String argument) { try { if (argument.split(":").length >= 2) return Integer.valueOf(argument.split(":")[1]); else return Integer.valueOf(argument); } catch (Exception e) { return 0; } } public Float getFloatFrom(String argument) { try { if (argument.split(":").length >= 2) return Float.valueOf(argument.split(":")[1]); else return Float.valueOf(argument); } catch (Exception e) { return 0f; } } public Double getDoubleFrom(String argument) { try { if (argument.split(":").length >= 2) return Double.valueOf(argument.split(":")[1]); else return Double.valueOf(argument); } catch (Exception e) { return 0.00; } } public ItemStack getItemFrom(String thisArg) { m = itemIdPattern.matcher(thisArg); Matcher m2 = itemIdDataPattern.matcher(thisArg); Matcher m3 = materialPattern.matcher(thisArg); Matcher m4 = materialDataPattern.matcher(thisArg); ItemStack stack = null; try { if (m.matches()) stack = new ItemStack(Integer.valueOf(thisArg)); else if (m2.matches()) { stack = new ItemStack(Integer.valueOf(thisArg.split(":")[0])); stack.setDurability(Short.valueOf(thisArg.split(":")[1])); } else if (m3.matches()) { stack = new ItemStack(Material.valueOf(thisArg.toUpperCase())); } else if (m4.matches()) { stack = new ItemStack(Material.valueOf(thisArg.split(":")[0].toUpperCase())); stack.setDurability(Short.valueOf(thisArg.split(":")[1])); } } catch (Exception e) { dB.echoError("Invalid item!"); if (denizen.getDebugger().showStackTraces) e.printStackTrace(); } return stack; } }
true
true
public boolean matchesValueArg(String argumentName, String argument, ArgumentType type) { if (argument == null) return false; if (argument.split(":").length == 1) return false; if (!argument.toUpperCase().contains(argumentName.toUpperCase() + ":")) return false; argument = argument.split(":", 2)[1]; switch (type) { case Word: m = wordPattern.matcher(argument); return m.matches(); case Integer: m = integerPattern.matcher(argument); return m.matches(); case Double: m = doublePattern.matcher(argument); return m.matches(); case Float: m = floatPattern.matcher(argument); return m.matches(); case Boolean: if (argument.equalsIgnoreCase("true")) return true; else return false; default: return true; } }
public boolean matchesValueArg(String argumentName, String argument, ArgumentType type) { if (argument == null) return false; if (argument.split(":").length == 1) return false; if (!argument.split(":")[0].equalsIgnoreCase(argumentName)) return false; argument = argument.split(":", 2)[1]; switch (type) { case Word: m = wordPattern.matcher(argument); return m.matches(); case Integer: m = integerPattern.matcher(argument); return m.matches(); case Double: m = doublePattern.matcher(argument); return m.matches(); case Float: m = floatPattern.matcher(argument); return m.matches(); case Boolean: if (argument.equalsIgnoreCase("true")) return true; else return false; default: return true; } }
diff --git a/src/main/java/loci/maven/plugin/cppwrap/CppWrapMojo.java b/src/main/java/loci/maven/plugin/cppwrap/CppWrapMojo.java index 75744e4..e2e7c80 100644 --- a/src/main/java/loci/maven/plugin/cppwrap/CppWrapMojo.java +++ b/src/main/java/loci/maven/plugin/cppwrap/CppWrapMojo.java @@ -1,264 +1,265 @@ // // CppWrapMojo.java // /* C++ Wrapper Maven plugin for generating C++ proxy classes for a Java library. Copyright (c) 2011, UW-Madison LOCI 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 UW-Madison LOCI 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 HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package loci.maven.plugin.cppwrap; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Arrays; import loci.jar2lib.Jar2Lib; import loci.jar2lib.VelocityException; import org.apache.maven.artifact.Artifact; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.project.MavenProject; /** * Goal which creates a C++ project wrapping a Maven Java project. * * Portions of this mojo were adapted from exec-maven-plugin's ExecJavaMojo. * * <dl><dt><b>Source code:</b></dt> * <dd><a href="http://dev.loci.wisc.edu/trac/software/browser/trunk/projects/cppwrap-maven-plugin/src/main/java/loci/maven/plugin/cppwrap/CppWrapMojo.java">Trac</a>, * <a href="http://dev.loci.wisc.edu/svn/software/trunk/projects/cppwrap-maven-plugin/src/main/java/loci/maven/plugin/cppwrap/CppWrapMojo.java">SVN</a></dd></dl> * * @author Curtis Rueden * * @goal wrap */ public class CppWrapMojo extends AbstractMojo { /** * The Maven project to wrap. * * @parameter expression="${project}" * @required * @readonly */ private MavenProject project; /** * Additional dependencies to wrap as part of the C++ project. * * For example, if a project human:body:jar:1.0 depends on projects * human:head:jar:1.0, human:arms:jar:1.0 and human:legs:jar:1.0, * and you wish to wrap human and head, but not arms or legs, * you could specify human:head:jar:1.0 as an extra artifact here. * * @parameter expression="${cppwrap.libraries}" */ private String[] libraries; /** * Path to conflicts list of Java constants to rename, * to avoid name collisions. * * @parameter expression="${cppwrap.conflictsFile}" * default-value="src/main/cppwrap/conflicts.txt" */ private File conflictsFile; /** * Path to header file to prepend to each C++ source file. * * @parameter expression="${cppwrap.headerFile}" * default-value="LICENSE.txt" */ private File headerFile; /** * Path to folder containing additional C++ source code. * * Each .cpp file in the folder should contain a main method. * These files will then be compiled as part of the build process, * as individual executables. * * @parameter expression="${cppwrap.sourceDir}" * default-value="src/main/cppwrap" */ private File sourceDir; /** * Path to output folder for C++ project. * * @parameter expression="${cppwrap.outputDir}" * default-value="target/cppwrap" */ private File outputDir; /** * Path to a text file listing core Java classes to be ensured * proxied. * * @parameter expression="${cppwrap.coreFile}" * default-value="src/main/cppwrap/core.txt" */ private File coreFile; /** * Path to text file, the contents of which will be * appended to resulting CMakeLists.txt for this project. * * @parameter expression="${cppwrap.extrasFile}" * default-value="src/main/cppwrap/extras.txt" */ private File extrasFile; @Override public void execute() throws MojoExecutionException { final String artifactId = project.getArtifactId(); final String projectId = artifactId.replaceAll("[^\\w\\-]", "_"); final String projectName = project.getName(); final List<String> libraryJars = getLibraryJars(); final List<String> classpathJars = getClasspathJars(); final String conflictsPath = conflictsFile.exists() ? conflictsFile.getPath() : null; final String headerPath = headerFile.exists() ? headerFile.getPath() : null; final String sourcePath = sourceDir.isDirectory() ? sourceDir.getPath() : null; final String outputPath = outputDir.getPath(); final String extrasPath = extrasFile.exists() ? extrasFile.getPath() : null; final String corePath = coreFile.exists() ? coreFile.getPath() : null; final Jar2Lib jar2lib = new Jar2Lib() { @Override protected void log(String message) { getLog().info(message); } }; jar2lib.setProjectId(projectId); jar2lib.setProjectName(projectName); jar2lib.setLibraryJars(libraryJars); jar2lib.setClasspathJars(classpathJars); jar2lib.setConflictsPath(conflictsPath); jar2lib.setHeaderPath(headerPath); jar2lib.setSourcePath(sourcePath); jar2lib.setOutputPath(outputPath); jar2lib.setExtrasPath(extrasPath); jar2lib.setCorePath(corePath); try { jar2lib.execute(); } catch (IOException e) { throw new MojoExecutionException("Error invoking jar2lib", e); } catch (VelocityException e) { throw new MojoExecutionException("Error invoking jar2lib", e); } } private List<String> getLibraryJars() throws MojoExecutionException { final List<String> jars = new ArrayList<String>(); // add project artifact + // TODO: Try project.getArtifacts()? final File projectArtifact = project.getArtifact().getFile(); if (projectArtifact == null || !projectArtifact.exists()) { throw new MojoExecutionException( "Must execute package target first (e.g., mvn package cppwrap:wrap)."); } jars.add(projectArtifact.getPath()); // add explicitly enumerated dependencies if (libraries != null) { @SuppressWarnings("unchecked") final List<Artifact> artifacts = project.getRuntimeArtifacts(); ArrayList<String> libs = new ArrayList<String>(Arrays.asList(libraries)); Collections.sort(artifacts, new ArtComparator()); Collections.sort(libs); int libIndex = 0; int artIndex = 0; boolean done = artIndex == artifacts.size(); while (!done) { if(libs.get(libIndex).compareTo(artifacts.get(artIndex).getId()) == 0) { File artifactFile = artifacts.get(artIndex).getFile(); if (!artifactFile.exists()) { throw new MojoExecutionException("Artifact not found: " + artifactFile); } jars.add(artifactFile.getPath()); libIndex++; } else { artIndex++; } if(artIndex == artifacts.size()) { throw new MojoExecutionException("Invalid library dependency: " + libs.get(libIndex)); } done = libIndex == libraries.length; } } return jars; } private List<String> getClasspathJars() { final List<String> jars = new ArrayList<String>(); // add project runtime dependencies @SuppressWarnings("unchecked") final List<Artifact> artifacts = project.getRuntimeArtifacts(); for (final Artifact classPathElement : artifacts) { jars.add(classPathElement.getFile().getPath()); } return jars; } private class ArtComparator implements Comparator { public int compare (Object obj1, Object obj2) { Artifact art1 = (Artifact)obj1; Artifact art2 = (Artifact)obj2; return art1.getId().compareTo(art2.getId()); } } }
true
true
private List<String> getLibraryJars() throws MojoExecutionException { final List<String> jars = new ArrayList<String>(); // add project artifact final File projectArtifact = project.getArtifact().getFile(); if (projectArtifact == null || !projectArtifact.exists()) { throw new MojoExecutionException( "Must execute package target first (e.g., mvn package cppwrap:wrap)."); } jars.add(projectArtifact.getPath()); // add explicitly enumerated dependencies if (libraries != null) { @SuppressWarnings("unchecked") final List<Artifact> artifacts = project.getRuntimeArtifacts(); ArrayList<String> libs = new ArrayList<String>(Arrays.asList(libraries)); Collections.sort(artifacts, new ArtComparator()); Collections.sort(libs); int libIndex = 0; int artIndex = 0; boolean done = artIndex == artifacts.size(); while (!done) { if(libs.get(libIndex).compareTo(artifacts.get(artIndex).getId()) == 0) { File artifactFile = artifacts.get(artIndex).getFile(); if (!artifactFile.exists()) { throw new MojoExecutionException("Artifact not found: " + artifactFile); } jars.add(artifactFile.getPath()); libIndex++; } else { artIndex++; } if(artIndex == artifacts.size()) { throw new MojoExecutionException("Invalid library dependency: " + libs.get(libIndex)); } done = libIndex == libraries.length; } } return jars; }
private List<String> getLibraryJars() throws MojoExecutionException { final List<String> jars = new ArrayList<String>(); // add project artifact // TODO: Try project.getArtifacts()? final File projectArtifact = project.getArtifact().getFile(); if (projectArtifact == null || !projectArtifact.exists()) { throw new MojoExecutionException( "Must execute package target first (e.g., mvn package cppwrap:wrap)."); } jars.add(projectArtifact.getPath()); // add explicitly enumerated dependencies if (libraries != null) { @SuppressWarnings("unchecked") final List<Artifact> artifacts = project.getRuntimeArtifacts(); ArrayList<String> libs = new ArrayList<String>(Arrays.asList(libraries)); Collections.sort(artifacts, new ArtComparator()); Collections.sort(libs); int libIndex = 0; int artIndex = 0; boolean done = artIndex == artifacts.size(); while (!done) { if(libs.get(libIndex).compareTo(artifacts.get(artIndex).getId()) == 0) { File artifactFile = artifacts.get(artIndex).getFile(); if (!artifactFile.exists()) { throw new MojoExecutionException("Artifact not found: " + artifactFile); } jars.add(artifactFile.getPath()); libIndex++; } else { artIndex++; } if(artIndex == artifacts.size()) { throw new MojoExecutionException("Invalid library dependency: " + libs.get(libIndex)); } done = libIndex == libraries.length; } } return jars; }
diff --git a/pa1/src/to/richard/tsp/ReplaceWorstSurvivorSelection.java b/pa1/src/to/richard/tsp/ReplaceWorstSurvivorSelection.java index 4676c27..93466f6 100644 --- a/pa1/src/to/richard/tsp/ReplaceWorstSurvivorSelection.java +++ b/pa1/src/to/richard/tsp/ReplaceWorstSurvivorSelection.java @@ -1,55 +1,55 @@ package to.richard.tsp; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * Author: Richard To * Date: 2/11/13 */ /** * Implementation of replace worst (GENITOR) survivor selection * * Basically move the genotypes with the n-highest fitness values. * * n is the population size. */ public class ReplaceWorstSurvivorSelection implements ISurvivorSelector { private FitnessEvaluator _fitnessEvaluator; private Comparator<Pair<Double, Genotype>> _comparator; public ReplaceWorstSurvivorSelection( FitnessEvaluator fitnessEvaluator, Comparator<Pair<Double, Genotype>> comparator) { _fitnessEvaluator = fitnessEvaluator; _comparator = comparator; } @Override public List<Genotype> replace(List<Genotype> parents, List<Genotype> offspring) { int populationSize = parents.size(); int totalPopulation = populationSize * 2; ArrayList<Pair<Double, Genotype>> fitnessGenotypes = new ArrayList<Pair<Double, Genotype>>(); ArrayList<Genotype> nextGeneration = new ArrayList<Genotype>(); for (Genotype genotype : parents) { fitnessGenotypes.add(_fitnessEvaluator.evaluateAsPair(genotype)); } - for (Genotype genotype : parents) { + for (Genotype genotype : offspring) { fitnessGenotypes.add(_fitnessEvaluator.evaluateAsPair(genotype)); } Collections.sort(fitnessGenotypes, _comparator); - for (int i = totalPopulation - 1; i >= populationSize; i++) { + for (int i = totalPopulation - 1; i >= populationSize; i--) { nextGeneration.add(fitnessGenotypes.get(i).getSecondValue()); } return nextGeneration; } }
false
true
public List<Genotype> replace(List<Genotype> parents, List<Genotype> offspring) { int populationSize = parents.size(); int totalPopulation = populationSize * 2; ArrayList<Pair<Double, Genotype>> fitnessGenotypes = new ArrayList<Pair<Double, Genotype>>(); ArrayList<Genotype> nextGeneration = new ArrayList<Genotype>(); for (Genotype genotype : parents) { fitnessGenotypes.add(_fitnessEvaluator.evaluateAsPair(genotype)); } for (Genotype genotype : parents) { fitnessGenotypes.add(_fitnessEvaluator.evaluateAsPair(genotype)); } Collections.sort(fitnessGenotypes, _comparator); for (int i = totalPopulation - 1; i >= populationSize; i++) { nextGeneration.add(fitnessGenotypes.get(i).getSecondValue()); } return nextGeneration; }
public List<Genotype> replace(List<Genotype> parents, List<Genotype> offspring) { int populationSize = parents.size(); int totalPopulation = populationSize * 2; ArrayList<Pair<Double, Genotype>> fitnessGenotypes = new ArrayList<Pair<Double, Genotype>>(); ArrayList<Genotype> nextGeneration = new ArrayList<Genotype>(); for (Genotype genotype : parents) { fitnessGenotypes.add(_fitnessEvaluator.evaluateAsPair(genotype)); } for (Genotype genotype : offspring) { fitnessGenotypes.add(_fitnessEvaluator.evaluateAsPair(genotype)); } Collections.sort(fitnessGenotypes, _comparator); for (int i = totalPopulation - 1; i >= populationSize; i--) { nextGeneration.add(fitnessGenotypes.get(i).getSecondValue()); } return nextGeneration; }
diff --git a/src/main/java/eu/doppel_helix/netbeans/mantisintegration/query/MantisQueryTableCellRenderer.java b/src/main/java/eu/doppel_helix/netbeans/mantisintegration/query/MantisQueryTableCellRenderer.java index 96f89c0..e6f8b0a 100644 --- a/src/main/java/eu/doppel_helix/netbeans/mantisintegration/query/MantisQueryTableCellRenderer.java +++ b/src/main/java/eu/doppel_helix/netbeans/mantisintegration/query/MantisQueryTableCellRenderer.java @@ -1,73 +1,80 @@ package eu.doppel_helix.netbeans.mantisintegration.query; import biz.futureware.mantisconnect.ObjectRef; import eu.doppel_helix.netbeans.mantisintegration.Mantis; import java.awt.Color; import java.awt.Component; import java.lang.reflect.InvocationTargetException; import java.math.BigInteger; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Map; import javax.swing.JComponent; import javax.swing.JTable; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.TableCellRenderer; import org.netbeans.modules.bugtracking.issuetable.IssueNode; public class MantisQueryTableCellRenderer extends DefaultTableCellRenderer { private TableCellRenderer superRenderer; private Map<BigInteger,Color> colorMap = Mantis.getInstance().getStatusColorMap(); DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); public MantisQueryTableCellRenderer(TableCellRenderer superRenderer) { this.superRenderer = superRenderer; } @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { Object originalValue = value; Color overrideColor = Color.WHITE; if(value instanceof IssueNode.IssueProperty) { try { - if ("mantis.issue.status".equals(((IssueNode.IssueProperty) originalValue).getName())) { - value = ((IssueNode.IssueProperty) value).getValue(); - if (value instanceof ObjectRef) { - ObjectRef or = (ObjectRef) value; - BigInteger level = or.getId(); - if(colorMap.get(level) != null) { - overrideColor = colorMap.get(level); + if (((IssueNode.IssueProperty) originalValue).getName().startsWith("mantis.issue.")) { + value = ((IssueNode.IssueProperty) value).getValue(); + if ("mantis.issue.status".equals(((IssueNode.IssueProperty) originalValue).getName())) { + if (value instanceof ObjectRef) { + ObjectRef or = (ObjectRef) value; + BigInteger level = or.getId(); + if(colorMap.get(level) != null) { + overrideColor = colorMap.get(level); + } } } } } catch (IllegalAccessException ex) { throw new RuntimeException(ex); } catch (InvocationTargetException ex) { throw new RuntimeException(ex); } } if(value instanceof BigInteger) { value = ((BigInteger) value).longValue(); } else if (value instanceof ObjectRef) { value = ((ObjectRef) value).getName(); } else if (value instanceof Date) { value = df.format((Date) value); } else if (value instanceof Calendar) { value = df.format(((Calendar) value).getTime()); } - Component c = superRenderer.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); + Component c = null; + if(value instanceof IssueNode.IssueProperty) { + c = superRenderer.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); + } else { + c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); + } if(overrideColor != null) { if(c instanceof JComponent) { ((JComponent)c).setOpaque(true); } c.setBackground(overrideColor); } return c; } }
false
true
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { Object originalValue = value; Color overrideColor = Color.WHITE; if(value instanceof IssueNode.IssueProperty) { try { if ("mantis.issue.status".equals(((IssueNode.IssueProperty) originalValue).getName())) { value = ((IssueNode.IssueProperty) value).getValue(); if (value instanceof ObjectRef) { ObjectRef or = (ObjectRef) value; BigInteger level = or.getId(); if(colorMap.get(level) != null) { overrideColor = colorMap.get(level); } } } } catch (IllegalAccessException ex) { throw new RuntimeException(ex); } catch (InvocationTargetException ex) { throw new RuntimeException(ex); } } if(value instanceof BigInteger) { value = ((BigInteger) value).longValue(); } else if (value instanceof ObjectRef) { value = ((ObjectRef) value).getName(); } else if (value instanceof Date) { value = df.format((Date) value); } else if (value instanceof Calendar) { value = df.format(((Calendar) value).getTime()); } Component c = superRenderer.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); if(overrideColor != null) { if(c instanceof JComponent) { ((JComponent)c).setOpaque(true); } c.setBackground(overrideColor); } return c; }
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { Object originalValue = value; Color overrideColor = Color.WHITE; if(value instanceof IssueNode.IssueProperty) { try { if (((IssueNode.IssueProperty) originalValue).getName().startsWith("mantis.issue.")) { value = ((IssueNode.IssueProperty) value).getValue(); if ("mantis.issue.status".equals(((IssueNode.IssueProperty) originalValue).getName())) { if (value instanceof ObjectRef) { ObjectRef or = (ObjectRef) value; BigInteger level = or.getId(); if(colorMap.get(level) != null) { overrideColor = colorMap.get(level); } } } } } catch (IllegalAccessException ex) { throw new RuntimeException(ex); } catch (InvocationTargetException ex) { throw new RuntimeException(ex); } } if(value instanceof BigInteger) { value = ((BigInteger) value).longValue(); } else if (value instanceof ObjectRef) { value = ((ObjectRef) value).getName(); } else if (value instanceof Date) { value = df.format((Date) value); } else if (value instanceof Calendar) { value = df.format(((Calendar) value).getTime()); } Component c = null; if(value instanceof IssueNode.IssueProperty) { c = superRenderer.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); } else { c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); } if(overrideColor != null) { if(c instanceof JComponent) { ((JComponent)c).setOpaque(true); } c.setBackground(overrideColor); } return c; }
diff --git a/expenditure-tracking/src/pt/ist/expenditureTrackingSystem/domain/EmailDigester.java b/expenditure-tracking/src/pt/ist/expenditureTrackingSystem/domain/EmailDigester.java index 55f969b9..c33d4527 100644 --- a/expenditure-tracking/src/pt/ist/expenditureTrackingSystem/domain/EmailDigester.java +++ b/expenditure-tracking/src/pt/ist/expenditureTrackingSystem/domain/EmailDigester.java @@ -1,63 +1,63 @@ /* * @(#)EmailDigester.java * * Copyright 2009 Instituto Superior Tecnico * Founding Authors: Luis Cruz, Nuno Ochoa, Paulo Abrantes * * https://fenix-ashes.ist.utl.pt/ * * This file is part of the Expenditure Tracking Module. * * The Expenditure Tracking Module 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. * * The Expenditure Tracking Module 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 the Expenditure Tracking Module. If not, see <http://www.gnu.org/licenses/>. * */ package pt.ist.expenditureTrackingSystem.domain; import myorg.domain.MyOrg; import myorg.domain.VirtualHost; import pt.ist.fenixWebFramework.services.Service; /** * * @author Luis Cruz * @author Paulo Abrantes * */ public class EmailDigester extends EmailDigester_Base { public EmailDigester() { super(); } @Override @Service public void executeTask() { for (final VirtualHost virtualHost : MyOrg.getInstance().getVirtualHostsSet()) { - if (!virtualHost.getHostname().startsWith("dot")) { + if (!virtualHost.hasSystemSender() || !virtualHost.getHostname().startsWith("dot")) { continue; } try { VirtualHost.setVirtualHostForThread(virtualHost); EmailDigesterUtil.executeTask(); } finally { VirtualHost.releaseVirtualHostFromThread(); } } } @Override public String getLocalizedName() { return getClass().getName(); } }
true
true
public void executeTask() { for (final VirtualHost virtualHost : MyOrg.getInstance().getVirtualHostsSet()) { if (!virtualHost.getHostname().startsWith("dot")) { continue; } try { VirtualHost.setVirtualHostForThread(virtualHost); EmailDigesterUtil.executeTask(); } finally { VirtualHost.releaseVirtualHostFromThread(); } } }
public void executeTask() { for (final VirtualHost virtualHost : MyOrg.getInstance().getVirtualHostsSet()) { if (!virtualHost.hasSystemSender() || !virtualHost.getHostname().startsWith("dot")) { continue; } try { VirtualHost.setVirtualHostForThread(virtualHost); EmailDigesterUtil.executeTask(); } finally { VirtualHost.releaseVirtualHostFromThread(); } } }
diff --git a/src/main/java/amber/gui/MainContentPanel.java b/src/main/java/amber/gui/MainContentPanel.java index 6dedf21..3cd8c21 100644 --- a/src/main/java/amber/gui/MainContentPanel.java +++ b/src/main/java/amber/gui/MainContentPanel.java @@ -1,208 +1,210 @@ package amber.gui; import amber.Amber; import amber.data.Workspace; import amber.data.io.FileMonitor; import amber.data.io.FileMonitor.FileListener; import amber.data.state.LazyState; import amber.data.state.Scope; import amber.data.state.node.IState; import amber.gui.editor.FileViewerPanel; import amber.gui.editor.tool.ToolPanel; import amber.gui.misc.FileTreeExplorer; import amber.swing.UIUtil; import amber.swing.tabs.CloseableTabbedPane; import amber.swing.tabs.CloseableTabbedPane.CloseableTabComponent; import amber.swing.tabs.TabCloseListener; import amber.swing.tree.SmartExpander; import amber.swing.tree.Trees; import amber.swing.tree.filesystem.FileSystemTree; import amber.tool.ToolDefinition; import amber.tool.ToolManifest; import java.awt.*; import java.io.File; import java.util.Arrays; import java.util.HashMap; import javax.swing.*; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; /** * * @author Tudor */ public class MainContentPanel extends javax.swing.JPanel { protected HashMap<Component, String> activeFiles = new HashMap<Component, String>(); protected CloseableTabbedPane activeFilesTabbedPane; protected FileMonitor monitor; protected JLabel openFileLabel = new JLabel("Double-click a file to open it.", JLabel.CENTER); @LazyState(scope = Scope.PROJECT, name = "ProjectTreeExpansion") protected String saveTreeExpansion() { return Trees.getExpansionState(treeView, 0); } /** * Creates new form MainIDEPanel */ public MainContentPanel(Workspace workspace) { initComponents(); Amber.getStateManager().unregisterStateOwner(this); treeView.addFileTreeAdapter(new FileTreeExplorer(treeView)); treeView.setRoot(workspace.getRootDirectory()); IState treeState = Amber.getStateManager().getState(Scope.PROJECT, "ProjectTreeExpansion"); if (treeState != null) { Trees.restoreExpanstionState(treeView, 0, (String) treeState.get()); } Amber.getStateManager().registerStateOwner(this); SmartExpander.installOn(treeView); treeView.setRootVisible(true); monitor = new FileMonitor(1500); monitor.addFile(workspace.getRootDirectory()); monitor.addListener(new FileListener(){ public void fileChanged(File file) { System.out.println("Changed: " + file); treeView.synchronize(); } }); projectDivider.setRightComponent(openFileLabel); } @Override public void removeNotify() { monitor.stop(); } public CloseableTabbedPane getFilesTabbedPane() { if (activeFilesTabbedPane == null) { activeFilesTabbedPane = new CloseableTabbedPane(); activeFilesTabbedPane.addTabCloseListener(new TabCloseListener() { public boolean tabClosed(String title, Component comp, CloseableTabbedPane pane) { System.out.println("Tab closing..."); if (comp instanceof FileViewerPanel && ((FileViewerPanel) comp).modified()) { switch (JOptionPane.showConfirmDialog(MainContentPanel.this, "Do you want to save the following file:\n" + title, "Confirm Close", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE)) { case JOptionPane.YES_OPTION: ((FileViewerPanel) comp).save(); break; case JOptionPane.NO_OPTION: break; case JOptionPane.CANCEL_OPTION: return false; } } if (activeFiles.containsKey(comp)) { Amber.getWorkspace().getOpenedFiles().remove(activeFiles.remove(comp)); } if (activeFilesTabbedPane.getTabCount() == 1) { projectDivider.setRightComponent(openFileLabel); activeFilesTabbedPane = null; } return true; } }); activeFilesTabbedPane.addChangeListener(new ChangeListener() { int oldMenuCount = 0; @Override public void stateChanged(ChangeEvent e) { + if (!(e.getSource() instanceof CloseableTabbedPane)) + return; JMenuBar menuBar = Amber.getUI().getMenu(); for (int i = 0; i < oldMenuCount; ++i) { menuBar.remove(menuBar.getMenuCount() - 2); } - Component component = activeFilesTabbedPane.getSelectedComponent(); + Component component = ((CloseableTabbedPane) e.getSource()).getSelectedComponent(); if (component instanceof FileViewerPanel) { JMenu[] menus = ((FileViewerPanel) component).getContextMenus(); for (JMenu menu : menus) { menuBar.add(menu, menuBar.getComponentCount() - 1); // Help menu should always be last } oldMenuCount = menus.length; } else { oldMenuCount = 0; } menuBar.revalidate(); } }); int location = projectDivider.getDividerLocation(); projectDivider.setRightComponent(activeFilesTabbedPane); projectDivider.setDividerLocation(location); } return activeFilesTabbedPane; } public void addTab(String id, Component tab) { activeFilesTabbedPane.add(id, tab); } public void addFileTab(FileViewerPanel file) { try { getFilesTabbedPane().add(file.getFile().getName(), file); } catch (RuntimeException ex) { getFilesTabbedPane().remove(file); throw ex; // Propagate to the error handler in FileTreeExplorer } activeFiles.put(file, file.getFile().getAbsolutePath()); int i = getFilesTabbedPane().getTabCount() - 1; getFilesTabbedPane().setSelectedIndex(i); ((CloseableTabComponent) getFilesTabbedPane().getTabComponentAt(i)).getTitleLabel().setIcon(file.getTabIcon()); } public void addToolTab(ToolDefinition tool) { ToolPanel toolPanel = new ToolPanel(tool); ToolManifest mf = tool.getManifest(); try { getFilesTabbedPane().add(mf.name(), toolPanel); } catch (RuntimeException ex) { getFilesTabbedPane().remove(toolPanel); throw ex; // Propagate to the error handler in FileTreeExplorer } getFilesTabbedPane().setToolTipTextAt(getFilesTabbedPane().getTabCount() - 1, String.format("<html>" + "<b>%s</b> v%s by %s" + "<br/>" + "&nbsp;&nbsp;&nbsp;%s" + "</html>", mf.name(), mf.version(), Arrays.toString(mf.authors()), mf.description())); getFilesTabbedPane().setSelectedIndex(getFilesTabbedPane().getTabCount() - 1); } public FileSystemTree getFileTree() { return treeView; } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { projectDivider = new amber.swing.misc.ThinSplitPane(); jScrollPane1 = new javax.swing.JScrollPane(); treeView = new amber.swing.tree.filesystem.FileSystemTree(); setLayout(new java.awt.BorderLayout()); projectDivider.setDividerLocation(150); projectDivider.setDividerSize(0); projectDivider.setMinimumSize(new java.awt.Dimension(0, 0)); jScrollPane1.setBorder(null); jScrollPane1.setMinimumSize(new java.awt.Dimension(0, 0)); jScrollPane1.setViewportView(treeView); projectDivider.setLeftComponent(jScrollPane1); add(projectDivider, java.awt.BorderLayout.CENTER); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JScrollPane jScrollPane1; private amber.swing.misc.ThinSplitPane projectDivider; private amber.swing.tree.filesystem.FileSystemTree treeView; // End of variables declaration//GEN-END:variables }
false
true
public CloseableTabbedPane getFilesTabbedPane() { if (activeFilesTabbedPane == null) { activeFilesTabbedPane = new CloseableTabbedPane(); activeFilesTabbedPane.addTabCloseListener(new TabCloseListener() { public boolean tabClosed(String title, Component comp, CloseableTabbedPane pane) { System.out.println("Tab closing..."); if (comp instanceof FileViewerPanel && ((FileViewerPanel) comp).modified()) { switch (JOptionPane.showConfirmDialog(MainContentPanel.this, "Do you want to save the following file:\n" + title, "Confirm Close", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE)) { case JOptionPane.YES_OPTION: ((FileViewerPanel) comp).save(); break; case JOptionPane.NO_OPTION: break; case JOptionPane.CANCEL_OPTION: return false; } } if (activeFiles.containsKey(comp)) { Amber.getWorkspace().getOpenedFiles().remove(activeFiles.remove(comp)); } if (activeFilesTabbedPane.getTabCount() == 1) { projectDivider.setRightComponent(openFileLabel); activeFilesTabbedPane = null; } return true; } }); activeFilesTabbedPane.addChangeListener(new ChangeListener() { int oldMenuCount = 0; @Override public void stateChanged(ChangeEvent e) { JMenuBar menuBar = Amber.getUI().getMenu(); for (int i = 0; i < oldMenuCount; ++i) { menuBar.remove(menuBar.getMenuCount() - 2); } Component component = activeFilesTabbedPane.getSelectedComponent(); if (component instanceof FileViewerPanel) { JMenu[] menus = ((FileViewerPanel) component).getContextMenus(); for (JMenu menu : menus) { menuBar.add(menu, menuBar.getComponentCount() - 1); // Help menu should always be last } oldMenuCount = menus.length; } else { oldMenuCount = 0; } menuBar.revalidate(); } }); int location = projectDivider.getDividerLocation(); projectDivider.setRightComponent(activeFilesTabbedPane); projectDivider.setDividerLocation(location); } return activeFilesTabbedPane; }
public CloseableTabbedPane getFilesTabbedPane() { if (activeFilesTabbedPane == null) { activeFilesTabbedPane = new CloseableTabbedPane(); activeFilesTabbedPane.addTabCloseListener(new TabCloseListener() { public boolean tabClosed(String title, Component comp, CloseableTabbedPane pane) { System.out.println("Tab closing..."); if (comp instanceof FileViewerPanel && ((FileViewerPanel) comp).modified()) { switch (JOptionPane.showConfirmDialog(MainContentPanel.this, "Do you want to save the following file:\n" + title, "Confirm Close", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE)) { case JOptionPane.YES_OPTION: ((FileViewerPanel) comp).save(); break; case JOptionPane.NO_OPTION: break; case JOptionPane.CANCEL_OPTION: return false; } } if (activeFiles.containsKey(comp)) { Amber.getWorkspace().getOpenedFiles().remove(activeFiles.remove(comp)); } if (activeFilesTabbedPane.getTabCount() == 1) { projectDivider.setRightComponent(openFileLabel); activeFilesTabbedPane = null; } return true; } }); activeFilesTabbedPane.addChangeListener(new ChangeListener() { int oldMenuCount = 0; @Override public void stateChanged(ChangeEvent e) { if (!(e.getSource() instanceof CloseableTabbedPane)) return; JMenuBar menuBar = Amber.getUI().getMenu(); for (int i = 0; i < oldMenuCount; ++i) { menuBar.remove(menuBar.getMenuCount() - 2); } Component component = ((CloseableTabbedPane) e.getSource()).getSelectedComponent(); if (component instanceof FileViewerPanel) { JMenu[] menus = ((FileViewerPanel) component).getContextMenus(); for (JMenu menu : menus) { menuBar.add(menu, menuBar.getComponentCount() - 1); // Help menu should always be last } oldMenuCount = menus.length; } else { oldMenuCount = 0; } menuBar.revalidate(); } }); int location = projectDivider.getDividerLocation(); projectDivider.setRightComponent(activeFilesTabbedPane); projectDivider.setDividerLocation(location); } return activeFilesTabbedPane; }
diff --git a/extensions/bundles/sdnnetwork/src/main/java/org/opennaas/extensions/sdnnetwork/driver/internal/actionsets/actions/AllocateFlowAction.java b/extensions/bundles/sdnnetwork/src/main/java/org/opennaas/extensions/sdnnetwork/driver/internal/actionsets/actions/AllocateFlowAction.java index 48baf7541..e86083769 100644 --- a/extensions/bundles/sdnnetwork/src/main/java/org/opennaas/extensions/sdnnetwork/driver/internal/actionsets/actions/AllocateFlowAction.java +++ b/extensions/bundles/sdnnetwork/src/main/java/org/opennaas/extensions/sdnnetwork/driver/internal/actionsets/actions/AllocateFlowAction.java @@ -1,173 +1,174 @@ package org.opennaas.extensions.sdnnetwork.driver.internal.actionsets.actions; import java.util.List; import org.opennaas.core.resources.ActivatorException; import org.opennaas.core.resources.IResource; import org.opennaas.core.resources.IResourceIdentifier; import org.opennaas.core.resources.IResourceManager; import org.opennaas.core.resources.ResourceException; import org.opennaas.core.resources.action.Action; import org.opennaas.core.resources.action.ActionException; import org.opennaas.core.resources.action.ActionResponse; import org.opennaas.core.resources.protocol.IProtocolSessionManager; import org.opennaas.extensions.openflowswitch.capability.IOpenflowForwardingCapability; import org.opennaas.extensions.openflowswitch.model.FloodlightOFAction; import org.opennaas.extensions.openflowswitch.model.FloodlightOFFlow; import org.opennaas.extensions.sdnnetwork.Activator; import org.opennaas.extensions.sdnnetwork.model.NetworkConnection; import org.opennaas.extensions.sdnnetwork.model.Port; import org.opennaas.extensions.sdnnetwork.model.Route; import org.opennaas.extensions.sdnnetwork.model.SDNNetworkOFFlow; /** * * @author Isart Canyameres Gimenez (i2cat) * @author Julio Carlos Barrera * */ public class AllocateFlowAction extends Action { @Override public ActionResponse execute(IProtocolSessionManager protocolSessionManager) throws ActionException { SDNNetworkOFFlow flow = (SDNNetworkOFFlow) params; // provision each link and mark the last one List<NetworkConnection> connections = flow.getRoute().getNetworkConnections(); for (int i = 0; i < connections.size(); i++) { NetworkConnection networkConnection = connections.get(i); try { provisionLink(networkConnection, new SDNNetworkOFFlow(flow), i == connections.size() - 1); } catch (Exception e) { throw new ActionException("Error provisioning link : ", e); } } return ActionResponse.okResponse(getActionID()); } /** * private void provisionLink(Port source, Port destination, SDNNetworkOFFlow sdnNetworkOFFlow, boolean lastLink) throws ActionException { if * (source.getDeviceId() != destination.getDeviceId()) { // link between different devices, assume it exists or it is provisioned } else { // link * inside same device, use device internal capability to provision it // get OpenNaaS resource Id from the map in the model String deviceId = * source.getDeviceId(); String resourceId = ((SDNNetworkModel) getModelToUpdate()).getDeviceResourceMap().get(deviceId); if (resourceId == null) * { throw new ActionException("No resource Id found from device Id: " + deviceId); } * * // get switch resource from Resource Manager using resource Id IResource resource = null; try { resource = * Activator.getResourceManagerService().getResourceById(resourceId); } catch (Exception e) { throw new * ActionException("Error getting switch resource from Resource Manager", e); } * * // get IOpenflowForwardingCapability from the obtained resource IOpenflowForwardingCapability capability = null; try { capability = * (IOpenflowForwardingCapability) resource.getCapabilityByInterface(IOpenflowForwardingCapability.class); } catch (ResourceException e) { throw * new ActionException("Error getting IOpenflowForwardingCapability from resource with Id: " + resourceId, e); } * * // construct FloodlightOFFlow based on SDNNetworkOFFlow, source Port, destination Port and lastLink FloodlightOFFlow flow = new * FloodlightOFFlow(sdnNetworkOFFlow, deviceId); * * flow.getMatch().setIngressPort(source.getPortNumber()); * * // Only last link in the flow should apply actions other than forwarding. // The rest of the links should have only forwarding actions. * List<FloodlightOFAction> actions = flow.getActions(); if (!lastLink) { FloodlightOFAction outputAction = null; for (FloodlightOFAction * floodlightOFAction : actions) { if (floodlightOFAction.getType() == FloodlightOFAction.TYPE_OUTPUT) { outputAction = floodlightOFAction; } } if * (outputAction == null) { throw new ActionException("No output action found in FloodlightOFFlow."); } // clear list and add output action * actions.clear(); actions.add(outputAction); } * * // invoke IOpenflowForwardingCapability try { capability.createOpenflowForwardingRule(flow); } catch (CapabilityException e) { throw new * ActionException("Error executing IOpenflowForwardingCapability from resource with Id: " + resourceId, e); } } } **/ /** * The commented code is the right way to do it, but since there's no way to set the mapping between the switchID and the deviceID and we have a * demo tomorrow, we will take the switch resource from the ResourceManager. Every switch contains in its model its floodlight switchId, so we can * use it as a work around. * * @param source * @param destination * @param sdnNetworkOFFlow * @param lastLink * @throws ResourceException * @throws ActivatorException */ private void provisionLink(NetworkConnection connection, SDNNetworkOFFlow sdnNetworkOFFlow, boolean isLastLinkInRoute) throws ResourceException, ActivatorException { if (connection.getSource().getDeviceId() != connection.getDestination().getDeviceId()) { /* link between different devices, assume it exists or it is provisioned */ } else { /* link inside same device, use device internal capability to provision it */ // Last link should include all actions of the original flow and the forwarding one. // The rest only the forwarding rule. // This way we can re-use original match in all links of the same flow. FloodlightOFFlow flow = generateOFFlow(connection, sdnNetworkOFFlow, isLastLinkInRoute); String resourceName = connection.getSource().getDeviceId(); IResource resource = getResourceByName(resourceName); IOpenflowForwardingCapability forwardingCapability = (IOpenflowForwardingCapability) resource .getCapabilityByInterface(IOpenflowForwardingCapability.class); forwardingCapability.createOpenflowForwardingRule(flow); } } /** * * @param connection * @param sdnNetworkOFFlow * @param keepActions * whether returned flow must have actions in sdnNetworkOFFlow or not. * @return a FloodlightOFFlow representing given connection in sdnNetworkOFFlow. * @throws ActionException */ private FloodlightOFFlow generateOFFlow(NetworkConnection connection, SDNNetworkOFFlow sdnNetworkOFFlow, boolean keepActions) throws ActionException { Port source = connection.getSource(); Port destination = connection.getDestination(); - FloodlightOFFlow flow = new FloodlightOFFlow(sdnNetworkOFFlow, connection.getId()); + FloodlightOFFlow flow = new FloodlightOFFlow(sdnNetworkOFFlow, null); + flow.setName(connection.getId()); flow.getMatch().setIngressPort(source.getPortNumber()); FloodlightOFAction outputAction = new FloodlightOFAction(); outputAction.setType(FloodlightOFAction.TYPE_OUTPUT); outputAction.setValue(destination.getPortNumber()); // All links should include a forwarding action (outputAction) List<FloodlightOFAction> actions = flow.getActions(); if (!keepActions) { actions.clear(); } else { for (FloodlightOFAction floodlightOFAction : actions) { if (floodlightOFAction.getType() == FloodlightOFAction.TYPE_OUTPUT) { actions.remove(floodlightOFAction); } } } actions.add(outputAction); return flow; } private IResource getResourceByName(String resourceName) throws ActivatorException, ResourceException { IResourceManager resourceManager = Activator.getResourceManagerService(); IResourceIdentifier resourceId = resourceManager.getIdentifierFromResourceName("openflowswitch", resourceName); return resourceManager.getResource(resourceId); } @Override public boolean checkParams(Object params) throws ActionException { if (params instanceof SDNNetworkOFFlow) { SDNNetworkOFFlow flow = (SDNNetworkOFFlow) params; Route route = flow.getRoute(); if (route == null) { throw new ActionException("Route must be set"); } List<NetworkConnection> connections = route.getNetworkConnections(); if (connections == null || connections.size() == 0) { throw new ActionException("NetworkConnection list must have at least 1 item"); } return true; } throw new ActionException("Action parameters must be set and SDNNetworkOFFlow type"); } }
true
true
private FloodlightOFFlow generateOFFlow(NetworkConnection connection, SDNNetworkOFFlow sdnNetworkOFFlow, boolean keepActions) throws ActionException { Port source = connection.getSource(); Port destination = connection.getDestination(); FloodlightOFFlow flow = new FloodlightOFFlow(sdnNetworkOFFlow, connection.getId()); flow.getMatch().setIngressPort(source.getPortNumber()); FloodlightOFAction outputAction = new FloodlightOFAction(); outputAction.setType(FloodlightOFAction.TYPE_OUTPUT); outputAction.setValue(destination.getPortNumber()); // All links should include a forwarding action (outputAction) List<FloodlightOFAction> actions = flow.getActions(); if (!keepActions) { actions.clear(); } else { for (FloodlightOFAction floodlightOFAction : actions) { if (floodlightOFAction.getType() == FloodlightOFAction.TYPE_OUTPUT) { actions.remove(floodlightOFAction); } } } actions.add(outputAction); return flow; }
private FloodlightOFFlow generateOFFlow(NetworkConnection connection, SDNNetworkOFFlow sdnNetworkOFFlow, boolean keepActions) throws ActionException { Port source = connection.getSource(); Port destination = connection.getDestination(); FloodlightOFFlow flow = new FloodlightOFFlow(sdnNetworkOFFlow, null); flow.setName(connection.getId()); flow.getMatch().setIngressPort(source.getPortNumber()); FloodlightOFAction outputAction = new FloodlightOFAction(); outputAction.setType(FloodlightOFAction.TYPE_OUTPUT); outputAction.setValue(destination.getPortNumber()); // All links should include a forwarding action (outputAction) List<FloodlightOFAction> actions = flow.getActions(); if (!keepActions) { actions.clear(); } else { for (FloodlightOFAction floodlightOFAction : actions) { if (floodlightOFAction.getType() == FloodlightOFAction.TYPE_OUTPUT) { actions.remove(floodlightOFAction); } } } actions.add(outputAction); return flow; }
diff --git a/src/com/android/packageinstaller/PackageInstallerActivity.java b/src/com/android/packageinstaller/PackageInstallerActivity.java index d3b2a947..8771a3ec 100644 --- a/src/com/android/packageinstaller/PackageInstallerActivity.java +++ b/src/com/android/packageinstaller/PackageInstallerActivity.java @@ -1,608 +1,609 @@ /* ** ** Copyright 2007, 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.packageinstaller; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageUserState; import android.content.pm.PackageManager.NameNotFoundException; import android.content.pm.PackageParser; import android.graphics.Rect; import android.net.Uri; import android.os.Bundle; import android.provider.Settings; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AppSecurityPermissions; import android.widget.Button; import android.widget.ScrollView; import android.widget.TabHost; import android.widget.TabWidget; import android.widget.TextView; import java.io.File; import java.util.ArrayList; /* * This activity is launched when a new application is installed via side loading * The package is first parsed and the user is notified of parse errors via a dialog. * If the package is successfully parsed, the user is notified to turn on the install unknown * applications setting. A memory check is made at this point and the user is notified of out * of memory conditions if any. If the package is already existing on the device, * a confirmation dialog (to replace the existing package) is presented to the user. * Based on the user response the package is then installed by launching InstallAppConfirm * sub activity. All state transitions are handled in this activity */ public class PackageInstallerActivity extends Activity implements OnCancelListener, OnClickListener { private static final String TAG = "PackageInstaller"; private Uri mPackageURI; private Uri mOriginatingURI; private Uri mReferrerURI; private boolean localLOGV = false; PackageManager mPm; PackageInfo mPkgInfo; ApplicationInfo mSourceInfo; // ApplicationInfo object primarily used for already existing applications private ApplicationInfo mAppInfo = null; // View for install progress View mInstallConfirm; // Buttons to indicate user acceptance private Button mOk; private Button mCancel; CaffeinatedScrollView mScrollView = null; private boolean mOkCanInstall = false; static final String PREFS_ALLOWED_SOURCES = "allowed_sources"; // Dialog identifiers used in showDialog private static final int DLG_BASE = 0; private static final int DLG_UNKNOWN_APPS = DLG_BASE + 1; private static final int DLG_PACKAGE_ERROR = DLG_BASE + 2; private static final int DLG_OUT_OF_SPACE = DLG_BASE + 3; private static final int DLG_INSTALL_ERROR = DLG_BASE + 4; private static final int DLG_ALLOW_SOURCE = DLG_BASE + 5; /** * This is a helper class that implements the management of tabs and all * details of connecting a ViewPager with associated TabHost. It relies on a * trick. Normally a tab host has a simple API for supplying a View or * Intent that each tab will show. This is not sufficient for switching * between pages. So instead we make the content part of the tab host * 0dp high (it is not shown) and the TabsAdapter supplies its own dummy * view to show as the tab content. It listens to changes in tabs, and takes * care of switch to the correct paged in the ViewPager whenever the selected * tab changes. */ public static class TabsAdapter extends PagerAdapter implements TabHost.OnTabChangeListener, ViewPager.OnPageChangeListener { private final Context mContext; private final TabHost mTabHost; private final ViewPager mViewPager; private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>(); private final Rect mTempRect = new Rect(); static final class TabInfo { private final String tag; private final View view; TabInfo(String _tag, View _view) { tag = _tag; view = _view; } } static class DummyTabFactory implements TabHost.TabContentFactory { private final Context mContext; public DummyTabFactory(Context context) { mContext = context; } @Override public View createTabContent(String tag) { View v = new View(mContext); v.setMinimumWidth(0); v.setMinimumHeight(0); return v; } } public TabsAdapter(Activity activity, TabHost tabHost, ViewPager pager) { mContext = activity; mTabHost = tabHost; mViewPager = pager; mTabHost.setOnTabChangedListener(this); mViewPager.setAdapter(this); mViewPager.setOnPageChangeListener(this); } public void addTab(TabHost.TabSpec tabSpec, View view) { tabSpec.setContent(new DummyTabFactory(mContext)); String tag = tabSpec.getTag(); TabInfo info = new TabInfo(tag, view); mTabs.add(info); mTabHost.addTab(tabSpec); notifyDataSetChanged(); } @Override public int getCount() { return mTabs.size(); } @Override public Object instantiateItem(ViewGroup container, int position) { View view = mTabs.get(position).view; container.addView(view); return view; } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView((View)object); } @Override public boolean isViewFromObject(View view, Object object) { return view == object; } @Override public void onTabChanged(String tabId) { int position = mTabHost.getCurrentTab(); mViewPager.setCurrentItem(position); } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { // Unfortunately when TabHost changes the current tab, it kindly // also takes care of putting focus on it when not in touch mode. // The jerk. // This hack tries to prevent this from pulling focus out of our // ViewPager. TabWidget widget = mTabHost.getTabWidget(); int oldFocusability = widget.getDescendantFocusability(); widget.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS); mTabHost.setCurrentTab(position); widget.setDescendantFocusability(oldFocusability); // Scroll the current tab into visibility if needed. View tab = widget.getChildTabViewAt(position); mTempRect.set(tab.getLeft(), tab.getTop(), tab.getRight(), tab.getBottom()); widget.requestRectangleOnScreen(mTempRect, false); // Make sure the scrollbars are visible for a moment after selection final View contentView = mTabs.get(position).view; if (contentView instanceof CaffeinatedScrollView) { ((CaffeinatedScrollView) contentView).awakenScrollBars(); } } @Override public void onPageScrollStateChanged(int state) { } } private void startInstallConfirm() { TabHost tabHost = (TabHost)findViewById(android.R.id.tabhost); tabHost.setup(); ViewPager viewPager = (ViewPager)findViewById(R.id.pager); TabsAdapter adapter = new TabsAdapter(this, tabHost, viewPager); boolean permVisible = false; mScrollView = null; mOkCanInstall = false; int msg = 0; if (mPkgInfo != null) { AppSecurityPermissions perms = new AppSecurityPermissions(this, mPkgInfo); final int NP = perms.getPermissionCount(AppSecurityPermissions.WHICH_PERSONAL); final int ND = perms.getPermissionCount(AppSecurityPermissions.WHICH_DEVICE); if (mAppInfo != null) { msg = (mAppInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0 ? R.string.install_confirm_question_update_system : R.string.install_confirm_question_update; mScrollView = new CaffeinatedScrollView(this); mScrollView.setFillViewport(true); if (perms.getPermissionCount(AppSecurityPermissions.WHICH_NEW) > 0) { permVisible = true; mScrollView.addView(perms.getPermissionsView( AppSecurityPermissions.WHICH_NEW)); } else { LayoutInflater inflater = (LayoutInflater)getSystemService( Context.LAYOUT_INFLATER_SERVICE); TextView label = (TextView)inflater.inflate(R.layout.label, null); label.setText(R.string.no_new_perms); mScrollView.addView(label); } adapter.addTab(tabHost.newTabSpec("new").setIndicator( getText(R.string.newPerms)), mScrollView); } else { findViewById(R.id.tabscontainer).setVisibility(View.GONE); + findViewById(R.id.divider).setVisibility(View.VISIBLE); } if (NP > 0 || ND > 0) { permVisible = true; LayoutInflater inflater = (LayoutInflater)getSystemService( Context.LAYOUT_INFLATER_SERVICE); View root = inflater.inflate(R.layout.permissions_list, null); if (mScrollView == null) { mScrollView = (CaffeinatedScrollView)root.findViewById(R.id.scrollview); } if (NP > 0) { ((ViewGroup)root.findViewById(R.id.privacylist)).addView( perms.getPermissionsView(AppSecurityPermissions.WHICH_PERSONAL)); } else { root.findViewById(R.id.privacylist).setVisibility(View.GONE); } if (ND > 0) { ((ViewGroup)root.findViewById(R.id.devicelist)).addView( perms.getPermissionsView(AppSecurityPermissions.WHICH_DEVICE)); } else { root.findViewById(R.id.devicelist).setVisibility(View.GONE); } adapter.addTab(tabHost.newTabSpec("all").setIndicator( getText(R.string.allPerms)), root); } } if (!permVisible) { if (msg == 0) { if (mAppInfo != null) { // This is an update to an application, but there are no // permissions at all. msg = (mAppInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0 ? R.string.install_confirm_question_update_system_no_perms : R.string.install_confirm_question_update_no_perms; } else { // This is a new application with no permissions. msg = R.string.install_confirm_question_no_perms; } } - tabHost.setVisibility(View.INVISIBLE); + tabHost.setVisibility(View.GONE); } if (msg != 0) { ((TextView)findViewById(R.id.install_confirm_question)).setText(msg); } mInstallConfirm.setVisibility(View.VISIBLE); mOk = (Button)findViewById(R.id.ok_button); mCancel = (Button)findViewById(R.id.cancel_button); mOk.setOnClickListener(this); mCancel.setOnClickListener(this); if (mScrollView == null) { // There is nothing to scroll view, so the ok button is immediately // set to install. mOk.setText(R.string.install); mOkCanInstall = true; } else { mScrollView.setFullScrollAction(new Runnable() { @Override public void run() { mOk.setText(R.string.install); mOkCanInstall = true; } }); } } private void showDialogInner(int id) { // TODO better fix for this? Remove dialog so that it gets created again removeDialog(id); showDialog(id); } @Override public Dialog onCreateDialog(int id, Bundle bundle) { switch (id) { case DLG_UNKNOWN_APPS: return new AlertDialog.Builder(this) .setTitle(R.string.unknown_apps_dlg_title) .setMessage(R.string.unknown_apps_dlg_text) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { Log.i(TAG, "Finishing off activity so that user can navigate to settings manually"); finish(); }}) .setPositiveButton(R.string.settings, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { Log.i(TAG, "Launching settings"); launchSettingsAppAndFinish(); } }) .setOnCancelListener(this) .create(); case DLG_PACKAGE_ERROR : return new AlertDialog.Builder(this) .setTitle(R.string.Parse_error_dlg_title) .setMessage(R.string.Parse_error_dlg_text) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { finish(); } }) .setOnCancelListener(this) .create(); case DLG_OUT_OF_SPACE: // Guaranteed not to be null. will default to package name if not set by app CharSequence appTitle = mPm.getApplicationLabel(mPkgInfo.applicationInfo); String dlgText = getString(R.string.out_of_space_dlg_text, appTitle.toString()); return new AlertDialog.Builder(this) .setTitle(R.string.out_of_space_dlg_title) .setMessage(dlgText) .setPositiveButton(R.string.manage_applications, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { //launch manage applications Intent intent = new Intent("android.intent.action.MANAGE_PACKAGE_STORAGE"); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); finish(); } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { Log.i(TAG, "Canceling installation"); finish(); } }) .setOnCancelListener(this) .create(); case DLG_INSTALL_ERROR : // Guaranteed not to be null. will default to package name if not set by app CharSequence appTitle1 = mPm.getApplicationLabel(mPkgInfo.applicationInfo); String dlgText1 = getString(R.string.install_failed_msg, appTitle1.toString()); return new AlertDialog.Builder(this) .setTitle(R.string.install_failed) .setNeutralButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { finish(); } }) .setMessage(dlgText1) .setOnCancelListener(this) .create(); case DLG_ALLOW_SOURCE: CharSequence appTitle2 = mPm.getApplicationLabel(mSourceInfo); String dlgText2 = getString(R.string.allow_source_dlg_text, appTitle2.toString()); return new AlertDialog.Builder(this) .setTitle(R.string.allow_source_dlg_title) .setMessage(dlgText2) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { setResult(RESULT_CANCELED); finish(); }}) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { SharedPreferences prefs = getSharedPreferences(PREFS_ALLOWED_SOURCES, Context.MODE_PRIVATE); prefs.edit().putBoolean(mSourceInfo.packageName, true).apply(); startInstallConfirm(); } }) .setOnCancelListener(this) .create(); } return null; } private void launchSettingsAppAndFinish() { // Create an intent to launch SettingsTwo activity Intent launchSettingsIntent = new Intent(Settings.ACTION_SECURITY_SETTINGS); launchSettingsIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(launchSettingsIntent); finish(); } private boolean isInstallingUnknownAppsAllowed() { return Settings.Global.getInt(getContentResolver(), Settings.Global.INSTALL_NON_MARKET_APPS, 0) > 0; } private void initiateInstall() { String pkgName = mPkgInfo.packageName; // Check if there is already a package on the device with this name // but it has been renamed to something else. String[] oldName = mPm.canonicalToCurrentPackageNames(new String[] { pkgName }); if (oldName != null && oldName.length > 0 && oldName[0] != null) { pkgName = oldName[0]; mPkgInfo.packageName = pkgName; mPkgInfo.applicationInfo.packageName = pkgName; } // Check if package is already installed. display confirmation dialog if replacing pkg try { // This is a little convoluted because we want to get all uninstalled // apps, but this may include apps with just data, and if it is just // data we still want to count it as "installed". mAppInfo = mPm.getApplicationInfo(pkgName, PackageManager.GET_UNINSTALLED_PACKAGES); if ((mAppInfo.flags&ApplicationInfo.FLAG_INSTALLED) == 0) { mAppInfo = null; } } catch (NameNotFoundException e) { mAppInfo = null; } startInstallConfirm(); } void setPmResult(int pmResult) { Intent result = new Intent(); result.putExtra(Intent.EXTRA_INSTALL_RESULT, pmResult); setResult(pmResult == PackageManager.INSTALL_SUCCEEDED ? RESULT_OK : RESULT_FIRST_USER, result); } @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); // get intent information final Intent intent = getIntent(); mPackageURI = intent.getData(); mOriginatingURI = intent.getParcelableExtra(Intent.EXTRA_ORIGINATING_URI); mReferrerURI = intent.getParcelableExtra(Intent.EXTRA_REFERRER); mPm = getPackageManager(); final String scheme = mPackageURI.getScheme(); if (scheme != null && !"file".equals(scheme) && !"package".equals(scheme)) { Log.w(TAG, "Unsupported scheme " + scheme); setPmResult(PackageManager.INSTALL_FAILED_INVALID_URI); return; } final PackageUtil.AppSnippet as; if ("package".equals(mPackageURI.getScheme())) { try { mPkgInfo = mPm.getPackageInfo(mPackageURI.getSchemeSpecificPart(), PackageManager.GET_PERMISSIONS | PackageManager.GET_UNINSTALLED_PACKAGES); } catch (NameNotFoundException e) { } if (mPkgInfo == null) { Log.w(TAG, "Requested package " + mPackageURI.getScheme() + " not available. Discontinuing installation"); showDialogInner(DLG_PACKAGE_ERROR); setPmResult(PackageManager.INSTALL_FAILED_INVALID_APK); return; } as = new PackageUtil.AppSnippet(mPm.getApplicationLabel(mPkgInfo.applicationInfo), mPm.getApplicationIcon(mPkgInfo.applicationInfo)); } else { final File sourceFile = new File(mPackageURI.getPath()); PackageParser.Package parsed = PackageUtil.getPackageInfo(sourceFile); // Check for parse errors if (parsed == null) { Log.w(TAG, "Parse error when parsing manifest. Discontinuing installation"); showDialogInner(DLG_PACKAGE_ERROR); setPmResult(PackageManager.INSTALL_FAILED_INVALID_APK); return; } mPkgInfo = PackageParser.generatePackageInfo(parsed, null, PackageManager.GET_PERMISSIONS, 0, 0, null, new PackageUserState()); as = PackageUtil.getAppSnippet(this, mPkgInfo.applicationInfo, sourceFile); } //set view setContentView(R.layout.install_start); mInstallConfirm = findViewById(R.id.install_confirm_panel); mInstallConfirm.setVisibility(View.INVISIBLE); PackageUtil.initSnippetForNewApp(this, as, R.id.app_snippet); // Deal with install source. String callerPackage = getCallingPackage(); if (callerPackage != null && intent.getBooleanExtra( Intent.EXTRA_NOT_UNKNOWN_SOURCE, false)) { try { mSourceInfo = mPm.getApplicationInfo(callerPackage, 0); if (mSourceInfo != null) { if ((mSourceInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { // System apps don't need to be approved. initiateInstall(); return; } /* for now this is disabled, since the user would need to * have enabled the global "unknown sources" setting in the * first place in order to get here. SharedPreferences prefs = getSharedPreferences(PREFS_ALLOWED_SOURCES, Context.MODE_PRIVATE); if (prefs.getBoolean(mSourceInfo.packageName, false)) { // User has already allowed this one. initiateInstall(); return; } //ask user to enable setting first showDialogInner(DLG_ALLOW_SOURCE); return; */ } } catch (NameNotFoundException e) { } } // Check unknown sources. if (!isInstallingUnknownAppsAllowed()) { //ask user to enable setting first showDialogInner(DLG_UNKNOWN_APPS); return; } initiateInstall(); } // Generic handling when pressing back key public void onCancel(DialogInterface dialog) { finish(); } public void onClick(View v) { if(v == mOk) { if (mOkCanInstall || mScrollView == null) { // Start subactivity to actually install the application Intent newIntent = new Intent(); newIntent.putExtra(PackageUtil.INTENT_ATTR_APPLICATION_INFO, mPkgInfo.applicationInfo); newIntent.setData(mPackageURI); newIntent.setClass(this, InstallAppProgress.class); String installerPackageName = getIntent().getStringExtra( Intent.EXTRA_INSTALLER_PACKAGE_NAME); if (mOriginatingURI != null) { newIntent.putExtra(Intent.EXTRA_ORIGINATING_URI, mOriginatingURI); } if (mReferrerURI != null) { newIntent.putExtra(Intent.EXTRA_REFERRER, mReferrerURI); } if (installerPackageName != null) { newIntent.putExtra(Intent.EXTRA_INSTALLER_PACKAGE_NAME, installerPackageName); } if (getIntent().getBooleanExtra(Intent.EXTRA_RETURN_RESULT, false)) { newIntent.putExtra(Intent.EXTRA_RETURN_RESULT, true); newIntent.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT); } if(localLOGV) Log.i(TAG, "downloaded app uri="+mPackageURI); startActivity(newIntent); finish(); } else { mScrollView.pageScroll(View.FOCUS_DOWN); } } else if(v == mCancel) { // Cancel and finish setResult(RESULT_CANCELED); finish(); } } }
false
true
private void startInstallConfirm() { TabHost tabHost = (TabHost)findViewById(android.R.id.tabhost); tabHost.setup(); ViewPager viewPager = (ViewPager)findViewById(R.id.pager); TabsAdapter adapter = new TabsAdapter(this, tabHost, viewPager); boolean permVisible = false; mScrollView = null; mOkCanInstall = false; int msg = 0; if (mPkgInfo != null) { AppSecurityPermissions perms = new AppSecurityPermissions(this, mPkgInfo); final int NP = perms.getPermissionCount(AppSecurityPermissions.WHICH_PERSONAL); final int ND = perms.getPermissionCount(AppSecurityPermissions.WHICH_DEVICE); if (mAppInfo != null) { msg = (mAppInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0 ? R.string.install_confirm_question_update_system : R.string.install_confirm_question_update; mScrollView = new CaffeinatedScrollView(this); mScrollView.setFillViewport(true); if (perms.getPermissionCount(AppSecurityPermissions.WHICH_NEW) > 0) { permVisible = true; mScrollView.addView(perms.getPermissionsView( AppSecurityPermissions.WHICH_NEW)); } else { LayoutInflater inflater = (LayoutInflater)getSystemService( Context.LAYOUT_INFLATER_SERVICE); TextView label = (TextView)inflater.inflate(R.layout.label, null); label.setText(R.string.no_new_perms); mScrollView.addView(label); } adapter.addTab(tabHost.newTabSpec("new").setIndicator( getText(R.string.newPerms)), mScrollView); } else { findViewById(R.id.tabscontainer).setVisibility(View.GONE); } if (NP > 0 || ND > 0) { permVisible = true; LayoutInflater inflater = (LayoutInflater)getSystemService( Context.LAYOUT_INFLATER_SERVICE); View root = inflater.inflate(R.layout.permissions_list, null); if (mScrollView == null) { mScrollView = (CaffeinatedScrollView)root.findViewById(R.id.scrollview); } if (NP > 0) { ((ViewGroup)root.findViewById(R.id.privacylist)).addView( perms.getPermissionsView(AppSecurityPermissions.WHICH_PERSONAL)); } else { root.findViewById(R.id.privacylist).setVisibility(View.GONE); } if (ND > 0) { ((ViewGroup)root.findViewById(R.id.devicelist)).addView( perms.getPermissionsView(AppSecurityPermissions.WHICH_DEVICE)); } else { root.findViewById(R.id.devicelist).setVisibility(View.GONE); } adapter.addTab(tabHost.newTabSpec("all").setIndicator( getText(R.string.allPerms)), root); } } if (!permVisible) { if (msg == 0) { if (mAppInfo != null) { // This is an update to an application, but there are no // permissions at all. msg = (mAppInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0 ? R.string.install_confirm_question_update_system_no_perms : R.string.install_confirm_question_update_no_perms; } else { // This is a new application with no permissions. msg = R.string.install_confirm_question_no_perms; } } tabHost.setVisibility(View.INVISIBLE); } if (msg != 0) { ((TextView)findViewById(R.id.install_confirm_question)).setText(msg); } mInstallConfirm.setVisibility(View.VISIBLE); mOk = (Button)findViewById(R.id.ok_button); mCancel = (Button)findViewById(R.id.cancel_button); mOk.setOnClickListener(this); mCancel.setOnClickListener(this); if (mScrollView == null) { // There is nothing to scroll view, so the ok button is immediately // set to install. mOk.setText(R.string.install); mOkCanInstall = true; } else { mScrollView.setFullScrollAction(new Runnable() { @Override public void run() { mOk.setText(R.string.install); mOkCanInstall = true; } }); } }
private void startInstallConfirm() { TabHost tabHost = (TabHost)findViewById(android.R.id.tabhost); tabHost.setup(); ViewPager viewPager = (ViewPager)findViewById(R.id.pager); TabsAdapter adapter = new TabsAdapter(this, tabHost, viewPager); boolean permVisible = false; mScrollView = null; mOkCanInstall = false; int msg = 0; if (mPkgInfo != null) { AppSecurityPermissions perms = new AppSecurityPermissions(this, mPkgInfo); final int NP = perms.getPermissionCount(AppSecurityPermissions.WHICH_PERSONAL); final int ND = perms.getPermissionCount(AppSecurityPermissions.WHICH_DEVICE); if (mAppInfo != null) { msg = (mAppInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0 ? R.string.install_confirm_question_update_system : R.string.install_confirm_question_update; mScrollView = new CaffeinatedScrollView(this); mScrollView.setFillViewport(true); if (perms.getPermissionCount(AppSecurityPermissions.WHICH_NEW) > 0) { permVisible = true; mScrollView.addView(perms.getPermissionsView( AppSecurityPermissions.WHICH_NEW)); } else { LayoutInflater inflater = (LayoutInflater)getSystemService( Context.LAYOUT_INFLATER_SERVICE); TextView label = (TextView)inflater.inflate(R.layout.label, null); label.setText(R.string.no_new_perms); mScrollView.addView(label); } adapter.addTab(tabHost.newTabSpec("new").setIndicator( getText(R.string.newPerms)), mScrollView); } else { findViewById(R.id.tabscontainer).setVisibility(View.GONE); findViewById(R.id.divider).setVisibility(View.VISIBLE); } if (NP > 0 || ND > 0) { permVisible = true; LayoutInflater inflater = (LayoutInflater)getSystemService( Context.LAYOUT_INFLATER_SERVICE); View root = inflater.inflate(R.layout.permissions_list, null); if (mScrollView == null) { mScrollView = (CaffeinatedScrollView)root.findViewById(R.id.scrollview); } if (NP > 0) { ((ViewGroup)root.findViewById(R.id.privacylist)).addView( perms.getPermissionsView(AppSecurityPermissions.WHICH_PERSONAL)); } else { root.findViewById(R.id.privacylist).setVisibility(View.GONE); } if (ND > 0) { ((ViewGroup)root.findViewById(R.id.devicelist)).addView( perms.getPermissionsView(AppSecurityPermissions.WHICH_DEVICE)); } else { root.findViewById(R.id.devicelist).setVisibility(View.GONE); } adapter.addTab(tabHost.newTabSpec("all").setIndicator( getText(R.string.allPerms)), root); } } if (!permVisible) { if (msg == 0) { if (mAppInfo != null) { // This is an update to an application, but there are no // permissions at all. msg = (mAppInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0 ? R.string.install_confirm_question_update_system_no_perms : R.string.install_confirm_question_update_no_perms; } else { // This is a new application with no permissions. msg = R.string.install_confirm_question_no_perms; } } tabHost.setVisibility(View.GONE); } if (msg != 0) { ((TextView)findViewById(R.id.install_confirm_question)).setText(msg); } mInstallConfirm.setVisibility(View.VISIBLE); mOk = (Button)findViewById(R.id.ok_button); mCancel = (Button)findViewById(R.id.cancel_button); mOk.setOnClickListener(this); mCancel.setOnClickListener(this); if (mScrollView == null) { // There is nothing to scroll view, so the ok button is immediately // set to install. mOk.setText(R.string.install); mOkCanInstall = true; } else { mScrollView.setFullScrollAction(new Runnable() { @Override public void run() { mOk.setText(R.string.install); mOkCanInstall = true; } }); } }
diff --git a/src/uk/ac/gla/dcs/tp3/w/algorithm/Graph.java b/src/uk/ac/gla/dcs/tp3/w/algorithm/Graph.java index eb2f29c..6dec019 100644 --- a/src/uk/ac/gla/dcs/tp3/w/algorithm/Graph.java +++ b/src/uk/ac/gla/dcs/tp3/w/algorithm/Graph.java @@ -1,187 +1,187 @@ package uk.ac.gla.dcs.tp3.w.algorithm; import java.util.LinkedList; import uk.ac.gla.dcs.tp3.w.league.League; import uk.ac.gla.dcs.tp3.w.league.Match; import uk.ac.gla.dcs.tp3.w.league.Team; public class Graph { private Vertex[] vertices; private int[][] matrix; private Vertex source; private Vertex sink; public Graph() { this(null, null); } public Graph(League l, Team t) { if (l == null || t == null) return; // Number of team nodes is one less than total number of teams. // The team nodes do not include the team being tested for elimination. int teamTotal = l.getTeams().length; // The r-combination of teamTotal for length 2 is the number of possible // combinations for matches between the list of Teams-{t}. int gameTotal = comb(teamTotal - 1, 2); // Total number of vertices is the number of teams-1 + number of match // pairs + source + sink. vertices = new Vertex[teamTotal + gameTotal + 1]; // Set first vertex to be source, and last vertex to be sink. // Create blank vertices for source and sink. source = new Vertex(0); sink = new Vertex(vertices.length - 1); vertices[0] = source; vertices[vertices.length - 1] = sink; // Create vertices for each team node, and make them adjacent to // the sink. Team[] teamsReal = l.getTeams(); Team[] teams = new Team[teamsReal.length - 1]; // Remove team T from the working list of Teams int pos = 0; for (Team to : teamsReal) { if (!to.equals(t)) { teams[pos] = to; pos++; } } // Create vertex for each team pair and make it adjacent from the // source. // Team[i] is in vertices[vertices.length -2 -i] pos = vertices.length - 2; for (int i = 0; i < teams.length; i++) { vertices[pos] = new TeamVertex(teams[i], pos); vertices[pos].getAdjList().add( new AdjListNode(teams[i].getUpcomingMatches().length, vertices[vertices.length - 1])); pos--; } // Create vertex for each team pair and make it adjacent from the // source. pos = 1; // TODO limit this to something more sensible int infinity = Integer.MAX_VALUE; for (int i = 0; i < teams.length; i++) { for (int j = 1; j < teams.length; j++) { vertices[pos] = new PairVertex(teams[i], teams[j], pos); vertices[pos].getAdjList().add( new AdjListNode(infinity, vertices[vertices.length - 2 - i])); vertices[pos].getAdjList().add( new AdjListNode(infinity, vertices[vertices.length - 2 - j])); vertices[0].getAdjList().add(new AdjListNode(0, vertices[pos])); pos++; } } // For each match not yet played and not involving t, increment the // capacity of the vertex going from home and away team node->sink and // float->pair node of home and away for (Match M : l.getFixtures()) { - if (!M.isPlayed() && !(M.getAwayTeam().equals(t)) - || M.getHomeTeam().equals(t)) { + if (!M.isPlayed() + && !(M.getAwayTeam().equals(t) || M.getHomeTeam().equals(t))) { Team home = M.getHomeTeam(); Team away = M.getAwayTeam(); for (int i = vertices.length - 2; i < teams.length; i--) { TeamVertex TV = (TeamVertex) vertices[i]; if (TV.getTeam().equals(home)) { vertices[i].getAdjList().peek().incCapacity(); } else if (TV.getTeam().equals(away)) { vertices[i].getAdjList().peek().incCapacity(); } } for (AdjListNode A : vertices[0].getAdjList()) { PairVertex PV = (PairVertex) A.getVertex(); if ((PV.getTeamA().equals(home) && PV.getTeamB().equals( away)) || PV.getTeamA().equals(away) && PV.getTeamB().equals(home)) { A.incCapacity(); } } } } // TODO Create the adjacency matrix representation of the graph. } public Vertex[] getV() { return vertices; } public void setV(Vertex[] v) { this.vertices = v; } public int[][] getMatrix() { return matrix; } public int getSize() { return vertices.length; } public void setMatrix(int[][] matrix) { this.matrix = matrix; } public Vertex getSource() { return source; } public void setSource(Vertex source) { this.source = source; } public Vertex getSink() { return sink; } public void setSink(Vertex sink) { this.sink = sink; } private static int fact(int s) { // For s < 2, the factorial is 1. Otherwise, multiply s by fact(s-1) return (s < 2) ? 1 : s * fact(s - 1); } private static int comb(int n, int r) { // r-combination of size n is n!/r!(n-r)! return (fact(n) / (fact(r) * fact(n - r))); } /** * carry out a breadth first search/traversal of the graph */ public void bfs() { // TODO Read over this code, I (GR) just dropped this in here from // bfs-example. for (Vertex v : vertices) v.setVisited(false); LinkedList<Vertex> queue = new LinkedList<Vertex>(); for (Vertex v : vertices) { if (!v.getVisited()) { v.setVisited(true); v.setPredecessor(v.getIndex()); queue.add(v); while (!queue.isEmpty()) { Vertex u = queue.removeFirst(); LinkedList<AdjListNode> list = u.getAdjList(); for (AdjListNode node : list) { Vertex w = node.getVertex(); if (!w.getVisited()) { w.setVisited(true); w.setPredecessor(u.getIndex()); queue.add(w); } } } } } } }
true
true
public Graph(League l, Team t) { if (l == null || t == null) return; // Number of team nodes is one less than total number of teams. // The team nodes do not include the team being tested for elimination. int teamTotal = l.getTeams().length; // The r-combination of teamTotal for length 2 is the number of possible // combinations for matches between the list of Teams-{t}. int gameTotal = comb(teamTotal - 1, 2); // Total number of vertices is the number of teams-1 + number of match // pairs + source + sink. vertices = new Vertex[teamTotal + gameTotal + 1]; // Set first vertex to be source, and last vertex to be sink. // Create blank vertices for source and sink. source = new Vertex(0); sink = new Vertex(vertices.length - 1); vertices[0] = source; vertices[vertices.length - 1] = sink; // Create vertices for each team node, and make them adjacent to // the sink. Team[] teamsReal = l.getTeams(); Team[] teams = new Team[teamsReal.length - 1]; // Remove team T from the working list of Teams int pos = 0; for (Team to : teamsReal) { if (!to.equals(t)) { teams[pos] = to; pos++; } } // Create vertex for each team pair and make it adjacent from the // source. // Team[i] is in vertices[vertices.length -2 -i] pos = vertices.length - 2; for (int i = 0; i < teams.length; i++) { vertices[pos] = new TeamVertex(teams[i], pos); vertices[pos].getAdjList().add( new AdjListNode(teams[i].getUpcomingMatches().length, vertices[vertices.length - 1])); pos--; } // Create vertex for each team pair and make it adjacent from the // source. pos = 1; // TODO limit this to something more sensible int infinity = Integer.MAX_VALUE; for (int i = 0; i < teams.length; i++) { for (int j = 1; j < teams.length; j++) { vertices[pos] = new PairVertex(teams[i], teams[j], pos); vertices[pos].getAdjList().add( new AdjListNode(infinity, vertices[vertices.length - 2 - i])); vertices[pos].getAdjList().add( new AdjListNode(infinity, vertices[vertices.length - 2 - j])); vertices[0].getAdjList().add(new AdjListNode(0, vertices[pos])); pos++; } } // For each match not yet played and not involving t, increment the // capacity of the vertex going from home and away team node->sink and // float->pair node of home and away for (Match M : l.getFixtures()) { if (!M.isPlayed() && !(M.getAwayTeam().equals(t)) || M.getHomeTeam().equals(t)) { Team home = M.getHomeTeam(); Team away = M.getAwayTeam(); for (int i = vertices.length - 2; i < teams.length; i--) { TeamVertex TV = (TeamVertex) vertices[i]; if (TV.getTeam().equals(home)) { vertices[i].getAdjList().peek().incCapacity(); } else if (TV.getTeam().equals(away)) { vertices[i].getAdjList().peek().incCapacity(); } } for (AdjListNode A : vertices[0].getAdjList()) { PairVertex PV = (PairVertex) A.getVertex(); if ((PV.getTeamA().equals(home) && PV.getTeamB().equals( away)) || PV.getTeamA().equals(away) && PV.getTeamB().equals(home)) { A.incCapacity(); } } } } // TODO Create the adjacency matrix representation of the graph. }
public Graph(League l, Team t) { if (l == null || t == null) return; // Number of team nodes is one less than total number of teams. // The team nodes do not include the team being tested for elimination. int teamTotal = l.getTeams().length; // The r-combination of teamTotal for length 2 is the number of possible // combinations for matches between the list of Teams-{t}. int gameTotal = comb(teamTotal - 1, 2); // Total number of vertices is the number of teams-1 + number of match // pairs + source + sink. vertices = new Vertex[teamTotal + gameTotal + 1]; // Set first vertex to be source, and last vertex to be sink. // Create blank vertices for source and sink. source = new Vertex(0); sink = new Vertex(vertices.length - 1); vertices[0] = source; vertices[vertices.length - 1] = sink; // Create vertices for each team node, and make them adjacent to // the sink. Team[] teamsReal = l.getTeams(); Team[] teams = new Team[teamsReal.length - 1]; // Remove team T from the working list of Teams int pos = 0; for (Team to : teamsReal) { if (!to.equals(t)) { teams[pos] = to; pos++; } } // Create vertex for each team pair and make it adjacent from the // source. // Team[i] is in vertices[vertices.length -2 -i] pos = vertices.length - 2; for (int i = 0; i < teams.length; i++) { vertices[pos] = new TeamVertex(teams[i], pos); vertices[pos].getAdjList().add( new AdjListNode(teams[i].getUpcomingMatches().length, vertices[vertices.length - 1])); pos--; } // Create vertex for each team pair and make it adjacent from the // source. pos = 1; // TODO limit this to something more sensible int infinity = Integer.MAX_VALUE; for (int i = 0; i < teams.length; i++) { for (int j = 1; j < teams.length; j++) { vertices[pos] = new PairVertex(teams[i], teams[j], pos); vertices[pos].getAdjList().add( new AdjListNode(infinity, vertices[vertices.length - 2 - i])); vertices[pos].getAdjList().add( new AdjListNode(infinity, vertices[vertices.length - 2 - j])); vertices[0].getAdjList().add(new AdjListNode(0, vertices[pos])); pos++; } } // For each match not yet played and not involving t, increment the // capacity of the vertex going from home and away team node->sink and // float->pair node of home and away for (Match M : l.getFixtures()) { if (!M.isPlayed() && !(M.getAwayTeam().equals(t) || M.getHomeTeam().equals(t))) { Team home = M.getHomeTeam(); Team away = M.getAwayTeam(); for (int i = vertices.length - 2; i < teams.length; i--) { TeamVertex TV = (TeamVertex) vertices[i]; if (TV.getTeam().equals(home)) { vertices[i].getAdjList().peek().incCapacity(); } else if (TV.getTeam().equals(away)) { vertices[i].getAdjList().peek().incCapacity(); } } for (AdjListNode A : vertices[0].getAdjList()) { PairVertex PV = (PairVertex) A.getVertex(); if ((PV.getTeamA().equals(home) && PV.getTeamB().equals( away)) || PV.getTeamA().equals(away) && PV.getTeamB().equals(home)) { A.incCapacity(); } } } } // TODO Create the adjacency matrix representation of the graph. }
diff --git a/src/org/harleydroid/J1850.java b/src/org/harleydroid/J1850.java index e26cce2..8c377cb 100644 --- a/src/org/harleydroid/J1850.java +++ b/src/org/harleydroid/J1850.java @@ -1,196 +1,186 @@ // // HarleyDroid: Harley Davidson J1850 Data Analyser for Android. // // Copyright (C) 2010,2011 Stelian Pop <[email protected]> // Based on various sources, especially: // minigpsd by Tom Zerucha <[email protected]> // AVR J1850 VPW Interface by Michael Wolf <[email protected]> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 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 org.harleydroid; public class J1850 { public static final int MAXBUF = 1024; // last reading of odometer ticks private static int odolast = 0; // accumulated odometer ticks (deals with overflow at 0xffff) private static int odoaccum = 0; // last reading of fuel ticks private static int fuellast = 0; // accumulated fuel ticks (deals with overflow at 0xffff) private static int fuelaccum = 0; static byte[] bytes_to_hex(byte[] in) { byte out[] = new byte[MAXBUF]; int inidx = 0, outidx = 0; while (inidx < in.length) { int digit0, digit1; while (inidx < in.length && Character.isWhitespace((char)in[inidx])) inidx++; if (inidx >= in.length) break; digit0 = Character.digit((char)in[inidx++], 16); while (inidx < in.length && Character.isWhitespace((char)in[inidx])) inidx++; if (inidx >= in.length) break; digit1 = Character.digit((char)in[inidx++], 16); out[outidx++] = (byte) (digit0 * 16 + digit1); } byte[] ret = new byte[outidx]; System.arraycopy(out, 0, ret, 0, outidx); return ret; } public static byte crc(byte[] in) { int i, j; byte crc = (byte)0xff; for (i = 0; i < in.length; i++) { byte c = in[i]; for (j = 0; j < 8; ++j) { byte poly = 0; if ((0x80 & (crc ^ c)) != 0) poly = 0x1d; crc = (byte) (((crc << 1) & 0xff) ^ poly); c <<= 1; } } return crc; } public static void parse(byte[] buffer, HarleyData hd) throws Exception { byte[] in; int x; int y; in = bytes_to_hex(buffer); /* System.out.print("BUF: "); for (int i = 0; i < in.length; i++) System.out.print(Integer.toHexString(in[i]) + " "); System.out.println(""); */ if (crc(in) != (byte)0xc4) throw new Exception("crc"); x = y = 0; if (in.length >= 4) x = ((in[0] << 24) & 0xff000000) | ((in[1] << 16) & 0x00ff0000) | ((in[2] << 8) & 0x0000ff00) | (in[3] & 0x000000ff); if (in.length >= 6) y = ((in[4] << 8) & 0x0000ff00) | (in[5] & 0x000000ff); if (x == 0x281b1002) hd.setRPM(y * 250); else if (x == 0x48291002) hd.setSpeed(y * 5); else if (x == 0xa8491010) hd.setEngineTemp(in[4]); else if (x == 0xa83b1003) { if (in[4] != 0) { int gear = 0; while ((in[4] >>= 1) != 0) gear++; hd.setGear(gear); } else hd.setGear(-1); } else if ((x == 0x48da4039) && ((in[4] & 0xfc) == 0)) hd.setTurnSignals(in[4] & 0x03); else if ((x & 0xffffff7f) == 0xa8691006) { - if ((x & 0x80) == 0) { - odolast = y - odolast; - if (odolast < 0) - odolast += 65536; - odoaccum += odolast; - odolast = y; - } else { - odoaccum = 0; - odolast = 0; - } + odolast = y - odolast; + if (odolast < 0) // ...could also test for (x & 0x80) + odolast += 65536; + odoaccum += odolast; + odolast = y; hd.setOdometer(odoaccum); } else if ((x & 0xffffff7f) == 0xa883100a) { - if ((x & 0x80) == 0) { - fuellast = y - fuellast; - if (fuellast < 0) - fuellast += 65536; - fuelaccum += fuellast; - fuellast = y; - } else { - fuelaccum = 0; - fuellast = 0; - } + fuellast = y - fuellast; + if (fuellast < 0) // ...could also test for (x & 0x80) + fuellast += 65536; + fuelaccum += fuellast; + fuellast = y; hd.setFuel(fuelaccum); } else if ((x == 0xa8836112) && ((in[4] & 0xd0) == 0xd0)) hd.setFull(in[4] & 0x0f); else if ((x & 0xffffff5d) == 0x483b4000) { hd.setNeutral((in[3] & 0x20) != 0); hd.setClutch((in[3] & 0x80) != 0); } else if (x == 0x68881003 || x == 0x68ff1003 || x == 0x68ff4003 || x == 0x68ff6103 || x == 0xc888100e || x == 0xc8896103 || x == 0xe889610e) { /* ping */ } else if ((x & 0xffffff7f) == 0x4892402a || (x & 0xffffff7f) == 0x6893612a) { /* shutdown - lock */ } else if (x == 0x68881083) { hd.setCheckEngine(true); } else throw new Exception("unknown"); } public static void main(String[] args) { // String line = "28 1B 10 02 00 00 D5"; // String line = "C8 88 10 0E BA "; // String line = "E8 89 61 0E 18 "; String line = "28 1B 10 02 10 74 4C"; byte[] in = line.getBytes(); for (int i = 0; i < in.length; i++) System.out.println("in[" + i + "] = " + in[i]); byte[] out = bytes_to_hex(in); for (int i = 0; i < out.length; i++) System.out.println("out[" + i + "] = " + out[i]); System.out.println("crc = " + crc(out)); try { HarleyData data = new HarleyData(); parse(in, data); System.out.println(data); } catch (Exception e) { e.printStackTrace(); } } }
false
true
public static void parse(byte[] buffer, HarleyData hd) throws Exception { byte[] in; int x; int y; in = bytes_to_hex(buffer); /* System.out.print("BUF: "); for (int i = 0; i < in.length; i++) System.out.print(Integer.toHexString(in[i]) + " "); System.out.println(""); */ if (crc(in) != (byte)0xc4) throw new Exception("crc"); x = y = 0; if (in.length >= 4) x = ((in[0] << 24) & 0xff000000) | ((in[1] << 16) & 0x00ff0000) | ((in[2] << 8) & 0x0000ff00) | (in[3] & 0x000000ff); if (in.length >= 6) y = ((in[4] << 8) & 0x0000ff00) | (in[5] & 0x000000ff); if (x == 0x281b1002) hd.setRPM(y * 250); else if (x == 0x48291002) hd.setSpeed(y * 5); else if (x == 0xa8491010) hd.setEngineTemp(in[4]); else if (x == 0xa83b1003) { if (in[4] != 0) { int gear = 0; while ((in[4] >>= 1) != 0) gear++; hd.setGear(gear); } else hd.setGear(-1); } else if ((x == 0x48da4039) && ((in[4] & 0xfc) == 0)) hd.setTurnSignals(in[4] & 0x03); else if ((x & 0xffffff7f) == 0xa8691006) { if ((x & 0x80) == 0) { odolast = y - odolast; if (odolast < 0) odolast += 65536; odoaccum += odolast; odolast = y; } else { odoaccum = 0; odolast = 0; } hd.setOdometer(odoaccum); } else if ((x & 0xffffff7f) == 0xa883100a) { if ((x & 0x80) == 0) { fuellast = y - fuellast; if (fuellast < 0) fuellast += 65536; fuelaccum += fuellast; fuellast = y; } else { fuelaccum = 0; fuellast = 0; } hd.setFuel(fuelaccum); } else if ((x == 0xa8836112) && ((in[4] & 0xd0) == 0xd0)) hd.setFull(in[4] & 0x0f); else if ((x & 0xffffff5d) == 0x483b4000) { hd.setNeutral((in[3] & 0x20) != 0); hd.setClutch((in[3] & 0x80) != 0); } else if (x == 0x68881003 || x == 0x68ff1003 || x == 0x68ff4003 || x == 0x68ff6103 || x == 0xc888100e || x == 0xc8896103 || x == 0xe889610e) { /* ping */ } else if ((x & 0xffffff7f) == 0x4892402a || (x & 0xffffff7f) == 0x6893612a) { /* shutdown - lock */ } else if (x == 0x68881083) { hd.setCheckEngine(true); } else throw new Exception("unknown"); }
public static void parse(byte[] buffer, HarleyData hd) throws Exception { byte[] in; int x; int y; in = bytes_to_hex(buffer); /* System.out.print("BUF: "); for (int i = 0; i < in.length; i++) System.out.print(Integer.toHexString(in[i]) + " "); System.out.println(""); */ if (crc(in) != (byte)0xc4) throw new Exception("crc"); x = y = 0; if (in.length >= 4) x = ((in[0] << 24) & 0xff000000) | ((in[1] << 16) & 0x00ff0000) | ((in[2] << 8) & 0x0000ff00) | (in[3] & 0x000000ff); if (in.length >= 6) y = ((in[4] << 8) & 0x0000ff00) | (in[5] & 0x000000ff); if (x == 0x281b1002) hd.setRPM(y * 250); else if (x == 0x48291002) hd.setSpeed(y * 5); else if (x == 0xa8491010) hd.setEngineTemp(in[4]); else if (x == 0xa83b1003) { if (in[4] != 0) { int gear = 0; while ((in[4] >>= 1) != 0) gear++; hd.setGear(gear); } else hd.setGear(-1); } else if ((x == 0x48da4039) && ((in[4] & 0xfc) == 0)) hd.setTurnSignals(in[4] & 0x03); else if ((x & 0xffffff7f) == 0xa8691006) { odolast = y - odolast; if (odolast < 0) // ...could also test for (x & 0x80) odolast += 65536; odoaccum += odolast; odolast = y; hd.setOdometer(odoaccum); } else if ((x & 0xffffff7f) == 0xa883100a) { fuellast = y - fuellast; if (fuellast < 0) // ...could also test for (x & 0x80) fuellast += 65536; fuelaccum += fuellast; fuellast = y; hd.setFuel(fuelaccum); } else if ((x == 0xa8836112) && ((in[4] & 0xd0) == 0xd0)) hd.setFull(in[4] & 0x0f); else if ((x & 0xffffff5d) == 0x483b4000) { hd.setNeutral((in[3] & 0x20) != 0); hd.setClutch((in[3] & 0x80) != 0); } else if (x == 0x68881003 || x == 0x68ff1003 || x == 0x68ff4003 || x == 0x68ff6103 || x == 0xc888100e || x == 0xc8896103 || x == 0xe889610e) { /* ping */ } else if ((x & 0xffffff7f) == 0x4892402a || (x & 0xffffff7f) == 0x6893612a) { /* shutdown - lock */ } else if (x == 0x68881083) { hd.setCheckEngine(true); } else throw new Exception("unknown"); }
diff --git a/backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/storage/StorageHandlingCommandBase.java b/backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/storage/StorageHandlingCommandBase.java index ccbe69d8..c74b1af5 100644 --- a/backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/storage/StorageHandlingCommandBase.java +++ b/backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/storage/StorageHandlingCommandBase.java @@ -1,372 +1,372 @@ package org.ovirt.engine.core.bll.storage; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.ovirt.engine.core.bll.Backend; import org.ovirt.engine.core.bll.CommandBase; import org.ovirt.engine.core.common.VdcObjectType; import org.ovirt.engine.core.common.action.StoragePoolParametersBase; import org.ovirt.engine.core.common.businessentities.IVdcQueryable; import org.ovirt.engine.core.common.businessentities.StorageDomainSharedStatus; import org.ovirt.engine.core.common.businessentities.StorageDomainStatus; import org.ovirt.engine.core.common.businessentities.StorageDomainType; import org.ovirt.engine.core.common.businessentities.StorageFormatType; import org.ovirt.engine.core.common.businessentities.StoragePoolStatus; import org.ovirt.engine.core.common.businessentities.VDS; import org.ovirt.engine.core.common.businessentities.storage_domains; import org.ovirt.engine.core.common.businessentities.storage_pool; import org.ovirt.engine.core.common.config.Config; import org.ovirt.engine.core.common.config.ConfigValues; import org.ovirt.engine.core.common.interfaces.SearchType; import org.ovirt.engine.core.common.queries.SearchParameters; import org.ovirt.engine.core.common.queries.VdcQueryType; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.compat.TransactionScopeOption; import org.ovirt.engine.core.compat.Version; import org.ovirt.engine.core.dal.VdcBllMessages; import org.ovirt.engine.core.dal.dbbroker.DbFacade; import org.ovirt.engine.core.utils.SyncronizeNumberOfAsyncOperations; import org.ovirt.engine.core.utils.linq.All; import org.ovirt.engine.core.utils.linq.LinqUtils; import org.ovirt.engine.core.utils.linq.Predicate; import org.ovirt.engine.core.utils.transaction.TransactionMethod; import org.ovirt.engine.core.utils.transaction.TransactionSupport; public abstract class StorageHandlingCommandBase<T extends StoragePoolParametersBase> extends CommandBase<T> { public StorageHandlingCommandBase(T parameters) { super(parameters); if (getParameters() != null && !getParameters().getStoragePoolId().equals(Guid.Empty)) { setStoragePoolId(getParameters().getStoragePoolId()); } } /** * Constructor for command creation when compensation is applied on startup * * @param commandId */ protected StorageHandlingCommandBase(Guid commandId) { super(commandId); } public static final String UpVdssInStoragePoolQuery = "HOST: status = UP and DATACENTER = {0}"; public static final String UpVdssInCluster = "HOST: status = UP and CLUSTER = {0}"; public static final String DesktopsInStoragePoolQuery = "VMS: DATACENTER = {0}"; public static List<VDS> GetAllRunningVdssInPool(storage_pool pool) { java.util.ArrayList<VDS> returnValue = new java.util.ArrayList<VDS>(); SearchParameters p = new SearchParameters(MessageFormat.format(UpVdssInStoragePoolQuery, pool.getname()), SearchType.VDS); p.setMaxCount(Integer.MAX_VALUE); Iterable<IVdcQueryable> fromVds = (Iterable<IVdcQueryable>) (Backend.getInstance().runInternalQuery( VdcQueryType.Search, p).getReturnValue()); if (fromVds != null) { for (IVdcQueryable vds : fromVds) { if (vds instanceof VDS) { returnValue.add((VDS) vds); } } } return returnValue; } protected void updateStoragePoolInDiffTransaction() { TransactionSupport.executeInScope(TransactionScopeOption.Suppress, new TransactionMethod<Object>() { @Override public Object runInTransaction() { DbFacade.getInstance().getStoragePoolDAO().update(getStoragePool()); return null; } }); } protected List<VDS> getAllRunningVdssInPool() { return GetAllRunningVdssInPool(getStoragePool()); } protected Guid getMasterDomainIdFromDb() { if (getStoragePool() != null) { return DbFacade.getInstance() .getStorageDomainDAO() .getMasterStorageDomainIdForPool(getStoragePool().getId()); } else { return Guid.Empty; } } protected boolean InitializeVds() { boolean returnValue = true; if (getVds() == null) { SearchParameters p = new SearchParameters(MessageFormat.format(UpVdssInStoragePoolQuery, getStoragePool() .getname()), SearchType.VDS); p.setMaxCount(Integer.MAX_VALUE); Object tempVar = LinqUtils.firstOrNull((List) Backend.getInstance() .runInternalQuery(VdcQueryType.Search, p).getReturnValue(), new All()); setVds(((VDS) ((tempVar instanceof VDS) ? tempVar : null))); if (getVds() == null) { returnValue = false; addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_NO_VDS_IN_POOL); } } return returnValue; } protected boolean CheckStoragePool() { boolean returnValue = false; if (getStoragePool() != null) { returnValue = DbFacade.getInstance().getStoragePoolDAO().get(getStoragePool().getId()) != null; } if (!returnValue) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_POOL_NOT_EXIST); } return returnValue; } protected boolean CheckStoragePoolStatus(StoragePoolStatus status) { boolean returnValue = false; if (getStoragePool() != null) { storage_pool storagePool = DbFacade.getInstance().getStoragePoolDAO().get(getStoragePool().getId()); returnValue = (storagePool.getstatus() == status); if (!returnValue && !getReturnValue().getCanDoActionMessages().contains( VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_POOL_STATUS_ILLEGAL.toString())) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_POOL_STATUS_ILLEGAL); } } return returnValue; } protected boolean CheckStoragePoolStatusNotEqual(StoragePoolStatus status, VdcBllMessages onFailMessage) { boolean returnValue = false; if (getStoragePool() != null) { storage_pool storagePool = DbFacade.getInstance().getStoragePoolDAO().get(getStoragePool().getId()); returnValue = (storagePool.getstatus() != status); if (!returnValue && !getReturnValue().getCanDoActionMessages().contains(onFailMessage.name())) { addCanDoActionMessage(onFailMessage); } } return returnValue; } protected boolean isStorageDomainTypeCorrect(storage_domains storageDomain) { if (storageDomain.getstorage_domain_type() != StorageDomainType.ISO && storageDomain.getstorage_domain_type() != StorageDomainType.ImportExport && getStoragePool().getstorage_pool_type() != storageDomain.getstorage_type()) { addCanDoActionMessage(VdcBllMessages.ERROR_CANNOT_ATTACH_STORAGE_DOMAIN_STORAGE_TYPE_NOT_MATCH); return false; } return true; } protected boolean isStorageDomainNotInPool(storage_domains storageDomain) { boolean returnValue = false; if (storageDomain != null) { // check if there is no pool-domain map returnValue = DbFacade.getInstance() .getStoragePoolIsoMapDAO() .getAllForStorage(storageDomain.getid()) .size() == 0; if (!returnValue) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_DOMAIN_STATUS_ILLEGAL); } } return returnValue; } protected boolean checkDomainCanBeAttached(storage_domains storageDomain) { return checkStorageDomainType(storageDomain) && isStorageDomainFormatCorrectForPool(storageDomain, getStoragePool()) && checkStorageDomainSharedStatusNotLocked(storageDomain) && ((storageDomain.getstorage_domain_type() == StorageDomainType.ISO || storageDomain.getstorage_domain_type() == StorageDomainType.ImportExport) || isStorageDomainNotInPool(storageDomain)) && isStorageDomainTypeCorrect(storageDomain); } /** * Check that we are not trying to attach more than one ISO or export * domain to the same data center. */ protected boolean checkStorageDomainType(final storage_domains storageDomain) { // Nothing to check if the storage domain is not an ISO or export: final StorageDomainType type = storageDomain.getstorage_domain_type(); if (type != StorageDomainType.ISO && type != StorageDomainType.ImportExport) { return true; } // Get the number of storage domains of the given type currently attached // to the pool: int count = LinqUtils.filter( DbFacade.getInstance().getStorageDomainDAO().getAllForStoragePool(getStoragePool().getId()), new Predicate<storage_domains>() { @Override public boolean eval(storage_domains a) { return a.getstorage_domain_type() == type; } } ).size(); // If the count is zero we are okay, we can add a new one: if (count == 0) { return true; } // If we are here then we already have at least one storage type of the given type // so whe have to prepare a friendy message for the user (see #713160) and fail: if (type == StorageDomainType.ISO) { addCanDoActionMessage(VdcBllMessages.ERROR_CANNOT_ATTACH_MORE_THAN_ONE_ISO_DOMAIN); } else if (type == StorageDomainType.ImportExport) { addCanDoActionMessage(VdcBllMessages.ERROR_CANNOT_ATTACH_MORE_THAN_ONE_EXPORT_DOMAIN); } return false; } protected boolean checkStorageDomainSharedStatusNotLocked(storage_domains storageDomain) { boolean returnValue = storageDomain != null && storageDomain.getstorage_domain_shared_status() != StorageDomainSharedStatus.Locked; if (!returnValue) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_DOMAIN_STATUS_ILLEGAL); } return returnValue; } protected boolean isStorageDomainNotNull(storage_domains domain) { if (domain == null) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_DOMAIN_NOT_EXIST); return false; } return true; } protected void CalcStoragePoolStatusByDomainsStatus() { List<storage_domains> domains = DbFacade.getInstance().getStorageDomainDAO().getAllForStoragePool( getStoragePool().getId()); // storage_domains masterDomain = null; //LINQ 31899 domains.Where(a => // a.storage_domain_type == StorageDomainType.Master).FirstOrDefault(); storage_domains masterDomain = LinqUtils.firstOrNull(domains, new Predicate<storage_domains>() { @Override public boolean eval(storage_domains a) { return a.getstorage_domain_type() == StorageDomainType.Master; } }); // if no master then Uninitialized // if master not active maintenance StoragePoolStatus newStatus = (masterDomain == null) ? StoragePoolStatus.Uninitialized - : (masterDomain.getstatus() != null && masterDomain.getstatus() == StorageDomainStatus.InActive) ? StoragePoolStatus.Maintanance + : (masterDomain.getstatus() != null && masterDomain.getstatus() == StorageDomainStatus.Maintenance) ? StoragePoolStatus.Maintanance : (masterDomain.getstatus() != null && masterDomain.getstatus() == StorageDomainStatus.Active) ? StoragePoolStatus.Up : StoragePoolStatus.Problematic; if (newStatus != getStoragePool().getstatus()) { getCompensationContext().snapshotEntity(getStoragePool()); getStoragePool().setstatus(newStatus); storage_pool poolFromDb = DbFacade.getInstance().getStoragePoolDAO().get(getStoragePool().getId()); if ((getStoragePool().getspm_vds_id() == null && poolFromDb.getspm_vds_id() != null) || (getStoragePool().getspm_vds_id() != null && !getStoragePool().getspm_vds_id().equals( poolFromDb.getspm_vds_id()))) { getStoragePool().setspm_vds_id(poolFromDb.getspm_vds_id()); } if (getStoragePool().getstatus() == StoragePoolStatus.Uninitialized) { getStoragePool().setspm_vds_id(null); } TransactionSupport.executeInScope(TransactionScopeOption.Required, new TransactionMethod<storage_pool>() { @Override public storage_pool runInTransaction() { DbFacade.getInstance().getStoragePoolDAO().update(getStoragePool()); return null; } }); StoragePoolStatusHandler.PoolStatusChanged(getStoragePool().getId(), getStoragePool().getstatus()); } } protected boolean CheckStoragePoolNameLengthValid() { boolean result = true; if (getStoragePool().getname().length() > Config.<Integer> GetValue(ConfigValues.StoragePoolNameSizeLimit)) { result = false; addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_NAME_LENGTH_IS_TOO_LONG); } return result; } /** * The following method should check if the format of the storage domain allows to it to be attached to the storage * pool. At case of failure the false value will be return and appropriate error message will be added to * canDoActionMessages * @param storageDomain * -the domain object * @param storagePool * - the pool object * @return */ protected boolean isStorageDomainFormatCorrectForPool(storage_domains storageDomain, storage_pool storagePool) { if (storageDomain.getstorage_domain_type() == StorageDomainType.ISO || storageDomain.getstorage_domain_type() == StorageDomainType.ImportExport) { return true; } Set<StorageFormatType> supportedFormatsSet = getSupportedStorageFormatSet(storagePool.getcompatibility_version()); if (supportedFormatsSet.contains(storageDomain.getStorageFormat())) { if (storagePool.getStoragePoolFormatType() == null || storagePool.getStoragePoolFormatType() == storageDomain.getStorageFormat()) { return true; } } addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_DOMAIN_FORMAT_ILLEGAL); getReturnValue().getCanDoActionMessages().add( String.format("$storageFormat %1$s", storageDomain.getStorageFormat().toString())); return false; } protected Set<StorageFormatType> getSupportedStorageFormatSet(Version version) { String[] supportedFormats = Config.<String> GetValue(ConfigValues.SupportedStorageFormats, version.toString()).split("[,]"); Set<StorageFormatType> supportedFormatsSet = new HashSet<StorageFormatType>(); for (String supportedFormat : supportedFormats) { supportedFormatsSet.add(StorageFormatType.forValue(supportedFormat)); } return supportedFormatsSet; } protected void runSynchronizeOperation(ActivateDeactivateSingleAsyncOperationFactory factory, Object... addionalParams) { List<VDS> allRunningVdsInPool = getAllRunningVdssInPool(); ArrayList parameters = InitAsyncOperationParameters(allRunningVdsInPool); if (addionalParams.length > 0) { parameters.addAll(Arrays.asList(addionalParams)); } SyncronizeNumberOfAsyncOperations sync = new SyncronizeNumberOfAsyncOperations(allRunningVdsInPool.size(), parameters, factory); sync.Execute(); } private java.util.ArrayList InitAsyncOperationParameters(List<VDS> allRunningVdsInPool) { java.util.ArrayList parameters = new java.util.ArrayList(); parameters.add(allRunningVdsInPool); parameters.add(getStorageDomain()); parameters.add(getStoragePool()); return parameters; } @Override public Map<Guid, VdcObjectType> getPermissionCheckSubjects() { return Collections.singletonMap(getStoragePoolId() == null ? null : getStoragePoolId().getValue(), VdcObjectType.StoragePool); } }
true
true
protected void CalcStoragePoolStatusByDomainsStatus() { List<storage_domains> domains = DbFacade.getInstance().getStorageDomainDAO().getAllForStoragePool( getStoragePool().getId()); // storage_domains masterDomain = null; //LINQ 31899 domains.Where(a => // a.storage_domain_type == StorageDomainType.Master).FirstOrDefault(); storage_domains masterDomain = LinqUtils.firstOrNull(domains, new Predicate<storage_domains>() { @Override public boolean eval(storage_domains a) { return a.getstorage_domain_type() == StorageDomainType.Master; } }); // if no master then Uninitialized // if master not active maintenance StoragePoolStatus newStatus = (masterDomain == null) ? StoragePoolStatus.Uninitialized : (masterDomain.getstatus() != null && masterDomain.getstatus() == StorageDomainStatus.InActive) ? StoragePoolStatus.Maintanance : (masterDomain.getstatus() != null && masterDomain.getstatus() == StorageDomainStatus.Active) ? StoragePoolStatus.Up : StoragePoolStatus.Problematic; if (newStatus != getStoragePool().getstatus()) { getCompensationContext().snapshotEntity(getStoragePool()); getStoragePool().setstatus(newStatus); storage_pool poolFromDb = DbFacade.getInstance().getStoragePoolDAO().get(getStoragePool().getId()); if ((getStoragePool().getspm_vds_id() == null && poolFromDb.getspm_vds_id() != null) || (getStoragePool().getspm_vds_id() != null && !getStoragePool().getspm_vds_id().equals( poolFromDb.getspm_vds_id()))) { getStoragePool().setspm_vds_id(poolFromDb.getspm_vds_id()); } if (getStoragePool().getstatus() == StoragePoolStatus.Uninitialized) { getStoragePool().setspm_vds_id(null); } TransactionSupport.executeInScope(TransactionScopeOption.Required, new TransactionMethod<storage_pool>() { @Override public storage_pool runInTransaction() { DbFacade.getInstance().getStoragePoolDAO().update(getStoragePool()); return null; } }); StoragePoolStatusHandler.PoolStatusChanged(getStoragePool().getId(), getStoragePool().getstatus()); } }
protected void CalcStoragePoolStatusByDomainsStatus() { List<storage_domains> domains = DbFacade.getInstance().getStorageDomainDAO().getAllForStoragePool( getStoragePool().getId()); // storage_domains masterDomain = null; //LINQ 31899 domains.Where(a => // a.storage_domain_type == StorageDomainType.Master).FirstOrDefault(); storage_domains masterDomain = LinqUtils.firstOrNull(domains, new Predicate<storage_domains>() { @Override public boolean eval(storage_domains a) { return a.getstorage_domain_type() == StorageDomainType.Master; } }); // if no master then Uninitialized // if master not active maintenance StoragePoolStatus newStatus = (masterDomain == null) ? StoragePoolStatus.Uninitialized : (masterDomain.getstatus() != null && masterDomain.getstatus() == StorageDomainStatus.Maintenance) ? StoragePoolStatus.Maintanance : (masterDomain.getstatus() != null && masterDomain.getstatus() == StorageDomainStatus.Active) ? StoragePoolStatus.Up : StoragePoolStatus.Problematic; if (newStatus != getStoragePool().getstatus()) { getCompensationContext().snapshotEntity(getStoragePool()); getStoragePool().setstatus(newStatus); storage_pool poolFromDb = DbFacade.getInstance().getStoragePoolDAO().get(getStoragePool().getId()); if ((getStoragePool().getspm_vds_id() == null && poolFromDb.getspm_vds_id() != null) || (getStoragePool().getspm_vds_id() != null && !getStoragePool().getspm_vds_id().equals( poolFromDb.getspm_vds_id()))) { getStoragePool().setspm_vds_id(poolFromDb.getspm_vds_id()); } if (getStoragePool().getstatus() == StoragePoolStatus.Uninitialized) { getStoragePool().setspm_vds_id(null); } TransactionSupport.executeInScope(TransactionScopeOption.Required, new TransactionMethod<storage_pool>() { @Override public storage_pool runInTransaction() { DbFacade.getInstance().getStoragePoolDAO().update(getStoragePool()); return null; } }); StoragePoolStatusHandler.PoolStatusChanged(getStoragePool().getId(), getStoragePool().getstatus()); } }
diff --git a/app/src/main/java/com/donnfelker/android/bootstrap/BootstrapServiceProvider.java b/app/src/main/java/com/donnfelker/android/bootstrap/BootstrapServiceProvider.java index 6d03c8e..75797ff 100644 --- a/app/src/main/java/com/donnfelker/android/bootstrap/BootstrapServiceProvider.java +++ b/app/src/main/java/com/donnfelker/android/bootstrap/BootstrapServiceProvider.java @@ -1,34 +1,34 @@ package com.donnfelker.android.bootstrap; import android.accounts.AccountsException; import android.app.Activity; import com.donnfelker.android.bootstrap.authenticator.ApiKeyProvider; import com.donnfelker.android.bootstrap.core.BootstrapService; import com.donnfelker.android.bootstrap.core.UserAgentProvider; import javax.inject.Inject; import java.io.IOException; /** * Provider for a {@link com.donnfelker.android.bootstrap.core.BootstrapService} instance */ public class BootstrapServiceProvider { @Inject ApiKeyProvider keyProvider; @Inject UserAgentProvider userAgentProvider; /** * Get service for configured key provider * <p> * This method gets an auth key and so it blocks and shouldn't be called on the main thread. * * @return bootstrap service * @throws IOException * @throws AccountsException */ public BootstrapService getService(Activity activity) throws IOException, AccountsException { - return new BootstrapService(keyProvider.getAuthKey(), userAgentProvider); + return new BootstrapService(keyProvider.getAuthKey(activity), userAgentProvider); } }
true
true
public BootstrapService getService(Activity activity) throws IOException, AccountsException { return new BootstrapService(keyProvider.getAuthKey(), userAgentProvider); }
public BootstrapService getService(Activity activity) throws IOException, AccountsException { return new BootstrapService(keyProvider.getAuthKey(activity), userAgentProvider); }
diff --git a/smos-dgg/src/main/java/org/esa/beam/smos/dgg/SmosDggTilizer.java b/smos-dgg/src/main/java/org/esa/beam/smos/dgg/SmosDggTilizer.java index 287c0cf2..211b29a7 100644 --- a/smos-dgg/src/main/java/org/esa/beam/smos/dgg/SmosDggTilizer.java +++ b/smos-dgg/src/main/java/org/esa/beam/smos/dgg/SmosDggTilizer.java @@ -1,133 +1,134 @@ package org.esa.beam.smos.dgg; import com.bc.ceres.glevel.MultiLevelModel; import com.bc.ceres.glevel.MultiLevelSource; import com.bc.ceres.glevel.support.DefaultMultiLevelModel; import com.bc.ceres.glevel.support.DefaultMultiLevelSource; import org.esa.beam.jai.TiledFileOpImage; import javax.imageio.stream.ImageOutputStream; import javax.imageio.stream.MemoryCacheImageOutputStream; import javax.media.jai.PlanarImage; import java.awt.Rectangle; import java.awt.geom.AffineTransform; import java.awt.image.DataBufferInt; import java.awt.image.Raster; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class SmosDggTilizer { public static void main(String[] args) throws IOException { new SmosDggTilizer().doIt(new File(args[0]), new File(args[1])); } private void doIt(File inputLevel0Dir, File outputDir) throws IOException { - //noinspection ResultOfMethodCallIgnored - outputDir.mkdir(); + if (!outputDir.exists() && !outputDir.mkdir()) { + throw new IOException("Failed to create directory: "+outputDir.getAbsolutePath()); + } final TiledFileOpImage opImage = TiledFileOpImage.create(inputLevel0Dir, null); final int dataType = opImage.getSampleModel().getDataType(); int tileWidth = 512; int tileHeight = 512; final int levelCount = 7; final MultiLevelModel model = new DefaultMultiLevelModel(levelCount, new AffineTransform(), opImage.getWidth(), opImage.getHeight()); final MultiLevelSource multiLevelSource = new DefaultMultiLevelSource(opImage, model); for (int level = 5; level < levelCount; level++) { final PlanarImage image = PlanarImage.wrapRenderedImage(multiLevelSource.getImage(level)); final int width = image.getWidth(); final int height = image.getHeight(); int numXTiles; int numYTiles; while (true) { numXTiles = width / tileWidth; numYTiles = height / tileHeight; if (numXTiles * tileWidth == width && numYTiles * tileHeight == image.getHeight()) { break; } if (numXTiles * tileWidth < width) { tileWidth /= 2; } if (numYTiles * tileHeight < height) { tileHeight /= 2; } } if (numXTiles == 0 || numYTiles == 0) { throw new IllegalStateException("numXTiles == 0 || numYTiles == 0"); } if (tileWidth < 512 && tileHeight < 512) { tileWidth = width; tileHeight = height; numXTiles = numYTiles = 1; } final File outputLevelDir = new File(outputDir, "" + level); - if (!outputLevelDir.mkdir()) { - throw new IOException("Failed to create directory: "+outputDir.getAbsolutePath()); + if (!outputLevelDir.exists() && !outputLevelDir.mkdir()) { + throw new IOException("Failed to create directory: "+outputLevelDir.getAbsolutePath()); } final File imagePropertiesFile = new File(outputLevelDir, "image.properties"); System.out.println("Writing " + imagePropertiesFile + "..."); final PrintWriter printWriter = new PrintWriter(new FileWriter(imagePropertiesFile)); writeImageProperties(level, dataType, width, height, tileWidth, tileHeight, numXTiles, numYTiles, new PrintWriter(System.out)); writeImageProperties(level, dataType, width, height, tileWidth, tileHeight, numXTiles, numYTiles, printWriter); System.out.flush(); printWriter.close(); writeTiles(outputLevelDir, image, tileWidth, tileHeight, numXTiles, numYTiles); } } private void writeTiles(File levelDir, PlanarImage image, int tileWidth, int tileHeight, int numXTiles, int numYTiles) throws IOException { for (int tileY = 0; tileY < numYTiles; tileY++) { for (int tileX = 0; tileX < numXTiles; tileX++) { final int x = tileX * tileWidth; final int y = tileY * tileHeight; final Raster raster = image.getData(new Rectangle(x, y, tileWidth, tileHeight)); int[] data = ((DataBufferInt) raster.getDataBuffer()).getData(); if (data.length != tileWidth * tileHeight) { data = new int[tileWidth * tileHeight]; raster.getDataElements(x, y, tileWidth, tileHeight, data); } writeData(levelDir, tileX, tileY, data); } } } private void writeImageProperties(int level, int dataType, int width, int height, int tileWidth, int tileHeight, int numXTiles, int numYTiles, PrintWriter printWriter) { printWriter.println("level = " + level); printWriter.println("dataType = " + dataType); printWriter.println("width = " + width); printWriter.println("height = " + height); printWriter.println("tileWidth = " + tileWidth); printWriter.println("tileHeight = " + tileHeight); printWriter.println("numXTiles = " + numXTiles); printWriter.println("numYTiles = " + numYTiles); } private void writeData(File levelDir, int tileX, int tileY, int[] data) throws IOException { final String baseName = tileX + "-" + tileY + ".raw"; final File file = new File(levelDir, baseName + ".zip"); final ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(file)); zipOutputStream.putNextEntry(new ZipEntry(baseName)); final ImageOutputStream imageOutputStream = new MemoryCacheImageOutputStream(zipOutputStream); imageOutputStream.writeInts(data, 0, data.length); imageOutputStream.flush(); zipOutputStream.closeEntry(); zipOutputStream.close(); } }
false
true
private void doIt(File inputLevel0Dir, File outputDir) throws IOException { //noinspection ResultOfMethodCallIgnored outputDir.mkdir(); final TiledFileOpImage opImage = TiledFileOpImage.create(inputLevel0Dir, null); final int dataType = opImage.getSampleModel().getDataType(); int tileWidth = 512; int tileHeight = 512; final int levelCount = 7; final MultiLevelModel model = new DefaultMultiLevelModel(levelCount, new AffineTransform(), opImage.getWidth(), opImage.getHeight()); final MultiLevelSource multiLevelSource = new DefaultMultiLevelSource(opImage, model); for (int level = 5; level < levelCount; level++) { final PlanarImage image = PlanarImage.wrapRenderedImage(multiLevelSource.getImage(level)); final int width = image.getWidth(); final int height = image.getHeight(); int numXTiles; int numYTiles; while (true) { numXTiles = width / tileWidth; numYTiles = height / tileHeight; if (numXTiles * tileWidth == width && numYTiles * tileHeight == image.getHeight()) { break; } if (numXTiles * tileWidth < width) { tileWidth /= 2; } if (numYTiles * tileHeight < height) { tileHeight /= 2; } } if (numXTiles == 0 || numYTiles == 0) { throw new IllegalStateException("numXTiles == 0 || numYTiles == 0"); } if (tileWidth < 512 && tileHeight < 512) { tileWidth = width; tileHeight = height; numXTiles = numYTiles = 1; } final File outputLevelDir = new File(outputDir, "" + level); if (!outputLevelDir.mkdir()) { throw new IOException("Failed to create directory: "+outputDir.getAbsolutePath()); } final File imagePropertiesFile = new File(outputLevelDir, "image.properties"); System.out.println("Writing " + imagePropertiesFile + "..."); final PrintWriter printWriter = new PrintWriter(new FileWriter(imagePropertiesFile)); writeImageProperties(level, dataType, width, height, tileWidth, tileHeight, numXTiles, numYTiles, new PrintWriter(System.out)); writeImageProperties(level, dataType, width, height, tileWidth, tileHeight, numXTiles, numYTiles, printWriter); System.out.flush(); printWriter.close(); writeTiles(outputLevelDir, image, tileWidth, tileHeight, numXTiles, numYTiles); } }
private void doIt(File inputLevel0Dir, File outputDir) throws IOException { if (!outputDir.exists() && !outputDir.mkdir()) { throw new IOException("Failed to create directory: "+outputDir.getAbsolutePath()); } final TiledFileOpImage opImage = TiledFileOpImage.create(inputLevel0Dir, null); final int dataType = opImage.getSampleModel().getDataType(); int tileWidth = 512; int tileHeight = 512; final int levelCount = 7; final MultiLevelModel model = new DefaultMultiLevelModel(levelCount, new AffineTransform(), opImage.getWidth(), opImage.getHeight()); final MultiLevelSource multiLevelSource = new DefaultMultiLevelSource(opImage, model); for (int level = 5; level < levelCount; level++) { final PlanarImage image = PlanarImage.wrapRenderedImage(multiLevelSource.getImage(level)); final int width = image.getWidth(); final int height = image.getHeight(); int numXTiles; int numYTiles; while (true) { numXTiles = width / tileWidth; numYTiles = height / tileHeight; if (numXTiles * tileWidth == width && numYTiles * tileHeight == image.getHeight()) { break; } if (numXTiles * tileWidth < width) { tileWidth /= 2; } if (numYTiles * tileHeight < height) { tileHeight /= 2; } } if (numXTiles == 0 || numYTiles == 0) { throw new IllegalStateException("numXTiles == 0 || numYTiles == 0"); } if (tileWidth < 512 && tileHeight < 512) { tileWidth = width; tileHeight = height; numXTiles = numYTiles = 1; } final File outputLevelDir = new File(outputDir, "" + level); if (!outputLevelDir.exists() && !outputLevelDir.mkdir()) { throw new IOException("Failed to create directory: "+outputLevelDir.getAbsolutePath()); } final File imagePropertiesFile = new File(outputLevelDir, "image.properties"); System.out.println("Writing " + imagePropertiesFile + "..."); final PrintWriter printWriter = new PrintWriter(new FileWriter(imagePropertiesFile)); writeImageProperties(level, dataType, width, height, tileWidth, tileHeight, numXTiles, numYTiles, new PrintWriter(System.out)); writeImageProperties(level, dataType, width, height, tileWidth, tileHeight, numXTiles, numYTiles, printWriter); System.out.flush(); printWriter.close(); writeTiles(outputLevelDir, image, tileWidth, tileHeight, numXTiles, numYTiles); } }
diff --git a/parser/org/eclipse/cdt/internal/core/parser/scanner/Scanner.java b/parser/org/eclipse/cdt/internal/core/parser/scanner/Scanner.java index 6b6660216..1e64fdd15 100644 --- a/parser/org/eclipse/cdt/internal/core/parser/scanner/Scanner.java +++ b/parser/org/eclipse/cdt/internal/core/parser/scanner/Scanner.java @@ -1,3645 +1,3643 @@ /******************************************************************************* * Copyright (c) 2001, 2004 IBM Rational Software and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v0.5 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v05.html * * Contributors: * IBM - Rational Software ******************************************************************************/ package org.eclipse.cdt.internal.core.parser.scanner; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.EmptyStackException; import java.util.HashMap; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import java.util.Vector; import org.eclipse.cdt.core.parser.BacktrackException; import org.eclipse.cdt.core.parser.CodeReader; import org.eclipse.cdt.core.parser.Directives; import org.eclipse.cdt.core.parser.EndOfFileException; import org.eclipse.cdt.core.parser.IMacroDescriptor; import org.eclipse.cdt.core.parser.IParserLogService; import org.eclipse.cdt.core.parser.IProblem; import org.eclipse.cdt.core.parser.IScanner; import org.eclipse.cdt.core.parser.IScannerInfo; import org.eclipse.cdt.core.parser.ISourceElementRequestor; import org.eclipse.cdt.core.parser.IToken; import org.eclipse.cdt.core.parser.KeywordSetKey; import org.eclipse.cdt.core.parser.Keywords; import org.eclipse.cdt.core.parser.NullLogService; import org.eclipse.cdt.core.parser.NullSourceElementRequestor; import org.eclipse.cdt.core.parser.OffsetLimitReachedException; import org.eclipse.cdt.core.parser.ParserFactory; import org.eclipse.cdt.core.parser.ParserLanguage; import org.eclipse.cdt.core.parser.ParserMode; import org.eclipse.cdt.core.parser.ScannerException; import org.eclipse.cdt.core.parser.ScannerInfo; import org.eclipse.cdt.core.parser.IMacroDescriptor.MacroType; import org.eclipse.cdt.core.parser.ast.ASTExpressionEvaluationException; import org.eclipse.cdt.core.parser.ast.IASTCompletionNode; import org.eclipse.cdt.core.parser.ast.IASTExpression; import org.eclipse.cdt.core.parser.ast.IASTFactory; import org.eclipse.cdt.core.parser.ast.IASTInclusion; import org.eclipse.cdt.core.parser.extension.IScannerExtension; import org.eclipse.cdt.internal.core.parser.IExpressionParser; import org.eclipse.cdt.internal.core.parser.InternalParserUtil; import org.eclipse.cdt.internal.core.parser.ast.ASTCompletionNode; import org.eclipse.cdt.internal.core.parser.ast.EmptyIterator; import org.eclipse.cdt.internal.core.parser.problem.IProblemFactory; import org.eclipse.cdt.internal.core.parser.scanner.ScannerUtility.InclusionDirective; import org.eclipse.cdt.internal.core.parser.scanner.ScannerUtility.InclusionParseException; import org.eclipse.cdt.internal.core.parser.token.KeywordSets; import org.eclipse.cdt.internal.core.parser.token.SimpleToken; import org.eclipse.cdt.internal.core.parser.token.TokenFactory; import org.eclipse.cdt.internal.core.parser.util.TraceUtil; /** * @author jcamelon * */ public final class Scanner implements IScanner, IScannerData { protected static final EndOfFileException EOF = new EndOfFileException(); private ScannerStringBuffer strbuff = new ScannerStringBuffer(100); protected static final String HEX_PREFIX = "0x"; //$NON-NLS-1$ private static final ObjectMacroDescriptor CPLUSPLUS_MACRO = new ObjectMacroDescriptor( __CPLUSPLUS, "199711L"); //$NON-NLS-1$ private static final ObjectMacroDescriptor STDC_VERSION_MACRO = new ObjectMacroDescriptor( __STDC_VERSION__, "199001L"); //$NON-NLS-1$ protected static final ObjectMacroDescriptor STDC_HOSTED_MACRO = new ObjectMacroDescriptor( __STDC_HOSTED__, "0"); //$NON-NLS-1$ protected static final ObjectMacroDescriptor STDC_MACRO = new ObjectMacroDescriptor( __STDC__, "1"); //$NON-NLS-1$ private static final NullSourceElementRequestor NULL_REQUESTOR = new NullSourceElementRequestor(); private final static String SCRATCH = "<scratch>"; //$NON-NLS-1$ private final List workingCopies; protected final ContextStack contextStack; private IASTFactory astFactory = null; private ISourceElementRequestor requestor; private ParserMode parserMode; private final CodeReader reader; private final ParserLanguage language; protected IParserLogService log; private final IProblemFactory problemFactory = new ScannerProblemFactory(); private Map definitions = new Hashtable(); private BranchTracker branches = new BranchTracker(); private final IScannerInfo originalConfig; private List includePathNames = new ArrayList(); private final Map privateDefinitions = new Hashtable(); private boolean initialContextInitialized = false; protected IToken finalToken; private final IScannerExtension scannerExtension; private static final int NO_OFFSET_LIMIT = -1; private int offsetLimit = NO_OFFSET_LIMIT; private boolean limitReached = false; private IScannerContext currentContext; private final Map fileCache = new HashMap(100); public void setScannerContext(IScannerContext context) { currentContext = context; } protected void handleProblem( int problemID, String argument, int beginningOffset, boolean warning, boolean error ) throws ScannerException { handleProblem( problemID, argument, beginningOffset, warning, error, true ); } protected void handleProblem( int problemID, String argument, int beginningOffset, boolean warning, boolean error, boolean extra ) throws ScannerException { IProblem problem = problemFactory.createProblem( problemID, beginningOffset, getCurrentOffset(), contextStack.getCurrentLineNumber(), getCurrentFile().toCharArray(), argument, warning, error ); // trace log TraceUtil.outputTrace(log, "Scanner problem encountered: ", problem, null, null, null ); //$NON-NLS-1$ if( (! requestor.acceptProblem( problem )) && extra ) throw new ScannerException( problem ); } Scanner( CodeReader reader, Map definitions, List includePaths, ISourceElementRequestor requestor, ParserMode mode, ParserLanguage language, IParserLogService log, IScannerExtension extension ) { String [] incs = (String [])includePaths.toArray(STRING_ARRAY); this.log = log; this.requestor = requestor; this.parserMode = mode; this.reader = reader; this.language = language; this.originalConfig = new ScannerInfo( definitions, incs ); this.contextStack = new ContextStack( this, log ); this.workingCopies = null; this.scannerExtension = extension; this.definitions = definitions; this.includePathNames = includePaths; if (reader.isFile()) fileCache.put(reader.filename, reader); setupBuiltInMacros(); } public Scanner(CodeReader reader, IScannerInfo info, ISourceElementRequestor requestor, ParserMode parserMode, ParserLanguage language, IParserLogService log, IScannerExtension extension, List workingCopies ) { this.log = log; this.requestor = requestor; this.parserMode = parserMode; this.reader = reader; this.language = language; this.originalConfig = info; this.contextStack = new ContextStack( this, log ); this.workingCopies = workingCopies; this.scannerExtension = extension; this.astFactory = ParserFactory.createASTFactory( this, parserMode, language ); if (reader.isFile()) fileCache.put(reader.filename, reader); TraceUtil.outputTrace(log, "Scanner constructed with the following configuration:"); //$NON-NLS-1$ TraceUtil.outputTrace(log, "\tPreprocessor definitions from IScannerInfo: "); //$NON-NLS-1$ if( info.getDefinedSymbols() != null ) { Iterator i = info.getDefinedSymbols().keySet().iterator(); Map m = info.getDefinedSymbols(); int numberOfSymbolsLogged = 0; while( i.hasNext() ) { String symbolName = (String) i.next(); Object value = m.get( symbolName ); if( value instanceof String ) { //TODO add in check here for '(' and ')' addDefinition( symbolName, scannerExtension.initializeMacroValue(this, (String) value)); TraceUtil.outputTrace(log, "\t\tNAME = ", symbolName, " VALUE = ", value.toString() ); //$NON-NLS-1$ //$NON-NLS-2$ ++numberOfSymbolsLogged; } else if( value instanceof IMacroDescriptor ) addDefinition( symbolName, (IMacroDescriptor)value); } if( numberOfSymbolsLogged == 0 ) TraceUtil.outputTrace(log, "\t\tNo definitions specified."); //$NON-NLS-1$ } else TraceUtil.outputTrace(log, "\t\tNo definitions specified."); //$NON-NLS-1$ TraceUtil.outputTrace( log, "\tInclude paths from IScannerInfo: "); //$NON-NLS-1$ if( info.getIncludePaths() != null ) { overwriteIncludePath( info.getIncludePaths() ); for( int i = 0; i < info.getIncludePaths().length; ++i ) TraceUtil.outputTrace( log, "\t\tPATH: ", info.getIncludePaths()[i], null, null); //$NON-NLS-1$ } else TraceUtil.outputTrace(log, "\t\tNo include paths specified."); //$NON-NLS-1$ setupBuiltInMacros(); } public final ParserLanguage getLanguage() { return language; } public final Map getPrivateDefinitions() { return privateDefinitions; } public final ContextStack getContextStack() { return contextStack; } public final IParserLogService getLogService() { return log; } public final List getIncludePathNames() { return includePathNames; } public final Map getPublicDefinitions() { return definitions; } public final ParserMode getParserMode() { return parserMode; } public final ISourceElementRequestor getClientRequestor() { return requestor; } public final Iterator getWorkingCopies() { return workingCopies != null ? workingCopies.iterator() : EmptyIterator.EMPTY_ITERATOR; } /** * */ protected void setupBuiltInMacros() { scannerExtension.setupBuiltInMacros(this); if( getDefinition(__STDC__) == null ) addDefinition( __STDC__, STDC_MACRO ); if( language == ParserLanguage.C ) { if( getDefinition(__STDC_HOSTED__) == null ) addDefinition( __STDC_HOSTED__, STDC_HOSTED_MACRO); if( getDefinition( __STDC_VERSION__) == null ) addDefinition( __STDC_VERSION__, STDC_VERSION_MACRO); } else if( getDefinition( __CPLUSPLUS ) == null ) addDefinition( __CPLUSPLUS, CPLUSPLUS_MACRO); //$NON-NLS-1$ if( getDefinition(__FILE__) == null ) addDefinition( __FILE__, new DynamicMacroDescriptor( __FILE__, new DynamicMacroEvaluator() { public String execute() { return contextStack.getMostRelevantFileContext().getContextName(); } } ) ); if( getDefinition( __LINE__) == null ) addDefinition( __LINE__, new DynamicMacroDescriptor( __LINE__, new DynamicMacroEvaluator() { public String execute() { return new Integer( contextStack.getCurrentLineNumber() ).toString(); } } ) ); if( getDefinition( __DATE__ ) == null ) addDefinition( __DATE__, new DynamicMacroDescriptor( __DATE__, new DynamicMacroEvaluator() { public String getMonth() { if( Calendar.MONTH == Calendar.JANUARY ) return "Jan" ; //$NON-NLS-1$ if( Calendar.MONTH == Calendar.FEBRUARY) return "Feb"; //$NON-NLS-1$ if( Calendar.MONTH == Calendar.MARCH) return "Mar"; //$NON-NLS-1$ if( Calendar.MONTH == Calendar.APRIL) return "Apr"; //$NON-NLS-1$ if( Calendar.MONTH == Calendar.MAY) return "May"; //$NON-NLS-1$ if( Calendar.MONTH == Calendar.JUNE) return "Jun"; //$NON-NLS-1$ if( Calendar.MONTH == Calendar.JULY) return "Jul"; //$NON-NLS-1$ if( Calendar.MONTH == Calendar.AUGUST) return "Aug"; //$NON-NLS-1$ if( Calendar.MONTH == Calendar.SEPTEMBER) return "Sep"; //$NON-NLS-1$ if( Calendar.MONTH == Calendar.OCTOBER) return "Oct"; //$NON-NLS-1$ if( Calendar.MONTH == Calendar.NOVEMBER) return "Nov"; //$NON-NLS-1$ if( Calendar.MONTH == Calendar.DECEMBER) return "Dec"; //$NON-NLS-1$ return ""; //$NON-NLS-1$ } public String execute() { StringBuffer result = new StringBuffer(); result.append( getMonth() ); result.append(" "); //$NON-NLS-1$ if( Calendar.DAY_OF_MONTH < 10 ) result.append(" "); //$NON-NLS-1$ result.append(Calendar.DAY_OF_MONTH); result.append(" "); //$NON-NLS-1$ result.append( Calendar.YEAR ); return result.toString(); } } ) ); if( getDefinition( __TIME__) == null ) addDefinition( __TIME__, new DynamicMacroDescriptor( __TIME__, new DynamicMacroEvaluator() { public String execute() { StringBuffer result = new StringBuffer(); if( Calendar.AM_PM == Calendar.PM ) result.append( Calendar.HOUR + 12 ); else { if( Calendar.HOUR < 10 ) result.append( '0'); result.append(Calendar.HOUR); } result.append(':'); if( Calendar.MINUTE < 10 ) result.append( '0'); result.append(Calendar.MINUTE); result.append(':'); if( Calendar.SECOND < 10 ) result.append( '0'); result.append(Calendar.SECOND); return result.toString(); } } ) ); } private void setupInitialContext() { IScannerContext context = null; try { if( offsetLimit == NO_OFFSET_LIMIT ) context = new ScannerContextTop(reader); else context = new LimitedScannerContext( this, reader, offsetLimit, 0 ); contextStack.pushInitialContext( context ); } catch( ContextException ce ) { handleInternalError(); } initialContextInitialized = true; } public void addIncludePath(String includePath) { includePathNames.add(includePath); } public void overwriteIncludePath(String [] newIncludePaths) { if( newIncludePaths == null ) return; includePathNames = new ArrayList(newIncludePaths.length); for( int i = 0; i < newIncludePaths.length; ++i ) { String path = newIncludePaths[i]; File file = new File( path ); if( !file.exists() && path.indexOf('\"') != -1 ) { StringTokenizer tokenizer = new StringTokenizer(path, "\"" ); //$NON-NLS-1$ strbuff.startString(); while( tokenizer.hasMoreTokens() ){ strbuff.append( tokenizer.nextToken() ); } file = new File( strbuff.toString() ); } if( file.exists() && file.isDirectory() ) includePathNames.add( path ); } } public void addDefinition(String key, IMacroDescriptor macro) { definitions.put(key, macro); } public void addDefinition(String key, String value) { addDefinition(key, new ObjectMacroDescriptor( key, value )); } public final IMacroDescriptor getDefinition(String key) { IMacroDescriptor descriptor = (IMacroDescriptor) definitions.get(key); if( descriptor != null ) return descriptor; return (IMacroDescriptor) privateDefinitions.get(key); } public final String[] getIncludePaths() { return (String[])includePathNames.toArray(); } protected boolean skipOverWhitespace() throws ScannerException { int c = getChar(false); boolean result = false; while ((c != NOCHAR) && ((c == ' ') || (c == '\t'))) { c = getChar(false); result = true; } if (c != NOCHAR) ungetChar(c); return result; } protected String getRestOfPreprocessorLine() throws ScannerException, EndOfFileException { skipOverWhitespace(); int c = getChar(false); if (c == '\n') return ""; //$NON-NLS-1$ strbuff.startString(); boolean inString = false; boolean inChar = false; while (true) { while ((c != '\n') && (c != '\r') && (c != '\\') && (c != '/') && (c != '"' || ( c == '"' && inChar ) ) && (c != '\'' || ( c == '\'' && inString ) ) && (c != NOCHAR)) { strbuff.append(c); c = getChar( true ); } if (c == '/') { //only care about comments outside of a quote if( inString || inChar ){ strbuff.append( c ); c = getChar( true ); continue; } // we need to peek ahead at the next character to see if // this is a comment or not int next = getChar(false); if (next == '/') { // single line comment skipOverSinglelineComment(); break; } else if (next == '*') { // multiline comment skipOverMultilineComment(); c = getChar( true ); continue; } else { // we are not in a comment strbuff.append(c); c = next; continue; } } else if( c == '"' ){ inString = !inString; strbuff.append(c); c = getChar( true ); continue; } else if( c == '\'' ){ inChar = !inChar; strbuff.append(c); c = getChar( true ); continue; } else if( c == '\\' ){ c = getChar(true); if( c == '\r' ){ c = getChar(true); if( c == '\n' ){ c = getChar(true); } } else if( c == '\n' ){ c = getChar(true); } else { strbuff.append('\\'); if( c == '"' || c == '\'' ){ strbuff.append(c); c = getChar( true ); } } continue; } else { ungetChar(c); break; } } return strbuff.toString(); } protected void skipOverTextUntilNewline() throws ScannerException { for (;;) { switch (getChar(false)) { case NOCHAR : case '\n' : return; case '\\' : getChar(false); } } } private void setCurrentToken(IToken t) { if (currentToken != null) currentToken.setNext(t); finalToken = t; currentToken = t; } protected void resetStorageBuffer() { if( storageBuffer != null ) storageBuffer = null; } protected IToken newToken(int t, String i) { IToken token = TokenFactory.createUniquelyImagedToken(t, i, this ); setCurrentToken(token); return currentToken; } protected IToken newConstantToken(int t) { setCurrentToken( TokenFactory.createToken(t, this)); return currentToken; } protected String getNextIdentifier() throws ScannerException { strbuff.startString(); skipOverWhitespace(); int c = getChar(false); if (((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z')) | (c == '_')) { strbuff.append(c); c = getChar(false); while (((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z')) || ((c >= '0') && (c <= '9')) || (c == '_')) { strbuff.append(c); c = getChar(false); } } ungetChar(c); return strbuff.toString(); } protected void handleInclusion(String fileName, boolean useIncludePaths, int beginOffset, int startLine, int nameOffset, int nameLine, int endOffset, int endLine ) throws ScannerException { CodeReader duple = null; totalLoop: for( int i = 0; i < 2; ++i ) { if( useIncludePaths ) // search include paths for this file { // iterate through the include paths Iterator iter = includePathNames.iterator(); while (iter.hasNext()) { String path = (String)iter.next(); String finalPath = ScannerUtility.createReconciledPath(path, fileName); duple = (CodeReader)fileCache.get(finalPath); if (duple == null) { duple = ScannerUtility.createReaderDuple( finalPath, requestor, getWorkingCopies() ); if (duple != null && duple.isFile()) fileCache.put(duple.filename, duple); } if( duple != null ) break totalLoop; } if (duple == null ) handleProblem( IProblem.PREPROCESSOR_INCLUSION_NOT_FOUND, fileName, beginOffset, false, true ); } else // local inclusion { String finalPath = ScannerUtility.createReconciledPath(new File( currentContext.getContextName() ).getParentFile().getAbsolutePath(), fileName); duple = (CodeReader)fileCache.get(finalPath); if (duple == null) { duple = ScannerUtility.createReaderDuple( finalPath, requestor, getWorkingCopies() ); if (duple != null && duple.isFile()) fileCache.put(duple.filename, duple); } if( duple != null ) break totalLoop; useIncludePaths = true; continue totalLoop; } } if (duple!= null) { IASTInclusion inclusion = null; try { inclusion = getASTFactory().createInclusion( fileName, duple.filename, !useIncludePaths, beginOffset, startLine, nameOffset, nameOffset + fileName.length(), nameLine, endOffset, endLine); } catch (Exception e) { /* do nothing */ } try { contextStack.updateInclusionContext( duple, inclusion, requestor); } catch (ContextException e1) { handleProblem( e1.getId(), fileName, beginOffset, false, true ); } } } /* protected void handleInclusion(String fileName, boolean useIncludePaths, int beginOffset, int startLine, int nameOffset, int nameLine, int endOffset, int endLine ) throws ScannerException { // if useIncludePaths is true then // #include <foo.h> // else // #include "foo.h" Reader inclusionReader = null; File includeFile = null; if( !useIncludePaths ) { // local inclusion is checked first String currentFilename = currentContext.getFilename(); File currentIncludeFile = new File( currentFilename ); String parentDirectory = currentIncludeFile.getParentFile().getAbsolutePath(); currentIncludeFile = null; //TODO remove ".." and "." segments includeFile = new File( parentDirectory, fileName ); if (includeFile.exists() && includeFile.isFile()) { try { inclusionReader = new BufferedReader(new FileReader(includeFile)); } catch (FileNotFoundException fnf) { inclusionReader = null; } } } // search include paths for this file // iterate through the include paths Iterator iter = scannerData.getIncludePathNames().iterator(); while ((inclusionReader == null) && iter.hasNext()) { String path = (String)iter.next(); //TODO remove ".." and "." segments includeFile = new File (path, fileName); if (includeFile.exists() && includeFile.isFile()) { try { inclusionReader = new BufferedReader(new FileReader(includeFile)); } catch (FileNotFoundException fnf) { inclusionReader = null; } } } if (inclusionReader == null ) handleProblem( IProblem.PREPROCESSOR_INCLUSION_NOT_FOUND, fileName, beginOffset, false, true ); else { IASTInclusion inclusion = null; try { inclusion = scannerData.getASTFactory().createInclusion( fileName, includeFile.getPath(), !useIncludePaths, beginOffset, startLine, nameOffset, nameOffset + fileName.length(), nameLine, endOffset, endLine); } catch (Exception e) { do nothing } try { scannerData.getContextStack().updateContext(inclusionReader, includeFile.getPath(), ScannerContext.ContextKind.INCLUSION, inclusion, scannerData.getClientRequestor() ); } catch (ContextException e1) { handleProblem( e1.getId(), fileName, beginOffset, false, true ); } } } */ // constants private static final int NOCHAR = -1; private static final String TEXT = "<text>"; //$NON-NLS-1$ private static final String EXPRESSION = "<expression>"; //$NON-NLS-1$ private static final String PASTING = "<pasting>"; //$NON-NLS-1$ private static final String DEFINED = "defined"; //$NON-NLS-1$ private static final String POUND_DEFINE = "#define "; //$NON-NLS-1$ private IScannerContext lastContext = null; private StringBuffer storageBuffer = null; private int count = 0; private static HashMap cppKeywords = new HashMap(); private static HashMap cKeywords = new HashMap(); private static HashMap ppDirectives = new HashMap(); private IToken currentToken = null; private IToken cachedToken = null; private boolean passOnToClient = true; // these are scanner configuration aspects that we perhaps want to tweak // eventually, these should be configurable by the client, but for now // we can just leave it internal // private boolean enableDigraphReplacement = true; // private boolean enableTrigraphReplacement = true; // private boolean enableTrigraphReplacementInStrings = true; private boolean throwExceptionOnBadCharacterRead = false; private boolean tokenizingMacroReplacementList = false; protected static final String EMPTY_STRING = ""; //$NON-NLS-1$ private Map tempMap = new HashMap(); //$NON-NLS-1$ public void setTokenizingMacroReplacementList( boolean mr ){ tokenizingMacroReplacementList = mr; } public final int getCharacter() throws ScannerException { if( ! initialContextInitialized ) setupInitialContext(); return getChar(false); } final int getChar() throws ScannerException { return getChar(false); } private final int getChar( boolean insideString ) throws ScannerException { lastContext = currentContext; if (lastContext.getKind() == IScannerContext.ContextKind.SENTINEL) // past the end of file return NOCHAR; int c = currentContext.getChar(); if (c != NOCHAR) return c; if (currentContext.isFinal()) return c; while (contextStack.rollbackContext(requestor)) { c = currentContext.getChar(); if (c != NOCHAR) return c; if (currentContext.isFinal()) return c; } return NOCHAR; /* if (enableTrigraphReplacement && (!insideString || enableTrigraphReplacementInStrings)) { // Trigraph processing enableTrigraphReplacement = false; if (c == '?') { c = getChar(insideString); if (c == '?') { c = getChar(insideString); switch (c) { case '(': expandDefinition("??(", "[", lastContext.getOffset() - 1); //$NON-NLS-1$ //$NON-NLS-2$ c = getChar(insideString); break; case ')': expandDefinition("??)", "]", lastContext.getOffset() - 1); //$NON-NLS-1$ //$NON-NLS-2$ c = getChar(insideString); break; case '<': expandDefinition("??<", "{", lastContext.getOffset() - 1); //$NON-NLS-1$ //$NON-NLS-2$ c = getChar(insideString); break; case '>': expandDefinition("??>", "}", lastContext.getOffset() - 1); //$NON-NLS-1$ //$NON-NLS-2$ c = getChar(insideString); break; case '=': expandDefinition("??=", "#", lastContext.getOffset() - 1); //$NON-NLS-1$ //$NON-NLS-2$ c = getChar(insideString); break; case '/': expandDefinition("??/", "\\", lastContext.getOffset() - 1); //$NON-NLS-1$ //$NON-NLS-2$ c = getChar(insideString); break; case '\'': expandDefinition("??\'", "^", lastContext.getOffset() - 1); //$NON-NLS-1$ //$NON-NLS-2$ c = getChar(insideString); break; case '!': expandDefinition("??!", "|", lastContext.getOffset() - 1); //$NON-NLS-1$ //$NON-NLS-2$ c = getChar(insideString); break; case '-': expandDefinition("??-", "~", lastContext.getOffset() - 1); //$NON-NLS-1$ //$NON-NLS-2$ c = getChar(insideString); break; default: // Not a trigraph ungetChar(c); ungetChar('?'); c = '?'; } } else { // Not a trigraph ungetChar(c); c = '?'; } } enableTrigraphReplacement = true; } if (!insideString) { if (enableDigraphReplacement) { enableDigraphReplacement = false; // Digraph processing if (c == '<') { c = getChar(false); if (c == '%') { expandDefinition("<%", "{", lastContext.getOffset() - 1); //$NON-NLS-1$ //$NON-NLS-2$ c = getChar(false); } else if (c == ':') { expandDefinition("<:", "[", lastContext.getOffset() - 1); //$NON-NLS-1$ //$NON-NLS-2$ c = getChar(false); } else { // Not a digraph ungetChar(c); c = '<'; } } else if (c == ':') { c = getChar(false); if (c == '>') { expandDefinition(":>", "]", lastContext.getOffset() - 1); //$NON-NLS-1$ //$NON-NLS-2$ c = getChar(false); } else { // Not a digraph ungetChar(c); c = ':'; } } else if (c == '%') { c = getChar(false); if (c == '>') { expandDefinition("%>", "}", lastContext.getOffset() - 1); //$NON-NLS-1$ //$NON-NLS-2$ c = getChar(false); } else if (c == ':') { expandDefinition("%:", "#", lastContext.getOffset() - 1); //$NON-NLS-1$ //$NON-NLS-2$ c = getChar(false); } else { // Not a digraph ungetChar(c); c = '%'; } } enableDigraphReplacement = true; } } return c;*/ } final void ungetChar(int c) { currentContext.ungetChar(c); if( lastContext != currentContext) contextStack.undoRollback( lastContext, requestor ); } protected boolean lookAheadForTokenPasting() throws ScannerException { int c = getChar(false); if( c == '#' ) { c = getChar(false); if( c == '#' ) return true; ungetChar( c ); } ungetChar( c ); return false; } protected void consumeUntilOutOfMacroExpansion() throws ScannerException { while( currentContext.getKind() == IScannerContext.ContextKind.MACROEXPANSION ) getChar(false); } public IToken nextToken() throws ScannerException, EndOfFileException { return nextToken( true ); } public boolean pasteIntoInputStream(String buff) throws ScannerException, EndOfFileException { // we have found ## in the input stream -- so save the results if( lookAheadForTokenPasting() ) { if( storageBuffer == null ) storageBuffer = new StringBuffer(buff); else storageBuffer.append( buff ); return true; } // a previous call has stored information, so we will add to it if( storageBuffer != null ) { storageBuffer.append( buff.toString() ); try { contextStack.updateMacroContext( storageBuffer.toString(), PASTING, requestor, -1, -1 ); } catch (ContextException e) { handleProblem( e.getId(), currentContext.getContextName(), getCurrentOffset(), false, true ); } storageBuffer = null; return true; } // there is no need to save the results -- we will not concatenate return false; } public int consumeNewlineAfterSlash() throws ScannerException { int c; c = getChar(false); if (c == '\r') { c = getChar(false); if (c == '\n') { // consume \ \r \n and then continue return getChar(true); } // consume the \ \r and then continue return c; } if (c == '\n') { // consume \ \n and then continue return getChar(true); } // '\' is not the last character on the line ungetChar(c); return '\\'; } public IToken processStringLiteral(boolean wideLiteral) throws ScannerException, EndOfFileException { int beginOffset = getCurrentOffset(); strbuff.startString(); int beforePrevious = NOCHAR; int previous = '"'; int c = getChar(true); for( ; ; ) { if (c == '\\') c = consumeNewlineAfterSlash(); if ( ( c == '"' ) && ( previous != '\\' || beforePrevious == '\\') ) break; if ( ( c == NOCHAR ) || (( c == '\n' ) && ( previous != '\\' || beforePrevious == '\\')) ) { // TODO : we could probably return the partial string -- it might cause // the parse to get by... handleProblem( IProblem.SCANNER_UNBOUNDED_STRING, null, beginOffset, false, true ); return null; } strbuff.append(c); beforePrevious = previous; previous = c; c = getChar(true); } int type = wideLiteral ? IToken.tLSTRING : IToken.tSTRING; //If the next token is going to be a string as well, we need to concatenate //it with this token. This will be recursive for as many strings as need to be concatenated String result = strbuff.toString(); IToken returnToken = newToken( type, result ); IToken next = null; try{ next = nextToken( true ); if ( next != null && (next.getType() == IToken.tSTRING || next.getType() == IToken.tLSTRING )) { returnToken.setImage(result + next.getImage()); } else cachedToken = next; } catch( EndOfFileException e ){ next = null; } currentToken = returnToken; returnToken.setNext( null ); return returnToken; } public IToken processNumber(int c, boolean pasting) throws ScannerException, EndOfFileException { // pasting happens when a macro appears in the middle of a number // we will "store" the first part of the number in the "pasting" buffer // until we have the full monty to evaluate // for example // #define F1 3 // #define F2 F1##F1 // int x = F2; int beginOffset = getCurrentOffset(); strbuff.startString(); boolean hex = false; boolean floatingPoint = ( c == '.' ) ? true : false; boolean firstCharZero = ( c== '0' )? true : false; strbuff.append(c); int firstChar = c; c = getChar(false); if( ! firstCharZero && floatingPoint && !(c >= '0' && c <= '9') ){ //if pasting, there could actually be a float here instead of just a . if( firstChar == '.' ) { if( c == '*' ){ return newConstantToken( IToken.tDOTSTAR ); } else if( c == '.' ){ if( getChar(false) == '.' ) return newConstantToken( IToken.tELLIPSIS ); handleProblem( IProblem.SCANNER_BAD_FLOATING_POINT, null, beginOffset, false, true ); } else { ungetChar( c ); return newConstantToken( IToken.tDOT ); } } } else if (c == 'x') { if( ! firstCharZero ) { handleProblem( IProblem.SCANNER_BAD_HEX_FORMAT, null, beginOffset, false, true ); return null; // c = getChar(); // continue; } strbuff.append(c); hex = true; c = getChar(false); } while ((c >= '0' && c <= '9') || (hex && ((c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')))) { strbuff.append(c); c = getChar(false); } if( c == '.' ) { strbuff.append(c); floatingPoint = true; c= getChar(false); while ((c >= '0' && c <= '9') || (hex && ((c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')))) { strbuff.append(c); c = getChar(false); } } if (c == 'e' || c == 'E' || (hex && (c == 'p' || c == 'P'))) { if( ! floatingPoint ) floatingPoint = true; // exponent type for floating point strbuff.append(c); c = getChar(false); // optional + or - if( c == '+' || c == '-' ) { strbuff.append(c ); c = getChar(false); } // digit sequence of exponent part while ((c >= '0' && c <= '9') ) { strbuff.append(c); c = getChar(false); } // optional suffix if( c == 'l' || c == 'L' || c == 'f' || c == 'F' ) { strbuff.append(c ); c = getChar(false); } } else { if( floatingPoint ){ //floating-suffix if( c == 'l' || c == 'L' || c == 'f' || c == 'F' ){ c = getChar(false); } } else { //integer suffix if( c == 'u' || c == 'U' ){ c = getChar(false); if( c == 'l' || c == 'L') c = getChar(false); if( c == 'l' || c == 'L') c = getChar(false); } else if( c == 'l' || c == 'L' ){ c = getChar(false); if( c == 'l' || c == 'L') c = getChar(false); if( c == 'u' || c == 'U' ) c = getChar(false); } } } ungetChar( c ); String result = strbuff.toString(); if( pasting && pasteIntoInputStream(result)) return null; if( floatingPoint && result.equals(".") ) //$NON-NLS-1$ return newConstantToken( IToken.tDOT ); int tokenType = floatingPoint ? IToken.tFLOATINGPT : IToken.tINTEGER; if( tokenType == IToken.tINTEGER && hex ) { if( result.equals( HEX_PREFIX ) ) { handleProblem( IProblem.SCANNER_BAD_HEX_FORMAT, HEX_PREFIX, beginOffset, false, true ); return null; } } return newToken( tokenType, result); } public IToken processPreprocessor() throws ScannerException, EndOfFileException { int c; int beginningOffset = currentContext.getOffset() - 1; int beginningLine = contextStack.getCurrentLineNumber(); // we are allowed arbitrary whitespace after the '#' and before the rest of the text boolean skipped = skipOverWhitespace(); c = getChar(false); if( c == '#' ) { if( skipped ) handleProblem( IProblem.PREPROCESSOR_INVALID_DIRECTIVE, "# #", beginningOffset, false, true ); //$NON-NLS-1$ else return newConstantToken( tPOUNDPOUND ); //$NON-NLS-1$ } else if( tokenizingMacroReplacementList ) { ungetChar( c ); return newConstantToken( tPOUND ); //$NON-NLS-1$ } strbuff.startString(); strbuff.append('#'); while (((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z')) || (c == '_') ) { strbuff.append(c); c = getChar(false); } ungetChar(c); String token = strbuff.toString(); if( isLimitReached() ) handleCompletionOnPreprocessorDirective(token); Object directive = ppDirectives.get(token); if (directive == null) { if( scannerExtension.canHandlePreprocessorDirective( token ) ) scannerExtension.handlePreprocessorDirective( this, token, getRestOfPreprocessorLine() ); else { if( passOnToClient ) handleProblem( IProblem.PREPROCESSOR_INVALID_DIRECTIVE, token, beginningOffset, false, true ); } return null; } int type = ((Integer) directive).intValue(); switch (type) { case PreprocessorDirectives.DEFINE : if ( ! passOnToClient ) { skipOverTextUntilNewline(); if( isLimitReached() ) handleInvalidCompletion(); return null; } poundDefine(beginningOffset, beginningLine); return null; case PreprocessorDirectives.INCLUDE : if (! passOnToClient ) { skipOverTextUntilNewline(); if( isLimitReached() ) handleInvalidCompletion(); return null; } poundInclude( beginningOffset, beginningLine ); return null; case PreprocessorDirectives.UNDEFINE : if (! passOnToClient) { skipOverTextUntilNewline(); if( isLimitReached() ) handleInvalidCompletion(); return null; } removeSymbol(getNextIdentifier()); skipOverTextUntilNewline(); return null; case PreprocessorDirectives.IF : //TODO add in content assist stuff here // get the rest of the line int currentOffset = getCurrentOffset(); String expression = getRestOfPreprocessorLine(); if( isLimitReached() ) handleCompletionOnExpression( expression ); if (expression.trim().equals("")) //$NON-NLS-1$ handleProblem( IProblem.PREPROCESSOR_INVALID_DIRECTIVE, "#if", beginningOffset, false, true ); //$NON-NLS-1$ boolean expressionEvalResult = false; if( branches.queryCurrentBranchForIf() ) expressionEvalResult = evaluateExpression(expression, currentOffset); passOnToClient = branches.poundIf( expressionEvalResult ); return null; case PreprocessorDirectives.IFDEF : //TODO add in content assist stuff here String definition = getNextIdentifier(); if( isLimitReached() ) handleCompletionOnDefinition( definition ); if (getDefinition(definition) == null) { // not defined passOnToClient = branches.poundIf( false ); skipOverTextUntilNewline(); } else // continue along, act like nothing is wrong :-) passOnToClient = branches.poundIf( true ); return null; case PreprocessorDirectives.ENDIF : String restOfLine = getRestOfPreprocessorLine().trim(); if( isLimitReached() ) handleInvalidCompletion(); if( ! restOfLine.equals( "" ) ) //$NON-NLS-1$ { strbuff.startString(); strbuff.append("#endif "); //$NON-NLS-1$ strbuff.append( restOfLine ); handleProblem( IProblem.PREPROCESSOR_INVALID_DIRECTIVE, strbuff.toString(), beginningOffset, false, true ); } try{ passOnToClient = branches.poundEndif(); } catch( EmptyStackException ese ) { handleProblem( IProblem.PREPROCESSOR_UNBALANCE_CONDITION, token, beginningOffset, false, true ); } return null; case PreprocessorDirectives.IFNDEF : //TODO add in content assist stuff here String definition2 = getNextIdentifier(); if( isLimitReached() ) handleCompletionOnDefinition( definition2 ); if (getDefinition(definition2) != null) { // not defined skipOverTextUntilNewline(); passOnToClient = branches.poundIf( false ); if( isLimitReached() ) handleInvalidCompletion(); } else // continue along, act like nothing is wrong :-) passOnToClient = branches.poundIf( true ); return null; case PreprocessorDirectives.ELSE : try { passOnToClient = branches.poundElse(); } catch( EmptyStackException ese ) { handleProblem( IProblem.PREPROCESSOR_UNBALANCE_CONDITION, token, beginningOffset, false, true ); } skipOverTextUntilNewline(); if( isLimitReached() ) handleInvalidCompletion(); return null; case PreprocessorDirectives.ELIF : //TODO add in content assist stuff here int co = getCurrentOffset(); String elifExpression = getRestOfPreprocessorLine(); if( isLimitReached() ) handleCompletionOnExpression( elifExpression ); if (elifExpression.equals("")) //$NON-NLS-1$ handleProblem( IProblem.PREPROCESSOR_INVALID_DIRECTIVE, "#elif", beginningOffset, false, true ); //$NON-NLS-1$ boolean elsifResult = false; if( branches.queryCurrentBranchForElif() ) elsifResult = evaluateExpression(elifExpression, co ); try { passOnToClient = branches.poundElif( elsifResult ); } catch( EmptyStackException ese ) { strbuff.startString(); strbuff.append( token ); strbuff.append( ' ' ); strbuff.append( elifExpression ); handleProblem( IProblem.PREPROCESSOR_UNBALANCE_CONDITION, strbuff.toString(), beginningOffset, false, true ); } return null; case PreprocessorDirectives.LINE : skipOverTextUntilNewline(); if( isLimitReached() ) handleInvalidCompletion(); return null; case PreprocessorDirectives.ERROR : if (! passOnToClient) { skipOverTextUntilNewline(); if( isLimitReached() ) handleInvalidCompletion(); return null; } String restOfErrorLine = getRestOfPreprocessorLine(); if( isLimitReached() ) handleInvalidCompletion(); handleProblem( IProblem.PREPROCESSOR_POUND_ERROR, restOfErrorLine, beginningOffset, false, true ); return null; case PreprocessorDirectives.PRAGMA : skipOverTextUntilNewline(); if( isLimitReached() ) handleInvalidCompletion(); return null; case PreprocessorDirectives.BLANK : String remainderOfLine = getRestOfPreprocessorLine().trim(); if (!remainderOfLine.equals("")) { //$NON-NLS-1$ strbuff.startString(); strbuff.append( "# "); //$NON-NLS-1$ strbuff.append( remainderOfLine ); handleProblem( IProblem.PREPROCESSOR_INVALID_DIRECTIVE, strbuff.toString(), beginningOffset, false, true); } return null; default : strbuff.startString(); strbuff.append( "# "); //$NON-NLS-1$ strbuff.append( token ); handleProblem( IProblem.PREPROCESSOR_INVALID_DIRECTIVE, strbuff.toString(), beginningOffset, false, true ); return null; } } // buff contains \\u or \\U protected boolean processUniversalCharacterName() throws ScannerException { // first octet is mandatory for( int i = 0; i < 4; ++i ) { int c = getChar(false); if( ! isHex( c )) return false; strbuff.append( c ); } Vector v = new Vector(); Overall: for( int i = 0; i < 4; ++i ) { int c = getChar(false); if( ! isHex( c )) { ungetChar( c ); break; } v.add( new Character((char) c )); } if( v.size() == 4 ) { for( int i = 0; i < 4; ++i ) strbuff.append( ((Character)v.get(i)).charValue()); } else { for( int i = v.size() - 1; i >= 0; --i ) ungetChar( ((Character)v.get(i)).charValue() ); } return true; } /** * @param c * @return */ private boolean isHex(int c) { switch( c ) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': return true; default: return false; } } protected IToken processKeywordOrIdentifier(boolean pasting) throws ScannerException, EndOfFileException { int baseOffset = lastContext.getOffset() - 1; // String buffer is slow, we need a better way such as memory mapped files int c = getChar(false); for( ; ; ) { // do the least expensive tests first! while ( ( scannerExtension.offersDifferentIdentifierCharacters() && scannerExtension.isValidIdentifierCharacter(c) ) || isValidIdentifierCharacter(c) ) { strbuff.append(c); c = getChar(false); if (c == '\\') { c = consumeNewlineAfterSlash(); } } if( c == '\\') { int next = getChar(false); if( next == 'u' || next == 'U') { strbuff.append( '\\'); strbuff.append( next ); if( !processUniversalCharacterName() ) return null; c = getChar(false); continue; // back to top of loop } ungetChar( next ); } break; } ungetChar(c); String ident = strbuff. toString(); if (ident.equals(DEFINED)) return newToken(IToken.tINTEGER, handleDefinedMacro()); if( ident.equals(Directives._PRAGMA) && language == ParserLanguage.C ) { handlePragmaOperator(); return null; } if (!disableMacroExpansion) { IMacroDescriptor mapping = getDefinition(ident); if (mapping != null && !isLimitReached() && !mapping.isCircular() ) if( contextStack.shouldExpandDefinition( ident ) ) { expandDefinition(ident, mapping, baseOffset); return null; } } if( pasting && pasteIntoInputStream(ident)) return null; Object tokenTypeObject; if( language == ParserLanguage.CPP ) tokenTypeObject = cppKeywords.get(ident); else tokenTypeObject = cKeywords.get(ident); if (tokenTypeObject != null) return newConstantToken(((Integer) tokenTypeObject).intValue()); if( scannerExtension.isExtensionKeyword( language, ident ) ) return newExtensionToken( scannerExtension.createExtensionToken(this, ident )); return newToken(IToken.tIDENTIFIER, ident); } /** * @param token * @return */ protected IToken newExtensionToken(IToken token) { setCurrentToken( token ); return currentToken; } /** * @param c * @return */ protected boolean isValidIdentifierCharacter(int c) { return ((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z')) || ((c >= '0') && (c <= '9')) || (c == '_') || Character.isUnicodeIdentifierPart( (char)c); } public IToken nextToken( boolean pasting ) throws ScannerException, EndOfFileException { if( ! initialContextInitialized ) setupInitialContext(); if( cachedToken != null ){ setCurrentToken( cachedToken ); cachedToken = null; return currentToken; } IToken token; count++; int c = getChar(false); while (c != NOCHAR) { if ( ! passOnToClient ) { while (c != NOCHAR && c != '#' ) { c = getChar(false); if( c == '/' ) { c = getChar(false); if( c == '/' ) { skipOverSinglelineComment(); - c = getChar(false); continue; } else if( c == '*' ) { skipOverMultilineComment(); - c = getChar(false); continue; } } } if( c == NOCHAR ) { if( isLimitReached() ) handleInvalidCompletion(); continue; } } switch (c) { case ' ' : case '\r' : case '\t' : case '\n' : c = getChar(false); continue; case ':' : c = getChar(false); switch (c) { case ':' : return newConstantToken(IToken.tCOLONCOLON); // Diagraph case '>' : return newConstantToken(IToken.tRBRACKET); default : ungetChar(c); return newConstantToken(IToken.tCOLON); } case ';' : return newConstantToken(IToken.tSEMI); case ',' : return newConstantToken(IToken.tCOMMA); case '?' : c = getChar(false); if (c == '?') { // trigraph c = getChar(false); switch (c) { case '=': // this is the same as the # case token = processPreprocessor(); if (token == null) { c = getChar(false); continue; } return token; default: // Not a trigraph ungetChar(c); ungetChar('?'); return newConstantToken(IToken.tQUESTION); } } ungetChar(c); return newConstantToken(IToken.tQUESTION); case '(' : return newConstantToken(IToken.tLPAREN); case ')' : return newConstantToken(IToken.tRPAREN); case '[' : return newConstantToken(IToken.tLBRACKET); case ']' : return newConstantToken(IToken.tRBRACKET); case '{' : return newConstantToken(IToken.tLBRACE); case '}' : return newConstantToken(IToken.tRBRACE); case '+' : c = getChar(false); switch (c) { case '=' : return newConstantToken(IToken.tPLUSASSIGN); case '+' : return newConstantToken(IToken.tINCR); default : ungetChar(c); return newConstantToken(IToken.tPLUS); } case '-' : c = getChar(false); switch (c) { case '=' : return newConstantToken(IToken.tMINUSASSIGN); case '-' : return newConstantToken(IToken.tDECR); case '>' : c = getChar(false); switch (c) { case '*' : return newConstantToken(IToken.tARROWSTAR); default : ungetChar(c); return newConstantToken(IToken.tARROW); } default : ungetChar(c); return newConstantToken(IToken.tMINUS); } case '*' : c = getChar(false); switch (c) { case '=' : return newConstantToken(IToken.tSTARASSIGN); default : ungetChar(c); return newConstantToken(IToken.tSTAR); } case '%' : c = getChar(false); switch (c) { case '=' : return newConstantToken(IToken.tMODASSIGN); // Diagraph case '>' : return newConstantToken(IToken.tRBRACE); case ':' : // this is the same as the # case token = processPreprocessor(); if (token == null) { c = getChar(false); continue; } return token; default : ungetChar(c); return newConstantToken(IToken.tMOD); } case '^' : c = getChar(false); switch (c) { case '=' : return newConstantToken(IToken.tXORASSIGN); default : ungetChar(c); return newConstantToken(IToken.tXOR); } case '&' : c = getChar(false); switch (c) { case '=' : return newConstantToken(IToken.tAMPERASSIGN); case '&' : return newConstantToken(IToken.tAND); default : ungetChar(c); return newConstantToken(IToken.tAMPER); } case '|' : c = getChar(false); switch (c) { case '=' : return newConstantToken(IToken.tBITORASSIGN); case '|' : return newConstantToken(IToken.tOR); default : ungetChar(c); return newConstantToken(IToken.tBITOR); } case '~' : return newConstantToken(IToken.tCOMPL); case '!' : c = getChar(false); switch (c) { case '=' : return newConstantToken(IToken.tNOTEQUAL); default : ungetChar(c); return newConstantToken(IToken.tNOT); } case '=' : c = getChar(false); switch (c) { case '=' : return newConstantToken(IToken.tEQUAL); default : ungetChar(c); return newConstantToken(IToken.tASSIGN); } case '<' : c = getChar(false); switch (c) { case '<' : c = getChar(false); switch (c) { case '=' : return newConstantToken(IToken.tSHIFTLASSIGN); default : ungetChar(c); return newConstantToken(IToken.tSHIFTL); } case '=' : return newConstantToken(IToken.tLTEQUAL); // Diagraphs case '%' : return newConstantToken(IToken.tLBRACE); case ':' : return newConstantToken(IToken.tLBRACKET); default : strbuff.startString(); strbuff.append('<'); strbuff.append(c); String query = strbuff.toString(); if( scannerExtension.isExtensionOperator( language, query ) ) return newExtensionToken( scannerExtension.createExtensionToken( this, query )); ungetChar(c); if( forInclusion ) temporarilyReplaceDefinitionsMap(); return newConstantToken(IToken.tLT); } case '>' : c = getChar(false); switch (c) { case '>' : c = getChar(false); switch (c) { case '=' : return newConstantToken(IToken.tSHIFTRASSIGN); default : ungetChar(c); return newConstantToken(IToken.tSHIFTR); } case '=' : return newConstantToken(IToken.tGTEQUAL); default : strbuff.startString(); strbuff.append('>'); strbuff.append( (char)c); String query = strbuff.toString(); if( scannerExtension.isExtensionOperator( language, query ) ) return newExtensionToken( scannerExtension.createExtensionToken( this, query )); ungetChar(c); if( forInclusion ) temporarilyReplaceDefinitionsMap(); return newConstantToken(IToken.tGT); } case '.' : c = getChar(false); switch (c) { case '.' : c = getChar(false); switch (c) { case '.' : return newConstantToken(IToken.tELLIPSIS); default : // TODO : there is something missing here! break; } break; case '*' : return newConstantToken(IToken.tDOTSTAR); case '0' : case '1' : case '2' : case '3' : case '4' : case '5' : case '6' : case '7' : case '8' : case '9' : ungetChar(c); return processNumber('.', pasting); default : ungetChar(c); return newConstantToken(IToken.tDOT); } break; // The logic around the escape \ is fuzzy. There is code in getChar(boolean) and // in consumeNewLineAfterSlash(). It currently works, but is fragile. // case '\\' : // c = consumeNewlineAfterSlash(); // // // if we are left with the \ we can skip it. // if (c == '\\') // c = getChar(); // continue; case '/' : c = getChar(false); switch (c) { case '/' : skipOverSinglelineComment(); c = getChar(false); continue; case '*' : skipOverMultilineComment(); c = getChar(false); continue; case '=' : return newConstantToken(IToken.tDIVASSIGN); default : ungetChar(c); return newConstantToken(IToken.tDIV); } case '0' : case '1' : case '2' : case '3' : case '4' : case '5' : case '6' : case '7' : case '8' : case '9' : token = processNumber(c, pasting); if (token == null) { c = getChar(false); continue; } return token; case 'L' : // check for wide literal c = getChar(false); if (c == '"') token = processStringLiteral(true); else if (c == '\'') return processCharacterLiteral( c, true ); else { // This is not a wide literal -- it must be a token or keyword ungetChar(c); strbuff.startString(); strbuff.append('L'); token = processKeywordOrIdentifier(pasting); } if (token == null) { c = getChar(false); continue; } return token; case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': // 'L' is handled elsewhere case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '_': strbuff.startString(); strbuff.append( c ); token = processKeywordOrIdentifier(pasting); if (token == null) { c = getChar(false); continue; } return token; case '"' : token = processStringLiteral(false); if (token == null) { c = getChar(false); continue; } return token; case '\'' : return processCharacterLiteral( c, false ); case '#': // This is a special case -- the preprocessor is integrated into // the scanner. If we get a null token, it means that everything // was handled correctly and we can go on to the next characgter. token = processPreprocessor(); if (token == null) { c = getChar(false); continue; } return token; default: if ( ( scannerExtension.offersDifferentIdentifierCharacters() && scannerExtension.isValidIdentifierStartCharacter(c) ) || isValidIdentifierStartCharacter(c) ) { strbuff.startString(); strbuff.append( c ); token = processKeywordOrIdentifier(pasting); if (token == null) { c = getChar(false); continue; } return token; } else if( c == '\\' ) { int next = getChar(false); strbuff.startString(); strbuff.append( '\\'); strbuff.append( next ); if( next == 'u' || next =='U' ) { if( !processUniversalCharacterName() ) { handleProblem( IProblem.SCANNER_BAD_CHARACTER, strbuff.toString(), getCurrentOffset(), false, true, throwExceptionOnBadCharacterRead ); c = getChar(false); continue; } token = processKeywordOrIdentifier( pasting ); if (token == null) { c = getChar(false); continue; } return token; } ungetChar( next ); handleProblem( IProblem.SCANNER_BAD_CHARACTER, strbuff.toString(), getCurrentOffset(), false, true, throwExceptionOnBadCharacterRead ); } handleProblem( IProblem.SCANNER_BAD_CHARACTER, new Character( (char)c ).toString(), getCurrentOffset(), false, true, throwExceptionOnBadCharacterRead ); c = getChar(false); continue; } } // we're done throwEOF(null); return null; } /** * @param c * @return */ protected boolean isValidIdentifierStartCharacter(int c) { return Character.isLetter((char)c) || ( c == '_'); } /** * @param definition */ protected void handleCompletionOnDefinition(String definition) throws EndOfFileException { IASTCompletionNode node = new ASTCompletionNode( IASTCompletionNode.CompletionKind.MACRO_REFERENCE, null, null, definition, KeywordSets.getKeywords(KeywordSetKey.EMPTY, language), EMPTY_STRING, null ); throwEOF( node ); } /** * @param expression2 */ protected void handleCompletionOnExpression(String expression) throws EndOfFileException { int completionPoint = expression.length() + 2; IASTCompletionNode.CompletionKind kind = IASTCompletionNode.CompletionKind.MACRO_REFERENCE; String prefix = EMPTY_STRING; if( ! expression.trim().equals(EMPTY_STRING)) { IScanner subScanner = new Scanner( new CodeReader(expression.toCharArray()), getTemporaryHashtable(), Collections.EMPTY_LIST, NULL_REQUESTOR, ParserMode.QUICK_PARSE, language, NULL_LOG_SERVICE, scannerExtension ); IToken lastToken = null; while( true ) { try { lastToken = subScanner.nextToken(); } catch( EndOfFileException eof ) { // ok break; } catch (ScannerException e) { handleInternalError(); break; } } if( ( lastToken != null )) { if( ( lastToken.getType() == IToken.tIDENTIFIER ) && ( lastToken.getEndOffset() == completionPoint ) ) prefix = lastToken.getImage(); else if( ( lastToken.getEndOffset() == completionPoint ) && ( lastToken.getType() != IToken.tIDENTIFIER ) ) kind = IASTCompletionNode.CompletionKind.NO_SUCH_KIND; } } IASTCompletionNode node = new ASTCompletionNode( kind, null, null, prefix, KeywordSets.getKeywords(((kind == IASTCompletionNode.CompletionKind.NO_SUCH_KIND )? KeywordSetKey.EMPTY : KeywordSetKey.MACRO), language), EMPTY_STRING, null ); throwEOF( node ); } /** * @return */ private Map getTemporaryHashtable() { tempMap.clear(); return tempMap = new HashMap(); } protected void handleInvalidCompletion() throws EndOfFileException { throwEOF( new ASTCompletionNode( IASTCompletionNode.CompletionKind.UNREACHABLE_CODE, null, null, EMPTY_STRING, KeywordSets.getKeywords(KeywordSetKey.EMPTY, language ) , EMPTY_STRING, null)); } protected void handleCompletionOnPreprocessorDirective( String prefix ) throws EndOfFileException { throwEOF( new ASTCompletionNode( IASTCompletionNode.CompletionKind.NO_SUCH_KIND, null, null, prefix, KeywordSets.getKeywords(KeywordSetKey.PP_DIRECTIVE, language ), EMPTY_STRING, null)); } /** * @param key */ protected void removeSymbol(String key) { definitions.remove(key); } /** * */ protected void handlePragmaOperator() throws ScannerException, EndOfFileException { // until we know what to do with pragmas, do the equivalent as // to what we do for #pragma blah blah blah (ignore it) getRestOfPreprocessorLine(); } /** * @param c * @param wideLiteral */ protected IToken processCharacterLiteral(int c, boolean wideLiteral) throws ScannerException { int beginOffset = getCurrentOffset(); int type = wideLiteral ? IToken.tLCHAR : IToken.tCHAR; strbuff.startString(); int prev = c; int prevPrev = c; c = getChar(true); for( ; ; ) { // error conditions if( ( c == '\n' ) || ( ( c == '\\' || c =='\'' )&& prev == '\\' ) || ( c == NOCHAR ) ) { handleProblem( IProblem.SCANNER_BAD_CHARACTER, new Character( (char)c ).toString(),beginOffset, false, true, throwExceptionOnBadCharacterRead ); c = '\''; } // exit condition if ( ( c =='\'' ) && ( prev != '\\' || prevPrev == '\\' ) ) break; strbuff.append(c); prevPrev = prev; prev = c; c = getChar(true); } return newToken( type, strbuff.toString()); } protected String getCurrentFile() { return contextStack.getMostRelevantFileContext() != null ? contextStack.getMostRelevantFileContext().getContextName() : ""; //$NON-NLS-1$ } protected int getCurrentOffset() { return contextStack.getMostRelevantFileContext() != null ? contextStack.getMostRelevantFileContext().getOffset() : -1; } protected static class endOfMacroTokenException extends Exception {} // the static instance we always use protected static endOfMacroTokenException endOfMacroToken = new endOfMacroTokenException(); public IToken nextTokenForStringizing() throws ScannerException, EndOfFileException { int beginOffset = getCurrentOffset(); int c = getChar(false); strbuff.startString(); try { while (c != NOCHAR) { switch (c) { case ' ' : case '\r' : case '\t' : case '\n' : if (strbuff.length() > 0) throw endOfMacroToken; c = getChar(false); continue; case '"' : if (strbuff.length() > 0) throw endOfMacroToken; // string strbuff.startString(); c = getChar(true); for( ; ; ) { if ( c =='"' ) break; if( c == NOCHAR) break; strbuff.append(c); c = getChar(true); } if (c != NOCHAR ) { return newToken( IToken.tSTRING, strbuff.toString()); } handleProblem( IProblem.SCANNER_UNBOUNDED_STRING, null, beginOffset, false, true ); c = getChar(false); continue; case '\'' : if (strbuff.length() > 0) throw endOfMacroToken; return processCharacterLiteral( c, false ); case ',' : if (strbuff.length() > 0) throw endOfMacroToken; return newToken(IToken.tCOMMA, ","); //$NON-NLS-1$ case '(' : if (strbuff.length() > 0) throw endOfMacroToken; return newToken(IToken.tLPAREN, "("); //$NON-NLS-1$ case ')' : if (strbuff.length() > 0) throw endOfMacroToken; return newToken(IToken.tRPAREN, ")"); //$NON-NLS-1$ case '/' : if (strbuff.length() > 0) throw endOfMacroToken; c = getChar(false); switch (c) { case '/' : skipOverSinglelineComment(); c = getChar(false); continue; case '*' : skipOverMultilineComment(); c = getChar(false); continue; default: strbuff.append('/'); continue; } default : strbuff.append(c); c = getChar(false); } } } catch (endOfMacroTokenException e) { // unget the first character after the end of token ungetChar(c); } // return completed token if (strbuff.length() > 0) { return newToken(IToken.tIDENTIFIER, strbuff.toString()); } // we're done throwEOF(null); return null; } /** * */ protected void throwEOF(IASTCompletionNode node) throws EndOfFileException, OffsetLimitReachedException { if( node == null ) { if( offsetLimit == NO_OFFSET_LIMIT ) throw EOF; if( finalToken != null && finalToken.getEndOffset() == offsetLimit ) throw new OffsetLimitReachedException(finalToken); throw new OffsetLimitReachedException( (IToken)null ); } throw new OffsetLimitReachedException( node ); } static { cppKeywords.put( Keywords.AND, new Integer(IToken.t_and)); cppKeywords.put( Keywords.AND_EQ, new Integer(IToken.t_and_eq)); cppKeywords.put( Keywords.ASM, new Integer(IToken.t_asm)); cppKeywords.put( Keywords.AUTO, new Integer(IToken.t_auto)); cppKeywords.put( Keywords.BITAND, new Integer(IToken.t_bitand)); cppKeywords.put( Keywords.BITOR, new Integer(IToken.t_bitor)); cppKeywords.put( Keywords.BOOL, new Integer(IToken.t_bool)); cppKeywords.put( Keywords.BREAK, new Integer(IToken.t_break)); cppKeywords.put( Keywords.CASE, new Integer(IToken.t_case)); cppKeywords.put( Keywords.CATCH, new Integer(IToken.t_catch)); cppKeywords.put( Keywords.CHAR, new Integer(IToken.t_char)); cppKeywords.put( Keywords.CLASS, new Integer(IToken.t_class)); cppKeywords.put( Keywords.COMPL, new Integer(IToken.t_compl)); cppKeywords.put( Keywords.CONST, new Integer(IToken.t_const)); cppKeywords.put( Keywords.CONST_CAST, new Integer(IToken.t_const_cast)); cppKeywords.put( Keywords.CONTINUE, new Integer(IToken.t_continue)); cppKeywords.put( Keywords.DEFAULT, new Integer(IToken.t_default)); cppKeywords.put( Keywords.DELETE, new Integer(IToken.t_delete)); cppKeywords.put( Keywords.DO, new Integer(IToken.t_do)); cppKeywords.put( Keywords.DOUBLE, new Integer(IToken.t_double)); cppKeywords.put( Keywords.DYNAMIC_CAST, new Integer(IToken.t_dynamic_cast)); cppKeywords.put( Keywords.ELSE, new Integer(IToken.t_else)); cppKeywords.put( Keywords.ENUM, new Integer(IToken.t_enum)); cppKeywords.put( Keywords.EXPLICIT, new Integer(IToken.t_explicit)); cppKeywords.put( Keywords.EXPORT, new Integer(IToken.t_export)); cppKeywords.put( Keywords.EXTERN, new Integer(IToken.t_extern)); cppKeywords.put( Keywords.FALSE, new Integer(IToken.t_false)); cppKeywords.put( Keywords.FLOAT, new Integer(IToken.t_float)); cppKeywords.put( Keywords.FOR, new Integer(IToken.t_for)); cppKeywords.put( Keywords.FRIEND, new Integer(IToken.t_friend)); cppKeywords.put( Keywords.GOTO, new Integer(IToken.t_goto)); cppKeywords.put( Keywords.IF, new Integer(IToken.t_if)); cppKeywords.put( Keywords.INLINE, new Integer(IToken.t_inline)); cppKeywords.put( Keywords.INT, new Integer(IToken.t_int)); cppKeywords.put( Keywords.LONG, new Integer(IToken.t_long)); cppKeywords.put( Keywords.MUTABLE, new Integer(IToken.t_mutable)); cppKeywords.put( Keywords.NAMESPACE, new Integer(IToken.t_namespace)); cppKeywords.put( Keywords.NEW, new Integer(IToken.t_new)); cppKeywords.put( Keywords.NOT, new Integer(IToken.t_not)); cppKeywords.put( Keywords.NOT_EQ, new Integer(IToken.t_not_eq)); cppKeywords.put( Keywords.OPERATOR, new Integer(IToken.t_operator)); cppKeywords.put( Keywords.OR, new Integer(IToken.t_or)); cppKeywords.put( Keywords.OR_EQ, new Integer(IToken.t_or_eq)); cppKeywords.put( Keywords.PRIVATE, new Integer(IToken.t_private)); cppKeywords.put( Keywords.PROTECTED, new Integer(IToken.t_protected)); cppKeywords.put( Keywords.PUBLIC, new Integer(IToken.t_public)); cppKeywords.put( Keywords.REGISTER, new Integer(IToken.t_register)); cppKeywords.put( Keywords.REINTERPRET_CAST, new Integer(IToken.t_reinterpret_cast)); cppKeywords.put( Keywords.RETURN, new Integer(IToken.t_return)); cppKeywords.put( Keywords.SHORT, new Integer(IToken.t_short)); cppKeywords.put( Keywords.SIGNED, new Integer(IToken.t_signed)); cppKeywords.put( Keywords.SIZEOF, new Integer(IToken.t_sizeof)); cppKeywords.put( Keywords.STATIC, new Integer(IToken.t_static)); cppKeywords.put( Keywords.STATIC_CAST, new Integer(IToken.t_static_cast)); cppKeywords.put( Keywords.STRUCT, new Integer(IToken.t_struct)); cppKeywords.put( Keywords.SWITCH, new Integer(IToken.t_switch)); cppKeywords.put( Keywords.TEMPLATE, new Integer(IToken.t_template)); cppKeywords.put( Keywords.THIS, new Integer(IToken.t_this)); cppKeywords.put( Keywords.THROW, new Integer(IToken.t_throw)); cppKeywords.put( Keywords.TRUE, new Integer(IToken.t_true)); cppKeywords.put( Keywords.TRY, new Integer(IToken.t_try)); cppKeywords.put( Keywords.TYPEDEF, new Integer(IToken.t_typedef)); cppKeywords.put( Keywords.TYPEID, new Integer(IToken.t_typeid)); cppKeywords.put( Keywords.TYPENAME, new Integer(IToken.t_typename)); cppKeywords.put( Keywords.UNION, new Integer(IToken.t_union)); cppKeywords.put( Keywords.UNSIGNED, new Integer(IToken.t_unsigned)); cppKeywords.put( Keywords.USING, new Integer(IToken.t_using)); cppKeywords.put( Keywords.VIRTUAL, new Integer(IToken.t_virtual)); cppKeywords.put( Keywords.VOID, new Integer(IToken.t_void)); cppKeywords.put( Keywords.VOLATILE, new Integer(IToken.t_volatile)); cppKeywords.put( Keywords.WCHAR_T, new Integer(IToken.t_wchar_t)); cppKeywords.put( Keywords.WHILE, new Integer(IToken.t_while)); cppKeywords.put( Keywords.XOR, new Integer(IToken.t_xor)); cppKeywords.put( Keywords.XOR_EQ, new Integer(IToken.t_xor_eq)); ppDirectives.put(Directives.POUND_DEFINE, new Integer(PreprocessorDirectives.DEFINE)); ppDirectives.put(Directives.POUND_UNDEF,new Integer(PreprocessorDirectives.UNDEFINE)); ppDirectives.put(Directives.POUND_IF, new Integer(PreprocessorDirectives.IF)); ppDirectives.put(Directives.POUND_IFDEF, new Integer(PreprocessorDirectives.IFDEF)); ppDirectives.put(Directives.POUND_IFNDEF, new Integer(PreprocessorDirectives.IFNDEF)); ppDirectives.put(Directives.POUND_ELSE, new Integer(PreprocessorDirectives.ELSE)); ppDirectives.put(Directives.POUND_ENDIF, new Integer(PreprocessorDirectives.ENDIF)); ppDirectives.put(Directives.POUND_INCLUDE, new Integer(PreprocessorDirectives.INCLUDE)); ppDirectives.put(Directives.POUND_LINE, new Integer(PreprocessorDirectives.LINE)); ppDirectives.put(Directives.POUND_ERROR, new Integer(PreprocessorDirectives.ERROR)); ppDirectives.put(Directives.POUND_PRAGMA, new Integer(PreprocessorDirectives.PRAGMA)); ppDirectives.put(Directives.POUND_ELIF, new Integer(PreprocessorDirectives.ELIF)); ppDirectives.put(Directives.POUND_BLANK, new Integer(PreprocessorDirectives.BLANK)); cKeywords.put( Keywords.AUTO, new Integer(IToken.t_auto)); cKeywords.put( Keywords.BREAK, new Integer(IToken.t_break)); cKeywords.put( Keywords.CASE, new Integer(IToken.t_case)); cKeywords.put( Keywords.CHAR, new Integer(IToken.t_char)); cKeywords.put( Keywords.CONST, new Integer(IToken.t_const)); cKeywords.put( Keywords.CONTINUE, new Integer(IToken.t_continue)); cKeywords.put( Keywords.DEFAULT, new Integer(IToken.t_default)); cKeywords.put( Keywords.DELETE, new Integer(IToken.t_delete)); cKeywords.put( Keywords.DO, new Integer(IToken.t_do)); cKeywords.put( Keywords.DOUBLE, new Integer(IToken.t_double)); cKeywords.put( Keywords.ELSE, new Integer(IToken.t_else)); cKeywords.put( Keywords.ENUM, new Integer(IToken.t_enum)); cKeywords.put( Keywords.EXTERN, new Integer(IToken.t_extern)); cKeywords.put( Keywords.FLOAT, new Integer(IToken.t_float)); cKeywords.put( Keywords.FOR, new Integer(IToken.t_for)); cKeywords.put( Keywords.GOTO, new Integer(IToken.t_goto)); cKeywords.put( Keywords.IF, new Integer(IToken.t_if)); cKeywords.put( Keywords.INLINE, new Integer(IToken.t_inline)); cKeywords.put( Keywords.INT, new Integer(IToken.t_int)); cKeywords.put( Keywords.LONG, new Integer(IToken.t_long)); cKeywords.put( Keywords.REGISTER, new Integer(IToken.t_register)); cKeywords.put( Keywords.RESTRICT, new Integer(IToken.t_restrict)); cKeywords.put( Keywords.RETURN, new Integer(IToken.t_return)); cKeywords.put( Keywords.SHORT, new Integer(IToken.t_short)); cKeywords.put( Keywords.SIGNED, new Integer(IToken.t_signed)); cKeywords.put( Keywords.SIZEOF, new Integer(IToken.t_sizeof)); cKeywords.put( Keywords.STATIC, new Integer(IToken.t_static)); cKeywords.put( Keywords.STRUCT, new Integer(IToken.t_struct)); cKeywords.put( Keywords.SWITCH, new Integer(IToken.t_switch)); cKeywords.put( Keywords.TYPEDEF, new Integer(IToken.t_typedef)); cKeywords.put( Keywords.UNION, new Integer(IToken.t_union)); cKeywords.put( Keywords.UNSIGNED, new Integer(IToken.t_unsigned)); cKeywords.put( Keywords.VOID, new Integer(IToken.t_void)); cKeywords.put( Keywords.VOLATILE, new Integer(IToken.t_volatile)); cKeywords.put( Keywords.WHILE, new Integer(IToken.t_while)); cKeywords.put( Keywords._BOOL, new Integer(IToken.t__Bool)); cKeywords.put( Keywords._COMPLEX, new Integer(IToken.t__Complex)); cKeywords.put( Keywords._IMAGINARY, new Integer(IToken.t__Imaginary)); } static public class PreprocessorDirectives { static public final int DEFINE = 0; static public final int UNDEFINE = 1; static public final int IF = 2; static public final int IFDEF = 3; static public final int IFNDEF = 4; static public final int ELSE = 5; static public final int ENDIF = 6; static public final int INCLUDE = 7; static public final int LINE = 8; static public final int ERROR = 9; static public final int PRAGMA = 10; static public final int BLANK = 11; static public final int ELIF = 12; } public final int getCount() { return count; } public final int getDepth() { return branches.getDepth(); } protected boolean evaluateExpressionNew(String expression, int beginningOffset ) throws ScannerException { // TODO John HELP! something has changed. If I turn this to true, My tests finish early (but the JUnits pass!) IScannerContext context = new ScannerContextTopString(expression, EXPRESSION, ';', true); contextStack.cs_push(context); ISourceElementRequestor savedRequestor = requestor; IParserLogService savedLog = log; log = NULL_LOG_SERVICE; requestor = NULL_REQUESTOR; boolean savedPassOnToClient = passOnToClient; ParserMode savedParserMode = parserMode; IASTFactory savedFactory = astFactory; passOnToClient = true; parserMode = ParserMode.QUICK_PARSE; IExpressionParser parser = InternalParserUtil.createExpressionParser(this, language, NULL_LOG_SERVICE); try { IASTExpression exp = parser.expression(null, null, null); return (exp.evaluateExpression() != 0); } catch( BacktrackException backtrack ) { return false; } catch (ASTExpressionEvaluationException e) { return false; } catch (EndOfFileException e) { return false; } finally { contextStack.cs_pop(); requestor = savedRequestor; passOnToClient = savedPassOnToClient; parserMode = savedParserMode; astFactory = savedFactory; log = savedLog; } } protected boolean evaluateExpressionOld(String expression, int beginningOffset ) throws ScannerException { IExpressionParser parser = null; strbuff.startString(); strbuff.append(expression); strbuff.append(';'); IScanner trial = new Scanner( new CodeReader(strbuff.toString().toCharArray()), definitions, includePathNames, NULL_REQUESTOR, ParserMode.QUICK_PARSE, language, NULL_LOG_SERVICE, scannerExtension ); parser = InternalParserUtil.createExpressionParser(trial, language, NULL_LOG_SERVICE); try { IASTExpression exp = parser.expression(null, null, null); return (exp.evaluateExpression() != 0); } catch( BacktrackException backtrack ) { if( parserMode == ParserMode.QUICK_PARSE ) return false; handleProblem( IProblem.PREPROCESSOR_CONDITIONAL_EVAL_ERROR, expression, beginningOffset, false, true ); } catch (ASTExpressionEvaluationException e) { if( parserMode == ParserMode.QUICK_PARSE ) return false; handleProblem( IProblem.PREPROCESSOR_CONDITIONAL_EVAL_ERROR, expression, beginningOffset, false, true ); } catch (EndOfFileException e) { if( parserMode == ParserMode.QUICK_PARSE ) return false; handleProblem( IProblem.PREPROCESSOR_CONDITIONAL_EVAL_ERROR, expression, beginningOffset, false, true ); } return true; } protected boolean evaluateExpression(String expression, int beginningOffset ) throws ScannerException { // boolean old_e = evaluateExpressionOld(expression, beginningOffset); boolean new_e = evaluateExpressionNew(expression, beginningOffset); // if (old_e != new_e) { // System.out.println("Ouch " + expression + " New: " + new_e + " Old: " + old_e); // } // if (true) return new_e; // else // return old_e; } protected void skipOverSinglelineComment() throws ScannerException, EndOfFileException { int c; loop: for (;;) { c = getChar(false); switch (c) { case NOCHAR : case '\n' : break loop; default : break; } } if( c== NOCHAR && isLimitReached() ) handleInvalidCompletion(); } protected boolean skipOverMultilineComment() throws ScannerException, EndOfFileException { int state = 0; boolean encounteredNewline = false; // simple state machine to handle multi-line comments // state 0 == no end of comment in site // state 1 == encountered *, expecting / // state 2 == we are no longer in a comment int c = getChar(false); while (state != 2 && c != NOCHAR) { if (c == '\n') encounteredNewline = true; switch (state) { case 0 : if (c == '*') state = 1; break; case 1 : if (c == '/') state = 2; else if (c != '*') state = 0; break; } c = getChar(false); } if ( state != 2) if (c == NOCHAR && !isLimitReached() ) handleProblem( IProblem.SCANNER_UNEXPECTED_EOF, null, getCurrentOffset(), false, true ); else if( c== NOCHAR ) // limit reached handleInvalidCompletion(); ungetChar(c); return encounteredNewline; } private static final InclusionParseException INCLUSION_PARSE_EXCEPTION = new InclusionParseException(); public InclusionDirective parseInclusionDirective( String includeLine, int baseOffset ) throws InclusionParseException { if (includeLine.equals("")) //$NON-NLS-1$ throw INCLUSION_PARSE_EXCEPTION ; ISourceElementRequestor savedRequestor = requestor; try { IScannerContext context = new ScannerContextTopString( includeLine, "INCLUDE", true ); //$NON-NLS-1$ contextStack.cs_push(context); requestor = NULL_REQUESTOR; boolean useIncludePath = true; StringBuffer localStringBuff = new StringBuffer(100); int startOffset = baseOffset, endOffset = baseOffset; IToken t = null; try { t = nextToken(false); } catch (EndOfFileException eof) { throw INCLUSION_PARSE_EXCEPTION ; } try { if (t.getType() == IToken.tSTRING) { localStringBuff.append(t.getImage()); startOffset = baseOffset + t.getOffset(); endOffset = baseOffset + t.getEndOffset(); useIncludePath = false; // This should throw EOF t = nextToken(false); contextStack.cs_pop(); requestor = savedRequestor; throw INCLUSION_PARSE_EXCEPTION ; } else if (t.getType() == IToken.tLT) { disableMacroExpansion = true; try { t = nextToken(false); startOffset = baseOffset + t.getOffset(); while (t.getType() != IToken.tGT) { localStringBuff.append(t.getImage()); skipOverWhitespace(); int c = getChar(); if (c == '\\') localStringBuff.append('\\'); else ungetChar(c); t = nextToken(false); } endOffset = baseOffset + t.getEndOffset(); } catch (EndOfFileException eof) { throw INCLUSION_PARSE_EXCEPTION ; } // This should throw EOF t = nextToken(false); throw INCLUSION_PARSE_EXCEPTION ; } else throw INCLUSION_PARSE_EXCEPTION ; } catch( EndOfFileException eof ) { // good } return new InclusionDirective( localStringBuff.toString(), useIncludePath, startOffset, endOffset ); } catch( ScannerException se ) { throw INCLUSION_PARSE_EXCEPTION ; } finally { contextStack.cs_pop(); requestor = savedRequestor; disableMacroExpansion = false; } } protected void poundInclude( int beginningOffset, int startLine ) throws ScannerException, EndOfFileException { skipOverWhitespace(); int baseOffset = lastContext.getOffset() ; int nameLine = contextStack.getCurrentLineNumber(); String includeLine = getRestOfPreprocessorLine(); if( isLimitReached() ) handleInvalidCompletion(); int endLine = contextStack.getCurrentLineNumber(); ScannerUtility.InclusionDirective directive = null; try { directive = parseInclusionDirective( includeLine, baseOffset ); } catch( ScannerUtility.InclusionParseException ipe ) { strbuff.startString(); strbuff.append( "#include "); //$NON-NLS-1$ strbuff.append( includeLine ); handleProblem( IProblem.PREPROCESSOR_INVALID_DIRECTIVE, strbuff.toString(), beginningOffset, false, true ); return; } if( parserMode == ParserMode.QUICK_PARSE ) { if( requestor != null ) { IASTInclusion i = null; try { i = getASTFactory().createInclusion( directive.getFilename(), "", //$NON-NLS-1$ !directive.useIncludePaths(), beginningOffset, startLine, directive.getStartOffset(), directive.getStartOffset() + directive.getFilename().length(), nameLine, directive.getEndOffset(), endLine); } catch (Exception e) { /* do nothing */ } if( i != null ) { i.enterScope( requestor, null ); i.exitScope( requestor, null ); } } } else handleInclusion(directive.getFilename().trim(), directive.useIncludePaths(), beginningOffset, startLine, directive.getStartOffset(), nameLine, directive.getEndOffset(), endLine); } protected Map definitionsBackupMap = null; protected void temporarilyReplaceDefinitionsMap() { definitionsBackupMap = definitions; definitions = Collections.EMPTY_MAP; } protected void restoreDefinitionsMap() { definitions = definitionsBackupMap; definitionsBackupMap = null; } protected boolean forInclusion = false; private final static IParserLogService NULL_LOG_SERVICE = new NullLogService(); private static final String [] STRING_ARRAY = new String[0]; private static final IToken [] EMPTY_TOKEN_ARRAY = new IToken[0]; private static final int START_BUFFER_SIZE = 8; private IToken[] tokenArrayBuffer = new IToken[START_BUFFER_SIZE]; /** * @param b */ protected void setForInclusion(boolean b) { forInclusion = b; } public boolean disableMacroExpansion = false; protected IToken[] tokenizeReplacementString( int beginning, String key, String replacementString, String[] parameterIdentifiers ) { if( replacementString.trim().equals( "" ) ) //$NON-NLS-1$ return EMPTY_TOKEN_ARRAY; IToken [] macroReplacementTokens = getTokenBuffer(); int currentIndex = 0; IScannerContext context = new ScannerContextTopString(replacementString, SCRATCH, true); contextStack.cs_push(context); ISourceElementRequestor savedRequestor = requestor; IParserLogService savedLog = log; setTokenizingMacroReplacementList( true ); disableMacroExpansion = true; requestor = NULL_REQUESTOR; log = NULL_LOG_SERVICE; try { IToken t = null; try { t = nextToken(false); } catch (ScannerException e) { } catch (EndOfFileException e) { } if( t == null ) return EMPTY_TOKEN_ARRAY; try { while (true) { //each # preprocessing token in the replacement list shall be followed //by a parameter as the next reprocessing token in the list if( t.getType() == tPOUND ){ if( currentIndex == macroReplacementTokens.length ) { IToken [] doubled = new IToken[macroReplacementTokens.length * 2]; System.arraycopy( macroReplacementTokens, 0, doubled, 0, macroReplacementTokens.length ); macroReplacementTokens = doubled; } macroReplacementTokens[currentIndex++] = t; t = nextToken(false); if( parameterIdentifiers != null ) { int index = findIndex( parameterIdentifiers, t.getImage()); if (index == -1 ) { //not found if( beginning != NO_OFFSET_LIMIT ) { strbuff.startString(); strbuff.append( POUND_DEFINE ); strbuff.append( key ); strbuff.append( ' ' ); strbuff.append( replacementString ); handleProblem( IProblem.PREPROCESSOR_MACRO_PASTING_ERROR, strbuff.toString(), beginning, false, true ); return EMPTY_TOKEN_ARRAY; } } } } if( currentIndex == macroReplacementTokens.length ) { IToken [] doubled = new IToken[macroReplacementTokens.length * 2]; System.arraycopy( macroReplacementTokens, 0, doubled, 0, macroReplacementTokens.length ); macroReplacementTokens = doubled; } macroReplacementTokens[currentIndex++] = t; t = nextToken(false); } } catch( EndOfFileException eof ) { } catch( ScannerException sc ) { } IToken [] result = new IToken[ currentIndex ]; System.arraycopy( macroReplacementTokens, 0, result, 0, currentIndex ); return result; } finally { contextStack.cs_pop(); setTokenizingMacroReplacementList( false ); requestor = savedRequestor; log = savedLog; disableMacroExpansion = false; } } /** * @return */ IToken[] getTokenBuffer() { Arrays.fill( tokenArrayBuffer, null ); return tokenArrayBuffer; } protected IMacroDescriptor createObjectMacroDescriptor(String key, String value ) { IToken t = null; if( !value.trim().equals( "" ) ) //$NON-NLS-1$ t = TokenFactory.createUniquelyImagedToken( IToken.tIDENTIFIER, value, this ); return new ObjectMacroDescriptor( key, t, value); } protected void poundDefine(int beginning, int beginningLine ) throws ScannerException, EndOfFileException { // definition String key = getNextIdentifier(); int offset = currentContext.getOffset() - key.length(); int nameLine = contextStack.getCurrentLineNumber(); // store the previous definition to check against later IMacroDescriptor previousDefinition = getDefinition( key ); IMacroDescriptor descriptor = null; // get the next character // the C++ standard says that macros must not put // whitespace between the end of the definition // identifier and the opening parenthesis int c = getChar(false); if (c == '(') { strbuff.startString(); c = getChar(true); while (c != ')') { if( c == '\\' ){ c = getChar(false); if( c == '\r' ) c = getChar(false); if( c == '\n' ){ c = getChar(false); continue; } ungetChar( c ); String line = strbuff.toString(); strbuff.startString(); strbuff.append( POUND_DEFINE ); strbuff.append( line ); strbuff.append( '\\'); strbuff.append( c ); handleProblem( IProblem.PREPROCESSOR_INVALID_MACRO_DEFN, strbuff.toString(), beginning, false, true); return; } else if( c == '\r' || c == '\n' || c == NOCHAR ){ String line = strbuff.toString(); strbuff.startString(); strbuff.append( POUND_DEFINE ); strbuff.append( line ); strbuff.append( '\\'); strbuff.append( c ); handleProblem( IProblem.PREPROCESSOR_INVALID_MACRO_DEFN, strbuff.toString(), beginning, false, true ); return; } strbuff.append(c); c = getChar(true); } String parameters = strbuff.toString(); // replace StringTokenizer later -- not performant StringTokenizer tokenizer = new StringTokenizer(parameters, ","); //$NON-NLS-1$ String []parameterIdentifiers = new String[tokenizer.countTokens()]; int ct = 0; while (tokenizer.hasMoreTokens()) { parameterIdentifiers[ ct++ ] = tokenizer.nextToken().trim(); } skipOverWhitespace(); IToken [] macroReplacementTokens = null; String replacementString = getRestOfPreprocessorLine(); // TODO: This tokenization could be done live, instead of using a sub-scanner. macroReplacementTokens = ( ! replacementString.equals( "" ) ) ? //$NON-NLS-1$ tokenizeReplacementString( beginning, key, replacementString, parameterIdentifiers ) : EMPTY_TOKEN_ARRAY; descriptor = new FunctionMacroDescriptor( key, parameterIdentifiers, macroReplacementTokens, replacementString); checkValidMacroRedefinition(key, previousDefinition, descriptor, beginning); addDefinition(key, descriptor); } else if ((c == '\n') || (c == '\r')) { descriptor = createObjectMacroDescriptor(key, ""); //$NON-NLS-1$ checkValidMacroRedefinition(key, previousDefinition, descriptor, beginning); addDefinition( key, descriptor ); } else if ((c == ' ') || (c == '\t') ) { // this is a simple definition skipOverWhitespace(); // get what we are to map the name to and add it to the definitions list String value = getRestOfPreprocessorLine(); descriptor = createObjectMacroDescriptor(key, value); checkValidMacroRedefinition(key, previousDefinition, descriptor, beginning); addDefinition( key, descriptor ); } else if (c == '/') { // this could be a comment c = getChar(false); if (c == '/') // one line comment { skipOverSinglelineComment(); descriptor = createObjectMacroDescriptor(key, ""); //$NON-NLS-1$ checkValidMacroRedefinition(key, previousDefinition, descriptor, beginning); addDefinition(key, descriptor); } else if (c == '*') // multi-line comment { if (skipOverMultilineComment()) { // we have gone over a newline // therefore, this symbol was defined to an empty string descriptor = createObjectMacroDescriptor(key, ""); //$NON-NLS-1$ checkValidMacroRedefinition(key, previousDefinition, descriptor, beginning); addDefinition(key, descriptor); } else { String value = getRestOfPreprocessorLine(); descriptor = createObjectMacroDescriptor(key, value); checkValidMacroRedefinition(key, previousDefinition, descriptor, beginning); addDefinition(key, descriptor); } } else { // this is not a comment // it is a bad statement StringBuffer potentialErrorMessage = new StringBuffer( POUND_DEFINE ); potentialErrorMessage.append( key ); potentialErrorMessage.append( " /"); //$NON-NLS-1$ potentialErrorMessage.append( getRestOfPreprocessorLine() ); handleProblem( IProblem.PREPROCESSOR_INVALID_MACRO_DEFN, potentialErrorMessage.toString(), beginning, false, true ); return; } } else { StringBuffer potentialErrorMessage = new StringBuffer( POUND_DEFINE ); potentialErrorMessage.append( key ); potentialErrorMessage.append( (char)c ); potentialErrorMessage.append( getRestOfPreprocessorLine() ); handleProblem( IProblem.PREPROCESSOR_INVALID_MACRO_DEFN, potentialErrorMessage.toString(), beginning, false, true ); return; } try { getASTFactory().createMacro( key, beginning, beginningLine, offset, offset + key.length(), nameLine, currentContext.getOffset(), contextStack.getCurrentLineNumber(), descriptor ).acceptElement( requestor, null ); } catch (Exception e) { /* do nothing */ } } protected void checkValidMacroRedefinition( String key, IMacroDescriptor previousDefinition, IMacroDescriptor newDefinition, int beginningOffset ) throws ScannerException { if( parserMode != ParserMode.QUICK_PARSE && previousDefinition != null ) { if( previousDefinition.compatible( newDefinition ) ) return; handleProblem( IProblem.PREPROCESSOR_INVALID_MACRO_REDEFN, key, beginningOffset, false, true ); } } /** * */ protected void handleInternalError() { // TODO Auto-generated method stub } protected Vector getMacroParameters (String params, boolean forStringizing) throws ScannerException { // split params up into single arguments int nParen = 0; Vector parameters = new Vector(); strbuff.startString(); for (int i = 0; i < params.length(); i++) { char c = params.charAt(i); switch (c) { case '(' : nParen++; break; case ')' : nParen--; break; case ',' : if (nParen == 0) { parameters.add(strbuff.toString()); strbuff.startString(); continue; } break; default : break; } strbuff.append( c ); } parameters.add(strbuff.toString()); setThrowExceptionOnBadCharacterRead(false); ISourceElementRequestor savedRequestor = requestor; IParserLogService savedLog = log; log = NULL_LOG_SERVICE; requestor = NULL_REQUESTOR; Vector parameterValues = new Vector(); for (int i = 0; i < parameters.size(); i++) { IScannerContext context = new ScannerContextTopString((String)parameters.elementAt(i), TEXT, true); contextStack.cs_push(context); IToken t = null; StringBuffer strBuff2 = new StringBuffer(); boolean space = false; try { while (true) { int c = getCharacter(); if ((c != ' ') && (c != '\t') && (c != '\r') && (c != '\n')) { space = false; } if (c != NOCHAR) ungetChar(c); t = (forStringizing ? nextTokenForStringizing() : nextToken(false)); if (space) strBuff2.append( ' ' ); switch (t.getType()) { case IToken.tSTRING : strBuff2.append('\"'); strBuff2.append(t.getImage()); strBuff2.append('\"'); break; case IToken.tLSTRING : strBuff2.append( "L\""); //$NON-NLS-1$ strBuff2.append(t.getImage()); strBuff2.append('\"'); break; case IToken.tCHAR : strBuff2.append('\''); strBuff2.append(t.getImage()); strBuff2.append('\''); break; default : strBuff2.append( t.getImage()); break; } space = true; } } catch (EndOfFileException e) { // Good contextStack.cs_pop(); parameterValues.add(strBuff2.toString()); } } setThrowExceptionOnBadCharacterRead(true); requestor = savedRequestor; log = savedLog; return parameterValues; } protected void expandDefinition(String symbol, String expansion, int symbolOffset ) throws ScannerException { expandDefinition( symbol, new ObjectMacroDescriptor( symbol, expansion ), symbolOffset); } protected void expandDefinition(String symbol, IMacroDescriptor expansion, int symbolOffset) throws ScannerException { // All the tokens generated by the macro expansion // will have dimensions (offset and length) equal to the expanding symbol. if ( expansion.getMacroType() == MacroType.OBJECT_LIKE || expansion.getMacroType() == MacroType.INTERNAL_LIKE ) { String replacementValue = expansion.getExpansionSignature(); try { contextStack.updateMacroContext( replacementValue, symbol, requestor, symbolOffset, symbol.length()); } catch (ContextException e) { handleProblem( e.getId(), currentContext.getContextName(), getCurrentOffset(), false, true ); consumeUntilOutOfMacroExpansion(); return; } } else if (expansion.getMacroType() == MacroType.FUNCTION_LIKE ) { skipOverWhitespace(); int c = getChar(false); if (c == '(') { strbuff.startString(); int bracketCount = 1; c = getChar(false); while (true) { if (c == '(') ++bracketCount; else if (c == ')') --bracketCount; if(bracketCount == 0 || c == NOCHAR) break; strbuff.append(c); c = getChar( true ); } String betweenTheBrackets = strbuff.toString().trim(); if (expansion.getExpansionSignature() == EMPTY_STRING) { return; // } // Position of the closing ')' int endMacroOffset = lastContext.getOffset() - 1; Vector parameterValues = getMacroParameters(betweenTheBrackets, false); Vector parameterValuesForStringizing = null; SimpleToken t = null; // create a string that represents what needs to be tokenized IToken [] tokens = expansion.getTokenizedExpansion(); String [] parameterNames = expansion.getParameters(); if (parameterNames.length != parameterValues.size()) { handleProblem( IProblem.PREPROCESSOR_MACRO_USAGE_ERROR, symbol, getCurrentOffset(), false, true ); consumeUntilOutOfMacroExpansion(); return; } strbuff.startString(); int numberOfTokens = tokens.length; for (int i = 0; i < numberOfTokens; ++i) { t = (SimpleToken) tokens[i]; if (t.getType() == IToken.tIDENTIFIER) { // is this identifier in the parameterNames // list? int index = findIndex( parameterNames, t.getImage() ); if (index == -1 ) { // not found // just add image to buffer strbuff.append(t.getImage() ); } else { strbuff.append( (String) parameterValues.elementAt(index) ); } } else if (t.getType() == tPOUND) { //next token should be a parameter which needs to be turned into //a string literal if( parameterValuesForStringizing == null) { String cache = strbuff.toString(); parameterValuesForStringizing = getMacroParameters(betweenTheBrackets, true); strbuff.startString(); strbuff.append(cache); } ++i; if( tokens.length == i ){ handleProblem( IProblem.PREPROCESSOR_MACRO_USAGE_ERROR, expansion.getName(), getCurrentOffset(), false, true ); return; } t = (SimpleToken) tokens[ i ]; int index = findIndex( parameterNames, t.getImage()); if( index == -1 ){ handleProblem( IProblem.PREPROCESSOR_MACRO_USAGE_ERROR, expansion.getName(), getCurrentOffset(), false, true ); return; } strbuff.append('\"'); String value = (String)parameterValuesForStringizing.elementAt(index); char val [] = value.toCharArray(); char ch; int length = value.length(); for( int j = 0; j < length; j++ ){ ch = val[j]; if( ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n' ){ //Each occurance of whitespace becomes a single space character while( ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n' ){ ch = val[++j]; } strbuff.append(' '); } //a \ character is inserted before each " and \ if( ch == '\"' || ch == '\\' ){ strbuff.append('\\'); strbuff.append(ch); } else { strbuff.append(ch); } } strbuff.append('\"'); } else { switch( t.getType() ) { case IToken.tSTRING: strbuff.append('\"'); strbuff.append(t.getImage()); strbuff.append('\"'); break; case IToken.tLSTRING: strbuff.append("L\""); //$NON-NLS-1$ strbuff.append(t.getImage()); strbuff.append('\"'); break; case IToken.tCHAR: strbuff.append('\''); strbuff.append(t.getImage()); strbuff.append('\''); break; default: strbuff.append(t.getImage()); break; } } boolean pastingNext = false; if( i != numberOfTokens - 1) { IToken t2 = tokens[i+1]; if( t2.getType() == tPOUNDPOUND ) { pastingNext = true; i++; } } if( t.getType() != tPOUNDPOUND && ! pastingNext ) if (i < (numberOfTokens-1)) // Do not append to the last one strbuff.append( ' ' ); } String finalString = strbuff.toString(); try { contextStack.updateMacroContext( finalString, expansion.getName(), requestor, symbolOffset, endMacroOffset - symbolOffset + 1 ); } catch (ContextException e) { handleProblem( e.getId(), currentContext.getContextName(), getCurrentOffset(), false, true ); consumeUntilOutOfMacroExpansion(); return; } } else { handleProblem( IProblem.PREPROCESSOR_MACRO_USAGE_ERROR, symbol, getCurrentOffset(), false, true ); consumeUntilOutOfMacroExpansion(); return; } } else { TraceUtil.outputTrace(log, "Unexpected type of MacroDescriptor stored in definitions table: ", null, expansion.getMacroType().toString(), null, null); //$NON-NLS-1$ } } /** * @param parameterNames * @param image * @return */ private int findIndex(String[] parameterNames, String image) { for( int i = 0; i < parameterNames.length; ++i ) if( parameterNames[i].equals( image ) ) return i; return -1; } protected String handleDefinedMacro() throws ScannerException { int o = getCurrentOffset(); skipOverWhitespace(); int c = getChar(false); String definitionIdentifier = null; if (c == '(') { definitionIdentifier = getNextIdentifier(); skipOverWhitespace(); c = getChar(false); if (c != ')') { handleProblem( IProblem.PREPROCESSOR_MACRO_USAGE_ERROR, "defined()", o, false, true ); //$NON-NLS-1$ return "0"; //$NON-NLS-1$ } } else { ungetChar(c); definitionIdentifier = getNextIdentifier(); } if (getDefinition(definitionIdentifier) != null) return "1"; //$NON-NLS-1$ return "0"; //$NON-NLS-1$ } public void setThrowExceptionOnBadCharacterRead( boolean throwOnBad ){ throwExceptionOnBadCharacterRead = throwOnBad; } /* (non-Javadoc) * @see org.eclipse.cdt.core.parser.IScanner#setASTFactory(org.eclipse.cdt.internal.core.parser.ast.IASTFactory) */ public void setASTFactory(IASTFactory f) { astFactory = f; } /* (non-Javadoc) * @see org.eclipse.cdt.core.parser.IScanner#setOffsetBoundary(int) */ public void setOffsetBoundary(int offset) { offsetLimit = offset; } /* (non-Javadoc) * @see org.eclipse.cdt.core.parser.IScanner#getDefinitions() */ public Map getDefinitions() { return Collections.unmodifiableMap(definitions); } /** * @param b */ public void setOffsetLimitReached(boolean b) { limitReached = b; } protected boolean isLimitReached() { if( offsetLimit == NO_OFFSET_LIMIT ) return false; return limitReached; } /* (non-Javadoc) * @see org.eclipse.cdt.core.parser.IScanner#isOnTopContext() */ public boolean isOnTopContext() { return ( currentContext.getKind() == IScannerContext.ContextKind.TOP ); } /* (non-Javadoc) * @see org.eclipse.cdt.core.parser.IFilenameProvider#getCurrentFilename() */ public char[] getCurrentFilename() { return getCurrentFile().toCharArray(); } /* (non-Javadoc) * @see java.lang.Object#toString() */ public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append( "Scanner @"); //$NON-NLS-1$ if( currentContext != null ) buffer.append( currentContext.toString()); else buffer.append( "EOF"); //$NON-NLS-1$ return buffer.toString(); } /* (non-Javadoc) * @see org.eclipse.cdt.core.parser.IFilenameProvider#getCurrentFileIndex() */ public int getCurrentFileIndex() { return contextStack.getMostRelevantFileContextIndex(); } /* (non-Javadoc) * @see org.eclipse.cdt.core.parser.IFilenameProvider#getFilenameForIndex(int) */ public String getFilenameForIndex(int index) { if( index < 0 ) return EMPTY_STRING; return contextStack.getInclusionFilename(index); } /* (non-Javadoc) * @see org.eclipse.cdt.internal.core.parser.scanner.IScannerData#getASTFactory() */ public IASTFactory getASTFactory() { if( astFactory == null ) astFactory = ParserFactory.createASTFactory( this, parserMode, language ); return astFactory; } /* (non-Javadoc) * @see org.eclipse.cdt.internal.core.parser.scanner.IScannerData#getBranchTracker() */ public BranchTracker getBranchTracker() { return branches; } /* (non-Javadoc) * @see org.eclipse.cdt.internal.core.parser.scanner.IScannerData#getInitialReader() */ public CodeReader getInitialReader() { return reader; } /* (non-Javadoc) * @see org.eclipse.cdt.internal.core.parser.scanner.IScannerData#getOriginalConfig() */ public IScannerInfo getOriginalConfig() { return originalConfig; } /* (non-Javadoc) * @see org.eclipse.cdt.internal.core.parser.scanner.IScannerData#getProblemFactory() */ public IProblemFactory getProblemFactory() { return problemFactory; } /* (non-Javadoc) * @see org.eclipse.cdt.internal.core.parser.scanner.IScannerData#getScanner() */ public IScanner getScanner() { return this; } /* (non-Javadoc) * @see org.eclipse.cdt.internal.core.parser.scanner.IScannerData#setDefinitions(java.util.Map) */ public void setDefinitions(Map map) { definitions = map; } /* (non-Javadoc) * @see org.eclipse.cdt.internal.core.parser.scanner.IScannerData#setIncludePathNames(java.util.List) */ public void setIncludePathNames(List includePathNames) { this.includePathNames = includePathNames; } public Map getFileCache() { return fileCache; } }
false
true
public IToken nextToken( boolean pasting ) throws ScannerException, EndOfFileException { if( ! initialContextInitialized ) setupInitialContext(); if( cachedToken != null ){ setCurrentToken( cachedToken ); cachedToken = null; return currentToken; } IToken token; count++; int c = getChar(false); while (c != NOCHAR) { if ( ! passOnToClient ) { while (c != NOCHAR && c != '#' ) { c = getChar(false); if( c == '/' ) { c = getChar(false); if( c == '/' ) { skipOverSinglelineComment(); c = getChar(false); continue; } else if( c == '*' ) { skipOverMultilineComment(); c = getChar(false); continue; } } } if( c == NOCHAR ) { if( isLimitReached() ) handleInvalidCompletion(); continue; } } switch (c) { case ' ' : case '\r' : case '\t' : case '\n' : c = getChar(false); continue; case ':' : c = getChar(false); switch (c) { case ':' : return newConstantToken(IToken.tCOLONCOLON); // Diagraph case '>' : return newConstantToken(IToken.tRBRACKET); default : ungetChar(c); return newConstantToken(IToken.tCOLON); } case ';' : return newConstantToken(IToken.tSEMI); case ',' : return newConstantToken(IToken.tCOMMA); case '?' : c = getChar(false); if (c == '?') { // trigraph c = getChar(false); switch (c) { case '=': // this is the same as the # case token = processPreprocessor(); if (token == null) { c = getChar(false); continue; } return token; default: // Not a trigraph ungetChar(c); ungetChar('?'); return newConstantToken(IToken.tQUESTION); } } ungetChar(c); return newConstantToken(IToken.tQUESTION); case '(' : return newConstantToken(IToken.tLPAREN); case ')' : return newConstantToken(IToken.tRPAREN); case '[' : return newConstantToken(IToken.tLBRACKET); case ']' : return newConstantToken(IToken.tRBRACKET); case '{' : return newConstantToken(IToken.tLBRACE); case '}' : return newConstantToken(IToken.tRBRACE); case '+' : c = getChar(false); switch (c) { case '=' : return newConstantToken(IToken.tPLUSASSIGN); case '+' : return newConstantToken(IToken.tINCR); default : ungetChar(c); return newConstantToken(IToken.tPLUS); } case '-' : c = getChar(false); switch (c) { case '=' : return newConstantToken(IToken.tMINUSASSIGN); case '-' : return newConstantToken(IToken.tDECR); case '>' : c = getChar(false); switch (c) { case '*' : return newConstantToken(IToken.tARROWSTAR); default : ungetChar(c); return newConstantToken(IToken.tARROW); } default : ungetChar(c); return newConstantToken(IToken.tMINUS); } case '*' : c = getChar(false); switch (c) { case '=' : return newConstantToken(IToken.tSTARASSIGN); default : ungetChar(c); return newConstantToken(IToken.tSTAR); } case '%' : c = getChar(false); switch (c) { case '=' : return newConstantToken(IToken.tMODASSIGN); // Diagraph case '>' : return newConstantToken(IToken.tRBRACE); case ':' : // this is the same as the # case token = processPreprocessor(); if (token == null) { c = getChar(false); continue; } return token; default : ungetChar(c); return newConstantToken(IToken.tMOD); } case '^' : c = getChar(false); switch (c) { case '=' : return newConstantToken(IToken.tXORASSIGN); default : ungetChar(c); return newConstantToken(IToken.tXOR); } case '&' : c = getChar(false); switch (c) { case '=' : return newConstantToken(IToken.tAMPERASSIGN); case '&' : return newConstantToken(IToken.tAND); default : ungetChar(c); return newConstantToken(IToken.tAMPER); } case '|' : c = getChar(false); switch (c) { case '=' : return newConstantToken(IToken.tBITORASSIGN); case '|' : return newConstantToken(IToken.tOR); default : ungetChar(c); return newConstantToken(IToken.tBITOR); } case '~' : return newConstantToken(IToken.tCOMPL); case '!' : c = getChar(false); switch (c) { case '=' : return newConstantToken(IToken.tNOTEQUAL); default : ungetChar(c); return newConstantToken(IToken.tNOT); } case '=' : c = getChar(false); switch (c) { case '=' : return newConstantToken(IToken.tEQUAL); default : ungetChar(c); return newConstantToken(IToken.tASSIGN); } case '<' : c = getChar(false); switch (c) { case '<' : c = getChar(false); switch (c) { case '=' : return newConstantToken(IToken.tSHIFTLASSIGN); default : ungetChar(c); return newConstantToken(IToken.tSHIFTL); } case '=' : return newConstantToken(IToken.tLTEQUAL); // Diagraphs case '%' : return newConstantToken(IToken.tLBRACE); case ':' : return newConstantToken(IToken.tLBRACKET); default : strbuff.startString(); strbuff.append('<'); strbuff.append(c); String query = strbuff.toString(); if( scannerExtension.isExtensionOperator( language, query ) ) return newExtensionToken( scannerExtension.createExtensionToken( this, query )); ungetChar(c); if( forInclusion ) temporarilyReplaceDefinitionsMap(); return newConstantToken(IToken.tLT); } case '>' : c = getChar(false); switch (c) { case '>' : c = getChar(false); switch (c) { case '=' : return newConstantToken(IToken.tSHIFTRASSIGN); default : ungetChar(c); return newConstantToken(IToken.tSHIFTR); } case '=' : return newConstantToken(IToken.tGTEQUAL); default : strbuff.startString(); strbuff.append('>'); strbuff.append( (char)c); String query = strbuff.toString(); if( scannerExtension.isExtensionOperator( language, query ) ) return newExtensionToken( scannerExtension.createExtensionToken( this, query )); ungetChar(c); if( forInclusion ) temporarilyReplaceDefinitionsMap(); return newConstantToken(IToken.tGT); } case '.' : c = getChar(false); switch (c) { case '.' : c = getChar(false); switch (c) { case '.' : return newConstantToken(IToken.tELLIPSIS); default : // TODO : there is something missing here! break; } break; case '*' : return newConstantToken(IToken.tDOTSTAR); case '0' : case '1' : case '2' : case '3' : case '4' : case '5' : case '6' : case '7' : case '8' : case '9' : ungetChar(c); return processNumber('.', pasting); default : ungetChar(c); return newConstantToken(IToken.tDOT); } break; // The logic around the escape \ is fuzzy. There is code in getChar(boolean) and // in consumeNewLineAfterSlash(). It currently works, but is fragile. // case '\\' : // c = consumeNewlineAfterSlash(); // // // if we are left with the \ we can skip it. // if (c == '\\') // c = getChar(); // continue; case '/' : c = getChar(false); switch (c) { case '/' : skipOverSinglelineComment(); c = getChar(false); continue; case '*' : skipOverMultilineComment(); c = getChar(false); continue; case '=' : return newConstantToken(IToken.tDIVASSIGN); default : ungetChar(c); return newConstantToken(IToken.tDIV); } case '0' : case '1' : case '2' : case '3' : case '4' : case '5' : case '6' : case '7' : case '8' : case '9' : token = processNumber(c, pasting); if (token == null) { c = getChar(false); continue; } return token; case 'L' : // check for wide literal c = getChar(false); if (c == '"') token = processStringLiteral(true); else if (c == '\'') return processCharacterLiteral( c, true ); else { // This is not a wide literal -- it must be a token or keyword ungetChar(c); strbuff.startString(); strbuff.append('L'); token = processKeywordOrIdentifier(pasting); } if (token == null) { c = getChar(false); continue; } return token; case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': // 'L' is handled elsewhere case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '_': strbuff.startString(); strbuff.append( c ); token = processKeywordOrIdentifier(pasting); if (token == null) { c = getChar(false); continue; } return token; case '"' : token = processStringLiteral(false); if (token == null) { c = getChar(false); continue; } return token; case '\'' : return processCharacterLiteral( c, false ); case '#': // This is a special case -- the preprocessor is integrated into // the scanner. If we get a null token, it means that everything // was handled correctly and we can go on to the next characgter. token = processPreprocessor(); if (token == null) { c = getChar(false); continue; } return token; default: if ( ( scannerExtension.offersDifferentIdentifierCharacters() && scannerExtension.isValidIdentifierStartCharacter(c) ) || isValidIdentifierStartCharacter(c) ) { strbuff.startString(); strbuff.append( c ); token = processKeywordOrIdentifier(pasting); if (token == null) { c = getChar(false); continue; } return token; } else if( c == '\\' ) { int next = getChar(false); strbuff.startString(); strbuff.append( '\\'); strbuff.append( next ); if( next == 'u' || next =='U' ) { if( !processUniversalCharacterName() ) { handleProblem( IProblem.SCANNER_BAD_CHARACTER, strbuff.toString(), getCurrentOffset(), false, true, throwExceptionOnBadCharacterRead ); c = getChar(false); continue; } token = processKeywordOrIdentifier( pasting ); if (token == null) { c = getChar(false); continue; } return token; } ungetChar( next ); handleProblem( IProblem.SCANNER_BAD_CHARACTER, strbuff.toString(), getCurrentOffset(), false, true, throwExceptionOnBadCharacterRead ); } handleProblem( IProblem.SCANNER_BAD_CHARACTER, new Character( (char)c ).toString(), getCurrentOffset(), false, true, throwExceptionOnBadCharacterRead ); c = getChar(false); continue; } } // we're done throwEOF(null); return null; }
public IToken nextToken( boolean pasting ) throws ScannerException, EndOfFileException { if( ! initialContextInitialized ) setupInitialContext(); if( cachedToken != null ){ setCurrentToken( cachedToken ); cachedToken = null; return currentToken; } IToken token; count++; int c = getChar(false); while (c != NOCHAR) { if ( ! passOnToClient ) { while (c != NOCHAR && c != '#' ) { c = getChar(false); if( c == '/' ) { c = getChar(false); if( c == '/' ) { skipOverSinglelineComment(); continue; } else if( c == '*' ) { skipOverMultilineComment(); continue; } } } if( c == NOCHAR ) { if( isLimitReached() ) handleInvalidCompletion(); continue; } } switch (c) { case ' ' : case '\r' : case '\t' : case '\n' : c = getChar(false); continue; case ':' : c = getChar(false); switch (c) { case ':' : return newConstantToken(IToken.tCOLONCOLON); // Diagraph case '>' : return newConstantToken(IToken.tRBRACKET); default : ungetChar(c); return newConstantToken(IToken.tCOLON); } case ';' : return newConstantToken(IToken.tSEMI); case ',' : return newConstantToken(IToken.tCOMMA); case '?' : c = getChar(false); if (c == '?') { // trigraph c = getChar(false); switch (c) { case '=': // this is the same as the # case token = processPreprocessor(); if (token == null) { c = getChar(false); continue; } return token; default: // Not a trigraph ungetChar(c); ungetChar('?'); return newConstantToken(IToken.tQUESTION); } } ungetChar(c); return newConstantToken(IToken.tQUESTION); case '(' : return newConstantToken(IToken.tLPAREN); case ')' : return newConstantToken(IToken.tRPAREN); case '[' : return newConstantToken(IToken.tLBRACKET); case ']' : return newConstantToken(IToken.tRBRACKET); case '{' : return newConstantToken(IToken.tLBRACE); case '}' : return newConstantToken(IToken.tRBRACE); case '+' : c = getChar(false); switch (c) { case '=' : return newConstantToken(IToken.tPLUSASSIGN); case '+' : return newConstantToken(IToken.tINCR); default : ungetChar(c); return newConstantToken(IToken.tPLUS); } case '-' : c = getChar(false); switch (c) { case '=' : return newConstantToken(IToken.tMINUSASSIGN); case '-' : return newConstantToken(IToken.tDECR); case '>' : c = getChar(false); switch (c) { case '*' : return newConstantToken(IToken.tARROWSTAR); default : ungetChar(c); return newConstantToken(IToken.tARROW); } default : ungetChar(c); return newConstantToken(IToken.tMINUS); } case '*' : c = getChar(false); switch (c) { case '=' : return newConstantToken(IToken.tSTARASSIGN); default : ungetChar(c); return newConstantToken(IToken.tSTAR); } case '%' : c = getChar(false); switch (c) { case '=' : return newConstantToken(IToken.tMODASSIGN); // Diagraph case '>' : return newConstantToken(IToken.tRBRACE); case ':' : // this is the same as the # case token = processPreprocessor(); if (token == null) { c = getChar(false); continue; } return token; default : ungetChar(c); return newConstantToken(IToken.tMOD); } case '^' : c = getChar(false); switch (c) { case '=' : return newConstantToken(IToken.tXORASSIGN); default : ungetChar(c); return newConstantToken(IToken.tXOR); } case '&' : c = getChar(false); switch (c) { case '=' : return newConstantToken(IToken.tAMPERASSIGN); case '&' : return newConstantToken(IToken.tAND); default : ungetChar(c); return newConstantToken(IToken.tAMPER); } case '|' : c = getChar(false); switch (c) { case '=' : return newConstantToken(IToken.tBITORASSIGN); case '|' : return newConstantToken(IToken.tOR); default : ungetChar(c); return newConstantToken(IToken.tBITOR); } case '~' : return newConstantToken(IToken.tCOMPL); case '!' : c = getChar(false); switch (c) { case '=' : return newConstantToken(IToken.tNOTEQUAL); default : ungetChar(c); return newConstantToken(IToken.tNOT); } case '=' : c = getChar(false); switch (c) { case '=' : return newConstantToken(IToken.tEQUAL); default : ungetChar(c); return newConstantToken(IToken.tASSIGN); } case '<' : c = getChar(false); switch (c) { case '<' : c = getChar(false); switch (c) { case '=' : return newConstantToken(IToken.tSHIFTLASSIGN); default : ungetChar(c); return newConstantToken(IToken.tSHIFTL); } case '=' : return newConstantToken(IToken.tLTEQUAL); // Diagraphs case '%' : return newConstantToken(IToken.tLBRACE); case ':' : return newConstantToken(IToken.tLBRACKET); default : strbuff.startString(); strbuff.append('<'); strbuff.append(c); String query = strbuff.toString(); if( scannerExtension.isExtensionOperator( language, query ) ) return newExtensionToken( scannerExtension.createExtensionToken( this, query )); ungetChar(c); if( forInclusion ) temporarilyReplaceDefinitionsMap(); return newConstantToken(IToken.tLT); } case '>' : c = getChar(false); switch (c) { case '>' : c = getChar(false); switch (c) { case '=' : return newConstantToken(IToken.tSHIFTRASSIGN); default : ungetChar(c); return newConstantToken(IToken.tSHIFTR); } case '=' : return newConstantToken(IToken.tGTEQUAL); default : strbuff.startString(); strbuff.append('>'); strbuff.append( (char)c); String query = strbuff.toString(); if( scannerExtension.isExtensionOperator( language, query ) ) return newExtensionToken( scannerExtension.createExtensionToken( this, query )); ungetChar(c); if( forInclusion ) temporarilyReplaceDefinitionsMap(); return newConstantToken(IToken.tGT); } case '.' : c = getChar(false); switch (c) { case '.' : c = getChar(false); switch (c) { case '.' : return newConstantToken(IToken.tELLIPSIS); default : // TODO : there is something missing here! break; } break; case '*' : return newConstantToken(IToken.tDOTSTAR); case '0' : case '1' : case '2' : case '3' : case '4' : case '5' : case '6' : case '7' : case '8' : case '9' : ungetChar(c); return processNumber('.', pasting); default : ungetChar(c); return newConstantToken(IToken.tDOT); } break; // The logic around the escape \ is fuzzy. There is code in getChar(boolean) and // in consumeNewLineAfterSlash(). It currently works, but is fragile. // case '\\' : // c = consumeNewlineAfterSlash(); // // // if we are left with the \ we can skip it. // if (c == '\\') // c = getChar(); // continue; case '/' : c = getChar(false); switch (c) { case '/' : skipOverSinglelineComment(); c = getChar(false); continue; case '*' : skipOverMultilineComment(); c = getChar(false); continue; case '=' : return newConstantToken(IToken.tDIVASSIGN); default : ungetChar(c); return newConstantToken(IToken.tDIV); } case '0' : case '1' : case '2' : case '3' : case '4' : case '5' : case '6' : case '7' : case '8' : case '9' : token = processNumber(c, pasting); if (token == null) { c = getChar(false); continue; } return token; case 'L' : // check for wide literal c = getChar(false); if (c == '"') token = processStringLiteral(true); else if (c == '\'') return processCharacterLiteral( c, true ); else { // This is not a wide literal -- it must be a token or keyword ungetChar(c); strbuff.startString(); strbuff.append('L'); token = processKeywordOrIdentifier(pasting); } if (token == null) { c = getChar(false); continue; } return token; case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': // 'L' is handled elsewhere case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '_': strbuff.startString(); strbuff.append( c ); token = processKeywordOrIdentifier(pasting); if (token == null) { c = getChar(false); continue; } return token; case '"' : token = processStringLiteral(false); if (token == null) { c = getChar(false); continue; } return token; case '\'' : return processCharacterLiteral( c, false ); case '#': // This is a special case -- the preprocessor is integrated into // the scanner. If we get a null token, it means that everything // was handled correctly and we can go on to the next characgter. token = processPreprocessor(); if (token == null) { c = getChar(false); continue; } return token; default: if ( ( scannerExtension.offersDifferentIdentifierCharacters() && scannerExtension.isValidIdentifierStartCharacter(c) ) || isValidIdentifierStartCharacter(c) ) { strbuff.startString(); strbuff.append( c ); token = processKeywordOrIdentifier(pasting); if (token == null) { c = getChar(false); continue; } return token; } else if( c == '\\' ) { int next = getChar(false); strbuff.startString(); strbuff.append( '\\'); strbuff.append( next ); if( next == 'u' || next =='U' ) { if( !processUniversalCharacterName() ) { handleProblem( IProblem.SCANNER_BAD_CHARACTER, strbuff.toString(), getCurrentOffset(), false, true, throwExceptionOnBadCharacterRead ); c = getChar(false); continue; } token = processKeywordOrIdentifier( pasting ); if (token == null) { c = getChar(false); continue; } return token; } ungetChar( next ); handleProblem( IProblem.SCANNER_BAD_CHARACTER, strbuff.toString(), getCurrentOffset(), false, true, throwExceptionOnBadCharacterRead ); } handleProblem( IProblem.SCANNER_BAD_CHARACTER, new Character( (char)c ).toString(), getCurrentOffset(), false, true, throwExceptionOnBadCharacterRead ); c = getChar(false); continue; } } // we're done throwEOF(null); return null; }
diff --git a/cobertura/src/net/sourceforge/cobertura/reporting/ComplexityCalculator.java b/cobertura/src/net/sourceforge/cobertura/reporting/ComplexityCalculator.java index 252c5e9..01e07de 100644 --- a/cobertura/src/net/sourceforge/cobertura/reporting/ComplexityCalculator.java +++ b/cobertura/src/net/sourceforge/cobertura/reporting/ComplexityCalculator.java @@ -1,268 +1,272 @@ /* * Cobertura - http://cobertura.sourceforge.net/ * * Copyright (C) 2005 Mark Doliner * Copyright (C) 2005 Jeremy Thomerson * Copyright (C) 2005 Grzegorz Lukasik * Copyright (C) 2008 Tri Bao Ho * Copyright (C) 2009 John Lewis * * Cobertura 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. * * Cobertura 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 Cobertura; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA */ package net.sourceforge.cobertura.reporting; import java.io.File; import java.io.InputStream; import java.io.IOException; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Vector; import net.sourceforge.cobertura.coveragedata.ClassData; import net.sourceforge.cobertura.coveragedata.PackageData; import net.sourceforge.cobertura.coveragedata.ProjectData; import net.sourceforge.cobertura.coveragedata.SourceFileData; import net.sourceforge.cobertura.javancss.Javancss; import net.sourceforge.cobertura.javancss.JavancssConstants; import net.sourceforge.cobertura.util.FileFinder; import net.sourceforge.cobertura.util.Source; import org.apache.log4j.Logger; /** * Allows complexity computing for source files, packages and a whole project. Average * McCabe's number for methods contained in the specified entity is returned. This class * depends on FileFinder which is used to map source file names to existing files. * * <p>One instance of this class should be used for the same set of source files - an * object of this class can cache computed results.</p> * * @author Grzegorz Lukasik */ public class ComplexityCalculator { private static final Logger logger = Logger.getLogger(ComplexityCalculator.class); public static final Complexity ZERO_COMPLEXITY = new Complexity(); // Finder used to map source file names to existing files private final FileFinder finder; // Contains pairs (String sourceFileName, Complexity complexity) private Map sourceFileCNNCache = new HashMap(); // Contains pairs (String packageName, Complexity complexity) private Map packageCNNCache = new HashMap(); /** * Creates new calculator. Passed {@link FileFinder} will be used to * map source file names to existing files when needed. * * @param finder {@link FileFinder} that allows to find source files * @throws NullPointerException if finder is null */ public ComplexityCalculator( FileFinder finder) { if( finder==null) throw new NullPointerException(); this.finder = finder; } /** * Calculates the code complexity number for an input stream. * "CCN" stands for "code complexity number." This is * sometimes referred to as McCabe's number. This method * calculates the average cyclomatic code complexity of all * methods of all classes in a given directory. * * @param file The input stream for which you want to calculate * the complexity * @return average complexity for the specified input stream */ private Complexity getAccumlatedCCNForSource(String sourceFileName, Source source) { if (source == null) { return ZERO_COMPLEXITY; } + if (!sourceFileName.endsWith(".java")) + { + return ZERO_COMPLEXITY; + } Javancss javancss = new Javancss(source.getInputStream()); if (javancss.getLastErrorMessage() != null) { //there is an error while parsing the java file. log it logger.warn("JavaNCSS got an error while parsing the java " + source.getOriginDesc() + "\n" + javancss.getLastErrorMessage()); } Vector methodMetrics = javancss.getFunctionMetrics(); int classCcn = 0; for( Enumeration method = methodMetrics.elements(); method.hasMoreElements();) { Vector singleMethodMetrics = (Vector)method.nextElement(); classCcn += ((Integer)singleMethodMetrics.elementAt(JavancssConstants.FCT_CCN)).intValue(); } return new Complexity( classCcn, methodMetrics.size()); } /** * Calculates the code complexity number for single source file. * "CCN" stands for "code complexity number." This is * sometimes referred to as McCabe's number. This method * calculates the average cyclomatic code complexity of all * methods of all classes in a given directory. * @param sourceFileName * * @param file The source file for which you want to calculate * the complexity * @return average complexity for the specified source file * @throws IOException */ private Complexity getAccumlatedCCNForSingleFile(String sourceFileName) throws IOException { Source source = finder.getSource(sourceFileName); try { return getAccumlatedCCNForSource(sourceFileName, source); } finally { if (source != null) { source.close(); } } } /** * Computes CCN for all sources contained in the project. * CCN for whole project is an average CCN for source files. * All source files for which CCN cannot be computed are ignored. * * @param projectData project to compute CCN for * @throws NullPointerException if projectData is null * @return CCN for project or 0 if no source files were found */ public double getCCNForProject( ProjectData projectData) { // Sum complexity for all packages Complexity act = new Complexity(); for( Iterator it = projectData.getPackages().iterator(); it.hasNext();) { PackageData packageData = (PackageData)it.next(); act.add( getCCNForPackageInternal( packageData)); } // Return average CCN for source files return act.averageCCN(); } /** * Computes CCN for all sources contained in the specified package. * All source files that cannot be mapped to existing files are ignored. * * @param packageData package to compute CCN for * @throws NullPointerException if <code>packageData</code> is <code>null</code> * @return CCN for the specified package or 0 if no source files were found */ public double getCCNForPackage(PackageData packageData) { return getCCNForPackageInternal(packageData).averageCCN(); } private Complexity getCCNForPackageInternal(PackageData packageData) { // Return CCN if computed earlier Complexity cachedCCN = (Complexity) packageCNNCache.get( packageData.getName()); if( cachedCCN!=null) { return cachedCCN; } // Compute CCN for all source files inside package Complexity act = new Complexity(); for( Iterator it = packageData.getSourceFiles().iterator(); it.hasNext();) { SourceFileData sourceData = (SourceFileData)it.next(); act.add( getCCNForSourceFileNameInternal( sourceData.getName())); } // Cache result and return it packageCNNCache.put( packageData.getName(), act); return act; } /** * Computes CCN for single source file. * * @param sourceFile source file to compute CCN for * @throws NullPointerException if <code>sourceFile</code> is <code>null</code> * @return CCN for the specified source file, 0 if cannot map <code>sourceFile</code> to existing file */ public double getCCNForSourceFile(SourceFileData sourceFile) { return getCCNForSourceFileNameInternal( sourceFile.getName()).averageCCN(); } private Complexity getCCNForSourceFileNameInternal(String sourceFileName) { // Return CCN if computed earlier Complexity cachedCCN = (Complexity) sourceFileCNNCache.get( sourceFileName); if( cachedCCN!=null) { return cachedCCN; } // Compute CCN and cache it for further use Complexity result = ZERO_COMPLEXITY; try { result = getAccumlatedCCNForSingleFile( sourceFileName ); } catch( IOException ex) { logger.info( "Cannot find source file during CCN computation, source=["+sourceFileName+"]"); } sourceFileCNNCache.put( sourceFileName, result); return result; } /** * Computes CCN for source file the specified class belongs to. * * @param classData package to compute CCN for * @return CCN for source file the specified class belongs to * @throws NullPointerException if <code>classData</code> is <code>null</code> */ public double getCCNForClass(ClassData classData) { return getCCNForSourceFileNameInternal( classData.getSourceFileName()).averageCCN(); } /** * Represents complexity of source file, package or project. Stores the number of * methods inside entity and accumlated complexity for these methods. */ private static class Complexity { private double accumlatedCCN; private int methodsNum; public Complexity(double accumlatedCCN, int methodsNum) { this.accumlatedCCN = accumlatedCCN; this.methodsNum = methodsNum; } public Complexity() { this(0,0); } public double averageCCN() { if( methodsNum==0) { return 0; } return accumlatedCCN/methodsNum; } public void add( Complexity second) { accumlatedCCN += second.accumlatedCCN; methodsNum += second.methodsNum; } } }
true
true
private Complexity getAccumlatedCCNForSource(String sourceFileName, Source source) { if (source == null) { return ZERO_COMPLEXITY; } Javancss javancss = new Javancss(source.getInputStream()); if (javancss.getLastErrorMessage() != null) { //there is an error while parsing the java file. log it logger.warn("JavaNCSS got an error while parsing the java " + source.getOriginDesc() + "\n" + javancss.getLastErrorMessage()); } Vector methodMetrics = javancss.getFunctionMetrics(); int classCcn = 0; for( Enumeration method = methodMetrics.elements(); method.hasMoreElements();) { Vector singleMethodMetrics = (Vector)method.nextElement(); classCcn += ((Integer)singleMethodMetrics.elementAt(JavancssConstants.FCT_CCN)).intValue(); } return new Complexity( classCcn, methodMetrics.size()); }
private Complexity getAccumlatedCCNForSource(String sourceFileName, Source source) { if (source == null) { return ZERO_COMPLEXITY; } if (!sourceFileName.endsWith(".java")) { return ZERO_COMPLEXITY; } Javancss javancss = new Javancss(source.getInputStream()); if (javancss.getLastErrorMessage() != null) { //there is an error while parsing the java file. log it logger.warn("JavaNCSS got an error while parsing the java " + source.getOriginDesc() + "\n" + javancss.getLastErrorMessage()); } Vector methodMetrics = javancss.getFunctionMetrics(); int classCcn = 0; for( Enumeration method = methodMetrics.elements(); method.hasMoreElements();) { Vector singleMethodMetrics = (Vector)method.nextElement(); classCcn += ((Integer)singleMethodMetrics.elementAt(JavancssConstants.FCT_CCN)).intValue(); } return new Complexity( classCcn, methodMetrics.size()); }
diff --git a/quadrotor/ControlTerminal/src/javiator/terminal/UDPTransceiver.java b/quadrotor/ControlTerminal/src/javiator/terminal/UDPTransceiver.java index 55566a7..7fc9a06 100644 --- a/quadrotor/ControlTerminal/src/javiator/terminal/UDPTransceiver.java +++ b/quadrotor/ControlTerminal/src/javiator/terminal/UDPTransceiver.java @@ -1,156 +1,156 @@ package javiator.terminal; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetSocketAddress; import java.net.SocketException; import javiator.util.LeanPacket; import javiator.util.Packet; import javiator.util.PacketType; /** * An alternate JControlTransceiver that uses UDP instead of TCP */ public class UDPTransceiver extends Transceiver { private static final boolean DEBUG = false; private DatagramSocket sendSocket, recvSocket; private int listenPort; private InetSocketAddress socketAddress; private boolean haveTraffic; /** * Create a new UDP Transceiver for talking to the JControl * @param parent the ControlTerminal object needed by superclass * @param listenPort the port to listen on for datagrams * @param sendHost the host to which to send datagrams * @param sendPort the port to which to send datagrams */ public UDPTransceiver(ControlTerminal parent, String sendHost, int sendPort) { super(parent); this.listenPort = sendPort; socketAddress = new InetSocketAddress(sendHost, sendPort); } /* (non-Javadoc) * @see javiator.util.Transceiver#connect() */ public void connect() { try { // recvSocket = new DatagramSocket(listenPort); sendSocket = new DatagramSocket(listenPort); haveTraffic = false; setConnected(true); setLinked(true); Packet packet = new Packet(PacketType.COMM_SWITCH_MODE, 0); sendPacket(packet); } catch (SocketException e) { e.printStackTrace(); setConnected(false); setLinked(false); } } /* (non-Javadoc) * @see javiator.util.Transceiver#disconnect() */ public void disconnect() { if (recvSocket != null) { recvSocket.close(); recvSocket = null; } if (sendSocket != null) { sendSocket.close(); sendSocket = null; } setConnected(false); haveTraffic = false; } /* (non-Javadoc) * @see javiator.util.Transceiver#receive() */ public void receive() { while (isConnected() && !isHalt()) { byte[] buffer = new byte[Packet.MAX_SIZE]; DatagramPacket recvPacket = new DatagramPacket(buffer, 0, buffer.length); try { if (!haveTraffic) { - System.err.println("Waiting for messages from JControl"); + System.err.println("Waiting for messages from control application"); } if (DEBUG) { System.err.println("Trying to receive"); } sendSocket.receive(recvPacket); if (!haveTraffic) { - System.err.println("First message received from JControl"); + System.err.println("First message received from control application"); haveTraffic = true; } arrived(); if (!LeanPacket.checksOut(buffer)) { throw new IOException("Corrupt packet received"); } if (DEBUG) { System.err.println("Processing packet: " + LeanPacket.dumpPacket(buffer, 0, buffer.length)); } Packet thePacket = new Packet(buffer[2], buffer[3]); System.arraycopy(buffer,LeanPacket.PAYLOAD_OFFSET, thePacket.payload, 0, buffer[3]); processPacket(thePacket); if (DEBUG) { System.err.println("Processing complete"); } lastPacket = thePacket; } catch (IOException e) { e.printStackTrace(); System.err.println(LeanPacket.dumpPacket(buffer, 0, buffer.length)); disconnect(); if (!isHalt()) { connect(); } } } setHalt(true); } /* (non-Javadoc) * @see javiator.util.Transceiver#sendPacket(javiator.util.Packet) */ public synchronized void sendPacket(Packet packet) { byte[] buffer = new byte[packet.size + LeanPacket.OVERHEAD]; LeanPacket.fillHeader(buffer, packet.type, packet.size); if (packet.payload != null) { System.arraycopy(packet.payload,0, buffer,LeanPacket.PAYLOAD_OFFSET, packet.size); } LeanPacket.addChecksum(buffer); if (DEBUG) { System.err.println("Sending packet: " + LeanPacket.dumpPacket(buffer, 0, buffer.length)); } try { DatagramPacket sendPacket = new DatagramPacket(buffer, 0, buffer.length, socketAddress); sendSocket.send(sendPacket); } catch (IOException e) { e.printStackTrace(); disconnect(); if (!isHalt()) { connect(); } } } }
false
true
public void receive() { while (isConnected() && !isHalt()) { byte[] buffer = new byte[Packet.MAX_SIZE]; DatagramPacket recvPacket = new DatagramPacket(buffer, 0, buffer.length); try { if (!haveTraffic) { System.err.println("Waiting for messages from JControl"); } if (DEBUG) { System.err.println("Trying to receive"); } sendSocket.receive(recvPacket); if (!haveTraffic) { System.err.println("First message received from JControl"); haveTraffic = true; } arrived(); if (!LeanPacket.checksOut(buffer)) { throw new IOException("Corrupt packet received"); } if (DEBUG) { System.err.println("Processing packet: " + LeanPacket.dumpPacket(buffer, 0, buffer.length)); } Packet thePacket = new Packet(buffer[2], buffer[3]); System.arraycopy(buffer,LeanPacket.PAYLOAD_OFFSET, thePacket.payload, 0, buffer[3]); processPacket(thePacket); if (DEBUG) { System.err.println("Processing complete"); } lastPacket = thePacket; } catch (IOException e) { e.printStackTrace(); System.err.println(LeanPacket.dumpPacket(buffer, 0, buffer.length)); disconnect(); if (!isHalt()) { connect(); } } } setHalt(true); }
public void receive() { while (isConnected() && !isHalt()) { byte[] buffer = new byte[Packet.MAX_SIZE]; DatagramPacket recvPacket = new DatagramPacket(buffer, 0, buffer.length); try { if (!haveTraffic) { System.err.println("Waiting for messages from control application"); } if (DEBUG) { System.err.println("Trying to receive"); } sendSocket.receive(recvPacket); if (!haveTraffic) { System.err.println("First message received from control application"); haveTraffic = true; } arrived(); if (!LeanPacket.checksOut(buffer)) { throw new IOException("Corrupt packet received"); } if (DEBUG) { System.err.println("Processing packet: " + LeanPacket.dumpPacket(buffer, 0, buffer.length)); } Packet thePacket = new Packet(buffer[2], buffer[3]); System.arraycopy(buffer,LeanPacket.PAYLOAD_OFFSET, thePacket.payload, 0, buffer[3]); processPacket(thePacket); if (DEBUG) { System.err.println("Processing complete"); } lastPacket = thePacket; } catch (IOException e) { e.printStackTrace(); System.err.println(LeanPacket.dumpPacket(buffer, 0, buffer.length)); disconnect(); if (!isHalt()) { connect(); } } } setHalt(true); }
diff --git a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/actions/ManageWatchpointAction.java b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/actions/ManageWatchpointAction.java index 8f0f9ff63..77ace001a 100644 --- a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/actions/ManageWatchpointAction.java +++ b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/actions/ManageWatchpointAction.java @@ -1,278 +1,278 @@ package org.eclipse.jdt.internal.debug.ui.actions; /* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.debug.core.DebugException; import org.eclipse.debug.core.DebugPlugin; import org.eclipse.debug.core.IBreakpointManager; import org.eclipse.debug.core.ILaunch; import org.eclipse.debug.core.ILaunchConfiguration; import org.eclipse.debug.core.model.IBreakpoint; import org.eclipse.jdt.core.IField; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.ISourceRange; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.search.IJavaSearchConstants; import org.eclipse.jdt.core.search.IJavaSearchScope; import org.eclipse.jdt.core.search.ITypeNameRequestor; import org.eclipse.jdt.core.search.SearchEngine; import org.eclipse.jdt.debug.core.IJavaBreakpoint; import org.eclipse.jdt.debug.core.IJavaFieldVariable; import org.eclipse.jdt.debug.core.IJavaWatchpoint; import org.eclipse.jdt.debug.core.JDIDebugModel; import org.eclipse.jdt.internal.corext.util.TypeInfo; import org.eclipse.jdt.internal.corext.util.TypeInfoRequestor; import org.eclipse.jdt.internal.debug.ui.BreakpointUtils; import org.eclipse.jdt.internal.debug.ui.JDIDebugUIPlugin; import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants; import org.eclipse.jface.action.IAction; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.ui.IWorkbenchPart; public class ManageWatchpointAction extends ManageBreakpointAction { /** * Cache of fields that have already been searched for and found * key: The variable to be search on (IJavaVariable) * value: The field that was found (IField) */ private Map fFoundFields= new HashMap(); public ManageWatchpointAction() { super(); fAddText= ActionMessages.getString("ManageWatchpointAction.Add_&Watchpoint_1"); //$NON-NLS-1$ fAddDescription= ActionMessages.getString("ManageWatchpointAction.Add_a_watchpoint_2"); //$NON-NLS-1$ fRemoveText= ActionMessages.getString("ManageWatchpointAction.Remove_&Watchpoint_4"); //$NON-NLS-1$ fRemoveDescription= ActionMessages.getString("ManageWatchpointAction.Remove_a_field_watchpoint_5"); //$NON-NLS-1$ } /** * @see IObjectActionDelegate#setActivePart(IAction, IWorkbenchPart) */ public void setActivePart(IAction action, IWorkbenchPart part) { setAction(action); } /** * @see IActionDelegate#run(IAction) */ public void run(IAction action) { if (getBreakpoint() == null) { try { IMember element= getElement(); IType type = element.getDeclaringType(); int start = -1; int end = -1; ISourceRange range = element.getNameRange(); if (range != null) { start = range.getOffset(); end = start + range.getLength(); } Map attributes = new HashMap(10); BreakpointUtils.addJavaBreakpointAttributes(attributes, element); setBreakpoint(JDIDebugModel.createWatchpoint(BreakpointUtils.getBreakpointResource(type),type.getFullyQualifiedName(), element.getElementName(), -1, start, end, 0, true, attributes)); } catch (JavaModelException exception) { MessageDialog.openError(JDIDebugUIPlugin.getActiveWorkbenchShell(), ActionMessages.getString("ManageWatchpointAction.Problems_adding_watchpoint_7"), "The selected field is not visible in the currently selected debug context. A stack frame or suspended thread which contains the declaring type of this field must be selected."); //$NON-NLS-1$ } catch (CoreException x) { MessageDialog.openError(JDIDebugUIPlugin.getActiveWorkbenchShell(), ActionMessages.getString("ManageWatchpointAction.Problems_adding_watchpoint_7"), x.getMessage()); //$NON-NLS-1$ } } else { // remove breakpoint try { IBreakpointManager breakpointManager= DebugPlugin.getDefault().getBreakpointManager(); breakpointManager.removeBreakpoint(getBreakpoint(), true); } catch (CoreException x) { MessageDialog.openError(JDIDebugUIPlugin.getActiveWorkbenchShell(), ActionMessages.getString("ManageWatchpointAction.Problems_removing_watchpoint_8"), x.getMessage()); //$NON-NLS-1$ } } update(); } protected IJavaBreakpoint getBreakpoint(IMember selectedField) { IBreakpointManager breakpointManager= DebugPlugin.getDefault().getBreakpointManager(); IBreakpoint[] breakpoints= breakpointManager.getBreakpoints(JDIDebugModel.getPluginIdentifier()); for (int i= 0; i < breakpoints.length; i++) { IBreakpoint breakpoint= breakpoints[i]; if (breakpoint instanceof IJavaWatchpoint) { try { if (equalFields(selectedField, (IJavaWatchpoint)breakpoint)) return (IJavaBreakpoint)breakpoint; } catch (CoreException e) { } } } return null; } /** * Compare two fields. The default <code>equals()</code> * method for <code>IField</code> doesn't give the comparison desired. */ private boolean equalFields(IMember breakpointField, IJavaWatchpoint watchpoint) throws CoreException { return (breakpointField.getElementName().equals(watchpoint.getFieldName()) && breakpointField.getDeclaringType().getFullyQualifiedName().equals(watchpoint.getTypeName())); } protected IMember getElement(ISelection s) { if (s instanceof IStructuredSelection) { IStructuredSelection ss= (IStructuredSelection) s; if (ss.size() == 1) { Object o= ss.getFirstElement(); if (o instanceof IField) { return (IField) o; } else if (o instanceof IJavaFieldVariable) { return getField((IJavaFieldVariable) o); } } } return null; } /** * Return the associated IField (Java model) for the given * IJavaFieldVariable (JDI model) */ public IField getField(IJavaFieldVariable variable) { IField field= (IField)fFoundFields.get(variable); if (field != null) { return field; } List types= searchForDeclaringType(variable); Iterator iter= types.iterator(); while (iter.hasNext()) { try { field= ((IType)iter.next()).getField(variable.getName()); } catch (DebugException exception) { } if (field != null) { // Return the first java model field that is found which // matches the JDI model field. fFoundFields.put(variable, field); return field; } } return null; } /** * Returns a list of matching types (IType - Java model) that correspond to the * declaring type (ReferenceType - JDI model) of the given variable. */ protected List searchForDeclaringType(IJavaFieldVariable variable) { List types= new ArrayList(); ILaunch launch = variable.getDebugTarget().getLaunch(); if (launch == null) { return types; } ILaunchConfiguration configuration= launch.getLaunchConfiguration(); IJavaProject javaProject = null; IWorkspace workspace= ResourcesPlugin.getWorkspace(); if (configuration == null) { // Old-style launcher support Object element = launch.getElement(); if (element instanceof IJavaElement) { javaProject = ((IJavaElement)element).getJavaProject(); } } else { // Launch configuration support try { String projectName= configuration.getAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, ""); //$NON-NLS-1$ - if (projectName != null) { + if (projectName.length() != 0) { javaProject= JavaCore.create(workspace.getRoot().getProject(projectName)); } } catch (CoreException e) { } } if (javaProject == null) { return types; } SearchEngine engine= new SearchEngine(); IJavaSearchScope scope= engine.createJavaSearchScope(new IJavaProject[] {javaProject}, true); String declaringType= null; try { declaringType= variable.getDeclaringType().getName(); } catch (DebugException exception) { return types; } ArrayList typeRefsFound= new ArrayList(3); ITypeNameRequestor requestor= new TypeInfoRequestor(typeRefsFound); try { engine.searchAllTypeNames(workspace, getPackage(declaringType), getTypeName(declaringType), IJavaSearchConstants.EXACT_MATCH, true, IJavaSearchConstants.CLASS, scope, requestor, IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, null); } catch (JavaModelException e) { return types; } Iterator iter= typeRefsFound.iterator(); TypeInfo typeInfo= null; while (iter.hasNext()) { typeInfo= (TypeInfo)iter.next(); try { types.add(typeInfo.resolveType(scope)); } catch (JavaModelException jme) { } } return types; } /** * Returns the package name of the given fully qualified type name. * The package name is assumed to be the dot-separated prefix of the * type name. */ protected char[] getPackage(String fullyQualifiedName) { int index= fullyQualifiedName.lastIndexOf('.'); if (index == -1) { return new char[0]; } return fullyQualifiedName.substring(0, index).toCharArray(); } /** * Returns a simple type name from the given fully qualified type name. * The type name is assumed to be the last contiguous segment of the * fullyQualifiedName not containing a '.' or '$' */ protected char[] getTypeName(String fullyQualifiedName) { int index= fullyQualifiedName.lastIndexOf('.'); String typeName= fullyQualifiedName.substring(index + 1); int lastInnerClass= typeName.lastIndexOf('$'); if (lastInnerClass != -1) { typeName= typeName.substring(lastInnerClass + 1); } return typeName.toCharArray(); } }
true
true
protected List searchForDeclaringType(IJavaFieldVariable variable) { List types= new ArrayList(); ILaunch launch = variable.getDebugTarget().getLaunch(); if (launch == null) { return types; } ILaunchConfiguration configuration= launch.getLaunchConfiguration(); IJavaProject javaProject = null; IWorkspace workspace= ResourcesPlugin.getWorkspace(); if (configuration == null) { // Old-style launcher support Object element = launch.getElement(); if (element instanceof IJavaElement) { javaProject = ((IJavaElement)element).getJavaProject(); } } else { // Launch configuration support try { String projectName= configuration.getAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, ""); //$NON-NLS-1$ if (projectName != null) { javaProject= JavaCore.create(workspace.getRoot().getProject(projectName)); } } catch (CoreException e) { } } if (javaProject == null) { return types; } SearchEngine engine= new SearchEngine(); IJavaSearchScope scope= engine.createJavaSearchScope(new IJavaProject[] {javaProject}, true); String declaringType= null; try { declaringType= variable.getDeclaringType().getName(); } catch (DebugException exception) { return types; } ArrayList typeRefsFound= new ArrayList(3); ITypeNameRequestor requestor= new TypeInfoRequestor(typeRefsFound); try { engine.searchAllTypeNames(workspace, getPackage(declaringType), getTypeName(declaringType), IJavaSearchConstants.EXACT_MATCH, true, IJavaSearchConstants.CLASS, scope, requestor, IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, null); } catch (JavaModelException e) { return types; } Iterator iter= typeRefsFound.iterator(); TypeInfo typeInfo= null; while (iter.hasNext()) { typeInfo= (TypeInfo)iter.next(); try { types.add(typeInfo.resolveType(scope)); } catch (JavaModelException jme) { } } return types; }
protected List searchForDeclaringType(IJavaFieldVariable variable) { List types= new ArrayList(); ILaunch launch = variable.getDebugTarget().getLaunch(); if (launch == null) { return types; } ILaunchConfiguration configuration= launch.getLaunchConfiguration(); IJavaProject javaProject = null; IWorkspace workspace= ResourcesPlugin.getWorkspace(); if (configuration == null) { // Old-style launcher support Object element = launch.getElement(); if (element instanceof IJavaElement) { javaProject = ((IJavaElement)element).getJavaProject(); } } else { // Launch configuration support try { String projectName= configuration.getAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, ""); //$NON-NLS-1$ if (projectName.length() != 0) { javaProject= JavaCore.create(workspace.getRoot().getProject(projectName)); } } catch (CoreException e) { } } if (javaProject == null) { return types; } SearchEngine engine= new SearchEngine(); IJavaSearchScope scope= engine.createJavaSearchScope(new IJavaProject[] {javaProject}, true); String declaringType= null; try { declaringType= variable.getDeclaringType().getName(); } catch (DebugException exception) { return types; } ArrayList typeRefsFound= new ArrayList(3); ITypeNameRequestor requestor= new TypeInfoRequestor(typeRefsFound); try { engine.searchAllTypeNames(workspace, getPackage(declaringType), getTypeName(declaringType), IJavaSearchConstants.EXACT_MATCH, true, IJavaSearchConstants.CLASS, scope, requestor, IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, null); } catch (JavaModelException e) { return types; } Iterator iter= typeRefsFound.iterator(); TypeInfo typeInfo= null; while (iter.hasNext()) { typeInfo= (TypeInfo)iter.next(); try { types.add(typeInfo.resolveType(scope)); } catch (JavaModelException jme) { } } return types; }
diff --git a/sirocco-cimi-command-line-tools/src/main/java/org/ow2/sirocco/apis/rest/cimi/tools/MachineCreateCommand.java b/sirocco-cimi-command-line-tools/src/main/java/org/ow2/sirocco/apis/rest/cimi/tools/MachineCreateCommand.java index 61eab5e..00fc873 100644 --- a/sirocco-cimi-command-line-tools/src/main/java/org/ow2/sirocco/apis/rest/cimi/tools/MachineCreateCommand.java +++ b/sirocco-cimi-command-line-tools/src/main/java/org/ow2/sirocco/apis/rest/cimi/tools/MachineCreateCommand.java @@ -1,106 +1,106 @@ /** * * SIROCCO * Copyright (C) 2011 France Telecom * Contact: [email protected] * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * * $Id$ * */ package org.ow2.sirocco.apis.rest.cimi.tools; import java.util.List; import org.ow2.sirocco.apis.rest.cimi.sdk.CimiClient; import org.ow2.sirocco.apis.rest.cimi.sdk.CimiException; import org.ow2.sirocco.apis.rest.cimi.sdk.CreateResult; import org.ow2.sirocco.apis.rest.cimi.sdk.Machine; import org.ow2.sirocco.apis.rest.cimi.sdk.MachineCreate; import org.ow2.sirocco.apis.rest.cimi.sdk.MachineTemplate; import com.beust.jcommander.Parameter; import com.beust.jcommander.Parameters; @Parameters(commandDescription = "create machine") public class MachineCreateCommand implements Command { @Parameter(names = "-template", description = "id of the template", required = false) private String templateId; @Parameter(names = "-config", description = "id of the config", required = false) private String configId; @Parameter(names = "-image", description = "id of the image", required = false) private String imageId; @Parameter(names = "-credential", description = "id of the credential", required = false) private String credId; @Parameter(names = "-userData", description = "user data", required = false) private String userData; @Parameter(names = "-name", description = "name of the template", required = false) private String name; @Parameter(names = "-description", description = "description of the template", required = false) private String description; @Parameter(names = "-properties", variableArity = true, description = "key value pairs", required = false) private List<String> properties; @Override public String getName() { return "machine-create"; } @Override public void execute(final CimiClient cimiClient) throws CimiException { - if (this.templateId == null && (this.configId == null && this.imageId == null)) { + if (this.templateId == null && (this.configId == null || this.imageId == null)) { throw new CimiException("You need to specify either a template id or both a config id and an image id"); } MachineCreate machineCreate = new MachineCreate(); MachineTemplate machineTemplate; if (this.templateId != null) { machineCreate.setMachineTemplateRef(this.templateId); machineTemplate = machineCreate.getMachineTemplate(); } else { machineTemplate = new MachineTemplate(); machineTemplate.setMachineConfigRef(this.configId); machineTemplate.setMachineImageRef(this.imageId); if (this.credId != null) { machineTemplate.setCredentialRef(this.credId); } } machineTemplate.setUserData(this.userData); machineCreate.setMachineTemplate(machineTemplate); machineCreate.setName(this.name); machineCreate.setDescription(this.description); if (this.properties != null) { for (int i = 0; i < this.properties.size() / 2; i++) { machineCreate.addProperty(this.properties.get(i * 2), this.properties.get(i * 2 + 1)); } } CreateResult<Machine> result = Machine.createMachine(cimiClient, machineCreate); if (result.getJob() != null) { System.out.println("Machine " + result.getJob().getTargetResourceRef() + " being created"); JobListCommand.printJob(result.getJob()); } else { MachineShowCommand.printMachine(result.getResource()); } } }
true
true
public void execute(final CimiClient cimiClient) throws CimiException { if (this.templateId == null && (this.configId == null && this.imageId == null)) { throw new CimiException("You need to specify either a template id or both a config id and an image id"); } MachineCreate machineCreate = new MachineCreate(); MachineTemplate machineTemplate; if (this.templateId != null) { machineCreate.setMachineTemplateRef(this.templateId); machineTemplate = machineCreate.getMachineTemplate(); } else { machineTemplate = new MachineTemplate(); machineTemplate.setMachineConfigRef(this.configId); machineTemplate.setMachineImageRef(this.imageId); if (this.credId != null) { machineTemplate.setCredentialRef(this.credId); } } machineTemplate.setUserData(this.userData); machineCreate.setMachineTemplate(machineTemplate); machineCreate.setName(this.name); machineCreate.setDescription(this.description); if (this.properties != null) { for (int i = 0; i < this.properties.size() / 2; i++) { machineCreate.addProperty(this.properties.get(i * 2), this.properties.get(i * 2 + 1)); } } CreateResult<Machine> result = Machine.createMachine(cimiClient, machineCreate); if (result.getJob() != null) { System.out.println("Machine " + result.getJob().getTargetResourceRef() + " being created"); JobListCommand.printJob(result.getJob()); } else { MachineShowCommand.printMachine(result.getResource()); } }
public void execute(final CimiClient cimiClient) throws CimiException { if (this.templateId == null && (this.configId == null || this.imageId == null)) { throw new CimiException("You need to specify either a template id or both a config id and an image id"); } MachineCreate machineCreate = new MachineCreate(); MachineTemplate machineTemplate; if (this.templateId != null) { machineCreate.setMachineTemplateRef(this.templateId); machineTemplate = machineCreate.getMachineTemplate(); } else { machineTemplate = new MachineTemplate(); machineTemplate.setMachineConfigRef(this.configId); machineTemplate.setMachineImageRef(this.imageId); if (this.credId != null) { machineTemplate.setCredentialRef(this.credId); } } machineTemplate.setUserData(this.userData); machineCreate.setMachineTemplate(machineTemplate); machineCreate.setName(this.name); machineCreate.setDescription(this.description); if (this.properties != null) { for (int i = 0; i < this.properties.size() / 2; i++) { machineCreate.addProperty(this.properties.get(i * 2), this.properties.get(i * 2 + 1)); } } CreateResult<Machine> result = Machine.createMachine(cimiClient, machineCreate); if (result.getJob() != null) { System.out.println("Machine " + result.getJob().getTargetResourceRef() + " being created"); JobListCommand.printJob(result.getJob()); } else { MachineShowCommand.printMachine(result.getResource()); } }
diff --git a/src/il/technion/ewolf/server/handlers/JsonHandler.java b/src/il/technion/ewolf/server/handlers/JsonHandler.java index db7b773..79e2c9f 100644 --- a/src/il/technion/ewolf/server/handlers/JsonHandler.java +++ b/src/il/technion/ewolf/server/handlers/JsonHandler.java @@ -1,103 +1,106 @@ package il.technion.ewolf.server.handlers; import static il.technion.ewolf.server.EWolfResponse.RES_SUCCESS; import il.technion.ewolf.server.EWolfResponse; import il.technion.ewolf.server.HttpSessionStore; import il.technion.ewolf.server.jsonDataHandlers.JsonDataHandler; import java.io.IOException; import java.text.DateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.apache.http.Header; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpRequestHandler; import org.apache.http.util.EntityUtils; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.inject.Inject; public class JsonHandler implements HttpRequestHandler { private Map<String,JsonDataHandler> handlers = new HashMap<String,JsonDataHandler>(); HttpSessionStore sessionStore; @Inject JsonHandler(HttpSessionStore sessionStore) { this.sessionStore = sessionStore; } public JsonHandler addHandler(String key, JsonDataHandler handler) { handlers.put(key, handler); return this; } @Override public void handle(HttpRequest req, HttpResponse res, HttpContext context) throws HttpException, IOException { boolean authorized = (Boolean) context.getAttribute("authorized"); String jsonReqAsString = EntityUtils.toString(((HttpEntityEnclosingRequest)req).getEntity()); JsonParser parser = new JsonParser(); JsonObject jsonReq = parser.parse(jsonReqAsString).getAsJsonObject(); JsonObject jsonRes = new JsonObject(); Gson gson = new GsonBuilder().serializeNulls().disableHtmlEscaping().create(); Set<Entry<String, JsonElement>> jsonReqAsSet = jsonReq.entrySet(); for (Entry<String, JsonElement> obj : jsonReqAsSet) { String key = obj.getKey(); if (!authorized) { if (!key.equals("login") && !key.equals("createAccount")) { res.setStatusCode(HttpStatus.SC_UNAUTHORIZED); return; } } if (key.equals("logout")) { DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.LONG); Header[] headers = req.getHeaders("Cookie"); for (Header h : headers) { String cookie = h.getValue(); - sessionStore.deleteSession(cookie); - res.setHeader("Set-Cookie", ";Expires=" + + String content = cookie.substring("session=".length()); +// String[] nameContent = cookie.split("="); +// String content = nameContent[1]; + sessionStore.deleteSession(content); + res.setHeader("Set-Cookie", "session=;Expires=" + dateFormat.format(new Date())); } res.setStatusCode(HttpStatus.SC_SEE_OTHER); res.setHeader("Location", "/"); return; } JsonDataHandler handler = handlers.get(key); if (handler != null) { EWolfResponse handlerRes = handler.handleData(obj.getValue()); jsonRes.add(key, gson.toJsonTree(handlerRes)); if (handlerRes.getResult().equals(RES_SUCCESS) && !authorized) { String cookie = sessionStore.createSession(); res.addHeader("Set-Cookie", "session=" + cookie); } } else { System.out.println("No handlers are registered to handle request " + "with keyword \"" + key + "\""); jsonRes.addProperty("result", "unavailable request"); } } String json = gson.toJson(jsonRes); res.setEntity(new StringEntity(json, ContentType.APPLICATION_JSON)); } }
true
true
public void handle(HttpRequest req, HttpResponse res, HttpContext context) throws HttpException, IOException { boolean authorized = (Boolean) context.getAttribute("authorized"); String jsonReqAsString = EntityUtils.toString(((HttpEntityEnclosingRequest)req).getEntity()); JsonParser parser = new JsonParser(); JsonObject jsonReq = parser.parse(jsonReqAsString).getAsJsonObject(); JsonObject jsonRes = new JsonObject(); Gson gson = new GsonBuilder().serializeNulls().disableHtmlEscaping().create(); Set<Entry<String, JsonElement>> jsonReqAsSet = jsonReq.entrySet(); for (Entry<String, JsonElement> obj : jsonReqAsSet) { String key = obj.getKey(); if (!authorized) { if (!key.equals("login") && !key.equals("createAccount")) { res.setStatusCode(HttpStatus.SC_UNAUTHORIZED); return; } } if (key.equals("logout")) { DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.LONG); Header[] headers = req.getHeaders("Cookie"); for (Header h : headers) { String cookie = h.getValue(); sessionStore.deleteSession(cookie); res.setHeader("Set-Cookie", ";Expires=" + dateFormat.format(new Date())); } res.setStatusCode(HttpStatus.SC_SEE_OTHER); res.setHeader("Location", "/"); return; } JsonDataHandler handler = handlers.get(key); if (handler != null) { EWolfResponse handlerRes = handler.handleData(obj.getValue()); jsonRes.add(key, gson.toJsonTree(handlerRes)); if (handlerRes.getResult().equals(RES_SUCCESS) && !authorized) { String cookie = sessionStore.createSession(); res.addHeader("Set-Cookie", "session=" + cookie); } } else { System.out.println("No handlers are registered to handle request " + "with keyword \"" + key + "\""); jsonRes.addProperty("result", "unavailable request"); } } String json = gson.toJson(jsonRes); res.setEntity(new StringEntity(json, ContentType.APPLICATION_JSON)); }
public void handle(HttpRequest req, HttpResponse res, HttpContext context) throws HttpException, IOException { boolean authorized = (Boolean) context.getAttribute("authorized"); String jsonReqAsString = EntityUtils.toString(((HttpEntityEnclosingRequest)req).getEntity()); JsonParser parser = new JsonParser(); JsonObject jsonReq = parser.parse(jsonReqAsString).getAsJsonObject(); JsonObject jsonRes = new JsonObject(); Gson gson = new GsonBuilder().serializeNulls().disableHtmlEscaping().create(); Set<Entry<String, JsonElement>> jsonReqAsSet = jsonReq.entrySet(); for (Entry<String, JsonElement> obj : jsonReqAsSet) { String key = obj.getKey(); if (!authorized) { if (!key.equals("login") && !key.equals("createAccount")) { res.setStatusCode(HttpStatus.SC_UNAUTHORIZED); return; } } if (key.equals("logout")) { DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.LONG); Header[] headers = req.getHeaders("Cookie"); for (Header h : headers) { String cookie = h.getValue(); String content = cookie.substring("session=".length()); // String[] nameContent = cookie.split("="); // String content = nameContent[1]; sessionStore.deleteSession(content); res.setHeader("Set-Cookie", "session=;Expires=" + dateFormat.format(new Date())); } res.setStatusCode(HttpStatus.SC_SEE_OTHER); res.setHeader("Location", "/"); return; } JsonDataHandler handler = handlers.get(key); if (handler != null) { EWolfResponse handlerRes = handler.handleData(obj.getValue()); jsonRes.add(key, gson.toJsonTree(handlerRes)); if (handlerRes.getResult().equals(RES_SUCCESS) && !authorized) { String cookie = sessionStore.createSession(); res.addHeader("Set-Cookie", "session=" + cookie); } } else { System.out.println("No handlers are registered to handle request " + "with keyword \"" + key + "\""); jsonRes.addProperty("result", "unavailable request"); } } String json = gson.toJson(jsonRes); res.setEntity(new StringEntity(json, ContentType.APPLICATION_JSON)); }
diff --git a/IndexWriter.java b/IndexWriter.java index aec413a..a75b7aa 100644 --- a/IndexWriter.java +++ b/IndexWriter.java @@ -1,469 +1,469 @@ /* This code is part of Freenet. It is distributed under the GNU General * Public License, version 2 (or at your option any later version). See * http://www.gnu.org/ for further details of the GPL. */ package plugins.XMLSpider; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.security.NoSuchAlgorithmException; import java.util.Date; import java.util.HashSet; import java.util.Set; import java.util.Vector; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.DOMImplementation; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Text; import plugins.XMLSpider.db.Config; import plugins.XMLSpider.db.Page; import plugins.XMLSpider.db.PerstRoot; import plugins.XMLSpider.db.Term; import plugins.XMLSpider.db.TermPosition; import plugins.XMLSpider.org.garret.perst.IterableIterator; import plugins.XMLSpider.org.garret.perst.Storage; import plugins.XMLSpider.org.garret.perst.StorageFactory; import freenet.support.Logger; import freenet.support.io.Closer; /** * Write index to disk file */ public class IndexWriter { private static final String[] HEX = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" }; //- Writing Index public long tProducedIndex; private Vector<String> indices; private int match; private long time_taken; private boolean logMINOR = Logger.shouldLog(Logger.MINOR, this); IndexWriter() { } public synchronized void makeIndex(PerstRoot perstRoot) throws Exception { logMINOR = Logger.shouldLog(Logger.MINOR, this); try { time_taken = System.currentTimeMillis(); Config config = perstRoot.getConfig(); File indexDir = new File(config.getIndexDir()); if (!indexDir.exists() && !indexDir.isDirectory() && !indexDir.mkdirs()) { Logger.error(this, "Cannot create index directory: " + indexDir); return; } makeSubIndices(perstRoot); makeMainIndex(config); time_taken = System.currentTimeMillis() - time_taken; if (logMINOR) Logger.minor(this, "Spider: indexes regenerated - tProducedIndex=" + (System.currentTimeMillis() - tProducedIndex) + "ms ago time taken=" + time_taken + "ms"); tProducedIndex = System.currentTimeMillis(); } finally { } } /** * generates the main index file that can be used by librarian for searching in the list of * subindices * * @param void * @author swati * @throws IOException * @throws NoSuchAlgorithmException */ private void makeMainIndex(Config config) throws IOException, NoSuchAlgorithmException { // Produce the main index file. if (logMINOR) Logger.minor(this, "Producing top index..."); //the main index file File outputFile = new File(config.getIndexDir() + "index.xml"); // Use a stream so we can explicitly close - minimise number of filehandles used. BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(outputFile)); StreamResult resultStream; resultStream = new StreamResult(fos); try { /* Initialize xml builder */ Document xmlDoc = null; DocumentBuilderFactory xmlFactory = null; DocumentBuilder xmlBuilder = null; DOMImplementation impl = null; Element rootElement = null; xmlFactory = DocumentBuilderFactory.newInstance(); try { xmlBuilder = xmlFactory.newDocumentBuilder(); } catch (javax.xml.parsers.ParserConfigurationException e) { Logger.error(this, "Spider: Error while initializing XML generator: " + e.toString(), e); return; } impl = xmlBuilder.getDOMImplementation(); /* Starting to generate index */ xmlDoc = impl.createDocument(null, "main_index", null); rootElement = xmlDoc.getDocumentElement(); /* Adding header to the index */ Element headerElement = xmlDoc.createElement("header"); /* -> title */ Element subHeaderElement = xmlDoc.createElement("title"); Text subHeaderText = xmlDoc.createTextNode(config.getIndexTitle()); subHeaderElement.appendChild(subHeaderText); headerElement.appendChild(subHeaderElement); /* -> owner */ subHeaderElement = xmlDoc.createElement("owner"); subHeaderText = xmlDoc.createTextNode(config.getIndexOwner()); subHeaderElement.appendChild(subHeaderText); headerElement.appendChild(subHeaderElement); /* -> owner email */ if (config.getIndexOwnerEmail() != null) { subHeaderElement = xmlDoc.createElement("email"); subHeaderText = xmlDoc.createTextNode(config.getIndexOwnerEmail()); subHeaderElement.appendChild(subHeaderText); headerElement.appendChild(subHeaderElement); } /* * the max number of digits in md5 to be used for matching with the search query is * stored in the xml */ Element prefixElement = xmlDoc.createElement("prefix"); /* Adding word index */ Element keywordsElement = xmlDoc.createElement("keywords"); for (int i = 0; i < indices.size(); i++) { Element subIndexElement = xmlDoc.createElement("subIndex"); subIndexElement.setAttribute("key", indices.elementAt(i)); //the subindex element key will contain the bits used for matching in that subindex keywordsElement.appendChild(subIndexElement); } prefixElement.setAttribute("value", match + ""); rootElement.appendChild(prefixElement); rootElement.appendChild(headerElement); rootElement.appendChild(keywordsElement); /* Serialization */ DOMSource domSource = new DOMSource(xmlDoc); TransformerFactory transformFactory = TransformerFactory.newInstance(); Transformer serializer; try { serializer = transformFactory.newTransformer(); } catch (javax.xml.transform.TransformerConfigurationException e) { Logger.error(this, "Spider: Error while serializing XML (transformFactory.newTransformer()): " + e.toString(), e); return; } serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); /* final step */ try { serializer.transform(domSource, resultStream); } catch (javax.xml.transform.TransformerException e) { Logger.error(this, "Spider: Error while serializing XML (transform()): " + e.toString(), e); return; } } finally { fos.close(); } //The main xml file is generated //As each word is generated enter it into the respective subindex //The parsing will start and nodes will be added as needed } /** * Generates the subindices. Each index has less than {@code MAX_ENTRIES} words. The original * treemap is split into several sublists indexed by the common substring of the hash code of * the words * * @throws Exception */ private void makeSubIndices(PerstRoot perstRoot) throws Exception { Logger.normal(this, "Generating index..."); indices = new Vector<String>(); match = 1; for (String hex : HEX) generateSubIndex(perstRoot, hex); } private void generateSubIndex(PerstRoot perstRoot, String prefix) throws Exception { if (logMINOR) Logger.minor(this, "Generating subindex for (" + prefix + ")"); if (prefix.length() > match) match = prefix.length(); if (generateXML(perstRoot, prefix)) return; if (logMINOR) Logger.minor(this, "Too big subindex for (" + prefix + ")"); for (String hex : HEX) generateSubIndex(perstRoot, prefix + hex); } /** * generates the xml index with the given list of words with prefix number of matching bits in * md5 * * @param prefix * prefix string * @return successful * @throws IOException */ private boolean generateXML(PerstRoot perstRoot, String prefix) throws IOException { final Config config = perstRoot.getConfig(); final long MAX_SIZE = config.getIndexSubindexMaxSize(); final int MAX_ENTRIES = config.getIndexMaxEntries(); File outputFile = new File(config.getIndexDir() + "index_" + prefix + ".xml"); BufferedOutputStream fos = null; int count = 0; int estimateSize = 0; try { DocumentBuilderFactory xmlFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder xmlBuilder; try { xmlBuilder = xmlFactory.newDocumentBuilder(); } catch (javax.xml.parsers.ParserConfigurationException e) { throw new RuntimeException("Spider: Error while initializing XML generator", e); } DOMImplementation impl = xmlBuilder.getDOMImplementation(); /* Starting to generate index */ Document xmlDoc = impl.createDocument(null, "sub_index", null); Element rootElement = xmlDoc.getDocumentElement(); if (config.isDebug()) { - xmlDoc.createAttributeNS("urn:freenet:xmlspider:debug", "debug"); rootElement.appendChild(xmlDoc.createComment(new Date().toGMTString())); } /* Adding header to the index */ Element headerElement = xmlDoc.createElement("header"); /* -> title */ Element subHeaderElement = xmlDoc.createElement("title"); Text subHeaderText = xmlDoc.createTextNode(config.getIndexTitle()); subHeaderElement.appendChild(subHeaderText); headerElement.appendChild(subHeaderElement); /* List of files referenced in this subindex */ Element filesElement = xmlDoc.createElement("files"); /* filesElement != fileElement */ Set<Long> fileid = new HashSet<Long>(); /* Adding word index */ Element keywordsElement = xmlDoc.createElement("keywords"); IterableIterator<Term> termIterator = perstRoot.getTermIterator(prefix, prefix + "g"); for (Term term : termIterator) { Element wordElement = xmlDoc.createElement("word"); wordElement.setAttribute("v", term.getWord()); - if (config.isDebug()) - wordElement.setAttribute("debug:md5", term.getMD5()); + if (config.isDebug()) { + wordElement.setAttributeNS("urn:freenet:xmlspider:debug", "debug:md5", term.getMD5()); + } count++; estimateSize += 12; estimateSize += term.getWord().length(); Set<Page> pages = term.getPages(); if ((count > 1 && (estimateSize + pages.size() * 13) > MAX_SIZE) || // (count > MAX_ENTRIES)) { if (prefix.length() < 3 && indices.size() < 256) // FIXME this is a hack to limit number of files. remove after metadata fix return false; } for (Page page : pages) { TermPosition termPos = page.getTermPosition(term, false); if (termPos == null) continue; synchronized (termPos) { synchronized (page) { /* * adding file information uriElement - lists the id of the file * containing a particular word fileElement - lists the id,key,title of * the files mentioned in the entire subindex */ Element uriElement = xmlDoc.createElement("file"); uriElement.setAttribute("id", Long.toString(page.getId())); /* Position by position */ int[] positions = termPos.positions; StringBuilder positionList = new StringBuilder(); for (int k = 0; k < positions.length; k++) { if (k != 0) positionList.append(','); positionList.append(positions[k]); } uriElement.appendChild(xmlDoc.createTextNode(positionList.toString())); wordElement.appendChild(uriElement); estimateSize += 13; estimateSize += positionList.length(); if (!fileid.contains(page.getId())) { fileid.add(page.getId()); Element fileElement = xmlDoc.createElement("file"); fileElement.setAttribute("id", Long.toString(page.getId())); fileElement.setAttribute("key", page.getURI()); fileElement.setAttribute("title", page.getPageTitle() != null ? page.getPageTitle() : page.getURI()); filesElement.appendChild(fileElement); estimateSize += 15; estimateSize += filesElement.getAttribute("id").length(); estimateSize += filesElement.getAttribute("key").length(); estimateSize += filesElement.getAttribute("title").length(); } } } } keywordsElement.appendChild(wordElement); } Element entriesElement = xmlDoc.createElement("entries"); entriesElement.setAttribute("value", count + ""); rootElement.appendChild(entriesElement); rootElement.appendChild(headerElement); rootElement.appendChild(filesElement); rootElement.appendChild(keywordsElement); /* Serialization */ DOMSource domSource = new DOMSource(xmlDoc); TransformerFactory transformFactory = TransformerFactory.newInstance(); Transformer serializer; try { serializer = transformFactory.newTransformer(); } catch (javax.xml.transform.TransformerConfigurationException e) { throw new RuntimeException("Spider: Error while serializing XML (transformFactory.newTransformer())", e); } serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); fos = new BufferedOutputStream(new FileOutputStream(outputFile)); StreamResult resultStream = new StreamResult(fos); /* final step */ try { serializer.transform(domSource, resultStream); } catch (javax.xml.transform.TransformerException e) { throw new RuntimeException("Spider: Error while serializing XML (transform())", e); } } finally { Closer.close(fos); } if (outputFile.length() > MAX_SIZE && count > 1) { if (prefix.length() < 3 && indices.size() < 256) { // FIXME this is a hack to limit number of files. remove after metadata fix outputFile.delete(); return false; } } if (logMINOR) Logger.minor(this, "Spider: indexes regenerated."); indices.add(prefix); return true; } public static void main(String[] arg) throws Exception { Storage db = StorageFactory.getInstance().createStorage(); db.setProperty("perst.object.cache.kind", "pinned"); db.setProperty("perst.object.cache.init.size", 8192); db.setProperty("perst.alternative.btree", true); db.setProperty("perst.string.encoding", "UTF-8"); db.setProperty("perst.concurrent.iterator", true); db.setProperty("perst.file.readonly", true); db.open(arg[0]); PerstRoot root = (PerstRoot) db.getRoot(); IndexWriter writer = new IndexWriter(); int benchmark = 0; long[] timeTaken = null; if (arg[1] != null) { benchmark = Integer.parseInt(arg[1]); timeTaken = new long[benchmark]; } for (int i = 0; i < benchmark; i++) { long startTime = System.currentTimeMillis(); writer.makeIndex(root); long endTime = System.currentTimeMillis(); long memFree = Runtime.getRuntime().freeMemory(); long memTotal = Runtime.getRuntime().totalMemory(); System.out.println("Index generated in " + (endTime - startTime) // + "ms. Used memory=" + (memTotal - memFree)); if (benchmark > 0) { timeTaken[i] = (endTime - startTime); System.out.println("Cooling down."); for (int j = 0; j < 3; j++) { System.gc(); System.runFinalization(); Thread.sleep(3000); } } } if (benchmark > 0) { long totalTime = 0; long totalSqTime = 0; for (long t : timeTaken) { totalTime += t; totalSqTime += t * t; } double meanTime = (totalTime / benchmark); double meanSqTime = (totalSqTime / benchmark); System.out.println("Mean time = " + (long) meanTime + "ms"); System.out.println(" sd = " + (long) Math.sqrt(meanSqTime - meanTime * meanTime) + "ms"); } } }
false
true
private boolean generateXML(PerstRoot perstRoot, String prefix) throws IOException { final Config config = perstRoot.getConfig(); final long MAX_SIZE = config.getIndexSubindexMaxSize(); final int MAX_ENTRIES = config.getIndexMaxEntries(); File outputFile = new File(config.getIndexDir() + "index_" + prefix + ".xml"); BufferedOutputStream fos = null; int count = 0; int estimateSize = 0; try { DocumentBuilderFactory xmlFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder xmlBuilder; try { xmlBuilder = xmlFactory.newDocumentBuilder(); } catch (javax.xml.parsers.ParserConfigurationException e) { throw new RuntimeException("Spider: Error while initializing XML generator", e); } DOMImplementation impl = xmlBuilder.getDOMImplementation(); /* Starting to generate index */ Document xmlDoc = impl.createDocument(null, "sub_index", null); Element rootElement = xmlDoc.getDocumentElement(); if (config.isDebug()) { xmlDoc.createAttributeNS("urn:freenet:xmlspider:debug", "debug"); rootElement.appendChild(xmlDoc.createComment(new Date().toGMTString())); } /* Adding header to the index */ Element headerElement = xmlDoc.createElement("header"); /* -> title */ Element subHeaderElement = xmlDoc.createElement("title"); Text subHeaderText = xmlDoc.createTextNode(config.getIndexTitle()); subHeaderElement.appendChild(subHeaderText); headerElement.appendChild(subHeaderElement); /* List of files referenced in this subindex */ Element filesElement = xmlDoc.createElement("files"); /* filesElement != fileElement */ Set<Long> fileid = new HashSet<Long>(); /* Adding word index */ Element keywordsElement = xmlDoc.createElement("keywords"); IterableIterator<Term> termIterator = perstRoot.getTermIterator(prefix, prefix + "g"); for (Term term : termIterator) { Element wordElement = xmlDoc.createElement("word"); wordElement.setAttribute("v", term.getWord()); if (config.isDebug()) wordElement.setAttribute("debug:md5", term.getMD5()); count++; estimateSize += 12; estimateSize += term.getWord().length(); Set<Page> pages = term.getPages(); if ((count > 1 && (estimateSize + pages.size() * 13) > MAX_SIZE) || // (count > MAX_ENTRIES)) { if (prefix.length() < 3 && indices.size() < 256) // FIXME this is a hack to limit number of files. remove after metadata fix return false; } for (Page page : pages) { TermPosition termPos = page.getTermPosition(term, false); if (termPos == null) continue; synchronized (termPos) { synchronized (page) { /* * adding file information uriElement - lists the id of the file * containing a particular word fileElement - lists the id,key,title of * the files mentioned in the entire subindex */ Element uriElement = xmlDoc.createElement("file"); uriElement.setAttribute("id", Long.toString(page.getId())); /* Position by position */ int[] positions = termPos.positions; StringBuilder positionList = new StringBuilder(); for (int k = 0; k < positions.length; k++) { if (k != 0) positionList.append(','); positionList.append(positions[k]); } uriElement.appendChild(xmlDoc.createTextNode(positionList.toString())); wordElement.appendChild(uriElement); estimateSize += 13; estimateSize += positionList.length(); if (!fileid.contains(page.getId())) { fileid.add(page.getId()); Element fileElement = xmlDoc.createElement("file"); fileElement.setAttribute("id", Long.toString(page.getId())); fileElement.setAttribute("key", page.getURI()); fileElement.setAttribute("title", page.getPageTitle() != null ? page.getPageTitle() : page.getURI()); filesElement.appendChild(fileElement); estimateSize += 15; estimateSize += filesElement.getAttribute("id").length(); estimateSize += filesElement.getAttribute("key").length(); estimateSize += filesElement.getAttribute("title").length(); } } } } keywordsElement.appendChild(wordElement); } Element entriesElement = xmlDoc.createElement("entries"); entriesElement.setAttribute("value", count + ""); rootElement.appendChild(entriesElement); rootElement.appendChild(headerElement); rootElement.appendChild(filesElement); rootElement.appendChild(keywordsElement); /* Serialization */ DOMSource domSource = new DOMSource(xmlDoc); TransformerFactory transformFactory = TransformerFactory.newInstance(); Transformer serializer; try { serializer = transformFactory.newTransformer(); } catch (javax.xml.transform.TransformerConfigurationException e) { throw new RuntimeException("Spider: Error while serializing XML (transformFactory.newTransformer())", e); } serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); fos = new BufferedOutputStream(new FileOutputStream(outputFile)); StreamResult resultStream = new StreamResult(fos); /* final step */ try { serializer.transform(domSource, resultStream); } catch (javax.xml.transform.TransformerException e) { throw new RuntimeException("Spider: Error while serializing XML (transform())", e); } } finally { Closer.close(fos); } if (outputFile.length() > MAX_SIZE && count > 1) { if (prefix.length() < 3 && indices.size() < 256) { // FIXME this is a hack to limit number of files. remove after metadata fix outputFile.delete(); return false; } } if (logMINOR) Logger.minor(this, "Spider: indexes regenerated."); indices.add(prefix); return true; }
private boolean generateXML(PerstRoot perstRoot, String prefix) throws IOException { final Config config = perstRoot.getConfig(); final long MAX_SIZE = config.getIndexSubindexMaxSize(); final int MAX_ENTRIES = config.getIndexMaxEntries(); File outputFile = new File(config.getIndexDir() + "index_" + prefix + ".xml"); BufferedOutputStream fos = null; int count = 0; int estimateSize = 0; try { DocumentBuilderFactory xmlFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder xmlBuilder; try { xmlBuilder = xmlFactory.newDocumentBuilder(); } catch (javax.xml.parsers.ParserConfigurationException e) { throw new RuntimeException("Spider: Error while initializing XML generator", e); } DOMImplementation impl = xmlBuilder.getDOMImplementation(); /* Starting to generate index */ Document xmlDoc = impl.createDocument(null, "sub_index", null); Element rootElement = xmlDoc.getDocumentElement(); if (config.isDebug()) { rootElement.appendChild(xmlDoc.createComment(new Date().toGMTString())); } /* Adding header to the index */ Element headerElement = xmlDoc.createElement("header"); /* -> title */ Element subHeaderElement = xmlDoc.createElement("title"); Text subHeaderText = xmlDoc.createTextNode(config.getIndexTitle()); subHeaderElement.appendChild(subHeaderText); headerElement.appendChild(subHeaderElement); /* List of files referenced in this subindex */ Element filesElement = xmlDoc.createElement("files"); /* filesElement != fileElement */ Set<Long> fileid = new HashSet<Long>(); /* Adding word index */ Element keywordsElement = xmlDoc.createElement("keywords"); IterableIterator<Term> termIterator = perstRoot.getTermIterator(prefix, prefix + "g"); for (Term term : termIterator) { Element wordElement = xmlDoc.createElement("word"); wordElement.setAttribute("v", term.getWord()); if (config.isDebug()) { wordElement.setAttributeNS("urn:freenet:xmlspider:debug", "debug:md5", term.getMD5()); } count++; estimateSize += 12; estimateSize += term.getWord().length(); Set<Page> pages = term.getPages(); if ((count > 1 && (estimateSize + pages.size() * 13) > MAX_SIZE) || // (count > MAX_ENTRIES)) { if (prefix.length() < 3 && indices.size() < 256) // FIXME this is a hack to limit number of files. remove after metadata fix return false; } for (Page page : pages) { TermPosition termPos = page.getTermPosition(term, false); if (termPos == null) continue; synchronized (termPos) { synchronized (page) { /* * adding file information uriElement - lists the id of the file * containing a particular word fileElement - lists the id,key,title of * the files mentioned in the entire subindex */ Element uriElement = xmlDoc.createElement("file"); uriElement.setAttribute("id", Long.toString(page.getId())); /* Position by position */ int[] positions = termPos.positions; StringBuilder positionList = new StringBuilder(); for (int k = 0; k < positions.length; k++) { if (k != 0) positionList.append(','); positionList.append(positions[k]); } uriElement.appendChild(xmlDoc.createTextNode(positionList.toString())); wordElement.appendChild(uriElement); estimateSize += 13; estimateSize += positionList.length(); if (!fileid.contains(page.getId())) { fileid.add(page.getId()); Element fileElement = xmlDoc.createElement("file"); fileElement.setAttribute("id", Long.toString(page.getId())); fileElement.setAttribute("key", page.getURI()); fileElement.setAttribute("title", page.getPageTitle() != null ? page.getPageTitle() : page.getURI()); filesElement.appendChild(fileElement); estimateSize += 15; estimateSize += filesElement.getAttribute("id").length(); estimateSize += filesElement.getAttribute("key").length(); estimateSize += filesElement.getAttribute("title").length(); } } } } keywordsElement.appendChild(wordElement); } Element entriesElement = xmlDoc.createElement("entries"); entriesElement.setAttribute("value", count + ""); rootElement.appendChild(entriesElement); rootElement.appendChild(headerElement); rootElement.appendChild(filesElement); rootElement.appendChild(keywordsElement); /* Serialization */ DOMSource domSource = new DOMSource(xmlDoc); TransformerFactory transformFactory = TransformerFactory.newInstance(); Transformer serializer; try { serializer = transformFactory.newTransformer(); } catch (javax.xml.transform.TransformerConfigurationException e) { throw new RuntimeException("Spider: Error while serializing XML (transformFactory.newTransformer())", e); } serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); fos = new BufferedOutputStream(new FileOutputStream(outputFile)); StreamResult resultStream = new StreamResult(fos); /* final step */ try { serializer.transform(domSource, resultStream); } catch (javax.xml.transform.TransformerException e) { throw new RuntimeException("Spider: Error while serializing XML (transform())", e); } } finally { Closer.close(fos); } if (outputFile.length() > MAX_SIZE && count > 1) { if (prefix.length() < 3 && indices.size() < 256) { // FIXME this is a hack to limit number of files. remove after metadata fix outputFile.delete(); return false; } } if (logMINOR) Logger.minor(this, "Spider: indexes regenerated."); indices.add(prefix); return true; }
diff --git a/api/test/exchangeRate/Task1Test.java b/api/test/exchangeRate/Task1Test.java index a0e2318..4ab8a33 100644 --- a/api/test/exchangeRate/Task1Test.java +++ b/api/test/exchangeRate/Task1Test.java @@ -1,134 +1,134 @@ package exchangeRate; import junit.framework.TestCase; /** Finish the Calculator API, and then write bodies of methods inside * of this class to match the given tasks. To fulfill your task, use the * API define in the <code> exchangeRate</code> package. * Do not you reflection, or other “hacks” as your code * shall run without any runtime permissions. */ public class Task1Test extends TestCase { private static CalculatorModule calculatorModule; public Task1Test(String testName) throws ExchangeRateCalculatorException { super(testName); calculatorModule = CalculatorModule.create(); calculatorModule.setExchangeRate(new ExchangeRate(1.0 / 17.0, new Currency("USD"), new Currency("CZK"))); calculatorModule.setExchangeRate(new ExchangeRate(17.0, new Currency("CZK"), new Currency("USD"))); calculatorModule.setExchangeRate(new ExchangeRate(100.0 / 80.0, new Currency("SKK"), new Currency("CZK"))); calculatorModule.setExchangeRate(new ExchangeRate(80.0 / 100.0, new Currency("CZK"), new Currency("SKK"))); } @Override protected void setUp() throws Exception { } @Override protected void tearDown() throws Exception { } // // Imagine that there are three parts of the whole system: // 1. there is someone who knows the current exchange rate // 2. there is someone who wants to calculate the exchange // 3. party 1 provides party 2 with an object that realizes the API. // Please design such API // /** Create a calculator that understands two currencies, CZK and * USD. Make 1 USD == 17 CZK. This is a method provided for #1 group - * e.g. those that know the exchange rate. They somehow need to create * the objects from the API and tell them the exchange rate. The API itself * knows nothing about any rates, before the createCZKtoUSD method is called. * * Creation of the calculator shall not require subclassing of any class * or interface on the client side. * * @return prepared calculator ready for converting USD to CZK and CZK to USD */ public static Calculator createCZKtoUSD() throws ExchangeRateCalculatorException { return calculatorModule.getCalculatorFactory().create(new Currency("CZK"), new Currency("USD")); } /** Create calculator that understands two currencies, CZK and * SKK. Make 100 SKK == 80 CZK. Again this is method for the #1 group - * it knows the exchange rate, and needs to use the API to create objects * with the exchange rate. Anyone shall be ready to call this method without * any other method being called previously. The API itself shall know * nothing about any rates, before this method is called. * * Creation of the calculator shall not require subclassing of any class * or interface on the client side. * * @return prepared calculator ready for converting SKK to CZK and CZK to SKK */ public static Calculator createSKKtoCZK() throws ExchangeRateCalculatorException { return calculatorModule.getCalculatorFactory().create(new Currency("SKK"), new Currency("CZK")); } // // now the methods for group #2 follow: // this group knows nothing about exchange rates, but knows how to use // the API to calculate exchanges. It somehow (by calling a method provided by // group #1) gets an object from the API and uses it to do the rate caluclations. // /** Use the calculator from <code>createCZKtoUSD</code> method and do few calculations * with it. */ public void testExchangeCZKUSD() throws Exception { Currency usd = new Currency("USD"); Currency czk = new Currency("CZK"); Calculator c = createCZKtoUSD(); // convert $5 to CZK using c: // assertEquals("Result is 85 CZK"); CurrencyValue result = c.convert(new CurrencyValue(usd, 5.0), czk); assertEquals(result.getValue(), 85.0); assertEquals(result.getCurrency(), czk); // convert $8 to CZK // assertEquals("Result is 136 CZK"); result = c.convert(new CurrencyValue(usd, 8.0), czk); - assertEquals(result.getValue(), 136); + assertEquals(result.getValue(), 136.0); assertEquals(result.getCurrency(), czk); // convert 1003CZK to USD // assertEquals("Result is 59 USD"); result = c.convert(new CurrencyValue(czk, 1003.0), usd); - assertEquals(result.getValue(), 59); + assertEquals(result.getValue(), 59.0); assertEquals(result.getCurrency(), usd); } /** Use the calculator from <code>createSKKtoCZK</code> method and do a few calculations * with it. */ public void testExchangeSKKCZK() throws Exception { Calculator c = createSKKtoCZK(); // convert 16CZK using c: // assertEquals("Result is 20 SKK"); // convert 500SKK to CZK // assertEquals("Result is 400 CZK"); } /** Verify that the CZK to USD calculator knows nothing about SKK. */ public void testCannotConvertToSKKwithCZKUSDCalculator() throws Exception { Calculator c = createCZKtoUSD(); // convert $5 to SKK, the API shall say this is not possible // convert 500 SKK to CZK, the API shall say this is not possible } /** Verify that the CZK to SKK calculator knows nothing about USD. */ public void testCannotConvertToUSDwithCZKSKKCalculator() throws Exception { Calculator c = createSKKtoCZK(); // convert $5 to SKK, the API shall say this is not possible // convert 500 CZK to USD, the API shall say this is not possible } }
false
true
public void testExchangeCZKUSD() throws Exception { Currency usd = new Currency("USD"); Currency czk = new Currency("CZK"); Calculator c = createCZKtoUSD(); // convert $5 to CZK using c: // assertEquals("Result is 85 CZK"); CurrencyValue result = c.convert(new CurrencyValue(usd, 5.0), czk); assertEquals(result.getValue(), 85.0); assertEquals(result.getCurrency(), czk); // convert $8 to CZK // assertEquals("Result is 136 CZK"); result = c.convert(new CurrencyValue(usd, 8.0), czk); assertEquals(result.getValue(), 136); assertEquals(result.getCurrency(), czk); // convert 1003CZK to USD // assertEquals("Result is 59 USD"); result = c.convert(new CurrencyValue(czk, 1003.0), usd); assertEquals(result.getValue(), 59); assertEquals(result.getCurrency(), usd); }
public void testExchangeCZKUSD() throws Exception { Currency usd = new Currency("USD"); Currency czk = new Currency("CZK"); Calculator c = createCZKtoUSD(); // convert $5 to CZK using c: // assertEquals("Result is 85 CZK"); CurrencyValue result = c.convert(new CurrencyValue(usd, 5.0), czk); assertEquals(result.getValue(), 85.0); assertEquals(result.getCurrency(), czk); // convert $8 to CZK // assertEquals("Result is 136 CZK"); result = c.convert(new CurrencyValue(usd, 8.0), czk); assertEquals(result.getValue(), 136.0); assertEquals(result.getCurrency(), czk); // convert 1003CZK to USD // assertEquals("Result is 59 USD"); result = c.convert(new CurrencyValue(czk, 1003.0), usd); assertEquals(result.getValue(), 59.0); assertEquals(result.getCurrency(), usd); }
diff --git a/ant/host-source/source/project/src/moai/google-billing/MoaiGoogleBillingSecurity.java b/ant/host-source/source/project/src/moai/google-billing/MoaiGoogleBillingSecurity.java index cbce19f7..f6439ac5 100644 --- a/ant/host-source/source/project/src/moai/google-billing/MoaiGoogleBillingSecurity.java +++ b/ant/host-source/source/project/src/moai/google-billing/MoaiGoogleBillingSecurity.java @@ -1,239 +1,239 @@ //----------------------------------------------------------------// // Portions Copyright (c) 2010-2011 Zipline Games, Inc. // Adapted from In-App Billing sample code from Google, Inc. // All Rights Reserved. // http://getmoai.com //----------------------------------------------------------------// package com.ziplinegames.moai; import android.text.TextUtils; import java.security.InvalidKeyException; import java.security.KeyFactory; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import java.security.SecureRandom; import java.security.Signature; import java.security.SignatureException; import java.security.spec.InvalidKeySpecException; import java.security.spec.X509EncodedKeySpec; import java.util.ArrayList; import java.util.HashSet; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.external.base64.*; //================================================================// // MoaiGoogleBillingSecurity //================================================================// public class MoaiGoogleBillingSecurity { private static final String KEY_FACTORY_ALGORITHM = "RSA"; private static final String SIGNATURE_ALGORITHM = "SHA1withRSA"; private static final SecureRandom RANDOM = new SecureRandom (); private static String sBase64EncodedPublicKey = null; private static HashSet < Long > sKnownNonces = new HashSet<Long> (); //================================================================// // VerifiedPurchase //================================================================// public static class VerifiedPurchase { public MoaiGoogleBillingConstants.PurchaseState purchaseState; public String notificationId; public String productId; public String orderId; public long purchaseTime; public String developerPayload; //----------------------------------------------------------------// public VerifiedPurchase ( MoaiGoogleBillingConstants.PurchaseState purchaseState, String notificationId, String productId, String orderId, long purchaseTime, String developerPayload ) { this.purchaseState = purchaseState; this.notificationId = notificationId; this.productId = productId; this.orderId = orderId; this.purchaseTime = purchaseTime; this.developerPayload = developerPayload; } } //----------------------------------------------------------------// public static long generateNonce () { long nonce = RANDOM.nextLong (); sKnownNonces.add ( nonce ); return nonce; } //----------------------------------------------------------------// public static void setPublicKey ( String key ) { sBase64EncodedPublicKey = key; } //----------------------------------------------------------------// public static void removeNonce ( long nonce ) { sKnownNonces.remove ( nonce ); } //----------------------------------------------------------------// public static boolean isNonceKnown ( long nonce ) { return sKnownNonces.contains ( nonce ); } //----------------------------------------------------------------// public static ArrayList < VerifiedPurchase > verifyPurchase ( String signedData, String signature ) { if ( sBase64EncodedPublicKey == null ) { MoaiLog.e ( "MoaiGoogleBillingSecurity verifyPurchase: please specify your Android Market public key using MOAIBilling.setMarketPublicKey ()" ); return null; } if ( signedData == null ) { MoaiLog.e ( "MoaiGoogleBillingSecurity verifyPurchase: data is null" ); return null; } boolean verified = false; if ( !TextUtils.isEmpty ( signature )) { PublicKey key = MoaiGoogleBillingSecurity.generatePublicKey ( sBase64EncodedPublicKey ); verified = MoaiGoogleBillingSecurity.verify ( key, signedData, signature ); if ( !verified ) { MoaiLog.w ( "MoaiGoogleBillingSecurity verifyPurchase: signature does not match data" ); return null; } } JSONObject jObject; JSONArray jTransactionsArray = null; int numTransactions = 0; long nonce = 0L; try { jObject = new JSONObject ( signedData ); nonce = jObject.optLong ( "nonce" ); jTransactionsArray = jObject.optJSONArray ( "orders" ); if ( jTransactionsArray != null ) { numTransactions = jTransactionsArray.length (); } } catch ( JSONException e ) { MoaiLog.e ( "MoaiGoogleBillingSecurity verifyPurchase: json exception", e ); return null; } if ( !MoaiGoogleBillingSecurity.isNonceKnown ( nonce )) { MoaiLog.w ( "MoaiGoogleBillingSecurity verifyPurchase: nonce not found ( " + nonce + " )" ); return null; } ArrayList < VerifiedPurchase > purchases = new ArrayList < VerifiedPurchase > (); try { for ( int i = 0; i < numTransactions; i++ ) { JSONObject jElement = jTransactionsArray.getJSONObject ( i ); int response = jElement.getInt ( "purchaseState" ); MoaiGoogleBillingConstants.PurchaseState purchaseState = MoaiGoogleBillingConstants.PurchaseState.valueOf ( response ); String productId = jElement.getString ( "productId" ); String packageName = jElement.getString ( "packageName" ); long purchaseTime = jElement.getLong ( "purchaseTime" ); String orderId = jElement.optString ( "orderId", "" ); String notifyId = null; if ( jElement.has ( "notificationId" )) { notifyId = jElement.getString ( "notificationId" ); } String developerPayload = jElement.optString ( "developerPayload", null ); - if (( purchaseState == MoaiGoogleBillingConstants.PurchaseState.PURCHASED ) && !verified ) { + if (( purchaseState == MoaiGoogleBillingConstants.PurchaseState.PURCHASE_COMPLETED ) && !verified ) { continue; } purchases.add ( new VerifiedPurchase ( purchaseState, notifyId, productId, orderId, purchaseTime, developerPayload )); } } catch ( JSONException e ) { MoaiLog.e ( "MoaiGoogleBillingSecurity verifyPurchase: json exception", e ); return null; } removeNonce ( nonce ); return purchases; } //----------------------------------------------------------------// public static PublicKey generatePublicKey ( String encodedPublicKey ) { try { byte [] decodedKey = Base64.decode ( encodedPublicKey ); KeyFactory keyFactory = KeyFactory.getInstance ( KEY_FACTORY_ALGORITHM ); return keyFactory.generatePublic ( new X509EncodedKeySpec ( decodedKey )); } catch ( NoSuchAlgorithmException e ) { MoaiLog.e ( "MoaiGoogleBillingSecurity generatePublicKey: no such algorithm" ); throw new RuntimeException ( e ); } catch ( InvalidKeySpecException e ) { MoaiLog.e ( "MoaiGoogleBillingSecurity generatePublicKey: invalid key" ); throw new IllegalArgumentException ( e ); } catch ( Base64DecoderException e ) { MoaiLog.e ( "MoaiGoogleBillingSecurity generatePublicKey: base64 decoding failed" ); throw new IllegalArgumentException ( e ); } } //----------------------------------------------------------------// public static boolean verify ( PublicKey publicKey, String signedData, String signature ) { Signature sig; try { sig = Signature.getInstance ( SIGNATURE_ALGORITHM ); sig.initVerify ( publicKey ); sig.update ( signedData.getBytes ()); if ( !sig.verify ( Base64.decode ( signature ))) { MoaiLog.e ( "MoaiGoogleBillingSecurity verify: signature verification failed" ); return false; } return true; } catch ( NoSuchAlgorithmException e ) { MoaiLog.e ( "MoaiGoogleBillingSecurity verify: no such algorithm" ); } catch ( InvalidKeyException e ) { MoaiLog.e ( "MoaiGoogleBillingSecurity verify: invalid key" ); } catch ( SignatureException e ) { MoaiLog.e ( "MoaiGoogleBillingSecurity verify: invalid signature" ); } catch ( Base64DecoderException e ) { MoaiLog.e ( "MoaiGoogleBillingSecurity verify: base64 decoding failed" ); } return false; } }
true
true
public static ArrayList < VerifiedPurchase > verifyPurchase ( String signedData, String signature ) { if ( sBase64EncodedPublicKey == null ) { MoaiLog.e ( "MoaiGoogleBillingSecurity verifyPurchase: please specify your Android Market public key using MOAIBilling.setMarketPublicKey ()" ); return null; } if ( signedData == null ) { MoaiLog.e ( "MoaiGoogleBillingSecurity verifyPurchase: data is null" ); return null; } boolean verified = false; if ( !TextUtils.isEmpty ( signature )) { PublicKey key = MoaiGoogleBillingSecurity.generatePublicKey ( sBase64EncodedPublicKey ); verified = MoaiGoogleBillingSecurity.verify ( key, signedData, signature ); if ( !verified ) { MoaiLog.w ( "MoaiGoogleBillingSecurity verifyPurchase: signature does not match data" ); return null; } } JSONObject jObject; JSONArray jTransactionsArray = null; int numTransactions = 0; long nonce = 0L; try { jObject = new JSONObject ( signedData ); nonce = jObject.optLong ( "nonce" ); jTransactionsArray = jObject.optJSONArray ( "orders" ); if ( jTransactionsArray != null ) { numTransactions = jTransactionsArray.length (); } } catch ( JSONException e ) { MoaiLog.e ( "MoaiGoogleBillingSecurity verifyPurchase: json exception", e ); return null; } if ( !MoaiGoogleBillingSecurity.isNonceKnown ( nonce )) { MoaiLog.w ( "MoaiGoogleBillingSecurity verifyPurchase: nonce not found ( " + nonce + " )" ); return null; } ArrayList < VerifiedPurchase > purchases = new ArrayList < VerifiedPurchase > (); try { for ( int i = 0; i < numTransactions; i++ ) { JSONObject jElement = jTransactionsArray.getJSONObject ( i ); int response = jElement.getInt ( "purchaseState" ); MoaiGoogleBillingConstants.PurchaseState purchaseState = MoaiGoogleBillingConstants.PurchaseState.valueOf ( response ); String productId = jElement.getString ( "productId" ); String packageName = jElement.getString ( "packageName" ); long purchaseTime = jElement.getLong ( "purchaseTime" ); String orderId = jElement.optString ( "orderId", "" ); String notifyId = null; if ( jElement.has ( "notificationId" )) { notifyId = jElement.getString ( "notificationId" ); } String developerPayload = jElement.optString ( "developerPayload", null ); if (( purchaseState == MoaiGoogleBillingConstants.PurchaseState.PURCHASED ) && !verified ) { continue; } purchases.add ( new VerifiedPurchase ( purchaseState, notifyId, productId, orderId, purchaseTime, developerPayload )); } } catch ( JSONException e ) { MoaiLog.e ( "MoaiGoogleBillingSecurity verifyPurchase: json exception", e ); return null; } removeNonce ( nonce ); return purchases; }
public static ArrayList < VerifiedPurchase > verifyPurchase ( String signedData, String signature ) { if ( sBase64EncodedPublicKey == null ) { MoaiLog.e ( "MoaiGoogleBillingSecurity verifyPurchase: please specify your Android Market public key using MOAIBilling.setMarketPublicKey ()" ); return null; } if ( signedData == null ) { MoaiLog.e ( "MoaiGoogleBillingSecurity verifyPurchase: data is null" ); return null; } boolean verified = false; if ( !TextUtils.isEmpty ( signature )) { PublicKey key = MoaiGoogleBillingSecurity.generatePublicKey ( sBase64EncodedPublicKey ); verified = MoaiGoogleBillingSecurity.verify ( key, signedData, signature ); if ( !verified ) { MoaiLog.w ( "MoaiGoogleBillingSecurity verifyPurchase: signature does not match data" ); return null; } } JSONObject jObject; JSONArray jTransactionsArray = null; int numTransactions = 0; long nonce = 0L; try { jObject = new JSONObject ( signedData ); nonce = jObject.optLong ( "nonce" ); jTransactionsArray = jObject.optJSONArray ( "orders" ); if ( jTransactionsArray != null ) { numTransactions = jTransactionsArray.length (); } } catch ( JSONException e ) { MoaiLog.e ( "MoaiGoogleBillingSecurity verifyPurchase: json exception", e ); return null; } if ( !MoaiGoogleBillingSecurity.isNonceKnown ( nonce )) { MoaiLog.w ( "MoaiGoogleBillingSecurity verifyPurchase: nonce not found ( " + nonce + " )" ); return null; } ArrayList < VerifiedPurchase > purchases = new ArrayList < VerifiedPurchase > (); try { for ( int i = 0; i < numTransactions; i++ ) { JSONObject jElement = jTransactionsArray.getJSONObject ( i ); int response = jElement.getInt ( "purchaseState" ); MoaiGoogleBillingConstants.PurchaseState purchaseState = MoaiGoogleBillingConstants.PurchaseState.valueOf ( response ); String productId = jElement.getString ( "productId" ); String packageName = jElement.getString ( "packageName" ); long purchaseTime = jElement.getLong ( "purchaseTime" ); String orderId = jElement.optString ( "orderId", "" ); String notifyId = null; if ( jElement.has ( "notificationId" )) { notifyId = jElement.getString ( "notificationId" ); } String developerPayload = jElement.optString ( "developerPayload", null ); if (( purchaseState == MoaiGoogleBillingConstants.PurchaseState.PURCHASE_COMPLETED ) && !verified ) { continue; } purchases.add ( new VerifiedPurchase ( purchaseState, notifyId, productId, orderId, purchaseTime, developerPayload )); } } catch ( JSONException e ) { MoaiLog.e ( "MoaiGoogleBillingSecurity verifyPurchase: json exception", e ); return null; } removeNonce ( nonce ); return purchases; }
diff --git a/src/edu/jhu/thrax/extraction/HieroRuleExtractor.java b/src/edu/jhu/thrax/extraction/HieroRuleExtractor.java index 79f291d..3ef67a1 100644 --- a/src/edu/jhu/thrax/extraction/HieroRuleExtractor.java +++ b/src/edu/jhu/thrax/extraction/HieroRuleExtractor.java @@ -1,178 +1,179 @@ package edu.jhu.thrax.extraction; import java.util.Collection; import java.util.Arrays; import java.util.Set; import java.util.HashSet; import java.util.ArrayList; import java.util.Queue; import java.util.LinkedList; import edu.jhu.thrax.datatypes.*; import edu.jhu.thrax.util.Vocabulary; import edu.jhu.thrax.features.Feature; import edu.jhu.thrax.ThraxConfig; /** * This class extracts Hiero-style SCFG rules. The inputs that are needed * are "source" "target" and "alignment", which are the source and target * sides of a parallel corpus, and an alignment between each of the sentences. */ public class HieroRuleExtractor implements RuleExtractor { public static String name = "hiero"; public String [] requiredInputs() { return new String [] { ThraxConfig.SOURCE, ThraxConfig.TARGET, ThraxConfig.ALIGNMENT }; } public int INIT_LENGTH_LIMIT = 10; public int SOURCE_LENGTH_LIMIT = 5; public int NT_LIMIT = 2; public int LEXICAL_MINIMUM = 1; public boolean ALLOW_ADJACENT_NTS = false; public boolean ALLOW_LOOSE_BOUNDS = false; public static final String X = "X"; public static final int X_ID = Vocabulary.getId(X); private ArrayList<Feature> features; private int featureLength; /** * Default constructor. All it does is to initialize the list of * features to an empty list. */ public HieroRuleExtractor() { features = new ArrayList<Feature>(); featureLength = 0; ALLOW_ADJACENT_NTS = ThraxConfig.opts.containsKey(ThraxConfig.ADJACENT); ALLOW_LOOSE_BOUNDS = ThraxConfig.opts.containsKey(ThraxConfig.LOOSE); } public Set<Rule> extract(Object [] inputs) { if (inputs.length < 3) { return null; } int [] source = (int []) inputs[0]; int [] target = (int []) inputs[1]; Alignment alignment = (Alignment) inputs[2]; PhrasePair [][] phrasesByStart = initialPhrasePairs(source, target, alignment); Queue<Rule> q = new LinkedList<Rule>(); for (int i = 0; i < source.length; i++) q.offer(new Rule(source, target, alignment, i, NT_LIMIT)); return processQueue(q, phrasesByStart); } public void addFeature(Feature f) { features.add(f); featureLength += f.length(); } public void score(Rule r) { r.scores = new double[featureLength]; int idx = 0; for (Feature f : features) { System.arraycopy(f.score(r), 0, r.scores, idx, f.length()); idx += f.length(); } } protected Set<Rule> processQueue(Queue<Rule> q, PhrasePair [][] phrasesByStart) { Set<Rule> rules = new HashSet<Rule>(); while (q.peek() != null) { Rule r = q.poll(); if (isWellFormed(r)) { for (Rule s : getLabelVariants(r)) { for (Feature feat : features) feat.noteExtraction(s); rules.add(s); } } if (r.appendPoint > phrasesByStart.length - 1) continue; if (phrasesByStart[r.appendPoint] == null) continue; for (PhrasePair pp : phrasesByStart[r.appendPoint]) { if (pp.sourceEnd - r.rhs.sourceStart > INIT_LENGTH_LIMIT || (r.rhs.targetStart >= 0 && pp.targetEnd - r.rhs.targetStart > INIT_LENGTH_LIMIT)) continue; if (r.numNTs < NT_LIMIT && r.numNTs + r.numTerminals < SOURCE_LENGTH_LIMIT && (!r.sourceEndsWithNT || ALLOW_ADJACENT_NTS)) { Rule s = r.copy(); s.extendWithNonterminal(pp); q.offer(s); } - if (r.numNTs + r.numTerminals + pp.sourceEnd - pp.sourceStart <= SOURCE_LENGTH_LIMIT) { + if (r.numNTs + r.numTerminals + pp.sourceEnd - pp.sourceStart <= SOURCE_LENGTH_LIMIT && + (r.appendPoint == r.rhs.sourceStart || r.sourceEndsWithNT)) { Rule s = r.copy(); s.extendWithTerminals(pp); q.offer(s); } } } return rules; } protected boolean isWellFormed(Rule r) { if (r.rhs.targetStart < 0) return false; for (int i = r.rhs.targetStart; i < r.rhs.targetEnd; i++) { if (r.targetLex[i] < 0) return false; } return (r.alignedWords >= LEXICAL_MINIMUM); } private Collection<Rule> variantSet = new HashSet<Rule>(1); protected Collection<Rule> getLabelVariants(Rule r) { variantSet.clear(); r.lhs = X_ID; Arrays.fill(r.nts, X_ID); variantSet.add(r); return variantSet; } private PhrasePair [][] initialPhrasePairs(int [] f, int [] e, Alignment a) { PhrasePair [][] result = new PhrasePair[f.length][]; ArrayList<PhrasePair> list = new ArrayList<PhrasePair>(); for (int i = 0; i < f.length; i++) { list.clear(); int maxlen = f.length - i < INIT_LENGTH_LIMIT ? f.length - i : INIT_LENGTH_LIMIT; for (int len = 1; len <= maxlen; len++) { if (!ALLOW_LOOSE_BOUNDS && (!a.sourceIsAligned(i) || !a.sourceIsAligned(i+len-1))) continue; PhrasePair pp = a.getPairFromSource(i, i+len); if (pp != null && pp.targetEnd - pp.targetStart <= INIT_LENGTH_LIMIT) { list.add(pp); } } result[i] = new PhrasePair[list.size()]; list.toArray(result[i]); } return result; } }
true
true
protected Set<Rule> processQueue(Queue<Rule> q, PhrasePair [][] phrasesByStart) { Set<Rule> rules = new HashSet<Rule>(); while (q.peek() != null) { Rule r = q.poll(); if (isWellFormed(r)) { for (Rule s : getLabelVariants(r)) { for (Feature feat : features) feat.noteExtraction(s); rules.add(s); } } if (r.appendPoint > phrasesByStart.length - 1) continue; if (phrasesByStart[r.appendPoint] == null) continue; for (PhrasePair pp : phrasesByStart[r.appendPoint]) { if (pp.sourceEnd - r.rhs.sourceStart > INIT_LENGTH_LIMIT || (r.rhs.targetStart >= 0 && pp.targetEnd - r.rhs.targetStart > INIT_LENGTH_LIMIT)) continue; if (r.numNTs < NT_LIMIT && r.numNTs + r.numTerminals < SOURCE_LENGTH_LIMIT && (!r.sourceEndsWithNT || ALLOW_ADJACENT_NTS)) { Rule s = r.copy(); s.extendWithNonterminal(pp); q.offer(s); } if (r.numNTs + r.numTerminals + pp.sourceEnd - pp.sourceStart <= SOURCE_LENGTH_LIMIT) { Rule s = r.copy(); s.extendWithTerminals(pp); q.offer(s); } } } return rules; }
protected Set<Rule> processQueue(Queue<Rule> q, PhrasePair [][] phrasesByStart) { Set<Rule> rules = new HashSet<Rule>(); while (q.peek() != null) { Rule r = q.poll(); if (isWellFormed(r)) { for (Rule s : getLabelVariants(r)) { for (Feature feat : features) feat.noteExtraction(s); rules.add(s); } } if (r.appendPoint > phrasesByStart.length - 1) continue; if (phrasesByStart[r.appendPoint] == null) continue; for (PhrasePair pp : phrasesByStart[r.appendPoint]) { if (pp.sourceEnd - r.rhs.sourceStart > INIT_LENGTH_LIMIT || (r.rhs.targetStart >= 0 && pp.targetEnd - r.rhs.targetStart > INIT_LENGTH_LIMIT)) continue; if (r.numNTs < NT_LIMIT && r.numNTs + r.numTerminals < SOURCE_LENGTH_LIMIT && (!r.sourceEndsWithNT || ALLOW_ADJACENT_NTS)) { Rule s = r.copy(); s.extendWithNonterminal(pp); q.offer(s); } if (r.numNTs + r.numTerminals + pp.sourceEnd - pp.sourceStart <= SOURCE_LENGTH_LIMIT && (r.appendPoint == r.rhs.sourceStart || r.sourceEndsWithNT)) { Rule s = r.copy(); s.extendWithTerminals(pp); q.offer(s); } } } return rules; }
diff --git a/apps/routerconsole/java/src/net/i2p/router/web/SummaryBarRenderer.java b/apps/routerconsole/java/src/net/i2p/router/web/SummaryBarRenderer.java index 8643a9c0c..23f297031 100644 --- a/apps/routerconsole/java/src/net/i2p/router/web/SummaryBarRenderer.java +++ b/apps/routerconsole/java/src/net/i2p/router/web/SummaryBarRenderer.java @@ -1,421 +1,421 @@ package net.i2p.router.web; import java.io.File; import java.io.IOException; import java.io.Writer; import net.i2p.router.RouterContext; /** * Refactored from summarynoframe.jsp to save ~100KB * */ public class SummaryBarRenderer { private RouterContext _context; private SummaryHelper _helper; public SummaryBarRenderer(RouterContext context, SummaryHelper helper) { _context = context; _helper = helper; } /** * Note - ensure all links in here are absolute, as the summary bar may be displayed * on lower-level directory errors. */ public void renderSummaryHTML(Writer out) throws IOException { StringBuilder buf = new StringBuilder(8*1024); buf.append("<a href=\"/index.jsp\" target=\"_top\"><img src=\"/themes/console/images/i2plogo.png\" alt=\"") .append(_("I2P Router Console")) .append("\" title=\"") .append(_("I2P Router Console")) .append("\"></a><hr>"); File lpath = new File(_context.getBaseDir(), "docs/toolbar.html"); // you better have target="_top" for the links in there... if (lpath.exists()) { ContentHelper linkhelper = new ContentHelper(); linkhelper.setPage(lpath.getAbsolutePath()); linkhelper.setMaxLines("100"); buf.append(linkhelper.getContent()); } else { buf.append("<h3><a href=\"/configclients.jsp\" target=\"_top\" title=\"") .append(_("Configure startup of clients and webapps (services); manually start dormant services")) .append("\">") .append(_("I2P Services")) .append("</a></h3>\n" + "<hr><table>" + "<tr><td><a href=\"/susidns/index.jsp\" target=\"_blank\" title=\"") .append(_("Manage your I2P hosts file here (I2P domain name resolution)")) .append("\">") .append(_("Addressbook")) .append("</a>\n" + "<a href=\"/i2psnark/\" target=\"_blank\" title=\"") .append(_("Built-in anonymous BitTorrent Client")) .append("\">") .append(_("Torrents")) .append("</a>\n" + "<a href=\"/susimail/susimail\" target=\"blank\" title=\"") .append(_("Anonymous webmail client")) .append("\">") .append(_("Webmail")) .append("</a>\n" + "<a href=\"http://127.0.0.1:7658/\" target=\"_blank\" title=\"") .append(_("Anonymous resident webserver")) .append("\">") .append(_("Webserver")) .append("</a></td></tr></table>\n" + "<hr><h3><a href=\"/config.jsp\" target=\"_top\" title=\"") .append(_("Configure I2P Router")) .append("\">") .append(_("I2P Internals")) .append("</a></h3><hr>\n" + "<table><tr><td>\n" + "<a href=\"/tunnels.jsp\" target=\"_top\" title=\"") .append(_("View existing tunnels and tunnel build status")) .append("\">") .append(_("Tunnels")) .append("</a>\n" + "<a href=\"/peers.jsp\" target=\"_top\" title=\"") .append(_("Show all current peer connections")) .append("\">") .append(_("Peers")) .append("</a>\n" + "<a href=\"/profiles.jsp\" target=\"_top\" title=\"") .append(_("Show recent peer performance profiles")) .append("\">") .append(_("Profiles")) .append("</a>\n" + "<a href=\"/netdb.jsp\" target=\"_top\" title=\"") .append(_("Show list of all known I2P routers")) .append("\">") .append(_("NetDB")) .append("</a>\n" + "<a href=\"/logs.jsp\" target=\"_top\" title=\"") .append(_("Health Report")) .append("\">") .append(_("Logs")) .append("</a>\n" + "<a href=\"/jobs.jsp\" target=\"_top\" title=\"") .append(_("Show the router's workload, and how it's performing")) .append("\">") .append(_("Jobs")) .append("</a>\n" + "<a href=\"/graphs.jsp\" target=\"_top\" title=\"") .append(_("Graph router performance")) .append("\">") .append(_("Graphs")) .append("</a>\n" + "<a href=\"/stats.jsp\" target=\"_top\" title=\"") .append(_("Textual router performance statistics")) .append("\">") .append(_("Stats")) .append("</a></td></tr></table>\n"); out.write(buf.toString()); buf.setLength(0); } buf.append("<hr><h3><a href=\"/help.jsp\" target=\"_top\" title=\"") .append(_("I2P Router Help")) .append("\">") .append(_("General")) .append("</a></h3><hr>" + "<h4><a title=\"") .append(_("Your unique I2P router identity is")) .append(' ') .append(_helper.getIdent()) .append(", ") .append(_("never reveal it to anyone")) .append("\" href=\"/netdb.jsp?r=.\" target=\"_top\">") .append(_("Local Identity")) .append("</a></h4><hr>\n" + "<table><tr><td align=\"left\">" + "<b>") .append(_("Version")) .append(":</b></td>" + "<td align=\"right\">") .append(_helper.getVersion()) .append("</td></tr>\n" + "<tr title=\"") .append(_("How long we've been running for this session")) .append("\">" + "<td align=\"left\"><b>") .append(_("Uptime")) .append(":</b></td>" + "<td align=\"right\">") .append(_helper.getUptime()) .append("</td></tr></table>\n" + "<hr><h4><a href=\"/config.jsp#help\" target=\"_top\" title=\"") .append(_("Help with configuring your firewall and router for optimal I2P performance")) .append("\">") .append(_helper.getReachability()) .append("</a></h4><hr>\n"); if (_helper.updateAvailable() || _helper.unsignedUpdateAvailable()) { // display all the time so we display the final failure message - buf.append("<br>").append(UpdateHandler.getStatus()); + buf.append(UpdateHandler.getStatus()); if ("true".equals(System.getProperty("net.i2p.router.web.UpdateHandler.updateInProgress"))) { // nothing } else if( // isDone() is always false for now, see UpdateHandler // ((!update.isDone()) && _helper.getAction() == null && _helper.getUpdateNonce() == null && ConfigRestartBean.getRestartTimeRemaining() > 12*60*1000) { long nonce = _context.random().nextLong(); String prev = System.getProperty("net.i2p.router.web.UpdateHandler.nonce"); if (prev != null) System.setProperty("net.i2p.router.web.UpdateHandler.noncePrev", prev); System.setProperty("net.i2p.router.web.UpdateHandler.nonce", nonce+""); String uri = _helper.getRequestURI(); - buf.append("<form action=\"").append(uri).append("\" method=\"GET\">\n"); + buf.append("<p><form action=\"").append(uri).append("\" method=\"GET\">\n"); buf.append("<input type=\"hidden\" name=\"updateNonce\" value=\"").append(nonce).append("\" >\n"); if (_helper.updateAvailable()) { buf.append("<button type=\"submit\" name=\"updateAction\" value=\"signed\" >") .append(_("Download")) .append(' ') .append(_helper.getUpdateVersion()) .append(' ') .append(_("Update")) .append("</button>\n"); } if (_helper.unsignedUpdateAvailable()) { buf.append("<button type=\"submit\" name=\"updateAction\" value=\"Unsigned\" >") .append(_("Download Unsigned")) .append("<br>") .append(_("Update")) .append(' ') .append(_helper.getUnsignedUpdateVersion()) .append("</button>\n"); } buf.append("</form>\n"); } } buf.append("<p>") .append(ConfigRestartBean.renderStatus(_helper.getRequestURI(), _helper.getAction(), _helper.getConsoleNonce())) .append("</p><hr><h3><a href=\"/peers.jsp\" target=\"_top\" title=\"") .append(_("Show all current peer connections")) .append("\">") .append(_("Peers")) .append("</a></h3><hr>\n" + "<table>\n" + "<tr><td align=\"left\"><b>") .append(_("Active")) .append(":</b></td><td align=\"right\">") .append(_helper.getActivePeers()) .append('/') .append(_helper.getActiveProfiles()) .append("</td></tr>\n" + "<tr><td align=\"left\"><b>") .append(_("Fast")) .append(":</b></td><td align=\"right\">") .append(_helper.getFastPeers()) .append("</td></tr>\n" + "<tr><td align=\"left\"><b>") .append(_("High capacity")) .append(":</b></td><td align=\"right\">") .append(_helper.getHighCapacityPeers()) .append("</td></tr>\n" + "<tr><td align=\"left\"><b>") .append(_("Integrated")) .append(":</b></td><td align=\"right\">") .append(_helper.getWellIntegratedPeers()) .append("</td></tr>\n" + "<tr><td align=\"left\"><b>") .append(_("Known")) .append(":</b></td><td align=\"right\">") .append(_helper.getAllPeers()) .append("</td></tr>\n" + "</table><hr>\n"); out.write(buf.toString()); buf.setLength(0); boolean anotherLine = false; if (_helper.showFirewallWarning()) { buf.append("<h4><a href=\"/config.jsp\" target=\"_top\" title=\"") .append(_("Help with firewall configuration")) .append("\">") .append(_("Check NAT/firewall")) .append("</a></h4>"); anotherLine = true; } boolean reseedInProgress = Boolean.valueOf(System.getProperty("net.i2p.router.web.ReseedHandler.reseedInProgress")).booleanValue(); // If showing the reseed link is allowed if (_helper.allowReseed()) { if (reseedInProgress) { // While reseed occurring, show status message instead buf.append("<i>").append(System.getProperty("net.i2p.router.web.ReseedHandler.statusMessage","")).append("</i><br>"); } else { // While no reseed occurring, show reseed link long nonce = _context.random().nextLong(); String prev = System.getProperty("net.i2p.router.web.ReseedHandler.nonce"); if (prev != null) System.setProperty("net.i2p.router.web.ReseedHandler.noncePrev", prev); System.setProperty("net.i2p.router.web.ReseedHandler.nonce", nonce+""); String uri = _helper.getRequestURI(); buf.append("<p><form action=\"").append(uri).append("\" method=\"GET\">\n"); buf.append("<input type=\"hidden\" name=\"reseedNonce\" value=\"").append(nonce).append("\" >\n"); buf.append("<button type=\"submit\" value=\"Reseed\" >").append(_("Reseed")).append("</button></form></p>\n"); } anotherLine = true; } // If a new reseed ain't running, and the last reseed had errors, show error message if (!reseedInProgress) { String reseedErrorMessage = System.getProperty("net.i2p.router.web.ReseedHandler.errorMessage",""); if (reseedErrorMessage.length() > 0) { buf.append("<i>").append(reseedErrorMessage).append("</i><br>"); anotherLine = true; } } if (anotherLine) buf.append("<hr>"); buf.append("<h3><a href=\"/config.jsp\" title=\"") .append(_("Configure router bandwidth allocation")) .append("\" target=\"_top\">") .append(_("Bandwidth in/out")) .append("</a></h3><hr>" + "<table>\n" + "<tr><td align=\"left\"><b>1s:</b></td><td align=\"right\">") .append(_helper.getInboundSecondKBps()) .append('/') .append(_helper.getOutboundSecondKBps()) .append("K/s</td></tr>\n" + "<tr><td align=\"left\"><b>5m:</b></td><td align=\"right\">") .append(_helper.getInboundFiveMinuteKBps()) .append('/') .append(_helper.getOutboundFiveMinuteKBps()) .append("K/s</td></tr>\n" + "<tr><td align=\"left\"><b>") .append(_("Total")) .append(":</b></td><td align=\"right\">") .append(_helper.getInboundLifetimeKBps()) .append('/') .append(_helper.getOutboundLifetimeKBps()) .append("K/s</td></tr>\n" + "<tr><td align=\"left\"><b>") .append(_("Used")) .append(":</b></td><td align=\"right\">") .append(_helper.getInboundTransferred()) .append('/') .append(_helper.getOutboundTransferred()) .append("</td></tr></table>\n" + "<hr><h3><a href=\"/tunnels.jsp\" target=\"_top\" title=\"") .append(_("View existing tunnels and tunnel build status")) .append("\">") .append(_("Tunnels in/out")) .append("</a></h3><hr>" + "<table>\n" + "<tr><td align=\"left\"><b>") .append(_("Exploratory")) .append(":</b></td><td align=\"right\">") .append(_helper.getInboundTunnels()) .append('/') .append(_helper.getOutboundTunnels()) .append("</td></tr>\n" + "<tr><td align=\"left\"><b>") .append(_("Client")) .append(":</b></td><td align=\"right\">") .append(_helper.getInboundClientTunnels()) .append('/') .append(_helper.getOutboundClientTunnels()) .append("</td></tr>\n" + "<tr><td align=\"left\"><b>") .append(_("Participating")) .append(":</b></td><td align=\"right\">") .append(_helper.getParticipatingTunnels()) .append("</td></tr>\n" + "</table><hr><h3><a href=\"/jobs.jsp\" target=\"_top\" title=\"") .append(_("What's in the router's job queue?")) .append("\">") .append(_("Congestion")) .append("</a></h3><hr>" + "<table>\n" + "<tr><td align=\"left\"><b>") .append(_("Job lag")) .append(":</b></td><td align=\"right\">") .append(_helper.getJobLag()) .append("</td></tr>\n" + "<tr><td align=\"left\"><b>") .append(_("Message delay")) .append(":</b></td><td align=\"right\">") .append(_helper.getMessageDelay()) .append("</td></tr>\n" + "<tr><td align=\"left\"><b>") .append(_("Tunnel lag")) .append(":</b></td><td align=\"right\">") .append(_helper.getTunnelLag()) .append("</td></tr>\n" + "<tr><td align=\"left\"><b>") .append(_("Backlog")) .append(":</b></td><td align=\"right\">") .append(_helper.getInboundBacklog()) .append("</td></tr>\n" + "</table><hr><h4>") .append(_(_helper.getTunnelStatus())) .append("</h4><hr>\n") .append(_helper.getDestinations()); out.write(buf.toString()); } /** translate a string */ private String _(String s) { return Messages.getString(s, _context); } }
false
true
public void renderSummaryHTML(Writer out) throws IOException { StringBuilder buf = new StringBuilder(8*1024); buf.append("<a href=\"/index.jsp\" target=\"_top\"><img src=\"/themes/console/images/i2plogo.png\" alt=\"") .append(_("I2P Router Console")) .append("\" title=\"") .append(_("I2P Router Console")) .append("\"></a><hr>"); File lpath = new File(_context.getBaseDir(), "docs/toolbar.html"); // you better have target="_top" for the links in there... if (lpath.exists()) { ContentHelper linkhelper = new ContentHelper(); linkhelper.setPage(lpath.getAbsolutePath()); linkhelper.setMaxLines("100"); buf.append(linkhelper.getContent()); } else { buf.append("<h3><a href=\"/configclients.jsp\" target=\"_top\" title=\"") .append(_("Configure startup of clients and webapps (services); manually start dormant services")) .append("\">") .append(_("I2P Services")) .append("</a></h3>\n" + "<hr><table>" + "<tr><td><a href=\"/susidns/index.jsp\" target=\"_blank\" title=\"") .append(_("Manage your I2P hosts file here (I2P domain name resolution)")) .append("\">") .append(_("Addressbook")) .append("</a>\n" + "<a href=\"/i2psnark/\" target=\"_blank\" title=\"") .append(_("Built-in anonymous BitTorrent Client")) .append("\">") .append(_("Torrents")) .append("</a>\n" + "<a href=\"/susimail/susimail\" target=\"blank\" title=\"") .append(_("Anonymous webmail client")) .append("\">") .append(_("Webmail")) .append("</a>\n" + "<a href=\"http://127.0.0.1:7658/\" target=\"_blank\" title=\"") .append(_("Anonymous resident webserver")) .append("\">") .append(_("Webserver")) .append("</a></td></tr></table>\n" + "<hr><h3><a href=\"/config.jsp\" target=\"_top\" title=\"") .append(_("Configure I2P Router")) .append("\">") .append(_("I2P Internals")) .append("</a></h3><hr>\n" + "<table><tr><td>\n" + "<a href=\"/tunnels.jsp\" target=\"_top\" title=\"") .append(_("View existing tunnels and tunnel build status")) .append("\">") .append(_("Tunnels")) .append("</a>\n" + "<a href=\"/peers.jsp\" target=\"_top\" title=\"") .append(_("Show all current peer connections")) .append("\">") .append(_("Peers")) .append("</a>\n" + "<a href=\"/profiles.jsp\" target=\"_top\" title=\"") .append(_("Show recent peer performance profiles")) .append("\">") .append(_("Profiles")) .append("</a>\n" + "<a href=\"/netdb.jsp\" target=\"_top\" title=\"") .append(_("Show list of all known I2P routers")) .append("\">") .append(_("NetDB")) .append("</a>\n" + "<a href=\"/logs.jsp\" target=\"_top\" title=\"") .append(_("Health Report")) .append("\">") .append(_("Logs")) .append("</a>\n" + "<a href=\"/jobs.jsp\" target=\"_top\" title=\"") .append(_("Show the router's workload, and how it's performing")) .append("\">") .append(_("Jobs")) .append("</a>\n" + "<a href=\"/graphs.jsp\" target=\"_top\" title=\"") .append(_("Graph router performance")) .append("\">") .append(_("Graphs")) .append("</a>\n" + "<a href=\"/stats.jsp\" target=\"_top\" title=\"") .append(_("Textual router performance statistics")) .append("\">") .append(_("Stats")) .append("</a></td></tr></table>\n"); out.write(buf.toString()); buf.setLength(0); } buf.append("<hr><h3><a href=\"/help.jsp\" target=\"_top\" title=\"") .append(_("I2P Router Help")) .append("\">") .append(_("General")) .append("</a></h3><hr>" + "<h4><a title=\"") .append(_("Your unique I2P router identity is")) .append(' ') .append(_helper.getIdent()) .append(", ") .append(_("never reveal it to anyone")) .append("\" href=\"/netdb.jsp?r=.\" target=\"_top\">") .append(_("Local Identity")) .append("</a></h4><hr>\n" + "<table><tr><td align=\"left\">" + "<b>") .append(_("Version")) .append(":</b></td>" + "<td align=\"right\">") .append(_helper.getVersion()) .append("</td></tr>\n" + "<tr title=\"") .append(_("How long we've been running for this session")) .append("\">" + "<td align=\"left\"><b>") .append(_("Uptime")) .append(":</b></td>" + "<td align=\"right\">") .append(_helper.getUptime()) .append("</td></tr></table>\n" + "<hr><h4><a href=\"/config.jsp#help\" target=\"_top\" title=\"") .append(_("Help with configuring your firewall and router for optimal I2P performance")) .append("\">") .append(_helper.getReachability()) .append("</a></h4><hr>\n"); if (_helper.updateAvailable() || _helper.unsignedUpdateAvailable()) { // display all the time so we display the final failure message buf.append("<br>").append(UpdateHandler.getStatus()); if ("true".equals(System.getProperty("net.i2p.router.web.UpdateHandler.updateInProgress"))) { // nothing } else if( // isDone() is always false for now, see UpdateHandler // ((!update.isDone()) && _helper.getAction() == null && _helper.getUpdateNonce() == null && ConfigRestartBean.getRestartTimeRemaining() > 12*60*1000) { long nonce = _context.random().nextLong(); String prev = System.getProperty("net.i2p.router.web.UpdateHandler.nonce"); if (prev != null) System.setProperty("net.i2p.router.web.UpdateHandler.noncePrev", prev); System.setProperty("net.i2p.router.web.UpdateHandler.nonce", nonce+""); String uri = _helper.getRequestURI(); buf.append("<form action=\"").append(uri).append("\" method=\"GET\">\n"); buf.append("<input type=\"hidden\" name=\"updateNonce\" value=\"").append(nonce).append("\" >\n"); if (_helper.updateAvailable()) { buf.append("<button type=\"submit\" name=\"updateAction\" value=\"signed\" >") .append(_("Download")) .append(' ') .append(_helper.getUpdateVersion()) .append(' ') .append(_("Update")) .append("</button>\n"); } if (_helper.unsignedUpdateAvailable()) { buf.append("<button type=\"submit\" name=\"updateAction\" value=\"Unsigned\" >") .append(_("Download Unsigned")) .append("<br>") .append(_("Update")) .append(' ') .append(_helper.getUnsignedUpdateVersion()) .append("</button>\n"); } buf.append("</form>\n"); } } buf.append("<p>") .append(ConfigRestartBean.renderStatus(_helper.getRequestURI(), _helper.getAction(), _helper.getConsoleNonce())) .append("</p><hr><h3><a href=\"/peers.jsp\" target=\"_top\" title=\"") .append(_("Show all current peer connections")) .append("\">") .append(_("Peers")) .append("</a></h3><hr>\n" + "<table>\n" + "<tr><td align=\"left\"><b>") .append(_("Active")) .append(":</b></td><td align=\"right\">") .append(_helper.getActivePeers()) .append('/') .append(_helper.getActiveProfiles()) .append("</td></tr>\n" + "<tr><td align=\"left\"><b>") .append(_("Fast")) .append(":</b></td><td align=\"right\">") .append(_helper.getFastPeers()) .append("</td></tr>\n" + "<tr><td align=\"left\"><b>") .append(_("High capacity")) .append(":</b></td><td align=\"right\">") .append(_helper.getHighCapacityPeers()) .append("</td></tr>\n" + "<tr><td align=\"left\"><b>") .append(_("Integrated")) .append(":</b></td><td align=\"right\">") .append(_helper.getWellIntegratedPeers()) .append("</td></tr>\n" + "<tr><td align=\"left\"><b>") .append(_("Known")) .append(":</b></td><td align=\"right\">") .append(_helper.getAllPeers()) .append("</td></tr>\n" + "</table><hr>\n"); out.write(buf.toString()); buf.setLength(0); boolean anotherLine = false; if (_helper.showFirewallWarning()) { buf.append("<h4><a href=\"/config.jsp\" target=\"_top\" title=\"") .append(_("Help with firewall configuration")) .append("\">") .append(_("Check NAT/firewall")) .append("</a></h4>"); anotherLine = true; } boolean reseedInProgress = Boolean.valueOf(System.getProperty("net.i2p.router.web.ReseedHandler.reseedInProgress")).booleanValue(); // If showing the reseed link is allowed if (_helper.allowReseed()) { if (reseedInProgress) { // While reseed occurring, show status message instead buf.append("<i>").append(System.getProperty("net.i2p.router.web.ReseedHandler.statusMessage","")).append("</i><br>"); } else { // While no reseed occurring, show reseed link long nonce = _context.random().nextLong(); String prev = System.getProperty("net.i2p.router.web.ReseedHandler.nonce"); if (prev != null) System.setProperty("net.i2p.router.web.ReseedHandler.noncePrev", prev); System.setProperty("net.i2p.router.web.ReseedHandler.nonce", nonce+""); String uri = _helper.getRequestURI(); buf.append("<p><form action=\"").append(uri).append("\" method=\"GET\">\n"); buf.append("<input type=\"hidden\" name=\"reseedNonce\" value=\"").append(nonce).append("\" >\n"); buf.append("<button type=\"submit\" value=\"Reseed\" >").append(_("Reseed")).append("</button></form></p>\n"); } anotherLine = true; } // If a new reseed ain't running, and the last reseed had errors, show error message if (!reseedInProgress) { String reseedErrorMessage = System.getProperty("net.i2p.router.web.ReseedHandler.errorMessage",""); if (reseedErrorMessage.length() > 0) { buf.append("<i>").append(reseedErrorMessage).append("</i><br>"); anotherLine = true; } } if (anotherLine) buf.append("<hr>"); buf.append("<h3><a href=\"/config.jsp\" title=\"") .append(_("Configure router bandwidth allocation")) .append("\" target=\"_top\">") .append(_("Bandwidth in/out")) .append("</a></h3><hr>" + "<table>\n" + "<tr><td align=\"left\"><b>1s:</b></td><td align=\"right\">") .append(_helper.getInboundSecondKBps()) .append('/') .append(_helper.getOutboundSecondKBps()) .append("K/s</td></tr>\n" + "<tr><td align=\"left\"><b>5m:</b></td><td align=\"right\">") .append(_helper.getInboundFiveMinuteKBps()) .append('/') .append(_helper.getOutboundFiveMinuteKBps()) .append("K/s</td></tr>\n" + "<tr><td align=\"left\"><b>") .append(_("Total")) .append(":</b></td><td align=\"right\">") .append(_helper.getInboundLifetimeKBps()) .append('/') .append(_helper.getOutboundLifetimeKBps()) .append("K/s</td></tr>\n" + "<tr><td align=\"left\"><b>") .append(_("Used")) .append(":</b></td><td align=\"right\">") .append(_helper.getInboundTransferred()) .append('/') .append(_helper.getOutboundTransferred()) .append("</td></tr></table>\n" + "<hr><h3><a href=\"/tunnels.jsp\" target=\"_top\" title=\"") .append(_("View existing tunnels and tunnel build status")) .append("\">") .append(_("Tunnels in/out")) .append("</a></h3><hr>" + "<table>\n" + "<tr><td align=\"left\"><b>") .append(_("Exploratory")) .append(":</b></td><td align=\"right\">") .append(_helper.getInboundTunnels()) .append('/') .append(_helper.getOutboundTunnels()) .append("</td></tr>\n" + "<tr><td align=\"left\"><b>") .append(_("Client")) .append(":</b></td><td align=\"right\">") .append(_helper.getInboundClientTunnels()) .append('/') .append(_helper.getOutboundClientTunnels()) .append("</td></tr>\n" + "<tr><td align=\"left\"><b>") .append(_("Participating")) .append(":</b></td><td align=\"right\">") .append(_helper.getParticipatingTunnels()) .append("</td></tr>\n" + "</table><hr><h3><a href=\"/jobs.jsp\" target=\"_top\" title=\"") .append(_("What's in the router's job queue?")) .append("\">") .append(_("Congestion")) .append("</a></h3><hr>" + "<table>\n" + "<tr><td align=\"left\"><b>") .append(_("Job lag")) .append(":</b></td><td align=\"right\">") .append(_helper.getJobLag()) .append("</td></tr>\n" + "<tr><td align=\"left\"><b>") .append(_("Message delay")) .append(":</b></td><td align=\"right\">") .append(_helper.getMessageDelay()) .append("</td></tr>\n" + "<tr><td align=\"left\"><b>") .append(_("Tunnel lag")) .append(":</b></td><td align=\"right\">") .append(_helper.getTunnelLag()) .append("</td></tr>\n" + "<tr><td align=\"left\"><b>") .append(_("Backlog")) .append(":</b></td><td align=\"right\">") .append(_helper.getInboundBacklog()) .append("</td></tr>\n" + "</table><hr><h4>") .append(_(_helper.getTunnelStatus())) .append("</h4><hr>\n") .append(_helper.getDestinations()); out.write(buf.toString()); }
public void renderSummaryHTML(Writer out) throws IOException { StringBuilder buf = new StringBuilder(8*1024); buf.append("<a href=\"/index.jsp\" target=\"_top\"><img src=\"/themes/console/images/i2plogo.png\" alt=\"") .append(_("I2P Router Console")) .append("\" title=\"") .append(_("I2P Router Console")) .append("\"></a><hr>"); File lpath = new File(_context.getBaseDir(), "docs/toolbar.html"); // you better have target="_top" for the links in there... if (lpath.exists()) { ContentHelper linkhelper = new ContentHelper(); linkhelper.setPage(lpath.getAbsolutePath()); linkhelper.setMaxLines("100"); buf.append(linkhelper.getContent()); } else { buf.append("<h3><a href=\"/configclients.jsp\" target=\"_top\" title=\"") .append(_("Configure startup of clients and webapps (services); manually start dormant services")) .append("\">") .append(_("I2P Services")) .append("</a></h3>\n" + "<hr><table>" + "<tr><td><a href=\"/susidns/index.jsp\" target=\"_blank\" title=\"") .append(_("Manage your I2P hosts file here (I2P domain name resolution)")) .append("\">") .append(_("Addressbook")) .append("</a>\n" + "<a href=\"/i2psnark/\" target=\"_blank\" title=\"") .append(_("Built-in anonymous BitTorrent Client")) .append("\">") .append(_("Torrents")) .append("</a>\n" + "<a href=\"/susimail/susimail\" target=\"blank\" title=\"") .append(_("Anonymous webmail client")) .append("\">") .append(_("Webmail")) .append("</a>\n" + "<a href=\"http://127.0.0.1:7658/\" target=\"_blank\" title=\"") .append(_("Anonymous resident webserver")) .append("\">") .append(_("Webserver")) .append("</a></td></tr></table>\n" + "<hr><h3><a href=\"/config.jsp\" target=\"_top\" title=\"") .append(_("Configure I2P Router")) .append("\">") .append(_("I2P Internals")) .append("</a></h3><hr>\n" + "<table><tr><td>\n" + "<a href=\"/tunnels.jsp\" target=\"_top\" title=\"") .append(_("View existing tunnels and tunnel build status")) .append("\">") .append(_("Tunnels")) .append("</a>\n" + "<a href=\"/peers.jsp\" target=\"_top\" title=\"") .append(_("Show all current peer connections")) .append("\">") .append(_("Peers")) .append("</a>\n" + "<a href=\"/profiles.jsp\" target=\"_top\" title=\"") .append(_("Show recent peer performance profiles")) .append("\">") .append(_("Profiles")) .append("</a>\n" + "<a href=\"/netdb.jsp\" target=\"_top\" title=\"") .append(_("Show list of all known I2P routers")) .append("\">") .append(_("NetDB")) .append("</a>\n" + "<a href=\"/logs.jsp\" target=\"_top\" title=\"") .append(_("Health Report")) .append("\">") .append(_("Logs")) .append("</a>\n" + "<a href=\"/jobs.jsp\" target=\"_top\" title=\"") .append(_("Show the router's workload, and how it's performing")) .append("\">") .append(_("Jobs")) .append("</a>\n" + "<a href=\"/graphs.jsp\" target=\"_top\" title=\"") .append(_("Graph router performance")) .append("\">") .append(_("Graphs")) .append("</a>\n" + "<a href=\"/stats.jsp\" target=\"_top\" title=\"") .append(_("Textual router performance statistics")) .append("\">") .append(_("Stats")) .append("</a></td></tr></table>\n"); out.write(buf.toString()); buf.setLength(0); } buf.append("<hr><h3><a href=\"/help.jsp\" target=\"_top\" title=\"") .append(_("I2P Router Help")) .append("\">") .append(_("General")) .append("</a></h3><hr>" + "<h4><a title=\"") .append(_("Your unique I2P router identity is")) .append(' ') .append(_helper.getIdent()) .append(", ") .append(_("never reveal it to anyone")) .append("\" href=\"/netdb.jsp?r=.\" target=\"_top\">") .append(_("Local Identity")) .append("</a></h4><hr>\n" + "<table><tr><td align=\"left\">" + "<b>") .append(_("Version")) .append(":</b></td>" + "<td align=\"right\">") .append(_helper.getVersion()) .append("</td></tr>\n" + "<tr title=\"") .append(_("How long we've been running for this session")) .append("\">" + "<td align=\"left\"><b>") .append(_("Uptime")) .append(":</b></td>" + "<td align=\"right\">") .append(_helper.getUptime()) .append("</td></tr></table>\n" + "<hr><h4><a href=\"/config.jsp#help\" target=\"_top\" title=\"") .append(_("Help with configuring your firewall and router for optimal I2P performance")) .append("\">") .append(_helper.getReachability()) .append("</a></h4><hr>\n"); if (_helper.updateAvailable() || _helper.unsignedUpdateAvailable()) { // display all the time so we display the final failure message buf.append(UpdateHandler.getStatus()); if ("true".equals(System.getProperty("net.i2p.router.web.UpdateHandler.updateInProgress"))) { // nothing } else if( // isDone() is always false for now, see UpdateHandler // ((!update.isDone()) && _helper.getAction() == null && _helper.getUpdateNonce() == null && ConfigRestartBean.getRestartTimeRemaining() > 12*60*1000) { long nonce = _context.random().nextLong(); String prev = System.getProperty("net.i2p.router.web.UpdateHandler.nonce"); if (prev != null) System.setProperty("net.i2p.router.web.UpdateHandler.noncePrev", prev); System.setProperty("net.i2p.router.web.UpdateHandler.nonce", nonce+""); String uri = _helper.getRequestURI(); buf.append("<p><form action=\"").append(uri).append("\" method=\"GET\">\n"); buf.append("<input type=\"hidden\" name=\"updateNonce\" value=\"").append(nonce).append("\" >\n"); if (_helper.updateAvailable()) { buf.append("<button type=\"submit\" name=\"updateAction\" value=\"signed\" >") .append(_("Download")) .append(' ') .append(_helper.getUpdateVersion()) .append(' ') .append(_("Update")) .append("</button>\n"); } if (_helper.unsignedUpdateAvailable()) { buf.append("<button type=\"submit\" name=\"updateAction\" value=\"Unsigned\" >") .append(_("Download Unsigned")) .append("<br>") .append(_("Update")) .append(' ') .append(_helper.getUnsignedUpdateVersion()) .append("</button>\n"); } buf.append("</form>\n"); } } buf.append("<p>") .append(ConfigRestartBean.renderStatus(_helper.getRequestURI(), _helper.getAction(), _helper.getConsoleNonce())) .append("</p><hr><h3><a href=\"/peers.jsp\" target=\"_top\" title=\"") .append(_("Show all current peer connections")) .append("\">") .append(_("Peers")) .append("</a></h3><hr>\n" + "<table>\n" + "<tr><td align=\"left\"><b>") .append(_("Active")) .append(":</b></td><td align=\"right\">") .append(_helper.getActivePeers()) .append('/') .append(_helper.getActiveProfiles()) .append("</td></tr>\n" + "<tr><td align=\"left\"><b>") .append(_("Fast")) .append(":</b></td><td align=\"right\">") .append(_helper.getFastPeers()) .append("</td></tr>\n" + "<tr><td align=\"left\"><b>") .append(_("High capacity")) .append(":</b></td><td align=\"right\">") .append(_helper.getHighCapacityPeers()) .append("</td></tr>\n" + "<tr><td align=\"left\"><b>") .append(_("Integrated")) .append(":</b></td><td align=\"right\">") .append(_helper.getWellIntegratedPeers()) .append("</td></tr>\n" + "<tr><td align=\"left\"><b>") .append(_("Known")) .append(":</b></td><td align=\"right\">") .append(_helper.getAllPeers()) .append("</td></tr>\n" + "</table><hr>\n"); out.write(buf.toString()); buf.setLength(0); boolean anotherLine = false; if (_helper.showFirewallWarning()) { buf.append("<h4><a href=\"/config.jsp\" target=\"_top\" title=\"") .append(_("Help with firewall configuration")) .append("\">") .append(_("Check NAT/firewall")) .append("</a></h4>"); anotherLine = true; } boolean reseedInProgress = Boolean.valueOf(System.getProperty("net.i2p.router.web.ReseedHandler.reseedInProgress")).booleanValue(); // If showing the reseed link is allowed if (_helper.allowReseed()) { if (reseedInProgress) { // While reseed occurring, show status message instead buf.append("<i>").append(System.getProperty("net.i2p.router.web.ReseedHandler.statusMessage","")).append("</i><br>"); } else { // While no reseed occurring, show reseed link long nonce = _context.random().nextLong(); String prev = System.getProperty("net.i2p.router.web.ReseedHandler.nonce"); if (prev != null) System.setProperty("net.i2p.router.web.ReseedHandler.noncePrev", prev); System.setProperty("net.i2p.router.web.ReseedHandler.nonce", nonce+""); String uri = _helper.getRequestURI(); buf.append("<p><form action=\"").append(uri).append("\" method=\"GET\">\n"); buf.append("<input type=\"hidden\" name=\"reseedNonce\" value=\"").append(nonce).append("\" >\n"); buf.append("<button type=\"submit\" value=\"Reseed\" >").append(_("Reseed")).append("</button></form></p>\n"); } anotherLine = true; } // If a new reseed ain't running, and the last reseed had errors, show error message if (!reseedInProgress) { String reseedErrorMessage = System.getProperty("net.i2p.router.web.ReseedHandler.errorMessage",""); if (reseedErrorMessage.length() > 0) { buf.append("<i>").append(reseedErrorMessage).append("</i><br>"); anotherLine = true; } } if (anotherLine) buf.append("<hr>"); buf.append("<h3><a href=\"/config.jsp\" title=\"") .append(_("Configure router bandwidth allocation")) .append("\" target=\"_top\">") .append(_("Bandwidth in/out")) .append("</a></h3><hr>" + "<table>\n" + "<tr><td align=\"left\"><b>1s:</b></td><td align=\"right\">") .append(_helper.getInboundSecondKBps()) .append('/') .append(_helper.getOutboundSecondKBps()) .append("K/s</td></tr>\n" + "<tr><td align=\"left\"><b>5m:</b></td><td align=\"right\">") .append(_helper.getInboundFiveMinuteKBps()) .append('/') .append(_helper.getOutboundFiveMinuteKBps()) .append("K/s</td></tr>\n" + "<tr><td align=\"left\"><b>") .append(_("Total")) .append(":</b></td><td align=\"right\">") .append(_helper.getInboundLifetimeKBps()) .append('/') .append(_helper.getOutboundLifetimeKBps()) .append("K/s</td></tr>\n" + "<tr><td align=\"left\"><b>") .append(_("Used")) .append(":</b></td><td align=\"right\">") .append(_helper.getInboundTransferred()) .append('/') .append(_helper.getOutboundTransferred()) .append("</td></tr></table>\n" + "<hr><h3><a href=\"/tunnels.jsp\" target=\"_top\" title=\"") .append(_("View existing tunnels and tunnel build status")) .append("\">") .append(_("Tunnels in/out")) .append("</a></h3><hr>" + "<table>\n" + "<tr><td align=\"left\"><b>") .append(_("Exploratory")) .append(":</b></td><td align=\"right\">") .append(_helper.getInboundTunnels()) .append('/') .append(_helper.getOutboundTunnels()) .append("</td></tr>\n" + "<tr><td align=\"left\"><b>") .append(_("Client")) .append(":</b></td><td align=\"right\">") .append(_helper.getInboundClientTunnels()) .append('/') .append(_helper.getOutboundClientTunnels()) .append("</td></tr>\n" + "<tr><td align=\"left\"><b>") .append(_("Participating")) .append(":</b></td><td align=\"right\">") .append(_helper.getParticipatingTunnels()) .append("</td></tr>\n" + "</table><hr><h3><a href=\"/jobs.jsp\" target=\"_top\" title=\"") .append(_("What's in the router's job queue?")) .append("\">") .append(_("Congestion")) .append("</a></h3><hr>" + "<table>\n" + "<tr><td align=\"left\"><b>") .append(_("Job lag")) .append(":</b></td><td align=\"right\">") .append(_helper.getJobLag()) .append("</td></tr>\n" + "<tr><td align=\"left\"><b>") .append(_("Message delay")) .append(":</b></td><td align=\"right\">") .append(_helper.getMessageDelay()) .append("</td></tr>\n" + "<tr><td align=\"left\"><b>") .append(_("Tunnel lag")) .append(":</b></td><td align=\"right\">") .append(_helper.getTunnelLag()) .append("</td></tr>\n" + "<tr><td align=\"left\"><b>") .append(_("Backlog")) .append(":</b></td><td align=\"right\">") .append(_helper.getInboundBacklog()) .append("</td></tr>\n" + "</table><hr><h4>") .append(_(_helper.getTunnelStatus())) .append("</h4><hr>\n") .append(_helper.getDestinations()); out.write(buf.toString()); }
diff --git a/src/main/java/com/araeosia/ArcherGames/CommandHandler.java b/src/main/java/com/araeosia/ArcherGames/CommandHandler.java index f9bb528..80c0737 100644 --- a/src/main/java/com/araeosia/ArcherGames/CommandHandler.java +++ b/src/main/java/com/araeosia/ArcherGames/CommandHandler.java @@ -1,157 +1,157 @@ package com.araeosia.ArcherGames; import com.araeosia.ArcherGames.utils.Archer; import java.util.HashMap; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerCommandPreprocessEvent; public class CommandHandler implements CommandExecutor, Listener { public ArcherGames plugin; public CommandHandler(ArcherGames plugin) { this.plugin = plugin; } public HashMap<String, Integer> chunkReloads; /** * * @param sender * @param cmd * @param commandLabel * @param args * @return */ @Override public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { if (cmd.getName().equalsIgnoreCase("vote")) { sender.sendMessage(plugin.strings.get("voteinfo")); for (String s : plugin.voteSites) { sender.sendMessage(ChatColor.GREEN + s); return true; } } else if (cmd.getName().equalsIgnoreCase("money")) { if (args.length == 0) { sender.sendMessage(ChatColor.GREEN + sender.getName()+"'s balance is " + plugin.econ.getBalance(sender.getName()) + ""); //Or something return true; } else { sender.sendMessage(ChatColor.GREEN + args[0] + "'s balance is "+plugin.econ.getBalance(args[0])); //Or something return true; } } else if (cmd.getName().equalsIgnoreCase("stats")) { if (args.length == 0) { //plugin.getStats(sender.getName()); return true; } else { //plugin.getStats(args[0]); return true; } } else if (cmd.getName().equalsIgnoreCase("listkits")) { sender.sendMessage(plugin.strings.get("kitinfo")); String kits = ""; for (String s : plugin.kits.keySet()) { kits += s + ", "; } sender.sendMessage(ChatColor.GREEN + kits); } else if (cmd.getName().equalsIgnoreCase("kit") || args.length != 0) { if (plugin.kits.containsKey(args[0])) { if(sender.hasPermission("ArcherGames.kits." + args[0])){ plugin.serverwide.livingPlayers.add(Archer.getByName(sender.getName())); Archer.getByName(sender.getName()).selectKit(args[0]); sender.sendMessage(String.format(plugin.strings.get("kitgivin"), args[0])); return true; } else { sender.sendMessage(ChatColor.RED + "You do not have permission to use this kit."); } } else { sender.sendMessage(ChatColor.RED + "That is not a valid kit."); } } else if(cmd.getName().equalsIgnoreCase("chunk")){ if(!(ScheduledTasks.gameStatus == 1)){ if(sender instanceof Player){ Player player = (Player) sender; player.getWorld().unloadChunk(player.getLocation().getChunk()); player.getWorld().loadChunk(player.getLocation().getChunk()); player.sendMessage(ChatColor.GREEN + "Chunk Reloaded."); } else{ return false; } } else{ return false; } } else if(cmd.getName().equalsIgnoreCase("pay")){ if(args.length != 0){ if(args.length != 1){ try { if(Double.parseDouble(args[1]) > 0){ plugin.econ.takePlayer(sender.getName(), Double.parseDouble(args[1])); plugin.econ.givePlayer(args[0], Double.parseDouble(args[1])); sender.sendMessage(ChatColor.GREEN + "$"+args[0] + " paid to " + args[0]); } } catch(Exception e){ return false; } } else { return false; } } else { return false; } } else if(cmd.getName().equalsIgnoreCase("time")){ - sender.sendMessage(ChatColor.GREEN + (plugin.scheduler.preGameCountdown - plugin.scheduler.currentLoop + " seconds left to game start.")); + sender.sendMessage(ChatColor.GREEN + ((String.format(plugin.strings.get("starttimeleft"), ((plugin.scheduler.preGameCountdown - plugin.scheduler.currentLoop) / 60 + " minute" + (((plugin.scheduler.preGameCountdown - plugin.scheduler.currentLoop) / 60) == 1 ? "" : "s") +", "+((plugin.scheduler.preGameCountdown - plugin.scheduler.currentLoop) % 60) + " second" + ((plugin.scheduler.preGameCountdown - plugin.scheduler.currentLoop != 1) ? "s" : "")))))); } else if(cmd.getName().equalsIgnoreCase("timer")){ if(args.length != 0){ if(sender.hasPermission("ArcherGames.admin")){ try{ plugin.scheduler.preGameCountdown = Integer.parseInt(args[0]); plugin.scheduler.currentLoop = 0; sender.sendMessage(ChatColor.GREEN + "Time left set to " + args[0] + " seconds left."); }catch (Exception e){ sender.sendMessage(ChatColor.RED + "Time could not be set."); } } } } else if (plugin.debug && cmd.getName().equalsIgnoreCase("ArcherGames")) { if (args[0].equalsIgnoreCase("startGame")) { ScheduledTasks.gameStatus = 2; sender.sendMessage(ChatColor.GREEN + "Game started."); plugin.log.info("[ArcherGames/Debug]: Game force-started by " + sender.getName()); return true; } } else if (cmd.getName().equalsIgnoreCase("lockdown")){ if (sender.hasPermission("archergames.admin")){ plugin.getConfig().set("ArcherGames.toggles.lockdownMode", !plugin.configToggles.get("ArcherGames.toggles.lockdownMode")); plugin.saveConfig(); sender.sendMessage(ChatColor.GREEN + "LockDown mode toggled."); return true; }else{ return false; } } return false; } /** * * @param event */ @EventHandler public void onCommandPreProccessEvent(final PlayerCommandPreprocessEvent event) { if (!plugin.serverwide.getArcher(event.getPlayer()).canTalk) { if (!event.getMessage().contains("kit")) { // Needs fixing. event.setCancelled(true); event.getPlayer().sendMessage(plugin.strings.get("nocommand")); } } } }
true
true
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { if (cmd.getName().equalsIgnoreCase("vote")) { sender.sendMessage(plugin.strings.get("voteinfo")); for (String s : plugin.voteSites) { sender.sendMessage(ChatColor.GREEN + s); return true; } } else if (cmd.getName().equalsIgnoreCase("money")) { if (args.length == 0) { sender.sendMessage(ChatColor.GREEN + sender.getName()+"'s balance is " + plugin.econ.getBalance(sender.getName()) + ""); //Or something return true; } else { sender.sendMessage(ChatColor.GREEN + args[0] + "'s balance is "+plugin.econ.getBalance(args[0])); //Or something return true; } } else if (cmd.getName().equalsIgnoreCase("stats")) { if (args.length == 0) { //plugin.getStats(sender.getName()); return true; } else { //plugin.getStats(args[0]); return true; } } else if (cmd.getName().equalsIgnoreCase("listkits")) { sender.sendMessage(plugin.strings.get("kitinfo")); String kits = ""; for (String s : plugin.kits.keySet()) { kits += s + ", "; } sender.sendMessage(ChatColor.GREEN + kits); } else if (cmd.getName().equalsIgnoreCase("kit") || args.length != 0) { if (plugin.kits.containsKey(args[0])) { if(sender.hasPermission("ArcherGames.kits." + args[0])){ plugin.serverwide.livingPlayers.add(Archer.getByName(sender.getName())); Archer.getByName(sender.getName()).selectKit(args[0]); sender.sendMessage(String.format(plugin.strings.get("kitgivin"), args[0])); return true; } else { sender.sendMessage(ChatColor.RED + "You do not have permission to use this kit."); } } else { sender.sendMessage(ChatColor.RED + "That is not a valid kit."); } } else if(cmd.getName().equalsIgnoreCase("chunk")){ if(!(ScheduledTasks.gameStatus == 1)){ if(sender instanceof Player){ Player player = (Player) sender; player.getWorld().unloadChunk(player.getLocation().getChunk()); player.getWorld().loadChunk(player.getLocation().getChunk()); player.sendMessage(ChatColor.GREEN + "Chunk Reloaded."); } else{ return false; } } else{ return false; } } else if(cmd.getName().equalsIgnoreCase("pay")){ if(args.length != 0){ if(args.length != 1){ try { if(Double.parseDouble(args[1]) > 0){ plugin.econ.takePlayer(sender.getName(), Double.parseDouble(args[1])); plugin.econ.givePlayer(args[0], Double.parseDouble(args[1])); sender.sendMessage(ChatColor.GREEN + "$"+args[0] + " paid to " + args[0]); } } catch(Exception e){ return false; } } else { return false; } } else { return false; } } else if(cmd.getName().equalsIgnoreCase("time")){ sender.sendMessage(ChatColor.GREEN + (plugin.scheduler.preGameCountdown - plugin.scheduler.currentLoop + " seconds left to game start.")); } else if(cmd.getName().equalsIgnoreCase("timer")){ if(args.length != 0){ if(sender.hasPermission("ArcherGames.admin")){ try{ plugin.scheduler.preGameCountdown = Integer.parseInt(args[0]); plugin.scheduler.currentLoop = 0; sender.sendMessage(ChatColor.GREEN + "Time left set to " + args[0] + " seconds left."); }catch (Exception e){ sender.sendMessage(ChatColor.RED + "Time could not be set."); } } } } else if (plugin.debug && cmd.getName().equalsIgnoreCase("ArcherGames")) { if (args[0].equalsIgnoreCase("startGame")) { ScheduledTasks.gameStatus = 2; sender.sendMessage(ChatColor.GREEN + "Game started."); plugin.log.info("[ArcherGames/Debug]: Game force-started by " + sender.getName()); return true; } } else if (cmd.getName().equalsIgnoreCase("lockdown")){ if (sender.hasPermission("archergames.admin")){ plugin.getConfig().set("ArcherGames.toggles.lockdownMode", !plugin.configToggles.get("ArcherGames.toggles.lockdownMode")); plugin.saveConfig(); sender.sendMessage(ChatColor.GREEN + "LockDown mode toggled."); return true; }else{ return false; } } return false; }
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { if (cmd.getName().equalsIgnoreCase("vote")) { sender.sendMessage(plugin.strings.get("voteinfo")); for (String s : plugin.voteSites) { sender.sendMessage(ChatColor.GREEN + s); return true; } } else if (cmd.getName().equalsIgnoreCase("money")) { if (args.length == 0) { sender.sendMessage(ChatColor.GREEN + sender.getName()+"'s balance is " + plugin.econ.getBalance(sender.getName()) + ""); //Or something return true; } else { sender.sendMessage(ChatColor.GREEN + args[0] + "'s balance is "+plugin.econ.getBalance(args[0])); //Or something return true; } } else if (cmd.getName().equalsIgnoreCase("stats")) { if (args.length == 0) { //plugin.getStats(sender.getName()); return true; } else { //plugin.getStats(args[0]); return true; } } else if (cmd.getName().equalsIgnoreCase("listkits")) { sender.sendMessage(plugin.strings.get("kitinfo")); String kits = ""; for (String s : plugin.kits.keySet()) { kits += s + ", "; } sender.sendMessage(ChatColor.GREEN + kits); } else if (cmd.getName().equalsIgnoreCase("kit") || args.length != 0) { if (plugin.kits.containsKey(args[0])) { if(sender.hasPermission("ArcherGames.kits." + args[0])){ plugin.serverwide.livingPlayers.add(Archer.getByName(sender.getName())); Archer.getByName(sender.getName()).selectKit(args[0]); sender.sendMessage(String.format(plugin.strings.get("kitgivin"), args[0])); return true; } else { sender.sendMessage(ChatColor.RED + "You do not have permission to use this kit."); } } else { sender.sendMessage(ChatColor.RED + "That is not a valid kit."); } } else if(cmd.getName().equalsIgnoreCase("chunk")){ if(!(ScheduledTasks.gameStatus == 1)){ if(sender instanceof Player){ Player player = (Player) sender; player.getWorld().unloadChunk(player.getLocation().getChunk()); player.getWorld().loadChunk(player.getLocation().getChunk()); player.sendMessage(ChatColor.GREEN + "Chunk Reloaded."); } else{ return false; } } else{ return false; } } else if(cmd.getName().equalsIgnoreCase("pay")){ if(args.length != 0){ if(args.length != 1){ try { if(Double.parseDouble(args[1]) > 0){ plugin.econ.takePlayer(sender.getName(), Double.parseDouble(args[1])); plugin.econ.givePlayer(args[0], Double.parseDouble(args[1])); sender.sendMessage(ChatColor.GREEN + "$"+args[0] + " paid to " + args[0]); } } catch(Exception e){ return false; } } else { return false; } } else { return false; } } else if(cmd.getName().equalsIgnoreCase("time")){ sender.sendMessage(ChatColor.GREEN + ((String.format(plugin.strings.get("starttimeleft"), ((plugin.scheduler.preGameCountdown - plugin.scheduler.currentLoop) / 60 + " minute" + (((plugin.scheduler.preGameCountdown - plugin.scheduler.currentLoop) / 60) == 1 ? "" : "s") +", "+((plugin.scheduler.preGameCountdown - plugin.scheduler.currentLoop) % 60) + " second" + ((plugin.scheduler.preGameCountdown - plugin.scheduler.currentLoop != 1) ? "s" : "")))))); } else if(cmd.getName().equalsIgnoreCase("timer")){ if(args.length != 0){ if(sender.hasPermission("ArcherGames.admin")){ try{ plugin.scheduler.preGameCountdown = Integer.parseInt(args[0]); plugin.scheduler.currentLoop = 0; sender.sendMessage(ChatColor.GREEN + "Time left set to " + args[0] + " seconds left."); }catch (Exception e){ sender.sendMessage(ChatColor.RED + "Time could not be set."); } } } } else if (plugin.debug && cmd.getName().equalsIgnoreCase("ArcherGames")) { if (args[0].equalsIgnoreCase("startGame")) { ScheduledTasks.gameStatus = 2; sender.sendMessage(ChatColor.GREEN + "Game started."); plugin.log.info("[ArcherGames/Debug]: Game force-started by " + sender.getName()); return true; } } else if (cmd.getName().equalsIgnoreCase("lockdown")){ if (sender.hasPermission("archergames.admin")){ plugin.getConfig().set("ArcherGames.toggles.lockdownMode", !plugin.configToggles.get("ArcherGames.toggles.lockdownMode")); plugin.saveConfig(); sender.sendMessage(ChatColor.GREEN + "LockDown mode toggled."); return true; }else{ return false; } } return false; }
diff --git a/trunk/java/com/tigervnc/network/TcpListener.java b/trunk/java/com/tigervnc/network/TcpListener.java index afe80753..d6e92ab9 100644 --- a/trunk/java/com/tigervnc/network/TcpListener.java +++ b/trunk/java/com/tigervnc/network/TcpListener.java @@ -1,167 +1,165 @@ /* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved. * Copyright (C) 2012 Brian P. Hinz * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. */ package com.tigervnc.network; import java.io.IOException; import java.lang.Exception; import java.nio.*; import java.nio.channels.*; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.net.UnknownHostException; import java.util.Set; import java.util.Iterator; public class TcpListener extends SocketListener { public static boolean socketsInitialised = false; public TcpListener(String listenaddr, int port, boolean localhostOnly, SocketDescriptor sock, boolean close_) throws Exception { closeFd = close_; if (sock != null) { fd = sock; return; } TcpSocket.initSockets(); try { channel = ServerSocketChannel.open(); channel.configureBlocking(false); } catch(IOException e) { throw new Exception("unable to create listening socket: "+e.toString()); } // - Bind it to the desired port InetAddress addr = null; try { if (localhostOnly) { addr = InetAddress.getByName(null); } else if (listenaddr != null) { addr = java.net.InetAddress.getByName(listenaddr); } else { - // FIXME: need to be sure we get the wildcard address? - addr = InetAddress.getByName(null); - //addr = InetAddress.getLocalHost(); + addr = InetAddress.getByName("0.0.0.0"); } } catch (UnknownHostException e) { System.out.println(e.toString()); System.exit(-1); } try { channel.socket().bind(new InetSocketAddress(addr, port)); } catch (IOException e) { throw new Exception("unable to bind listening socket: "+e.toString()); } // - Set it to be a listening socket try { selector = Selector.open(); channel.register(selector, SelectionKey.OP_ACCEPT); } catch (IOException e) { throw new Exception("unable to set socket to listening mode: "+e.toString()); } } public TcpListener(String listenaddr, int port) throws Exception { this(listenaddr, port, false, null, true); } // TcpListener::~TcpListener() { // if (closeFd) closesocket(fd); // } public void shutdown() { //shutdown(getFd(), 2); } public TcpSocket accept() { SocketChannel new_sock = null; // Accept an incoming connection try { if (selector.select(0) > 0) { Set keys = selector.selectedKeys(); Iterator iter = keys.iterator(); while (iter.hasNext()) { SelectionKey key = (SelectionKey)iter.next(); iter.remove(); if (key.isAcceptable()) { new_sock = channel.accept(); break; } } keys.clear(); if (new_sock == null) return null; } } catch (IOException e) { throw new SocketException("unable to accept new connection: "+e.toString()); } // Disable Nagle's algorithm, to reduce latency TcpSocket.enableNagles(new_sock, false); // Create the socket object & check connection is allowed SocketDescriptor fd = null; try { fd = new SocketDescriptor(); } catch (java.lang.Exception e) { System.out.println(e.toString()); System.exit(-1); } fd.setChannel(new_sock); TcpSocket s = new TcpSocket(fd); //if (filter && !filter->verifyConnection(s)) { // delete s; // return 0; //} return s; } /* void TcpListener::getMyAddresses(std::list<char*>* result) { const hostent* addrs = gethostbyname(0); if (addrs == 0) throw rdr::SystemException("gethostbyname", errorNumber); if (addrs->h_addrtype != AF_INET) throw rdr::Exception("getMyAddresses: bad family"); for (int i=0; addrs->h_addr_list[i] != 0; i++) { const char* addrC = inet_ntoa(*((struct in_addr*)addrs->h_addr_list[i])); char* addr = new char[strlen(addrC)+1]; strcpy(addr, addrC); result->push_back(addr); } } */ //public int getMyPort() { // return TcpSocket.getSockPort(); //} private boolean closeFd; private ServerSocketChannel channel; private Selector selector; }
true
true
public TcpListener(String listenaddr, int port, boolean localhostOnly, SocketDescriptor sock, boolean close_) throws Exception { closeFd = close_; if (sock != null) { fd = sock; return; } TcpSocket.initSockets(); try { channel = ServerSocketChannel.open(); channel.configureBlocking(false); } catch(IOException e) { throw new Exception("unable to create listening socket: "+e.toString()); } // - Bind it to the desired port InetAddress addr = null; try { if (localhostOnly) { addr = InetAddress.getByName(null); } else if (listenaddr != null) { addr = java.net.InetAddress.getByName(listenaddr); } else { // FIXME: need to be sure we get the wildcard address? addr = InetAddress.getByName(null); //addr = InetAddress.getLocalHost(); } } catch (UnknownHostException e) { System.out.println(e.toString()); System.exit(-1); } try { channel.socket().bind(new InetSocketAddress(addr, port)); } catch (IOException e) { throw new Exception("unable to bind listening socket: "+e.toString()); } // - Set it to be a listening socket try { selector = Selector.open(); channel.register(selector, SelectionKey.OP_ACCEPT); } catch (IOException e) { throw new Exception("unable to set socket to listening mode: "+e.toString()); } }
public TcpListener(String listenaddr, int port, boolean localhostOnly, SocketDescriptor sock, boolean close_) throws Exception { closeFd = close_; if (sock != null) { fd = sock; return; } TcpSocket.initSockets(); try { channel = ServerSocketChannel.open(); channel.configureBlocking(false); } catch(IOException e) { throw new Exception("unable to create listening socket: "+e.toString()); } // - Bind it to the desired port InetAddress addr = null; try { if (localhostOnly) { addr = InetAddress.getByName(null); } else if (listenaddr != null) { addr = java.net.InetAddress.getByName(listenaddr); } else { addr = InetAddress.getByName("0.0.0.0"); } } catch (UnknownHostException e) { System.out.println(e.toString()); System.exit(-1); } try { channel.socket().bind(new InetSocketAddress(addr, port)); } catch (IOException e) { throw new Exception("unable to bind listening socket: "+e.toString()); } // - Set it to be a listening socket try { selector = Selector.open(); channel.register(selector, SelectionKey.OP_ACCEPT); } catch (IOException e) { throw new Exception("unable to set socket to listening mode: "+e.toString()); } }
diff --git a/src/org/odk/collect/android/activities/FormHierarchyActivity.java b/src/org/odk/collect/android/activities/FormHierarchyActivity.java index 568917b..e4ee6d4 100644 --- a/src/org/odk/collect/android/activities/FormHierarchyActivity.java +++ b/src/org/odk/collect/android/activities/FormHierarchyActivity.java @@ -1,503 +1,503 @@ package org.odk.collect.android.activities; import java.util.ArrayList; import java.util.List; import java.util.Vector; import org.javarosa.core.model.FormDef; import org.javarosa.core.model.FormIndex; import org.javarosa.core.model.GroupDef; import org.javarosa.core.model.IFormElement; import org.javarosa.core.model.QuestionDef; import org.javarosa.core.model.data.IAnswerData; import org.javarosa.core.model.instance.TreeElement; import org.javarosa.core.model.instance.TreeReference; import org.javarosa.formmanager.view.FormElementBinding; import org.odk.collect.android.R; import org.odk.collect.android.adapters.HierarchyListAdapter; import org.odk.collect.android.logic.FormHandler; import org.odk.collect.android.logic.HierarchyElement; import android.app.ListActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ListView; import android.widget.Toast; /** * * TODO: WARNING, this file is by no means complete, or correct for that matter. * It is hacky attempt #1 to make a hierarchy viewer by stealing a bunch of * things from formHandler. JavaRosa should give us better methods to accomplish * this (and will in the future...fingers crossed) But until then, we're * trying... * */ public class FormHierarchyActivity extends ListActivity { private static final String t = "FormHierarchyActivity"; FormDef mForm; int state; private static final int CHILD = 1; private static final int EXPANDED = 2; private static final int COLLAPSED = 3; private static final int QUESTION = 4; private final String mIndent = " -- "; private Button mBackButton; private FormIndex mCurrentIndex; List<HierarchyElement> formList; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.hierarchy_layout); // We'll use formhandler to set the CurrentIndex before returning to // FormEntryActivity FormHandler mFormHandler = FormEntryActivity.mFormHandler; mForm = mFormHandler.getForm(); mCurrentIndex = mFormHandler.getIndex(); if (mCurrentIndex.isBeginningOfFormIndex()) { // we always have to start on a valid formIndex mCurrentIndex = mForm.incrementIndex(mCurrentIndex); } mBackButton = (Button) findViewById(R.id.backbutton); mBackButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { Log.e("carl", "clicked back"); mCurrentIndex = stepIndexOut(mCurrentIndex); /* * Log.e("carl", "mCurrentIndex = " + mCurrentIndex); * Log.e("Carl", "local index = " + * mCurrentIndex.getLocalIndex()); Log.e("carl", * "instance index = " + mCurrentIndex.getInstanceIndex()); */ if (mCurrentIndex == null || indexIsBeginning(mCurrentIndex)) { mCurrentIndex = FormIndex.createBeginningOfFormIndex(); mCurrentIndex = mForm.incrementIndex(mCurrentIndex); } else { FormIndex levelTest = mCurrentIndex; int level = 0; while (levelTest.getNextLevel() != null) { level++; levelTest = levelTest.getNextLevel(); } FormIndex tempIndex; boolean done = false; while (!done) { Log.e("carl", "stepping in loop"); tempIndex = mCurrentIndex; int i = 0; while (tempIndex.getNextLevel() != null && i < level) { Log.e("carl", "stepping in next level"); tempIndex = tempIndex.getNextLevel(); i++; } if (tempIndex.getLocalIndex() == 0) { done = true; } else { mCurrentIndex = prevIndex(mCurrentIndex); } // Log.e("carl", "temp instance = " + // tempIndex.getInstanceIndex()); } Log.e("carl", "now showing : " + mCurrentIndex); Log.e("Carl", "now shoing instance index = " + mCurrentIndex.getInstanceIndex()); } refreshView(); // we've already stepped back... // now we just have to refresh, I think } }); Button startButton = (Button) findViewById(R.id.startbutton); startButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { mCurrentIndex = FormIndex.createBeginningOfFormIndex(); FormEntryActivity.mFormHandler.setFormIndex(mCurrentIndex); finish(); } }); Button endButton = (Button) findViewById(R.id.endbutton); endButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { mCurrentIndex = FormIndex.createEndOfFormIndex(); FormEntryActivity.mFormHandler.setFormIndex(mCurrentIndex); finish(); } }); refreshView(); } private boolean indexIsBeginning(FormIndex fi) { String startTest = fi.toString(); int firstComma = startTest.indexOf(","); Log.e("carl", "firstcomma found at " + firstComma); int secondComma = startTest.indexOf(",", firstComma + 1); Log.e("carl", "secondcomma found at " + secondComma); boolean beginning = (secondComma == -1); return beginning; } public void refreshView() { formList = new ArrayList<HierarchyElement>(); FormIndex currentIndex = mCurrentIndex; // would like to use this, but it's broken and changes the currentIndex // TODO: fix in javarosa. /* * FormIndex startTest = stepIndexOut(currentIndex); Log.e("carl", * "starttest = " + startTest); boolean beginning = (startTest == null); */ // begin hack around: boolean beginning = indexIsBeginning(currentIndex); // end hack around String displayGroup = ""; int level = 0; String repeatGroup = "-1"; Log.e("Carl", "just checking at beginnig " + currentIndex); if (!beginning) { FormIndex levelTest = currentIndex; while (levelTest.getNextLevel() != null) { level++; levelTest = levelTest.getNextLevel(); } Log.e("Carl", "level is: " + level); boolean found = false; while (!found) { FormIndex localTest = currentIndex; for (int i = 0; i < level; i++) { localTest = localTest.getNextLevel(); - } + } Log.e("carl", "localtest local = " + localTest.getLocalIndex() + " and instance = " + localTest.getInstanceIndex()); if (localTest.getLocalIndex() == 0) found = true; else currentIndex = prevIndex(currentIndex); } // we're displaying only things only within a given group FormIndex prevIndex = prevIndex(currentIndex); Log.e("Carl", "local = " + prevIndex.getLocalIndex() + " and instance = " + prevIndex.getInstanceIndex()); displayGroup = mForm.getChildInstanceRef(prevIndex).toString(false); Log.e("carl", "display group is: " + displayGroup); mBackButton.setEnabled(true); } else { Log.e("carl", "at beginning"); currentIndex = FormIndex.createBeginningOfFormIndex(); currentIndex = nextRelevantIndex(currentIndex); Log.e("carl", "index is now " + mForm.getChildInstanceRef(currentIndex).toString(false)); Log.e("carl", "index # is " + currentIndex); mBackButton.setEnabled(false); } int repeatIndex = -1; int groupCount = 1; String repeatedGroupName = ""; while (!isEnd(currentIndex)) { FormIndex normalizedLevel = currentIndex; for (int i = 0; i < level; i++) { normalizedLevel = normalizedLevel.getNextLevel(); Log.e("carl", "incrementing normalized level"); } Log.e("carl", "index # is: " + currentIndex + " for: " + mForm.getChildInstanceRef(currentIndex).toString(false)); IFormElement e = mForm.getChild(currentIndex); String currentGroupName = mForm.getChildInstanceRef(currentIndex) .toString(false); // we're displaying only a particular group, and we've reached the // end of that group if (displayGroup.equalsIgnoreCase(currentGroupName)) { break; } // Here we're adding new child elements to a group, or skipping over // elements in the index // that are just members of the current group. if (currentGroupName.startsWith(repeatGroup)) { Log.e("carl", "testing: " + repeatIndex + " against: " + normalizedLevel.getInstanceIndex()); // the last repeated group doesn't exist, so make sure the next // item is still in the group. FormIndex nextIndex = nextRelevantIndex(currentIndex); if (nextIndex.isEndOfFormIndex()) break; String nextIndexName = mForm.getChildInstanceRef(nextIndex) .toString(false); if (repeatIndex != normalizedLevel.getInstanceIndex() && nextIndexName.startsWith(repeatGroup)) { repeatIndex = normalizedLevel.getInstanceIndex(); Log.e("Carl", "adding new group: " + currentGroupName + " in repeat"); HierarchyElement h = formList.get(formList.size() - 1); h .AddChild(new HierarchyElement(mIndent + repeatedGroupName + " " + groupCount++, "", null, CHILD, currentIndex)); } // if it's not a new repeat, we skip it because it's in the // group anyway currentIndex = nextRelevantIndex(currentIndex); continue; } if (e instanceof GroupDef) { GroupDef g = (GroupDef) e; // h += "\t" + g.getLongText() + "\t" + g.getRepeat(); if (g.getRepeat() && !currentGroupName.startsWith(repeatGroup)) { // we have a new repeated group that we haven't seen // before repeatGroup = currentGroupName; repeatIndex = normalizedLevel.getInstanceIndex(); Log.e("carl", "found new repeat: " + repeatGroup + " with instance index: " + repeatIndex); FormIndex nextIndex = nextRelevantIndex(currentIndex); if (nextIndex.isEndOfFormIndex()) break; String nextIndexName = mForm.getChildInstanceRef(nextIndex) .toString(false); // Make sure the next element is in this group, else no // reason to add it if (nextIndexName.startsWith(repeatGroup)) { groupCount = 0; // add the group, but this index is also the first // instance of a // repeat, so add it as a child of the group repeatedGroupName = g.getLongText(); HierarchyElement group = new HierarchyElement( repeatedGroupName, "Repeated Group", getResources().getDrawable( R.drawable.arrow_right_float), COLLAPSED, currentIndex); group.AddChild(new HierarchyElement(mIndent + repeatedGroupName + " " + groupCount++, "", null, CHILD, currentIndex)); formList.add(group); } else { Log.e("Carl", "no children, so skipping"); } currentIndex = nextRelevantIndex(currentIndex); continue; } } else if (e instanceof QuestionDef) { QuestionDef q = (QuestionDef) e; // h += "\t" + q.getLongText(); // Log.e("FHV", h); String answer = ""; FormElementBinding feb = new FormElementBinding(null, currentIndex, mForm); IAnswerData a = feb.getValue(); if (a != null) answer = a.getDisplayText(); formList.add(new HierarchyElement(q.getLongText(), answer, null, QUESTION, currentIndex)); } else { Log.e(t, "we shouldn't get here"); } currentIndex = nextRelevantIndex(currentIndex); } HierarchyListAdapter itla = new HierarchyListAdapter(this); itla.setListItems(formList); setListAdapter(itla); } // used to go 'back', the only problem is this changes whatever it's // referencing public FormIndex stepIndexOut(FormIndex index) { if (index.isTerminal()) { return null; } else { index.setNextLevel(stepIndexOut(index.getNextLevel())); return index; } } private FormIndex prevIndex(FormIndex index) { do { index = mForm.decrementIndex(index); } while (index.isInForm() && !isRelevant(index)); return index; } @Override protected void onListItemClick(ListView l, View v, int position, long id) { HierarchyElement h = (HierarchyElement) l.getItemAtPosition(position); Log.e("carl", "item is " + h.getPrimaryText()); switch (h.getType()) { case EXPANDED: Log.e("carl", "is expanded group, collapsing"); h.setType(COLLAPSED); ArrayList<HierarchyElement> children = h.getChildren(); for (int i = 0; i < children.size(); i++) { formList.remove(position + 1); } h.setIcon(getResources().getDrawable(R.drawable.arrow_right_float)); break; case COLLAPSED: Log.e("carl", "is collapsed group, expanding"); h.setType(EXPANDED); ArrayList<HierarchyElement> children1 = h.getChildren(); for (int i = 0; i < children1.size(); i++) { Log.e("Carl", "adding child: " + children1.get(i).getFormIndex()); formList.add(position + 1 + i, children1.get(i)); } h.setIcon(getResources().getDrawable( android.R.drawable.arrow_down_float)); break; case QUESTION: // Toast.makeText(this, "Question", Toast.LENGTH_SHORT).show(); FormEntryActivity.mFormHandler.setFormIndex(h.getFormIndex()); finish(); return; case CHILD: // Toast.makeText(this, "CHILD", Toast.LENGTH_SHORT).show(); mCurrentIndex = h.getFormIndex(); mCurrentIndex = nextRelevantIndex(mCurrentIndex); Log.e("carl", "clicked index was " + mCurrentIndex); refreshView(); return; } // Should only get here if we've expanded or collapsed a group HierarchyListAdapter itla = new HierarchyListAdapter(this); itla.setListItems(formList); setListAdapter(itla); this.getListView().setSelection(position); } private FormIndex nextRelevantIndex(FormIndex index) { do { index = mForm.incrementIndex(index); } while (index.isInForm() && !isRelevant(index)); return index; } private boolean isRelevant(FormIndex questionIndex) { TreeReference ref = mForm.getChildInstanceRef(questionIndex); boolean isAskNewRepeat = false; Vector<IFormElement> defs = getIndexVector(questionIndex); IFormElement last = (defs.size() == 0 ? null : (IFormElement) defs .lastElement()); if (last instanceof GroupDef && ((GroupDef) last).getRepeat() && mForm.getDataModel().resolveReference( mForm.getChildInstanceRef(questionIndex)) == null) { isAskNewRepeat = true; } boolean relevant; if (isAskNewRepeat) { relevant = mForm.canCreateRepeat(ref); } else { TreeElement node = mForm.getDataModel().resolveReference(ref); relevant = node.isRelevant(); // check instance flag first } if (relevant) { /* * if instance flag/condition says relevant, we still have check the * <group>/<repeat> hierarchy */ FormIndex ancestorIndex = null; FormIndex cur = null; FormIndex qcur = questionIndex; for (int i = 0; i < defs.size() - 1; i++) { FormIndex next = new FormIndex(qcur.getLocalIndex(), qcur .getInstanceIndex()); if (ancestorIndex == null) { ancestorIndex = next; cur = next; } else { cur.setNextLevel(next); cur = next; } qcur = qcur.getNextLevel(); TreeElement ancestorNode = mForm.getDataModel() .resolveReference( mForm.getChildInstanceRef(ancestorIndex)); if (!ancestorNode.isRelevant()) { relevant = false; break; } } } return relevant; } @SuppressWarnings("unchecked") public Vector<IFormElement> getIndexVector(FormIndex index) { return mForm.explodeIndex(index); } public boolean isEnd(FormIndex mCurrentIndex) { if (mCurrentIndex.isEndOfFormIndex()) return true; else return false; } // private boolean indexIsGroup(FormIndex index) { // Vector<IFormElement> defs = getIndexVector(index); // IFormElement last = (defs.size() == 0 ? null : (IFormElement) // defs.lastElement()); // if (last instanceof GroupDef) { // return true; // } else { // return false; // } // } // // // private TreeElement resolveReferenceForCurrentIndex(FormIndex i) { // return // mForm.getDataModel().resolveReference(mForm.getChildInstanceRef(i)); // } }
true
true
public void refreshView() { formList = new ArrayList<HierarchyElement>(); FormIndex currentIndex = mCurrentIndex; // would like to use this, but it's broken and changes the currentIndex // TODO: fix in javarosa. /* * FormIndex startTest = stepIndexOut(currentIndex); Log.e("carl", * "starttest = " + startTest); boolean beginning = (startTest == null); */ // begin hack around: boolean beginning = indexIsBeginning(currentIndex); // end hack around String displayGroup = ""; int level = 0; String repeatGroup = "-1"; Log.e("Carl", "just checking at beginnig " + currentIndex); if (!beginning) { FormIndex levelTest = currentIndex; while (levelTest.getNextLevel() != null) { level++; levelTest = levelTest.getNextLevel(); } Log.e("Carl", "level is: " + level); boolean found = false; while (!found) { FormIndex localTest = currentIndex; for (int i = 0; i < level; i++) { localTest = localTest.getNextLevel(); } Log.e("carl", "localtest local = " + localTest.getLocalIndex() + " and instance = " + localTest.getInstanceIndex()); if (localTest.getLocalIndex() == 0) found = true; else currentIndex = prevIndex(currentIndex); } // we're displaying only things only within a given group FormIndex prevIndex = prevIndex(currentIndex); Log.e("Carl", "local = " + prevIndex.getLocalIndex() + " and instance = " + prevIndex.getInstanceIndex()); displayGroup = mForm.getChildInstanceRef(prevIndex).toString(false); Log.e("carl", "display group is: " + displayGroup); mBackButton.setEnabled(true); } else { Log.e("carl", "at beginning"); currentIndex = FormIndex.createBeginningOfFormIndex(); currentIndex = nextRelevantIndex(currentIndex); Log.e("carl", "index is now " + mForm.getChildInstanceRef(currentIndex).toString(false)); Log.e("carl", "index # is " + currentIndex); mBackButton.setEnabled(false); } int repeatIndex = -1; int groupCount = 1; String repeatedGroupName = ""; while (!isEnd(currentIndex)) { FormIndex normalizedLevel = currentIndex; for (int i = 0; i < level; i++) { normalizedLevel = normalizedLevel.getNextLevel(); Log.e("carl", "incrementing normalized level"); } Log.e("carl", "index # is: " + currentIndex + " for: " + mForm.getChildInstanceRef(currentIndex).toString(false)); IFormElement e = mForm.getChild(currentIndex); String currentGroupName = mForm.getChildInstanceRef(currentIndex) .toString(false); // we're displaying only a particular group, and we've reached the // end of that group if (displayGroup.equalsIgnoreCase(currentGroupName)) { break; } // Here we're adding new child elements to a group, or skipping over // elements in the index // that are just members of the current group. if (currentGroupName.startsWith(repeatGroup)) { Log.e("carl", "testing: " + repeatIndex + " against: " + normalizedLevel.getInstanceIndex()); // the last repeated group doesn't exist, so make sure the next // item is still in the group. FormIndex nextIndex = nextRelevantIndex(currentIndex); if (nextIndex.isEndOfFormIndex()) break; String nextIndexName = mForm.getChildInstanceRef(nextIndex) .toString(false); if (repeatIndex != normalizedLevel.getInstanceIndex() && nextIndexName.startsWith(repeatGroup)) { repeatIndex = normalizedLevel.getInstanceIndex(); Log.e("Carl", "adding new group: " + currentGroupName + " in repeat"); HierarchyElement h = formList.get(formList.size() - 1); h .AddChild(new HierarchyElement(mIndent + repeatedGroupName + " " + groupCount++, "", null, CHILD, currentIndex)); } // if it's not a new repeat, we skip it because it's in the // group anyway currentIndex = nextRelevantIndex(currentIndex); continue; } if (e instanceof GroupDef) { GroupDef g = (GroupDef) e; // h += "\t" + g.getLongText() + "\t" + g.getRepeat(); if (g.getRepeat() && !currentGroupName.startsWith(repeatGroup)) { // we have a new repeated group that we haven't seen // before repeatGroup = currentGroupName; repeatIndex = normalizedLevel.getInstanceIndex(); Log.e("carl", "found new repeat: " + repeatGroup + " with instance index: " + repeatIndex); FormIndex nextIndex = nextRelevantIndex(currentIndex); if (nextIndex.isEndOfFormIndex()) break; String nextIndexName = mForm.getChildInstanceRef(nextIndex) .toString(false); // Make sure the next element is in this group, else no // reason to add it if (nextIndexName.startsWith(repeatGroup)) { groupCount = 0; // add the group, but this index is also the first // instance of a // repeat, so add it as a child of the group repeatedGroupName = g.getLongText(); HierarchyElement group = new HierarchyElement( repeatedGroupName, "Repeated Group", getResources().getDrawable( R.drawable.arrow_right_float), COLLAPSED, currentIndex); group.AddChild(new HierarchyElement(mIndent + repeatedGroupName + " " + groupCount++, "", null, CHILD, currentIndex)); formList.add(group); } else { Log.e("Carl", "no children, so skipping"); } currentIndex = nextRelevantIndex(currentIndex); continue; } } else if (e instanceof QuestionDef) { QuestionDef q = (QuestionDef) e; // h += "\t" + q.getLongText(); // Log.e("FHV", h); String answer = ""; FormElementBinding feb = new FormElementBinding(null, currentIndex, mForm); IAnswerData a = feb.getValue(); if (a != null) answer = a.getDisplayText(); formList.add(new HierarchyElement(q.getLongText(), answer, null, QUESTION, currentIndex)); } else { Log.e(t, "we shouldn't get here"); } currentIndex = nextRelevantIndex(currentIndex); } HierarchyListAdapter itla = new HierarchyListAdapter(this); itla.setListItems(formList); setListAdapter(itla); }
public void refreshView() { formList = new ArrayList<HierarchyElement>(); FormIndex currentIndex = mCurrentIndex; // would like to use this, but it's broken and changes the currentIndex // TODO: fix in javarosa. /* * FormIndex startTest = stepIndexOut(currentIndex); Log.e("carl", * "starttest = " + startTest); boolean beginning = (startTest == null); */ // begin hack around: boolean beginning = indexIsBeginning(currentIndex); // end hack around String displayGroup = ""; int level = 0; String repeatGroup = "-1"; Log.e("Carl", "just checking at beginnig " + currentIndex); if (!beginning) { FormIndex levelTest = currentIndex; while (levelTest.getNextLevel() != null) { level++; levelTest = levelTest.getNextLevel(); } Log.e("Carl", "level is: " + level); boolean found = false; while (!found) { FormIndex localTest = currentIndex; for (int i = 0; i < level; i++) { localTest = localTest.getNextLevel(); } Log.e("carl", "localtest local = " + localTest.getLocalIndex() + " and instance = " + localTest.getInstanceIndex()); if (localTest.getLocalIndex() == 0) found = true; else currentIndex = prevIndex(currentIndex); } // we're displaying only things only within a given group FormIndex prevIndex = prevIndex(currentIndex); Log.e("Carl", "local = " + prevIndex.getLocalIndex() + " and instance = " + prevIndex.getInstanceIndex()); displayGroup = mForm.getChildInstanceRef(prevIndex).toString(false); Log.e("carl", "display group is: " + displayGroup); mBackButton.setEnabled(true); } else { Log.e("carl", "at beginning"); currentIndex = FormIndex.createBeginningOfFormIndex(); currentIndex = nextRelevantIndex(currentIndex); Log.e("carl", "index is now " + mForm.getChildInstanceRef(currentIndex).toString(false)); Log.e("carl", "index # is " + currentIndex); mBackButton.setEnabled(false); } int repeatIndex = -1; int groupCount = 1; String repeatedGroupName = ""; while (!isEnd(currentIndex)) { FormIndex normalizedLevel = currentIndex; for (int i = 0; i < level; i++) { normalizedLevel = normalizedLevel.getNextLevel(); Log.e("carl", "incrementing normalized level"); } Log.e("carl", "index # is: " + currentIndex + " for: " + mForm.getChildInstanceRef(currentIndex).toString(false)); IFormElement e = mForm.getChild(currentIndex); String currentGroupName = mForm.getChildInstanceRef(currentIndex) .toString(false); // we're displaying only a particular group, and we've reached the // end of that group if (displayGroup.equalsIgnoreCase(currentGroupName)) { break; } // Here we're adding new child elements to a group, or skipping over // elements in the index // that are just members of the current group. if (currentGroupName.startsWith(repeatGroup)) { Log.e("carl", "testing: " + repeatIndex + " against: " + normalizedLevel.getInstanceIndex()); // the last repeated group doesn't exist, so make sure the next // item is still in the group. FormIndex nextIndex = nextRelevantIndex(currentIndex); if (nextIndex.isEndOfFormIndex()) break; String nextIndexName = mForm.getChildInstanceRef(nextIndex) .toString(false); if (repeatIndex != normalizedLevel.getInstanceIndex() && nextIndexName.startsWith(repeatGroup)) { repeatIndex = normalizedLevel.getInstanceIndex(); Log.e("Carl", "adding new group: " + currentGroupName + " in repeat"); HierarchyElement h = formList.get(formList.size() - 1); h .AddChild(new HierarchyElement(mIndent + repeatedGroupName + " " + groupCount++, "", null, CHILD, currentIndex)); } // if it's not a new repeat, we skip it because it's in the // group anyway currentIndex = nextRelevantIndex(currentIndex); continue; } if (e instanceof GroupDef) { GroupDef g = (GroupDef) e; // h += "\t" + g.getLongText() + "\t" + g.getRepeat(); if (g.getRepeat() && !currentGroupName.startsWith(repeatGroup)) { // we have a new repeated group that we haven't seen // before repeatGroup = currentGroupName; repeatIndex = normalizedLevel.getInstanceIndex(); Log.e("carl", "found new repeat: " + repeatGroup + " with instance index: " + repeatIndex); FormIndex nextIndex = nextRelevantIndex(currentIndex); if (nextIndex.isEndOfFormIndex()) break; String nextIndexName = mForm.getChildInstanceRef(nextIndex) .toString(false); // Make sure the next element is in this group, else no // reason to add it if (nextIndexName.startsWith(repeatGroup)) { groupCount = 0; // add the group, but this index is also the first // instance of a // repeat, so add it as a child of the group repeatedGroupName = g.getLongText(); HierarchyElement group = new HierarchyElement( repeatedGroupName, "Repeated Group", getResources().getDrawable( R.drawable.arrow_right_float), COLLAPSED, currentIndex); group.AddChild(new HierarchyElement(mIndent + repeatedGroupName + " " + groupCount++, "", null, CHILD, currentIndex)); formList.add(group); } else { Log.e("Carl", "no children, so skipping"); } currentIndex = nextRelevantIndex(currentIndex); continue; } } else if (e instanceof QuestionDef) { QuestionDef q = (QuestionDef) e; // h += "\t" + q.getLongText(); // Log.e("FHV", h); String answer = ""; FormElementBinding feb = new FormElementBinding(null, currentIndex, mForm); IAnswerData a = feb.getValue(); if (a != null) answer = a.getDisplayText(); formList.add(new HierarchyElement(q.getLongText(), answer, null, QUESTION, currentIndex)); } else { Log.e(t, "we shouldn't get here"); } currentIndex = nextRelevantIndex(currentIndex); } HierarchyListAdapter itla = new HierarchyListAdapter(this); itla.setListItems(formList); setListAdapter(itla); }
diff --git a/src/powercrystals/minefactoryreloaded/gui/control/ButtonLogicPinSelect.java b/src/powercrystals/minefactoryreloaded/gui/control/ButtonLogicPinSelect.java index e5034f38..af606695 100644 --- a/src/powercrystals/minefactoryreloaded/gui/control/ButtonLogicPinSelect.java +++ b/src/powercrystals/minefactoryreloaded/gui/control/ButtonLogicPinSelect.java @@ -1,129 +1,129 @@ package powercrystals.minefactoryreloaded.gui.control; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import powercrystals.core.gui.GuiColor; import powercrystals.core.gui.GuiRender; import powercrystals.core.gui.controls.Button; import powercrystals.minefactoryreloaded.gui.client.GuiRedNetLogic; import powercrystals.minefactoryreloaded.MineFactoryReloadedCore; public class ButtonLogicPinSelect extends Button { private static GuiColor[] _pinColors = new GuiColor[] { new GuiColor(223, 223, 223), // white new GuiColor(219, 125, 63), // orange new GuiColor(180, 81, 188), // magenta new GuiColor(107, 138, 207), // light blue new GuiColor(177, 166, 39), // yellow new GuiColor( 66, 174, 57), // lime new GuiColor(208, 132, 153), // pink new GuiColor( 65, 65, 65), // dark gray new GuiColor(155, 155, 155), // light gray new GuiColor( 47, 111, 137), // cyan new GuiColor(127, 62, 182), // purple new GuiColor( 46, 57, 141), // blue new GuiColor( 79, 50, 31), // brown new GuiColor( 53, 71, 28), // green new GuiColor(151, 52, 49), // red new GuiColor( 22, 22, 26), // black }; private static String[] _pinColorNames = new String[] { "WT", "ORNG", "MGTA", "L_BL", "YLLW", "LIME", "PINK", "D_GR", "L_GR", "CYAN", "PURP", "BLUE", "BRWN", "GRN", "RED", "BLK", }; private int _pinIndex; private LogicButtonType _buttonType; private GuiRedNetLogic _containerScreen; private int _pin; private int _buffer; public ButtonLogicPinSelect(GuiRedNetLogic containerScreen, int x, int y, int pinIndex, LogicButtonType buttonType) { super(containerScreen, x, y, 30, 14, ""); _pinIndex = pinIndex; _buttonType = buttonType; _containerScreen = containerScreen; } public int getBuffer() { return _buffer; } public void setBuffer(int buffer) { _buffer = buffer; } public int getPin() { return _pin; } public void setPin(int pin) { _pin = pin; setText(((Integer)_pin).toString()); } @Override public void onClick() { _pin++; if((_buffer == 14 && _pin > 0) || (_buffer == 13 && _pin >= _containerScreen.getVariableCount()) || (_buffer < 13 && _pin > 15)) { _pin = 0; } setText(((Integer)_pin).toString()); if(_buttonType == LogicButtonType.Input) { _containerScreen.setInputPinMapping(_pinIndex, _buffer, _pin); } else { _containerScreen.setOutputPinMapping(_pinIndex, _buffer, _pin); } } @Override public void drawForeground(int mouseX, int mouseY) { if(_buffer < 12) { if(!MineFactoryReloadedCore.colorblindMode.getBoolean(false)) { GuiRender.drawRect(x + 3, y + 3, x + width - 3, y + height - 3, _pinColors[_pin].getColor()); } else { - GuiRender.drawCenteredString(containerScreen.fontRenderer, _pinColorNames[_pin], x + width / 2, y + height / 2 - 6, getTextColor(mouseX, mouseY)); + GuiRender.drawCenteredString(containerScreen.fontRenderer, _pinColorNames[_pin], x + width / 2, y + height / 2 - 4, getTextColor(mouseX, mouseY)); } } else if(_buffer < 14) { super.drawForeground(mouseX, mouseY); } } }
true
true
public void drawForeground(int mouseX, int mouseY) { if(_buffer < 12) { if(!MineFactoryReloadedCore.colorblindMode.getBoolean(false)) { GuiRender.drawRect(x + 3, y + 3, x + width - 3, y + height - 3, _pinColors[_pin].getColor()); } else { GuiRender.drawCenteredString(containerScreen.fontRenderer, _pinColorNames[_pin], x + width / 2, y + height / 2 - 6, getTextColor(mouseX, mouseY)); } } else if(_buffer < 14) { super.drawForeground(mouseX, mouseY); } }
public void drawForeground(int mouseX, int mouseY) { if(_buffer < 12) { if(!MineFactoryReloadedCore.colorblindMode.getBoolean(false)) { GuiRender.drawRect(x + 3, y + 3, x + width - 3, y + height - 3, _pinColors[_pin].getColor()); } else { GuiRender.drawCenteredString(containerScreen.fontRenderer, _pinColorNames[_pin], x + width / 2, y + height / 2 - 4, getTextColor(mouseX, mouseY)); } } else if(_buffer < 14) { super.drawForeground(mouseX, mouseY); } }
diff --git a/mad_schuelerturnier_dataloader/src/main/java/com/googlecode/madschuelerturnier/business/dataloader/CVSMannschaftParser.java b/mad_schuelerturnier_dataloader/src/main/java/com/googlecode/madschuelerturnier/business/dataloader/CVSMannschaftParser.java index 540cd6f4..6439f05c 100644 --- a/mad_schuelerturnier_dataloader/src/main/java/com/googlecode/madschuelerturnier/business/dataloader/CVSMannschaftParser.java +++ b/mad_schuelerturnier_dataloader/src/main/java/com/googlecode/madschuelerturnier/business/dataloader/CVSMannschaftParser.java @@ -1,160 +1,160 @@ package com.googlecode.madschuelerturnier.business.dataloader; import au.com.bytecode.opencsv.CSVReader; import com.google.common.base.Charsets; import com.google.common.io.Resources; import com.googlecode.madschuelerturnier.model.Mannschaft; import com.googlecode.madschuelerturnier.model.enums.GeschlechtEnum; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import java.io.IOException; import java.io.StringReader; import java.net.URL; import java.util.ArrayList; import java.util.List; /** * @author $Author: [email protected] $ * @since 0.7 */ @Component public class CVSMannschaftParser { private static final Logger LOG = Logger.getLogger(CVSMannschaftParser.class); public synchronized List<Mannschaft> loadMannschaften4Jahr(String jahr, Boolean knaben, Integer klasse) { List<Mannschaft> result = new ArrayList<Mannschaft>(); List<Mannschaft> alle = parseFileContent(loadCSVFile(jahr)); if (knaben == null && klasse == null) { return alle; } if (knaben != null) { for (Mannschaft mannschaft : alle) { if (knaben) { if (mannschaft.getGeschlecht() == GeschlechtEnum.K) { result.add(mannschaft); } } else { if (mannschaft.getGeschlecht() == GeschlechtEnum.M) { result.add(mannschaft); } } } alle = result; } if (klasse != null) { for (Mannschaft mannschaft : alle) { if (mannschaft.getKlasse() == klasse) { result.add(mannschaft); } } } return result; } public String loadCSVFile(String jahr) { String text = ""; URL url = Resources.getResource("testmannschaften-orig-" + jahr + ".csv"); try { text = Resources.toString(url, Charsets.UTF_8); } catch (IOException e) { LOG.error(e.getMessage(), e); } return text; } public List<Mannschaft> parseFileContent(String text) { List<Mannschaft> result = new ArrayList<Mannschaft>(); LOG.info("parse: " + text); CSVReader reader = new CSVReader(new StringReader(text), ',', '\"', 1); try { List<String[]> lines = reader.readAll(); for (String[] line : lines) { Mannschaft m = parseLine(line); if (m != null) { result.add(m); } } } catch (IOException e) { LOG.error(e.getMessage(), e); } return result; } - public Mannschaft parseLine(String[] myEntry) { + private Mannschaft parseLine(String[] myEntry) { Long id = null; Mannschaft mann = new Mannschaft(); // 0 Id if (myEntry[0] != null && !"".equals(myEntry[0])) { id = Long.parseLong(myEntry[0]); } // 1 Spieljahr try { mann.setSpielJahr(Integer.parseInt(myEntry[1].trim())); } catch (Exception e) { LOG.error("beim parsen, zeile ohne jahrzahl " + myEntry[1]); return null; } // 3 Captain Name mann.setCaptainName(myEntry[3].trim()); // 4 Captain Telefon mann.setCaptainTelefon(myEntry[4].trim()); // 5 Captain Email mann.setCaptainEmail(myEntry[5].trim()); // 6 Begleitperson Name mann.setBegleitpersonName(myEntry[6].trim()); // 7 Begleitperson Telefon mann.setBegleitpersonTelefon(myEntry[7].trim()); // 8 Begleitperson Email mann.setBegleitpersonEmail(myEntry[8].trim()); // 9 Schulhaus mann.setSchulhaus(myEntry[9].trim()); // 10 M / K if (myEntry[10].equals("K")) { mann.setGeschlecht(GeschlechtEnum.K); } else { mann.setGeschlecht(GeschlechtEnum.M); } // 11 Klasse mann.setKlasse(Integer.parseInt(myEntry[11].trim())); // 12 Klasse Bez. mann.setKlassenBezeichnung(myEntry[12].trim()); // 13 Spieler try { mann.setAnzahlSpieler(Integer.parseInt(myEntry[13].trim())); } catch (Exception e) { mann.setAnzahlSpieler(20); } // 14 Notizen mann.setNotizen(myEntry[14]); if (myEntry.length > 15) { mann.setSpielWunschHint(myEntry[15]); } return mann; } }
true
true
public Mannschaft parseLine(String[] myEntry) { Long id = null; Mannschaft mann = new Mannschaft(); // 0 Id if (myEntry[0] != null && !"".equals(myEntry[0])) { id = Long.parseLong(myEntry[0]); } // 1 Spieljahr try { mann.setSpielJahr(Integer.parseInt(myEntry[1].trim())); } catch (Exception e) { LOG.error("beim parsen, zeile ohne jahrzahl " + myEntry[1]); return null; } // 3 Captain Name mann.setCaptainName(myEntry[3].trim()); // 4 Captain Telefon mann.setCaptainTelefon(myEntry[4].trim()); // 5 Captain Email mann.setCaptainEmail(myEntry[5].trim()); // 6 Begleitperson Name mann.setBegleitpersonName(myEntry[6].trim()); // 7 Begleitperson Telefon mann.setBegleitpersonTelefon(myEntry[7].trim()); // 8 Begleitperson Email mann.setBegleitpersonEmail(myEntry[8].trim()); // 9 Schulhaus mann.setSchulhaus(myEntry[9].trim()); // 10 M / K if (myEntry[10].equals("K")) { mann.setGeschlecht(GeschlechtEnum.K); } else { mann.setGeschlecht(GeschlechtEnum.M); } // 11 Klasse mann.setKlasse(Integer.parseInt(myEntry[11].trim())); // 12 Klasse Bez. mann.setKlassenBezeichnung(myEntry[12].trim()); // 13 Spieler try { mann.setAnzahlSpieler(Integer.parseInt(myEntry[13].trim())); } catch (Exception e) { mann.setAnzahlSpieler(20); } // 14 Notizen mann.setNotizen(myEntry[14]); if (myEntry.length > 15) { mann.setSpielWunschHint(myEntry[15]); } return mann; }
private Mannschaft parseLine(String[] myEntry) { Long id = null; Mannschaft mann = new Mannschaft(); // 0 Id if (myEntry[0] != null && !"".equals(myEntry[0])) { id = Long.parseLong(myEntry[0]); } // 1 Spieljahr try { mann.setSpielJahr(Integer.parseInt(myEntry[1].trim())); } catch (Exception e) { LOG.error("beim parsen, zeile ohne jahrzahl " + myEntry[1]); return null; } // 3 Captain Name mann.setCaptainName(myEntry[3].trim()); // 4 Captain Telefon mann.setCaptainTelefon(myEntry[4].trim()); // 5 Captain Email mann.setCaptainEmail(myEntry[5].trim()); // 6 Begleitperson Name mann.setBegleitpersonName(myEntry[6].trim()); // 7 Begleitperson Telefon mann.setBegleitpersonTelefon(myEntry[7].trim()); // 8 Begleitperson Email mann.setBegleitpersonEmail(myEntry[8].trim()); // 9 Schulhaus mann.setSchulhaus(myEntry[9].trim()); // 10 M / K if (myEntry[10].equals("K")) { mann.setGeschlecht(GeschlechtEnum.K); } else { mann.setGeschlecht(GeschlechtEnum.M); } // 11 Klasse mann.setKlasse(Integer.parseInt(myEntry[11].trim())); // 12 Klasse Bez. mann.setKlassenBezeichnung(myEntry[12].trim()); // 13 Spieler try { mann.setAnzahlSpieler(Integer.parseInt(myEntry[13].trim())); } catch (Exception e) { mann.setAnzahlSpieler(20); } // 14 Notizen mann.setNotizen(myEntry[14]); if (myEntry.length > 15) { mann.setSpielWunschHint(myEntry[15]); } return mann; }
diff --git a/src/com/android/music/MediaPlaybackActivityStarter.java b/src/com/android/music/MediaPlaybackActivityStarter.java index 373c61c..248a5f1 100644 --- a/src/com/android/music/MediaPlaybackActivityStarter.java +++ b/src/com/android/music/MediaPlaybackActivityStarter.java @@ -1,40 +1,41 @@ /* * Copyright (C) 2007 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.music; import android.app.Activity; import android.content.Intent; import android.os.Bundle; public class MediaPlaybackActivityStarter extends Activity { public MediaPlaybackActivityStarter() { } @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); - Intent i = new Intent(this, MediaPlaybackActivity.class); + Intent i = new Intent(getIntent()); + i.setClass(this, MediaPlaybackActivity.class); startActivity(i); finish(); } }
true
true
public void onCreate(Bundle icicle) { super.onCreate(icicle); Intent i = new Intent(this, MediaPlaybackActivity.class); startActivity(i); finish(); }
public void onCreate(Bundle icicle) { super.onCreate(icicle); Intent i = new Intent(getIntent()); i.setClass(this, MediaPlaybackActivity.class); startActivity(i); finish(); }
diff --git a/beanmodeller-maven-plugin/src/main/java/com/coremedia.beanmodeller/processors/doctypegenerator/XSDCopyier.java b/beanmodeller-maven-plugin/src/main/java/com/coremedia.beanmodeller/processors/doctypegenerator/XSDCopyier.java index eea0a93..62c5574 100644 --- a/beanmodeller-maven-plugin/src/main/java/com/coremedia.beanmodeller/processors/doctypegenerator/XSDCopyier.java +++ b/beanmodeller-maven-plugin/src/main/java/com/coremedia.beanmodeller/processors/doctypegenerator/XSDCopyier.java @@ -1,102 +1,103 @@ package com.coremedia.beanmodeller.processors.doctypegenerator; import com.coremedia.beanmodeller.beaninformation.GrammarInformation; import com.coremedia.beanmodeller.maven.PluginException; import com.coremedia.beanmodeller.processors.MavenProcessor; import com.coremedia.beanmodeller.utils.BeanModellerHelper; import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Map; /** * This class copies all XSD found by the marshaller to the path 'lib/xml' of the content server * Telekom .COM Relaunch 2011 * User: marcus * Date: 09.02.11 * Time: 11:51 */ public class XSDCopyier extends MavenProcessor { private String xsdPath; public XSDCopyier(String xsdPath) { this.xsdPath = xsdPath; } public void copyXSD(Map<String, GrammarInformation> schemas) throws DocTypeMarshallerException { if (xsdPath == null) { throw new DocTypeMarshallerException("You must provide a target path for the XSDs"); } if (schemas == null) { throw new DocTypeMarshallerException("You must provide schemas to copy!"); } File targetDir = null; try { targetDir = BeanModellerHelper.getSanitizedDirectory(xsdPath); } catch (PluginException e) { throw new DocTypeMarshallerException("Unable to get target directory", e); } getLog().info("Copying " + schemas.size() + " schemas to " + xsdPath); for (String schemaName : schemas.keySet()) { copySchema(schemas, targetDir, schemaName); } } private void copySchema(Map<String, GrammarInformation> schemas, File targetDir, String schemaName) throws DocTypeMarshallerException { GrammarInformation grammarInformation = schemas.get(schemaName); URL schemaUrl = grammarInformation.getGrammarURL(); + String schemaLocation = grammarInformation.getGrammarLocation(); if (schemaUrl != null && ("file".equals(schemaUrl.getProtocol()) || "jar".equals(schemaUrl.getProtocol()))) { try { String targetFileName; - if (schemaName.startsWith("classpath:")) { - targetFileName = schemaName.substring("classpath:".length()); + if (schemaLocation != null && schemaLocation.startsWith("classpath:")) { + targetFileName = schemaLocation.substring("classpath:".length()); } else { targetFileName = schemaName; } File targetFile = BeanModellerHelper.getSanitizedFile(targetDir, targetFileName); if ("file".equals(schemaUrl.getProtocol())) { File sourceFile = new File(schemaUrl.getPath()); if (sourceFile.length() == 0) { throw new DocTypeMarshallerException("Unable to read " + sourceFile); } getLog().info("Copying " + schemaName + " from " + sourceFile.getAbsolutePath() + " to " + targetFile.getAbsolutePath()); FileUtils.copyFile(sourceFile, targetFile); } else if ("jar".equals(schemaUrl.getProtocol())) { String resourcePath = schemaUrl.getPath(); int resourceNamePosition = resourcePath.lastIndexOf('!'); if (resourceNamePosition < 0) { throw new DocTypeMarshallerException("Unable to determine filename from " + schemaUrl + "."); } String resourceName = resourcePath.substring(resourceNamePosition + 1); getLog().info("Copying " + schemaName + " from classpath " + resourceName + "(" + schemaUrl + ") to " + targetFile.getAbsolutePath()); InputStream resourceStream = getClass().getResourceAsStream(resourceName); if (resourceStream == null) { throw new DocTypeMarshallerException("Unable to open input stream for resource " + resourceName + " from URL " + schemaUrl); } FileUtils.copyInputStreamToFile(resourceStream, targetFile); } } catch (IOException e) { throw new DocTypeMarshallerException("Unable to copy " + schemaUrl + " to " + targetDir, e); } catch (PluginException e) { throw new DocTypeMarshallerException("Unable to copy " + schemaUrl + " to " + targetDir, e); } } else { if (schemaUrl == null) { getLog().warn("Unable to copy " + schemaUrl + " since I the URL is null!"); } else { getLog().warn("Unable to copy " + schemaUrl + " since I cannot handle protocol " + schemaUrl.getProtocol() + "!"); } } } }
false
true
private void copySchema(Map<String, GrammarInformation> schemas, File targetDir, String schemaName) throws DocTypeMarshallerException { GrammarInformation grammarInformation = schemas.get(schemaName); URL schemaUrl = grammarInformation.getGrammarURL(); if (schemaUrl != null && ("file".equals(schemaUrl.getProtocol()) || "jar".equals(schemaUrl.getProtocol()))) { try { String targetFileName; if (schemaName.startsWith("classpath:")) { targetFileName = schemaName.substring("classpath:".length()); } else { targetFileName = schemaName; } File targetFile = BeanModellerHelper.getSanitizedFile(targetDir, targetFileName); if ("file".equals(schemaUrl.getProtocol())) { File sourceFile = new File(schemaUrl.getPath()); if (sourceFile.length() == 0) { throw new DocTypeMarshallerException("Unable to read " + sourceFile); } getLog().info("Copying " + schemaName + " from " + sourceFile.getAbsolutePath() + " to " + targetFile.getAbsolutePath()); FileUtils.copyFile(sourceFile, targetFile); } else if ("jar".equals(schemaUrl.getProtocol())) { String resourcePath = schemaUrl.getPath(); int resourceNamePosition = resourcePath.lastIndexOf('!'); if (resourceNamePosition < 0) { throw new DocTypeMarshallerException("Unable to determine filename from " + schemaUrl + "."); } String resourceName = resourcePath.substring(resourceNamePosition + 1); getLog().info("Copying " + schemaName + " from classpath " + resourceName + "(" + schemaUrl + ") to " + targetFile.getAbsolutePath()); InputStream resourceStream = getClass().getResourceAsStream(resourceName); if (resourceStream == null) { throw new DocTypeMarshallerException("Unable to open input stream for resource " + resourceName + " from URL " + schemaUrl); } FileUtils.copyInputStreamToFile(resourceStream, targetFile); } } catch (IOException e) { throw new DocTypeMarshallerException("Unable to copy " + schemaUrl + " to " + targetDir, e); } catch (PluginException e) { throw new DocTypeMarshallerException("Unable to copy " + schemaUrl + " to " + targetDir, e); } } else { if (schemaUrl == null) { getLog().warn("Unable to copy " + schemaUrl + " since I the URL is null!"); } else { getLog().warn("Unable to copy " + schemaUrl + " since I cannot handle protocol " + schemaUrl.getProtocol() + "!"); } } }
private void copySchema(Map<String, GrammarInformation> schemas, File targetDir, String schemaName) throws DocTypeMarshallerException { GrammarInformation grammarInformation = schemas.get(schemaName); URL schemaUrl = grammarInformation.getGrammarURL(); String schemaLocation = grammarInformation.getGrammarLocation(); if (schemaUrl != null && ("file".equals(schemaUrl.getProtocol()) || "jar".equals(schemaUrl.getProtocol()))) { try { String targetFileName; if (schemaLocation != null && schemaLocation.startsWith("classpath:")) { targetFileName = schemaLocation.substring("classpath:".length()); } else { targetFileName = schemaName; } File targetFile = BeanModellerHelper.getSanitizedFile(targetDir, targetFileName); if ("file".equals(schemaUrl.getProtocol())) { File sourceFile = new File(schemaUrl.getPath()); if (sourceFile.length() == 0) { throw new DocTypeMarshallerException("Unable to read " + sourceFile); } getLog().info("Copying " + schemaName + " from " + sourceFile.getAbsolutePath() + " to " + targetFile.getAbsolutePath()); FileUtils.copyFile(sourceFile, targetFile); } else if ("jar".equals(schemaUrl.getProtocol())) { String resourcePath = schemaUrl.getPath(); int resourceNamePosition = resourcePath.lastIndexOf('!'); if (resourceNamePosition < 0) { throw new DocTypeMarshallerException("Unable to determine filename from " + schemaUrl + "."); } String resourceName = resourcePath.substring(resourceNamePosition + 1); getLog().info("Copying " + schemaName + " from classpath " + resourceName + "(" + schemaUrl + ") to " + targetFile.getAbsolutePath()); InputStream resourceStream = getClass().getResourceAsStream(resourceName); if (resourceStream == null) { throw new DocTypeMarshallerException("Unable to open input stream for resource " + resourceName + " from URL " + schemaUrl); } FileUtils.copyInputStreamToFile(resourceStream, targetFile); } } catch (IOException e) { throw new DocTypeMarshallerException("Unable to copy " + schemaUrl + " to " + targetDir, e); } catch (PluginException e) { throw new DocTypeMarshallerException("Unable to copy " + schemaUrl + " to " + targetDir, e); } } else { if (schemaUrl == null) { getLog().warn("Unable to copy " + schemaUrl + " since I the URL is null!"); } else { getLog().warn("Unable to copy " + schemaUrl + " since I cannot handle protocol " + schemaUrl.getProtocol() + "!"); } } }
diff --git a/src/uk/co/mindtrains/Layout.java b/src/uk/co/mindtrains/Layout.java index 4870091..afb3674 100644 --- a/src/uk/co/mindtrains/Layout.java +++ b/src/uk/co/mindtrains/Layout.java @@ -1,261 +1,261 @@ /* * Copyright (c) 2006 Andy Wood */ package uk.co.mindtrains; import java.awt.Component; import java.awt.Point; import java.awt.Rectangle; import java.awt.datatransfer.UnsupportedFlavorException; import java.awt.dnd.DnDConstants; import java.awt.dnd.DropTarget; import java.awt.dnd.DropTargetDragEvent; import java.awt.dnd.DropTargetDropEvent; import java.awt.dnd.DropTargetEvent; import java.awt.dnd.DropTargetListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionAdapter; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.beans.PropertyDescriptor; import java.io.IOException; import javax.swing.JDesktopPane; import javax.swing.JInternalFrame; import javax.swing.JLayeredPane; import javax.swing.border.LineBorder; import uk.co.mindtrains.Piece.Label; import com.l2fprod.common.propertysheet.DefaultProperty; import com.l2fprod.common.propertysheet.Property; import com.l2fprod.common.propertysheet.PropertyEditorRegistry; import com.l2fprod.common.propertysheet.PropertySheetTableModel; /** * Layout class manages the list of track pieces as the user is * putting it together. */ public class Layout extends JDesktopPane { private static final long serialVersionUID = 1L; private Piece.Label dragging; private Piece.Label main; private Point dragOffset; private Rectangle draggingRect = new Rectangle(); private PropertySheetTableModel model; public Layout( Point start, PropertySheetTableModel m, final PropertyEditorRegistry registry ) { model = m; setLayout( null ); addMouseListener( new MouseAdapter() { public void mousePressed( MouseEvent e ) { Component piece = findComponentAt( e.getPoint() ); if ( piece != null && piece instanceof Piece.Label ) { setDragging( (Piece.Label)piece ); dragOffset = new Point( e.getX() - piece.getX(), e.getY() - piece.getY() ); remove( piece ); dragging.setBorder( LineBorder.createGrayLineBorder() ); add( piece, 0 ); model.setProperties( createProperties( dragging.getPiece().getProperties(), registry ) ); repaint(); } else - dragging = null; + setDragging( null ); } } ); addMouseMotionListener( new MouseMotionAdapter() { public void mouseDragged( MouseEvent e ) { if ( dragging != null ) { dragging.setLocation( e.getX() - (int)dragOffset.getX(), e.getY() - (int)dragOffset.getY() ); snap( dragging ); } } } ); new DropTarget( this, DnDConstants.ACTION_COPY, new DropTargetListener() { public void dragEnter( DropTargetDragEvent dtde ) { dtde.acceptDrag(DnDConstants.ACTION_COPY); add( dragging, JLayeredPane.DRAG_LAYER ); Point location = new Point( dtde.getLocation() ); location.translate( -dragging.getIcon().getIconWidth(), -dragging.getIcon().getIconHeight() ); dragging.setLocation( location ); snap( dragging ); draggingRect.setRect( dragging.getLocation().x, dragging.getLocation().y, dragging.getIcon().getIconWidth(), dragging.getIcon().getIconHeight() ); paintImmediately( draggingRect ); } public void dragOver( DropTargetDragEvent dtde ) { dtde.acceptDrag(DnDConstants.ACTION_COPY); Point location = new Point( dtde.getLocation() ); location.translate( -dragging.getIcon().getIconWidth(), -dragging.getIcon().getIconHeight() ); dragging.setLocation( location ); snap( dragging ); Rectangle newRect = new Rectangle( dragging.getLocation().x, dragging.getLocation().y, dragging.getIcon().getIconWidth(), dragging.getIcon().getIconHeight() ); draggingRect.add( newRect ); paintImmediately( draggingRect ); draggingRect = newRect; } public void dropActionChanged( DropTargetDragEvent dtde ) { dtde.acceptDrag(DnDConstants.ACTION_COPY); } public void dragExit( DropTargetEvent dte ) { remove( dragging ); paintImmediately( draggingRect ); } public void drop( DropTargetDropEvent dtde ) { dtde.acceptDrop( DnDConstants.ACTION_COPY ); remove( dragging ); paintImmediately( draggingRect ); try { Piece piece = (Piece)dtde.getTransferable().getTransferData( IconTransferHandler.NATIVE_FLAVOR ); Point location = new Point( dtde.getLocation() ); location.translate( -piece.getIcon().getIconWidth(), -piece.getIcon().getIconHeight() ); add( piece, location, true ); repaint(); dtde.dropComplete( true ); } catch ( UnsupportedFlavorException e ) { e.printStackTrace(); } catch ( IOException e ) { e.printStackTrace(); } } }, true ); IconTransferHandler.setLayout( this ); } public void setDragging( Piece.Label d ) { if ( dragging != null ) { dragging.setBorder( null ); model.setProperties( new Property[ 0 ] ); } dragging = d; } public Piece.Label add( Piece piece, Point location, boolean snap ) { Piece.Label label = piece.new Label(); label.setLocation( location ); if ( snap ) snap( label ); add( label, 0 ); return label; } public void run( JInternalFrame palette, PropertySheetTableModel model ) { new Run( this, palette, model ); } public void setMain( Label main ) { this.main = main; } public Piece.Label getMain() { return main; } protected void snap( Piece.Label piece ) { Point snap = null; for ( int i = 0; i < getComponentCount(); i++ ) { Component component = getComponent( i ); if ( component != piece && component instanceof Piece.Label ) snap = Piece.closest( ( (Piece.Label)component ).getPiece().snap( piece.getPiece() ), snap, piece.getLocation() ); } if ( snap != null ) piece.setLocation( snap ); } public void save() { try { Saver saver = new Saver( this ); saver.save( "docs/saved.xml" ); } catch ( IOException e ) { e.printStackTrace( System.err ); } } public static Property[] createProperties( final Object object, PropertyEditorRegistry registry ) { if ( object != null ) { try { PropertyDescriptor[] descriptors = Introspector.getBeanInfo( object.getClass(), Object.class ).getPropertyDescriptors(); Property[] properties = new Property[ descriptors.length ]; for ( int i = 0; i < descriptors.length; i++ ) { final DefaultProperty property = new DefaultProperty(); property.setName( descriptors[ i ].getName() ); property.setDisplayName( descriptors[ i ].getDisplayName() ); property.setType( descriptors[ i ].getPropertyType() ); property.readFromObject( object ); property.addPropertyChangeListener( new PropertyChangeListener() { public void propertyChange( PropertyChangeEvent arg0 ) { property.writeToObject( object ); } } ); properties[ i ] = property; } if ( object instanceof Increment.By ) registry.registerEditor( properties[ 0 ], Increment.By.Editor.class ); else if ( object instanceof If.Limit ) registry.registerEditor( properties[ 0 ], If.Limit.Editor.class ); return properties; } catch ( IntrospectionException e ) { e.printStackTrace( System.err ); } } return new Property[ 0 ]; } }
true
true
public Layout( Point start, PropertySheetTableModel m, final PropertyEditorRegistry registry ) { model = m; setLayout( null ); addMouseListener( new MouseAdapter() { public void mousePressed( MouseEvent e ) { Component piece = findComponentAt( e.getPoint() ); if ( piece != null && piece instanceof Piece.Label ) { setDragging( (Piece.Label)piece ); dragOffset = new Point( e.getX() - piece.getX(), e.getY() - piece.getY() ); remove( piece ); dragging.setBorder( LineBorder.createGrayLineBorder() ); add( piece, 0 ); model.setProperties( createProperties( dragging.getPiece().getProperties(), registry ) ); repaint(); } else dragging = null; } } ); addMouseMotionListener( new MouseMotionAdapter() { public void mouseDragged( MouseEvent e ) { if ( dragging != null ) { dragging.setLocation( e.getX() - (int)dragOffset.getX(), e.getY() - (int)dragOffset.getY() ); snap( dragging ); } } } ); new DropTarget( this, DnDConstants.ACTION_COPY, new DropTargetListener() { public void dragEnter( DropTargetDragEvent dtde ) { dtde.acceptDrag(DnDConstants.ACTION_COPY); add( dragging, JLayeredPane.DRAG_LAYER ); Point location = new Point( dtde.getLocation() ); location.translate( -dragging.getIcon().getIconWidth(), -dragging.getIcon().getIconHeight() ); dragging.setLocation( location ); snap( dragging ); draggingRect.setRect( dragging.getLocation().x, dragging.getLocation().y, dragging.getIcon().getIconWidth(), dragging.getIcon().getIconHeight() ); paintImmediately( draggingRect ); } public void dragOver( DropTargetDragEvent dtde ) { dtde.acceptDrag(DnDConstants.ACTION_COPY); Point location = new Point( dtde.getLocation() ); location.translate( -dragging.getIcon().getIconWidth(), -dragging.getIcon().getIconHeight() ); dragging.setLocation( location ); snap( dragging ); Rectangle newRect = new Rectangle( dragging.getLocation().x, dragging.getLocation().y, dragging.getIcon().getIconWidth(), dragging.getIcon().getIconHeight() ); draggingRect.add( newRect ); paintImmediately( draggingRect ); draggingRect = newRect; } public void dropActionChanged( DropTargetDragEvent dtde ) { dtde.acceptDrag(DnDConstants.ACTION_COPY); } public void dragExit( DropTargetEvent dte ) { remove( dragging ); paintImmediately( draggingRect ); } public void drop( DropTargetDropEvent dtde ) { dtde.acceptDrop( DnDConstants.ACTION_COPY ); remove( dragging ); paintImmediately( draggingRect ); try { Piece piece = (Piece)dtde.getTransferable().getTransferData( IconTransferHandler.NATIVE_FLAVOR ); Point location = new Point( dtde.getLocation() ); location.translate( -piece.getIcon().getIconWidth(), -piece.getIcon().getIconHeight() ); add( piece, location, true ); repaint(); dtde.dropComplete( true ); } catch ( UnsupportedFlavorException e ) { e.printStackTrace(); } catch ( IOException e ) { e.printStackTrace(); } } }, true ); IconTransferHandler.setLayout( this ); }
public Layout( Point start, PropertySheetTableModel m, final PropertyEditorRegistry registry ) { model = m; setLayout( null ); addMouseListener( new MouseAdapter() { public void mousePressed( MouseEvent e ) { Component piece = findComponentAt( e.getPoint() ); if ( piece != null && piece instanceof Piece.Label ) { setDragging( (Piece.Label)piece ); dragOffset = new Point( e.getX() - piece.getX(), e.getY() - piece.getY() ); remove( piece ); dragging.setBorder( LineBorder.createGrayLineBorder() ); add( piece, 0 ); model.setProperties( createProperties( dragging.getPiece().getProperties(), registry ) ); repaint(); } else setDragging( null ); } } ); addMouseMotionListener( new MouseMotionAdapter() { public void mouseDragged( MouseEvent e ) { if ( dragging != null ) { dragging.setLocation( e.getX() - (int)dragOffset.getX(), e.getY() - (int)dragOffset.getY() ); snap( dragging ); } } } ); new DropTarget( this, DnDConstants.ACTION_COPY, new DropTargetListener() { public void dragEnter( DropTargetDragEvent dtde ) { dtde.acceptDrag(DnDConstants.ACTION_COPY); add( dragging, JLayeredPane.DRAG_LAYER ); Point location = new Point( dtde.getLocation() ); location.translate( -dragging.getIcon().getIconWidth(), -dragging.getIcon().getIconHeight() ); dragging.setLocation( location ); snap( dragging ); draggingRect.setRect( dragging.getLocation().x, dragging.getLocation().y, dragging.getIcon().getIconWidth(), dragging.getIcon().getIconHeight() ); paintImmediately( draggingRect ); } public void dragOver( DropTargetDragEvent dtde ) { dtde.acceptDrag(DnDConstants.ACTION_COPY); Point location = new Point( dtde.getLocation() ); location.translate( -dragging.getIcon().getIconWidth(), -dragging.getIcon().getIconHeight() ); dragging.setLocation( location ); snap( dragging ); Rectangle newRect = new Rectangle( dragging.getLocation().x, dragging.getLocation().y, dragging.getIcon().getIconWidth(), dragging.getIcon().getIconHeight() ); draggingRect.add( newRect ); paintImmediately( draggingRect ); draggingRect = newRect; } public void dropActionChanged( DropTargetDragEvent dtde ) { dtde.acceptDrag(DnDConstants.ACTION_COPY); } public void dragExit( DropTargetEvent dte ) { remove( dragging ); paintImmediately( draggingRect ); } public void drop( DropTargetDropEvent dtde ) { dtde.acceptDrop( DnDConstants.ACTION_COPY ); remove( dragging ); paintImmediately( draggingRect ); try { Piece piece = (Piece)dtde.getTransferable().getTransferData( IconTransferHandler.NATIVE_FLAVOR ); Point location = new Point( dtde.getLocation() ); location.translate( -piece.getIcon().getIconWidth(), -piece.getIcon().getIconHeight() ); add( piece, location, true ); repaint(); dtde.dropComplete( true ); } catch ( UnsupportedFlavorException e ) { e.printStackTrace(); } catch ( IOException e ) { e.printStackTrace(); } } }, true ); IconTransferHandler.setLayout( this ); }
diff --git a/org.seasar.kijimuna.ui/src/org/seasar/kijimuna/ui/internal/preference/ProjectPreferencePage.java b/org.seasar.kijimuna.ui/src/org/seasar/kijimuna/ui/internal/preference/ProjectPreferencePage.java index 254f186..b9295bf 100644 --- a/org.seasar.kijimuna.ui/src/org/seasar/kijimuna/ui/internal/preference/ProjectPreferencePage.java +++ b/org.seasar.kijimuna.ui/src/org/seasar/kijimuna/ui/internal/preference/ProjectPreferencePage.java @@ -1,211 +1,211 @@ /* * Copyright 2004-2006 the Seasar Foundation and the Others. * * 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.seasar.kijimuna.ui.internal.preference; import java.lang.reflect.InvocationTargetException; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.dialogs.PropertyPage; import org.seasar.kijimuna.core.ConstCore; import org.seasar.kijimuna.core.KijimunaCore; import org.seasar.kijimuna.core.util.PreferencesUtil; import org.seasar.kijimuna.core.util.ProjectUtils; import org.seasar.kijimuna.ui.KijimunaUI; import org.seasar.kijimuna.ui.internal.preference.design.ErrorMarkerDesign; import org.seasar.kijimuna.ui.internal.preference.design.Messages; /** * @author Masataka Kurihara (Gluegent, Inc.) */ public class ProjectPreferencePage extends PropertyPage implements ConstCore { private Button natureCheck; private Button enableProjectCustomSetting; private ErrorMarkerDesign markerDesign; private Composite base; protected Control createContents(Composite parent) { IPreferenceStore store = PreferencesUtil.getPreferenceStoreOfProject(getProject()); setPreferenceStore(store); GridLayout layout = new GridLayout(1, true); layout.marginHeight = 0; layout.marginWidth = 0; parent.setLayout(layout); // nature checkbox natureCheck = new Button(parent, SWT.CHECK | SWT.LEFT); natureCheck.setText(Messages.getString("ProjectPreferencePage.1")); //$NON-NLS-1$ natureCheck.setFont(parent.getFont()); natureCheck.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { handleNatureCheck(); } }); Label separator = new Label(parent, SWT.SEPARATOR | SWT.HORIZONTAL); GridData separatorGd = new GridData(); separatorGd.horizontalAlignment = GridData.FILL; separator.setLayoutData(separatorGd); base = new Composite(parent, SWT.NONE){ public void setEnabled(boolean enabled) { enableProjectCustomSetting.setEnabled(enabled); if(enabled){ markerDesign.setEnabled(enableProjectCustomSetting.getSelection()); }else{ markerDesign.setEnabled(false); } } }; base.setLayout(layout); GridData pgd = new GridData(); pgd.horizontalAlignment = GridData.FILL; pgd.verticalAlignment = GridData.FILL; pgd.grabExcessVerticalSpace = true; pgd.grabExcessHorizontalSpace = true; base.setLayoutData(pgd); enableProjectCustomSetting = new Button(base, SWT.CHECK | SWT.LEFT); - enableProjectCustomSetting.setText("プロジェクト固有の設定を有効にする"); + enableProjectCustomSetting.setText(Messages.getString("ProjectPreferencePage.2")); //$NON-NLS-1$ enableProjectCustomSetting.addSelectionListener(new SelectionAdapter(){ public void widgetSelected(SelectionEvent e) { handleEnableProjectCustomSetting(); } }); Group group = new Group(base, SWT.SHADOW_NONE); group.setLayout(new GridLayout(1, true)); - group.setText("エラーマーカー"); + group.setText(Messages.getString("ErrorMarkerDesign.1")); //$NON-NLS-1$ GridData gd = new GridData(); gd.horizontalAlignment = GridData.FILL; gd.grabExcessHorizontalSpace = true; group.setLayoutData(gd); // error marker markerDesign = new ErrorMarkerDesign(group, SWT.NULL, getPreferenceStore()); markerDesign.setLayoutData(gd); init(); return parent; } private void init() { try { boolean hasNature = getProject().hasNature(ID_NATURE_DICON); natureCheck.setSelection(hasNature); handleNatureCheck(); } catch (CoreException e) { KijimunaUI.reportException(e); } IPreferenceStore store = getPreferenceStore(); boolean projectCustom = store.getBoolean(MARKER_SEVERITY_ENABLE_PROJECT_CUSTOM); enableProjectCustomSetting.setSelection(projectCustom); handleEnableProjectCustomSetting(); } private void handleNatureCheck(){ base.setEnabled(natureCheck.getSelection()); } private void handleEnableProjectCustomSetting() { markerDesign.setEnabled(enableProjectCustomSetting.getSelection()); } private IProject getProject() { return (IProject) getElement(); } public boolean performOk() { applyModification(); cleanupDiconModel(); return true; } protected void performApply() { applyModification(); } private void applyModification() { try { IProject project = getProject(); if (natureCheck.getSelection()) { if (!project.hasNature(ID_NATURE_DICON)) { ProjectUtils.addNature(project, ID_NATURE_DICON); } } else { ProjectUtils.removeNature(project, ID_NATURE_DICON); } IPreferenceStore store = getPreferenceStore(); boolean enablePrjCustom = enableProjectCustomSetting.getSelection(); store.setValue(MARKER_SEVERITY_ENABLE_PROJECT_CUSTOM, enablePrjCustom); markerDesign.store(); } catch (CoreException e) { KijimunaUI.reportException(e); } } protected void performDefaults() { if (natureCheck.getSelection()) { markerDesign.loadDefault(); boolean b = getPreferenceStore().getDefaultBoolean(MARKER_SEVERITY_ENABLE_PROJECT_CUSTOM); enableProjectCustomSetting.setSelection(b); handleEnableProjectCustomSetting(); } } private void cleanupDiconModel() { IRunnableWithProgress runnable = new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { KijimunaCore.getProjectRecorder().cleanup(getProject(), monitor); } }; IWorkbenchWindow w = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); try { if (w != null) { w.run(true, true, runnable); } } catch (InvocationTargetException e) { KijimunaCore.reportException(e); } catch (InterruptedException e) { KijimunaCore.reportException(e); } } }
false
true
protected Control createContents(Composite parent) { IPreferenceStore store = PreferencesUtil.getPreferenceStoreOfProject(getProject()); setPreferenceStore(store); GridLayout layout = new GridLayout(1, true); layout.marginHeight = 0; layout.marginWidth = 0; parent.setLayout(layout); // nature checkbox natureCheck = new Button(parent, SWT.CHECK | SWT.LEFT); natureCheck.setText(Messages.getString("ProjectPreferencePage.1")); //$NON-NLS-1$ natureCheck.setFont(parent.getFont()); natureCheck.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { handleNatureCheck(); } }); Label separator = new Label(parent, SWT.SEPARATOR | SWT.HORIZONTAL); GridData separatorGd = new GridData(); separatorGd.horizontalAlignment = GridData.FILL; separator.setLayoutData(separatorGd); base = new Composite(parent, SWT.NONE){ public void setEnabled(boolean enabled) { enableProjectCustomSetting.setEnabled(enabled); if(enabled){ markerDesign.setEnabled(enableProjectCustomSetting.getSelection()); }else{ markerDesign.setEnabled(false); } } }; base.setLayout(layout); GridData pgd = new GridData(); pgd.horizontalAlignment = GridData.FILL; pgd.verticalAlignment = GridData.FILL; pgd.grabExcessVerticalSpace = true; pgd.grabExcessHorizontalSpace = true; base.setLayoutData(pgd); enableProjectCustomSetting = new Button(base, SWT.CHECK | SWT.LEFT); enableProjectCustomSetting.setText("プロジェクト固有の設定を有効にする"); enableProjectCustomSetting.addSelectionListener(new SelectionAdapter(){ public void widgetSelected(SelectionEvent e) { handleEnableProjectCustomSetting(); } }); Group group = new Group(base, SWT.SHADOW_NONE); group.setLayout(new GridLayout(1, true)); group.setText("エラーマーカー"); GridData gd = new GridData(); gd.horizontalAlignment = GridData.FILL; gd.grabExcessHorizontalSpace = true; group.setLayoutData(gd); // error marker markerDesign = new ErrorMarkerDesign(group, SWT.NULL, getPreferenceStore()); markerDesign.setLayoutData(gd); init(); return parent; }
protected Control createContents(Composite parent) { IPreferenceStore store = PreferencesUtil.getPreferenceStoreOfProject(getProject()); setPreferenceStore(store); GridLayout layout = new GridLayout(1, true); layout.marginHeight = 0; layout.marginWidth = 0; parent.setLayout(layout); // nature checkbox natureCheck = new Button(parent, SWT.CHECK | SWT.LEFT); natureCheck.setText(Messages.getString("ProjectPreferencePage.1")); //$NON-NLS-1$ natureCheck.setFont(parent.getFont()); natureCheck.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { handleNatureCheck(); } }); Label separator = new Label(parent, SWT.SEPARATOR | SWT.HORIZONTAL); GridData separatorGd = new GridData(); separatorGd.horizontalAlignment = GridData.FILL; separator.setLayoutData(separatorGd); base = new Composite(parent, SWT.NONE){ public void setEnabled(boolean enabled) { enableProjectCustomSetting.setEnabled(enabled); if(enabled){ markerDesign.setEnabled(enableProjectCustomSetting.getSelection()); }else{ markerDesign.setEnabled(false); } } }; base.setLayout(layout); GridData pgd = new GridData(); pgd.horizontalAlignment = GridData.FILL; pgd.verticalAlignment = GridData.FILL; pgd.grabExcessVerticalSpace = true; pgd.grabExcessHorizontalSpace = true; base.setLayoutData(pgd); enableProjectCustomSetting = new Button(base, SWT.CHECK | SWT.LEFT); enableProjectCustomSetting.setText(Messages.getString("ProjectPreferencePage.2")); //$NON-NLS-1$ enableProjectCustomSetting.addSelectionListener(new SelectionAdapter(){ public void widgetSelected(SelectionEvent e) { handleEnableProjectCustomSetting(); } }); Group group = new Group(base, SWT.SHADOW_NONE); group.setLayout(new GridLayout(1, true)); group.setText(Messages.getString("ErrorMarkerDesign.1")); //$NON-NLS-1$ GridData gd = new GridData(); gd.horizontalAlignment = GridData.FILL; gd.grabExcessHorizontalSpace = true; group.setLayoutData(gd); // error marker markerDesign = new ErrorMarkerDesign(group, SWT.NULL, getPreferenceStore()); markerDesign.setLayoutData(gd); init(); return parent; }
diff --git a/query/src/main/java/org/infinispan/query/clustered/ISPNPriorityQueueFactory.java b/query/src/main/java/org/infinispan/query/clustered/ISPNPriorityQueueFactory.java index 9c91993ebe..af1693a5b0 100644 --- a/query/src/main/java/org/infinispan/query/clustered/ISPNPriorityQueueFactory.java +++ b/query/src/main/java/org/infinispan/query/clustered/ISPNPriorityQueueFactory.java @@ -1,119 +1,119 @@ /* * JBoss, Home of Professional Open Source. * Copyright 2011, 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.infinispan.query.clustered; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import org.apache.lucene.search.FieldDoc; import org.apache.lucene.search.SortField; import org.apache.lucene.util.PriorityQueue; import org.hibernate.search.SearchException; import org.infinispan.util.ReflectionUtil; /** * ISPNPriorityQueueFactory. * * Factory to construct a lucene PriotityQueue (unfortunately not public classes) * * @author Israel Lacerra <[email protected]> * @author Sanne Grinovero <[email protected]> (C) 2011 Red Hat Inc. * @since 5.1 */ class ISPNPriorityQueueFactory { private ISPNPriorityQueueFactory() { } /** * Creates a org.apache.lucene.search.FieldDocSortedHitQueue instance and set the size and sort * fields * * @param size * @param sort * @return a PriorityQueue<FieldDoc> instance */ public static PriorityQueue<FieldDoc> getFieldDocSortedHitQueue(int size, SortField[] sort) { String className = "org.apache.lucene.search.FieldDocSortedHitQueue"; Object[] constructorArgument = new Object[]{ size }; Class[] types = new Class[]{ int.class }; PriorityQueue<FieldDoc> queue = buildPriorityQueueSafe(className, types, constructorArgument); Method[] methods = queue.getClass().getDeclaredMethods(); - for(Method method : methods){ - if(method.getName().equals("setFields")){ - Object[] parameters = new Object[1]; - parameters[0] = sort; - ReflectionUtil.invokeAccessibly(queue, method, parameters); - } + for (Method method : methods) { + if (method.getName().equals("setFields")) { + Object[] parameters = new Object[1]; + parameters[0] = sort; + ReflectionUtil.invokeAccessibly(queue, method, parameters); + } } return queue; } /** * Creates a org.apache.lucene.search.HitQueue instance and set the size * * @param size * @param sort * @return a PriorityQueue<FieldDoc> instance */ public static PriorityQueue<FieldDoc> getHitQueue(int size) { String className = "org.apache.lucene.search.HitQueue"; Object[] constructorArgument = new Object[]{ size, false }; Class[] types = new Class[]{ int.class, boolean.class }; return buildPriorityQueueSafe(className, types, constructorArgument); } /** * @param className fully qualified name of the class to construct * @param types types of the constructor to use * @param constructorArgument arguments for the chosen constructor */ private static PriorityQueue<FieldDoc> buildPriorityQueueSafe(String className, Class[] types, Object[] constructorArgument) { try { return buildPriorityQueue(className, types, constructorArgument); } catch (Exception e) { throw new SearchException("Could not initialize required Lucene class: " + className + ". Either the Lucene version is incompatible, or security is preventing me to access it.", e); } } /** * Creates a class instance from classname, types and arguments, to workaround the * fact that these Lucene PriorityQueues are not public. * @param className * @param types * @param constructorArgument */ private static PriorityQueue<FieldDoc> buildPriorityQueue(String className, Class[] types, java.lang.Object[] constructorArgument) throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException { Class<?> clazz = Class.forName(className); Constructor c = clazz.getDeclaredConstructor(types); c.setAccessible(true); Object newInstance = c.newInstance(constructorArgument); return (PriorityQueue<FieldDoc>) newInstance; } }
true
true
public static PriorityQueue<FieldDoc> getFieldDocSortedHitQueue(int size, SortField[] sort) { String className = "org.apache.lucene.search.FieldDocSortedHitQueue"; Object[] constructorArgument = new Object[]{ size }; Class[] types = new Class[]{ int.class }; PriorityQueue<FieldDoc> queue = buildPriorityQueueSafe(className, types, constructorArgument); Method[] methods = queue.getClass().getDeclaredMethods(); for(Method method : methods){ if(method.getName().equals("setFields")){ Object[] parameters = new Object[1]; parameters[0] = sort; ReflectionUtil.invokeAccessibly(queue, method, parameters); } } return queue; }
public static PriorityQueue<FieldDoc> getFieldDocSortedHitQueue(int size, SortField[] sort) { String className = "org.apache.lucene.search.FieldDocSortedHitQueue"; Object[] constructorArgument = new Object[]{ size }; Class[] types = new Class[]{ int.class }; PriorityQueue<FieldDoc> queue = buildPriorityQueueSafe(className, types, constructorArgument); Method[] methods = queue.getClass().getDeclaredMethods(); for (Method method : methods) { if (method.getName().equals("setFields")) { Object[] parameters = new Object[1]; parameters[0] = sort; ReflectionUtil.invokeAccessibly(queue, method, parameters); } } return queue; }
diff --git a/Tron/src/com/tfuruya/tron/TronGame.java b/Tron/src/com/tfuruya/tron/TronGame.java index 905bae7..3b8dc64 100644 --- a/Tron/src/com/tfuruya/tron/TronGame.java +++ b/Tron/src/com/tfuruya/tron/TronGame.java @@ -1,68 +1,70 @@ package com.tfuruya.tron; public class TronGame { private int numPlayer; public TronGame(int player) { player = numPlayer; } public TronData update(TronData data, TronAction[] action) { int x[] = new int[numPlayer]; int y[] = new int[numPlayer]; for (int i=0; i<numPlayer; i++) { // Initialize x, y x[i] = data.getX()[i]; y[i] = data.getY()[i]; // If dead, don't move if (data.isDead(i)) continue; // Update to new point according to given action switch (action[i].get()) { case TronAction.LEFT: { x[i] --; break; } case TronAction.UP: { y[i] --; break; } case TronAction.RIGHT: { x[i] ++; break; } case TronAction.DOWN: { y[i] ++; break; } } // evaluate new point if (!data.isValid(x[i], y[i])) { data.setDead(i); } } // modify data if (!data.isGameOver) { for (int j=0; j<numPlayer; j++) { - data.occupyNewPoint(x[j], y[j], action[j], j); + if (!data.isDead(j)) { + data.occupyNewPoint(x[j], y[j], action[j], j); + } } } return data; } // Called at beginning of every game public void reset(TronData data, int player) { numPlayer = player; } }
true
true
public TronData update(TronData data, TronAction[] action) { int x[] = new int[numPlayer]; int y[] = new int[numPlayer]; for (int i=0; i<numPlayer; i++) { // Initialize x, y x[i] = data.getX()[i]; y[i] = data.getY()[i]; // If dead, don't move if (data.isDead(i)) continue; // Update to new point according to given action switch (action[i].get()) { case TronAction.LEFT: { x[i] --; break; } case TronAction.UP: { y[i] --; break; } case TronAction.RIGHT: { x[i] ++; break; } case TronAction.DOWN: { y[i] ++; break; } } // evaluate new point if (!data.isValid(x[i], y[i])) { data.setDead(i); } } // modify data if (!data.isGameOver) { for (int j=0; j<numPlayer; j++) { data.occupyNewPoint(x[j], y[j], action[j], j); } } return data; }
public TronData update(TronData data, TronAction[] action) { int x[] = new int[numPlayer]; int y[] = new int[numPlayer]; for (int i=0; i<numPlayer; i++) { // Initialize x, y x[i] = data.getX()[i]; y[i] = data.getY()[i]; // If dead, don't move if (data.isDead(i)) continue; // Update to new point according to given action switch (action[i].get()) { case TronAction.LEFT: { x[i] --; break; } case TronAction.UP: { y[i] --; break; } case TronAction.RIGHT: { x[i] ++; break; } case TronAction.DOWN: { y[i] ++; break; } } // evaluate new point if (!data.isValid(x[i], y[i])) { data.setDead(i); } } // modify data if (!data.isGameOver) { for (int j=0; j<numPlayer; j++) { if (!data.isDead(j)) { data.occupyNewPoint(x[j], y[j], action[j], j); } } } return data; }
diff --git a/ExtensibleCoreServer/src/main/java/es/gob/catastro/service/core/aop/LoggerInterceptor.java b/ExtensibleCoreServer/src/main/java/es/gob/catastro/service/core/aop/LoggerInterceptor.java index d53eb51..b25cc51 100644 --- a/ExtensibleCoreServer/src/main/java/es/gob/catastro/service/core/aop/LoggerInterceptor.java +++ b/ExtensibleCoreServer/src/main/java/es/gob/catastro/service/core/aop/LoggerInterceptor.java @@ -1,32 +1,32 @@ package es.gob.catastro.service.core.aop; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; @Aspect public class LoggerInterceptor { private static final Log log = LogFactory.getLog(LoggerInterceptor.class); @Around("this(java.rmi.Remote)") public Object executeCall(ProceedingJoinPoint pjp) throws Throwable { String call = pjp.getTarget().getClass().getName()+"."+pjp.getSignature().getName(); log.debug("CALL: " + call); try { long ini = System.currentTimeMillis(); Object obj = pjp.proceed(); long fin = System.currentTimeMillis(); log.info("OK: " + call+" duracion llamada (mseg): "+(fin-ini)); return obj; - } catch (Exception ex) { + } catch (Throwable ex) { log.info("ERR: " + call, ex); - return ex; + throw ex; } } }
false
true
public Object executeCall(ProceedingJoinPoint pjp) throws Throwable { String call = pjp.getTarget().getClass().getName()+"."+pjp.getSignature().getName(); log.debug("CALL: " + call); try { long ini = System.currentTimeMillis(); Object obj = pjp.proceed(); long fin = System.currentTimeMillis(); log.info("OK: " + call+" duracion llamada (mseg): "+(fin-ini)); return obj; } catch (Exception ex) { log.info("ERR: " + call, ex); return ex; } }
public Object executeCall(ProceedingJoinPoint pjp) throws Throwable { String call = pjp.getTarget().getClass().getName()+"."+pjp.getSignature().getName(); log.debug("CALL: " + call); try { long ini = System.currentTimeMillis(); Object obj = pjp.proceed(); long fin = System.currentTimeMillis(); log.info("OK: " + call+" duracion llamada (mseg): "+(fin-ini)); return obj; } catch (Throwable ex) { log.info("ERR: " + call, ex); throw ex; } }
diff --git a/src/com/ichi2/anki/Lookup.java b/src/com/ichi2/anki/Lookup.java index cc013aed..7e7647cc 100644 --- a/src/com/ichi2/anki/Lookup.java +++ b/src/com/ichi2/anki/Lookup.java @@ -1,183 +1,183 @@ package com.ichi2.anki; import com.ichi2.themes.StyledDialog; import com.tomgibara.android.veecheck.util.PrefSettings; import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.util.Log; public class Lookup { /** * Searches */ private static final int DICTIONARY_AEDICT = 0; private static final int DICTIONARY_EIJIRO_WEB = 1; // japanese web dictionary private static final int DICTIONARY_LEO_WEB = 2; // German web dictionary for English, French, Spanish, Italian, Chinese, Russian private static final int DICTIONARY_LEO_APP = 3; // German web dictionary for English, French, Spanish, Italian, Chinese, Russian private static final int DICTIONARY_COLORDICT = 4; private static final int DICTIONARY_FORA = 5; private static final int DICTIONARY_NCIKU_WEB = 6; // chinese web dictionary private static Context mContext; private static boolean mIsDictionaryAvailable; private static String mDictionaryAction; private static int mDictionary; private static String mLookupText; private static String mDeckFilename; private static Card mCurrentCard; public static boolean initialize(Context context, String deckFilename) { mContext = context; mDeckFilename = deckFilename; int customDictionary = MetaDB.getLookupDictionary(context, mDeckFilename); if (customDictionary != -1) { mDictionary = customDictionary; } else { SharedPreferences preferences = PrefSettings.getSharedPrefs(AnkiDroidApp.getInstance().getBaseContext()); mDictionary = Integer.parseInt( preferences.getString("dictionary", Integer.toString(DICTIONARY_COLORDICT))); } switch (mDictionary) { case DICTIONARY_AEDICT: mDictionaryAction = "sk.baka.aedict.action.ACTION_SEARCH_EDICT"; mIsDictionaryAvailable = Utils.isIntentAvailable(mContext, mDictionaryAction); break; case DICTIONARY_LEO_WEB: case DICTIONARY_NCIKU_WEB: case DICTIONARY_EIJIRO_WEB: mDictionaryAction = "android.intent.action.VIEW"; mIsDictionaryAvailable = Utils.isIntentAvailable(mContext, mDictionaryAction); break; case DICTIONARY_LEO_APP: mDictionaryAction = "android.intent.action.SEND"; mIsDictionaryAvailable = Utils.isIntentAvailable(mContext, mDictionaryAction, new ComponentName("org.leo.android.dict", "org.leo.android.dict.LeoDict")); break; case DICTIONARY_COLORDICT: mDictionaryAction = "colordict.intent.action.SEARCH"; mIsDictionaryAvailable = Utils.isIntentAvailable(mContext, mDictionaryAction); break; case DICTIONARY_FORA: mDictionaryAction = "com.ngc.fora.action.LOOKUP"; mIsDictionaryAvailable = Utils.isIntentAvailable(mContext, mDictionaryAction); break; default: mIsDictionaryAvailable = false; break; } Log.i(AnkiDroidApp.TAG, "Is intent available = " + mIsDictionaryAvailable); return mIsDictionaryAvailable; } public static boolean lookUp(String text, Card card) { mCurrentCard = card; // clear text from leading and closing dots, commas, brackets etc. text = text.trim().replaceAll("[,;:\\s\\(\\[\\)\\]\\.]*$", "").replaceAll("^[,;:\\s\\(\\[\\)\\]\\.]*", ""); switch (mDictionary) { case DICTIONARY_AEDICT: Intent aedictSearchIntent = new Intent(mDictionaryAction); aedictSearchIntent.putExtra("kanjis", text); mContext.startActivity(aedictSearchIntent); return true; case DICTIONARY_LEO_WEB: case DICTIONARY_LEO_APP: mLookupText = text; // localisation is needless here since leo.org translates only into or out of German final CharSequence[] itemValues = {"en", "fr", "es", "it", "ch", "ru"}; String language = getLanguage(MetaDB.LANGUAGES_QA_UNDEFINED); if (language.length() > 0) { for (int i = 0; i < itemValues.length; i++) { if (language.equals(itemValues[i])) { lookupLeo(language, mLookupText); mLookupText = ""; return true; } } } - final String[] items = {"Englisch", "Französisch", "Spanisch", "Italienisch", "Chinesisch", "Russisch"}; + final String[] items = {"Englisch", "Franz�sisch", "Spanisch", "Italienisch", "Chinesisch", "Russisch"}; StyledDialog.Builder builder = new StyledDialog.Builder(mContext); builder.setTitle("\"" + mLookupText + "\" nachschlagen"); builder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { String language = itemValues[item].toString(); storeLanguage(language, MetaDB.LANGUAGES_QA_UNDEFINED); lookupLeo(language, mLookupText); mLookupText = ""; } }); StyledDialog alert = builder.create(); alert.show(); return true; case DICTIONARY_COLORDICT: Intent colordictSearchIntent = new Intent(mDictionaryAction); colordictSearchIntent.putExtra("EXTRA_QUERY", text); mContext.startActivity(colordictSearchIntent); return true; case DICTIONARY_FORA: Intent foraSearchIntent = new Intent(mDictionaryAction); foraSearchIntent.putExtra("HEADWORD", text.trim()); mContext.startActivity(foraSearchIntent); return true; case DICTIONARY_NCIKU_WEB: Intent ncikuWebIntent = new Intent(mDictionaryAction, Uri.parse("http://m.nciku.com/en/entry/?query=" + text)); mContext.startActivity(ncikuWebIntent); return true; case DICTIONARY_EIJIRO_WEB: Intent eijiroWebIntent = new Intent(mDictionaryAction, Uri.parse("http://eow.alc.co.jp/" + text)); mContext.startActivity(eijiroWebIntent); return true; } return false; } private static void lookupLeo(String language, CharSequence text) { switch(mDictionary) { case DICTIONARY_LEO_WEB: Intent leoSearchIntent = new Intent(mDictionaryAction, Uri.parse("http://pda.leo.org/?lp=" + language + "de&search=" + text)); mContext.startActivity(leoSearchIntent); break; case DICTIONARY_LEO_APP: Intent leoAppSearchIntent = new Intent(mDictionaryAction); leoAppSearchIntent.putExtra("org.leo.android.dict.DICTIONARY", language + "de"); leoAppSearchIntent.putExtra(Intent.EXTRA_TEXT, text); leoAppSearchIntent.setComponent(new ComponentName("org.leo.android.dict", "org.leo.android.dict.LeoDict")); mContext.startActivity(leoAppSearchIntent); break; default: } } public static String getSearchStringTitle() { return String.format(mContext.getString(R.string.menu_search), mContext.getResources().getStringArray(R.array.dictionary_labels)[mDictionary]); } public static boolean isAvailable() { return mIsDictionaryAvailable; } private static String getLanguage(int questionAnswer) { if (mCurrentCard == null) { return ""; } else { return MetaDB.getLanguage(mContext, mDeckFilename, Model.getModel(AnkiDroidApp.deck(), mCurrentCard.getCardModelId(), false).getId(), mCurrentCard.getCardModelId(), questionAnswer); } } private static void storeLanguage(String language, int questionAnswer) { if (mCurrentCard != null) { MetaDB.storeLanguage(mContext, mDeckFilename, Model.getModel(AnkiDroidApp.deck(), mCurrentCard.getCardModelId(), false).getId(), mCurrentCard.getCardModelId(), questionAnswer, language); } } }
true
true
public static boolean lookUp(String text, Card card) { mCurrentCard = card; // clear text from leading and closing dots, commas, brackets etc. text = text.trim().replaceAll("[,;:\\s\\(\\[\\)\\]\\.]*$", "").replaceAll("^[,;:\\s\\(\\[\\)\\]\\.]*", ""); switch (mDictionary) { case DICTIONARY_AEDICT: Intent aedictSearchIntent = new Intent(mDictionaryAction); aedictSearchIntent.putExtra("kanjis", text); mContext.startActivity(aedictSearchIntent); return true; case DICTIONARY_LEO_WEB: case DICTIONARY_LEO_APP: mLookupText = text; // localisation is needless here since leo.org translates only into or out of German final CharSequence[] itemValues = {"en", "fr", "es", "it", "ch", "ru"}; String language = getLanguage(MetaDB.LANGUAGES_QA_UNDEFINED); if (language.length() > 0) { for (int i = 0; i < itemValues.length; i++) { if (language.equals(itemValues[i])) { lookupLeo(language, mLookupText); mLookupText = ""; return true; } } } final String[] items = {"Englisch", "Französisch", "Spanisch", "Italienisch", "Chinesisch", "Russisch"}; StyledDialog.Builder builder = new StyledDialog.Builder(mContext); builder.setTitle("\"" + mLookupText + "\" nachschlagen"); builder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { String language = itemValues[item].toString(); storeLanguage(language, MetaDB.LANGUAGES_QA_UNDEFINED); lookupLeo(language, mLookupText); mLookupText = ""; } }); StyledDialog alert = builder.create(); alert.show(); return true; case DICTIONARY_COLORDICT: Intent colordictSearchIntent = new Intent(mDictionaryAction); colordictSearchIntent.putExtra("EXTRA_QUERY", text); mContext.startActivity(colordictSearchIntent); return true; case DICTIONARY_FORA: Intent foraSearchIntent = new Intent(mDictionaryAction); foraSearchIntent.putExtra("HEADWORD", text.trim()); mContext.startActivity(foraSearchIntent); return true; case DICTIONARY_NCIKU_WEB: Intent ncikuWebIntent = new Intent(mDictionaryAction, Uri.parse("http://m.nciku.com/en/entry/?query=" + text)); mContext.startActivity(ncikuWebIntent); return true; case DICTIONARY_EIJIRO_WEB: Intent eijiroWebIntent = new Intent(mDictionaryAction, Uri.parse("http://eow.alc.co.jp/" + text)); mContext.startActivity(eijiroWebIntent); return true; } return false; }
public static boolean lookUp(String text, Card card) { mCurrentCard = card; // clear text from leading and closing dots, commas, brackets etc. text = text.trim().replaceAll("[,;:\\s\\(\\[\\)\\]\\.]*$", "").replaceAll("^[,;:\\s\\(\\[\\)\\]\\.]*", ""); switch (mDictionary) { case DICTIONARY_AEDICT: Intent aedictSearchIntent = new Intent(mDictionaryAction); aedictSearchIntent.putExtra("kanjis", text); mContext.startActivity(aedictSearchIntent); return true; case DICTIONARY_LEO_WEB: case DICTIONARY_LEO_APP: mLookupText = text; // localisation is needless here since leo.org translates only into or out of German final CharSequence[] itemValues = {"en", "fr", "es", "it", "ch", "ru"}; String language = getLanguage(MetaDB.LANGUAGES_QA_UNDEFINED); if (language.length() > 0) { for (int i = 0; i < itemValues.length; i++) { if (language.equals(itemValues[i])) { lookupLeo(language, mLookupText); mLookupText = ""; return true; } } } final String[] items = {"Englisch", "Franz�sisch", "Spanisch", "Italienisch", "Chinesisch", "Russisch"}; StyledDialog.Builder builder = new StyledDialog.Builder(mContext); builder.setTitle("\"" + mLookupText + "\" nachschlagen"); builder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { String language = itemValues[item].toString(); storeLanguage(language, MetaDB.LANGUAGES_QA_UNDEFINED); lookupLeo(language, mLookupText); mLookupText = ""; } }); StyledDialog alert = builder.create(); alert.show(); return true; case DICTIONARY_COLORDICT: Intent colordictSearchIntent = new Intent(mDictionaryAction); colordictSearchIntent.putExtra("EXTRA_QUERY", text); mContext.startActivity(colordictSearchIntent); return true; case DICTIONARY_FORA: Intent foraSearchIntent = new Intent(mDictionaryAction); foraSearchIntent.putExtra("HEADWORD", text.trim()); mContext.startActivity(foraSearchIntent); return true; case DICTIONARY_NCIKU_WEB: Intent ncikuWebIntent = new Intent(mDictionaryAction, Uri.parse("http://m.nciku.com/en/entry/?query=" + text)); mContext.startActivity(ncikuWebIntent); return true; case DICTIONARY_EIJIRO_WEB: Intent eijiroWebIntent = new Intent(mDictionaryAction, Uri.parse("http://eow.alc.co.jp/" + text)); mContext.startActivity(eijiroWebIntent); return true; } return false; }
diff --git a/gwtpplugin/src/com/gwtplatform/plugin/wizard/NewPresenterWizardPage.java b/gwtpplugin/src/com/gwtplatform/plugin/wizard/NewPresenterWizardPage.java index b706181..3fc3cac 100644 --- a/gwtpplugin/src/com/gwtplatform/plugin/wizard/NewPresenterWizardPage.java +++ b/gwtpplugin/src/com/gwtplatform/plugin/wizard/NewPresenterWizardPage.java @@ -1,1473 +1,1473 @@ /** * Copyright 2011 IMAGEM Solutions TI sant� * * 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.gwtplatform.plugin.wizard; import java.util.ArrayList; import java.util.List; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.QualifiedName; import org.eclipse.jdt.core.IField; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.ITypeHierarchy; import org.eclipse.jdt.core.JavaConventions; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.search.IJavaSearchConstants; import org.eclipse.jdt.core.search.IJavaSearchScope; import org.eclipse.jdt.core.search.SearchEngine; import org.eclipse.jdt.internal.ui.dialogs.FilteredTypesSelectionDialog; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.ui.dialogs.ITypeInfoFilterExtension; import org.eclipse.jdt.ui.dialogs.ITypeInfoRequestor; import org.eclipse.jdt.ui.dialogs.TypeSelectionExtension; import org.eclipse.jdt.ui.wizards.NewTypeWizardPage; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.window.Window; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.dialogs.ISelectionStatusValidator; import com.gwtplatform.plugin.Activator; /** * * @author Michael Renaud * */ /** * @author beaudoin * */ public class NewPresenterWizardPage extends NewTypeWizardPage { private static final String PAGE_NAME = "NewPresenterWizardPage"; private IStatus fRevealInParentStatus = new StatusInfo(); private IStatus fPlaceStatus = new StatusInfo(); private IStatus fGinStatus = new StatusInfo(); private Button isPlace; private Button isProxyStandard; private Button isProxyCodeSplit; private Text tokenName; private Text gatekeeper; private Button onBind; private Button onHide; private Button onReset; private Button onReveal; private Button onUnbind; private Button isPresenterWidget; private Button useUiBinder; private Button isRevealContentEvent; private Button isRevealRootContentEvent; private Button isRevealRootLayoutContentEvent; private Button isRevealRootPopupContentEvent; private Text contentSlot; private Button browseGatekeeper; private Button browseContentSlot; private Button browseTokenName; private String selectedSlot; private String selectedTokenName; private Text presenterModule; private Text ginjector; private Button browseGinjector; private Button isSingleton; private Text annotation; private Button browseAnnotation; private boolean isPlaceEnabled; private Button isPopup; public NewPresenterWizardPage(IStructuredSelection selection) { super(true, PAGE_NAME); setTitle("Create a Presenter"); setDescription("Create a Presenter, its View and its GIN's reference"); init(selection); } // -------- Initialization --------- /** * The wizard owning this page is responsible for calling this method with the * current selection. The selection is used to initialize the fields of the * wizard page. * * @param selection * used to initialize the fields */ protected void init(IStructuredSelection selection) { IJavaElement jelem = getInitialJavaElement(selection); initContainerPage(jelem); initTypePage(jelem); doStatusUpdate(); } // ------ validation -------- private void doStatusUpdate() { // status of all used components IStatus[] status = new IStatus[] { fContainerStatus, fPackageStatus, fTypeNameStatus, fRevealInParentStatus, fPlaceStatus, fGinStatus }; // the mode severe status will be displayed and the OK button // enabled/disabled. updateStatus(status); } /* * @see NewContainerWizardPage#handleFieldChanged */ protected void handleFieldChanged(String fieldName) { super.handleFieldChanged(fieldName); doStatusUpdate(); } @Override public void createControl(Composite parent) { initializeDialogUnits(parent); Composite composite = new Composite(parent, SWT.NONE); composite.setFont(parent.getFont()); int nColumns = 4; GridLayout layout = new GridLayout(); layout.numColumns = nColumns; composite.setLayout(layout); // pick & choose the wanted UI components createContainerControls(composite, nColumns); createPackageControls(composite, nColumns); // createEnclosingTypeControls(composite, nColumns); createSeparator(composite, nColumns); createTypeNameControls(composite, nColumns); createUITypeControls(composite, nColumns); createWidgetControls(composite, nColumns); createRevealInParentControls(composite, nColumns); createPlaceControls(composite, nColumns); createMethodStubsControls(composite, nColumns); createGinControls(composite, nColumns); setControl(composite); setFocus(); setDefaultValues(); Dialog.applyDialogFont(composite); } private void setDefaultValues() { try { if (tokenName != null) { String nameTokensValue = getJavaProject().getProject().getPersistentProperty( new QualifiedName(Activator.PLUGIN_ID, "nametokens")); tokenName.setText(nameTokensValue == null ? "" : nameTokensValue + "#"); fPlaceStatus = placeChanged(); doStatusUpdate(); } if (ginjector != null && presenterModule != null) { String ginjectorValue = getJavaProject().getProject().getPersistentProperty( new QualifiedName(Activator.PLUGIN_ID, "ginjector")); String presenterModuleValue = getJavaProject().getProject().getPersistentProperty( new QualifiedName(Activator.PLUGIN_ID, "presentermodule")); ginjector.setText(ginjectorValue == null ? "" : ginjectorValue); presenterModule.setText(presenterModuleValue == null ? "" : presenterModuleValue); fGinStatus = ginChanged(); doStatusUpdate(); } } catch (CoreException e1) { } } protected String getTypeNameLabel() { return "Presenter name:"; } protected IStatus typeNameChanged() { StatusInfo status = (StatusInfo) super.typeNameChanged(); if (status.isOK()) { String typeNameWithParameters = getTypeName(); if (!typeNameWithParameters.endsWith("Presenter")) { status.setError("Presenter class must ends by \"Presenter\""); return status; } } return status; } private void createUITypeControls(Composite composite, int nColumns) { Label label = new Label(composite, SWT.NULL); label.setText("Ui:"); GridData gd = new GridData(GridData.FILL); gd.horizontalSpan = nColumns - 1; GridLayout layout = new GridLayout(); layout.numColumns = 2; layout.verticalSpacing = 5; Composite checks = new Composite(composite, SWT.NULL); checks.setLayoutData(gd); checks.setLayout(layout); isPresenterWidget = new Button(checks, SWT.CHECK); isPresenterWidget.setText("Extend PresenterWidget"); isPresenterWidget.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { setRevealInParentEnabled(!isPresenterWidget.getSelection()); setPlaceEnabled(!isPresenterWidget.getSelection()); setGinjectorEnabled(!isPresenterWidget.getSelection()); setWidgetEnabled(isPresenterWidget.getSelection()); } @Override public void widgetDefaultSelected(SelectionEvent e) { setRevealInParentEnabled(!isPresenterWidget.getSelection()); setPlaceEnabled(!isPresenterWidget.getSelection()); setGinjectorEnabled(!isPresenterWidget.getSelection()); setWidgetEnabled(isPresenterWidget.getSelection()); } }); useUiBinder = new Button(checks, SWT.CHECK); useUiBinder.setText("Use UiBinder"); useUiBinder.setSelection(true); } private void createWidgetControls(Composite composite, int nColumns) { Label label = new Label(composite, SWT.NULL); label.setText("PresenterWidget:"); GridData gd = new GridData(GridData.FILL); gd.horizontalSpan = nColumns - 1; GridLayout layout = new GridLayout(); layout.numColumns = 2; layout.verticalSpacing = 5; Composite checks = new Composite(composite, SWT.NULL); checks.setLayoutData(gd); checks.setLayout(layout); isSingleton = new Button(checks, SWT.CHECK); isSingleton.setText("Singleton"); isSingleton.setSelection(false); isSingleton.setEnabled(false); isPopup = new Button(checks, SWT.CHECK); isPopup.setText("PopupView"); isPopup.setSelection(false); isPopup.setEnabled(false); } private void setWidgetEnabled(boolean enabled) { isSingleton.setEnabled(enabled); isPopup.setEnabled(enabled); } private void createRevealInParentControls(Composite composite, int nColumns) { Label label = new Label(composite, SWT.NULL); label.setText("Reveal Event:"); GridData gd = new GridData(GridData.FILL); gd.horizontalSpan = nColumns - 1; GridLayout layout = new GridLayout(); layout.numColumns = 2; layout.verticalSpacing = 5; Composite radios = new Composite(composite, SWT.NULL); radios.setLayoutData(gd); radios.setLayout(layout); isRevealContentEvent = new Button(radios, SWT.RADIO); isRevealContentEvent.setText("RevealContentEvent"); isRevealContentEvent.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { contentSlot.setEnabled(isRevealContentEvent.isEnabled() ? isRevealContentEvent .getSelection() : false); browseContentSlot.setEnabled(isRevealContentEvent.isEnabled() ? isRevealContentEvent .getSelection() : false); fRevealInParentStatus = revealInParentChanged(); doStatusUpdate(); } @Override public void widgetDefaultSelected(SelectionEvent e) { contentSlot.setEnabled(isRevealContentEvent.isEnabled() ? isRevealContentEvent .getSelection() : false); browseContentSlot.setEnabled(isRevealContentEvent.isEnabled() ? isRevealContentEvent .getSelection() : false); fRevealInParentStatus = revealInParentChanged(); doStatusUpdate(); } }); isRevealContentEvent.setSelection(true); isRevealRootContentEvent = new Button(radios, SWT.RADIO); isRevealRootContentEvent.setText("RevealRootContentEvent"); isRevealRootLayoutContentEvent = new Button(radios, SWT.RADIO); isRevealRootLayoutContentEvent.setText("RevealRootLayoutContentEvent"); isRevealRootPopupContentEvent = new Button(radios, SWT.RADIO); isRevealRootPopupContentEvent.setText("RevealRootPopupContentEvent"); isRevealRootPopupContentEvent.setEnabled(false); label = new Label(composite, SWT.NULL); label.setText("Content Slot:"); gd = new GridData(GridData.FILL_HORIZONTAL); gd.horizontalSpan = nColumns - 2; contentSlot = new Text(composite, SWT.BORDER | SWT.SINGLE); contentSlot.setLayoutData(gd); contentSlot.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { fRevealInParentStatus = revealInParentChanged(); doStatusUpdate(); } }); browseContentSlot = new Button(composite, SWT.PUSH); browseContentSlot.setText("Browse..."); browseContentSlot.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); browseContentSlot.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { IType contentSlotType = chooseContentSlot(); if (contentSlotType != null) { contentSlot.setText(contentSlotType.getFullyQualifiedName('.') + "#" + selectedSlot); } } @Override public void widgetDefaultSelected(SelectionEvent e) { IType contentSlotType = chooseContentSlot(); if (contentSlotType != null) { contentSlot.setText(contentSlotType.getFullyQualifiedName('.') + "#" + selectedSlot); } } }); fRevealInParentStatus = revealInParentChanged(); doStatusUpdate(); } protected void setRevealInParentEnabled(boolean enabled) { isRevealContentEvent.setEnabled(enabled); isRevealRootContentEvent.setEnabled(enabled); isRevealRootLayoutContentEvent.setEnabled(enabled); // isRevealRootPopupContentEvent.setEnabled(enabled); contentSlot.setEnabled(isRevealContentEvent.isEnabled() ? isRevealContentEvent.getSelection() : false); browseContentSlot.setEnabled(isRevealContentEvent.isEnabled() ? isRevealContentEvent .getSelection() : false); fRevealInParentStatus = revealInParentChanged(); doStatusUpdate(); } protected IStatus revealInParentChanged() { StatusInfo status = new StatusInfo(); if (isRevealContentEvent.isEnabled() && isRevealContentEvent.getSelection()) { if (contentSlot.getText().isEmpty()) { status .setError("You must enter the parent's content slot when selecting RevealContentEvent"); return status; } String slotParent = ""; String slotName = ""; if (!contentSlot.getText().contains("#")) { slotParent = contentSlot.getText(); } else { String[] split = contentSlot.getText().split("#"); slotParent = split[0]; if (split.length > 1) { slotName = split[1]; } } try { IType type = getJavaProject().findType(slotParent); if (type == null || !type.exists()) { status.setError(slotParent + " doesn't exist"); return status; } ITypeHierarchy hierarchy = type.newSupertypeHierarchy(new NullProgressMonitor()); IType[] interfaces = hierarchy.getAllInterfaces(); boolean hasSlots = false; for (IType inter : interfaces) { if (inter.getFullyQualifiedName('.').equals("com.gwtplatform.mvp.client.HasSlots")) { hasSlots = true; break; } } if (!hasSlots) { status.setError(slotParent + " doesn't implement HasSlots"); return status; } if (slotName.isEmpty()) { status .setError("You must enter the slot's name (fully.qualified.ParentPresenter#SlotName)"); return status; } IField field = type.getField(slotName); if (!field.exists()) { status.setError(slotName + " doesn't exist"); return status; } if (!field.getAnnotation("ContentSlot").exists()) { status.setError(slotName + " isn't a ContentSlot"); return status; } } catch (JavaModelException e) { status.setError("An unexpected error has happened. Close the wizard and retry."); return status; } } return status; } protected IType chooseContentSlot() { IJavaProject project = getJavaProject(); if (project == null) { return null; } IJavaElement[] elements = new IJavaElement[] { project }; IJavaSearchScope scope = SearchEngine.createJavaSearchScope(elements); FilteredTypesSelectionDialog dialog = new FilteredTypesSelectionDialog(getShell(), false, getWizard().getContainer(), scope, IJavaSearchConstants.CLASS, new ContentSlotSelectionExtension()); dialog.setTitle("ContentSlot Selection"); dialog.setMessage("Select the Presenter's parent"); dialog.setInitialPattern("*Presenter"); if (dialog.open() == Window.OK) { return (IType) dialog.getFirstResult(); } return null; } private void createPlaceControls(Composite composite, int nColumns) { Label label = new Label(composite, SWT.NULL); label.setText("Place:"); GridData gd = new GridData(GridData.FILL); gd.horizontalSpan = nColumns - 1; GridLayout layout = new GridLayout(); layout.numColumns = 1; layout.verticalSpacing = 5; Composite checks = new Composite(composite, SWT.NULL); checks.setLayoutData(gd); checks.setLayout(layout); isPlace = new Button(checks, SWT.CHECK); isPlace.setText("Is Place"); isPlace.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { setPlaceEnabled(isPlace.getSelection()); isPlace.setEnabled(true); fPlaceStatus = placeChanged(); doStatusUpdate(); } @Override public void widgetDefaultSelected(SelectionEvent e) { setPlaceEnabled(isPlace.getSelection()); isPlace.setEnabled(true); fPlaceStatus = placeChanged(); doStatusUpdate(); } }); isPlace.setSelection(true); isPlaceEnabled = true; // Proxy label = new Label(composite, SWT.NULL); label.setText("Proxy:"); layout = new GridLayout(); layout.numColumns = 2; layout.verticalSpacing = 5; Composite radios = new Composite(composite, SWT.NULL); radios.setLayoutData(gd); radios.setLayout(layout); isProxyStandard = new Button(radios, SWT.RADIO); isProxyStandard.setText("Standard"); isProxyCodeSplit = new Button(radios, SWT.RADIO); isProxyCodeSplit.setText("CodeSplit"); isProxyCodeSplit.setSelection(true); // Token label = new Label(composite, SWT.NULL); label.setText("Token name:"); gd = new GridData(GridData.FILL_HORIZONTAL); gd.horizontalSpan = nColumns - 2; tokenName = new Text(composite, SWT.BORDER | SWT.SINGLE); tokenName.setLayoutData(gd); tokenName.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { fPlaceStatus = placeChanged(); doStatusUpdate(); } }); browseTokenName = new Button(composite, SWT.PUSH); browseTokenName.setText("Browse..."); browseTokenName.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); browseTokenName.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { IType selection = chooseTokenName(); if (selection != null) { tokenName.setText(selection.getFullyQualifiedName('.') + "#" + selectedTokenName); } } @Override public void widgetDefaultSelected(SelectionEvent e) { IType selection = chooseTokenName(); if (selection != null) { tokenName.setText(selection.getFullyQualifiedName('.') + "#" + selectedTokenName); } } }); // BindConstant label = new Label(composite, SWT.NULL); label.setText("Place annotation:"); annotation = new Text(composite, SWT.BORDER | SWT.SINGLE); annotation.setLayoutData(gd); annotation.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { fPlaceStatus = placeChanged(); doStatusUpdate(); } }); browseAnnotation = new Button(composite, SWT.PUSH); browseAnnotation.setText("Browse..."); browseAnnotation.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); browseAnnotation.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { IType selection = chooseAnnotation(); if (selection != null) { - contentSlot.setText(selection.getFullyQualifiedName('.')); + annotation.setText(selection.getFullyQualifiedName('.')); } } @Override public void widgetDefaultSelected(SelectionEvent e) { IType selection = chooseAnnotation(); if (selection != null) { - contentSlot.setText(selection.getFullyQualifiedName('.')); + annotation.setText(selection.getFullyQualifiedName('.')); } } }); // GateKeeper label = new Label(composite, SWT.NULL); label.setText("Gatekeeper:"); gatekeeper = new Text(composite, SWT.BORDER | SWT.SINGLE); gatekeeper.setLayoutData(gd); gatekeeper.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { fPlaceStatus = placeChanged(); doStatusUpdate(); } }); browseGatekeeper = new Button(composite, SWT.PUSH); browseGatekeeper.setText("Browse..."); browseGatekeeper.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); browseGatekeeper.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { IType selection = chooseGatekeeper(); if (selection != null) { gatekeeper.setText(selection.getFullyQualifiedName('.')); } } @Override public void widgetDefaultSelected(SelectionEvent e) { IType selection = chooseGatekeeper(); if (selection != null) { gatekeeper.setText(selection.getFullyQualifiedName('.')); } } }); fPlaceStatus = placeChanged(); doStatusUpdate(); } protected IStatus placeChanged() { StatusInfo status = new StatusInfo(); if (isPlace.isEnabled() && isPlace.getSelection()) { // Token if (tokenName.getText().isEmpty()) { status.setError("Enter the token's name (fully.qualified.NameTokens#name)"); return status; } String parent = ""; String token = ""; if (!tokenName.getText().contains("#")) { parent = tokenName.getText(); } else { String[] split = tokenName.getText().split("#"); parent = split[0]; if (split.length > 1) { token = split[1]; } } try { IType type = getJavaProject().findType(parent); if (type == null || !type.exists()) { status.setError(parent + " doesn't exist"); return status; } if (type.isBinary()) { status.setError(parent + " is a Binary class"); return status; } if (token.isEmpty()) { status.setError("You must enter the token name (fully.qualified.NameTokens#name)"); return status; } char start = token.toCharArray()[0]; if (start >= 48 && start <= 57) { status.setError("Token name must not start by a number"); return status; } for (char c : token.toCharArray()) { // [a-z][0-9]! if (!((c >= 97 && c <= 122) || (c >= 48 && c <= 57) || c == 33)) { status.setError("Token name must contain only lower-case letters, numbers and !"); return status; } } IField field = type.getField(token); if (field.exists()) { status.setError("The token " + token + " already exists."); return status; } } catch (JavaModelException e) { status.setError("An unexpected error has happened. Close the wizard and retry."); return status; } // Annotation if (!annotation.getText().isEmpty()) { try { IType type = getJavaProject().findType(annotation.getText()); if (type == null || !type.exists()) { // New type, we will try to create the annotation IStatus nameStatus = JavaConventions.validateJavaTypeName(annotation.getText(), JavaCore.VERSION_1_6, JavaCore.VERSION_1_7); if (nameStatus.getCode() != IStatus.OK && nameStatus.getCode() != IStatus.WARNING) { status.setError(annotation.getText() + " is not a valid type name."); return status; } } else { // Existing type, just reuse it if (!type.isAnnotation()) { status.setError(annotation.getText() + " isn't an Annotation"); return status; } } } catch (JavaModelException e) { status.setError("An unexpected error has happened. Close the wizard and retry."); return status; } } // Gatekeeper if (!gatekeeper.getText().isEmpty()) { try { IType type = getJavaProject().findType(gatekeeper.getText()); if (type == null || !type.exists()) { status.setError(gatekeeper.getText() + " doesn't exist"); return status; } ITypeHierarchy hierarchy = type.newSupertypeHierarchy(new NullProgressMonitor()); IType[] interfaces = hierarchy.getAllInterfaces(); boolean isGateKeeper = false; for (IType inter : interfaces) { if (inter.getFullyQualifiedName('.').equals( "com.gwtplatform.mvp.client.proxy.Gatekeeper")) { isGateKeeper = true; break; } } if (!isGateKeeper) { status.setError(gatekeeper.getText() + " doesn't implement GateKeeper"); return status; } } catch (JavaModelException e) { status.setError("An unexpected error has happened. Close the wizard and retry."); return status; } } } return status; } protected IType chooseTokenName() { IJavaProject project = getJavaProject(); if (project == null) { return null; } IJavaElement[] elements = new IJavaElement[] { project }; IJavaSearchScope scope = SearchEngine.createJavaSearchScope(elements); FilteredTypesSelectionDialog dialog = new FilteredTypesSelectionDialog(getShell(), false, getWizard().getContainer(), scope, IJavaSearchConstants.CLASS, new TokenNameSelectionExtension()); dialog.setTitle("Token name Selection"); dialog.setMessage("Select the Tokens class"); dialog.setInitialPattern("*Tokens"); if (dialog.open() == Window.OK) { return (IType) dialog.getFirstResult(); } return null; } protected IType chooseAnnotation() { IJavaProject project = getJavaProject(); if (project == null) { return null; } IJavaElement[] elements = new IJavaElement[] { project }; IJavaSearchScope scope = SearchEngine.createJavaSearchScope(elements); FilteredTypesSelectionDialog dialog = new FilteredTypesSelectionDialog(getShell(), false, getWizard().getContainer(), scope, IJavaSearchConstants.ANNOTATION_TYPE, new AnnotationSelectionExtension()); dialog.setTitle("Annotation Selection"); dialog.setMessage("Select the annotation to bind"); dialog.setInitialPattern("*.client.place."); if (dialog.open() == Window.OK) { return (IType) dialog.getFirstResult(); } return null; } private IType chooseGatekeeper() { IJavaProject project = getJavaProject(); if (project == null) { return null; } IJavaElement[] elements = new IJavaElement[] { project }; IJavaSearchScope scope = SearchEngine.createJavaSearchScope(elements); FilteredTypesSelectionDialog dialog = new FilteredTypesSelectionDialog(getShell(), false, getWizard().getContainer(), scope, IJavaSearchConstants.CLASS, new GatekeeperSelectionExtension()); dialog.setTitle("Gatekeeper Selection"); dialog.setMessage("Select the Presenter's Gatekeeper"); dialog.setInitialPattern("*Gatekeeper"); if (dialog.open() == Window.OK) { return (IType) dialog.getFirstResult(); } return null; } protected void setPlaceEnabled(boolean enabled) { isPlaceEnabled = enabled; isPlace.setEnabled(enabled); isProxyStandard.setEnabled(isPlace.getSelection() ? enabled : false); isProxyCodeSplit.setEnabled(isPlace.getSelection() ? enabled : false); tokenName.setEnabled(isPlace.getSelection() ? enabled : false); browseTokenName.setEnabled(isPlace.getSelection() ? enabled : false); annotation.setEnabled(isPlace.getSelection() ? enabled : false); browseAnnotation.setEnabled(isPlace.getSelection() ? enabled : false); gatekeeper.setEnabled(isPlace.getSelection() ? enabled : false); browseGatekeeper.setEnabled(isPlace.getSelection() ? enabled : false); fPlaceStatus = placeChanged(); doStatusUpdate(); } protected void createMethodStubsControls(Composite composite, int nColumns) { // Methods Label label = new Label(composite, SWT.BEGINNING); label.setText("Method stubs:"); label.setLayoutData(new GridData(GridData.FILL_VERTICAL)); GridData gd = new GridData(GridData.FILL_HORIZONTAL); gd.horizontalSpan = nColumns - 1; GridLayout layout = new GridLayout(); layout.numColumns = 3; layout.verticalSpacing = 5; Composite methods = new Composite(composite, SWT.NULL); methods.setLayoutData(gd); methods.setLayout(layout); onBind = new Button(methods, SWT.CHECK); onBind.setText("onBind()"); onBind.setSelection(true); onHide = new Button(methods, SWT.CHECK); onHide.setText("onHide()"); onReset = new Button(methods, SWT.CHECK); onReset.setText("onReset()"); onReveal = new Button(methods, SWT.CHECK); onReveal.setText("onReveal()"); onUnbind = new Button(methods, SWT.CHECK); onUnbind.setText("onUnbind()"); label = new Label(methods, SWT.NULL); } private void createGinControls(Composite composite, int nColumns) { // Ginjector Label label = new Label(composite, SWT.NULL); label.setText("Ginjector:"); GridData gd = new GridData(GridData.FILL_HORIZONTAL); gd.horizontalSpan = nColumns - 2; ginjector = new Text(composite, SWT.BORDER | SWT.SINGLE); ginjector.setLayoutData(gd); ginjector.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { fGinStatus = ginChanged(); doStatusUpdate(); } }); browseGinjector = new Button(composite, SWT.PUSH); browseGinjector.setText("Browse..."); browseGinjector.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); browseGinjector.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { IType selection = chooseGinjector(); if (selection != null) { ginjector.setText(selection.getFullyQualifiedName('.')); } } @Override public void widgetDefaultSelected(SelectionEvent e) { IType selection = chooseGinjector(); if (selection != null) { ginjector.setText(selection.getFullyQualifiedName('.')); } } }); // Presenter Module label = new Label(composite, SWT.NULL); label.setText("Presenter Module:"); presenterModule = new Text(composite, SWT.BORDER | SWT.SINGLE); presenterModule.setLayoutData(gd); presenterModule.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { fGinStatus = ginChanged(); doStatusUpdate(); } }); Button browsePresenterModule = new Button(composite, SWT.PUSH); browsePresenterModule.setText("Browse..."); browsePresenterModule.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); browsePresenterModule.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { IType selection = choosePresenterModule(); if (selection != null) { presenterModule.setText(selection.getFullyQualifiedName('.')); } } @Override public void widgetDefaultSelected(SelectionEvent e) { IType selection = choosePresenterModule(); if (selection != null) { presenterModule.setText(selection.getFullyQualifiedName('.')); } } }); fGinStatus = ginChanged(); doStatusUpdate(); } protected IStatus ginChanged() { StatusInfo status = new StatusInfo(); if (ginjector.isEnabled()) { if (ginjector.getText().isEmpty()) { status.setError("Enter a Ginjector"); return status; } try { IType type = getJavaProject().findType(ginjector.getText()); if (type == null || !type.exists()) { status.setError(ginjector.getText() + " doesn't exist"); return status; } if (type.isBinary()) { status.setError(ginjector.getText() + " is a Binary class"); return status; } ITypeHierarchy hierarchy = type.newSupertypeHierarchy(new NullProgressMonitor()); IType[] interfaces = hierarchy.getAllInterfaces(); boolean isGinjector = false; for (IType inter : interfaces) { if (inter.getFullyQualifiedName('.').equals("com.google.gwt.inject.client.Ginjector")) { isGinjector = true; break; } } if (!isGinjector) { status.setError(ginjector.getText() + " doesn't extend Ginjector"); return status; } } catch (JavaModelException e) { status.setError("An unexpected error has happened. Close the wizard and retry."); return status; } } if (presenterModule.getText().isEmpty()) { status.setError("Enter a PresenterModule"); return status; } try { IType type = getJavaProject().findType(presenterModule.getText()); if (type == null || !type.exists()) { status.setError(presenterModule.getText() + " doesn't exist"); return status; } if (type.isBinary()) { status.setError(ginjector.getText() + " is a Binary class"); return status; } ITypeHierarchy hierarchy = type.newSupertypeHierarchy(new NullProgressMonitor()); IType[] superclasses = hierarchy.getAllClasses(); boolean isPresenterModule = false; for (IType superclass : superclasses) { if (superclass.getFullyQualifiedName('.').equals( "com.gwtplatform.mvp.client.gin.AbstractPresenterModule")) { isPresenterModule = true; break; } } if (!isPresenterModule) { status.setError(ginjector.getText() + " doesn't implement AbstractPresenterModule"); return status; } } catch (JavaModelException e) { status.setError("An unexpected error has happened. Close the wizard and retry."); return status; } return status; } protected IType chooseGinjector() { IJavaProject project = getJavaProject(); if (project == null) { return null; } IJavaElement[] elements = new IJavaElement[] { project }; IJavaSearchScope scope = SearchEngine.createJavaSearchScope(elements); FilteredTypesSelectionDialog dialog = new FilteredTypesSelectionDialog(getShell(), false, getWizard().getContainer(), scope, IJavaSearchConstants.INTERFACE, new GinjectorSelectionExtension()); dialog.setTitle("Ginjector Selection"); dialog.setMessage("Select a Ginjector"); dialog.setInitialPattern("*Ginjector"); if (dialog.open() == Window.OK) { return (IType) dialog.getFirstResult(); } return null; } protected IType choosePresenterModule() { IJavaProject project = getJavaProject(); if (project == null) { return null; } IJavaElement[] elements = new IJavaElement[] { project }; IJavaSearchScope scope = SearchEngine.createJavaSearchScope(elements); FilteredTypesSelectionDialog dialog = new FilteredTypesSelectionDialog(getShell(), false, getWizard().getContainer(), scope, IJavaSearchConstants.CLASS, new PresenterModuleSelectionExtension()); dialog.setTitle("PresenterModule Selection"); dialog.setMessage("Select a PresenterModule"); dialog.setInitialPattern("*Module"); if (dialog.open() == Window.OK) { return (IType) dialog.getFirstResult(); } return null; } protected void setGinjectorEnabled(boolean enabled) { ginjector.setEnabled(enabled); browseGinjector.setEnabled(enabled); fGinStatus = ginChanged(); doStatusUpdate(); } public boolean isWidget() { return isPresenterWidget.getSelection(); } public boolean useUiBinder() { return useUiBinder.getSelection(); } public boolean isSingleton() { return isSingleton.getSelection(); } public boolean isPopup() { return isPopup.getSelection() && isWidget(); } public String getRevealEvent() { if (isRevealContentEvent.getSelection()) { return "com.gwtplatform.mvp.client.proxy.RevealContentEvent"; } else if (isRevealRootContentEvent.getSelection()) { return "com.gwtplatform.mvp.client.proxy.RevealRootContentEvent"; } else if (isRevealRootLayoutContentEvent.getSelection()) { return "com.gwtplatform.mvp.client.proxy.RevealRootLayoutContentEvent"; } else { return "com.gwtplatform.mvp.client.proxy.RevealRootPopupContentEvent"; } } public String getViewPackageText() { return getPackageText(); } public String getViewTypeName() { return getTypeName().replaceAll("Presenter", "View"); } public String getParent() { return contentSlot.getText().split("#")[0]; } public String getContentSlot() { return contentSlot.getText().split("#")[1]; } public boolean isPlace() { return isPlace.getSelection() && isPlaceEnabled; } public boolean isProxyStandard() { return isProxyStandard.getSelection(); } public String getTokenClass() { return tokenName.getText().split("#")[0]; } public String getTokenName() { return tokenName.getText().split("#")[1]; } public String getAnnotation() { return annotation.getText(); } public String getGatekeeper() { return gatekeeper.getText(); } public String getGinjector() { return ginjector.getText(); } public String getPresenterModule() { return presenterModule.getText(); } public String[] getMethodStubs() { List<String> methods = new ArrayList<String>(); if (onBind.getSelection()) { methods.add("onBind"); } if (onHide.getSelection()) { methods.add("onHide"); } if (onReset.getSelection()) { methods.add("onReset"); } if (onReveal.getSelection()) { methods.add("onReveal"); } if (onUnbind.getSelection()) { methods.add("onUnbind"); } return methods.toArray(new String[methods.size()]); } /** * */ public class GatekeeperSelectionExtension extends TypeSelectionExtension { @Override public ITypeInfoFilterExtension getFilterExtension() { ITypeInfoFilterExtension extension = new ITypeInfoFilterExtension() { @Override public boolean select(ITypeInfoRequestor requestor) { try { IType type = getJavaProject().findType( requestor.getPackageName() + "." + requestor.getTypeName()); if (type == null || !type.exists()) { return false; } ITypeHierarchy hierarchy = type.newSupertypeHierarchy(new NullProgressMonitor()); IType[] interfaces = hierarchy.getAllInterfaces(); for (IType inter : interfaces) { if (inter.getFullyQualifiedName('.').equals( "com.gwtplatform.mvp.client.proxy.Gatekeeper")) { return true; } } return false; } catch (JavaModelException e) { return false; } } }; return extension; } } /** * */ public class ContentSlotSelectionExtension extends TypeSelectionExtension { private Combo slot; @Override public ITypeInfoFilterExtension getFilterExtension() { ITypeInfoFilterExtension extension = new ITypeInfoFilterExtension() { @Override public boolean select(ITypeInfoRequestor requestor) { try { IType type = getJavaProject().findType( requestor.getPackageName() + "." + requestor.getTypeName()); if (type == null || !type.exists()) { return false; } ITypeHierarchy hierarchy = type.newSupertypeHierarchy(new NullProgressMonitor()); IType[] interfaces = hierarchy.getAllInterfaces(); for (IType inter : interfaces) { if (inter.getFullyQualifiedName('.').equals("com.gwtplatform.mvp.client.HasSlots")) { for (IField field : type.getFields()) { if (field.getAnnotation("ContentSlot").exists()) { return true; } } } } return false; } catch (JavaModelException e) { return false; } } }; return extension; } @Override public ISelectionStatusValidator getSelectionValidator() { ISelectionStatusValidator validator = new ISelectionStatusValidator() { @Override public IStatus validate(Object[] selection) { slot.removeAll(); IType type = (IType) selection[0]; try { for (IField field : type.getFields()) { if (field.getAnnotation("ContentSlot").exists()) { slot.add(field.getElementName()); } } slot.select(0); } catch (JavaModelException e) { return new StatusInfo(); } return new StatusInfo(); } }; return validator; } @Override public Control createContentArea(Composite parent) { GridLayout layout = new GridLayout(); layout.numColumns = 2; Composite composite = new Composite(parent, SWT.NONE); composite.setFont(parent.getFont()); composite.setLayout(layout); Label label = new Label(composite, SWT.NONE); label.setText("Slot:"); slot = new Combo(composite, SWT.READ_ONLY); slot.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); slot.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { if (slot.getSelectionIndex() >= 0) { selectedSlot = slot.getItem(slot.getSelectionIndex()); } } }); return composite; } } /** * */ public class AnnotationSelectionExtension extends TypeSelectionExtension { @Override public ITypeInfoFilterExtension getFilterExtension() { ITypeInfoFilterExtension extension = new ITypeInfoFilterExtension() { @Override public boolean select(ITypeInfoRequestor requestor) { try { IType type = getJavaProject().findType( requestor.getPackageName() + "." + requestor.getTypeName()); if (type == null || !type.exists()) { return false; } return type.isAnnotation(); } catch (JavaModelException e) { return false; } } }; return extension; } } /** * */ public class TokenNameSelectionExtension extends TypeSelectionExtension { private Text name; @Override public ITypeInfoFilterExtension getFilterExtension() { ITypeInfoFilterExtension extension = new ITypeInfoFilterExtension() { @Override public boolean select(ITypeInfoRequestor requestor) { try { IType type = getJavaProject().findType( requestor.getPackageName() + "." + requestor.getTypeName()); if (type == null || !type.exists() || type.isBinary()) { return false; } return true; } catch (JavaModelException e) { return false; } } }; return extension; } @Override public Control createContentArea(Composite parent) { GridLayout layout = new GridLayout(); layout.numColumns = 2; Composite composite = new Composite(parent, SWT.NONE); composite.setFont(parent.getFont()); composite.setLayout(layout); Label label = new Label(composite, SWT.NONE); label.setText("Token name:"); name = new Text(composite, SWT.BORDER | SWT.SINGLE); name.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); name.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { selectedTokenName = name.getText(); } }); return composite; } } /** * */ public class GinjectorSelectionExtension extends TypeSelectionExtension { @Override public ITypeInfoFilterExtension getFilterExtension() { ITypeInfoFilterExtension extension = new ITypeInfoFilterExtension() { @Override public boolean select(ITypeInfoRequestor requestor) { try { IType type = getJavaProject().findType( requestor.getPackageName() + "." + requestor.getTypeName()); if (type == null || !type.exists() || type.isBinary()) { return false; } ITypeHierarchy hierarchy = type.newSupertypeHierarchy(new NullProgressMonitor()); IType[] interfaces = hierarchy.getAllInterfaces(); for (IType inter : interfaces) { if (inter.getFullyQualifiedName('.').equals("com.google.gwt.inject.client.Ginjector")) { return true; } } return false; } catch (JavaModelException e) { return false; } } }; return extension; } } /** * */ public class PresenterModuleSelectionExtension extends TypeSelectionExtension { @Override public ITypeInfoFilterExtension getFilterExtension() { ITypeInfoFilterExtension extension = new ITypeInfoFilterExtension() { @Override public boolean select(ITypeInfoRequestor requestor) { try { IType type = getJavaProject().findType( requestor.getPackageName() + "." + requestor.getTypeName()); if (type == null || !type.exists() || type.isBinary()) { return false; } ITypeHierarchy hierarchy = type.newSupertypeHierarchy(new NullProgressMonitor()); IType[] superclasses = hierarchy.getAllClasses(); for (IType superclass : superclasses) { if (superclass.getFullyQualifiedName('.').equals( "com.gwtplatform.mvp.client.gin.AbstractPresenterModule")) { return true; } } return false; } catch (JavaModelException e) { return false; } } }; return extension; } } }
false
true
private void createPlaceControls(Composite composite, int nColumns) { Label label = new Label(composite, SWT.NULL); label.setText("Place:"); GridData gd = new GridData(GridData.FILL); gd.horizontalSpan = nColumns - 1; GridLayout layout = new GridLayout(); layout.numColumns = 1; layout.verticalSpacing = 5; Composite checks = new Composite(composite, SWT.NULL); checks.setLayoutData(gd); checks.setLayout(layout); isPlace = new Button(checks, SWT.CHECK); isPlace.setText("Is Place"); isPlace.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { setPlaceEnabled(isPlace.getSelection()); isPlace.setEnabled(true); fPlaceStatus = placeChanged(); doStatusUpdate(); } @Override public void widgetDefaultSelected(SelectionEvent e) { setPlaceEnabled(isPlace.getSelection()); isPlace.setEnabled(true); fPlaceStatus = placeChanged(); doStatusUpdate(); } }); isPlace.setSelection(true); isPlaceEnabled = true; // Proxy label = new Label(composite, SWT.NULL); label.setText("Proxy:"); layout = new GridLayout(); layout.numColumns = 2; layout.verticalSpacing = 5; Composite radios = new Composite(composite, SWT.NULL); radios.setLayoutData(gd); radios.setLayout(layout); isProxyStandard = new Button(radios, SWT.RADIO); isProxyStandard.setText("Standard"); isProxyCodeSplit = new Button(radios, SWT.RADIO); isProxyCodeSplit.setText("CodeSplit"); isProxyCodeSplit.setSelection(true); // Token label = new Label(composite, SWT.NULL); label.setText("Token name:"); gd = new GridData(GridData.FILL_HORIZONTAL); gd.horizontalSpan = nColumns - 2; tokenName = new Text(composite, SWT.BORDER | SWT.SINGLE); tokenName.setLayoutData(gd); tokenName.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { fPlaceStatus = placeChanged(); doStatusUpdate(); } }); browseTokenName = new Button(composite, SWT.PUSH); browseTokenName.setText("Browse..."); browseTokenName.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); browseTokenName.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { IType selection = chooseTokenName(); if (selection != null) { tokenName.setText(selection.getFullyQualifiedName('.') + "#" + selectedTokenName); } } @Override public void widgetDefaultSelected(SelectionEvent e) { IType selection = chooseTokenName(); if (selection != null) { tokenName.setText(selection.getFullyQualifiedName('.') + "#" + selectedTokenName); } } }); // BindConstant label = new Label(composite, SWT.NULL); label.setText("Place annotation:"); annotation = new Text(composite, SWT.BORDER | SWT.SINGLE); annotation.setLayoutData(gd); annotation.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { fPlaceStatus = placeChanged(); doStatusUpdate(); } }); browseAnnotation = new Button(composite, SWT.PUSH); browseAnnotation.setText("Browse..."); browseAnnotation.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); browseAnnotation.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { IType selection = chooseAnnotation(); if (selection != null) { contentSlot.setText(selection.getFullyQualifiedName('.')); } } @Override public void widgetDefaultSelected(SelectionEvent e) { IType selection = chooseAnnotation(); if (selection != null) { contentSlot.setText(selection.getFullyQualifiedName('.')); } } }); // GateKeeper label = new Label(composite, SWT.NULL); label.setText("Gatekeeper:"); gatekeeper = new Text(composite, SWT.BORDER | SWT.SINGLE); gatekeeper.setLayoutData(gd); gatekeeper.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { fPlaceStatus = placeChanged(); doStatusUpdate(); } }); browseGatekeeper = new Button(composite, SWT.PUSH); browseGatekeeper.setText("Browse..."); browseGatekeeper.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); browseGatekeeper.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { IType selection = chooseGatekeeper(); if (selection != null) { gatekeeper.setText(selection.getFullyQualifiedName('.')); } } @Override public void widgetDefaultSelected(SelectionEvent e) { IType selection = chooseGatekeeper(); if (selection != null) { gatekeeper.setText(selection.getFullyQualifiedName('.')); } } }); fPlaceStatus = placeChanged(); doStatusUpdate(); }
private void createPlaceControls(Composite composite, int nColumns) { Label label = new Label(composite, SWT.NULL); label.setText("Place:"); GridData gd = new GridData(GridData.FILL); gd.horizontalSpan = nColumns - 1; GridLayout layout = new GridLayout(); layout.numColumns = 1; layout.verticalSpacing = 5; Composite checks = new Composite(composite, SWT.NULL); checks.setLayoutData(gd); checks.setLayout(layout); isPlace = new Button(checks, SWT.CHECK); isPlace.setText("Is Place"); isPlace.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { setPlaceEnabled(isPlace.getSelection()); isPlace.setEnabled(true); fPlaceStatus = placeChanged(); doStatusUpdate(); } @Override public void widgetDefaultSelected(SelectionEvent e) { setPlaceEnabled(isPlace.getSelection()); isPlace.setEnabled(true); fPlaceStatus = placeChanged(); doStatusUpdate(); } }); isPlace.setSelection(true); isPlaceEnabled = true; // Proxy label = new Label(composite, SWT.NULL); label.setText("Proxy:"); layout = new GridLayout(); layout.numColumns = 2; layout.verticalSpacing = 5; Composite radios = new Composite(composite, SWT.NULL); radios.setLayoutData(gd); radios.setLayout(layout); isProxyStandard = new Button(radios, SWT.RADIO); isProxyStandard.setText("Standard"); isProxyCodeSplit = new Button(radios, SWT.RADIO); isProxyCodeSplit.setText("CodeSplit"); isProxyCodeSplit.setSelection(true); // Token label = new Label(composite, SWT.NULL); label.setText("Token name:"); gd = new GridData(GridData.FILL_HORIZONTAL); gd.horizontalSpan = nColumns - 2; tokenName = new Text(composite, SWT.BORDER | SWT.SINGLE); tokenName.setLayoutData(gd); tokenName.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { fPlaceStatus = placeChanged(); doStatusUpdate(); } }); browseTokenName = new Button(composite, SWT.PUSH); browseTokenName.setText("Browse..."); browseTokenName.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); browseTokenName.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { IType selection = chooseTokenName(); if (selection != null) { tokenName.setText(selection.getFullyQualifiedName('.') + "#" + selectedTokenName); } } @Override public void widgetDefaultSelected(SelectionEvent e) { IType selection = chooseTokenName(); if (selection != null) { tokenName.setText(selection.getFullyQualifiedName('.') + "#" + selectedTokenName); } } }); // BindConstant label = new Label(composite, SWT.NULL); label.setText("Place annotation:"); annotation = new Text(composite, SWT.BORDER | SWT.SINGLE); annotation.setLayoutData(gd); annotation.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { fPlaceStatus = placeChanged(); doStatusUpdate(); } }); browseAnnotation = new Button(composite, SWT.PUSH); browseAnnotation.setText("Browse..."); browseAnnotation.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); browseAnnotation.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { IType selection = chooseAnnotation(); if (selection != null) { annotation.setText(selection.getFullyQualifiedName('.')); } } @Override public void widgetDefaultSelected(SelectionEvent e) { IType selection = chooseAnnotation(); if (selection != null) { annotation.setText(selection.getFullyQualifiedName('.')); } } }); // GateKeeper label = new Label(composite, SWT.NULL); label.setText("Gatekeeper:"); gatekeeper = new Text(composite, SWT.BORDER | SWT.SINGLE); gatekeeper.setLayoutData(gd); gatekeeper.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { fPlaceStatus = placeChanged(); doStatusUpdate(); } }); browseGatekeeper = new Button(composite, SWT.PUSH); browseGatekeeper.setText("Browse..."); browseGatekeeper.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); browseGatekeeper.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { IType selection = chooseGatekeeper(); if (selection != null) { gatekeeper.setText(selection.getFullyQualifiedName('.')); } } @Override public void widgetDefaultSelected(SelectionEvent e) { IType selection = chooseGatekeeper(); if (selection != null) { gatekeeper.setText(selection.getFullyQualifiedName('.')); } } }); fPlaceStatus = placeChanged(); doStatusUpdate(); }
diff --git a/source/yacy.java b/source/yacy.java index 6716d994a..2f8b57d12 100644 --- a/source/yacy.java +++ b/source/yacy.java @@ -1,1045 +1,1046 @@ // yacy.java // ----------------------- // (C) by Michael Peter Christen; [email protected] // first published on http://www.yacy.net // Frankfurt, Germany, 2004, 2005 // // $LastChangedDate$ // $LastChangedRevision$ // $LastChangedBy$ // // 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. import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Properties; import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; import de.anomic.data.translator; import de.anomic.http.HttpClient; import de.anomic.http.JakartaCommonsHttpClient; import de.anomic.http.JakartaCommonsHttpResponse; import de.anomic.http.httpHeader; import de.anomic.http.httpd; import de.anomic.index.indexContainer; import de.anomic.index.indexRWIEntry; import de.anomic.index.indexRWIRowEntry; import de.anomic.index.indexRepositoryReference; import de.anomic.index.indexURLReference; import de.anomic.index.indexWord; import de.anomic.kelondro.kelondroBLOBTree; import de.anomic.kelondro.kelondroBase64Order; import de.anomic.kelondro.kelondroMScoreCluster; import de.anomic.kelondro.kelondroMapObjects; import de.anomic.kelondro.kelondroRowCollection; import de.anomic.plasma.plasmaSwitchboard; import de.anomic.plasma.plasmaWordIndex; import de.anomic.server.serverCore; import de.anomic.server.serverDate; import de.anomic.server.serverFileUtils; import de.anomic.server.serverMemory; import de.anomic.server.serverSemaphore; import de.anomic.server.serverSystem; import de.anomic.server.logging.serverLog; import de.anomic.tools.enumerateFiles; import de.anomic.tools.yFormatter; import de.anomic.yacy.yacyClient; import de.anomic.yacy.yacySeedDB; import de.anomic.yacy.yacyURL; import de.anomic.yacy.yacyVersion; /** * This is the main class of YaCy. Several threads are started from here: * <ul> * <li>one single instance of the plasmaSwitchboard is generated, which itself * starts a thread with a plasmaHTMLCache object. This object simply counts * files sizes in the cache and terminates them. It also generates a * plasmaCrawlerLoader object, which may itself start some more httpc-calling * threads to load web pages. They terminate automatically when a page has * loaded. * <li>one serverCore - thread is started, which implements a multi-threaded * server. The process may start itself many more processes that handle * connections.lo * <li>finally, all idle-dependent processes are written in a queue in * plasmaSwitchboard which are worked off inside an idle-sensitive loop of the * main process. (here) * </ul> * * On termination, the following must be done: * <ul> * <li>stop feeding of the crawling process because it othervise fills the * indexing queue. * <li>say goodbye to connected peers and disable new connections. Don't wait for * success. * <li>first terminate the serverCore thread. This prevents that new cache * objects are queued. * <li>wait that the plasmaHTMLCache terminates (it should be normal that this * process already has terminated). * <li>then wait for termination of all loader process of the * plasmaCrawlerLoader. * <li>work off the indexing and cache storage queue. These values are inside a * RAM cache and would be lost otherwise. * <li>write all settings. * <li>terminate. * </ul> */ public final class yacy { // static objects public static final String vString = "@REPL_VERSION@"; public static double version = 0.1; public static boolean pro = false; public static final String vDATE = "@REPL_DATE@"; public static final String copyright = "[ YaCy v" + vString + ", build " + vDATE + " by Michael Christen / www.yacy.net ]"; public static final String hline = "-------------------------------------------------------------------------------"; /** * a reference to the {@link plasmaSwitchboard} created by the * {@link yacy#startup(String, long, long)} method. */ private static plasmaSwitchboard sb = null; /** * Semaphore needed by {@link yacy#setUpdaterCallback(serverUpdaterCallback)} to block * until the {@link plasmaSwitchboard }object was created. */ private static serverSemaphore sbSync = new serverSemaphore(0); /** * Semaphore needed by {@link yacy#waitForFinishedStartup()} to block * until startup has finished */ private static serverSemaphore startupFinishedSync = new serverSemaphore(0); /** * Starts up the whole application. Sets up all datastructures and starts * the main threads. * * @param homePath Root-path where all information is to be found. * @param startupFree free memory at startup time, to be used later for statistics */ private static void startup(File homePath, long startupMemFree, long startupMemTotal) { int oldRev=0; int newRev=0; try { // start up System.out.println(copyright); System.out.println(hline); // check java version try { "a".codePointAt(0); // needs at least Java 1.5 } catch (NoSuchMethodError e) { System.err.println("STARTUP: Java Version too low. You need at least Java 1.5 to run YaCy"); Thread.sleep(3000); System.exit(-1); } // ensure that there is a DATA directory, if not, create one and if that fails warn and die File f = homePath; if (!(f.exists())) f.mkdirs(); f = new File(homePath, "DATA/"); if (!(f.exists())) f.mkdirs(); if (!(f.exists())) { System.err.println("Error creating DATA-directory in " + homePath.toString() + " . Please check your write-permission for this folder. YaCy will now terminate."); System.exit(-1); } // setting up logging f = new File(homePath, "DATA/LOG/yacy.logging"); - if (!(new File(f.getPath()).exists())) f.mkdirs(); + final File logPath =new File(f.getPath()); + if (!logPath.exists()) logPath.mkdirs(); if (!f.exists()) try { serverFileUtils.copy(new File(homePath, "yacy.logging"), f); }catch (IOException e){ System.out.println("could not copy yacy.logging"); } try{ serverLog.configureLogging(homePath, f); } catch (IOException e) { System.out.println("could not find logging properties in homePath=" + homePath); e.printStackTrace(); } serverLog.logConfig("STARTUP", "Java version: " + System.getProperty("java.version", "no-java-version")); serverLog.logConfig("STARTUP", "Operation system: " + System.getProperty("os.name","unknown")); serverLog.logConfig("STARTUP", "Application root-path: " + homePath); serverLog.logConfig("STARTUP", "Time zone: UTC" + serverDate.UTCDiffString() + "; UTC+0000 is " + System.currentTimeMillis()); serverLog.logConfig("STARTUP", "Maximum file system path length: " + serverSystem.maxPathLength); f = new File(homePath, "DATA/yacy.running"); if (f.exists()) { // another instance running? VM crash? User will have to care about this serverLog.logSevere("STARTUP", "WARNING: the file " + f + " exists, this usually means that a YaCy instance is still running"); f.delete(); } f.createNewFile(); f.deleteOnExit(); pro = new File(homePath, "libx").exists(); String oldconf = "DATA/SETTINGS/httpProxy.conf".replace("/", File.separator); String newconf = "DATA/SETTINGS/yacy.conf".replace("/", File.separator); File oldconffile = new File(homePath, oldconf); if (oldconffile.exists()) { oldconffile.renameTo(new File(homePath, newconf)); } sb = new plasmaSwitchboard(homePath, "defaults/yacy.init".replace("/", File.separator), newconf, pro); sbSync.V(); // signal that the sb reference was set // save information about available memory at startup time sb.setConfig("memoryFreeAfterStartup", startupMemFree); sb.setConfig("memoryTotalAfterStartup", startupMemTotal); // hardcoded, forced, temporary value-migration sb.setConfig("htTemplatePath", "htroot/env/templates"); sb.setConfig("parseableExt", "html,htm,txt,php,shtml,asp"); // if we are running an SVN version, we try to detect the used svn revision now ... final Properties buildProp = new Properties(); File buildPropFile = new File(homePath,"build.properties"); try { buildProp.load(new FileInputStream(buildPropFile)); } catch (Exception e) { serverLog.logWarning("STARTUP", buildPropFile.toString() + " not found in settings path"); } oldRev=Integer.parseInt(sb.getConfig("svnRevision", "0")); try { if (buildProp.containsKey("releaseNr")) { // this normally looks like this: $Revision$ final String svnReleaseNrStr = buildProp.getProperty("releaseNr"); final Pattern pattern = Pattern.compile("\\$Revision:\\s(.*)\\s\\$",Pattern.DOTALL+Pattern.CASE_INSENSITIVE); final Matcher matcher = pattern.matcher(svnReleaseNrStr); if (matcher.find()) { final String svrReleaseNr = matcher.group(1); try { try {version = Double.parseDouble(vString);} catch (NumberFormatException e) {version = (float) 0.1;} version = yacyVersion.versvn2combinedVersion(version, Integer.parseInt(svrReleaseNr)); } catch (NumberFormatException e) {} sb.setConfig("svnRevision", svrReleaseNr); } } newRev=Integer.parseInt(sb.getConfig("svnRevision", "0")); } catch (Exception e) { System.err.println("Unable to determine the currently used SVN revision number."); } sb.setConfig("version", Double.toString(version)); sb.setConfig("vString", yacyVersion.combined2prettyVersion(Double.toString(version))); sb.setConfig("vdate", (vDATE.startsWith("@")) ? serverDate.formatShortDay() : vDATE); sb.setConfig("applicationRoot", homePath.toString()); serverLog.logConfig("STARTUP", "YACY Version: " + version + ", Built " + sb.getConfig("vdate", "00000000")); yacyVersion.latestRelease = version; // read environment int timeout = Math.max(20000, Integer.parseInt(sb.getConfig("httpdTimeout", "20000"))); // create some directories final File htRootPath = new File(homePath, sb.getConfig("htRootPath", "htroot")); final File htDocsPath = sb.getConfigPath(plasmaSwitchboard.HTDOCS_PATH, plasmaSwitchboard.HTDOCS_PATH_DEFAULT); if (!(htDocsPath.exists())) htDocsPath.mkdir(); //final File htTemplatePath = new File(homePath, sb.getConfig("htTemplatePath","htdocs")); // create default notifier picture //TODO: Use templates instead of copying images ... if (!((new File(htDocsPath, "notifier.gif")).exists())) try { serverFileUtils.copy(new File(htRootPath, "env/grafics/empty.gif"), new File(htDocsPath, "notifier.gif")); } catch (IOException e) {} final File htdocsReadme = new File(htDocsPath, "readme.txt"); if (!(htdocsReadme.exists())) try {serverFileUtils.copy(( "This is your root directory for individual Web Content\r\n" + "\r\n" + "Please place your html files into the www subdirectory.\r\n" + "The URL of that path is either\r\n" + "http://www.<your-peer-name>.yacy or\r\n" + "http://<your-ip>:<your-port>/www\r\n" + "\r\n" + "Other subdirectories may be created; they map to corresponding sub-domains.\r\n" + "This directory shares it's content with the applications htroot path, so you\r\n" + "may access your yacy search page with\r\n" + "http://<your-peer-name>.yacy/\r\n" + "\r\n").getBytes(), htdocsReadme);} catch (IOException e) { System.out.println("Error creating htdocs readme: " + e.getMessage()); } final File wwwDefaultPath = new File(htDocsPath, "www"); if (!(wwwDefaultPath.exists())) wwwDefaultPath.mkdir(); final File shareDefaultPath = new File(htDocsPath, "share"); if (!(shareDefaultPath.exists())) shareDefaultPath.mkdir(); migration.migrate(sb, oldRev, newRev); // delete old release files int deleteOldDownloadsAfterDays = (int) sb.getConfigLong("update.deleteOld", 30); yacyVersion.deleteOldDownloads(sb.releasePath, deleteOldDownloadsAfterDays ); // set user-agent final String userAgent = "yacy/" + Double.toString(version) + " (www.yacy.net; " + de.anomic.http.HttpClient.getSystemOST() + ")"; JakartaCommonsHttpClient.setUserAgent(userAgent); // start main threads final String port = sb.getConfig("port", "8080"); try { final httpd protocolHandler = new httpd(sb); final serverCore server = new serverCore( timeout /*control socket timeout in milliseconds*/, true /* block attacks (wrong protocol) */, protocolHandler /*command class*/, sb, 30000 /*command max length incl. GET args*/); server.setName("httpd:"+port); server.setPriority(Thread.MAX_PRIORITY); server.setObeyIntermission(false); if (server == null) { serverLog.logSevere("STARTUP", "Failed to start server. Probably port " + port + " already in use."); } else { // first start the server sb.deployThread("10_httpd", "HTTPD Server/Proxy", "the HTTPD, used as web server and proxy", null, server, 0, 0, 0, 0); //server.start(); // open the browser window final boolean browserPopUpTrigger = sb.getConfig("browserPopUpTrigger", "true").equals("true"); if (browserPopUpTrigger) { String browserPopUpPage = sb.getConfig("browserPopUpPage", "ConfigBasic.html"); //boolean properPW = (sb.getConfig("adminAccount", "").length() == 0) && (sb.getConfig(httpd.ADMIN_ACCOUNT_B64MD5, "").length() > 0); //if (!properPW) browserPopUpPage = "ConfigBasic.html"; final String browserPopUpApplication = sb.getConfig("browserPopUpApplication", "netscape"); serverSystem.openBrowser((server.withSSL()?"https":"http") + "://localhost:" + serverCore.getPortNr(port) + "/" + browserPopUpPage, browserPopUpApplication); } // Copy the shipped locales into DATA, existing files are overwritten final File locale_work = sb.getConfigPath("locale.work", "DATA/LOCALE/locales"); final File locale_source = sb.getConfigPath("locale.source", "locales"); try{ final File[] locale_source_files = locale_source.listFiles(); locale_work.mkdirs(); File target; for (int i=0; i < locale_source_files.length; i++){ target = new File(locale_work, locale_source_files[i].getName()); if (locale_source_files[i].getName().endsWith(".lng")) { if (target.exists()) target.delete(); serverFileUtils.copy(locale_source_files[i], target); } } serverLog.logInfo("STARTUP", "Copied the default locales to " + locale_work.toString()); }catch(NullPointerException e){ serverLog.logSevere("STARTUP", "Nullpointer Exception while copying the default Locales"); } //regenerate Locales from Translationlist, if needed final String lang = sb.getConfig("locale.language", ""); if (!lang.equals("") && !lang.equals("default")) { //locale is used String currentRev = ""; try{ final BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File(sb.getConfigPath("locale.translated_html", "DATA/LOCALE/htroot"), lang+"/version" )))); currentRev = br.readLine(); br.close(); }catch(IOException e){ //Error } if (!currentRev.equals(sb.getConfig("svnRevision", ""))) try { //is this another version?! final File sourceDir = new File(sb.getConfig("htRootPath", "htroot")); final File destDir = new File(sb.getConfigPath("locale.translated_html", "DATA/LOCALE/htroot"), lang); if (translator.translateFilesRecursive(sourceDir, destDir, new File(locale_work, lang + ".lng"), "html,template,inc", "locale")){ //translate it //write the new Versionnumber final BufferedWriter bw = new BufferedWriter(new PrintWriter(new FileWriter(new File(destDir, "version")))); bw.write(sb.getConfig("svnRevision", "Error getting Version")); bw.close(); } } catch (IOException e) {} } // initialize number formatter with this locale yFormatter.setLocale(lang); // registering shutdown hook serverLog.logConfig("STARTUP", "Registering Shutdown Hook"); final Runtime run = Runtime.getRuntime(); run.addShutdownHook(new shutdownHookThread(Thread.currentThread(), sb)); // save information about available memory after all initializations //try { sb.setConfig("memoryFreeAfterInitBGC", serverMemory.free()); sb.setConfig("memoryTotalAfterInitBGC", serverMemory.total()); System.gc(); sb.setConfig("memoryFreeAfterInitAGC", serverMemory.free()); sb.setConfig("memoryTotalAfterInitAGC", serverMemory.total()); //} catch (ConcurrentModificationException e) {} // signal finished startup startupFinishedSync.V(); // wait for server shutdown try { sb.waitForShutdown(); } catch (Exception e) { serverLog.logSevere("MAIN CONTROL LOOP", "PANIC: " + e.getMessage(),e); } // shut down if (kelondroRowCollection.sortingthreadexecutor != null) kelondroRowCollection.sortingthreadexecutor.shutdown(); serverLog.logConfig("SHUTDOWN", "caught termination signal"); server.terminate(false); server.interrupt(); server.close(); if (server.isAlive()) try { // TODO only send request, don't read response (cause server is already down resulting in error) yacyURL u = new yacyURL((server.withSSL()?"https":"http")+"://localhost:" + serverCore.getPortNr(port), null); HttpClient.wget(u.toString()); // kick server serverLog.logConfig("SHUTDOWN", "sent termination signal to server socket"); } catch (IOException ee) { serverLog.logConfig("SHUTDOWN", "termination signal to server socket missed (server shutdown, ok)"); } JakartaCommonsHttpClient.closeAllConnections(); MultiThreadedHttpConnectionManager.shutdownAll(); // idle until the processes are down if (server.isAlive()) { Thread.sleep(2000); // wait a while server.interrupt(); MultiThreadedHttpConnectionManager.shutdownAll(); } serverLog.logConfig("SHUTDOWN", "server has terminated"); sb.close(); MultiThreadedHttpConnectionManager.shutdownAll(); } } catch (Exception e) { serverLog.logSevere("STARTUP", "Unexpected Error: " + e.getClass().getName(),e); //System.exit(1); } } catch (Exception ee) { serverLog.logSevere("STARTUP", "FATAL ERROR: " + ee.getMessage(),ee); } finally { startupFinishedSync.V(); } serverLog.logConfig("SHUTDOWN", "goodbye. (this is the last line)"); //try { // System.exit(0); //} catch (Exception e) {} // was once stopped by de.anomic.net.ftpc$sm.checkExit(ftpc.java:1790) } /** * Loads the configuration from the data-folder. * FIXME: Why is this called over and over again from every method, instead * of setting the configurationdata once for this class in main? * * @param mes Where are we called from, so that the errormessages can be * more descriptive. * @param homePath Root-path where all the information is to be found. * @return Properties read from the configurationfile. */ private static Properties configuration(String mes, File homePath) { serverLog.logConfig(mes, "Application Root Path: " + homePath.toString()); // read data folder File dataFolder = new File(homePath, "DATA"); if (!(dataFolder.exists())) { serverLog.logSevere(mes, "Application was never started or root path wrong."); System.exit(-1); } Properties config = new Properties(); try { config.load(new FileInputStream(new File(homePath, "DATA/SETTINGS/yacy.conf"))); } catch (FileNotFoundException e) { serverLog.logSevere(mes, "could not find configuration file."); System.exit(-1); } catch (IOException e) { serverLog.logSevere(mes, "could not read configuration file."); System.exit(-1); } return config; } public static void shutdown() { if (sb != null) { // YaCy is running in the same runtime. we can shutdown via interrupt sb.terminate(); } else { File applicationRoot = new File(System.getProperty("user.dir").replace('\\', '/')); shutdown(applicationRoot); } } /** * Call the shutdown-page of YaCy to tell it to shut down. This method is * called if you start yacy with the argument -shutdown. * * @param homePath Root-path where all the information is to be found. */ static void shutdown(File homePath) { // start up System.out.println(copyright); System.out.println(hline); Properties config = configuration("REMOTE-SHUTDOWN", homePath); // read port int port = serverCore.getPortNr(config.getProperty("port", "8080")); // read password String encodedPassword = (String) config.get(httpd.ADMIN_ACCOUNT_B64MD5); if (encodedPassword == null) encodedPassword = ""; // not defined // send 'wget' to web interface httpHeader requestHeader = new httpHeader(); requestHeader.put(httpHeader.AUTHORIZATION, "realm=" + encodedPassword); // for http-authentify JakartaCommonsHttpClient con = new JakartaCommonsHttpClient(10000, requestHeader, null); JakartaCommonsHttpResponse res = null; try { res = con.GET("http://localhost:"+ port +"/Steering.html?shutdown="); // read response if (res.getStatusLine().startsWith("2")) { serverLog.logConfig("REMOTE-SHUTDOWN", "YACY accepted shutdown command."); serverLog.logConfig("REMOTE-SHUTDOWN", "Stand by for termination, which may last some seconds."); ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { serverFileUtils.copyToStream(new BufferedInputStream(res.getDataAsStream()), new BufferedOutputStream(bos)); } finally { res.closeStream(); } } else { serverLog.logSevere("REMOTE-SHUTDOWN", "error response from YACY socket: " + res.getStatusLine()); System.exit(-1); } } catch (IOException e) { serverLog.logSevere("REMOTE-SHUTDOWN", "could not establish connection to YACY socket: " + e.getMessage()); System.exit(-1); } finally { // release connection if(res != null) { res.closeStream(); } } // finished serverLog.logConfig("REMOTE-SHUTDOWN", "SUCCESSFULLY FINISHED remote-shutdown:"); serverLog.logConfig("REMOTE-SHUTDOWN", "YACY will terminate after working off all enqueued tasks."); } /** * This method gets all found words and outputs a statistic about the score * of the words. The output of this method can be used to create stop-word * lists. This method will be called if you start yacy with the argument * -genwordstat. * FIXME: How can stop-word list be created from this output? What type of * score is output? * * @param homePath Root-Path where all the information is to be found. */ private static void genWordstat(File homePath) { // start up System.out.println(copyright); System.out.println(hline); Properties config = configuration("GEN-WORDSTAT", homePath); // load words serverLog.logInfo("GEN-WORDSTAT", "loading words..."); HashMap<String, String> words = loadWordMap(new File(homePath, "yacy.words")); // find all hashes serverLog.logInfo("GEN-WORDSTAT", "searching all word-hash databases..."); File dbRoot = new File(homePath, config.getProperty("dbPath")); enumerateFiles ef = new enumerateFiles(new File(dbRoot, "WORDS"), true, false, true, true); File f; String h; kelondroMScoreCluster<String> hs = new kelondroMScoreCluster<String>(); while (ef.hasMoreElements()) { f = ef.nextElement(); h = f.getName().substring(0, yacySeedDB.commonHashLength); hs.addScore(h, (int) f.length()); } // list the hashes in reverse order serverLog.logInfo("GEN-WORDSTAT", "listing words in reverse size order..."); String w; Iterator<String> i = hs.scores(false); while (i.hasNext()) { h = i.next(); w = words.get(h); if (w == null) System.out.print("# " + h); else System.out.print(w); System.out.println(" - " + hs.getScore(h)); } // finished serverLog.logConfig("GEN-WORDSTAT", "FINISHED"); } /** * @param homePath path to the YaCy directory * @param networkName */ public static void minimizeUrlDB(File homePath, String networkName) { // run with "java -classpath classes yacy -minimizeUrlDB" try {serverLog.configureLogging(homePath, new File(homePath, "DATA/LOG/yacy.logging"));} catch (Exception e) {} File indexPrimaryRoot = new File(homePath, "DATA/INDEX"); File indexSecondaryRoot = new File(homePath, "DATA/INDEX"); File indexRoot2 = new File(homePath, "DATA/INDEX2"); serverLog log = new serverLog("URL-CLEANUP"); try { log.logInfo("STARTING URL CLEANUP"); // db containing all currently loades urls indexRepositoryReference currentUrlDB = new indexRepositoryReference(new File(indexSecondaryRoot, networkName)); // db used to hold all neede urls indexRepositoryReference minimizedUrlDB = new indexRepositoryReference(new File(indexRoot2, networkName)); int cacheMem = (int)(serverMemory.max() - serverMemory.total()); if (cacheMem < 2048000) throw new OutOfMemoryError("Not enough memory available to start clean up."); plasmaWordIndex wordIndex = new plasmaWordIndex(networkName, log, indexPrimaryRoot, indexSecondaryRoot, 10000); Iterator<indexContainer> indexContainerIterator = wordIndex.wordContainers("AAAAAAAAAAAA", false, false); long urlCounter = 0, wordCounter = 0; long wordChunkStart = System.currentTimeMillis(), wordChunkEnd = 0; String wordChunkStartHash = "AAAAAAAAAAAA", wordChunkEndHash; while (indexContainerIterator.hasNext()) { indexContainer wordIdxContainer = null; try { wordCounter++; wordIdxContainer = indexContainerIterator.next(); // the combined container will fit, read the container Iterator<indexRWIRowEntry> wordIdxEntries = wordIdxContainer.entries(); indexRWIEntry iEntry; while (wordIdxEntries.hasNext()) { iEntry = wordIdxEntries.next(); String urlHash = iEntry.urlHash(); if ((currentUrlDB.exists(urlHash)) && (!minimizedUrlDB.exists(urlHash))) try { indexURLReference urlEntry = currentUrlDB.load(urlHash, null, 0); urlCounter++; minimizedUrlDB.store(urlEntry); if (urlCounter % 500 == 0) { log.logInfo(urlCounter + " URLs found so far."); } } catch (IOException e) {} } if (wordCounter%500 == 0) { wordChunkEndHash = wordIdxContainer.getWordHash(); wordChunkEnd = System.currentTimeMillis(); long duration = wordChunkEnd - wordChunkStart; log.logInfo(wordCounter + " words scanned " + "[" + wordChunkStartHash + " .. " + wordChunkEndHash + "]\n" + "Duration: "+ 500*1000/duration + " words/s" + " | Free memory: " + serverMemory.free() + " | Total memory: " + serverMemory.total()); wordChunkStart = wordChunkEnd; wordChunkStartHash = wordChunkEndHash; } // we have read all elements, now we can close it wordIdxContainer = null; } catch (Exception e) { log.logSevere("Exception", e); } finally { if (wordIdxContainer != null) try { wordIdxContainer = null; } catch (Exception e) {} } } log.logInfo("current LURL DB contains " + currentUrlDB.size() + " entries."); log.logInfo("mimimized LURL DB contains " + minimizedUrlDB.size() + " entries."); currentUrlDB.close(); minimizedUrlDB.close(); wordIndex.close(); // TODO: rename the mimimized UrlDB to the name of the previous UrlDB log.logInfo("FINISHED URL CLEANUP, WAIT FOR DUMP"); log.logInfo("You can now backup your old URL DB and rename minimized/urlHash.db to urlHash.db"); log.logInfo("TERMINATED URL CLEANUP"); } catch (Exception e) { log.logSevere("Exception: " + e.getMessage(), e); } catch (Error e) { log.logSevere("Error: " + e.getMessage(), e); } } /** * Reads all words from the given file and creates a hashmap, where key is * the plasma word hash and value is the word itself. * * @param wordlist File where the words are stored. * @return HashMap with the hash-word - relation. */ private static HashMap<String, String> loadWordMap(File wordlist) { // returns a hash-word - Relation HashMap<String, String> wordmap = new HashMap<String, String>(); try { String word; BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(wordlist))); while ((word = br.readLine()) != null) wordmap.put(indexWord.word2hash(word), word); br.close(); } catch (IOException e) {} return wordmap; } /** * Cleans a wordlist in a file according to the length of the words. The * file with the given filename is read and then only the words in the given * length-range are written back to the file. * * @param wordlist Name of the file the words are stored in. * @param minlength Minimal needed length for each word to be stored. * @param maxlength Maximal allowed length for each word to be stored. */ private static void cleanwordlist(String wordlist, int minlength, int maxlength) { // start up System.out.println(copyright); System.out.println(hline); serverLog.logConfig("CLEAN-WORDLIST", "START"); String word; TreeSet<String> wordset = new TreeSet<String>(); int count = 0; try { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(wordlist))); String seps = "' .,:/-&"; while ((word = br.readLine()) != null) { word = word.toLowerCase().trim(); for (int i = 0; i < seps.length(); i++) { if (word.indexOf(seps.charAt(i)) >= 0) word = word.substring(0, word.indexOf(seps.charAt(i))); } if ((word.length() >= minlength) && (word.length() <= maxlength)) wordset.add(word); count++; } br.close(); if (wordset.size() != count) { count = count - wordset.size(); BufferedWriter bw = new BufferedWriter(new PrintWriter(new FileWriter(wordlist))); while (wordset.size() > 0) { word = wordset.first(); bw.write(word + "\n"); wordset.remove(word); } bw.close(); serverLog.logInfo("CLEAN-WORDLIST", "shrinked wordlist by " + count + " words."); } else { serverLog.logInfo("CLEAN-WORDLIST", "not necessary to change wordlist"); } } catch (IOException e) { serverLog.logSevere("CLEAN-WORDLIST", "ERROR: " + e.getMessage()); System.exit(-1); } // finished serverLog.logConfig("CLEAN-WORDLIST", "FINISHED"); } private static void transferCR(String targetaddress, String crfile) { File f = new File(crfile); try { byte[] b = serverFileUtils.read(f); String result = yacyClient.transfer(targetaddress, f.getName(), b); if (result == null) serverLog.logInfo("TRANSFER-CR", "transmitted file " + crfile + " to " + targetaddress + " successfully"); else serverLog.logInfo("TRANSFER-CR", "error transmitting file " + crfile + " to " + targetaddress + ": " + result); } catch (IOException e) { serverLog.logInfo("TRANSFER-CR", "could not read file " + crfile); } } private static String[] shift(String[] args, int pos, int count) { String[] newargs = new String[args.length - count]; System.arraycopy(args, 0, newargs, 0, pos); System.arraycopy(args, pos + count, newargs, pos, args.length - pos - count); return newargs; } /** * Uses an Iteration over urlHash.db to detect malformed URL-Entries. * Damaged URL-Entries will be marked in a HashSet and removed at the end of the function. * * @param homePath Root-Path where all information is to be found. */ private static void urldbcleanup(File homePath, String networkName) { File root = homePath; File indexroot = new File(root, "DATA/INDEX"); try {serverLog.configureLogging(homePath, new File(homePath, "DATA/LOG/yacy.logging"));} catch (Exception e) {} indexRepositoryReference currentUrlDB = new indexRepositoryReference(new File(indexroot, networkName)); currentUrlDB.deadlinkCleaner(null); currentUrlDB.close(); } private static void RWIHashList(File homePath, String targetName, String resource, String format) { plasmaWordIndex WordIndex = null; serverLog log = new serverLog("HASHLIST"); File indexPrimaryRoot = new File(homePath, "DATA/INDEX"); File indexSecondaryRoot = new File(homePath, "DATA/INDEX"); String wordChunkStartHash = "AAAAAAAAAAAA"; try {serverLog.configureLogging(homePath, new File(homePath, "DATA/LOG/yacy.logging"));} catch (Exception e) {} log.logInfo("STARTING CREATION OF RWI-HASHLIST"); File root = homePath; try { Iterator<indexContainer> indexContainerIterator = null; if (resource.equals("all")) { WordIndex = new plasmaWordIndex("freeworld", log, indexPrimaryRoot, indexSecondaryRoot, 10000); indexContainerIterator = WordIndex.wordContainers(wordChunkStartHash, false, false); } int counter = 0; indexContainer container = null; if (format.equals("zip")) { log.logInfo("Writing Hashlist to ZIP-file: " + targetName + ".zip"); ZipEntry zipEntry = new ZipEntry(targetName + ".txt"); File file = new File(root, targetName + ".zip"); ZipOutputStream bos = new ZipOutputStream(new FileOutputStream(file)); bos.putNextEntry(zipEntry); if(indexContainerIterator != null) { while (indexContainerIterator.hasNext()) { counter++; container = indexContainerIterator.next(); bos.write((container.getWordHash()).getBytes()); bos.write(serverCore.CRLF); if (counter % 500 == 0) { log.logInfo("Found " + counter + " Hashs until now. Last found Hash: " + container.getWordHash()); } } } bos.flush(); bos.close(); } else { log.logInfo("Writing Hashlist to TXT-file: " + targetName + ".txt"); File file = new File(root, targetName + ".txt"); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file)); if(indexContainerIterator != null) { while (indexContainerIterator.hasNext()) { counter++; container = indexContainerIterator.next(); bos.write((container.getWordHash()).getBytes()); bos.write(serverCore.CRLF); if (counter % 500 == 0) { log.logInfo("Found " + counter + " Hashs until now. Last found Hash: " + container.getWordHash()); } } } bos.flush(); bos.close(); } log.logInfo("Total number of Hashs: " + counter + ". Last found Hash: " + (container == null ? "null" : container.getWordHash())); } catch (IOException e) { log.logSevere("IOException", e); } if (WordIndex != null) { WordIndex.close(); WordIndex = null; } } /** * Searching for peers affected by Bug * @param homePath */ public static void testPeerDB(File homePath) { try { File yacyDBPath = new File(homePath, "DATA/INDEX/freeworld/NETWORK"); String[] dbFileNames = {"seed.new.db","seed.old.db","seed.pot.db"}; for (int i=0; i < dbFileNames.length; i++) { File dbFile = new File(yacyDBPath,dbFileNames[i]); kelondroMapObjects db = new kelondroMapObjects(new kelondroBLOBTree(dbFile, true, true, yacySeedDB.commonHashLength, 480, '#', kelondroBase64Order.enhancedCoder, true, false, true), 500, yacySeedDB.sortFields, yacySeedDB.longaccFields, yacySeedDB.doubleaccFields, null, null); kelondroMapObjects.mapIterator it; it = db.maps(true, false); while (it.hasNext()) { Map<String, String> dna = it.next(); String peerHash = dna.get("key"); if (peerHash.length() < yacySeedDB.commonHashLength) { String peerName = dna.get("Name"); String peerIP = dna.get("IP"); String peerPort = dna.get("Port"); while (peerHash.length() < yacySeedDB.commonHashLength) { peerHash = peerHash + "_"; } System.err.println("Invalid Peer-Hash found in '" + dbFileNames[i] + "': " + peerName + ":" + peerHash + ", http://" + peerIP + ":" + peerPort); } } db.close(); } } catch (Exception e) { e.printStackTrace(); } } /** * Main-method which is started by java. Checks for special arguments or * starts up the application. * * @param args * Given arguments from the command line. */ public static void main(String args[]) { // check assertion status //ClassLoader.getSystemClassLoader().setDefaultAssertionStatus(true); boolean assertionenabled = false; assert assertionenabled = true; if (assertionenabled) System.out.println("Asserts are enabled"); // check memory amount System.gc(); long startupMemFree = serverMemory.free(); long startupMemTotal = serverMemory.total(); // go into headless awt mode System.setProperty("java.awt.headless", "true"); File applicationRoot = new File(System.getProperty("user.dir").replace('\\', '/')); //System.out.println("args.length=" + args.length); //System.out.print("args=["); for (int i = 0; i < args.length; i++) System.out.print(args[i] + ", "); System.out.println("]"); if ((args.length >= 1) && ((args[0].toLowerCase().equals("-startup")) || (args[0].equals("-start")))) { // normal start-up of yacy if (args.length == 2) applicationRoot= new File(args[1]); startup(applicationRoot, startupMemFree, startupMemTotal); } else if ((args.length >= 1) && ((args[0].toLowerCase().equals("-shutdown")) || (args[0].equals("-stop")))) { // normal shutdown of yacy if (args.length == 2) applicationRoot= new File(args[1]); shutdown(applicationRoot); } else if ((args.length >= 1) && (args[0].toLowerCase().equals("-minimizeurldb"))) { // migrate words from DATA/PLASMADB/WORDS path to assortment cache, if possible // attention: this may run long and should not be interrupted! if (args.length >= 3 && args[1].toLowerCase().equals("-cache")) { args = shift(args, 1, 2); } if (args.length == 2) applicationRoot= new File(args[1]); minimizeUrlDB(applicationRoot, "freeworld"); } else if ((args.length >= 1) && (args[0].toLowerCase().equals("-testpeerdb"))) { if (args.length == 2) { applicationRoot = new File(args[1]); } else if (args.length > 2) { System.err.println("Usage: -testPeerDB [homeDbRoot]"); } testPeerDB(applicationRoot); } else if ((args.length >= 1) && (args[0].toLowerCase().equals("-genwordstat"))) { // this can help to create a stop-word list // to use this, you need a 'yacy.words' file in the root path // start this with "java -classpath classes yacy -genwordstat [<rootdir>]" if (args.length == 2) applicationRoot= new File(args[1]); genWordstat(applicationRoot); } else if ((args.length == 4) && (args[0].toLowerCase().equals("-cleanwordlist"))) { // this can be used to organize and clean a word-list // start this with "java -classpath classes yacy -cleanwordlist <word-file> <minlength> <maxlength>" int minlength = Integer.parseInt(args[2]); int maxlength = Integer.parseInt(args[3]); cleanwordlist(args[1], minlength, maxlength); } else if ((args.length >= 1) && (args[0].toLowerCase().equals("-transfercr"))) { // transfer a single cr file to a remote peer String targetaddress = args[1]; String crfile = args[2]; transferCR(targetaddress, crfile); } else if ((args.length >= 1) && (args[0].toLowerCase().equals("-urldbcleanup"))) { // generate a url list and save it in a file if (args.length == 2) applicationRoot= new File(args[1]); urldbcleanup(applicationRoot, "freeworld"); } else if ((args.length >= 1) && (args[0].toLowerCase().equals("-rwihashlist"))) { // generate a url list and save it in a file String domain = "all"; String format = "txt"; if (args.length >= 2) domain= args[1]; if (args.length >= 3) format= args[2]; if (args.length == 4) applicationRoot= new File(args[3]); String outfile = "rwihashlist_" + System.currentTimeMillis(); RWIHashList(applicationRoot, outfile, domain, format); } else { if (args.length == 1) applicationRoot= new File(args[0]); startup(applicationRoot, startupMemFree, startupMemTotal); } } } /** * This class is a helper class whose instance is started, when the java virtual * machine shuts down. Signals the plasmaSwitchboard to shut down. */ class shutdownHookThread extends Thread { private plasmaSwitchboard sb = null; private Thread mainThread = null; public shutdownHookThread(Thread mainThread, plasmaSwitchboard sb) { super(); this.sb = sb; this.mainThread = mainThread; } public void run() { try { if (!this.sb.isTerminated()) { serverLog.logConfig("SHUTDOWN","Shutdown via shutdown hook."); // sending the yacy main thread a shutdown signal serverLog.logFine("SHUTDOWN","Signaling shutdown to the switchboard."); this.sb.terminate(); // waiting for the yacy thread to finish execution serverLog.logFine("SHUTDOWN","Waiting for main thread to finish."); if (this.mainThread.isAlive() && !this.sb.isTerminated()) { this.mainThread.join(); } } } catch (Exception e) { serverLog.logSevere("SHUTDOWN","Unexpected error. " + e.getClass().getName(),e); } } }
true
true
private static void startup(File homePath, long startupMemFree, long startupMemTotal) { int oldRev=0; int newRev=0; try { // start up System.out.println(copyright); System.out.println(hline); // check java version try { "a".codePointAt(0); // needs at least Java 1.5 } catch (NoSuchMethodError e) { System.err.println("STARTUP: Java Version too low. You need at least Java 1.5 to run YaCy"); Thread.sleep(3000); System.exit(-1); } // ensure that there is a DATA directory, if not, create one and if that fails warn and die File f = homePath; if (!(f.exists())) f.mkdirs(); f = new File(homePath, "DATA/"); if (!(f.exists())) f.mkdirs(); if (!(f.exists())) { System.err.println("Error creating DATA-directory in " + homePath.toString() + " . Please check your write-permission for this folder. YaCy will now terminate."); System.exit(-1); } // setting up logging f = new File(homePath, "DATA/LOG/yacy.logging"); if (!(new File(f.getPath()).exists())) f.mkdirs(); if (!f.exists()) try { serverFileUtils.copy(new File(homePath, "yacy.logging"), f); }catch (IOException e){ System.out.println("could not copy yacy.logging"); } try{ serverLog.configureLogging(homePath, f); } catch (IOException e) { System.out.println("could not find logging properties in homePath=" + homePath); e.printStackTrace(); } serverLog.logConfig("STARTUP", "Java version: " + System.getProperty("java.version", "no-java-version")); serverLog.logConfig("STARTUP", "Operation system: " + System.getProperty("os.name","unknown")); serverLog.logConfig("STARTUP", "Application root-path: " + homePath); serverLog.logConfig("STARTUP", "Time zone: UTC" + serverDate.UTCDiffString() + "; UTC+0000 is " + System.currentTimeMillis()); serverLog.logConfig("STARTUP", "Maximum file system path length: " + serverSystem.maxPathLength); f = new File(homePath, "DATA/yacy.running"); if (f.exists()) { // another instance running? VM crash? User will have to care about this serverLog.logSevere("STARTUP", "WARNING: the file " + f + " exists, this usually means that a YaCy instance is still running"); f.delete(); } f.createNewFile(); f.deleteOnExit(); pro = new File(homePath, "libx").exists(); String oldconf = "DATA/SETTINGS/httpProxy.conf".replace("/", File.separator); String newconf = "DATA/SETTINGS/yacy.conf".replace("/", File.separator); File oldconffile = new File(homePath, oldconf); if (oldconffile.exists()) { oldconffile.renameTo(new File(homePath, newconf)); } sb = new plasmaSwitchboard(homePath, "defaults/yacy.init".replace("/", File.separator), newconf, pro); sbSync.V(); // signal that the sb reference was set // save information about available memory at startup time sb.setConfig("memoryFreeAfterStartup", startupMemFree); sb.setConfig("memoryTotalAfterStartup", startupMemTotal); // hardcoded, forced, temporary value-migration sb.setConfig("htTemplatePath", "htroot/env/templates"); sb.setConfig("parseableExt", "html,htm,txt,php,shtml,asp"); // if we are running an SVN version, we try to detect the used svn revision now ... final Properties buildProp = new Properties(); File buildPropFile = new File(homePath,"build.properties"); try { buildProp.load(new FileInputStream(buildPropFile)); } catch (Exception e) { serverLog.logWarning("STARTUP", buildPropFile.toString() + " not found in settings path"); } oldRev=Integer.parseInt(sb.getConfig("svnRevision", "0")); try { if (buildProp.containsKey("releaseNr")) { // this normally looks like this: $Revision$ final String svnReleaseNrStr = buildProp.getProperty("releaseNr"); final Pattern pattern = Pattern.compile("\\$Revision:\\s(.*)\\s\\$",Pattern.DOTALL+Pattern.CASE_INSENSITIVE); final Matcher matcher = pattern.matcher(svnReleaseNrStr); if (matcher.find()) { final String svrReleaseNr = matcher.group(1); try { try {version = Double.parseDouble(vString);} catch (NumberFormatException e) {version = (float) 0.1;} version = yacyVersion.versvn2combinedVersion(version, Integer.parseInt(svrReleaseNr)); } catch (NumberFormatException e) {} sb.setConfig("svnRevision", svrReleaseNr); } } newRev=Integer.parseInt(sb.getConfig("svnRevision", "0")); } catch (Exception e) { System.err.println("Unable to determine the currently used SVN revision number."); } sb.setConfig("version", Double.toString(version)); sb.setConfig("vString", yacyVersion.combined2prettyVersion(Double.toString(version))); sb.setConfig("vdate", (vDATE.startsWith("@")) ? serverDate.formatShortDay() : vDATE); sb.setConfig("applicationRoot", homePath.toString()); serverLog.logConfig("STARTUP", "YACY Version: " + version + ", Built " + sb.getConfig("vdate", "00000000")); yacyVersion.latestRelease = version; // read environment int timeout = Math.max(20000, Integer.parseInt(sb.getConfig("httpdTimeout", "20000"))); // create some directories final File htRootPath = new File(homePath, sb.getConfig("htRootPath", "htroot")); final File htDocsPath = sb.getConfigPath(plasmaSwitchboard.HTDOCS_PATH, plasmaSwitchboard.HTDOCS_PATH_DEFAULT); if (!(htDocsPath.exists())) htDocsPath.mkdir(); //final File htTemplatePath = new File(homePath, sb.getConfig("htTemplatePath","htdocs")); // create default notifier picture //TODO: Use templates instead of copying images ... if (!((new File(htDocsPath, "notifier.gif")).exists())) try { serverFileUtils.copy(new File(htRootPath, "env/grafics/empty.gif"), new File(htDocsPath, "notifier.gif")); } catch (IOException e) {} final File htdocsReadme = new File(htDocsPath, "readme.txt"); if (!(htdocsReadme.exists())) try {serverFileUtils.copy(( "This is your root directory for individual Web Content\r\n" + "\r\n" + "Please place your html files into the www subdirectory.\r\n" + "The URL of that path is either\r\n" + "http://www.<your-peer-name>.yacy or\r\n" + "http://<your-ip>:<your-port>/www\r\n" + "\r\n" + "Other subdirectories may be created; they map to corresponding sub-domains.\r\n" + "This directory shares it's content with the applications htroot path, so you\r\n" + "may access your yacy search page with\r\n" + "http://<your-peer-name>.yacy/\r\n" + "\r\n").getBytes(), htdocsReadme);} catch (IOException e) { System.out.println("Error creating htdocs readme: " + e.getMessage()); } final File wwwDefaultPath = new File(htDocsPath, "www"); if (!(wwwDefaultPath.exists())) wwwDefaultPath.mkdir(); final File shareDefaultPath = new File(htDocsPath, "share"); if (!(shareDefaultPath.exists())) shareDefaultPath.mkdir(); migration.migrate(sb, oldRev, newRev); // delete old release files int deleteOldDownloadsAfterDays = (int) sb.getConfigLong("update.deleteOld", 30); yacyVersion.deleteOldDownloads(sb.releasePath, deleteOldDownloadsAfterDays ); // set user-agent final String userAgent = "yacy/" + Double.toString(version) + " (www.yacy.net; " + de.anomic.http.HttpClient.getSystemOST() + ")"; JakartaCommonsHttpClient.setUserAgent(userAgent); // start main threads final String port = sb.getConfig("port", "8080"); try { final httpd protocolHandler = new httpd(sb); final serverCore server = new serverCore( timeout /*control socket timeout in milliseconds*/, true /* block attacks (wrong protocol) */, protocolHandler /*command class*/, sb, 30000 /*command max length incl. GET args*/); server.setName("httpd:"+port); server.setPriority(Thread.MAX_PRIORITY); server.setObeyIntermission(false); if (server == null) { serverLog.logSevere("STARTUP", "Failed to start server. Probably port " + port + " already in use."); } else { // first start the server sb.deployThread("10_httpd", "HTTPD Server/Proxy", "the HTTPD, used as web server and proxy", null, server, 0, 0, 0, 0); //server.start(); // open the browser window final boolean browserPopUpTrigger = sb.getConfig("browserPopUpTrigger", "true").equals("true"); if (browserPopUpTrigger) { String browserPopUpPage = sb.getConfig("browserPopUpPage", "ConfigBasic.html"); //boolean properPW = (sb.getConfig("adminAccount", "").length() == 0) && (sb.getConfig(httpd.ADMIN_ACCOUNT_B64MD5, "").length() > 0); //if (!properPW) browserPopUpPage = "ConfigBasic.html"; final String browserPopUpApplication = sb.getConfig("browserPopUpApplication", "netscape"); serverSystem.openBrowser((server.withSSL()?"https":"http") + "://localhost:" + serverCore.getPortNr(port) + "/" + browserPopUpPage, browserPopUpApplication); } // Copy the shipped locales into DATA, existing files are overwritten final File locale_work = sb.getConfigPath("locale.work", "DATA/LOCALE/locales"); final File locale_source = sb.getConfigPath("locale.source", "locales"); try{ final File[] locale_source_files = locale_source.listFiles(); locale_work.mkdirs(); File target; for (int i=0; i < locale_source_files.length; i++){ target = new File(locale_work, locale_source_files[i].getName()); if (locale_source_files[i].getName().endsWith(".lng")) { if (target.exists()) target.delete(); serverFileUtils.copy(locale_source_files[i], target); } } serverLog.logInfo("STARTUP", "Copied the default locales to " + locale_work.toString()); }catch(NullPointerException e){ serverLog.logSevere("STARTUP", "Nullpointer Exception while copying the default Locales"); } //regenerate Locales from Translationlist, if needed final String lang = sb.getConfig("locale.language", ""); if (!lang.equals("") && !lang.equals("default")) { //locale is used String currentRev = ""; try{ final BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File(sb.getConfigPath("locale.translated_html", "DATA/LOCALE/htroot"), lang+"/version" )))); currentRev = br.readLine(); br.close(); }catch(IOException e){ //Error } if (!currentRev.equals(sb.getConfig("svnRevision", ""))) try { //is this another version?! final File sourceDir = new File(sb.getConfig("htRootPath", "htroot")); final File destDir = new File(sb.getConfigPath("locale.translated_html", "DATA/LOCALE/htroot"), lang); if (translator.translateFilesRecursive(sourceDir, destDir, new File(locale_work, lang + ".lng"), "html,template,inc", "locale")){ //translate it //write the new Versionnumber final BufferedWriter bw = new BufferedWriter(new PrintWriter(new FileWriter(new File(destDir, "version")))); bw.write(sb.getConfig("svnRevision", "Error getting Version")); bw.close(); } } catch (IOException e) {} } // initialize number formatter with this locale yFormatter.setLocale(lang); // registering shutdown hook serverLog.logConfig("STARTUP", "Registering Shutdown Hook"); final Runtime run = Runtime.getRuntime(); run.addShutdownHook(new shutdownHookThread(Thread.currentThread(), sb)); // save information about available memory after all initializations //try { sb.setConfig("memoryFreeAfterInitBGC", serverMemory.free()); sb.setConfig("memoryTotalAfterInitBGC", serverMemory.total()); System.gc(); sb.setConfig("memoryFreeAfterInitAGC", serverMemory.free()); sb.setConfig("memoryTotalAfterInitAGC", serverMemory.total()); //} catch (ConcurrentModificationException e) {} // signal finished startup startupFinishedSync.V(); // wait for server shutdown try { sb.waitForShutdown(); } catch (Exception e) { serverLog.logSevere("MAIN CONTROL LOOP", "PANIC: " + e.getMessage(),e); } // shut down if (kelondroRowCollection.sortingthreadexecutor != null) kelondroRowCollection.sortingthreadexecutor.shutdown(); serverLog.logConfig("SHUTDOWN", "caught termination signal"); server.terminate(false); server.interrupt(); server.close(); if (server.isAlive()) try { // TODO only send request, don't read response (cause server is already down resulting in error) yacyURL u = new yacyURL((server.withSSL()?"https":"http")+"://localhost:" + serverCore.getPortNr(port), null); HttpClient.wget(u.toString()); // kick server serverLog.logConfig("SHUTDOWN", "sent termination signal to server socket"); } catch (IOException ee) { serverLog.logConfig("SHUTDOWN", "termination signal to server socket missed (server shutdown, ok)"); } JakartaCommonsHttpClient.closeAllConnections(); MultiThreadedHttpConnectionManager.shutdownAll(); // idle until the processes are down if (server.isAlive()) { Thread.sleep(2000); // wait a while server.interrupt(); MultiThreadedHttpConnectionManager.shutdownAll(); } serverLog.logConfig("SHUTDOWN", "server has terminated"); sb.close(); MultiThreadedHttpConnectionManager.shutdownAll(); } } catch (Exception e) { serverLog.logSevere("STARTUP", "Unexpected Error: " + e.getClass().getName(),e); //System.exit(1); } } catch (Exception ee) { serverLog.logSevere("STARTUP", "FATAL ERROR: " + ee.getMessage(),ee); } finally { startupFinishedSync.V(); } serverLog.logConfig("SHUTDOWN", "goodbye. (this is the last line)"); //try { // System.exit(0); //} catch (Exception e) {} // was once stopped by de.anomic.net.ftpc$sm.checkExit(ftpc.java:1790) }
private static void startup(File homePath, long startupMemFree, long startupMemTotal) { int oldRev=0; int newRev=0; try { // start up System.out.println(copyright); System.out.println(hline); // check java version try { "a".codePointAt(0); // needs at least Java 1.5 } catch (NoSuchMethodError e) { System.err.println("STARTUP: Java Version too low. You need at least Java 1.5 to run YaCy"); Thread.sleep(3000); System.exit(-1); } // ensure that there is a DATA directory, if not, create one and if that fails warn and die File f = homePath; if (!(f.exists())) f.mkdirs(); f = new File(homePath, "DATA/"); if (!(f.exists())) f.mkdirs(); if (!(f.exists())) { System.err.println("Error creating DATA-directory in " + homePath.toString() + " . Please check your write-permission for this folder. YaCy will now terminate."); System.exit(-1); } // setting up logging f = new File(homePath, "DATA/LOG/yacy.logging"); final File logPath =new File(f.getPath()); if (!logPath.exists()) logPath.mkdirs(); if (!f.exists()) try { serverFileUtils.copy(new File(homePath, "yacy.logging"), f); }catch (IOException e){ System.out.println("could not copy yacy.logging"); } try{ serverLog.configureLogging(homePath, f); } catch (IOException e) { System.out.println("could not find logging properties in homePath=" + homePath); e.printStackTrace(); } serverLog.logConfig("STARTUP", "Java version: " + System.getProperty("java.version", "no-java-version")); serverLog.logConfig("STARTUP", "Operation system: " + System.getProperty("os.name","unknown")); serverLog.logConfig("STARTUP", "Application root-path: " + homePath); serverLog.logConfig("STARTUP", "Time zone: UTC" + serverDate.UTCDiffString() + "; UTC+0000 is " + System.currentTimeMillis()); serverLog.logConfig("STARTUP", "Maximum file system path length: " + serverSystem.maxPathLength); f = new File(homePath, "DATA/yacy.running"); if (f.exists()) { // another instance running? VM crash? User will have to care about this serverLog.logSevere("STARTUP", "WARNING: the file " + f + " exists, this usually means that a YaCy instance is still running"); f.delete(); } f.createNewFile(); f.deleteOnExit(); pro = new File(homePath, "libx").exists(); String oldconf = "DATA/SETTINGS/httpProxy.conf".replace("/", File.separator); String newconf = "DATA/SETTINGS/yacy.conf".replace("/", File.separator); File oldconffile = new File(homePath, oldconf); if (oldconffile.exists()) { oldconffile.renameTo(new File(homePath, newconf)); } sb = new plasmaSwitchboard(homePath, "defaults/yacy.init".replace("/", File.separator), newconf, pro); sbSync.V(); // signal that the sb reference was set // save information about available memory at startup time sb.setConfig("memoryFreeAfterStartup", startupMemFree); sb.setConfig("memoryTotalAfterStartup", startupMemTotal); // hardcoded, forced, temporary value-migration sb.setConfig("htTemplatePath", "htroot/env/templates"); sb.setConfig("parseableExt", "html,htm,txt,php,shtml,asp"); // if we are running an SVN version, we try to detect the used svn revision now ... final Properties buildProp = new Properties(); File buildPropFile = new File(homePath,"build.properties"); try { buildProp.load(new FileInputStream(buildPropFile)); } catch (Exception e) { serverLog.logWarning("STARTUP", buildPropFile.toString() + " not found in settings path"); } oldRev=Integer.parseInt(sb.getConfig("svnRevision", "0")); try { if (buildProp.containsKey("releaseNr")) { // this normally looks like this: $Revision$ final String svnReleaseNrStr = buildProp.getProperty("releaseNr"); final Pattern pattern = Pattern.compile("\\$Revision:\\s(.*)\\s\\$",Pattern.DOTALL+Pattern.CASE_INSENSITIVE); final Matcher matcher = pattern.matcher(svnReleaseNrStr); if (matcher.find()) { final String svrReleaseNr = matcher.group(1); try { try {version = Double.parseDouble(vString);} catch (NumberFormatException e) {version = (float) 0.1;} version = yacyVersion.versvn2combinedVersion(version, Integer.parseInt(svrReleaseNr)); } catch (NumberFormatException e) {} sb.setConfig("svnRevision", svrReleaseNr); } } newRev=Integer.parseInt(sb.getConfig("svnRevision", "0")); } catch (Exception e) { System.err.println("Unable to determine the currently used SVN revision number."); } sb.setConfig("version", Double.toString(version)); sb.setConfig("vString", yacyVersion.combined2prettyVersion(Double.toString(version))); sb.setConfig("vdate", (vDATE.startsWith("@")) ? serverDate.formatShortDay() : vDATE); sb.setConfig("applicationRoot", homePath.toString()); serverLog.logConfig("STARTUP", "YACY Version: " + version + ", Built " + sb.getConfig("vdate", "00000000")); yacyVersion.latestRelease = version; // read environment int timeout = Math.max(20000, Integer.parseInt(sb.getConfig("httpdTimeout", "20000"))); // create some directories final File htRootPath = new File(homePath, sb.getConfig("htRootPath", "htroot")); final File htDocsPath = sb.getConfigPath(plasmaSwitchboard.HTDOCS_PATH, plasmaSwitchboard.HTDOCS_PATH_DEFAULT); if (!(htDocsPath.exists())) htDocsPath.mkdir(); //final File htTemplatePath = new File(homePath, sb.getConfig("htTemplatePath","htdocs")); // create default notifier picture //TODO: Use templates instead of copying images ... if (!((new File(htDocsPath, "notifier.gif")).exists())) try { serverFileUtils.copy(new File(htRootPath, "env/grafics/empty.gif"), new File(htDocsPath, "notifier.gif")); } catch (IOException e) {} final File htdocsReadme = new File(htDocsPath, "readme.txt"); if (!(htdocsReadme.exists())) try {serverFileUtils.copy(( "This is your root directory for individual Web Content\r\n" + "\r\n" + "Please place your html files into the www subdirectory.\r\n" + "The URL of that path is either\r\n" + "http://www.<your-peer-name>.yacy or\r\n" + "http://<your-ip>:<your-port>/www\r\n" + "\r\n" + "Other subdirectories may be created; they map to corresponding sub-domains.\r\n" + "This directory shares it's content with the applications htroot path, so you\r\n" + "may access your yacy search page with\r\n" + "http://<your-peer-name>.yacy/\r\n" + "\r\n").getBytes(), htdocsReadme);} catch (IOException e) { System.out.println("Error creating htdocs readme: " + e.getMessage()); } final File wwwDefaultPath = new File(htDocsPath, "www"); if (!(wwwDefaultPath.exists())) wwwDefaultPath.mkdir(); final File shareDefaultPath = new File(htDocsPath, "share"); if (!(shareDefaultPath.exists())) shareDefaultPath.mkdir(); migration.migrate(sb, oldRev, newRev); // delete old release files int deleteOldDownloadsAfterDays = (int) sb.getConfigLong("update.deleteOld", 30); yacyVersion.deleteOldDownloads(sb.releasePath, deleteOldDownloadsAfterDays ); // set user-agent final String userAgent = "yacy/" + Double.toString(version) + " (www.yacy.net; " + de.anomic.http.HttpClient.getSystemOST() + ")"; JakartaCommonsHttpClient.setUserAgent(userAgent); // start main threads final String port = sb.getConfig("port", "8080"); try { final httpd protocolHandler = new httpd(sb); final serverCore server = new serverCore( timeout /*control socket timeout in milliseconds*/, true /* block attacks (wrong protocol) */, protocolHandler /*command class*/, sb, 30000 /*command max length incl. GET args*/); server.setName("httpd:"+port); server.setPriority(Thread.MAX_PRIORITY); server.setObeyIntermission(false); if (server == null) { serverLog.logSevere("STARTUP", "Failed to start server. Probably port " + port + " already in use."); } else { // first start the server sb.deployThread("10_httpd", "HTTPD Server/Proxy", "the HTTPD, used as web server and proxy", null, server, 0, 0, 0, 0); //server.start(); // open the browser window final boolean browserPopUpTrigger = sb.getConfig("browserPopUpTrigger", "true").equals("true"); if (browserPopUpTrigger) { String browserPopUpPage = sb.getConfig("browserPopUpPage", "ConfigBasic.html"); //boolean properPW = (sb.getConfig("adminAccount", "").length() == 0) && (sb.getConfig(httpd.ADMIN_ACCOUNT_B64MD5, "").length() > 0); //if (!properPW) browserPopUpPage = "ConfigBasic.html"; final String browserPopUpApplication = sb.getConfig("browserPopUpApplication", "netscape"); serverSystem.openBrowser((server.withSSL()?"https":"http") + "://localhost:" + serverCore.getPortNr(port) + "/" + browserPopUpPage, browserPopUpApplication); } // Copy the shipped locales into DATA, existing files are overwritten final File locale_work = sb.getConfigPath("locale.work", "DATA/LOCALE/locales"); final File locale_source = sb.getConfigPath("locale.source", "locales"); try{ final File[] locale_source_files = locale_source.listFiles(); locale_work.mkdirs(); File target; for (int i=0; i < locale_source_files.length; i++){ target = new File(locale_work, locale_source_files[i].getName()); if (locale_source_files[i].getName().endsWith(".lng")) { if (target.exists()) target.delete(); serverFileUtils.copy(locale_source_files[i], target); } } serverLog.logInfo("STARTUP", "Copied the default locales to " + locale_work.toString()); }catch(NullPointerException e){ serverLog.logSevere("STARTUP", "Nullpointer Exception while copying the default Locales"); } //regenerate Locales from Translationlist, if needed final String lang = sb.getConfig("locale.language", ""); if (!lang.equals("") && !lang.equals("default")) { //locale is used String currentRev = ""; try{ final BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File(sb.getConfigPath("locale.translated_html", "DATA/LOCALE/htroot"), lang+"/version" )))); currentRev = br.readLine(); br.close(); }catch(IOException e){ //Error } if (!currentRev.equals(sb.getConfig("svnRevision", ""))) try { //is this another version?! final File sourceDir = new File(sb.getConfig("htRootPath", "htroot")); final File destDir = new File(sb.getConfigPath("locale.translated_html", "DATA/LOCALE/htroot"), lang); if (translator.translateFilesRecursive(sourceDir, destDir, new File(locale_work, lang + ".lng"), "html,template,inc", "locale")){ //translate it //write the new Versionnumber final BufferedWriter bw = new BufferedWriter(new PrintWriter(new FileWriter(new File(destDir, "version")))); bw.write(sb.getConfig("svnRevision", "Error getting Version")); bw.close(); } } catch (IOException e) {} } // initialize number formatter with this locale yFormatter.setLocale(lang); // registering shutdown hook serverLog.logConfig("STARTUP", "Registering Shutdown Hook"); final Runtime run = Runtime.getRuntime(); run.addShutdownHook(new shutdownHookThread(Thread.currentThread(), sb)); // save information about available memory after all initializations //try { sb.setConfig("memoryFreeAfterInitBGC", serverMemory.free()); sb.setConfig("memoryTotalAfterInitBGC", serverMemory.total()); System.gc(); sb.setConfig("memoryFreeAfterInitAGC", serverMemory.free()); sb.setConfig("memoryTotalAfterInitAGC", serverMemory.total()); //} catch (ConcurrentModificationException e) {} // signal finished startup startupFinishedSync.V(); // wait for server shutdown try { sb.waitForShutdown(); } catch (Exception e) { serverLog.logSevere("MAIN CONTROL LOOP", "PANIC: " + e.getMessage(),e); } // shut down if (kelondroRowCollection.sortingthreadexecutor != null) kelondroRowCollection.sortingthreadexecutor.shutdown(); serverLog.logConfig("SHUTDOWN", "caught termination signal"); server.terminate(false); server.interrupt(); server.close(); if (server.isAlive()) try { // TODO only send request, don't read response (cause server is already down resulting in error) yacyURL u = new yacyURL((server.withSSL()?"https":"http")+"://localhost:" + serverCore.getPortNr(port), null); HttpClient.wget(u.toString()); // kick server serverLog.logConfig("SHUTDOWN", "sent termination signal to server socket"); } catch (IOException ee) { serverLog.logConfig("SHUTDOWN", "termination signal to server socket missed (server shutdown, ok)"); } JakartaCommonsHttpClient.closeAllConnections(); MultiThreadedHttpConnectionManager.shutdownAll(); // idle until the processes are down if (server.isAlive()) { Thread.sleep(2000); // wait a while server.interrupt(); MultiThreadedHttpConnectionManager.shutdownAll(); } serverLog.logConfig("SHUTDOWN", "server has terminated"); sb.close(); MultiThreadedHttpConnectionManager.shutdownAll(); } } catch (Exception e) { serverLog.logSevere("STARTUP", "Unexpected Error: " + e.getClass().getName(),e); //System.exit(1); } } catch (Exception ee) { serverLog.logSevere("STARTUP", "FATAL ERROR: " + ee.getMessage(),ee); } finally { startupFinishedSync.V(); } serverLog.logConfig("SHUTDOWN", "goodbye. (this is the last line)"); //try { // System.exit(0); //} catch (Exception e) {} // was once stopped by de.anomic.net.ftpc$sm.checkExit(ftpc.java:1790) }
diff --git a/Enemy.java b/Enemy.java index a4f0712..16fbd2d 100644 --- a/Enemy.java +++ b/Enemy.java @@ -1,17 +1,17 @@ import java.awt.Color; import java.awt.Graphics2D; public class Enemy extends Item { public Enemy() { super(0,300,50,50); } public void move(boolean[] keys){ dx=5; super.move(new boolean[] {false,false,false,false,false,false,false}); - if (xpos>600) - xpos=0; + if (x>600) + x=0; } public void redraw(Graphics2D g) { g.setColor(Color.yellow); g.fillRect(x, y, width, height); } }
true
true
public void move(boolean[] keys){ dx=5; super.move(new boolean[] {false,false,false,false,false,false,false}); if (xpos>600) xpos=0; }
public void move(boolean[] keys){ dx=5; super.move(new boolean[] {false,false,false,false,false,false,false}); if (x>600) x=0; }
diff --git a/src/org/broad/igv/sam/reader/ReadGroupFilter.java b/src/org/broad/igv/sam/reader/ReadGroupFilter.java index cbab828a..4db08f38 100644 --- a/src/org/broad/igv/sam/reader/ReadGroupFilter.java +++ b/src/org/broad/igv/sam/reader/ReadGroupFilter.java @@ -1,90 +1,90 @@ /* * Copyright (c) 2007-2011 by The Broad Institute of MIT and Harvard. All Rights Reserved. * * This software is licensed under the terms of the GNU Lesser General Public License (LGPL), * Version 2.1 which is available at http://www.opensource.org/licenses/lgpl-2.1.php. * * THE SOFTWARE IS PROVIDED "AS IS." THE BROAD AND MIT MAKE NO REPRESENTATIONS OR * WARRANTES OF ANY KIND CONCERNING THE SOFTWARE, EXPRESS OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, WHETHER * OR NOT DISCOVERABLE. IN NO EVENT SHALL THE BROAD OR MIT, OR THEIR RESPECTIVE * TRUSTEES, DIRECTORS, OFFICERS, EMPLOYEES, AND AFFILIATES BE LIABLE FOR ANY DAMAGES * OF ANY KIND, INCLUDING, WITHOUT LIMITATION, INCIDENTAL OR CONSEQUENTIAL DAMAGES, * ECONOMIC DAMAGES OR INJURY TO PROPERTY AND LOST PROFITS, REGARDLESS OF WHETHER * THE BROAD OR MIT SHALL BE ADVISED, SHALL HAVE OTHER REASON TO KNOW, OR IN FACT * SHALL KNOW OF THE POSSIBILITY OF THE FOREGOING. */ package org.broad.igv.sam.reader; import org.broad.igv.PreferenceManager; import org.broad.igv.sam.Alignment; import org.broad.igv.ui.util.MessageUtils; import org.broad.tribble.readers.AsciiLineReader; import org.broad.igv.util.ParsingUtils; import org.broad.igv.util.ResourceLocator; import java.io.IOException; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * Created by IntelliJ IDEA. * User: jrobinso * Date: Oct 1, 2009 * Time: 7:09:37 PM * To change this template use File | Settings | File Templates. */ public class ReadGroupFilter { private Set<String> filteredReadGroups; private ReadGroupFilter(Set<String> filteredReadGroups) { this.filteredReadGroups = filteredReadGroups; } public boolean filterAlignment(Alignment alignment) { return filteredReadGroups.contains(alignment.getReadGroup()); } static Map<String, ReadGroupFilter> filterCache = new HashMap(); public static synchronized ReadGroupFilter getFilter() { PreferenceManager samPrefs = PreferenceManager.getInstance(); if (samPrefs.getAsBoolean(PreferenceManager.SAM_FILTER_ALIGNMENTS)) { String filterURL = samPrefs.get(PreferenceManager.SAM_FILTER_URL); ReadGroupFilter filter = filterURL == null ? null : filterCache.get(filterURL); - if (filter == null) { + if (filter == null && filterURL != null && filterURL.trim().length() > 0) { Set<String> readGroups = new HashSet(); AsciiLineReader reader = null; try { reader = ParsingUtils.openAsciiReader(new ResourceLocator(filterURL)); String nextLine; while ((nextLine = reader.readLine()) != null) { readGroups.add(nextLine.trim()); } filter = new ReadGroupFilter(readGroups); filterCache.put(filterURL, filter); } - catch (IOException e) { + catch (Exception e) { MessageUtils.showMessage("Error reading read filter list: " + e.getMessage()); } } return filter; } return null; } }
false
true
public static synchronized ReadGroupFilter getFilter() { PreferenceManager samPrefs = PreferenceManager.getInstance(); if (samPrefs.getAsBoolean(PreferenceManager.SAM_FILTER_ALIGNMENTS)) { String filterURL = samPrefs.get(PreferenceManager.SAM_FILTER_URL); ReadGroupFilter filter = filterURL == null ? null : filterCache.get(filterURL); if (filter == null) { Set<String> readGroups = new HashSet(); AsciiLineReader reader = null; try { reader = ParsingUtils.openAsciiReader(new ResourceLocator(filterURL)); String nextLine; while ((nextLine = reader.readLine()) != null) { readGroups.add(nextLine.trim()); } filter = new ReadGroupFilter(readGroups); filterCache.put(filterURL, filter); } catch (IOException e) { MessageUtils.showMessage("Error reading read filter list: " + e.getMessage()); } } return filter; } return null; }
public static synchronized ReadGroupFilter getFilter() { PreferenceManager samPrefs = PreferenceManager.getInstance(); if (samPrefs.getAsBoolean(PreferenceManager.SAM_FILTER_ALIGNMENTS)) { String filterURL = samPrefs.get(PreferenceManager.SAM_FILTER_URL); ReadGroupFilter filter = filterURL == null ? null : filterCache.get(filterURL); if (filter == null && filterURL != null && filterURL.trim().length() > 0) { Set<String> readGroups = new HashSet(); AsciiLineReader reader = null; try { reader = ParsingUtils.openAsciiReader(new ResourceLocator(filterURL)); String nextLine; while ((nextLine = reader.readLine()) != null) { readGroups.add(nextLine.trim()); } filter = new ReadGroupFilter(readGroups); filterCache.put(filterURL, filter); } catch (Exception e) { MessageUtils.showMessage("Error reading read filter list: " + e.getMessage()); } } return filter; } return null; }
diff --git a/Exercise1/src/main/java/at/ac/tuwien/complang/carfactory/businesslogic/jms/JmsPainter.java b/Exercise1/src/main/java/at/ac/tuwien/complang/carfactory/businesslogic/jms/JmsPainter.java index b6ea398..7afc533 100644 --- a/Exercise1/src/main/java/at/ac/tuwien/complang/carfactory/businesslogic/jms/JmsPainter.java +++ b/Exercise1/src/main/java/at/ac/tuwien/complang/carfactory/businesslogic/jms/JmsPainter.java @@ -1,115 +1,119 @@ package at.ac.tuwien.complang.carfactory.businesslogic.jms; import java.awt.Color; import java.io.Serializable; import javax.jms.JMSException; import javax.jms.MessageConsumer; import javax.jms.MessageProducer; import javax.jms.ObjectMessage; import javax.jms.Queue; import javax.jms.Session; import javax.jms.Topic; import org.apache.activemq.ActiveMQConnectionFactory; import at.ac.tuwien.complang.carfactory.application.enums.PaintState; import at.ac.tuwien.complang.carfactory.application.jms.constants.QueueConstants; import at.ac.tuwien.complang.carfactory.domain.Body; import at.ac.tuwien.complang.carfactory.domain.Car; public class JmsPainter extends JmsAbstractWorker { //Fields private Session session; private Topic carTopic, paintedBodyTopic, paintedCarTopic; private Queue bodyQueue; private MessageConsumer bodyConsumer, carConsumer; private Color color; public JmsPainter(long id, Color color) { super(id); this.color = color; /** * Workflow: * 1. Connect to the Car and Body Topics * 2. Try to take a unpainted car * 3. Try to take an unpainted body * 4. Paint the body (of the car) * 5. Write the body back to the topic (body or car topic) * 6. notify GUI (gui should update the part with the painter id */ } @Override protected void connectToQueues() { //test get Motor ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(); try { connection = connectionFactory.createConnection(); connection.start(); session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); //createQueue connects to a queue if it exists otherwise creates it this.bodyQueue = session.createQueue(QueueConstants.BODYQUEUE); this.bodyConsumer = session.createConsumer(bodyQueue); this.paintedBodyTopic = session.createTopic(QueueConstants.PAINTEDBODYTOPIC); this.carTopic = session.createTopic(QueueConstants.CARTOPIC); this.carConsumer = session.createConsumer(carTopic); this.paintedCarTopic = session.createTopic(QueueConstants.PAINTEDCARTOPIC); System.out.println("Queues connected"); } catch (JMSException e) { e.printStackTrace(); } } public void startWorkLoop() { //the assembly loop never terminates. As long as the assembler is running, it will paint cars and bodys. while(true) { try { ObjectMessage objectMessage = null; while(objectMessage == null) { //Try to get a car from the car Queue (one which is not yet painted) objectMessage = (ObjectMessage) carConsumer.receive(1); if(objectMessage == null) { objectMessage = (ObjectMessage) bodyConsumer.receive(1); } + if(objectMessage == null) { + //Sleep 500ms if both message queues are empty + try { + Thread.sleep(500); + } catch (InterruptedException e) { } + } } Serializable object = (Serializable) objectMessage.getObject(); if(object instanceof Car) { Car car = (Car) object; if(car.getPaintState() == PaintState.PAINTED) { throw new RuntimeException("PAINTED cars should only be in the painted car queue"); } - car.setPaintState(PaintState.PAINTED); car.setColor(pid, color); MessageProducer messageProducer; try { messageProducer = session.createProducer(paintedCarTopic); messageProducer.send(session.createObjectMessage(object)); System.out.println("[Painter] Painted car " + car.getId() + " send to paintedCarTopic"); } catch(JMSException e) { e.printStackTrace(); } } else if (object instanceof Body) { Body body = (Body) object; if(body.getPaintState() == PaintState.PAINTED) { - throw new RuntimeException("PAINTED cars should only be in the painted car queue"); + throw new RuntimeException("PAINTED bodies should only be in the painted bodies queue"); } body.setPaintState(PaintState.PAINTED); body.setColor(pid, color); MessageProducer messageProducer; try { messageProducer = session.createProducer(paintedBodyTopic); messageProducer.send(session.createObjectMessage(object)); System.out.println("[Painter] Painted body " + body.getId() + " send to paintedBodyTopic"); } catch(JMSException e) { e.printStackTrace(); } } } catch (JMSException e) { - // TODO Auto-generated catch block e.printStackTrace(); } } } }
false
true
public void startWorkLoop() { //the assembly loop never terminates. As long as the assembler is running, it will paint cars and bodys. while(true) { try { ObjectMessage objectMessage = null; while(objectMessage == null) { //Try to get a car from the car Queue (one which is not yet painted) objectMessage = (ObjectMessage) carConsumer.receive(1); if(objectMessage == null) { objectMessage = (ObjectMessage) bodyConsumer.receive(1); } } Serializable object = (Serializable) objectMessage.getObject(); if(object instanceof Car) { Car car = (Car) object; if(car.getPaintState() == PaintState.PAINTED) { throw new RuntimeException("PAINTED cars should only be in the painted car queue"); } car.setPaintState(PaintState.PAINTED); car.setColor(pid, color); MessageProducer messageProducer; try { messageProducer = session.createProducer(paintedCarTopic); messageProducer.send(session.createObjectMessage(object)); System.out.println("[Painter] Painted car " + car.getId() + " send to paintedCarTopic"); } catch(JMSException e) { e.printStackTrace(); } } else if (object instanceof Body) { Body body = (Body) object; if(body.getPaintState() == PaintState.PAINTED) { throw new RuntimeException("PAINTED cars should only be in the painted car queue"); } body.setPaintState(PaintState.PAINTED); body.setColor(pid, color); MessageProducer messageProducer; try { messageProducer = session.createProducer(paintedBodyTopic); messageProducer.send(session.createObjectMessage(object)); System.out.println("[Painter] Painted body " + body.getId() + " send to paintedBodyTopic"); } catch(JMSException e) { e.printStackTrace(); } } } catch (JMSException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
public void startWorkLoop() { //the assembly loop never terminates. As long as the assembler is running, it will paint cars and bodys. while(true) { try { ObjectMessage objectMessage = null; while(objectMessage == null) { //Try to get a car from the car Queue (one which is not yet painted) objectMessage = (ObjectMessage) carConsumer.receive(1); if(objectMessage == null) { objectMessage = (ObjectMessage) bodyConsumer.receive(1); } if(objectMessage == null) { //Sleep 500ms if both message queues are empty try { Thread.sleep(500); } catch (InterruptedException e) { } } } Serializable object = (Serializable) objectMessage.getObject(); if(object instanceof Car) { Car car = (Car) object; if(car.getPaintState() == PaintState.PAINTED) { throw new RuntimeException("PAINTED cars should only be in the painted car queue"); } car.setColor(pid, color); MessageProducer messageProducer; try { messageProducer = session.createProducer(paintedCarTopic); messageProducer.send(session.createObjectMessage(object)); System.out.println("[Painter] Painted car " + car.getId() + " send to paintedCarTopic"); } catch(JMSException e) { e.printStackTrace(); } } else if (object instanceof Body) { Body body = (Body) object; if(body.getPaintState() == PaintState.PAINTED) { throw new RuntimeException("PAINTED bodies should only be in the painted bodies queue"); } body.setPaintState(PaintState.PAINTED); body.setColor(pid, color); MessageProducer messageProducer; try { messageProducer = session.createProducer(paintedBodyTopic); messageProducer.send(session.createObjectMessage(object)); System.out.println("[Painter] Painted body " + body.getId() + " send to paintedBodyTopic"); } catch(JMSException e) { e.printStackTrace(); } } } catch (JMSException e) { e.printStackTrace(); } } }
diff --git a/src/main/java/com/araeosia/ArcherGames/CommandHandler.java b/src/main/java/com/araeosia/ArcherGames/CommandHandler.java index 9d191ef..0999ff2 100644 --- a/src/main/java/com/araeosia/ArcherGames/CommandHandler.java +++ b/src/main/java/com/araeosia/ArcherGames/CommandHandler.java @@ -1,362 +1,362 @@ package com.araeosia.ArcherGames; import com.araeosia.ArcherGames.utils.Archer; import com.araeosia.ArcherGames.utils.BookItem; import com.araeosia.ArcherGames.utils.Kit; import java.util.HashMap; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerCommandPreprocessEvent; import org.bukkit.inventory.ItemStack; public class CommandHandler implements CommandExecutor, Listener { public ArcherGames plugin; public CommandHandler(ArcherGames plugin) { this.plugin = plugin; } public HashMap<String, Integer> chunkReloads; /** * * @param sender * @param cmd * @param commandLabel * @param args * @return */ @Override public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { if (cmd.getName().equalsIgnoreCase("vote")) { sender.sendMessage(plugin.strings.get("voteinfo")); for (String s : plugin.voteSites.split("~")) { sender.sendMessage(ChatColor.GREEN + s); return true; } } else if (cmd.getName().equalsIgnoreCase("money")) { if (args.length == 0) { sender.sendMessage(ChatColor.GREEN + sender.getName() + "'s balance is " + plugin.db.getMoney(sender.getName()) + ""); return true; } else { sender.sendMessage(ChatColor.GREEN + args[0] + "'s balance is " + plugin.db.getMoney(args[0])); return true; } } else if (cmd.getName().equalsIgnoreCase("who") || cmd.getName().equalsIgnoreCase("online") || cmd.getName().equalsIgnoreCase("players")) { String outputAlive = ""; int alive = 0; String outputSpec = ""; int spec = 0; for (Player p : plugin.getServer().getOnlinePlayers()) { if (plugin.serverwide.getArcher(p).getPlaying()) { outputAlive += p.getDisplayName() + ", "; alive++; } else { spec++; outputSpec += p.getDisplayName() + ", "; } } sender.sendMessage(ChatColor.GRAY + "" + alive + ChatColor.DARK_GRAY + " Archers are currently playing: "); sender.sendMessage(outputAlive); sender.sendMessage(ChatColor.GRAY + "" + spec + ChatColor.DARK_GRAY + " Spectators are currently watching: "); sender.sendMessage(outputSpec); return true; } else if (cmd.getName().equalsIgnoreCase("kit") || cmd.getName().equalsIgnoreCase("kits")) { if (args.length != 0) { if (ScheduledTasks.gameStatus != 1) { sender.sendMessage(plugin.strings.get("alreadystartedkits")); } else { Kit selectedKit = new Kit(); Boolean isOkay = false; for (Kit kit : plugin.kits) { if (args[0].equalsIgnoreCase(kit.getName())) { isOkay = true; selectedKit = kit; } } if (isOkay) { if (plugin.serverwide.getArcher(sender.getName()).getPlaying()) { sender.sendMessage(String.format(plugin.strings.get("alreadyselected"), plugin.serverwide.getArcher(sender.getName()).getKit().getName())); } if (sender.hasPermission(selectedKit.getPermission())) { plugin.serverwide.joinGame(sender.getName(), selectedKit); sender.sendMessage(String.format(plugin.strings.get("kitgiven"), selectedKit.getName())); } else { sender.sendMessage(ChatColor.RED + "You do not have permission to use this kit."); } } else { sender.sendMessage(ChatColor.RED + "That is not a valid kit."); } } } else { sender.sendMessage(ChatColor.AQUA + "Use /kit (kitname) to select a kit."); sender.sendMessage(ChatColor.DARK_GREEN + plugin.strings.get("kitinfo")); String kits = ""; String kitsNo = ""; for (Kit kit : plugin.kits) { if (sender.hasPermission(kit.getPermission())) { kits += kit.getName() + ", "; } else { kitsNo += kit.getName() + ", "; } } sender.sendMessage(ChatColor.GREEN + kits); sender.sendMessage(ChatColor.DARK_RED + plugin.strings.get("kitnoaccessible")); sender.sendMessage(ChatColor.RED + kitsNo); } return true; } else if (cmd.getName().equalsIgnoreCase("chunk")) { if (sender instanceof Player) { Player player = (Player) sender; player.getWorld().unloadChunk(player.getLocation().getChunk()); player.getWorld().loadChunk(player.getLocation().getChunk()); player.teleport(player.getLocation()); player.sendMessage(ChatColor.GREEN + "Chunk Reloaded."); return true; } else { return false; } } else if (cmd.getName().equalsIgnoreCase("pay")) { if (args.length != 0) { if (args.length != 1) { try { if (Double.parseDouble(args[1]) > 0) { if (plugin.db.hasMoney(sender.getName(), Double.parseDouble(args[1]))) { plugin.db.takeMoney(sender.getName(), Double.parseDouble(args[1])); plugin.db.addMoney(args[0], Double.parseDouble(args[1])); } else { sender.sendMessage("You cannot afford to send this amount of money!"); } sender.sendMessage(ChatColor.GREEN + "$" + args[0] + " paid to " + args[0]); } } catch (Exception e) { return false; } } else { return false; } } else { return false; } } else if (cmd.getName().equalsIgnoreCase("time")) { if (!(ScheduledTasks.gameStatus >= 2)) { sender.sendMessage(ChatColor.GREEN + ((String.format(plugin.strings.get("starttimeleft"), ((plugin.scheduler.preGameCountdown - plugin.scheduler.currentLoop) / 60 + " minute" + (((plugin.scheduler.preGameCountdown - plugin.scheduler.currentLoop) / 60) == 1 ? "" : "s") + ", " + ((plugin.scheduler.preGameCountdown - plugin.scheduler.currentLoop) % 60) + " second" + ((plugin.scheduler.preGameCountdown - plugin.scheduler.currentLoop != 1) ? "s" : "")))))); } else if (!(ScheduledTasks.gameStatus >= 3)) { sender.sendMessage(ChatColor.GREEN + ((String.format(plugin.strings.get("invincibilityend"), ((plugin.scheduler.gameInvincibleCountdown - plugin.scheduler.currentLoop) / 60 + " minute" + (((plugin.scheduler.gameInvincibleCountdown - plugin.scheduler.currentLoop) / 60) == 1 ? "" : "s") + ", " + ((plugin.scheduler.gameInvincibleCountdown - plugin.scheduler.currentLoop) % 60) + " second" + ((plugin.scheduler.gameInvincibleCountdown - plugin.scheduler.currentLoop != 1) ? "s" : "")))))); } else if (!(ScheduledTasks.gameStatus >= 4)) { sender.sendMessage(ChatColor.GREEN + ((plugin.scheduler.gameOvertimeCountdown - plugin.scheduler.currentLoop) % 60 == 0 ? (plugin.scheduler.gameOvertimeCountdown - plugin.scheduler.currentLoop) / 60 + " minutes until overtime starts" : (plugin.scheduler.gameOvertimeCountdown - plugin.scheduler.currentLoop) / 60 + " minutes and " + (plugin.scheduler.gameOvertimeCountdown - plugin.scheduler.currentLoop) % 60 + " seconds until overtime starts.")); } else { sender.sendMessage(ChatColor.RED + "Nothing to time!"); } return true; } else if (cmd.getName().equalsIgnoreCase("timer")) { if (args.length != 0) { if (sender.hasPermission("ArcherGames.admin")) { try { plugin.scheduler.preGameCountdown = Integer.parseInt(args[0]); plugin.scheduler.currentLoop = 0; sender.sendMessage(ChatColor.GREEN + "Time left to start set to " + args[0] + " seconds left."); return true; } catch (Exception e) { sender.sendMessage(ChatColor.RED + "Time could not be set."); return true; } } } } else if (plugin.debug && cmd.getName().equalsIgnoreCase("ArcherGames")) { if (args[0].equalsIgnoreCase("startGame")) { ScheduledTasks.gameStatus = 2; sender.sendMessage(ChatColor.GREEN + "Game started."); plugin.log.info("[ArcherGames/Debug]: Game force-started by " + sender.getName()); return true; } } else if (cmd.getName().equalsIgnoreCase("lockdown")) { if (sender.hasPermission("archergames.admin")) { plugin.getConfig().set("ArcherGames.toggles.lockdownMode", !plugin.configToggles.get("ArcherGames.toggles.lockdownMode")); plugin.saveConfig(); sender.sendMessage(ChatColor.GREEN + "LockDown mode toggled."); return true; } else { return false; } } else if (cmd.getName().equalsIgnoreCase("credtop")) { sender.sendMessage(ChatColor.GREEN + "Here are the top credit amounts on ArcherGames currently:"); HashMap<String, Integer> credits = plugin.db.getTopPoints(); int i = 1; for (String playerName : credits.keySet()) { sender.sendMessage(ChatColor.GREEN + "" + i + ": " + playerName + " | " + credits.get(playerName)); i++; } return true; } else if (cmd.getName().equalsIgnoreCase("baltop")) { sender.sendMessage(ChatColor.GREEN + "Here are the top balance amounts on ArcherGames currently:"); HashMap<String, Integer> balances = plugin.db.getTopPoints(); int i = 1; for (String playerName : balances.keySet()) { sender.sendMessage(ChatColor.GREEN + "" + i + ": " + playerName + " | " + balances.get(playerName)); i++; } return true; } else if (cmd.getName().equalsIgnoreCase("wintop")) { sender.sendMessage(ChatColor.GREEN + "Here are the top amounts of won games on ArcherGames currently:"); HashMap<String, Integer> wins = plugin.db.getTopWinners(); int i = 1; for (String playerName : wins.keySet()) { sender.sendMessage(ChatColor.GREEN + "" + i + ": " + playerName + " | " + wins.get(playerName)); i++; } return true; } else if (cmd.getName().equalsIgnoreCase("stats")) { String lookup = args.length == 0 ? sender.getName() : args[0]; sender.sendMessage(ChatColor.GREEN + lookup + "'s Statistics:"); sender.sendMessage(ChatColor.GREEN + "Wins: " + plugin.db.getWins(lookup)); sender.sendMessage(ChatColor.GREEN + "Games played: " + plugin.db.getPlays(lookup)); sender.sendMessage(ChatColor.GREEN + "Credits: " + plugin.db.getPoints(lookup)); sender.sendMessage(ChatColor.GREEN + "Deaths: " + plugin.db.getDeaths(lookup)); sender.sendMessage(ChatColor.GREEN + "Time Played: " + plugin.db.getPlayTime(lookup)); return true; } else if (cmd.getName().equalsIgnoreCase("credits")) { String lookup = args.length == 0 ? sender.getName() : args[0]; sender.sendMessage(ChatColor.GREEN + "" + lookup + " has " + plugin.db.getPoints(lookup) + " credits."); return true; } else if (cmd.getName().equalsIgnoreCase("track")) { if (sender.hasPermission("ArcherGames.donor.track")) { if (sender instanceof Player) { if (args.length != 0) { Player player = (Player) sender; if (!player.getInventory().contains(Material.COMPASS)) { player.getInventory().addItem(new ItemStack(Material.COMPASS)); } for(Player p : plugin.getServer().getOnlinePlayers()){ - if(p.getName().contains("(?i)" + args[0])){ + if(p.getName().contains(args[0])){ player.setCompassTarget(plugin.getServer().getPlayer(args[0]).getLocation()); player.sendMessage(ChatColor.GREEN + "Compass set to point to " + args[0]); break; } } } else { sender.sendMessage(ChatColor.RED + "You need to sepcify a player to point your compass at!"); return true; } } else { sender.sendMessage(ChatColor.RED + "You must be a player to execute that command!"); return true; } } else { sender.sendMessage(ChatColor.RED + "You do not have permission to use this command!"); return true; } } else if (cmd.getName().equalsIgnoreCase("ride")) { if (sender instanceof Player) { if (!plugin.serverwide.ridingPlayers.contains(sender.getName())) { plugin.serverwide.ridingPlayers.add(sender.getName()); sender.sendMessage(ChatColor.GREEN + "You are now able to right click and ride players."); } else { plugin.serverwide.ridingPlayers.remove(sender.getName()); sender.sendMessage(ChatColor.GREEN + "You are no longer able to right click and ride players."); } } else { sender.sendMessage(ChatColor.RED + "You must be a player to execute that command."); return true; } } else if (cmd.getName().equalsIgnoreCase("help")) { if (sender instanceof Player) { Player player = (Player) sender; if (!player.getInventory().contains(Material.WRITTEN_BOOK)) { BookItem bi = new BookItem(new ItemStack(387, 1)); bi.setAuthor(plugin.getConfig().getString("ArcherGames.startbook.author")); bi.setTitle(plugin.getConfig().getString("ArcherGames.startbook.Title")); String[] pages = plugin.getConfig().getStringList("ArcherGames.startbook.pages").toArray(new String[11]); bi.setPages(pages); player.getInventory().addItem(bi.getItemStack()); return true; } else { sender.sendMessage(ChatColor.RED + "You already have a help book! Check your inventory!"); return true; } } else { sender.sendMessage(ChatColor.RED + "You must be a player to execute that command!"); return true; } } else if (cmd.getName().equalsIgnoreCase("commands")) { sendHelp(sender, "kit [kitname]", "Pick or list the kits, depending on arguements."); sendHelp(sender, "vote", "List the sites you can vote for the server on."); sendHelp(sender, "money [player]", "Show either your or another player's money balance."); sendHelp(sender, "stats [player]", "Show either your or another player's stats."); sendHelp(sender, "chunk", "Reload your current chunk to fix a loading issue"); sendHelp(sender, "pay (player) (amt)", "Send the specified player the specified amount of money"); sendHelp(sender, "time", "Show the amount of time before the next event happens (Game start, Overtime, etc.)"); sendHelp(sender, "timer (time)", "Set the amount of time left to the start of the game."); sendHelp(sender, "who/online/players", "See the players online and who is alive."); sendHelp(sender, "credtop", "Show the top players for credits earned."); sendHelp(sender, "baltop", "Show the top players for money earned."); sendHelp(sender, "wintop", "Show the top players for games won."); sendHelp(sender, "stats [player]", "Show the specified player, or your, stats."); sendHelp(sender, "track (player)", "Use a compass to point at onother player. (Donor only)"); sendHelp(sender, "ride", "Toggle the ability to right click players and 'ride' them"); sendHelp(sender, "help", "Give yourself a help book."); sendHelp(sender, "commands", "Show this help page."); sendHelp(sender, "goto (player)", "Teleport to another player while spectating."); return true; } else if (cmd.getName().equalsIgnoreCase("goto")) { if (args.length != 0) { Player p = null; for (Player player : plugin.getServer().getOnlinePlayers()) { - if (player.getName().contains("(?i)" + args[0])) { + if (player.getName().contains(args[0])) { p = player; } } if (p != null) { if (sender instanceof Player) { if (!plugin.serverwide.getArcher(sender.getName()).getPlaying()) { ((Player) sender).teleport(p); sender.sendMessage(ChatColor.GREEN + "You have been teleported to " + p.getName()); return true; } else { sender.sendMessage("You must be dead to use that command!"); return true; } } else { sender.sendMessage(ChatColor.RED + "You must be a player to execute that command!"); return true; } } else { sender.sendMessage(ChatColor.RED + "That is not a valid player!"); return true; } } } return false; } /** * * @param event */ @EventHandler public void onCommandPreProccessEvent(final PlayerCommandPreprocessEvent event) { if (!(plugin.serverwide.getArcher(event.getPlayer()).getKit() == null) || !event.getPlayer().hasPermission("archergames.overrides.command")) { if (!event.getMessage().contains("kit") && false) { // Needs fixing. event.setCancelled(true); event.getPlayer().sendMessage(plugin.strings.get("nocommand")); } } } private void sendHelp(CommandSender sender, String command, String description) { sender.sendMessage(ChatColor.GOLD + "/" + command + ": " + ChatColor.YELLOW + description); } }
false
true
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { if (cmd.getName().equalsIgnoreCase("vote")) { sender.sendMessage(plugin.strings.get("voteinfo")); for (String s : plugin.voteSites.split("~")) { sender.sendMessage(ChatColor.GREEN + s); return true; } } else if (cmd.getName().equalsIgnoreCase("money")) { if (args.length == 0) { sender.sendMessage(ChatColor.GREEN + sender.getName() + "'s balance is " + plugin.db.getMoney(sender.getName()) + ""); return true; } else { sender.sendMessage(ChatColor.GREEN + args[0] + "'s balance is " + plugin.db.getMoney(args[0])); return true; } } else if (cmd.getName().equalsIgnoreCase("who") || cmd.getName().equalsIgnoreCase("online") || cmd.getName().equalsIgnoreCase("players")) { String outputAlive = ""; int alive = 0; String outputSpec = ""; int spec = 0; for (Player p : plugin.getServer().getOnlinePlayers()) { if (plugin.serverwide.getArcher(p).getPlaying()) { outputAlive += p.getDisplayName() + ", "; alive++; } else { spec++; outputSpec += p.getDisplayName() + ", "; } } sender.sendMessage(ChatColor.GRAY + "" + alive + ChatColor.DARK_GRAY + " Archers are currently playing: "); sender.sendMessage(outputAlive); sender.sendMessage(ChatColor.GRAY + "" + spec + ChatColor.DARK_GRAY + " Spectators are currently watching: "); sender.sendMessage(outputSpec); return true; } else if (cmd.getName().equalsIgnoreCase("kit") || cmd.getName().equalsIgnoreCase("kits")) { if (args.length != 0) { if (ScheduledTasks.gameStatus != 1) { sender.sendMessage(plugin.strings.get("alreadystartedkits")); } else { Kit selectedKit = new Kit(); Boolean isOkay = false; for (Kit kit : plugin.kits) { if (args[0].equalsIgnoreCase(kit.getName())) { isOkay = true; selectedKit = kit; } } if (isOkay) { if (plugin.serverwide.getArcher(sender.getName()).getPlaying()) { sender.sendMessage(String.format(plugin.strings.get("alreadyselected"), plugin.serverwide.getArcher(sender.getName()).getKit().getName())); } if (sender.hasPermission(selectedKit.getPermission())) { plugin.serverwide.joinGame(sender.getName(), selectedKit); sender.sendMessage(String.format(plugin.strings.get("kitgiven"), selectedKit.getName())); } else { sender.sendMessage(ChatColor.RED + "You do not have permission to use this kit."); } } else { sender.sendMessage(ChatColor.RED + "That is not a valid kit."); } } } else { sender.sendMessage(ChatColor.AQUA + "Use /kit (kitname) to select a kit."); sender.sendMessage(ChatColor.DARK_GREEN + plugin.strings.get("kitinfo")); String kits = ""; String kitsNo = ""; for (Kit kit : plugin.kits) { if (sender.hasPermission(kit.getPermission())) { kits += kit.getName() + ", "; } else { kitsNo += kit.getName() + ", "; } } sender.sendMessage(ChatColor.GREEN + kits); sender.sendMessage(ChatColor.DARK_RED + plugin.strings.get("kitnoaccessible")); sender.sendMessage(ChatColor.RED + kitsNo); } return true; } else if (cmd.getName().equalsIgnoreCase("chunk")) { if (sender instanceof Player) { Player player = (Player) sender; player.getWorld().unloadChunk(player.getLocation().getChunk()); player.getWorld().loadChunk(player.getLocation().getChunk()); player.teleport(player.getLocation()); player.sendMessage(ChatColor.GREEN + "Chunk Reloaded."); return true; } else { return false; } } else if (cmd.getName().equalsIgnoreCase("pay")) { if (args.length != 0) { if (args.length != 1) { try { if (Double.parseDouble(args[1]) > 0) { if (plugin.db.hasMoney(sender.getName(), Double.parseDouble(args[1]))) { plugin.db.takeMoney(sender.getName(), Double.parseDouble(args[1])); plugin.db.addMoney(args[0], Double.parseDouble(args[1])); } else { sender.sendMessage("You cannot afford to send this amount of money!"); } sender.sendMessage(ChatColor.GREEN + "$" + args[0] + " paid to " + args[0]); } } catch (Exception e) { return false; } } else { return false; } } else { return false; } } else if (cmd.getName().equalsIgnoreCase("time")) { if (!(ScheduledTasks.gameStatus >= 2)) { sender.sendMessage(ChatColor.GREEN + ((String.format(plugin.strings.get("starttimeleft"), ((plugin.scheduler.preGameCountdown - plugin.scheduler.currentLoop) / 60 + " minute" + (((plugin.scheduler.preGameCountdown - plugin.scheduler.currentLoop) / 60) == 1 ? "" : "s") + ", " + ((plugin.scheduler.preGameCountdown - plugin.scheduler.currentLoop) % 60) + " second" + ((plugin.scheduler.preGameCountdown - plugin.scheduler.currentLoop != 1) ? "s" : "")))))); } else if (!(ScheduledTasks.gameStatus >= 3)) { sender.sendMessage(ChatColor.GREEN + ((String.format(plugin.strings.get("invincibilityend"), ((plugin.scheduler.gameInvincibleCountdown - plugin.scheduler.currentLoop) / 60 + " minute" + (((plugin.scheduler.gameInvincibleCountdown - plugin.scheduler.currentLoop) / 60) == 1 ? "" : "s") + ", " + ((plugin.scheduler.gameInvincibleCountdown - plugin.scheduler.currentLoop) % 60) + " second" + ((plugin.scheduler.gameInvincibleCountdown - plugin.scheduler.currentLoop != 1) ? "s" : "")))))); } else if (!(ScheduledTasks.gameStatus >= 4)) { sender.sendMessage(ChatColor.GREEN + ((plugin.scheduler.gameOvertimeCountdown - plugin.scheduler.currentLoop) % 60 == 0 ? (plugin.scheduler.gameOvertimeCountdown - plugin.scheduler.currentLoop) / 60 + " minutes until overtime starts" : (plugin.scheduler.gameOvertimeCountdown - plugin.scheduler.currentLoop) / 60 + " minutes and " + (plugin.scheduler.gameOvertimeCountdown - plugin.scheduler.currentLoop) % 60 + " seconds until overtime starts.")); } else { sender.sendMessage(ChatColor.RED + "Nothing to time!"); } return true; } else if (cmd.getName().equalsIgnoreCase("timer")) { if (args.length != 0) { if (sender.hasPermission("ArcherGames.admin")) { try { plugin.scheduler.preGameCountdown = Integer.parseInt(args[0]); plugin.scheduler.currentLoop = 0; sender.sendMessage(ChatColor.GREEN + "Time left to start set to " + args[0] + " seconds left."); return true; } catch (Exception e) { sender.sendMessage(ChatColor.RED + "Time could not be set."); return true; } } } } else if (plugin.debug && cmd.getName().equalsIgnoreCase("ArcherGames")) { if (args[0].equalsIgnoreCase("startGame")) { ScheduledTasks.gameStatus = 2; sender.sendMessage(ChatColor.GREEN + "Game started."); plugin.log.info("[ArcherGames/Debug]: Game force-started by " + sender.getName()); return true; } } else if (cmd.getName().equalsIgnoreCase("lockdown")) { if (sender.hasPermission("archergames.admin")) { plugin.getConfig().set("ArcherGames.toggles.lockdownMode", !plugin.configToggles.get("ArcherGames.toggles.lockdownMode")); plugin.saveConfig(); sender.sendMessage(ChatColor.GREEN + "LockDown mode toggled."); return true; } else { return false; } } else if (cmd.getName().equalsIgnoreCase("credtop")) { sender.sendMessage(ChatColor.GREEN + "Here are the top credit amounts on ArcherGames currently:"); HashMap<String, Integer> credits = plugin.db.getTopPoints(); int i = 1; for (String playerName : credits.keySet()) { sender.sendMessage(ChatColor.GREEN + "" + i + ": " + playerName + " | " + credits.get(playerName)); i++; } return true; } else if (cmd.getName().equalsIgnoreCase("baltop")) { sender.sendMessage(ChatColor.GREEN + "Here are the top balance amounts on ArcherGames currently:"); HashMap<String, Integer> balances = plugin.db.getTopPoints(); int i = 1; for (String playerName : balances.keySet()) { sender.sendMessage(ChatColor.GREEN + "" + i + ": " + playerName + " | " + balances.get(playerName)); i++; } return true; } else if (cmd.getName().equalsIgnoreCase("wintop")) { sender.sendMessage(ChatColor.GREEN + "Here are the top amounts of won games on ArcherGames currently:"); HashMap<String, Integer> wins = plugin.db.getTopWinners(); int i = 1; for (String playerName : wins.keySet()) { sender.sendMessage(ChatColor.GREEN + "" + i + ": " + playerName + " | " + wins.get(playerName)); i++; } return true; } else if (cmd.getName().equalsIgnoreCase("stats")) { String lookup = args.length == 0 ? sender.getName() : args[0]; sender.sendMessage(ChatColor.GREEN + lookup + "'s Statistics:"); sender.sendMessage(ChatColor.GREEN + "Wins: " + plugin.db.getWins(lookup)); sender.sendMessage(ChatColor.GREEN + "Games played: " + plugin.db.getPlays(lookup)); sender.sendMessage(ChatColor.GREEN + "Credits: " + plugin.db.getPoints(lookup)); sender.sendMessage(ChatColor.GREEN + "Deaths: " + plugin.db.getDeaths(lookup)); sender.sendMessage(ChatColor.GREEN + "Time Played: " + plugin.db.getPlayTime(lookup)); return true; } else if (cmd.getName().equalsIgnoreCase("credits")) { String lookup = args.length == 0 ? sender.getName() : args[0]; sender.sendMessage(ChatColor.GREEN + "" + lookup + " has " + plugin.db.getPoints(lookup) + " credits."); return true; } else if (cmd.getName().equalsIgnoreCase("track")) { if (sender.hasPermission("ArcherGames.donor.track")) { if (sender instanceof Player) { if (args.length != 0) { Player player = (Player) sender; if (!player.getInventory().contains(Material.COMPASS)) { player.getInventory().addItem(new ItemStack(Material.COMPASS)); } for(Player p : plugin.getServer().getOnlinePlayers()){ if(p.getName().contains("(?i)" + args[0])){ player.setCompassTarget(plugin.getServer().getPlayer(args[0]).getLocation()); player.sendMessage(ChatColor.GREEN + "Compass set to point to " + args[0]); break; } } } else { sender.sendMessage(ChatColor.RED + "You need to sepcify a player to point your compass at!"); return true; } } else { sender.sendMessage(ChatColor.RED + "You must be a player to execute that command!"); return true; } } else { sender.sendMessage(ChatColor.RED + "You do not have permission to use this command!"); return true; } } else if (cmd.getName().equalsIgnoreCase("ride")) { if (sender instanceof Player) { if (!plugin.serverwide.ridingPlayers.contains(sender.getName())) { plugin.serverwide.ridingPlayers.add(sender.getName()); sender.sendMessage(ChatColor.GREEN + "You are now able to right click and ride players."); } else { plugin.serverwide.ridingPlayers.remove(sender.getName()); sender.sendMessage(ChatColor.GREEN + "You are no longer able to right click and ride players."); } } else { sender.sendMessage(ChatColor.RED + "You must be a player to execute that command."); return true; } } else if (cmd.getName().equalsIgnoreCase("help")) { if (sender instanceof Player) { Player player = (Player) sender; if (!player.getInventory().contains(Material.WRITTEN_BOOK)) { BookItem bi = new BookItem(new ItemStack(387, 1)); bi.setAuthor(plugin.getConfig().getString("ArcherGames.startbook.author")); bi.setTitle(plugin.getConfig().getString("ArcherGames.startbook.Title")); String[] pages = plugin.getConfig().getStringList("ArcherGames.startbook.pages").toArray(new String[11]); bi.setPages(pages); player.getInventory().addItem(bi.getItemStack()); return true; } else { sender.sendMessage(ChatColor.RED + "You already have a help book! Check your inventory!"); return true; } } else { sender.sendMessage(ChatColor.RED + "You must be a player to execute that command!"); return true; } } else if (cmd.getName().equalsIgnoreCase("commands")) { sendHelp(sender, "kit [kitname]", "Pick or list the kits, depending on arguements."); sendHelp(sender, "vote", "List the sites you can vote for the server on."); sendHelp(sender, "money [player]", "Show either your or another player's money balance."); sendHelp(sender, "stats [player]", "Show either your or another player's stats."); sendHelp(sender, "chunk", "Reload your current chunk to fix a loading issue"); sendHelp(sender, "pay (player) (amt)", "Send the specified player the specified amount of money"); sendHelp(sender, "time", "Show the amount of time before the next event happens (Game start, Overtime, etc.)"); sendHelp(sender, "timer (time)", "Set the amount of time left to the start of the game."); sendHelp(sender, "who/online/players", "See the players online and who is alive."); sendHelp(sender, "credtop", "Show the top players for credits earned."); sendHelp(sender, "baltop", "Show the top players for money earned."); sendHelp(sender, "wintop", "Show the top players for games won."); sendHelp(sender, "stats [player]", "Show the specified player, or your, stats."); sendHelp(sender, "track (player)", "Use a compass to point at onother player. (Donor only)"); sendHelp(sender, "ride", "Toggle the ability to right click players and 'ride' them"); sendHelp(sender, "help", "Give yourself a help book."); sendHelp(sender, "commands", "Show this help page."); sendHelp(sender, "goto (player)", "Teleport to another player while spectating."); return true; } else if (cmd.getName().equalsIgnoreCase("goto")) { if (args.length != 0) { Player p = null; for (Player player : plugin.getServer().getOnlinePlayers()) { if (player.getName().contains("(?i)" + args[0])) { p = player; } } if (p != null) { if (sender instanceof Player) { if (!plugin.serverwide.getArcher(sender.getName()).getPlaying()) { ((Player) sender).teleport(p); sender.sendMessage(ChatColor.GREEN + "You have been teleported to " + p.getName()); return true; } else { sender.sendMessage("You must be dead to use that command!"); return true; } } else { sender.sendMessage(ChatColor.RED + "You must be a player to execute that command!"); return true; } } else { sender.sendMessage(ChatColor.RED + "That is not a valid player!"); return true; } } } return false; }
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { if (cmd.getName().equalsIgnoreCase("vote")) { sender.sendMessage(plugin.strings.get("voteinfo")); for (String s : plugin.voteSites.split("~")) { sender.sendMessage(ChatColor.GREEN + s); return true; } } else if (cmd.getName().equalsIgnoreCase("money")) { if (args.length == 0) { sender.sendMessage(ChatColor.GREEN + sender.getName() + "'s balance is " + plugin.db.getMoney(sender.getName()) + ""); return true; } else { sender.sendMessage(ChatColor.GREEN + args[0] + "'s balance is " + plugin.db.getMoney(args[0])); return true; } } else if (cmd.getName().equalsIgnoreCase("who") || cmd.getName().equalsIgnoreCase("online") || cmd.getName().equalsIgnoreCase("players")) { String outputAlive = ""; int alive = 0; String outputSpec = ""; int spec = 0; for (Player p : plugin.getServer().getOnlinePlayers()) { if (plugin.serverwide.getArcher(p).getPlaying()) { outputAlive += p.getDisplayName() + ", "; alive++; } else { spec++; outputSpec += p.getDisplayName() + ", "; } } sender.sendMessage(ChatColor.GRAY + "" + alive + ChatColor.DARK_GRAY + " Archers are currently playing: "); sender.sendMessage(outputAlive); sender.sendMessage(ChatColor.GRAY + "" + spec + ChatColor.DARK_GRAY + " Spectators are currently watching: "); sender.sendMessage(outputSpec); return true; } else if (cmd.getName().equalsIgnoreCase("kit") || cmd.getName().equalsIgnoreCase("kits")) { if (args.length != 0) { if (ScheduledTasks.gameStatus != 1) { sender.sendMessage(plugin.strings.get("alreadystartedkits")); } else { Kit selectedKit = new Kit(); Boolean isOkay = false; for (Kit kit : plugin.kits) { if (args[0].equalsIgnoreCase(kit.getName())) { isOkay = true; selectedKit = kit; } } if (isOkay) { if (plugin.serverwide.getArcher(sender.getName()).getPlaying()) { sender.sendMessage(String.format(plugin.strings.get("alreadyselected"), plugin.serverwide.getArcher(sender.getName()).getKit().getName())); } if (sender.hasPermission(selectedKit.getPermission())) { plugin.serverwide.joinGame(sender.getName(), selectedKit); sender.sendMessage(String.format(plugin.strings.get("kitgiven"), selectedKit.getName())); } else { sender.sendMessage(ChatColor.RED + "You do not have permission to use this kit."); } } else { sender.sendMessage(ChatColor.RED + "That is not a valid kit."); } } } else { sender.sendMessage(ChatColor.AQUA + "Use /kit (kitname) to select a kit."); sender.sendMessage(ChatColor.DARK_GREEN + plugin.strings.get("kitinfo")); String kits = ""; String kitsNo = ""; for (Kit kit : plugin.kits) { if (sender.hasPermission(kit.getPermission())) { kits += kit.getName() + ", "; } else { kitsNo += kit.getName() + ", "; } } sender.sendMessage(ChatColor.GREEN + kits); sender.sendMessage(ChatColor.DARK_RED + plugin.strings.get("kitnoaccessible")); sender.sendMessage(ChatColor.RED + kitsNo); } return true; } else if (cmd.getName().equalsIgnoreCase("chunk")) { if (sender instanceof Player) { Player player = (Player) sender; player.getWorld().unloadChunk(player.getLocation().getChunk()); player.getWorld().loadChunk(player.getLocation().getChunk()); player.teleport(player.getLocation()); player.sendMessage(ChatColor.GREEN + "Chunk Reloaded."); return true; } else { return false; } } else if (cmd.getName().equalsIgnoreCase("pay")) { if (args.length != 0) { if (args.length != 1) { try { if (Double.parseDouble(args[1]) > 0) { if (plugin.db.hasMoney(sender.getName(), Double.parseDouble(args[1]))) { plugin.db.takeMoney(sender.getName(), Double.parseDouble(args[1])); plugin.db.addMoney(args[0], Double.parseDouble(args[1])); } else { sender.sendMessage("You cannot afford to send this amount of money!"); } sender.sendMessage(ChatColor.GREEN + "$" + args[0] + " paid to " + args[0]); } } catch (Exception e) { return false; } } else { return false; } } else { return false; } } else if (cmd.getName().equalsIgnoreCase("time")) { if (!(ScheduledTasks.gameStatus >= 2)) { sender.sendMessage(ChatColor.GREEN + ((String.format(plugin.strings.get("starttimeleft"), ((plugin.scheduler.preGameCountdown - plugin.scheduler.currentLoop) / 60 + " minute" + (((plugin.scheduler.preGameCountdown - plugin.scheduler.currentLoop) / 60) == 1 ? "" : "s") + ", " + ((plugin.scheduler.preGameCountdown - plugin.scheduler.currentLoop) % 60) + " second" + ((plugin.scheduler.preGameCountdown - plugin.scheduler.currentLoop != 1) ? "s" : "")))))); } else if (!(ScheduledTasks.gameStatus >= 3)) { sender.sendMessage(ChatColor.GREEN + ((String.format(plugin.strings.get("invincibilityend"), ((plugin.scheduler.gameInvincibleCountdown - plugin.scheduler.currentLoop) / 60 + " minute" + (((plugin.scheduler.gameInvincibleCountdown - plugin.scheduler.currentLoop) / 60) == 1 ? "" : "s") + ", " + ((plugin.scheduler.gameInvincibleCountdown - plugin.scheduler.currentLoop) % 60) + " second" + ((plugin.scheduler.gameInvincibleCountdown - plugin.scheduler.currentLoop != 1) ? "s" : "")))))); } else if (!(ScheduledTasks.gameStatus >= 4)) { sender.sendMessage(ChatColor.GREEN + ((plugin.scheduler.gameOvertimeCountdown - plugin.scheduler.currentLoop) % 60 == 0 ? (plugin.scheduler.gameOvertimeCountdown - plugin.scheduler.currentLoop) / 60 + " minutes until overtime starts" : (plugin.scheduler.gameOvertimeCountdown - plugin.scheduler.currentLoop) / 60 + " minutes and " + (plugin.scheduler.gameOvertimeCountdown - plugin.scheduler.currentLoop) % 60 + " seconds until overtime starts.")); } else { sender.sendMessage(ChatColor.RED + "Nothing to time!"); } return true; } else if (cmd.getName().equalsIgnoreCase("timer")) { if (args.length != 0) { if (sender.hasPermission("ArcherGames.admin")) { try { plugin.scheduler.preGameCountdown = Integer.parseInt(args[0]); plugin.scheduler.currentLoop = 0; sender.sendMessage(ChatColor.GREEN + "Time left to start set to " + args[0] + " seconds left."); return true; } catch (Exception e) { sender.sendMessage(ChatColor.RED + "Time could not be set."); return true; } } } } else if (plugin.debug && cmd.getName().equalsIgnoreCase("ArcherGames")) { if (args[0].equalsIgnoreCase("startGame")) { ScheduledTasks.gameStatus = 2; sender.sendMessage(ChatColor.GREEN + "Game started."); plugin.log.info("[ArcherGames/Debug]: Game force-started by " + sender.getName()); return true; } } else if (cmd.getName().equalsIgnoreCase("lockdown")) { if (sender.hasPermission("archergames.admin")) { plugin.getConfig().set("ArcherGames.toggles.lockdownMode", !plugin.configToggles.get("ArcherGames.toggles.lockdownMode")); plugin.saveConfig(); sender.sendMessage(ChatColor.GREEN + "LockDown mode toggled."); return true; } else { return false; } } else if (cmd.getName().equalsIgnoreCase("credtop")) { sender.sendMessage(ChatColor.GREEN + "Here are the top credit amounts on ArcherGames currently:"); HashMap<String, Integer> credits = plugin.db.getTopPoints(); int i = 1; for (String playerName : credits.keySet()) { sender.sendMessage(ChatColor.GREEN + "" + i + ": " + playerName + " | " + credits.get(playerName)); i++; } return true; } else if (cmd.getName().equalsIgnoreCase("baltop")) { sender.sendMessage(ChatColor.GREEN + "Here are the top balance amounts on ArcherGames currently:"); HashMap<String, Integer> balances = plugin.db.getTopPoints(); int i = 1; for (String playerName : balances.keySet()) { sender.sendMessage(ChatColor.GREEN + "" + i + ": " + playerName + " | " + balances.get(playerName)); i++; } return true; } else if (cmd.getName().equalsIgnoreCase("wintop")) { sender.sendMessage(ChatColor.GREEN + "Here are the top amounts of won games on ArcherGames currently:"); HashMap<String, Integer> wins = plugin.db.getTopWinners(); int i = 1; for (String playerName : wins.keySet()) { sender.sendMessage(ChatColor.GREEN + "" + i + ": " + playerName + " | " + wins.get(playerName)); i++; } return true; } else if (cmd.getName().equalsIgnoreCase("stats")) { String lookup = args.length == 0 ? sender.getName() : args[0]; sender.sendMessage(ChatColor.GREEN + lookup + "'s Statistics:"); sender.sendMessage(ChatColor.GREEN + "Wins: " + plugin.db.getWins(lookup)); sender.sendMessage(ChatColor.GREEN + "Games played: " + plugin.db.getPlays(lookup)); sender.sendMessage(ChatColor.GREEN + "Credits: " + plugin.db.getPoints(lookup)); sender.sendMessage(ChatColor.GREEN + "Deaths: " + plugin.db.getDeaths(lookup)); sender.sendMessage(ChatColor.GREEN + "Time Played: " + plugin.db.getPlayTime(lookup)); return true; } else if (cmd.getName().equalsIgnoreCase("credits")) { String lookup = args.length == 0 ? sender.getName() : args[0]; sender.sendMessage(ChatColor.GREEN + "" + lookup + " has " + plugin.db.getPoints(lookup) + " credits."); return true; } else if (cmd.getName().equalsIgnoreCase("track")) { if (sender.hasPermission("ArcherGames.donor.track")) { if (sender instanceof Player) { if (args.length != 0) { Player player = (Player) sender; if (!player.getInventory().contains(Material.COMPASS)) { player.getInventory().addItem(new ItemStack(Material.COMPASS)); } for(Player p : plugin.getServer().getOnlinePlayers()){ if(p.getName().contains(args[0])){ player.setCompassTarget(plugin.getServer().getPlayer(args[0]).getLocation()); player.sendMessage(ChatColor.GREEN + "Compass set to point to " + args[0]); break; } } } else { sender.sendMessage(ChatColor.RED + "You need to sepcify a player to point your compass at!"); return true; } } else { sender.sendMessage(ChatColor.RED + "You must be a player to execute that command!"); return true; } } else { sender.sendMessage(ChatColor.RED + "You do not have permission to use this command!"); return true; } } else if (cmd.getName().equalsIgnoreCase("ride")) { if (sender instanceof Player) { if (!plugin.serverwide.ridingPlayers.contains(sender.getName())) { plugin.serverwide.ridingPlayers.add(sender.getName()); sender.sendMessage(ChatColor.GREEN + "You are now able to right click and ride players."); } else { plugin.serverwide.ridingPlayers.remove(sender.getName()); sender.sendMessage(ChatColor.GREEN + "You are no longer able to right click and ride players."); } } else { sender.sendMessage(ChatColor.RED + "You must be a player to execute that command."); return true; } } else if (cmd.getName().equalsIgnoreCase("help")) { if (sender instanceof Player) { Player player = (Player) sender; if (!player.getInventory().contains(Material.WRITTEN_BOOK)) { BookItem bi = new BookItem(new ItemStack(387, 1)); bi.setAuthor(plugin.getConfig().getString("ArcherGames.startbook.author")); bi.setTitle(plugin.getConfig().getString("ArcherGames.startbook.Title")); String[] pages = plugin.getConfig().getStringList("ArcherGames.startbook.pages").toArray(new String[11]); bi.setPages(pages); player.getInventory().addItem(bi.getItemStack()); return true; } else { sender.sendMessage(ChatColor.RED + "You already have a help book! Check your inventory!"); return true; } } else { sender.sendMessage(ChatColor.RED + "You must be a player to execute that command!"); return true; } } else if (cmd.getName().equalsIgnoreCase("commands")) { sendHelp(sender, "kit [kitname]", "Pick or list the kits, depending on arguements."); sendHelp(sender, "vote", "List the sites you can vote for the server on."); sendHelp(sender, "money [player]", "Show either your or another player's money balance."); sendHelp(sender, "stats [player]", "Show either your or another player's stats."); sendHelp(sender, "chunk", "Reload your current chunk to fix a loading issue"); sendHelp(sender, "pay (player) (amt)", "Send the specified player the specified amount of money"); sendHelp(sender, "time", "Show the amount of time before the next event happens (Game start, Overtime, etc.)"); sendHelp(sender, "timer (time)", "Set the amount of time left to the start of the game."); sendHelp(sender, "who/online/players", "See the players online and who is alive."); sendHelp(sender, "credtop", "Show the top players for credits earned."); sendHelp(sender, "baltop", "Show the top players for money earned."); sendHelp(sender, "wintop", "Show the top players for games won."); sendHelp(sender, "stats [player]", "Show the specified player, or your, stats."); sendHelp(sender, "track (player)", "Use a compass to point at onother player. (Donor only)"); sendHelp(sender, "ride", "Toggle the ability to right click players and 'ride' them"); sendHelp(sender, "help", "Give yourself a help book."); sendHelp(sender, "commands", "Show this help page."); sendHelp(sender, "goto (player)", "Teleport to another player while spectating."); return true; } else if (cmd.getName().equalsIgnoreCase("goto")) { if (args.length != 0) { Player p = null; for (Player player : plugin.getServer().getOnlinePlayers()) { if (player.getName().contains(args[0])) { p = player; } } if (p != null) { if (sender instanceof Player) { if (!plugin.serverwide.getArcher(sender.getName()).getPlaying()) { ((Player) sender).teleport(p); sender.sendMessage(ChatColor.GREEN + "You have been teleported to " + p.getName()); return true; } else { sender.sendMessage("You must be dead to use that command!"); return true; } } else { sender.sendMessage(ChatColor.RED + "You must be a player to execute that command!"); return true; } } else { sender.sendMessage(ChatColor.RED + "That is not a valid player!"); return true; } } } return false; }
diff --git a/src/main/java/org/osaf/cosmo/cmp/UserResource.java b/src/main/java/org/osaf/cosmo/cmp/UserResource.java index f4fa78c7b..2612845d0 100644 --- a/src/main/java/org/osaf/cosmo/cmp/UserResource.java +++ b/src/main/java/org/osaf/cosmo/cmp/UserResource.java @@ -1,302 +1,303 @@ /* * Copyright 2005-2006 Open Source Applications 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. */ package org.osaf.cosmo.cmp; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.jackrabbit.webdav.xml.DomUtil; import org.apache.jackrabbit.webdav.xml.ElementIterator; import org.osaf.cosmo.model.User; import org.osaf.cosmo.util.DateUtil; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * A resource view of a {@link User}. */ public class UserResource implements CmpResource, OutputsXml { private static final Log log = LogFactory.getLog(UserResource.class); /** */ public static final String EL_USER = "user"; /** */ public static final String EL_USERNAME = "username"; /** */ public static final String EL_PASSWORD = "password"; /** */ public static final String EL_FIRSTNAME = "firstName"; /** */ public static final String EL_LASTNAME = "lastName"; /** */ public static final String EL_EMAIL = "email"; /** */ public static final String EL_URL = "url"; /** */ public static final String EL_HOMEDIRURL = "homedirUrl"; /** */ public static final String EL_CREATED = "created"; /** */ public static final String EL_MODIFIED = "modified"; /** */ public static final String EL_ADMINISTRATOR = "administrator"; /** */ public static final String EL_UNACTIVATED = "unactivated"; private User user; private String urlBase; private String userUrl; private String homedirUrl; /** * Constructs a resource that represents the given {@link User}. */ public UserResource(User user, String urlBase) { this.user = user; this.urlBase = urlBase; calculateUserUrl(); calculateHomedirUrl(); } /** * Constructs a resource that represents the given {@link User} * and updates its properties as per the given * {@link org.w3c.dom.Document}. */ public UserResource(User user, String urlBase, Document doc) { this.user = user; this.urlBase = urlBase; setUser(doc); calculateUserUrl(); calculateHomedirUrl(); } /** * Constructs a resource that represents a {@link User} * with properties as per the given {@link org.w3c.dom.Document}. */ public UserResource(String urlBase, Document doc) { this.urlBase = urlBase; this.user = new User(); setUser(doc); calculateUserUrl(); calculateHomedirUrl(); } // CmpResource methods /** * Returns the <code>User</code> that backs this resource. */ public Object getEntity() { return user; } // OutputsXml methods /** * Returns an XML representation of the resource in the form of a * {@link org.w3c.dom.Element}. * * The XML is structured like so: * * <pre> * <user> * <username>bcm</username> * <firstName>Brian</firstName> * <lastName>Moseley</firstName> * <email>[email protected]</email> * <created>2006-10-05T17:41:02-0700</created> * <modified>2006-10-05T17:41:02-0700</modified> * <administrator>true</administrator> * <url>http://localhost:8080/cmp/user/bcm</url> * <homedirUrl>http://localhost:8080/home/bcm</homedirUrl> * </user> * </pre> * * The user's password is not included in the XML representation. */ public Element toXml(Document doc) { Element e = DomUtil.createElement(doc, EL_USER, NS_CMP); Element username = DomUtil.createElement(doc, EL_USERNAME, NS_CMP); DomUtil.setText(username, user.getUsername()); e.appendChild(username); Element firstName = DomUtil.createElement(doc, EL_FIRSTNAME, NS_CMP); DomUtil.setText(firstName, user.getFirstName()); e.appendChild(firstName); Element lastName = DomUtil.createElement(doc, EL_LASTNAME, NS_CMP); DomUtil.setText(lastName, user.getLastName()); e.appendChild(lastName); Element email = DomUtil.createElement(doc, EL_EMAIL, NS_CMP); DomUtil.setText(email, user.getEmail()); e.appendChild(email); Element created = DomUtil.createElement(doc, EL_CREATED, NS_CMP); DomUtil.setText(created, DateUtil.formatRfc3339Date(user.getDateCreated())); e.appendChild(created); Element modified = DomUtil.createElement(doc, EL_MODIFIED, NS_CMP); DomUtil.setText(modified, DateUtil.formatRfc3339Date(user.getDateModified())); e.appendChild(modified); Element admin = DomUtil.createElement(doc, EL_ADMINISTRATOR, NS_CMP); DomUtil.setText(admin, user.getAdmin().toString()); e.appendChild(admin); Element url = DomUtil.createElement(doc, EL_URL, NS_CMP); DomUtil.setText(url, userUrl); e.appendChild(url); if (!user.isActivated()){ Element unactivated = DomUtil.createElement(doc, EL_UNACTIVATED, NS_CMP); e.appendChild(unactivated); } if (! user.getUsername().equals(User.USERNAME_OVERLORD)) { Element hurl = DomUtil.createElement(doc, EL_HOMEDIRURL, NS_CMP); DomUtil.setText(hurl, homedirUrl); e.appendChild(hurl); } return e; } // our methods /** * Returns an entity tag as defined in RFC 2616 that uniqely * identifies the state of the <code>User</code> backing this * resource. */ public String getEntityTag() { if (user == null) { return ""; } return "\"" + user.hashCode() + "-" + user.getDateModified().getTime() + "\""; } /** * Just as {@link #getEntity}, except the returned object is cast * to <code>User</code>. */ public User getUser() { return (User) getEntity(); } /** */ public String getUserUrl() { return userUrl; } /** */ public String getHomedirUrl() { return homedirUrl; } /** */ protected void setUser(Document doc) { if (doc == null) { return; } Element root = doc.getDocumentElement(); if (! DomUtil.matches(root, EL_USER, NS_CMP)) { throw new CmpException("root element not user"); } for (ElementIterator i=DomUtil.getChildren(root); i.hasNext();) { Element e = i.nextElement(); if (DomUtil.matches(e, EL_USERNAME, NS_CMP)) { if (user.getUsername() != null && user.getUsername().equals(User.USERNAME_OVERLORD)) { throw new CmpException("root user's username may not " + "be changed"); } user.setUsername(DomUtil.getTextTrim(e)); } else if (DomUtil.matches(e, EL_PASSWORD, NS_CMP)) { user.setPassword(DomUtil.getTextTrim(e)); } else if (DomUtil.matches(e, EL_FIRSTNAME, NS_CMP)) { if (user.getUsername() != null && user.getUsername().equals(User.USERNAME_OVERLORD)) { throw new CmpException("root user's first name may not " + "be changed"); } user.setFirstName(DomUtil.getTextTrim(e)); } else if (DomUtil.matches(e, EL_LASTNAME, NS_CMP)) { if (user.getUsername() != null && user.getUsername().equals(User.USERNAME_OVERLORD)) { throw new CmpException("root user's last name may not " + "be changed"); } user.setLastName(DomUtil.getTextTrim(e)); } else if (DomUtil.matches(e, EL_EMAIL, NS_CMP)) { user.setEmail(DomUtil.getTextTrim(e)); } else if (DomUtil.matches(e, EL_ADMINISTRATOR, NS_CMP)){ if (user.getUsername() != null && - user.getUsername().equals(User.USERNAME_OVERLORD)) { + user.getUsername().equals(User.USERNAME_OVERLORD) && + !DomUtil.getTextTrim(e).toLowerCase().equals("true")) { throw new CmpException("root user's admin status " + - "may not be changed"); + "must be true"); } user.setAdmin(Boolean.parseBoolean(DomUtil.getTextTrim(e))); } else { throw new CmpException("unknown user attribute element " + e.getTagName()); } } } /** */ protected void calculateUserUrl() { userUrl = urlBase + "/cmp/user/" + user.getUsername(); } /** */ protected void calculateHomedirUrl() { homedirUrl = urlBase + "/home/" + user.getUsername(); } }
false
true
protected void setUser(Document doc) { if (doc == null) { return; } Element root = doc.getDocumentElement(); if (! DomUtil.matches(root, EL_USER, NS_CMP)) { throw new CmpException("root element not user"); } for (ElementIterator i=DomUtil.getChildren(root); i.hasNext();) { Element e = i.nextElement(); if (DomUtil.matches(e, EL_USERNAME, NS_CMP)) { if (user.getUsername() != null && user.getUsername().equals(User.USERNAME_OVERLORD)) { throw new CmpException("root user's username may not " + "be changed"); } user.setUsername(DomUtil.getTextTrim(e)); } else if (DomUtil.matches(e, EL_PASSWORD, NS_CMP)) { user.setPassword(DomUtil.getTextTrim(e)); } else if (DomUtil.matches(e, EL_FIRSTNAME, NS_CMP)) { if (user.getUsername() != null && user.getUsername().equals(User.USERNAME_OVERLORD)) { throw new CmpException("root user's first name may not " + "be changed"); } user.setFirstName(DomUtil.getTextTrim(e)); } else if (DomUtil.matches(e, EL_LASTNAME, NS_CMP)) { if (user.getUsername() != null && user.getUsername().equals(User.USERNAME_OVERLORD)) { throw new CmpException("root user's last name may not " + "be changed"); } user.setLastName(DomUtil.getTextTrim(e)); } else if (DomUtil.matches(e, EL_EMAIL, NS_CMP)) { user.setEmail(DomUtil.getTextTrim(e)); } else if (DomUtil.matches(e, EL_ADMINISTRATOR, NS_CMP)){ if (user.getUsername() != null && user.getUsername().equals(User.USERNAME_OVERLORD)) { throw new CmpException("root user's admin status " + "may not be changed"); } user.setAdmin(Boolean.parseBoolean(DomUtil.getTextTrim(e))); } else { throw new CmpException("unknown user attribute element " + e.getTagName()); } } }
protected void setUser(Document doc) { if (doc == null) { return; } Element root = doc.getDocumentElement(); if (! DomUtil.matches(root, EL_USER, NS_CMP)) { throw new CmpException("root element not user"); } for (ElementIterator i=DomUtil.getChildren(root); i.hasNext();) { Element e = i.nextElement(); if (DomUtil.matches(e, EL_USERNAME, NS_CMP)) { if (user.getUsername() != null && user.getUsername().equals(User.USERNAME_OVERLORD)) { throw new CmpException("root user's username may not " + "be changed"); } user.setUsername(DomUtil.getTextTrim(e)); } else if (DomUtil.matches(e, EL_PASSWORD, NS_CMP)) { user.setPassword(DomUtil.getTextTrim(e)); } else if (DomUtil.matches(e, EL_FIRSTNAME, NS_CMP)) { if (user.getUsername() != null && user.getUsername().equals(User.USERNAME_OVERLORD)) { throw new CmpException("root user's first name may not " + "be changed"); } user.setFirstName(DomUtil.getTextTrim(e)); } else if (DomUtil.matches(e, EL_LASTNAME, NS_CMP)) { if (user.getUsername() != null && user.getUsername().equals(User.USERNAME_OVERLORD)) { throw new CmpException("root user's last name may not " + "be changed"); } user.setLastName(DomUtil.getTextTrim(e)); } else if (DomUtil.matches(e, EL_EMAIL, NS_CMP)) { user.setEmail(DomUtil.getTextTrim(e)); } else if (DomUtil.matches(e, EL_ADMINISTRATOR, NS_CMP)){ if (user.getUsername() != null && user.getUsername().equals(User.USERNAME_OVERLORD) && !DomUtil.getTextTrim(e).toLowerCase().equals("true")) { throw new CmpException("root user's admin status " + "must be true"); } user.setAdmin(Boolean.parseBoolean(DomUtil.getTextTrim(e))); } else { throw new CmpException("unknown user attribute element " + e.getTagName()); } } }
diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSProjectPropertiesPage.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSProjectPropertiesPage.java index 2147bf549..18e02e222 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSProjectPropertiesPage.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSProjectPropertiesPage.java @@ -1,450 +1,450 @@ /******************************************************************************* * Copyright (c) 2000, 2004 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.team.internal.ccvs.ui; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.dialogs.*; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.jface.viewers.*; import org.eclipse.osgi.util.NLS; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.*; import org.eclipse.team.core.RepositoryProvider; import org.eclipse.team.core.TeamException; import org.eclipse.team.internal.ccvs.core.*; import org.eclipse.team.internal.ccvs.core.resources.CVSWorkspaceRoot; import org.eclipse.team.internal.ccvs.core.syncinfo.FolderSyncInfo; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.model.WorkbenchContentProvider; import org.eclipse.ui.model.WorkbenchLabelProvider; public class CVSProjectPropertiesPage extends CVSPropertiesPage { IProject project; ICVSRepositoryLocation oldLocation; ICVSRepositoryLocation newLocation = null; private static final int TABLE_HEIGHT_HINT = 150; // Widgets Text methodText; Text userText; Text hostText; Text pathText; Text moduleText; Text portText; Text tagText; private Button fetchButton; private Button watchEditButton; IUserInfo info; CVSTeamProvider provider; private boolean fetch; private boolean watchEdit; public static boolean isCompatible(ICVSRepositoryLocation location, ICVSRepositoryLocation oldLocation) { if (!location.getHost().equals(oldLocation.getHost())) return false; if (!location.getRootDirectory().equals(oldLocation.getRootDirectory())) return false; if (location.equals(oldLocation)) return false; return true; } private class RepositorySelectionDialog extends Dialog { ICVSRepositoryLocation[] allLocations; ICVSRepositoryLocation[] compatibleLocatons; ICVSRepositoryLocation selectedLocation; TableViewer viewer; Button okButton; boolean showCompatible = true; public RepositorySelectionDialog(Shell shell, ICVSRepositoryLocation oldLocation) { super(shell); initialize(oldLocation); } private void initialize(ICVSRepositoryLocation oldLocation) { allLocations = CVSUIPlugin.getPlugin().getRepositoryManager().getKnownRepositoryLocations(); List locations = new ArrayList(); for (int i = 0; i < allLocations.length; i++) { ICVSRepositoryLocation location = allLocations[i]; if (isCompatible(location, oldLocation)) { locations.add(location); } } compatibleLocatons = (ICVSRepositoryLocation[]) locations.toArray(new ICVSRepositoryLocation[locations.size()]); } protected void createButtonsForButtonBar(Composite parent) { // create OK and Cancel buttons by default okButton = createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true); okButton.setEnabled(false); createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); } protected Control createDialogArea(Composite parent) { parent.getShell().setText(CVSUIMessages.CVSProjectPropertiesPage_Select_a_Repository_1); //$NON-NLS-1$ Composite composite = (Composite) super.createDialogArea(parent); createLabel(composite, CVSUIMessages.CVSProjectPropertiesPage_Select_a_CVS_repository_location_to_share_the_project_with__2, 1); //$NON-NLS-1$ Table table = new Table(composite, SWT.SINGLE | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL); GridData data = new GridData(GridData.FILL_HORIZONTAL); data.heightHint = TABLE_HEIGHT_HINT; table.setLayoutData(data); viewer = new TableViewer(table); viewer.setLabelProvider(new WorkbenchLabelProvider()); viewer.setContentProvider(new WorkbenchContentProvider() { public Object[] getElements(Object inputElement) { if (showCompatible) { return compatibleLocatons; } else { return allLocations; } } }); viewer.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { IStructuredSelection selection = (IStructuredSelection)event.getSelection(); if (selection.isEmpty()) { selectedLocation = null; okButton.setEnabled(false); } else { selectedLocation = (ICVSRepositoryLocation)selection.getFirstElement(); okButton.setEnabled(true); } } }); viewer.addDoubleClickListener(new IDoubleClickListener() { public void doubleClick(DoubleClickEvent event) { okPressed(); } }); viewer.setInput(compatibleLocatons); final Button compatibleButton = createCheckBox(composite, CVSUIMessages.CVSProjectPropertiesPage_31); //$NON-NLS-1$ compatibleButton.setSelection(showCompatible); compatibleButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { showCompatible = compatibleButton.getSelection(); viewer.refresh(); } }); Dialog.applyDialogFont(parent); return composite; } protected void cancelPressed() { selectedLocation = null; super.cancelPressed(); } public ICVSRepositoryLocation getLocation() { return selectedLocation; } } /* * @see PreferencesPage#createContents */ protected Control createContents(Composite parent) { initialize(); Composite composite = new Composite(parent, SWT.NULL); composite.setLayoutData(new GridData(GridData.FILL_BOTH)); GridLayout layout = new GridLayout(); layout.numColumns = 2; composite.setLayout(layout); Label label = createLabel(composite, CVSUIMessages.CVSProjectPropertiesPage_connectionType, 1); //$NON-NLS-1$ methodText = createReadOnlyText(composite, "", 1); //$NON-NLS-1$ label = createLabel(composite, CVSUIMessages.CVSProjectPropertiesPage_user, 1); //$NON-NLS-1$ userText = createReadOnlyText(composite, "", 1); //$NON-NLS-1$ - label = createLabel(composite, CVSUIMessages.CVSPropertiesPage_host, 1); //$NON-NLS-1$ + label = createLabel(composite, CVSUIMessages.CVSRepositoryLocationPropertySource_host, 1); //$NON-NLS-1$ hostText = createReadOnlyText(composite, "", 1); //$NON-NLS-1$ label = createLabel(composite, CVSUIMessages.CVSPropertiesPage_port, 1); //$NON-NLS-1$ portText = createReadOnlyText(composite, "", 1); //$NON-NLS-1$ - label = createLabel(composite, CVSUIMessages.CVSPropertiesPage_path, 1); //$NON-NLS-1$ + label = createLabel(composite, CVSUIMessages.CVSRepositoryLocationPropertySource_root, 1); //$NON-NLS-1$ pathText = createReadOnlyText(composite, "", 1); //$NON-NLS-1$ label = createLabel(composite, CVSUIMessages.CVSPropertiesPage_module, 1); //$NON-NLS-1$ moduleText = createReadOnlyText(composite, "", 1); //$NON-NLS-1$ label = createLabel(composite, CVSUIMessages.CVSPropertiesPage_tag, 1); //$NON-NLS-1$ tagText = createReadOnlyText(composite, "", 1); //$NON-NLS-1$ createLabel(composite, "", 1); //$NON-NLS-1$ // Should absent directories be fetched on update fetchButton = createCheckBox(composite, CVSUIMessages.CVSProjectPropertiesPage_fetchAbsentDirectoriesOnUpdate); //$NON-NLS-1$ fetchButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { fetch = fetchButton.getSelection(); } }); // Should the project be configured for watch/edit watchEditButton = createCheckBox(composite, CVSUIMessages.CVSProjectPropertiesPage_configureForWatchEdit); //$NON-NLS-1$ watchEditButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { watchEdit = watchEditButton.getSelection(); } }); createLabel(composite, "", 1); //$NON-NLS-1$ createLabel(composite, "", 1); //$NON-NLS-1$ createLabel(composite, "", 1); //$NON-NLS-1$ createLabel(composite, "", 1); //$NON-NLS-1$ label = new Label(composite, SWT.WRAP); label.setText(CVSUIMessages.CVSProjectPropertiesPage_You_can_change_the_sharing_of_this_project_to_another_repository_location__However__this_is_only_possible_if_the_new_location_is___compatible____on_the_same_host_with_the_same_repository_path___1); //$NON-NLS-1$ GridData data = new GridData(GridData.FILL_HORIZONTAL); data.widthHint = 200; data.horizontalSpan = 2; label.setLayoutData(data); Button changeButton = new Button(composite, SWT.PUSH); changeButton.setText(CVSUIMessages.CVSProjectPropertiesPage_Change_Sharing_5); //$NON-NLS-1$ changeButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { RepositorySelectionDialog dialog = new RepositorySelectionDialog(getShell(), oldLocation); dialog.open(); ICVSRepositoryLocation location = dialog.getLocation(); if (location == null) return; newLocation = location; initializeValues(newLocation); } }); initializeValues(oldLocation); PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IHelpContextIds.PROJECT_PROPERTY_PAGE); Dialog.applyDialogFont(parent); return composite; } /** * Utility method that creates a label instance * and sets the default layout data. * * @param parent the parent for the new label * @param text the text for the new label * @return the new label */ protected Label createLabel(Composite parent, String text, int span) { Label label = new Label(parent, SWT.LEFT); label.setText(text); GridData data = new GridData(); data.horizontalSpan = span; data.horizontalAlignment = GridData.FILL; label.setLayoutData(data); return label; } /** * Utility method that creates a text instance * and sets the default layout data. * * @param parent the parent for the new label * @param text the text for the new text * @return the new text */ protected Text createReadOnlyText(Composite parent, String text, int span) { Text txt = new Text(parent, SWT.LEFT | SWT.READ_ONLY); txt.setText(text); GridData data = new GridData(); data.horizontalSpan = span; data.horizontalAlignment = GridData.FILL; txt.setLayoutData(data); return txt; } /** * Creates a new checkbox instance and sets the default layout data. * * @param group the composite in which to create the checkbox * @param label the string to set into the checkbox * @return the new checkbox */ protected Button createCheckBox(Composite group, String label) { Button button = new Button(group, SWT.CHECK | SWT.LEFT); button.setText(label); GridData data = new GridData(); data.horizontalSpan = 2; button.setLayoutData(data); return button; } /** * Initializes the page */ private void initialize() { // Get the project that is the source of this property page project = null; IAdaptable element = getElement(); if (element instanceof IProject) { project = (IProject)element; } else { Object adapter = element.getAdapter(IProject.class); if (adapter instanceof IProject) { project = (IProject)adapter; } } // Do some pre-checks to ensure we're in a good state provider = (CVSTeamProvider)RepositoryProvider.getProvider(project, CVSProviderPlugin.getTypeId()); if (provider == null) return; CVSWorkspaceRoot cvsRoot = provider.getCVSWorkspaceRoot(); try { oldLocation = cvsRoot.getRemoteLocation(); fetch = provider.getFetchAbsentDirectories(); watchEdit = provider.isWatchEditEnabled(); } catch (TeamException e) { handle(e); } } /** * Set the initial values of the widgets */ private void initializeValues(ICVSRepositoryLocation location) { if (provider == null) return; CVSWorkspaceRoot cvsRoot = provider.getCVSWorkspaceRoot(); ICVSFolder folder = cvsRoot.getLocalRoot(); try { if (!folder.isCVSFolder()) return; methodText.setText(location.getMethod().getName()); info = location.getUserInfo(true); userText.setText(info.getUsername()); hostText.setText(location.getHost()); int port = location.getPort(); if (port == ICVSRepositoryLocation.USE_DEFAULT_PORT) { portText.setText(CVSUIMessages.CVSPropertiesPage_defaultPort); //$NON-NLS-1$ } else { portText.setText("" + port); //$NON-NLS-1$ } pathText.setText(location.getRootDirectory()); FolderSyncInfo syncInfo = folder.getFolderSyncInfo(); if (syncInfo == null) return; String label = syncInfo.getRepository(); if (label.equals(FolderSyncInfo.VIRTUAL_DIRECTORY)) { label = NLS.bind(CVSUIMessages.CVSPropertiesPage_virtualModule, new String[] { label }); //$NON-NLS-1$ } moduleText.setText(label); fetchButton.setSelection(fetch); watchEditButton.setSelection(watchEdit); } catch (TeamException e) { handle(e); } initializeTag(); } private void initializeTag() { provider = (CVSTeamProvider)RepositoryProvider.getProvider(project, CVSProviderPlugin.getTypeId()); if (provider == null) return; try { ICVSFolder local = CVSWorkspaceRoot.getCVSFolderFor(project); CVSTag tag = local.getFolderSyncInfo().getTag(); tagText.setText(getTagLabel(tag)); } catch (TeamException e) { handle(e); } } /* * @see PreferencesPage#performOk */ public boolean performOk() { final boolean[] changeReadOnly = { false }; try { if (fetch != provider.getFetchAbsentDirectories()) provider.setFetchAbsentDirectories(fetch); if (watchEdit != provider.isWatchEditEnabled()) { provider.setWatchEditEnabled(watchEdit); changeReadOnly[0] = true; } } catch (CVSException e) { handle(e); } if (newLocation == null && !changeReadOnly[0]) { return true; } try { if (newLocation != null && !isCompatible(newLocation, oldLocation)) { if (!MessageDialog.openQuestion(getShell(), CVSUIMessages.CVSProjectPropertiesPage_32, CVSUIMessages.CVSProjectPropertiesPage_33)) { //$NON-NLS-1$ //$NON-NLS-2$ return false; } } new ProgressMonitorDialog(getShell()).run(true, true, new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { monitor.beginTask(CVSUIMessages.CVSProjectPropertiesPage_progressTaskName, //$NON-NLS-1$ ((newLocation == null)?0:100) + (changeReadOnly[0]?100:0)); if (newLocation != null) provider.setRemoteRoot(newLocation, Policy.subMonitorFor(monitor, 100)); if (changeReadOnly[0]) setReadOnly(watchEdit, Policy.infiniteSubMonitorFor(monitor, 100)); } catch (TeamException e) { throw new InvocationTargetException(e); } } }); newLocation = null; if (changeReadOnly[0]) { CVSUIPlugin.broadcastPropertyChange(new PropertyChangeEvent(this, CVSUIPlugin.P_DECORATORS_CHANGED, null, null)); } } catch (InvocationTargetException e) { handle(e); } catch (InterruptedException e) { return false; } return true; } /** * @param watchEdit */ protected void setReadOnly(final boolean watchEdit, final IProgressMonitor monitor) throws CVSException { monitor.beginTask(null, 512); String taskName = watchEdit? CVSUIMessages.CVSProjectPropertiesPage_setReadOnly: //$NON-NLS-1$ CVSUIMessages.CVSProjectPropertiesPage_clearReadOnly; //$NON-NLS-1$ monitor.subTask(taskName); ICVSFolder root = CVSWorkspaceRoot.getCVSFolderFor(project); root.accept(new ICVSResourceVisitor() { public void visitFile(ICVSFile file) throws CVSException { // only change managed, unmodified files if (file.isManaged() && !file.isModified(null)) file.setReadOnly(watchEdit); monitor.worked(1); } public void visitFolder(ICVSFolder folder) throws CVSException { folder.acceptChildren(this); } }); monitor.done(); } /** * Shows the given errors to the user. */ protected void handle(Throwable t) { CVSUIPlugin.openError(getShell(), null, null, t); } }
false
true
protected Control createContents(Composite parent) { initialize(); Composite composite = new Composite(parent, SWT.NULL); composite.setLayoutData(new GridData(GridData.FILL_BOTH)); GridLayout layout = new GridLayout(); layout.numColumns = 2; composite.setLayout(layout); Label label = createLabel(composite, CVSUIMessages.CVSProjectPropertiesPage_connectionType, 1); //$NON-NLS-1$ methodText = createReadOnlyText(composite, "", 1); //$NON-NLS-1$ label = createLabel(composite, CVSUIMessages.CVSProjectPropertiesPage_user, 1); //$NON-NLS-1$ userText = createReadOnlyText(composite, "", 1); //$NON-NLS-1$ label = createLabel(composite, CVSUIMessages.CVSPropertiesPage_host, 1); //$NON-NLS-1$ hostText = createReadOnlyText(composite, "", 1); //$NON-NLS-1$ label = createLabel(composite, CVSUIMessages.CVSPropertiesPage_port, 1); //$NON-NLS-1$ portText = createReadOnlyText(composite, "", 1); //$NON-NLS-1$ label = createLabel(composite, CVSUIMessages.CVSPropertiesPage_path, 1); //$NON-NLS-1$ pathText = createReadOnlyText(composite, "", 1); //$NON-NLS-1$ label = createLabel(composite, CVSUIMessages.CVSPropertiesPage_module, 1); //$NON-NLS-1$ moduleText = createReadOnlyText(composite, "", 1); //$NON-NLS-1$ label = createLabel(composite, CVSUIMessages.CVSPropertiesPage_tag, 1); //$NON-NLS-1$ tagText = createReadOnlyText(composite, "", 1); //$NON-NLS-1$ createLabel(composite, "", 1); //$NON-NLS-1$ // Should absent directories be fetched on update fetchButton = createCheckBox(composite, CVSUIMessages.CVSProjectPropertiesPage_fetchAbsentDirectoriesOnUpdate); //$NON-NLS-1$ fetchButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { fetch = fetchButton.getSelection(); } }); // Should the project be configured for watch/edit watchEditButton = createCheckBox(composite, CVSUIMessages.CVSProjectPropertiesPage_configureForWatchEdit); //$NON-NLS-1$ watchEditButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { watchEdit = watchEditButton.getSelection(); } }); createLabel(composite, "", 1); //$NON-NLS-1$ createLabel(composite, "", 1); //$NON-NLS-1$ createLabel(composite, "", 1); //$NON-NLS-1$ createLabel(composite, "", 1); //$NON-NLS-1$ label = new Label(composite, SWT.WRAP); label.setText(CVSUIMessages.CVSProjectPropertiesPage_You_can_change_the_sharing_of_this_project_to_another_repository_location__However__this_is_only_possible_if_the_new_location_is___compatible____on_the_same_host_with_the_same_repository_path___1); //$NON-NLS-1$ GridData data = new GridData(GridData.FILL_HORIZONTAL); data.widthHint = 200; data.horizontalSpan = 2; label.setLayoutData(data); Button changeButton = new Button(composite, SWT.PUSH); changeButton.setText(CVSUIMessages.CVSProjectPropertiesPage_Change_Sharing_5); //$NON-NLS-1$ changeButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { RepositorySelectionDialog dialog = new RepositorySelectionDialog(getShell(), oldLocation); dialog.open(); ICVSRepositoryLocation location = dialog.getLocation(); if (location == null) return; newLocation = location; initializeValues(newLocation); } }); initializeValues(oldLocation); PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IHelpContextIds.PROJECT_PROPERTY_PAGE); Dialog.applyDialogFont(parent); return composite; }
protected Control createContents(Composite parent) { initialize(); Composite composite = new Composite(parent, SWT.NULL); composite.setLayoutData(new GridData(GridData.FILL_BOTH)); GridLayout layout = new GridLayout(); layout.numColumns = 2; composite.setLayout(layout); Label label = createLabel(composite, CVSUIMessages.CVSProjectPropertiesPage_connectionType, 1); //$NON-NLS-1$ methodText = createReadOnlyText(composite, "", 1); //$NON-NLS-1$ label = createLabel(composite, CVSUIMessages.CVSProjectPropertiesPage_user, 1); //$NON-NLS-1$ userText = createReadOnlyText(composite, "", 1); //$NON-NLS-1$ label = createLabel(composite, CVSUIMessages.CVSRepositoryLocationPropertySource_host, 1); //$NON-NLS-1$ hostText = createReadOnlyText(composite, "", 1); //$NON-NLS-1$ label = createLabel(composite, CVSUIMessages.CVSPropertiesPage_port, 1); //$NON-NLS-1$ portText = createReadOnlyText(composite, "", 1); //$NON-NLS-1$ label = createLabel(composite, CVSUIMessages.CVSRepositoryLocationPropertySource_root, 1); //$NON-NLS-1$ pathText = createReadOnlyText(composite, "", 1); //$NON-NLS-1$ label = createLabel(composite, CVSUIMessages.CVSPropertiesPage_module, 1); //$NON-NLS-1$ moduleText = createReadOnlyText(composite, "", 1); //$NON-NLS-1$ label = createLabel(composite, CVSUIMessages.CVSPropertiesPage_tag, 1); //$NON-NLS-1$ tagText = createReadOnlyText(composite, "", 1); //$NON-NLS-1$ createLabel(composite, "", 1); //$NON-NLS-1$ // Should absent directories be fetched on update fetchButton = createCheckBox(composite, CVSUIMessages.CVSProjectPropertiesPage_fetchAbsentDirectoriesOnUpdate); //$NON-NLS-1$ fetchButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { fetch = fetchButton.getSelection(); } }); // Should the project be configured for watch/edit watchEditButton = createCheckBox(composite, CVSUIMessages.CVSProjectPropertiesPage_configureForWatchEdit); //$NON-NLS-1$ watchEditButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { watchEdit = watchEditButton.getSelection(); } }); createLabel(composite, "", 1); //$NON-NLS-1$ createLabel(composite, "", 1); //$NON-NLS-1$ createLabel(composite, "", 1); //$NON-NLS-1$ createLabel(composite, "", 1); //$NON-NLS-1$ label = new Label(composite, SWT.WRAP); label.setText(CVSUIMessages.CVSProjectPropertiesPage_You_can_change_the_sharing_of_this_project_to_another_repository_location__However__this_is_only_possible_if_the_new_location_is___compatible____on_the_same_host_with_the_same_repository_path___1); //$NON-NLS-1$ GridData data = new GridData(GridData.FILL_HORIZONTAL); data.widthHint = 200; data.horizontalSpan = 2; label.setLayoutData(data); Button changeButton = new Button(composite, SWT.PUSH); changeButton.setText(CVSUIMessages.CVSProjectPropertiesPage_Change_Sharing_5); //$NON-NLS-1$ changeButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { RepositorySelectionDialog dialog = new RepositorySelectionDialog(getShell(), oldLocation); dialog.open(); ICVSRepositoryLocation location = dialog.getLocation(); if (location == null) return; newLocation = location; initializeValues(newLocation); } }); initializeValues(oldLocation); PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IHelpContextIds.PROJECT_PROPERTY_PAGE); Dialog.applyDialogFont(parent); return composite; }
diff --git a/source/java/org/encuestame/core/persistence/util/EnMeSchemaExport.java b/source/java/org/encuestame/core/persistence/util/EnMeSchemaExport.java index 387a66e45..eb2eb1fcf 100644 --- a/source/java/org/encuestame/core/persistence/util/EnMeSchemaExport.java +++ b/source/java/org/encuestame/core/persistence/util/EnMeSchemaExport.java @@ -1,117 +1,117 @@ /** * encuestame: system online surveys Copyright (C) 2009 encuestame Development * Team * * This program is free software; you can redistribute it and/or modify it under * the terms of version 3 of the GNU General Public License as published by the * Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License 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 org.encuestame.core.persistence.util; import java.util.Date; import org.encuestame.core.exception.EnMeExpcetion; import org.encuestame.core.persistence.dao.CatStateDaoImp; import org.encuestame.core.persistence.pojo.CatState; import org.encuestame.core.service.SecurityService; import org.encuestame.web.beans.admon.UnitPermission; import org.encuestame.web.beans.admon.UnitUserBean; import org.springframework.context.support.FileSystemXmlApplicationContext; import org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean; /** * EnMeSchemaExport. * * @author Picado, Juan [email protected] * @since October 19, 2009 */ public class EnMeSchemaExport { /** spring config files. **/ private static final String[] SPRING_CONFIG_FILES = new String[] { "source/config/spring/encuestame-hibernate-context.xml", "source/config/spring/encuestame-dao-context.xml", "source/config/spring/encuestame-param-context.xml", "source/config/spring/encuestame-service-context.xml", "source/config/spring/encuestame-email-context.xml" }; /** spring config files. **/ private static final String[] SPRING_CONFIG_TEST_FILES = new String[] { "source/config/spring/encuestame-hibernate-context.xml", "source/config/spring/encuestame-dao-context.xml", "source/config/spring/encuestame-param-test-context.xml", "source/config/spring/encuestame-service-context.xml", "source/config/spring/encuestame-email-context.xml" }; /** * Drop schema and create schema. */ public void create() { final FileSystemXmlApplicationContext appContext = new FileSystemXmlApplicationContext( SPRING_CONFIG_FILES); final AnnotationSessionFactoryBean annotationSF = (AnnotationSessionFactoryBean) appContext .getBean("&sessionFactory"); annotationSF.dropDatabaseSchema(); final SecurityService securityService = (SecurityService) appContext .getBean("securityService"); annotationSF.createDatabaseSchema(); try { final UnitPermission permissionBean = new UnitPermission(); // create encuestame user permission. permissionBean.setPermission("ENCUESTAME_USER"); permissionBean.setDescription("ENCUESTAME_USER"); securityService.createPermission(permissionBean); // create permission admin final UnitPermission permissionAdmin = new UnitPermission(); permissionAdmin.setPermission("ENCUESTAME_ADMIN"); permissionAdmin.setDescription("ENCUESTAME_ADMIN"); securityService.createPermission(permissionAdmin); //create user admin final UnitUserBean user = new UnitUserBean(); user.setDate_new(new Date()); user.setEmail("[email protected]"); user.setPassword("12345"); user.setUsername("admin"); user.setName("admin"); user.setStatus(true); securityService.createUser(user); //admin user permission securityService.assignPermission(user, permissionAdmin); final CatStateDaoImp stateDao = (CatStateDaoImp) appContext.getBean("catStateDaoImp"); final CatState activate = new CatState(); activate.setDescState("activate"); stateDao.saveOrUpdate(activate); final CatState inactive = new CatState(); inactive.setDescState("inactive"); stateDao.saveOrUpdate(inactive); stateDao.saveOrUpdate(inactive); } catch (EnMeExpcetion e) { System.out.println("Error create data " + e.getMessage()); } //Create test database final FileSystemXmlApplicationContext appContextTest = new FileSystemXmlApplicationContext( SPRING_CONFIG_TEST_FILES); final AnnotationSessionFactoryBean annotationSFTest = (AnnotationSessionFactoryBean) appContextTest .getBean("&sessionFactory"); - annotationSF.dropDatabaseSchema(); + annotationSFTest.dropDatabaseSchema(); annotationSFTest.createDatabaseSchema(); } /** * @param args args */ public static void main(String[] args) { new EnMeSchemaExport().create(); } }
true
true
public void create() { final FileSystemXmlApplicationContext appContext = new FileSystemXmlApplicationContext( SPRING_CONFIG_FILES); final AnnotationSessionFactoryBean annotationSF = (AnnotationSessionFactoryBean) appContext .getBean("&sessionFactory"); annotationSF.dropDatabaseSchema(); final SecurityService securityService = (SecurityService) appContext .getBean("securityService"); annotationSF.createDatabaseSchema(); try { final UnitPermission permissionBean = new UnitPermission(); // create encuestame user permission. permissionBean.setPermission("ENCUESTAME_USER"); permissionBean.setDescription("ENCUESTAME_USER"); securityService.createPermission(permissionBean); // create permission admin final UnitPermission permissionAdmin = new UnitPermission(); permissionAdmin.setPermission("ENCUESTAME_ADMIN"); permissionAdmin.setDescription("ENCUESTAME_ADMIN"); securityService.createPermission(permissionAdmin); //create user admin final UnitUserBean user = new UnitUserBean(); user.setDate_new(new Date()); user.setEmail("[email protected]"); user.setPassword("12345"); user.setUsername("admin"); user.setName("admin"); user.setStatus(true); securityService.createUser(user); //admin user permission securityService.assignPermission(user, permissionAdmin); final CatStateDaoImp stateDao = (CatStateDaoImp) appContext.getBean("catStateDaoImp"); final CatState activate = new CatState(); activate.setDescState("activate"); stateDao.saveOrUpdate(activate); final CatState inactive = new CatState(); inactive.setDescState("inactive"); stateDao.saveOrUpdate(inactive); stateDao.saveOrUpdate(inactive); } catch (EnMeExpcetion e) { System.out.println("Error create data " + e.getMessage()); } //Create test database final FileSystemXmlApplicationContext appContextTest = new FileSystemXmlApplicationContext( SPRING_CONFIG_TEST_FILES); final AnnotationSessionFactoryBean annotationSFTest = (AnnotationSessionFactoryBean) appContextTest .getBean("&sessionFactory"); annotationSF.dropDatabaseSchema(); annotationSFTest.createDatabaseSchema(); }
public void create() { final FileSystemXmlApplicationContext appContext = new FileSystemXmlApplicationContext( SPRING_CONFIG_FILES); final AnnotationSessionFactoryBean annotationSF = (AnnotationSessionFactoryBean) appContext .getBean("&sessionFactory"); annotationSF.dropDatabaseSchema(); final SecurityService securityService = (SecurityService) appContext .getBean("securityService"); annotationSF.createDatabaseSchema(); try { final UnitPermission permissionBean = new UnitPermission(); // create encuestame user permission. permissionBean.setPermission("ENCUESTAME_USER"); permissionBean.setDescription("ENCUESTAME_USER"); securityService.createPermission(permissionBean); // create permission admin final UnitPermission permissionAdmin = new UnitPermission(); permissionAdmin.setPermission("ENCUESTAME_ADMIN"); permissionAdmin.setDescription("ENCUESTAME_ADMIN"); securityService.createPermission(permissionAdmin); //create user admin final UnitUserBean user = new UnitUserBean(); user.setDate_new(new Date()); user.setEmail("[email protected]"); user.setPassword("12345"); user.setUsername("admin"); user.setName("admin"); user.setStatus(true); securityService.createUser(user); //admin user permission securityService.assignPermission(user, permissionAdmin); final CatStateDaoImp stateDao = (CatStateDaoImp) appContext.getBean("catStateDaoImp"); final CatState activate = new CatState(); activate.setDescState("activate"); stateDao.saveOrUpdate(activate); final CatState inactive = new CatState(); inactive.setDescState("inactive"); stateDao.saveOrUpdate(inactive); stateDao.saveOrUpdate(inactive); } catch (EnMeExpcetion e) { System.out.println("Error create data " + e.getMessage()); } //Create test database final FileSystemXmlApplicationContext appContextTest = new FileSystemXmlApplicationContext( SPRING_CONFIG_TEST_FILES); final AnnotationSessionFactoryBean annotationSFTest = (AnnotationSessionFactoryBean) appContextTest .getBean("&sessionFactory"); annotationSFTest.dropDatabaseSchema(); annotationSFTest.createDatabaseSchema(); }
diff --git a/src/com/android/gallery3d/app/PhotoPage.java b/src/com/android/gallery3d/app/PhotoPage.java index b43cf2a70..506d1ca6f 100644 --- a/src/com/android/gallery3d/app/PhotoPage.java +++ b/src/com/android/gallery3d/app/PhotoPage.java @@ -1,1496 +1,1498 @@ /* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.gallery3d.app; import android.annotation.TargetApi; import android.app.ActionBar.OnMenuVisibilityListener; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Rect; import android.net.Uri; import android.nfc.NfcAdapter; import android.nfc.NfcAdapter.CreateBeamUrisCallback; import android.nfc.NfcEvent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.SystemClock; import android.view.Menu; import android.view.MenuItem; import android.widget.RelativeLayout; import android.widget.Toast; import com.android.camera.CameraActivity; import com.android.camera.ProxyLauncher; import com.android.gallery3d.R; import com.android.gallery3d.common.ApiHelper; import com.android.gallery3d.data.ComboAlbum; import com.android.gallery3d.data.DataManager; import com.android.gallery3d.data.FilterDeleteSet; import com.android.gallery3d.data.FilterSource; import com.android.gallery3d.data.LocalImage; import com.android.gallery3d.data.MediaDetails; import com.android.gallery3d.data.MediaItem; import com.android.gallery3d.data.MediaObject; import com.android.gallery3d.data.MediaObject.PanoramaSupportCallback; import com.android.gallery3d.data.MediaSet; import com.android.gallery3d.data.MtpSource; import com.android.gallery3d.data.Path; import com.android.gallery3d.data.SecureAlbum; import com.android.gallery3d.data.SecureSource; import com.android.gallery3d.data.SnailAlbum; import com.android.gallery3d.data.SnailItem; import com.android.gallery3d.data.SnailSource; import com.android.gallery3d.filtershow.FilterShowActivity; import com.android.gallery3d.picasasource.PicasaSource; import com.android.gallery3d.ui.DetailsHelper; import com.android.gallery3d.ui.DetailsHelper.CloseListener; import com.android.gallery3d.ui.DetailsHelper.DetailsSource; import com.android.gallery3d.ui.GLView; import com.android.gallery3d.ui.ImportCompleteListener; import com.android.gallery3d.ui.MenuExecutor; import com.android.gallery3d.ui.PhotoView; import com.android.gallery3d.ui.SelectionManager; import com.android.gallery3d.ui.SynchronizedHandler; import com.android.gallery3d.util.GalleryUtils; public class PhotoPage extends ActivityState implements PhotoView.Listener, AppBridge.Server, PhotoPageBottomControls.Delegate, GalleryActionBar.OnAlbumModeSelectedListener { private static final String TAG = "PhotoPage"; private static final int MSG_HIDE_BARS = 1; private static final int MSG_ON_FULL_SCREEN_CHANGED = 4; private static final int MSG_UPDATE_ACTION_BAR = 5; private static final int MSG_UNFREEZE_GLROOT = 6; private static final int MSG_WANT_BARS = 7; private static final int MSG_REFRESH_BOTTOM_CONTROLS = 8; private static final int MSG_ON_CAMERA_CENTER = 9; private static final int MSG_ON_PICTURE_CENTER = 10; private static final int MSG_REFRESH_IMAGE = 11; private static final int MSG_UPDATE_PHOTO_UI = 12; private static final int MSG_UPDATE_PROGRESS = 13; private static final int MSG_UPDATE_DEFERRED = 14; private static final int MSG_UPDATE_SHARE_URI = 15; private static final int MSG_UPDATE_PANORAMA_UI = 16; private static final int HIDE_BARS_TIMEOUT = 3500; private static final int UNFREEZE_GLROOT_TIMEOUT = 250; private static final int REQUEST_SLIDESHOW = 1; private static final int REQUEST_CROP = 2; private static final int REQUEST_CROP_PICASA = 3; private static final int REQUEST_EDIT = 4; private static final int REQUEST_PLAY_VIDEO = 5; private static final int REQUEST_TRIM = 6; public static final String KEY_MEDIA_SET_PATH = "media-set-path"; public static final String KEY_MEDIA_ITEM_PATH = "media-item-path"; public static final String KEY_INDEX_HINT = "index-hint"; public static final String KEY_OPEN_ANIMATION_RECT = "open-animation-rect"; public static final String KEY_APP_BRIDGE = "app-bridge"; public static final String KEY_TREAT_BACK_AS_UP = "treat-back-as-up"; public static final String KEY_START_IN_FILMSTRIP = "start-in-filmstrip"; public static final String KEY_RETURN_INDEX_HINT = "return-index-hint"; public static final String KEY_SHOW_WHEN_LOCKED = "show_when_locked"; public static final String KEY_IN_CAMERA_ROLL = "in_camera_roll"; public static final String KEY_ALBUMPAGE_TRANSITION = "albumpage-transition"; public static final int MSG_ALBUMPAGE_NONE = 0; public static final int MSG_ALBUMPAGE_STARTED = 1; public static final int MSG_ALBUMPAGE_RESUMED = 2; public static final int MSG_ALBUMPAGE_PICKED = 4; public static final String ACTION_NEXTGEN_EDIT = "action_nextgen_edit"; private GalleryApp mApplication; private SelectionManager mSelectionManager; private PhotoView mPhotoView; private PhotoPage.Model mModel; private DetailsHelper mDetailsHelper; private boolean mShowDetails; // mMediaSet could be null if there is no KEY_MEDIA_SET_PATH supplied. // E.g., viewing a photo in gmail attachment private FilterDeleteSet mMediaSet; // The mediaset used by camera launched from secure lock screen. private SecureAlbum mSecureAlbum; private int mCurrentIndex = 0; private Handler mHandler; private boolean mShowBars = true; private volatile boolean mActionBarAllowed = true; private GalleryActionBar mActionBar; private boolean mIsMenuVisible; private boolean mHaveImageEditor; private PhotoPageBottomControls mBottomControls; private PhotoPageProgressBar mProgressBar; private MediaItem mCurrentPhoto = null; private MenuExecutor mMenuExecutor; private boolean mIsActive; private boolean mShowSpinner; private String mSetPathString; // This is the original mSetPathString before adding the camera preview item. private String mOriginalSetPathString; private AppBridge mAppBridge; private SnailItem mScreenNailItem; private SnailAlbum mScreenNailSet; private OrientationManager mOrientationManager; private boolean mTreatBackAsUp; private boolean mStartInFilmstrip; private boolean mHasCameraScreennailOrPlaceholder = false; private boolean mRecenterCameraOnResume = true; // These are only valid after the panorama callback private boolean mIsPanorama; private boolean mIsPanorama360; private long mCameraSwitchCutoff = 0; private boolean mSkipUpdateCurrentPhoto = false; private static final long CAMERA_SWITCH_CUTOFF_THRESHOLD_MS = 300; private static final long DEFERRED_UPDATE_MS = 250; private boolean mDeferredUpdateWaiting = false; private long mDeferUpdateUntil = Long.MAX_VALUE; // The item that is deleted (but it can still be undeleted before commiting) private Path mDeletePath; private boolean mDeleteIsFocus; // whether the deleted item was in focus private Uri[] mNfcPushUris = new Uri[1]; private final MyMenuVisibilityListener mMenuVisibilityListener = new MyMenuVisibilityListener(); private UpdateProgressListener mProgressListener; private final PanoramaSupportCallback mUpdatePanoramaMenuItemsCallback = new PanoramaSupportCallback() { @Override public void panoramaInfoAvailable(MediaObject mediaObject, boolean isPanorama, boolean isPanorama360) { if (mediaObject == mCurrentPhoto) { mHandler.obtainMessage(MSG_UPDATE_PANORAMA_UI, isPanorama360 ? 1 : 0, 0, mediaObject).sendToTarget(); } } }; private final PanoramaSupportCallback mRefreshBottomControlsCallback = new PanoramaSupportCallback() { @Override public void panoramaInfoAvailable(MediaObject mediaObject, boolean isPanorama, boolean isPanorama360) { if (mediaObject == mCurrentPhoto) { mHandler.obtainMessage(MSG_REFRESH_BOTTOM_CONTROLS, isPanorama ? 1 : 0, isPanorama360 ? 1 : 0, mediaObject).sendToTarget(); } } }; private final PanoramaSupportCallback mUpdateShareURICallback = new PanoramaSupportCallback() { @Override public void panoramaInfoAvailable(MediaObject mediaObject, boolean isPanorama, boolean isPanorama360) { if (mediaObject == mCurrentPhoto) { mHandler.obtainMessage(MSG_UPDATE_SHARE_URI, isPanorama360 ? 1 : 0, 0, mediaObject) .sendToTarget(); } } }; public static interface Model extends PhotoView.Model { public void resume(); public void pause(); public boolean isEmpty(); public void setCurrentPhoto(Path path, int indexHint); } private class MyMenuVisibilityListener implements OnMenuVisibilityListener { @Override public void onMenuVisibilityChanged(boolean isVisible) { mIsMenuVisible = isVisible; refreshHidingMessage(); } } private class UpdateProgressListener implements StitchingChangeListener { @Override public void onStitchingResult(Uri uri) { sendUpdate(uri, MSG_REFRESH_IMAGE); } @Override public void onStitchingQueued(Uri uri) { sendUpdate(uri, MSG_UPDATE_PROGRESS); } @Override public void onStitchingProgress(Uri uri, final int progress) { sendUpdate(uri, MSG_UPDATE_PROGRESS); } private void sendUpdate(Uri uri, int message) { MediaObject currentPhoto = mCurrentPhoto; boolean isCurrentPhoto = currentPhoto instanceof LocalImage && currentPhoto.getContentUri().equals(uri); if (isCurrentPhoto) { mHandler.sendEmptyMessage(message); } } }; @Override protected int getBackgroundColorId() { return R.color.photo_background; } private final GLView mRootPane = new GLView() { @Override protected void onLayout( boolean changed, int left, int top, int right, int bottom) { mPhotoView.layout(0, 0, right - left, bottom - top); if (mShowDetails) { mDetailsHelper.layout(left, mActionBar.getHeight(), right, bottom); } } }; @Override public void onCreate(Bundle data, Bundle restoreState) { super.onCreate(data, restoreState); mActionBar = mActivity.getGalleryActionBar(); mSelectionManager = new SelectionManager(mActivity, false); mMenuExecutor = new MenuExecutor(mActivity, mSelectionManager); mPhotoView = new PhotoView(mActivity); mPhotoView.setListener(this); mRootPane.addComponent(mPhotoView); mApplication = (GalleryApp) ((Activity) mActivity).getApplication(); mOrientationManager = mActivity.getOrientationManager(); mActivity.getGLRoot().setOrientationSource(mOrientationManager); mHandler = new SynchronizedHandler(mActivity.getGLRoot()) { @Override public void handleMessage(Message message) { switch (message.what) { case MSG_HIDE_BARS: { hideBars(); break; } case MSG_REFRESH_BOTTOM_CONTROLS: { if (mCurrentPhoto == message.obj && mBottomControls != null) { mIsPanorama = message.arg1 == 1; mIsPanorama360 = message.arg2 == 1; mBottomControls.refresh(); } break; } case MSG_ON_FULL_SCREEN_CHANGED: { - mAppBridge.onFullScreenChanged(message.arg1 == 1); + if (mAppBridge != null) { + mAppBridge.onFullScreenChanged(message.arg1 == 1); + } break; } case MSG_UPDATE_ACTION_BAR: { updateBars(); break; } case MSG_WANT_BARS: { wantBars(); break; } case MSG_UNFREEZE_GLROOT: { mActivity.getGLRoot().unfreeze(); break; } case MSG_UPDATE_DEFERRED: { long nextUpdate = mDeferUpdateUntil - SystemClock.uptimeMillis(); if (nextUpdate <= 0) { mDeferredUpdateWaiting = false; updateUIForCurrentPhoto(); } else { mHandler.sendEmptyMessageDelayed(MSG_UPDATE_DEFERRED, nextUpdate); } break; } case MSG_ON_CAMERA_CENTER: { mSkipUpdateCurrentPhoto = false; boolean stayedOnCamera = false; if (!mPhotoView.getFilmMode()) { stayedOnCamera = true; } else if (SystemClock.uptimeMillis() < mCameraSwitchCutoff && mMediaSet.getMediaItemCount() > 1) { mPhotoView.switchToImage(1); } else { if (mAppBridge != null) mPhotoView.setFilmMode(false); stayedOnCamera = true; } if (stayedOnCamera) { if (mAppBridge == null) { launchCamera(); /* We got here by swiping from photo 1 to the placeholder, so make it be the thing that is in focus when the user presses back from the camera app */ mPhotoView.switchToImage(1); } else { updateBars(); updateCurrentPhoto(mModel.getMediaItem(0)); } } break; } case MSG_ON_PICTURE_CENTER: { if (!mPhotoView.getFilmMode() && mCurrentPhoto != null && (mCurrentPhoto.getSupportedOperations() & MediaObject.SUPPORT_ACTION) != 0) { mPhotoView.setFilmMode(true); } break; } case MSG_REFRESH_IMAGE: { final MediaItem photo = mCurrentPhoto; mCurrentPhoto = null; updateCurrentPhoto(photo); break; } case MSG_UPDATE_PHOTO_UI: { updateUIForCurrentPhoto(); break; } case MSG_UPDATE_PROGRESS: { updateProgressBar(); break; } case MSG_UPDATE_SHARE_URI: { if (mCurrentPhoto == message.obj) { boolean isPanorama360 = message.arg1 != 0; Uri contentUri = mCurrentPhoto.getContentUri(); Intent panoramaIntent = null; if (isPanorama360) { panoramaIntent = createSharePanoramaIntent(contentUri); } Intent shareIntent = createShareIntent(mCurrentPhoto); mActionBar.setShareIntents(panoramaIntent, shareIntent); setNfcBeamPushUri(contentUri); } break; } case MSG_UPDATE_PANORAMA_UI: { if (mCurrentPhoto == message.obj) { boolean isPanorama360 = message.arg1 != 0; updatePanoramaUI(isPanorama360); } break; } default: throw new AssertionError(message.what); } } }; mSetPathString = data.getString(KEY_MEDIA_SET_PATH); mOriginalSetPathString = mSetPathString; setupNfcBeamPush(); String itemPathString = data.getString(KEY_MEDIA_ITEM_PATH); Path itemPath = itemPathString != null ? Path.fromString(data.getString(KEY_MEDIA_ITEM_PATH)) : null; mTreatBackAsUp = data.getBoolean(KEY_TREAT_BACK_AS_UP, false); mStartInFilmstrip = data.getBoolean(KEY_START_IN_FILMSTRIP, false); boolean inCameraRoll = data.getBoolean(KEY_IN_CAMERA_ROLL, false); mCurrentIndex = data.getInt(KEY_INDEX_HINT, 0); if (mSetPathString != null) { mShowSpinner = true; mAppBridge = (AppBridge) data.getParcelable(KEY_APP_BRIDGE); if (mAppBridge != null) { mShowBars = false; mHasCameraScreennailOrPlaceholder = true; mAppBridge.setServer(this); // Get the ScreenNail from AppBridge and register it. int id = SnailSource.newId(); Path screenNailSetPath = SnailSource.getSetPath(id); Path screenNailItemPath = SnailSource.getItemPath(id); mScreenNailSet = (SnailAlbum) mActivity.getDataManager() .getMediaObject(screenNailSetPath); mScreenNailItem = (SnailItem) mActivity.getDataManager() .getMediaObject(screenNailItemPath); mScreenNailItem.setScreenNail(mAppBridge.attachScreenNail()); if (data.getBoolean(KEY_SHOW_WHEN_LOCKED, false)) { // Set the flag to be on top of the lock screen. mFlags |= FLAG_SHOW_WHEN_LOCKED; } // Don't display "empty album" action item for capture intents. if (!mSetPathString.equals("/local/all/0")) { // Check if the path is a secure album. if (SecureSource.isSecurePath(mSetPathString)) { mSecureAlbum = (SecureAlbum) mActivity.getDataManager() .getMediaSet(mSetPathString); mShowSpinner = false; } mSetPathString = "/filter/empty/{"+mSetPathString+"}"; } // Combine the original MediaSet with the one for ScreenNail // from AppBridge. mSetPathString = "/combo/item/{" + screenNailSetPath + "," + mSetPathString + "}"; // Start from the screen nail. itemPath = screenNailItemPath; } else if (inCameraRoll && GalleryUtils.isCameraAvailable(mActivity)) { mSetPathString = "/combo/item/{" + FilterSource.FILTER_CAMERA_SHORTCUT + "," + mSetPathString + "}"; mCurrentIndex++; mHasCameraScreennailOrPlaceholder = true; } MediaSet originalSet = mActivity.getDataManager() .getMediaSet(mSetPathString); if (mHasCameraScreennailOrPlaceholder && originalSet instanceof ComboAlbum) { // Use the name of the camera album rather than the default // ComboAlbum behavior ((ComboAlbum) originalSet).useNameOfChild(1); } mSelectionManager.setSourceMediaSet(originalSet); mSetPathString = "/filter/delete/{" + mSetPathString + "}"; mMediaSet = (FilterDeleteSet) mActivity.getDataManager() .getMediaSet(mSetPathString); if (mMediaSet == null) { Log.w(TAG, "failed to restore " + mSetPathString); } if (itemPath == null) { int mediaItemCount = mMediaSet.getMediaItemCount(); if (mediaItemCount > 0) { if (mCurrentIndex >= mediaItemCount) mCurrentIndex = 0; itemPath = mMediaSet.getMediaItem(mCurrentIndex, 1) .get(0).getPath(); } else { // Bail out, PhotoPage can't load on an empty album return; } } PhotoDataAdapter pda = new PhotoDataAdapter( mActivity, mPhotoView, mMediaSet, itemPath, mCurrentIndex, mAppBridge == null ? -1 : 0, mAppBridge == null ? false : mAppBridge.isPanorama(), mAppBridge == null ? false : mAppBridge.isStaticCamera()); mModel = pda; mPhotoView.setModel(mModel); pda.setDataListener(new PhotoDataAdapter.DataListener() { @Override public void onPhotoChanged(int index, Path item) { int oldIndex = mCurrentIndex; mCurrentIndex = index; if (mHasCameraScreennailOrPlaceholder) { if (mCurrentIndex > 0) { mSkipUpdateCurrentPhoto = false; } if (oldIndex == 0 && mCurrentIndex > 0 && !mPhotoView.getFilmMode()) { mPhotoView.setFilmMode(true); } else if (oldIndex == 2 && mCurrentIndex == 1) { mCameraSwitchCutoff = SystemClock.uptimeMillis() + CAMERA_SWITCH_CUTOFF_THRESHOLD_MS; mPhotoView.stopScrolling(); } else if (oldIndex >= 1 && mCurrentIndex == 0) { mPhotoView.setWantPictureCenterCallbacks(true); mSkipUpdateCurrentPhoto = true; } } if (!mSkipUpdateCurrentPhoto) { if (item != null) { MediaItem photo = mModel.getMediaItem(0); if (photo != null) updateCurrentPhoto(photo); } updateBars(); } // Reset the timeout for the bars after a swipe refreshHidingMessage(); } @Override public void onLoadingFinished(boolean loadingFailed) { if (!mModel.isEmpty()) { MediaItem photo = mModel.getMediaItem(0); if (photo != null) updateCurrentPhoto(photo); } else if (mIsActive) { // We only want to finish the PhotoPage if there is no // deletion that the user can undo. if (mMediaSet.getNumberOfDeletions() == 0) { mActivity.getStateManager().finishState( PhotoPage.this); } } } @Override public void onLoadingStarted() { } }); } else { // Get default media set by the URI MediaItem mediaItem = (MediaItem) mActivity.getDataManager().getMediaObject(itemPath); mModel = new SinglePhotoDataAdapter(mActivity, mPhotoView, mediaItem); mPhotoView.setModel(mModel); updateCurrentPhoto(mediaItem); mShowSpinner = false; } mPhotoView.setFilmMode(mStartInFilmstrip && mMediaSet.getMediaItemCount() > 1); RelativeLayout galleryRoot = (RelativeLayout) ((Activity) mActivity) .findViewById(mAppBridge != null ? R.id.content : R.id.gallery_root); if (galleryRoot != null) { if (mSecureAlbum == null) { mBottomControls = new PhotoPageBottomControls(this, mActivity, galleryRoot); } StitchingProgressManager progressManager = mApplication.getStitchingProgressManager(); if (progressManager != null) { mProgressBar = new PhotoPageProgressBar(mActivity, galleryRoot); mProgressListener = new UpdateProgressListener(); progressManager.addChangeListener(mProgressListener); if (mSecureAlbum != null) { progressManager.addChangeListener(mSecureAlbum); } } } } @Override public void onPictureCenter(boolean isCamera) { isCamera = isCamera || (mHasCameraScreennailOrPlaceholder && mAppBridge == null); mPhotoView.setWantPictureCenterCallbacks(false); mHandler.removeMessages(MSG_ON_CAMERA_CENTER); mHandler.removeMessages(MSG_ON_PICTURE_CENTER); mHandler.sendEmptyMessage(isCamera ? MSG_ON_CAMERA_CENTER : MSG_ON_PICTURE_CENTER); } @Override public boolean canDisplayBottomControls() { return mIsActive && !mPhotoView.canUndo(); } @Override public boolean canDisplayBottomControl(int control) { if (mCurrentPhoto == null) { return false; } switch(control) { case R.id.photopage_bottom_control_edit: return mHaveImageEditor && mShowBars && !mPhotoView.getFilmMode() && (mCurrentPhoto.getSupportedOperations() & MediaItem.SUPPORT_EDIT) != 0 && mCurrentPhoto.getMediaType() == MediaObject.MEDIA_TYPE_IMAGE; case R.id.photopage_bottom_control_panorama: return mIsPanorama; case R.id.photopage_bottom_control_tiny_planet: return mHaveImageEditor && mShowBars && mIsPanorama360 && !mPhotoView.getFilmMode(); default: return false; } } @Override public void onBottomControlClicked(int control) { switch(control) { case R.id.photopage_bottom_control_edit: launchPhotoEditor(); return; case R.id.photopage_bottom_control_panorama: mActivity.getPanoramaViewHelper() .showPanorama(mCurrentPhoto.getContentUri()); return; case R.id.photopage_bottom_control_tiny_planet: launchTinyPlanet(); return; default: return; } } @TargetApi(ApiHelper.VERSION_CODES.JELLY_BEAN) private void setupNfcBeamPush() { if (!ApiHelper.HAS_SET_BEAM_PUSH_URIS) return; NfcAdapter adapter = NfcAdapter.getDefaultAdapter(mActivity); if (adapter != null) { adapter.setBeamPushUris(null, mActivity); adapter.setBeamPushUrisCallback(new CreateBeamUrisCallback() { @Override public Uri[] createBeamUris(NfcEvent event) { return mNfcPushUris; } }, mActivity); } } private void setNfcBeamPushUri(Uri uri) { mNfcPushUris[0] = uri; } private static Intent createShareIntent(MediaObject mediaObject) { int type = mediaObject.getMediaType(); return new Intent(Intent.ACTION_SEND) .setType(MenuExecutor.getMimeType(type)) .putExtra(Intent.EXTRA_STREAM, mediaObject.getContentUri()) .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); } private static Intent createSharePanoramaIntent(Uri contentUri) { return new Intent(Intent.ACTION_SEND) .setType(GalleryUtils.MIME_TYPE_PANORAMA360) .putExtra(Intent.EXTRA_STREAM, contentUri) .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); } private void overrideTransitionToEditor() { ((Activity) mActivity).overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.fade_out); } private void launchTinyPlanet() { // Deep link into tiny planet MediaItem current = mModel.getMediaItem(0); Intent intent = new Intent(FilterShowActivity.TINY_PLANET_ACTION); intent.setClass(mActivity, FilterShowActivity.class); intent.setDataAndType(current.getContentUri(), current.getMimeType()) .setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); intent.putExtra(FilterShowActivity.LAUNCH_FULLSCREEN, mActivity.isFullscreen()); mActivity.startActivityForResult(intent, REQUEST_EDIT); overrideTransitionToEditor(); } private void launchCamera() { Intent intent = new Intent(mActivity, CameraActivity.class) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); mRecenterCameraOnResume = false; mActivity.startActivity(intent); } private void launchPhotoEditor() { MediaItem current = mModel.getMediaItem(0); if (current == null || (current.getSupportedOperations() & MediaObject.SUPPORT_EDIT) == 0) { return; } Intent intent = new Intent(ACTION_NEXTGEN_EDIT); intent.setDataAndType(current.getContentUri(), current.getMimeType()) .setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); if (mActivity.getPackageManager() .queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY).size() == 0) { intent.setAction(Intent.ACTION_EDIT); } intent.putExtra(FilterShowActivity.LAUNCH_FULLSCREEN, mActivity.isFullscreen()); ((Activity) mActivity).startActivityForResult(Intent.createChooser(intent, null), REQUEST_EDIT); overrideTransitionToEditor(); } private void requestDeferredUpdate() { mDeferUpdateUntil = SystemClock.uptimeMillis() + DEFERRED_UPDATE_MS; if (!mDeferredUpdateWaiting) { mDeferredUpdateWaiting = true; mHandler.sendEmptyMessageDelayed(MSG_UPDATE_DEFERRED, DEFERRED_UPDATE_MS); } } private void updateUIForCurrentPhoto() { if (mCurrentPhoto == null) return; // If by swiping or deletion the user ends up on an action item // and zoomed in, zoom out so that the context of the action is // more clear if ((mCurrentPhoto.getSupportedOperations() & MediaObject.SUPPORT_ACTION) != 0 && !mPhotoView.getFilmMode()) { mPhotoView.setWantPictureCenterCallbacks(true); } updateMenuOperations(); refreshBottomControlsWhenReady(); if (mShowDetails) { mDetailsHelper.reloadDetails(); } if ((mSecureAlbum == null) && (mCurrentPhoto.getSupportedOperations() & MediaItem.SUPPORT_SHARE) != 0) { mCurrentPhoto.getPanoramaSupport(mUpdateShareURICallback); } updateProgressBar(); } private void updateCurrentPhoto(MediaItem photo) { if (mCurrentPhoto == photo) return; mCurrentPhoto = photo; if (mPhotoView.getFilmMode()) { requestDeferredUpdate(); } else { updateUIForCurrentPhoto(); } } private void updateProgressBar() { if (mProgressBar != null) { mProgressBar.hideProgress(); StitchingProgressManager progressManager = mApplication.getStitchingProgressManager(); if (progressManager != null && mCurrentPhoto instanceof LocalImage) { Integer progress = progressManager.getProgress(mCurrentPhoto.getContentUri()); if (progress != null) { mProgressBar.setProgress(progress); } } } } private void updateMenuOperations() { Menu menu = mActionBar.getMenu(); // it could be null if onCreateActionBar has not been called yet if (menu == null) return; MenuItem item = menu.findItem(R.id.action_slideshow); if (item != null) { item.setVisible((mSecureAlbum == null) && canDoSlideShow()); } if (mCurrentPhoto == null) return; int supportedOperations = mCurrentPhoto.getSupportedOperations(); if (mSecureAlbum != null) { supportedOperations &= MediaObject.SUPPORT_DELETE; } else if (!mHaveImageEditor) { supportedOperations &= ~MediaObject.SUPPORT_EDIT; } MenuExecutor.updateMenuOperation(menu, supportedOperations); mCurrentPhoto.getPanoramaSupport(mUpdatePanoramaMenuItemsCallback); } private boolean canDoSlideShow() { if (mMediaSet == null || mCurrentPhoto == null) { return false; } if (mCurrentPhoto.getMediaType() != MediaObject.MEDIA_TYPE_IMAGE) { return false; } if (MtpSource.isMtpPath(mOriginalSetPathString)) { return false; } return true; } ////////////////////////////////////////////////////////////////////////// // Action Bar show/hide management ////////////////////////////////////////////////////////////////////////// private void showBars() { if (mShowBars) return; mShowBars = true; mOrientationManager.unlockOrientation(); mActionBar.show(); mActivity.getGLRoot().setLightsOutMode(false); refreshHidingMessage(); refreshBottomControlsWhenReady(); } private void hideBars() { if (!mShowBars) return; mShowBars = false; mActionBar.hide(); mActivity.getGLRoot().setLightsOutMode(true); mHandler.removeMessages(MSG_HIDE_BARS); refreshBottomControlsWhenReady(); } private void refreshHidingMessage() { mHandler.removeMessages(MSG_HIDE_BARS); if (!mIsMenuVisible && !mPhotoView.getFilmMode()) { mHandler.sendEmptyMessageDelayed(MSG_HIDE_BARS, HIDE_BARS_TIMEOUT); } } private boolean canShowBars() { // No bars if we are showing camera preview. if (mAppBridge != null && mCurrentIndex == 0 && !mPhotoView.getFilmMode()) return false; // No bars if it's not allowed. if (!mActionBarAllowed) return false; return true; } private void wantBars() { if (canShowBars()) showBars(); } private void toggleBars() { if (mShowBars) { hideBars(); } else { if (canShowBars()) showBars(); } } private void updateBars() { if (!canShowBars()) { hideBars(); } } @Override protected void onBackPressed() { if (mShowDetails) { hideDetails(); } else if (mAppBridge == null || !switchWithCaptureAnimation(-1)) { // We are leaving this page. Set the result now. setResult(); if (mStartInFilmstrip && !mPhotoView.getFilmMode()) { mPhotoView.setFilmMode(true); } else if (mTreatBackAsUp) { onUpPressed(); } else { super.onBackPressed(); } } } private void onUpPressed() { if ((mStartInFilmstrip || mAppBridge != null) && !mPhotoView.getFilmMode()) { mPhotoView.setFilmMode(true); return; } if (mActivity.getStateManager().getStateCount() > 1) { setResult(); super.onBackPressed(); return; } if (mOriginalSetPathString == null) return; if (mAppBridge == null) { // We're in view mode so set up the stacks on our own. Bundle data = new Bundle(getData()); data.putString(AlbumPage.KEY_MEDIA_PATH, mOriginalSetPathString); data.putString(AlbumPage.KEY_PARENT_MEDIA_PATH, mActivity.getDataManager().getTopSetPath( DataManager.INCLUDE_ALL)); mActivity.getStateManager().switchState(this, AlbumPage.class, data); } else { GalleryUtils.startGalleryActivity(mActivity); } } private void setResult() { Intent result = null; result = new Intent(); result.putExtra(KEY_RETURN_INDEX_HINT, mCurrentIndex); setStateResult(Activity.RESULT_OK, result); } ////////////////////////////////////////////////////////////////////////// // AppBridge.Server interface ////////////////////////////////////////////////////////////////////////// @Override public void setCameraRelativeFrame(Rect frame) { mPhotoView.setCameraRelativeFrame(frame); } @Override public boolean switchWithCaptureAnimation(int offset) { return mPhotoView.switchWithCaptureAnimation(offset); } @Override public void setSwipingEnabled(boolean enabled) { mPhotoView.setSwipingEnabled(enabled); } @Override public void notifyScreenNailChanged() { mScreenNailItem.setScreenNail(mAppBridge.attachScreenNail()); mScreenNailSet.notifyChange(); } @Override public void addSecureAlbumItem(boolean isVideo, int id) { mSecureAlbum.addMediaItem(isVideo, id); } @Override protected boolean onCreateActionBar(Menu menu) { mActionBar.createActionBarMenu(R.menu.photo, menu); mHaveImageEditor = GalleryUtils.isEditorAvailable(mActivity, "image/*"); updateMenuOperations(); mActionBar.setTitle(mMediaSet != null ? mMediaSet.getName() : ""); return true; } private MenuExecutor.ProgressListener mConfirmDialogListener = new MenuExecutor.ProgressListener() { @Override public void onProgressUpdate(int index) {} @Override public void onProgressComplete(int result) {} @Override public void onConfirmDialogShown() { mHandler.removeMessages(MSG_HIDE_BARS); } @Override public void onConfirmDialogDismissed(boolean confirmed) { refreshHidingMessage(); } @Override public void onProgressStart() {} }; private void switchToGrid() { if (mActivity.getStateManager().hasStateClass(AlbumPage.class)) { onUpPressed(); } else { if (mOriginalSetPathString == null) return; if (mProgressBar != null) { updateCurrentPhoto(null); mProgressBar.hideProgress(); } Bundle data = new Bundle(getData()); data.putString(AlbumPage.KEY_MEDIA_PATH, mOriginalSetPathString); data.putString(AlbumPage.KEY_PARENT_MEDIA_PATH, mActivity.getDataManager().getTopSetPath( DataManager.INCLUDE_ALL)); // We only show cluster menu in the first AlbumPage in stack // TODO: Enable this when running from the camera app boolean inAlbum = mActivity.getStateManager().hasStateClass(AlbumPage.class); data.putBoolean(AlbumPage.KEY_SHOW_CLUSTER_MENU, !inAlbum && mAppBridge == null); data.putBoolean(PhotoPage.KEY_APP_BRIDGE, mAppBridge != null); // Account for live preview being first item mActivity.getTransitionStore().put(KEY_RETURN_INDEX_HINT, mAppBridge != null ? mCurrentIndex - 1 : mCurrentIndex); if (mHasCameraScreennailOrPlaceholder && mAppBridge != null) { mActivity.getStateManager().startState(AlbumPage.class, data); } else { mActivity.getStateManager().switchState(this, AlbumPage.class, data); } } } @Override protected boolean onItemSelected(MenuItem item) { if (mModel == null) return true; refreshHidingMessage(); MediaItem current = mModel.getMediaItem(0); if (current == null) { // item is not ready, ignore return true; } int currentIndex = mModel.getCurrentIndex(); Path path = current.getPath(); DataManager manager = mActivity.getDataManager(); int action = item.getItemId(); String confirmMsg = null; switch (action) { case android.R.id.home: { onUpPressed(); return true; } case R.id.action_slideshow: { Bundle data = new Bundle(); data.putString(SlideshowPage.KEY_SET_PATH, mMediaSet.getPath().toString()); data.putString(SlideshowPage.KEY_ITEM_PATH, path.toString()); data.putInt(SlideshowPage.KEY_PHOTO_INDEX, currentIndex); data.putBoolean(SlideshowPage.KEY_REPEAT, true); mActivity.getStateManager().startStateForResult( SlideshowPage.class, REQUEST_SLIDESHOW, data); return true; } case R.id.action_crop: { Activity activity = mActivity; Intent intent = new Intent(FilterShowActivity.CROP_ACTION); intent.setClass(activity, FilterShowActivity.class); intent.setDataAndType(manager.getContentUri(path), current.getMimeType()) .setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); activity.startActivityForResult(intent, PicasaSource.isPicasaImage(current) ? REQUEST_CROP_PICASA : REQUEST_CROP); return true; } case R.id.action_trim: { Intent intent = new Intent(mActivity, TrimVideo.class); intent.setData(manager.getContentUri(path)); // We need the file path to wrap this into a RandomAccessFile. intent.putExtra(KEY_MEDIA_ITEM_PATH, current.getFilePath()); mActivity.startActivityForResult(intent, REQUEST_TRIM); return true; } case R.id.action_edit: { launchPhotoEditor(); return true; } case R.id.action_details: { if (mShowDetails) { hideDetails(); } else { showDetails(); } return true; } case R.id.action_delete: confirmMsg = mActivity.getResources().getQuantityString( R.plurals.delete_selection, 1); case R.id.action_setas: case R.id.action_rotate_ccw: case R.id.action_rotate_cw: case R.id.action_show_on_map: mSelectionManager.deSelectAll(); mSelectionManager.toggle(path); mMenuExecutor.onMenuClicked(item, confirmMsg, mConfirmDialogListener); return true; case R.id.action_import: mSelectionManager.deSelectAll(); mSelectionManager.toggle(path); mMenuExecutor.onMenuClicked(item, confirmMsg, new ImportCompleteListener(mActivity)); return true; default : return false; } } private void hideDetails() { mShowDetails = false; mDetailsHelper.hide(); } private void showDetails() { mShowDetails = true; if (mDetailsHelper == null) { mDetailsHelper = new DetailsHelper(mActivity, mRootPane, new MyDetailsSource()); mDetailsHelper.setCloseListener(new CloseListener() { @Override public void onClose() { hideDetails(); } }); } mDetailsHelper.show(); } //////////////////////////////////////////////////////////////////////////// // Callbacks from PhotoView //////////////////////////////////////////////////////////////////////////// @Override public void onSingleTapUp(int x, int y) { if (mAppBridge != null) { if (mAppBridge.onSingleTapUp(x, y)) return; } MediaItem item = mModel.getMediaItem(0); if (item == null || item == mScreenNailItem) { // item is not ready or it is camera preview, ignore return; } int supported = item.getSupportedOperations(); boolean playVideo = ((supported & MediaItem.SUPPORT_PLAY) != 0); boolean unlock = ((supported & MediaItem.SUPPORT_UNLOCK) != 0); boolean goBack = ((supported & MediaItem.SUPPORT_BACK) != 0); boolean launchCamera = ((supported & MediaItem.SUPPORT_CAMERA_SHORTCUT) != 0); if (playVideo) { // determine if the point is at center (1/6) of the photo view. // (The position of the "play" icon is at center (1/6) of the photo) int w = mPhotoView.getWidth(); int h = mPhotoView.getHeight(); playVideo = (Math.abs(x - w / 2) * 12 <= w) && (Math.abs(y - h / 2) * 12 <= h); } if (playVideo) { if (mSecureAlbum == null) { playVideo(mActivity, item.getPlayUri(), item.getName()); } else { mActivity.getStateManager().finishState(this); } } else if (goBack) { onBackPressed(); } else if (unlock) { Intent intent = new Intent(mActivity, Gallery.class); intent.putExtra(Gallery.KEY_DISMISS_KEYGUARD, true); mActivity.startActivity(intent); } else if (launchCamera) { launchCamera(); } else { toggleBars(); } } @Override public void onActionBarAllowed(boolean allowed) { mActionBarAllowed = allowed; mHandler.sendEmptyMessage(MSG_UPDATE_ACTION_BAR); } @Override public void onActionBarWanted() { mHandler.sendEmptyMessage(MSG_WANT_BARS); } @Override public void onFullScreenChanged(boolean full) { Message m = mHandler.obtainMessage( MSG_ON_FULL_SCREEN_CHANGED, full ? 1 : 0, 0); m.sendToTarget(); } // How we do delete/undo: // // When the user choose to delete a media item, we just tell the // FilterDeleteSet to hide that item. If the user choose to undo it, we // again tell FilterDeleteSet not to hide it. If the user choose to commit // the deletion, we then actually delete the media item. @Override public void onDeleteImage(Path path, int offset) { onCommitDeleteImage(); // commit the previous deletion mDeletePath = path; mDeleteIsFocus = (offset == 0); mMediaSet.addDeletion(path, mCurrentIndex + offset); } @Override public void onUndoDeleteImage() { if (mDeletePath == null) return; // If the deletion was done on the focused item, we want the model to // focus on it when it is undeleted. if (mDeleteIsFocus) mModel.setFocusHintPath(mDeletePath); mMediaSet.removeDeletion(mDeletePath); mDeletePath = null; } @Override public void onCommitDeleteImage() { if (mDeletePath == null) return; mSelectionManager.deSelectAll(); mSelectionManager.toggle(mDeletePath); mMenuExecutor.onMenuClicked(R.id.action_delete, null, true, false); mDeletePath = null; } public void playVideo(Activity activity, Uri uri, String title) { try { Intent intent = new Intent(Intent.ACTION_VIEW) .setDataAndType(uri, "video/*") .putExtra(Intent.EXTRA_TITLE, title) .putExtra(MovieActivity.KEY_TREAT_UP_AS_BACK, true); activity.startActivityForResult(intent, REQUEST_PLAY_VIDEO); } catch (ActivityNotFoundException e) { Toast.makeText(activity, activity.getString(R.string.video_err), Toast.LENGTH_SHORT).show(); } } private void setCurrentPhotoByIntent(Intent intent) { if (intent == null) return; Path path = mApplication.getDataManager() .findPathByUri(intent.getData(), intent.getType()); if (path != null) { Path albumPath = mApplication.getDataManager().getDefaultSetOf(path); if (!albumPath.equalsIgnoreCase(mOriginalSetPathString)) { // If the edited image is stored in a different album, we need // to start a new activity state to show the new image Bundle data = new Bundle(getData()); data.putString(KEY_MEDIA_SET_PATH, albumPath.toString()); data.putString(PhotoPage.KEY_MEDIA_ITEM_PATH, path.toString()); mActivity.getStateManager().startState(PhotoPage.class, data); return; } mModel.setCurrentPhoto(path, mCurrentIndex); } } @Override protected void onStateResult(int requestCode, int resultCode, Intent data) { if (resultCode == Activity.RESULT_CANCELED) { // This is a reset, not a canceled return; } if (resultCode == ProxyLauncher.RESULT_USER_CANCELED) { // Unmap reset vs. canceled resultCode = Activity.RESULT_CANCELED; } mRecenterCameraOnResume = false; switch (requestCode) { case REQUEST_EDIT: setCurrentPhotoByIntent(data); break; case REQUEST_CROP: if (resultCode == Activity.RESULT_OK) { setCurrentPhotoByIntent(data); } break; case REQUEST_CROP_PICASA: { if (resultCode == Activity.RESULT_OK) { Context context = mActivity.getAndroidContext(); String message = context.getString(R.string.crop_saved, context.getString(R.string.folder_edited_online_photos)); Toast.makeText(context, message, Toast.LENGTH_SHORT).show(); } break; } case REQUEST_SLIDESHOW: { if (data == null) break; String path = data.getStringExtra(SlideshowPage.KEY_ITEM_PATH); int index = data.getIntExtra(SlideshowPage.KEY_PHOTO_INDEX, 0); if (path != null) { mModel.setCurrentPhoto(Path.fromString(path), index); } } } } @Override public void onPause() { super.onPause(); mIsActive = false; mActivity.getGLRoot().unfreeze(); mHandler.removeMessages(MSG_UNFREEZE_GLROOT); DetailsHelper.pause(); // Hide the detail dialog on exit if (mShowDetails) hideDetails(); if (mModel != null) { mModel.pause(); } mPhotoView.pause(); mHandler.removeMessages(MSG_HIDE_BARS); mHandler.removeMessages(MSG_REFRESH_BOTTOM_CONTROLS); refreshBottomControlsWhenReady(); mActionBar.removeOnMenuVisibilityListener(mMenuVisibilityListener); if (mShowSpinner) { mActionBar.disableAlbumModeMenu(true); } onCommitDeleteImage(); mMenuExecutor.pause(); if (mMediaSet != null) mMediaSet.clearDeletion(); } @Override public void onCurrentImageUpdated() { mActivity.getGLRoot().unfreeze(); } @Override public void onFilmModeChanged(boolean enabled) { refreshBottomControlsWhenReady(); if (mShowSpinner) { if (enabled) { mActionBar.enableAlbumModeMenu( GalleryActionBar.ALBUM_FILMSTRIP_MODE_SELECTED, this); } else { mActionBar.disableAlbumModeMenu(true); } } if (enabled) { mHandler.removeMessages(MSG_HIDE_BARS); } else { refreshHidingMessage(); } } private void transitionFromAlbumPageIfNeeded() { TransitionStore transitions = mActivity.getTransitionStore(); int albumPageTransition = transitions.get( KEY_ALBUMPAGE_TRANSITION, MSG_ALBUMPAGE_NONE); if (albumPageTransition == MSG_ALBUMPAGE_NONE && mAppBridge != null && mRecenterCameraOnResume) { // Generally, resuming the PhotoPage when in Camera should // reset to the capture mode to allow quick photo taking mCurrentIndex = 0; mPhotoView.resetToFirstPicture(); } else { int resumeIndex = transitions.get(KEY_INDEX_HINT, -1); if (resumeIndex >= 0) { if (mHasCameraScreennailOrPlaceholder) { // Account for preview/placeholder being the first item resumeIndex++; } if (resumeIndex < mMediaSet.getMediaItemCount()) { mCurrentIndex = resumeIndex; mModel.moveTo(mCurrentIndex); } } } if (albumPageTransition == MSG_ALBUMPAGE_RESUMED) { mPhotoView.setFilmMode(mStartInFilmstrip || mAppBridge != null); } else if (albumPageTransition == MSG_ALBUMPAGE_PICKED) { mPhotoView.setFilmMode(false); } } @Override protected void onResume() { super.onResume(); if (mModel == null) { mActivity.getStateManager().finishState(this); return; } transitionFromAlbumPageIfNeeded(); mActivity.getGLRoot().freeze(); mIsActive = true; setContentPane(mRootPane); mModel.resume(); mPhotoView.resume(); mActionBar.setDisplayOptions( ((mSecureAlbum == null) && (mSetPathString != null)), false); mActionBar.addOnMenuVisibilityListener(mMenuVisibilityListener); refreshBottomControlsWhenReady(); if (mShowSpinner && mPhotoView.getFilmMode()) { mActionBar.enableAlbumModeMenu( GalleryActionBar.ALBUM_FILMSTRIP_MODE_SELECTED, this); } if (!mShowBars) { mActionBar.hide(); mActivity.getGLRoot().setLightsOutMode(true); } boolean haveImageEditor = GalleryUtils.isEditorAvailable(mActivity, "image/*"); if (haveImageEditor != mHaveImageEditor) { mHaveImageEditor = haveImageEditor; updateMenuOperations(); } mRecenterCameraOnResume = true; mHandler.sendEmptyMessageDelayed(MSG_UNFREEZE_GLROOT, UNFREEZE_GLROOT_TIMEOUT); } @Override protected void onDestroy() { if (mAppBridge != null) { mAppBridge.setServer(null); mScreenNailItem.setScreenNail(null); mAppBridge.detachScreenNail(); mAppBridge = null; mScreenNailSet = null; mScreenNailItem = null; } mActivity.getGLRoot().setOrientationSource(null); if (mBottomControls != null) mBottomControls.cleanup(); // Remove all pending messages. mHandler.removeCallbacksAndMessages(null); super.onDestroy(); } private class MyDetailsSource implements DetailsSource { @Override public MediaDetails getDetails() { return mModel.getMediaItem(0).getDetails(); } @Override public int size() { return mMediaSet != null ? mMediaSet.getMediaItemCount() : 1; } @Override public int setIndex() { return mModel.getCurrentIndex(); } } @Override public void onAlbumModeSelected(int mode) { if (mode == GalleryActionBar.ALBUM_GRID_MODE_SELECTED) { switchToGrid(); } } @Override public void refreshBottomControlsWhenReady() { if (mBottomControls == null) { return; } MediaObject currentPhoto = mCurrentPhoto; if (currentPhoto == null) { mHandler.obtainMessage(MSG_REFRESH_BOTTOM_CONTROLS, 0, 0, currentPhoto).sendToTarget(); } else { currentPhoto.getPanoramaSupport(mRefreshBottomControlsCallback); } } private void updatePanoramaUI(boolean isPanorama360) { Menu menu = mActionBar.getMenu(); // it could be null if onCreateActionBar has not been called yet if (menu == null) { return; } MenuExecutor.updateMenuForPanorama(menu, isPanorama360, isPanorama360); if (isPanorama360) { MenuItem item = menu.findItem(R.id.action_share); if (item != null) { item.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER); item.setTitle(mActivity.getResources().getString(R.string.share_as_photo)); } } else if ((mCurrentPhoto.getSupportedOperations() & MediaObject.SUPPORT_SHARE) != 0) { MenuItem item = menu.findItem(R.id.action_share); if (item != null) { item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM); item.setTitle(mActivity.getResources().getString(R.string.share)); } } } @Override public void onUndoBarVisibilityChanged(boolean visible) { refreshBottomControlsWhenReady(); } }
true
true
public void onCreate(Bundle data, Bundle restoreState) { super.onCreate(data, restoreState); mActionBar = mActivity.getGalleryActionBar(); mSelectionManager = new SelectionManager(mActivity, false); mMenuExecutor = new MenuExecutor(mActivity, mSelectionManager); mPhotoView = new PhotoView(mActivity); mPhotoView.setListener(this); mRootPane.addComponent(mPhotoView); mApplication = (GalleryApp) ((Activity) mActivity).getApplication(); mOrientationManager = mActivity.getOrientationManager(); mActivity.getGLRoot().setOrientationSource(mOrientationManager); mHandler = new SynchronizedHandler(mActivity.getGLRoot()) { @Override public void handleMessage(Message message) { switch (message.what) { case MSG_HIDE_BARS: { hideBars(); break; } case MSG_REFRESH_BOTTOM_CONTROLS: { if (mCurrentPhoto == message.obj && mBottomControls != null) { mIsPanorama = message.arg1 == 1; mIsPanorama360 = message.arg2 == 1; mBottomControls.refresh(); } break; } case MSG_ON_FULL_SCREEN_CHANGED: { mAppBridge.onFullScreenChanged(message.arg1 == 1); break; } case MSG_UPDATE_ACTION_BAR: { updateBars(); break; } case MSG_WANT_BARS: { wantBars(); break; } case MSG_UNFREEZE_GLROOT: { mActivity.getGLRoot().unfreeze(); break; } case MSG_UPDATE_DEFERRED: { long nextUpdate = mDeferUpdateUntil - SystemClock.uptimeMillis(); if (nextUpdate <= 0) { mDeferredUpdateWaiting = false; updateUIForCurrentPhoto(); } else { mHandler.sendEmptyMessageDelayed(MSG_UPDATE_DEFERRED, nextUpdate); } break; } case MSG_ON_CAMERA_CENTER: { mSkipUpdateCurrentPhoto = false; boolean stayedOnCamera = false; if (!mPhotoView.getFilmMode()) { stayedOnCamera = true; } else if (SystemClock.uptimeMillis() < mCameraSwitchCutoff && mMediaSet.getMediaItemCount() > 1) { mPhotoView.switchToImage(1); } else { if (mAppBridge != null) mPhotoView.setFilmMode(false); stayedOnCamera = true; } if (stayedOnCamera) { if (mAppBridge == null) { launchCamera(); /* We got here by swiping from photo 1 to the placeholder, so make it be the thing that is in focus when the user presses back from the camera app */ mPhotoView.switchToImage(1); } else { updateBars(); updateCurrentPhoto(mModel.getMediaItem(0)); } } break; } case MSG_ON_PICTURE_CENTER: { if (!mPhotoView.getFilmMode() && mCurrentPhoto != null && (mCurrentPhoto.getSupportedOperations() & MediaObject.SUPPORT_ACTION) != 0) { mPhotoView.setFilmMode(true); } break; } case MSG_REFRESH_IMAGE: { final MediaItem photo = mCurrentPhoto; mCurrentPhoto = null; updateCurrentPhoto(photo); break; } case MSG_UPDATE_PHOTO_UI: { updateUIForCurrentPhoto(); break; } case MSG_UPDATE_PROGRESS: { updateProgressBar(); break; } case MSG_UPDATE_SHARE_URI: { if (mCurrentPhoto == message.obj) { boolean isPanorama360 = message.arg1 != 0; Uri contentUri = mCurrentPhoto.getContentUri(); Intent panoramaIntent = null; if (isPanorama360) { panoramaIntent = createSharePanoramaIntent(contentUri); } Intent shareIntent = createShareIntent(mCurrentPhoto); mActionBar.setShareIntents(panoramaIntent, shareIntent); setNfcBeamPushUri(contentUri); } break; } case MSG_UPDATE_PANORAMA_UI: { if (mCurrentPhoto == message.obj) { boolean isPanorama360 = message.arg1 != 0; updatePanoramaUI(isPanorama360); } break; } default: throw new AssertionError(message.what); } } }; mSetPathString = data.getString(KEY_MEDIA_SET_PATH); mOriginalSetPathString = mSetPathString; setupNfcBeamPush(); String itemPathString = data.getString(KEY_MEDIA_ITEM_PATH); Path itemPath = itemPathString != null ? Path.fromString(data.getString(KEY_MEDIA_ITEM_PATH)) : null; mTreatBackAsUp = data.getBoolean(KEY_TREAT_BACK_AS_UP, false); mStartInFilmstrip = data.getBoolean(KEY_START_IN_FILMSTRIP, false); boolean inCameraRoll = data.getBoolean(KEY_IN_CAMERA_ROLL, false); mCurrentIndex = data.getInt(KEY_INDEX_HINT, 0); if (mSetPathString != null) { mShowSpinner = true; mAppBridge = (AppBridge) data.getParcelable(KEY_APP_BRIDGE); if (mAppBridge != null) { mShowBars = false; mHasCameraScreennailOrPlaceholder = true; mAppBridge.setServer(this); // Get the ScreenNail from AppBridge and register it. int id = SnailSource.newId(); Path screenNailSetPath = SnailSource.getSetPath(id); Path screenNailItemPath = SnailSource.getItemPath(id); mScreenNailSet = (SnailAlbum) mActivity.getDataManager() .getMediaObject(screenNailSetPath); mScreenNailItem = (SnailItem) mActivity.getDataManager() .getMediaObject(screenNailItemPath); mScreenNailItem.setScreenNail(mAppBridge.attachScreenNail()); if (data.getBoolean(KEY_SHOW_WHEN_LOCKED, false)) { // Set the flag to be on top of the lock screen. mFlags |= FLAG_SHOW_WHEN_LOCKED; } // Don't display "empty album" action item for capture intents. if (!mSetPathString.equals("/local/all/0")) { // Check if the path is a secure album. if (SecureSource.isSecurePath(mSetPathString)) { mSecureAlbum = (SecureAlbum) mActivity.getDataManager() .getMediaSet(mSetPathString); mShowSpinner = false; } mSetPathString = "/filter/empty/{"+mSetPathString+"}"; } // Combine the original MediaSet with the one for ScreenNail // from AppBridge. mSetPathString = "/combo/item/{" + screenNailSetPath + "," + mSetPathString + "}"; // Start from the screen nail. itemPath = screenNailItemPath; } else if (inCameraRoll && GalleryUtils.isCameraAvailable(mActivity)) { mSetPathString = "/combo/item/{" + FilterSource.FILTER_CAMERA_SHORTCUT + "," + mSetPathString + "}"; mCurrentIndex++; mHasCameraScreennailOrPlaceholder = true; } MediaSet originalSet = mActivity.getDataManager() .getMediaSet(mSetPathString); if (mHasCameraScreennailOrPlaceholder && originalSet instanceof ComboAlbum) { // Use the name of the camera album rather than the default // ComboAlbum behavior ((ComboAlbum) originalSet).useNameOfChild(1); } mSelectionManager.setSourceMediaSet(originalSet); mSetPathString = "/filter/delete/{" + mSetPathString + "}"; mMediaSet = (FilterDeleteSet) mActivity.getDataManager() .getMediaSet(mSetPathString); if (mMediaSet == null) { Log.w(TAG, "failed to restore " + mSetPathString); } if (itemPath == null) { int mediaItemCount = mMediaSet.getMediaItemCount(); if (mediaItemCount > 0) { if (mCurrentIndex >= mediaItemCount) mCurrentIndex = 0; itemPath = mMediaSet.getMediaItem(mCurrentIndex, 1) .get(0).getPath(); } else { // Bail out, PhotoPage can't load on an empty album return; } } PhotoDataAdapter pda = new PhotoDataAdapter( mActivity, mPhotoView, mMediaSet, itemPath, mCurrentIndex, mAppBridge == null ? -1 : 0, mAppBridge == null ? false : mAppBridge.isPanorama(), mAppBridge == null ? false : mAppBridge.isStaticCamera()); mModel = pda; mPhotoView.setModel(mModel); pda.setDataListener(new PhotoDataAdapter.DataListener() { @Override public void onPhotoChanged(int index, Path item) { int oldIndex = mCurrentIndex; mCurrentIndex = index; if (mHasCameraScreennailOrPlaceholder) { if (mCurrentIndex > 0) { mSkipUpdateCurrentPhoto = false; } if (oldIndex == 0 && mCurrentIndex > 0 && !mPhotoView.getFilmMode()) { mPhotoView.setFilmMode(true); } else if (oldIndex == 2 && mCurrentIndex == 1) { mCameraSwitchCutoff = SystemClock.uptimeMillis() + CAMERA_SWITCH_CUTOFF_THRESHOLD_MS; mPhotoView.stopScrolling(); } else if (oldIndex >= 1 && mCurrentIndex == 0) { mPhotoView.setWantPictureCenterCallbacks(true); mSkipUpdateCurrentPhoto = true; } } if (!mSkipUpdateCurrentPhoto) { if (item != null) { MediaItem photo = mModel.getMediaItem(0); if (photo != null) updateCurrentPhoto(photo); } updateBars(); } // Reset the timeout for the bars after a swipe refreshHidingMessage(); } @Override public void onLoadingFinished(boolean loadingFailed) { if (!mModel.isEmpty()) { MediaItem photo = mModel.getMediaItem(0); if (photo != null) updateCurrentPhoto(photo); } else if (mIsActive) { // We only want to finish the PhotoPage if there is no // deletion that the user can undo. if (mMediaSet.getNumberOfDeletions() == 0) { mActivity.getStateManager().finishState( PhotoPage.this); } } } @Override public void onLoadingStarted() { } }); } else { // Get default media set by the URI MediaItem mediaItem = (MediaItem) mActivity.getDataManager().getMediaObject(itemPath); mModel = new SinglePhotoDataAdapter(mActivity, mPhotoView, mediaItem); mPhotoView.setModel(mModel); updateCurrentPhoto(mediaItem); mShowSpinner = false; } mPhotoView.setFilmMode(mStartInFilmstrip && mMediaSet.getMediaItemCount() > 1); RelativeLayout galleryRoot = (RelativeLayout) ((Activity) mActivity) .findViewById(mAppBridge != null ? R.id.content : R.id.gallery_root); if (galleryRoot != null) { if (mSecureAlbum == null) { mBottomControls = new PhotoPageBottomControls(this, mActivity, galleryRoot); } StitchingProgressManager progressManager = mApplication.getStitchingProgressManager(); if (progressManager != null) { mProgressBar = new PhotoPageProgressBar(mActivity, galleryRoot); mProgressListener = new UpdateProgressListener(); progressManager.addChangeListener(mProgressListener); if (mSecureAlbum != null) { progressManager.addChangeListener(mSecureAlbum); } } } }
public void onCreate(Bundle data, Bundle restoreState) { super.onCreate(data, restoreState); mActionBar = mActivity.getGalleryActionBar(); mSelectionManager = new SelectionManager(mActivity, false); mMenuExecutor = new MenuExecutor(mActivity, mSelectionManager); mPhotoView = new PhotoView(mActivity); mPhotoView.setListener(this); mRootPane.addComponent(mPhotoView); mApplication = (GalleryApp) ((Activity) mActivity).getApplication(); mOrientationManager = mActivity.getOrientationManager(); mActivity.getGLRoot().setOrientationSource(mOrientationManager); mHandler = new SynchronizedHandler(mActivity.getGLRoot()) { @Override public void handleMessage(Message message) { switch (message.what) { case MSG_HIDE_BARS: { hideBars(); break; } case MSG_REFRESH_BOTTOM_CONTROLS: { if (mCurrentPhoto == message.obj && mBottomControls != null) { mIsPanorama = message.arg1 == 1; mIsPanorama360 = message.arg2 == 1; mBottomControls.refresh(); } break; } case MSG_ON_FULL_SCREEN_CHANGED: { if (mAppBridge != null) { mAppBridge.onFullScreenChanged(message.arg1 == 1); } break; } case MSG_UPDATE_ACTION_BAR: { updateBars(); break; } case MSG_WANT_BARS: { wantBars(); break; } case MSG_UNFREEZE_GLROOT: { mActivity.getGLRoot().unfreeze(); break; } case MSG_UPDATE_DEFERRED: { long nextUpdate = mDeferUpdateUntil - SystemClock.uptimeMillis(); if (nextUpdate <= 0) { mDeferredUpdateWaiting = false; updateUIForCurrentPhoto(); } else { mHandler.sendEmptyMessageDelayed(MSG_UPDATE_DEFERRED, nextUpdate); } break; } case MSG_ON_CAMERA_CENTER: { mSkipUpdateCurrentPhoto = false; boolean stayedOnCamera = false; if (!mPhotoView.getFilmMode()) { stayedOnCamera = true; } else if (SystemClock.uptimeMillis() < mCameraSwitchCutoff && mMediaSet.getMediaItemCount() > 1) { mPhotoView.switchToImage(1); } else { if (mAppBridge != null) mPhotoView.setFilmMode(false); stayedOnCamera = true; } if (stayedOnCamera) { if (mAppBridge == null) { launchCamera(); /* We got here by swiping from photo 1 to the placeholder, so make it be the thing that is in focus when the user presses back from the camera app */ mPhotoView.switchToImage(1); } else { updateBars(); updateCurrentPhoto(mModel.getMediaItem(0)); } } break; } case MSG_ON_PICTURE_CENTER: { if (!mPhotoView.getFilmMode() && mCurrentPhoto != null && (mCurrentPhoto.getSupportedOperations() & MediaObject.SUPPORT_ACTION) != 0) { mPhotoView.setFilmMode(true); } break; } case MSG_REFRESH_IMAGE: { final MediaItem photo = mCurrentPhoto; mCurrentPhoto = null; updateCurrentPhoto(photo); break; } case MSG_UPDATE_PHOTO_UI: { updateUIForCurrentPhoto(); break; } case MSG_UPDATE_PROGRESS: { updateProgressBar(); break; } case MSG_UPDATE_SHARE_URI: { if (mCurrentPhoto == message.obj) { boolean isPanorama360 = message.arg1 != 0; Uri contentUri = mCurrentPhoto.getContentUri(); Intent panoramaIntent = null; if (isPanorama360) { panoramaIntent = createSharePanoramaIntent(contentUri); } Intent shareIntent = createShareIntent(mCurrentPhoto); mActionBar.setShareIntents(panoramaIntent, shareIntent); setNfcBeamPushUri(contentUri); } break; } case MSG_UPDATE_PANORAMA_UI: { if (mCurrentPhoto == message.obj) { boolean isPanorama360 = message.arg1 != 0; updatePanoramaUI(isPanorama360); } break; } default: throw new AssertionError(message.what); } } }; mSetPathString = data.getString(KEY_MEDIA_SET_PATH); mOriginalSetPathString = mSetPathString; setupNfcBeamPush(); String itemPathString = data.getString(KEY_MEDIA_ITEM_PATH); Path itemPath = itemPathString != null ? Path.fromString(data.getString(KEY_MEDIA_ITEM_PATH)) : null; mTreatBackAsUp = data.getBoolean(KEY_TREAT_BACK_AS_UP, false); mStartInFilmstrip = data.getBoolean(KEY_START_IN_FILMSTRIP, false); boolean inCameraRoll = data.getBoolean(KEY_IN_CAMERA_ROLL, false); mCurrentIndex = data.getInt(KEY_INDEX_HINT, 0); if (mSetPathString != null) { mShowSpinner = true; mAppBridge = (AppBridge) data.getParcelable(KEY_APP_BRIDGE); if (mAppBridge != null) { mShowBars = false; mHasCameraScreennailOrPlaceholder = true; mAppBridge.setServer(this); // Get the ScreenNail from AppBridge and register it. int id = SnailSource.newId(); Path screenNailSetPath = SnailSource.getSetPath(id); Path screenNailItemPath = SnailSource.getItemPath(id); mScreenNailSet = (SnailAlbum) mActivity.getDataManager() .getMediaObject(screenNailSetPath); mScreenNailItem = (SnailItem) mActivity.getDataManager() .getMediaObject(screenNailItemPath); mScreenNailItem.setScreenNail(mAppBridge.attachScreenNail()); if (data.getBoolean(KEY_SHOW_WHEN_LOCKED, false)) { // Set the flag to be on top of the lock screen. mFlags |= FLAG_SHOW_WHEN_LOCKED; } // Don't display "empty album" action item for capture intents. if (!mSetPathString.equals("/local/all/0")) { // Check if the path is a secure album. if (SecureSource.isSecurePath(mSetPathString)) { mSecureAlbum = (SecureAlbum) mActivity.getDataManager() .getMediaSet(mSetPathString); mShowSpinner = false; } mSetPathString = "/filter/empty/{"+mSetPathString+"}"; } // Combine the original MediaSet with the one for ScreenNail // from AppBridge. mSetPathString = "/combo/item/{" + screenNailSetPath + "," + mSetPathString + "}"; // Start from the screen nail. itemPath = screenNailItemPath; } else if (inCameraRoll && GalleryUtils.isCameraAvailable(mActivity)) { mSetPathString = "/combo/item/{" + FilterSource.FILTER_CAMERA_SHORTCUT + "," + mSetPathString + "}"; mCurrentIndex++; mHasCameraScreennailOrPlaceholder = true; } MediaSet originalSet = mActivity.getDataManager() .getMediaSet(mSetPathString); if (mHasCameraScreennailOrPlaceholder && originalSet instanceof ComboAlbum) { // Use the name of the camera album rather than the default // ComboAlbum behavior ((ComboAlbum) originalSet).useNameOfChild(1); } mSelectionManager.setSourceMediaSet(originalSet); mSetPathString = "/filter/delete/{" + mSetPathString + "}"; mMediaSet = (FilterDeleteSet) mActivity.getDataManager() .getMediaSet(mSetPathString); if (mMediaSet == null) { Log.w(TAG, "failed to restore " + mSetPathString); } if (itemPath == null) { int mediaItemCount = mMediaSet.getMediaItemCount(); if (mediaItemCount > 0) { if (mCurrentIndex >= mediaItemCount) mCurrentIndex = 0; itemPath = mMediaSet.getMediaItem(mCurrentIndex, 1) .get(0).getPath(); } else { // Bail out, PhotoPage can't load on an empty album return; } } PhotoDataAdapter pda = new PhotoDataAdapter( mActivity, mPhotoView, mMediaSet, itemPath, mCurrentIndex, mAppBridge == null ? -1 : 0, mAppBridge == null ? false : mAppBridge.isPanorama(), mAppBridge == null ? false : mAppBridge.isStaticCamera()); mModel = pda; mPhotoView.setModel(mModel); pda.setDataListener(new PhotoDataAdapter.DataListener() { @Override public void onPhotoChanged(int index, Path item) { int oldIndex = mCurrentIndex; mCurrentIndex = index; if (mHasCameraScreennailOrPlaceholder) { if (mCurrentIndex > 0) { mSkipUpdateCurrentPhoto = false; } if (oldIndex == 0 && mCurrentIndex > 0 && !mPhotoView.getFilmMode()) { mPhotoView.setFilmMode(true); } else if (oldIndex == 2 && mCurrentIndex == 1) { mCameraSwitchCutoff = SystemClock.uptimeMillis() + CAMERA_SWITCH_CUTOFF_THRESHOLD_MS; mPhotoView.stopScrolling(); } else if (oldIndex >= 1 && mCurrentIndex == 0) { mPhotoView.setWantPictureCenterCallbacks(true); mSkipUpdateCurrentPhoto = true; } } if (!mSkipUpdateCurrentPhoto) { if (item != null) { MediaItem photo = mModel.getMediaItem(0); if (photo != null) updateCurrentPhoto(photo); } updateBars(); } // Reset the timeout for the bars after a swipe refreshHidingMessage(); } @Override public void onLoadingFinished(boolean loadingFailed) { if (!mModel.isEmpty()) { MediaItem photo = mModel.getMediaItem(0); if (photo != null) updateCurrentPhoto(photo); } else if (mIsActive) { // We only want to finish the PhotoPage if there is no // deletion that the user can undo. if (mMediaSet.getNumberOfDeletions() == 0) { mActivity.getStateManager().finishState( PhotoPage.this); } } } @Override public void onLoadingStarted() { } }); } else { // Get default media set by the URI MediaItem mediaItem = (MediaItem) mActivity.getDataManager().getMediaObject(itemPath); mModel = new SinglePhotoDataAdapter(mActivity, mPhotoView, mediaItem); mPhotoView.setModel(mModel); updateCurrentPhoto(mediaItem); mShowSpinner = false; } mPhotoView.setFilmMode(mStartInFilmstrip && mMediaSet.getMediaItemCount() > 1); RelativeLayout galleryRoot = (RelativeLayout) ((Activity) mActivity) .findViewById(mAppBridge != null ? R.id.content : R.id.gallery_root); if (galleryRoot != null) { if (mSecureAlbum == null) { mBottomControls = new PhotoPageBottomControls(this, mActivity, galleryRoot); } StitchingProgressManager progressManager = mApplication.getStitchingProgressManager(); if (progressManager != null) { mProgressBar = new PhotoPageProgressBar(mActivity, galleryRoot); mProgressListener = new UpdateProgressListener(); progressManager.addChangeListener(mProgressListener); if (mSecureAlbum != null) { progressManager.addChangeListener(mSecureAlbum); } } } }
diff --git a/src/master/src/org/drftpd/vfs/VirtualFileSystemDirectory.java b/src/master/src/org/drftpd/vfs/VirtualFileSystemDirectory.java index aa198ee0..4cd36904 100644 --- a/src/master/src/org/drftpd/vfs/VirtualFileSystemDirectory.java +++ b/src/master/src/org/drftpd/vfs/VirtualFileSystemDirectory.java @@ -1,310 +1,313 @@ /* * This file is part of DrFTPD, Distributed FTP Daemon. * * DrFTPD 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. * * DrFTPD 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 DrFTPD; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.drftpd.vfs; import java.beans.DefaultPersistenceDelegate; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.beans.XMLEncoder; import java.io.FileNotFoundException; import java.lang.ref.SoftReference; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Set; import java.util.TreeMap; import org.drftpd.exceptions.FileExistsException; /** * Lowest representation of a directory.<br> * This class deals directly w/ the actual VFS and should not be used * outside the of the VirtualFileSystem part. * @see org.drftpd.vfs.DirectoryHandle */ public class VirtualFileSystemDirectory extends VirtualFileSystemInode { protected static final Collection<String> transientListDirectory = Arrays .asList(new String[] { "name", "parent", "files"}); private transient TreeMap<String, SoftReference<VirtualFileSystemInode>> _files = null; protected long _size = 0; public VirtualFileSystemDirectory(String user, String group) { super(user, group); _files = new CaseInsensitiveTreeMap<String, SoftReference<VirtualFileSystemInode>>(); } /** * Add another inode to the directory tree. * @param inode */ protected synchronized void addChild(VirtualFileSystemInode inode) { _files.put(inode.getName(), new SoftReference<VirtualFileSystemInode>( inode)); if (getLastModified() < inode.getLastModified()) { setLastModified(inode.getLastModified()); } addSize(inode.getSize()); commit(); } protected synchronized void addSize(long l) { _size = getSize() + l; getParent().addSize(l); commit(); } /** * Create a directory inside the current Directory. * @param name * @param user * @param group * @throws FileExistsException if this directory already exists. */ public synchronized void createDirectory(String name, String user, String group) throws FileExistsException { if (_files.containsKey(name)) { throw new FileExistsException("An object named " + name + " already exists in " + getPath()); } VirtualFileSystemDirectory inode = createDirectoryRaw(name, user, group); getVFS().notifyInodeCreated(inode); } /** * Do not use this method unless you REALLY know what you're doing. This * method should only be used in two cases, in the createDirectory(string, * string, string) method of this class and in VirtualFileSystem.loadInode() * * @param name * @param user * @param group */ protected VirtualFileSystemDirectory createDirectoryRaw(String name, String user, String group) { VirtualFileSystemDirectory inode = new VirtualFileSystemDirectory(user, group); inode.setName(name); inode.setParent(this); inode.commit(); addChild(inode); logger.info("createDirectory(" + inode + ")"); return inode; } /** * Create a file inside the current directory. * @param name * @param user * @param group * @param initialSlave * @throws FileExistsException if this file already exists. */ public synchronized void createFile(String name, String user, String group, String initialSlave) throws FileExistsException { if (_files.containsKey(name)) { throw new FileExistsException(name + " already exists"); } VirtualFileSystemInode inode = new VirtualFileSystemFile(user, group, 0, initialSlave); inode.setName(name); inode.setParent(this); inode.commit(); addChild(inode); commit(); logger.info("createFile(" + inode + ")"); getVFS().notifyInodeCreated(inode); } /** * Create a link inside the current directory. * @param name * @param target * @param user * @param group * @throws FileExistsException if this link already exists. */ public synchronized void createLink(String name, String target, String user, String group) throws FileExistsException { if (_files.containsKey(name)) { throw new FileExistsException(name + " already exists"); } VirtualFileSystemInode inode = new VirtualFileSystemLink(user, group, target); inode.setName(name); inode.setParent(this); inode.commit(); addChild(inode); commit(); logger.info("createLink(" + inode + ")"); getVFS().notifyInodeCreated(inode); } /** * @return a Set containing all inode names inside this directory. */ public Set<String> getInodeNames() { return new HashSet<String>(_files.keySet()); } /** * @return a set containing all Inode objects inside this directory. */ public Set<InodeHandle> getInodes() { HashSet<InodeHandle> set = new HashSet<InodeHandle>(); String path = getPath() + (getPath().equals("/") ? "" : VirtualFileSystem.separator); // not dynamically called for efficiency for (String inodeName : new HashSet<String>(_files.keySet())) { VirtualFileSystemInode inode = null; try { inode = getInodeByName(inodeName); } catch (FileNotFoundException e) { logger.debug(path + inodeName + " is missing or was corrupted, stop deleting files outside of drftpd!", e); // This entry is already removed from the REAL _files Set, but we're iterating over a copy continue; } if (inode.isDirectory()) { set.add(new DirectoryHandle(path + inodeName)); } else if (inode.isFile()) { set.add(new FileHandle(path + inodeName)); } else if (inode.isLink()) { set.add(new LinkHandle(path + inodeName)); } } return set; } /** * @param name * @return VirtualFileSystemInode object if 'name' exists on the dir. * @throws FileNotFoundException */ protected synchronized VirtualFileSystemInode getInodeByName(String name) throws FileNotFoundException { name = VirtualFileSystem.fixPath(name); if (name.startsWith(VirtualFileSystem.separator)) { return VirtualFileSystem.getVirtualFileSystem().getInodeByPath(name); } if (name.indexOf(VirtualFileSystem.separator) != -1) { return VirtualFileSystem.getVirtualFileSystem().getInodeByPath( getPath() + VirtualFileSystem.separator + name); } if (name.equals("..")) { return getParent(); } if (name.equals(".")) { return this; } if (!_files.containsKey(name)) { throw new FileNotFoundException("FileNotFound: " + name + " does not exist"); } SoftReference<VirtualFileSystemInode> sf = _files.get(name); VirtualFileSystemInode inode = null; if (sf != null) { inode = sf.get(); } if (inode == null) { + // The next line is so that we load the file from disk using the casing of the name + // stored against the parent directory not the casing passed by the caller + name = _files.ceilingKey(name); inode = getVFS().loadInode( getPath() + VirtualFileSystem.separator + name); inode.setParent(this); // _files.remove(name); // Map instance replaces what is previously there with put() _files.put(name, new SoftReference<VirtualFileSystemInode>(inode)); } return inode; } /** * Remove the inode from the directory tree. * * @param child */ protected synchronized void removeChild(VirtualFileSystemInode child) { addSize(-child.getSize()); removeMissingChild(child.getName()); commit(); } /** * Changes the directory tree. * @param files */ public synchronized void setFiles(Collection<String> files) { for (String file : files) { _files.put(file, null); } } /** * Configure the serialization of the Directory. */ @Override protected void setupXML(XMLEncoder enc) { super.setupXML(enc); PropertyDescriptor[] pdArr; try { pdArr = Introspector.getBeanInfo(VirtualFileSystemDirectory.class) .getPropertyDescriptors(); } catch (IntrospectionException e) { logger.error("I don't know what to do here", e); throw new RuntimeException(e); } for (int x = 0; x < pdArr.length; x++) { //logger.debug("PropertyDescriptor - VirtualFileSystemDirectory - " + pdArr[x].getDisplayName()); if (transientListDirectory.contains(pdArr[x].getName())) { pdArr[x].setValue("transient", Boolean.TRUE); } } enc.setPersistenceDelegate(VirtualFileSystemDirectory.class, new DefaultPersistenceDelegate(new String[] { "username", "group" })); } @Override public String toString() { return "Directory" + super.toString(); } @Override public long getSize() { return _size; } @Override public void setSize(long l) { _size = l; } public synchronized void removeMissingChild(String name) { if (_files.remove(name) != null) { setLastModified(System.currentTimeMillis()); commit(); } } }
true
true
protected synchronized VirtualFileSystemInode getInodeByName(String name) throws FileNotFoundException { name = VirtualFileSystem.fixPath(name); if (name.startsWith(VirtualFileSystem.separator)) { return VirtualFileSystem.getVirtualFileSystem().getInodeByPath(name); } if (name.indexOf(VirtualFileSystem.separator) != -1) { return VirtualFileSystem.getVirtualFileSystem().getInodeByPath( getPath() + VirtualFileSystem.separator + name); } if (name.equals("..")) { return getParent(); } if (name.equals(".")) { return this; } if (!_files.containsKey(name)) { throw new FileNotFoundException("FileNotFound: " + name + " does not exist"); } SoftReference<VirtualFileSystemInode> sf = _files.get(name); VirtualFileSystemInode inode = null; if (sf != null) { inode = sf.get(); } if (inode == null) { inode = getVFS().loadInode( getPath() + VirtualFileSystem.separator + name); inode.setParent(this); // _files.remove(name); // Map instance replaces what is previously there with put() _files.put(name, new SoftReference<VirtualFileSystemInode>(inode)); } return inode; }
protected synchronized VirtualFileSystemInode getInodeByName(String name) throws FileNotFoundException { name = VirtualFileSystem.fixPath(name); if (name.startsWith(VirtualFileSystem.separator)) { return VirtualFileSystem.getVirtualFileSystem().getInodeByPath(name); } if (name.indexOf(VirtualFileSystem.separator) != -1) { return VirtualFileSystem.getVirtualFileSystem().getInodeByPath( getPath() + VirtualFileSystem.separator + name); } if (name.equals("..")) { return getParent(); } if (name.equals(".")) { return this; } if (!_files.containsKey(name)) { throw new FileNotFoundException("FileNotFound: " + name + " does not exist"); } SoftReference<VirtualFileSystemInode> sf = _files.get(name); VirtualFileSystemInode inode = null; if (sf != null) { inode = sf.get(); } if (inode == null) { // The next line is so that we load the file from disk using the casing of the name // stored against the parent directory not the casing passed by the caller name = _files.ceilingKey(name); inode = getVFS().loadInode( getPath() + VirtualFileSystem.separator + name); inode.setParent(this); // _files.remove(name); // Map instance replaces what is previously there with put() _files.put(name, new SoftReference<VirtualFileSystemInode>(inode)); } return inode; }
diff --git a/war-core/src/main/java/com/silverpeas/socialnetwork/myContactProfil/servlets/MyContactProfilRequestRouter.java b/war-core/src/main/java/com/silverpeas/socialnetwork/myContactProfil/servlets/MyContactProfilRequestRouter.java index 90d67fccee..28ffb2d60c 100644 --- a/war-core/src/main/java/com/silverpeas/socialnetwork/myContactProfil/servlets/MyContactProfilRequestRouter.java +++ b/war-core/src/main/java/com/silverpeas/socialnetwork/myContactProfil/servlets/MyContactProfilRequestRouter.java @@ -1,126 +1,126 @@ /** * Copyright (C) 2000 - 2012 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/legal/licensing" * * 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.socialnetwork.myContactProfil.servlets; import com.silverpeas.directory.model.Member; import com.silverpeas.socialnetwork.myContactProfil.control.MyContactProfilSessionController; import com.stratelia.silverpeas.peasCore.ComponentContext; import com.stratelia.silverpeas.peasCore.MainSessionController; import com.stratelia.silverpeas.peasCore.servlets.ComponentRequestRouter; import com.stratelia.webactiv.beans.admin.UserDetail; import javax.servlet.http.HttpServletRequest; import java.util.ArrayList; import java.util.List; import java.util.Random; /** * @author azzedine */ public class MyContactProfilRequestRouter extends ComponentRequestRouter<MyContactProfilSessionController> { private static final long serialVersionUID = 1L; private final int NUMBER_CONTACTS_TO_DISPLAY = 3; /** * get Session ControlBeanName * @return String */ @Override public String getSessionControlBeanName() { return "myContactProfil"; } /** * create ComponentSession Controller * @param mainSessionCtrl * @param componentContext * @return ComponentSessionController */ @Override public MyContactProfilSessionController createComponentSessionController( MainSessionController mainSessionCtrl, ComponentContext componentContext) { return new MyContactProfilSessionController(mainSessionCtrl, componentContext); } /** *get Destination * @param function * @param sc * @param request * @return */ @Override public String getDestination(String function, MyContactProfilSessionController sc, HttpServletRequest request) { String destination = "#"; String userId = request.getParameter("userId"); if (function.equalsIgnoreCase("Infos")) { request.setAttribute("View", function); - destination = "/socialnetwork/jsp/myContactProfil/myContactProfile.jsp"; + destination = "/socialNetwork/jsp/myContactProfil/myContactProfile.jsp"; } else if ("Main".equalsIgnoreCase(function)) { request.setAttribute("View", "Wall"); - destination = "/socialnetwork/jsp/myContactProfil/myContactProfile.jsp"; + destination = "/socialNetwork/jsp/myContactProfil/myContactProfile.jsp"; } request.setAttribute("UserFull", sc.getUserFull(userId)); request.setAttribute("Member", new Member(sc.getUserDetail(userId))); List<String> contactIds = sc.getContactsIdsForUser(userId); request.setAttribute("Contacts", chooseContactsToDisplay(contactIds, sc)); request.setAttribute("ContactsNumber", contactIds.size()); contactIds = sc.getCommonContactsIdsForUser(userId); request.setAttribute("CommonContacts", chooseContactsToDisplay(contactIds, sc)); request.setAttribute("CommonContactsNumber", contactIds.size()); return destination; } /** * methode to choose (x) contacts for display it in the page profil x is the number of contacts * the methode use Random rule * @param contactIds * @return List<SNContactUser> */ private List<UserDetail> chooseContactsToDisplay(List<String> contactIds, MyContactProfilSessionController sc) { List<UserDetail> contacts = new ArrayList<UserDetail>(); int numberOfContactsTodisplay = sc.getSettings().getInteger("numberOfContactsTodisplay", NUMBER_CONTACTS_TO_DISPLAY); if (contactIds.size() <= numberOfContactsTodisplay) { for (String contactId : contactIds) { contacts.add(sc.getUserDetail(contactId)); } } else { Random random = new Random(); int indexContactsChoosed = (random.nextInt(contactIds.size())); for (int i = 0; i < numberOfContactsTodisplay; i++) { String contactId = contactIds.get((indexContactsChoosed + i) % numberOfContactsTodisplay); contacts.add(sc.getUserDetail(contactId)); } } return contacts; } }
false
true
public String getDestination(String function, MyContactProfilSessionController sc, HttpServletRequest request) { String destination = "#"; String userId = request.getParameter("userId"); if (function.equalsIgnoreCase("Infos")) { request.setAttribute("View", function); destination = "/socialnetwork/jsp/myContactProfil/myContactProfile.jsp"; } else if ("Main".equalsIgnoreCase(function)) { request.setAttribute("View", "Wall"); destination = "/socialnetwork/jsp/myContactProfil/myContactProfile.jsp"; } request.setAttribute("UserFull", sc.getUserFull(userId)); request.setAttribute("Member", new Member(sc.getUserDetail(userId))); List<String> contactIds = sc.getContactsIdsForUser(userId); request.setAttribute("Contacts", chooseContactsToDisplay(contactIds, sc)); request.setAttribute("ContactsNumber", contactIds.size()); contactIds = sc.getCommonContactsIdsForUser(userId); request.setAttribute("CommonContacts", chooseContactsToDisplay(contactIds, sc)); request.setAttribute("CommonContactsNumber", contactIds.size()); return destination; }
public String getDestination(String function, MyContactProfilSessionController sc, HttpServletRequest request) { String destination = "#"; String userId = request.getParameter("userId"); if (function.equalsIgnoreCase("Infos")) { request.setAttribute("View", function); destination = "/socialNetwork/jsp/myContactProfil/myContactProfile.jsp"; } else if ("Main".equalsIgnoreCase(function)) { request.setAttribute("View", "Wall"); destination = "/socialNetwork/jsp/myContactProfil/myContactProfile.jsp"; } request.setAttribute("UserFull", sc.getUserFull(userId)); request.setAttribute("Member", new Member(sc.getUserDetail(userId))); List<String> contactIds = sc.getContactsIdsForUser(userId); request.setAttribute("Contacts", chooseContactsToDisplay(contactIds, sc)); request.setAttribute("ContactsNumber", contactIds.size()); contactIds = sc.getCommonContactsIdsForUser(userId); request.setAttribute("CommonContacts", chooseContactsToDisplay(contactIds, sc)); request.setAttribute("CommonContactsNumber", contactIds.size()); return destination; }
diff --git a/ide/eclipse/registry/org.wso2.carbonstudio.eclipse.greg.manager.local/src/org/wso2/carbonstudio/eclipse/greg/manager/local/ui/remoteviewer/actions/CheckoutActionContributor.java b/ide/eclipse/registry/org.wso2.carbonstudio.eclipse.greg.manager.local/src/org/wso2/carbonstudio/eclipse/greg/manager/local/ui/remoteviewer/actions/CheckoutActionContributor.java index 3cf74c947..e92e90f2d 100644 --- a/ide/eclipse/registry/org.wso2.carbonstudio.eclipse.greg.manager.local/src/org/wso2/carbonstudio/eclipse/greg/manager/local/ui/remoteviewer/actions/CheckoutActionContributor.java +++ b/ide/eclipse/registry/org.wso2.carbonstudio.eclipse.greg.manager.local/src/org/wso2/carbonstudio/eclipse/greg/manager/local/ui/remoteviewer/actions/CheckoutActionContributor.java @@ -1,206 +1,206 @@ /* * Copyright (c) 2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.carbonstudio.eclipse.greg.manager.local.ui.remoteviewer.actions; import java.io.File; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.jface.action.Action; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.dialogs.ContainerSelectionDialog; import org.wso2.carbonstudio.eclipse.greg.base.interfaces.IRegistryAction; import org.wso2.carbonstudio.eclipse.greg.base.model.RegistryResourceNode; import org.wso2.carbonstudio.eclipse.greg.base.model.RegistryResourceType; import org.wso2.carbonstudio.eclipse.greg.base.ui.util.ImageUtils; import org.wso2.carbonstudio.eclipse.greg.manager.local.Activator; import org.wso2.carbonstudio.eclipse.greg.manager.local.utils.RegistryCheckInClientUtils; import org.wso2.carbonstudio.eclipse.logging.core.ICarbonStudioLog; import org.wso2.carbonstudio.eclipse.logging.core.Logger; import org.wso2.carbon.registry.synchronization.SynchronizationException; public class CheckoutActionContributor implements IRegistryAction { private static ICarbonStudioLog log=Logger.getLog(Activator.PLUGIN_ID); private Action checkoutAction; private RegistryResourceNode selectedObj; private Shell shell; /** * CheckoutActionContributor constructor */ public CheckoutActionContributor() { } /** * create checkout action for the selected object */ public Action createAction(Shell shell, Object selected) { setShell(shell); setSelectedObj((RegistryResourceNode) selected); if (checkoutAction == null) { checkoutAction = new Action("Checkout...") { public void run() { try { checkoutRegistryPath(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }; checkoutAction.setImageDescriptor(ImageUtils .getImageDescriptor(ImageUtils.ACTION_CHECK_OUT_MENU)); } return checkoutAction; } /** * check whether the selected object is set enabled */ public boolean isEnabled(Object selected) { if (selected instanceof RegistryResourceNode) { RegistryResourceNode r = (RegistryResourceNode) selected; return (r.getResourceType()==RegistryResourceType.COLLECTION || r.getResourceType() == RegistryResourceType.RESOURCE) && !r.isError(); } return false; } /** * isVisible check for the selected object */ public boolean isVisible(Object selected) { if (selected instanceof RegistryResourceNode) { RegistryResourceNode r = (RegistryResourceNode) selected; return (r.getResourceType()==RegistryResourceType.COLLECTION || r.getResourceType() == RegistryResourceType.RESOURCE) && !r.isError(); } return false; } /** * check out RegistryPath * @throws Exception */ private void checkoutRegistryPath() throws Exception { String checkoutPath = ""; if (getSelectedObj() instanceof RegistryResourceNode) { RegistryResourceNode r = (RegistryResourceNode) getSelectedObj(); IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); ContainerSelectionDialog dialog = new ContainerSelectionDialog(getShell(), root, false, "Select location to checkout"); while (true) { if (dialog.open() == ContainerSelectionDialog.OK) { Object[] result = dialog.getResult(); if (result.length == 1) { IPath path = ((Path) result[0]); if (root.exists(path)) { String chkoutFolder; if (r.getResourceType()==RegistryResourceType.RESOURCE){ chkoutFolder = r.getRegistryResourceNodeParent().getLastSegmentInPath(); checkoutPath = r.getRegistryResourceNodeParent().getRegistryResourcePath(); }else if(r.getResourceType()==RegistryResourceType.UNDEFINED){ throw new Exception("Resource not Defined"); } else{ chkoutFolder = r.getLastSegmentInPath(); checkoutPath = r.getRegistryResourcePath(); } if (chkoutFolder.equals("/")){ chkoutFolder = "ROOT"; } path = path.append(chkoutFolder); IProject project = root.getProject(path.segment(0)); path = root.getLocation().append(path); try { if (RegistryCheckInClientUtils.isCheckoutPathValid(path.toOSString())){ (new File(path.toOSString())).mkdirs(); try { RegistryCheckInClientUtils.checkout( r.getConnectionInfo().getUsername(), r.getConnectionInfo().getPassword(), path.toOSString(), r.getConnectionInfo().getUrl().toString(), - r.getRegistryResourcePath()); + checkoutPath); } catch (SynchronizationException e1) { e1.printStackTrace(); } try { project.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor()); } catch (CoreException e) { log.error(e); } } } catch (Exception e1) { MessageDialog.openError(getShell(), "Error in checkout path", e1 .getMessage()); continue; } } } } break; } } } /** * set selected registry resource node * @param selectedObj */ public void setSelectedObj(RegistryResourceNode selectedObj) { this.selectedObj = selectedObj; } /** * get selected registry resource node * @return */ public RegistryResourceNode getSelectedObj() { return selectedObj; } /** * set shell * @param shell */ public void setShell(Shell shell) { this.shell = shell; } /** * get shell * @return */ public Shell getShell() { return shell; } }
true
true
private void checkoutRegistryPath() throws Exception { String checkoutPath = ""; if (getSelectedObj() instanceof RegistryResourceNode) { RegistryResourceNode r = (RegistryResourceNode) getSelectedObj(); IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); ContainerSelectionDialog dialog = new ContainerSelectionDialog(getShell(), root, false, "Select location to checkout"); while (true) { if (dialog.open() == ContainerSelectionDialog.OK) { Object[] result = dialog.getResult(); if (result.length == 1) { IPath path = ((Path) result[0]); if (root.exists(path)) { String chkoutFolder; if (r.getResourceType()==RegistryResourceType.RESOURCE){ chkoutFolder = r.getRegistryResourceNodeParent().getLastSegmentInPath(); checkoutPath = r.getRegistryResourceNodeParent().getRegistryResourcePath(); }else if(r.getResourceType()==RegistryResourceType.UNDEFINED){ throw new Exception("Resource not Defined"); } else{ chkoutFolder = r.getLastSegmentInPath(); checkoutPath = r.getRegistryResourcePath(); } if (chkoutFolder.equals("/")){ chkoutFolder = "ROOT"; } path = path.append(chkoutFolder); IProject project = root.getProject(path.segment(0)); path = root.getLocation().append(path); try { if (RegistryCheckInClientUtils.isCheckoutPathValid(path.toOSString())){ (new File(path.toOSString())).mkdirs(); try { RegistryCheckInClientUtils.checkout( r.getConnectionInfo().getUsername(), r.getConnectionInfo().getPassword(), path.toOSString(), r.getConnectionInfo().getUrl().toString(), r.getRegistryResourcePath()); } catch (SynchronizationException e1) { e1.printStackTrace(); } try { project.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor()); } catch (CoreException e) { log.error(e); } } } catch (Exception e1) { MessageDialog.openError(getShell(), "Error in checkout path", e1 .getMessage()); continue; } } } } break; } } }
private void checkoutRegistryPath() throws Exception { String checkoutPath = ""; if (getSelectedObj() instanceof RegistryResourceNode) { RegistryResourceNode r = (RegistryResourceNode) getSelectedObj(); IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); ContainerSelectionDialog dialog = new ContainerSelectionDialog(getShell(), root, false, "Select location to checkout"); while (true) { if (dialog.open() == ContainerSelectionDialog.OK) { Object[] result = dialog.getResult(); if (result.length == 1) { IPath path = ((Path) result[0]); if (root.exists(path)) { String chkoutFolder; if (r.getResourceType()==RegistryResourceType.RESOURCE){ chkoutFolder = r.getRegistryResourceNodeParent().getLastSegmentInPath(); checkoutPath = r.getRegistryResourceNodeParent().getRegistryResourcePath(); }else if(r.getResourceType()==RegistryResourceType.UNDEFINED){ throw new Exception("Resource not Defined"); } else{ chkoutFolder = r.getLastSegmentInPath(); checkoutPath = r.getRegistryResourcePath(); } if (chkoutFolder.equals("/")){ chkoutFolder = "ROOT"; } path = path.append(chkoutFolder); IProject project = root.getProject(path.segment(0)); path = root.getLocation().append(path); try { if (RegistryCheckInClientUtils.isCheckoutPathValid(path.toOSString())){ (new File(path.toOSString())).mkdirs(); try { RegistryCheckInClientUtils.checkout( r.getConnectionInfo().getUsername(), r.getConnectionInfo().getPassword(), path.toOSString(), r.getConnectionInfo().getUrl().toString(), checkoutPath); } catch (SynchronizationException e1) { e1.printStackTrace(); } try { project.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor()); } catch (CoreException e) { log.error(e); } } } catch (Exception e1) { MessageDialog.openError(getShell(), "Error in checkout path", e1 .getMessage()); continue; } } } } break; } } }
diff --git a/src/main/java/com/tek42/perforce/parse/Workspaces.java b/src/main/java/com/tek42/perforce/parse/Workspaces.java index 176416e..7ac4436 100644 --- a/src/main/java/com/tek42/perforce/parse/Workspaces.java +++ b/src/main/java/com/tek42/perforce/parse/Workspaces.java @@ -1,167 +1,178 @@ /* * P4Java - java integration with Perforce SCM * Copyright (C) 2007-, Mike Wille, Tek42 * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * You can contact the author at: * * Web: http://tek42.com * Email: [email protected] * Mail: 755 W Big Beaver Road * Suite 1110 * Troy, MI 48084 */ package com.tek42.perforce.parse; import com.tek42.perforce.Depot; import com.tek42.perforce.PerforceException; import com.tek42.perforce.model.Workspace; /** * Base API object for interacting with workspaces. * * @author Mike Wille */ public class Workspaces extends AbstractPerforceTemplate { public Workspaces(Depot depot) { super(depot); } /** * Returns a workspace specified by name. * * @param name * @return * @throws PerforceException */ public Workspace getWorkspace(String name) throws PerforceException { WorkspaceBuilder builder = new WorkspaceBuilder(); Workspace workspace = builder.build(getPerforceResponse(builder.getBuildCmd(getP4Exe(), name))); if(workspace == null) throw new PerforceException("Failed to retrieve workspace: " + name); return workspace; } /** * Saves changes to an existing workspace, or creates a new one. * * @param workspace * @throws PerforceException */ public void saveWorkspace(Workspace workspace) throws PerforceException { WorkspaceBuilder builder = new WorkspaceBuilder(); saveToPerforce(workspace, builder); } /** * Synchronizes to the latest change for the specified path. Convenience function * for {@see syncTo(String, boolean)} * * @param path * @return * @throws PerforceException */ public StringBuilder syncToHead(String path) throws PerforceException { return syncToHead(path, false); } /** * Synchronizes to the latest change for the specified path. Allows a force sync to be performed by passing true to * forceSync parameter. * * @param path * The depot path to sync to * @param forceSync * True to force sync and overwrite local files * @return StringBuilder containing output of p4 response. * @throws PerforceException */ public StringBuilder syncToHead(String path, boolean forceSync) throws PerforceException { if(!path.endsWith("#head")) { path += "#head"; } return syncTo(path, forceSync); } /** * Provides method to sync to a depot path and allows for any revision, changelist, label, etc. * to be appended to the path. * <p> * A force sync can be specified by passing true to forceSync. * * @param path * The depot path to sync to. Perforce suffix for [revRange] is allowed. * @param forceSync * Should we force a sync to grab all files regardless of version on disk? * @return * A StringBuilder that contains the output of the p4 execution. * @throws PerforceException */ public StringBuilder syncTo(String path, boolean forceSync) throws PerforceException { + final StringBuilder errors = new StringBuilder(); ResponseFilter filter = new ResponseFilter(){ private int count=0; @Override public boolean accept(String line) { count++; - if(line.startsWith("Request too large")){ + if(line.contains("Request too large")){ return true; } + if(line.startsWith("error:")){ + errors.append(line); + errors.append("\n"); + } //return at most 50 lines. Throw away the rest so we don't run out of memory if(count<50){ return true; } return false; } }; if(forceSync){ - StringBuilder response = getPerforceResponse(new String[] { getP4Exe(), "sync", "-f", path }, filter); + StringBuilder response = getPerforceResponse(new String[] { getP4Exe(), "-s", "sync", "-f", path }, filter); if(hitMax(response)){ throw new PerforceException("Hit perforce server limit while force syncing: " + response); } + if(errors.length()>0){ + throw new PerforceException("Errors encountered while force syncing: " + errors.toString()); + } return response; } else { - StringBuilder response = getPerforceResponse(new String[] { getP4Exe(), "sync", path }, filter); + StringBuilder response = getPerforceResponse(new String[] { getP4Exe(), "-s", "sync", path }, filter); if(hitMax(response)){ throw new PerforceException("Hit perforce server limit while syncing: " + response); } + if(errors.length()>0){ + throw new PerforceException("Errors encountered while syncing: " + errors.toString()); + } return response; } } public StringBuilder flushTo(String path) throws PerforceException { StringBuilder response = getPerforceResponse(new String[] { getP4Exe(), "sync", "-k", path }); if(hitMax(response)){ throw new PerforceException("Hit perforce server limit while flushing client: " + response); } return response; } /** * Test whether there are any changes pending for the current client (P4CLIENT env var). * * @return * A StringBuilder that contains the output of the p4 execution. * @throws PerforceException */ public StringBuilder syncDryRun() throws PerforceException { StringBuilder result = getPerforceResponse(new String[] { getP4Exe(), "sync", "-n" }); return result; } }
false
true
public StringBuilder syncTo(String path, boolean forceSync) throws PerforceException { ResponseFilter filter = new ResponseFilter(){ private int count=0; @Override public boolean accept(String line) { count++; if(line.startsWith("Request too large")){ return true; } //return at most 50 lines. Throw away the rest so we don't run out of memory if(count<50){ return true; } return false; } }; if(forceSync){ StringBuilder response = getPerforceResponse(new String[] { getP4Exe(), "sync", "-f", path }, filter); if(hitMax(response)){ throw new PerforceException("Hit perforce server limit while force syncing: " + response); } return response; } else { StringBuilder response = getPerforceResponse(new String[] { getP4Exe(), "sync", path }, filter); if(hitMax(response)){ throw new PerforceException("Hit perforce server limit while syncing: " + response); } return response; } }
public StringBuilder syncTo(String path, boolean forceSync) throws PerforceException { final StringBuilder errors = new StringBuilder(); ResponseFilter filter = new ResponseFilter(){ private int count=0; @Override public boolean accept(String line) { count++; if(line.contains("Request too large")){ return true; } if(line.startsWith("error:")){ errors.append(line); errors.append("\n"); } //return at most 50 lines. Throw away the rest so we don't run out of memory if(count<50){ return true; } return false; } }; if(forceSync){ StringBuilder response = getPerforceResponse(new String[] { getP4Exe(), "-s", "sync", "-f", path }, filter); if(hitMax(response)){ throw new PerforceException("Hit perforce server limit while force syncing: " + response); } if(errors.length()>0){ throw new PerforceException("Errors encountered while force syncing: " + errors.toString()); } return response; } else { StringBuilder response = getPerforceResponse(new String[] { getP4Exe(), "-s", "sync", path }, filter); if(hitMax(response)){ throw new PerforceException("Hit perforce server limit while syncing: " + response); } if(errors.length()>0){ throw new PerforceException("Errors encountered while syncing: " + errors.toString()); } return response; } }